Sonar Fixes (#2233)

Signed-off-by: Avgustin Marinov <Avgustin.Marinov@bosch.com>
This commit is contained in:
Avgustin Marinov
2025-01-24 15:41:06 +02:00
committed by GitHub
parent 0280d96d2c
commit a61e9cd6ae
66 changed files with 401 additions and 387 deletions

View File

@@ -19,7 +19,6 @@ import java.util.Map;
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;
@@ -87,7 +86,7 @@ public class PropertyBasedArtifactUrlHandler implements ArtifactUrlHandler {
.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();
}

View File

@@ -71,9 +71,8 @@ class PropertyBasedArtifactUrlHandlerTest {
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

View File

@@ -24,12 +24,12 @@ import org.springframework.test.context.TestPropertySource;
@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()));
}
@@ -37,7 +37,7 @@ public class PreAuthorizeEnabledTest extends AbstractSecurityTest {
@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()));
}

View File

@@ -32,7 +32,7 @@ import org.springframework.security.web.authentication.preauth.PreAuthenticatedA
@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";
@@ -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,
@@ -59,7 +59,7 @@ public class PreAuthTokenSourceTrustAuthenticationProviderTest {
@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,
@@ -72,7 +72,7 @@ public class PreAuthTokenSourceTrustAuthenticationProviderTest {
@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";
@@ -88,7 +88,7 @@ public class PreAuthTokenSourceTrustAuthenticationProviderTest {
@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,
@@ -104,7 +104,7 @@ public class PreAuthTokenSourceTrustAuthenticationProviderTest {
@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";
@@ -125,7 +125,7 @@ public class PreAuthTokenSourceTrustAuthenticationProviderTest {
@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";

View File

@@ -387,8 +387,11 @@ public interface MgmtTargetTagRestApi {
@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
}
}

View File

@@ -22,18 +22,18 @@ import org.junit.jupiter.api.Test;
@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");
@@ -44,7 +44,7 @@ public class PagedListTest {
@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");

View File

@@ -14,7 +14,6 @@ import static org.assertj.core.api.Assertions.assertThat;
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;
@@ -24,7 +23,7 @@ import org.springframework.context.annotation.Description;
@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;
@@ -32,7 +31,7 @@ public class MgmtTargetAssignmentResponseBodyTest {
@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);
@@ -70,9 +69,8 @@ public class MgmtTargetAssignmentResponseBodyTest {
}
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;
}

View File

@@ -32,6 +32,7 @@ import org.eclipse.hawkbit.mgmt.json.model.target.MgmtTarget;
@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

View File

@@ -16,7 +16,6 @@ import java.util.Collection;
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;

View File

@@ -37,10 +37,13 @@ import org.springframework.web.context.WebApplicationContext;
@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.

View File

@@ -15,7 +15,6 @@ import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
@@ -68,7 +67,7 @@ final class MgmtRolloutMapper {
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) {
@@ -200,14 +199,13 @@ final class MgmtRolloutMapper {
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,

View File

@@ -12,7 +12,6 @@ package org.eclipse.hawkbit.mgmt.rest.resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import jakarta.validation.ValidationException;
@@ -147,7 +146,7 @@ public class MgmtRolloutResource implements MgmtRolloutRestApi {
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

View File

@@ -15,7 +15,6 @@ import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
@@ -57,7 +56,7 @@ public final class MgmtSoftwareModuleMapper {
.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,
@@ -66,7 +65,7 @@ public final class MgmtSoftwareModuleMapper {
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) {
@@ -74,8 +73,7 @@ public final class MgmtSoftwareModuleMapper {
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) {
@@ -83,7 +81,7 @@ public final class MgmtSoftwareModuleMapper {
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) {

View File

@@ -15,7 +15,6 @@ import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
@@ -39,7 +38,7 @@ final class MgmtSoftwareModuleTypeMapper {
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) {
@@ -47,7 +46,7 @@ final class MgmtSoftwareModuleTypeMapper {
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) {

View File

@@ -70,8 +70,7 @@ public class MgmtSystemManagementResource implements MgmtSystemManagementRestApi
.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);
}
@@ -89,7 +88,7 @@ public class MgmtSystemManagementResource implements MgmtSystemManagementRestApi
.ok(cacheNames.stream().map(cacheManager::getCache)
.filter(Objects::nonNull)
.map(cache -> new MgmtSystemCache(cache.getName(), Collections.emptyList()))
.collect(Collectors.toList()));
.toList());
}
/**

View File

@@ -15,7 +15,6 @@ import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
@@ -111,7 +110,7 @@ final class MgmtTagMapper {
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) {

View File

@@ -38,12 +38,12 @@ import org.springframework.util.CollectionUtils;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class MgmtTargetFilterQueryMapper {
static List<MgmtTargetFilterQuery> toResponse(final List<TargetFilterQuery> filters,
final boolean confirmationFlowEnabled, final boolean isRepresentationFull) {
static List<MgmtTargetFilterQuery> toResponse(
final List<TargetFilterQuery> filters, final boolean confirmationFlowEnabled, final boolean isRepresentationFull) {
if (CollectionUtils.isEmpty(filters)) {
return Collections.emptyList();
}
return filters.stream().map(filter -> toResponse(filter, confirmationFlowEnabled, isRepresentationFull)).collect(Collectors.toList());
return filters.stream().map(filter -> toResponse(filter, confirmationFlowEnabled, isRepresentationFull)).toList();
}
static MgmtTargetFilterQuery toResponse(final TargetFilterQuery filter, final boolean confirmationFlowEnabled,

View File

@@ -19,7 +19,6 @@ import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
@@ -124,7 +123,7 @@ public final class MgmtTargetMapper {
final Function<Target, PollStatus> pollStatusResolver = configHelper.pollStatusResolver();
return new ResponseList<>(
targets.stream().map(target -> toResponse(target, configHelper, pollStatusResolver)).collect(Collectors.toList()));
targets.stream().map(target -> toResponse(target, configHelper, pollStatusResolver)).toList());
}
/**
@@ -194,7 +193,7 @@ public final class MgmtTargetMapper {
}
return targetsRest.stream().map(targetRest -> fromRequest(entityFactory, targetRest))
.collect(Collectors.toList());
.toList();
}
static List<MetaData> fromRequestTargetMetadata(final List<MgmtMetadata> metadata,
@@ -205,7 +204,7 @@ public final class MgmtTargetMapper {
return metadata.stream().map(
metadataRest -> entityFactory.generateTargetMetadata(metadataRest.getKey(), metadataRest.getValue()))
.collect(Collectors.toList());
.toList();
}
static List<MgmtActionStatus> toActionStatusRestResponse(final Collection<ActionStatus> actionStatus,
@@ -219,7 +218,7 @@ public final class MgmtTargetMapper {
deploymentManagement.findMessagesByActionStatusId(
PageRequest.of(0, MgmtRestConstants.REQUEST_PARAMETER_PAGING_MAX_LIMIT), status.getId())
.getContent()))
.collect(Collectors.toList());
.toList();
}
static MgmtAction toResponse(final String targetId, final Action action) {
@@ -317,7 +316,7 @@ public final class MgmtTargetMapper {
}
static List<MgmtMetadata> toResponseTargetMetadata(final List<TargetMetadata> metadata) {
return metadata.stream().map(MgmtTargetMapper::toResponseTargetMetadata).collect(Collectors.toList());
return metadata.stream().map(MgmtTargetMapper::toResponseTargetMetadata).toList();
}
private static void addPollStatus(final Target target, final MgmtTarget targetRest, final Function<Target, PollStatus> pollStatusResolver) {

View File

@@ -137,7 +137,7 @@ public class MgmtTargetResource implements MgmtTargetRestApi {
@Override
public ResponseEntity<MgmtTarget> updateTarget(final String targetId, final MgmtTargetRequestBody targetRest) {
if (targetRest.getRequestAttributes() != null) {
if (targetRest.getRequestAttributes()) {
if (Boolean.TRUE.equals(targetRest.getRequestAttributes())) {
targetManagement.requestControllerAttributes(targetId);
} else {
return ResponseEntity.badRequest().build();
@@ -336,7 +336,7 @@ public class MgmtTargetResource implements MgmtTargetRestApi {
: dsAssignment.getConfirmationRequired();
return MgmtDeploymentRequestMapper.createAssignmentRequestBuilder(dsAssignment, targetId)
.setConfirmationRequired(isConfirmationRequired).build();
}).collect(Collectors.toList());
}).toList();
final List<DistributionSetAssignmentResult> assignmentResults = deploymentManagement
.assignDistributionSets(deploymentRequests);

View File

@@ -157,11 +157,9 @@ public class MgmtTargetTagResource implements MgmtTargetTagRestApi {
} else {
final AtomicReference<Collection<String>> notFound = new AtomicReference<>();
this.targetManagement.assignTag(controllerIds, targetTagId, notFound::set);
if (notFound.get() != null) {
// has not found
if (onNotFoundPolicy == OnNotFoundPolicy.ON_WHAT_FOUND_AND_FAIL) {
if (notFound.get() != null && onNotFoundPolicy == OnNotFoundPolicy.ON_WHAT_FOUND_AND_FAIL) {
// has not found and ON_WHAT_FOUND_AND_FAIL
throw new EntityNotFoundException(Target.class, notFound.get());
} // else - success
}
}
return ResponseEntity.ok().build();
@@ -183,11 +181,9 @@ public class MgmtTargetTagResource implements MgmtTargetTagRestApi {
} else {
final AtomicReference<Collection<String>> notFound = new AtomicReference<>();
this.targetManagement.unassignTag(controllerIds, targetTagId, notFound::set);
if (notFound.get() != null) {
// has not found
if (onNotFoundPolicy == OnNotFoundPolicy.ON_WHAT_FOUND_AND_FAIL) {
if (notFound.get() != null && onNotFoundPolicy == OnNotFoundPolicy.ON_WHAT_FOUND_AND_FAIL) {
// has not found and ON_WHAT_FOUND_AND_FAIL
throw new EntityNotFoundException(Target.class, notFound.get());
} // else - success
}
}
return ResponseEntity.ok().build();

View File

@@ -16,7 +16,6 @@ import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
@@ -43,14 +42,14 @@ public final class MgmtTargetTypeMapper {
}
return targetTypesRest.stream()
.map(targetRest -> fromRequest(entityFactory, targetRest))
.collect(Collectors.toList());
.toList();
}
static List<MgmtTargetType> toListResponse(final List<TargetType> types) {
if (types == null) {
return Collections.emptyList();
}
return new ResponseList<>(types.stream().map(MgmtTargetTypeMapper::toResponse).collect(Collectors.toList()));
return new ResponseList<>(types.stream().map(MgmtTargetTypeMapper::toResponse).toList());
}
static MgmtTargetType toResponse(final TargetType type) {
@@ -78,7 +77,7 @@ public final class MgmtTargetTypeMapper {
private static Collection<Long> getDistributionSets(final MgmtTargetTypeRequestBodyPost targetTypesRest) {
return Optional.ofNullable(targetTypesRest.getCompatibledistributionsettypes())
.map(ds -> ds.stream().map(MgmtDistributionSetTypeAssignment::getId).collect(Collectors.toList()))
.map(ds -> ds.stream().map(MgmtDistributionSetTypeAssignment::getId).toList())
.orElse(Collections.emptyList());
}
}

View File

@@ -23,7 +23,7 @@ import org.eclipse.hawkbit.repository.model.TenantConfigurationValue;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class MgmtTenantManagementMapper {
public static String DEFAULT_DISTRIBUTION_SET_TYPE_KEY = "default.ds.type";
public static final String DEFAULT_DISTRIBUTION_SET_TYPE_KEY = "default.ds.type";
public static MgmtSystemTenantConfigurationValue toResponseTenantConfigurationValue(
final String key, final TenantConfigurationValue<?> repoConfValue) {

View File

@@ -891,23 +891,20 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
.getWithDetails(distributionSetManagement.findByRsql("name==three", PAGE).getContent().get(0).getId())
.get();
assertThat(
JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
assertThat((Object)JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()))
.hasToString("http://localhost/rest/v1/distributionsets/" + one.getId());
assertThat(JsonPath.compile("[0]id").read(mvcResult.getResponse().getContentAsString()).toString())
assertThat((Object)JsonPath.compile("[0]id").read(mvcResult.getResponse().getContentAsString()))
.hasToString(String.valueOf(one.getId()));
assertThat(
JsonPath.compile("[1]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
assertThat((Object)JsonPath.compile("[1]_links.self.href").read(mvcResult.getResponse().getContentAsString()))
.hasToString("http://localhost/rest/v1/distributionsets/" + two.getId());
assertThat(JsonPath.compile("[1]id").read(mvcResult.getResponse().getContentAsString()).toString())
assertThat((Object)JsonPath.compile("[1]id").read(mvcResult.getResponse().getContentAsString()))
.hasToString(String.valueOf(two.getId()));
assertThat(
JsonPath.compile("[2]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
assertThat((Object)JsonPath.compile("[2]_links.self.href").read(mvcResult.getResponse().getContentAsString()))
.hasToString("http://localhost/rest/v1/distributionsets/" + three.getId());
assertThat(JsonPath.compile("[2]id").read(mvcResult.getResponse().getContentAsString()).toString())
assertThat((Object)JsonPath.compile("[2]id").read(mvcResult.getResponse().getContentAsString()))
.hasToString(String.valueOf(three.getId()));
// check in database

View File

@@ -685,14 +685,11 @@ class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIntegrati
assertThat(created2.getOptionalModuleTypes()).containsOnly(osType, runtimeType, appType);
assertThat(created3.getMandatoryModuleTypes()).containsOnly(osType, runtimeType);
assertThat(
JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
assertThat((Object)JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()))
.hasToString("http://localhost/rest/v1/distributionsettypes/" + created1.getId());
assertThat(
JsonPath.compile("[1]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
assertThat((Object)JsonPath.compile("[1]_links.self.href").read(mvcResult.getResponse().getContentAsString()))
.hasToString("http://localhost/rest/v1/distributionsettypes/" + created2.getId());
assertThat(
JsonPath.compile("[2]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
assertThat((Object)JsonPath.compile("[2]_links.self.href").read(mvcResult.getResponse().getContentAsString()))
.hasToString("http://localhost/rest/v1/distributionsettypes/" + created3.getId());
assertThat(distributionSetTypeManagement.count()).isEqualTo(7);

View File

@@ -188,7 +188,7 @@ class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTest {
approvalStrategy.setApproveDecidedBy("testUser");
final int amountTargets = 2;
final String remark = "Some remark";
final List<Target> targets = testdataFactory.createTargets(amountTargets, "rollout");
testdataFactory.createTargets(amountTargets, "rollout");
final DistributionSet dsA = testdataFactory.createDistributionSet("");
final Rollout rollout = createRollout("rollout1", 3, dsA.getId(), "controllerId==rollout*", false);
@@ -1927,10 +1927,6 @@ class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTest {
retrieveAndCompareRolloutsContent(dsA, urlTemplate, isFullRepresentation, false, null, null);
}
private Rollout getRollout(final long rolloutId) {
return rolloutManagement.get(rolloutId).orElseThrow(NoSuchElementException::new);
}
private void retrieveAndCompareRolloutsContent(final DistributionSet dsA, final String urlTemplate,
final boolean isFullRepresentation, final boolean isStartTypeScheduled, final Long startAt,
final Long forcetime) throws Exception {

View File

@@ -104,7 +104,7 @@ class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegrationTes
public void createSMFromAlreadyMarkedAsDeletedType() throws Exception {
final String SM_TYPE = "someSmType";
final SoftwareModule sm = testdataFactory.createSoftwareModule(SM_TYPE);
final DistributionSetType t = testdataFactory.findOrCreateDistributionSetType(
testdataFactory.findOrCreateDistributionSetType(
"testKey", "testType", Collections.singletonList(sm.getType()),
Collections.singletonList(sm.getType()));
final DistributionSetType type = testdataFactory.findOrCreateDistributionSetType("testKey", "testType");
@@ -295,7 +295,7 @@ class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegrationTes
.andExpect(jsonPath("$.lastModifiedAt", equalTo(sm.getLastModifiedAt())))
.andExpect(jsonPath("$.deleted", equalTo(false)));
final SoftwareModule updatedSm = softwareModuleManagement.get(sm.getId()).get();
softwareModuleManagement.get(sm.getId());
assertThat(sm.getLastModifiedBy()).isEqualTo("smUpdateTester");
assertThat(sm.getLastModifiedAt()).isEqualTo(sm.getLastModifiedAt());
assertThat(sm.isDeleted()).isFalse();
@@ -400,15 +400,12 @@ class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegrationTes
mvcResult.getResponse().getContentAsString());
final Long artId = softwareModuleManagement.get(sm.getId()).get().getArtifacts().get(0).getId();
assertThat(artResult.getArtifactId()).as("Wrong artifact id").isEqualTo(artId);
assertThat(JsonPath.compile("$._links.self.href")
.read(mvcResult.getResponse().getContentAsString())
.toString()).as("Link contains no self url")
.isEqualTo("http://localhost/rest/v1/softwaremodules/" + sm.getId() + "/artifacts/" + artId);
assertThat(JsonPath.compile("$._links.download.href")
.read(mvcResult.getResponse().getContentAsString())
.toString()).as("response contains no download url ")
.isEqualTo(
"http://localhost/rest/v1/softwaremodules/" + sm.getId() + "/artifacts/" + artId + "/download");
assertThat((Object)JsonPath.compile("$._links.self.href").read(mvcResult.getResponse().getContentAsString()))
.as("Link contains no self url")
.hasToString("http://localhost/rest/v1/softwaremodules/" + sm.getId() + "/artifacts/" + artId);
assertThat((Object)JsonPath.compile("$._links.download.href").read(mvcResult.getResponse().getContentAsString()))
.as("response contains no download url ")
.hasToString("http://localhost/rest/v1/softwaremodules/" + sm.getId() + "/artifacts/" + artId + "/download");
assertArtifact(sm, random);
}

View File

@@ -213,15 +213,12 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractManagementApiInt
final SoftwareModuleType created2 = softwareModuleTypeManagement.findByKey("test2").get();
final SoftwareModuleType created3 = softwareModuleTypeManagement.findByKey("test3").get();
assertThat(
JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
.isEqualTo("http://localhost/rest/v1/softwaremoduletypes/" + created1.getId());
assertThat(
JsonPath.compile("[1]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
.isEqualTo("http://localhost/rest/v1/softwaremoduletypes/" + created2.getId());
assertThat(
JsonPath.compile("[2]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
.isEqualTo("http://localhost/rest/v1/softwaremoduletypes/" + created3.getId());
assertThat((Object) JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()))
.hasToString("http://localhost/rest/v1/softwaremoduletypes/" + created1.getId());
assertThat((Object)JsonPath.compile("[1]_links.self.href").read(mvcResult.getResponse().getContentAsString()))
.hasToString("http://localhost/rest/v1/softwaremoduletypes/" + created2.getId());
assertThat((Object)JsonPath.compile("[2]_links.self.href").read(mvcResult.getResponse().getContentAsString()))
.hasToString("http://localhost/rest/v1/softwaremoduletypes/" + created3.getId());
assertThat(softwareModuleTypeManagement.count()).isEqualTo(6);
}
@@ -334,7 +331,7 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractManagementApiInt
testType = softwareModuleTypeManagement.get(testType.getId()).get();
assertThat(testType.getLastModifiedAt()).isEqualTo(testType.getLastModifiedAt());
assertThat(testType.isDeleted()).isEqualTo(false);
assertThat(testType.isDeleted()).isFalse();
}
@Test
@@ -466,15 +463,4 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractManagementApiInt
.update(entityFactory.softwareModuleType().update(testType.getId()).description("Desc1234"));
return testType;
}
private void createSoftwareModulesAlphabetical(final int amount) {
char character = 'a';
for (int index = 0; index < amount; index++) {
final String str = String.valueOf(character);
softwareModuleManagement.create(entityFactory.softwareModule().create().type(osType).name(str)
.description(str).vendor(str).version(str));
character++;
}
}
}

View File

@@ -97,8 +97,7 @@ public class MgmtTargetFilterQueryResourceTest extends AbstractManagementApiInte
@Description("Handles the GET request of retrieving all target filter queries within SP.")
public void getTargetFilterQueries() throws Exception {
final String filterName = "filter_01";
final TargetFilterQuery filterQuery = createSingleTargetFilterQuery(filterName, "name==test_01");
createSingleTargetFilterQuery(filterName, "name==test_01");
mvc.perform(get(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING))
.andExpect(status().isOk())
.andDo(MockMvcResultPrinter.print());
@@ -393,7 +392,7 @@ public class MgmtTargetFilterQueryResourceTest extends AbstractManagementApiInte
.andExpect(status().isBadRequest())
.andReturn();
assertThat(targetFilterQueryManagement.count()).isEqualTo(0);
assertThat(targetFilterQueryManagement.count()).isZero();
// verify response json exception message
final ExceptionInfo exceptionInfo = ResourceUtility
@@ -414,7 +413,7 @@ public class MgmtTargetFilterQueryResourceTest extends AbstractManagementApiInte
.andExpect(status().isBadRequest())
.andReturn();
assertThat(targetFilterQueryManagement.count()).isEqualTo(0);
assertThat(targetFilterQueryManagement.count()).isZero();
}
@Test
@@ -613,7 +612,7 @@ public class MgmtTargetFilterQueryResourceTest extends AbstractManagementApiInte
final List<TargetFilterQuery> filters = targetFilterQueryManagement.findAll(PAGE).getContent();
assertThat(filters).hasSize(1);
assertThat(filters.get(0).getAutoAssignWeight().get()).isEqualTo(45);
assertThat(filters.get(0).getAutoAssignWeight()).contains(45);
}
@ParameterizedTest

View File

@@ -1006,15 +1006,12 @@ class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest {
.andExpect(jsonPath("[2].createdBy", equalTo("bumlux")))
.andReturn();
assertThat(
JsonPath.compile("[0]._links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
.isEqualTo("http://localhost/rest/v1/targets/id1");
assertThat(
JsonPath.compile("[1]._links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
.isEqualTo("http://localhost/rest/v1/targets/id2");
assertThat(
JsonPath.compile("[2]._links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
.isEqualTo("http://localhost/rest/v1/targets/id3");
assertThat((Object) JsonPath.compile("[0]._links.self.href").read(mvcResult.getResponse().getContentAsString()))
.hasToString("http://localhost/rest/v1/targets/id1");
assertThat((Object)JsonPath.compile("[1]._links.self.href").read(mvcResult.getResponse().getContentAsString()))
.hasToString("http://localhost/rest/v1/targets/id2");
assertThat((Object)JsonPath.compile("[2]._links.self.href").read(mvcResult.getResponse().getContentAsString()))
.hasToString("http://localhost/rest/v1/targets/id3");
final Target t1 = assertTarget("id1", "testname1", "testid1");
assertThat(t1.getSecurityToken()).isEqualTo("token");
@@ -2275,7 +2272,7 @@ class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest {
final List<Target> targets = Arrays.asList(test1, test2, test3);
final MvcResult mvcPostResult = mvc
mvc
.perform(post("/rest/v1/targets").content(JsonBuilder.targets(targets, true))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print())

View File

@@ -91,9 +91,7 @@ public class MgmtTargetTagResourceTest extends AbstractManagementApiIntegrationT
@Test
@Description("Handles the GET request of retrieving all targets tags within SP based by parameter")
public void getTargetTagsWithParameters() throws Exception {
final List<TargetTag> tags = testdataFactory.createTargetTags(2, "");
final TargetTag assigned = tags.get(0);
final TargetTag unassigned = tags.get(1);
testdataFactory.createTargetTags(2, "");
mvc.perform(get(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "?limit=10&sort=name:ASC&offset=0&q=name==targetTag"))
.andExpect(status().isOk())
.andDo(MockMvcResultPrinter.print());
@@ -233,7 +231,7 @@ public class MgmtTargetTagResourceTest extends AbstractManagementApiIntegrationT
final TargetTag tag = testdataFactory.createTargetTags(1, "").get(0);
final int targetsAssigned = 5;
final List<Target> targets = testdataFactory.createTargets(targetsAssigned);
targetManagement.assignTag(targets.stream().map(Target::getControllerId).collect(Collectors.toList()), tag.getId());
targetManagement.assignTag(targets.stream().map(Target::getControllerId).toList(), tag.getId());
mvc.perform(get(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned"))
.andDo(MockMvcResultPrinter.print())
@@ -254,7 +252,7 @@ public class MgmtTargetTagResourceTest extends AbstractManagementApiIntegrationT
final int targetsAssigned = 5;
final int limitSize = 1;
final List<Target> targets = testdataFactory.createTargets(targetsAssigned);
targetManagement.assignTag(targets.stream().map(Target::getControllerId).collect(Collectors.toList()), tag.getId());
targetManagement.assignTag(targets.stream().map(Target::getControllerId).toList(), tag.getId());
mvc.perform(get(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned")
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(limitSize)))
@@ -278,7 +276,7 @@ public class MgmtTargetTagResourceTest extends AbstractManagementApiIntegrationT
final int expectedSize = targetsAssigned - offsetParam;
final List<Target> targets = testdataFactory.createTargets(targetsAssigned);
targetManagement.assignTag(targets.stream().map(Target::getControllerId).collect(Collectors.toList()), tag.getId());
targetManagement.assignTag(targets.stream().map(Target::getControllerId).toList(), tag.getId());
mvc.perform(get(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned")
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(offsetParam))
@@ -306,8 +304,7 @@ public class MgmtTargetTagResourceTest extends AbstractManagementApiIntegrationT
.andExpect(status().isOk());
final List<Target> updated = targetManagement.findByTag(PAGE, tag.getId()).getContent();
assertThat(updated.stream().map(Target::getControllerId).collect(Collectors.toList()))
.containsOnly(assigned.getControllerId());
assertThat(updated.stream().map(Target::getControllerId).toList()).containsOnly(assigned.getControllerId());
}
@Test
@@ -329,7 +326,7 @@ public class MgmtTargetTagResourceTest extends AbstractManagementApiIntegrationT
.andExpect(status().isOk());
final List<Target> updated = targetManagement.findByTag(PAGE, tag.getId()).getContent();
assertThat(updated.stream().map(Target::getControllerId).collect(Collectors.toList()))
assertThat(updated.stream().map(Target::getControllerId).toList())
.containsOnly(assigned0.getControllerId(), assigned1.getControllerId());
}
@@ -459,7 +456,7 @@ public class MgmtTargetTagResourceTest extends AbstractManagementApiIntegrationT
final Target assigned = targets.get(0);
final Target unassigned = targets.get(1);
targetManagement.assignTag(targets.stream().map(Target::getControllerId).collect(Collectors.toList()), tag.getId());
targetManagement.assignTag(targets.stream().map(Target::getControllerId).toList(), tag.getId());
mvc.perform(delete(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned/" +
unassigned.getControllerId()))
@@ -467,7 +464,7 @@ public class MgmtTargetTagResourceTest extends AbstractManagementApiIntegrationT
.andExpect(status().isOk());
final List<Target> updated = targetManagement.findByTag(PAGE, tag.getId()).getContent();
assertThat(updated.stream().map(Target::getControllerId).collect(Collectors.toList()))
assertThat(updated.stream().map(Target::getControllerId).toList())
.containsOnly(assigned.getControllerId());
}
@@ -484,7 +481,7 @@ public class MgmtTargetTagResourceTest extends AbstractManagementApiIntegrationT
final Target unassigned0 = targets.get(1);
final Target unassigned1 = targets.get(2);
targetManagement.assignTag(targets.stream().map(Target::getControllerId).collect(Collectors.toList()), tag.getId());
targetManagement.assignTag(targets.stream().map(Target::getControllerId).toList(), tag.getId());
mvc.perform(delete(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned")
.content(JsonBuilder.toArray(Arrays.asList(unassigned0.getControllerId(), unassigned1.getControllerId())))
@@ -493,7 +490,7 @@ public class MgmtTargetTagResourceTest extends AbstractManagementApiIntegrationT
.andExpect(status().isOk());
final List<Target> updated = targetManagement.findByTag(PAGE, tag.getId()).getContent();
assertThat(updated.stream().map(Target::getControllerId).collect(Collectors.toList()))
assertThat(updated.stream().map(Target::getControllerId).toList())
.containsOnly(assigned.getControllerId());
}

View File

@@ -164,7 +164,7 @@ class MgmtTargetTypeResourceTest extends AbstractManagementApiIntegrationTest {
String typeNameA = "ATestTypeGETsorted";
String typeNameB = "BTestTypeGETsorted";
String typeNameC = "CTestTypeGETsorted";
TargetType testTypeB = createTestTargetTypeInDB(typeNameB);
createTestTargetTypeInDB(typeNameB);
TargetType testTypeC = createTestTargetTypeInDB(typeNameC);
TargetType testTypeA = createTestTargetTypeInDB(typeNameA);

View File

@@ -26,12 +26,12 @@ import org.springframework.http.HttpStatus;
@Feature("Integration Test - Security")
@Story("PreAuthorized enabled")
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("/rest/v1/distributionsets")).andExpect(result ->
assertThat(result.getResponse().getStatus()).isEqualTo(HttpStatus.FORBIDDEN.value()));
}
@@ -39,7 +39,7 @@ public class PreAuthorizeEnabledTest extends AbstractSecurityTest {
@Test
@Description("Tests whether request succeed if a role is granted for the user")
@WithUser(authorities = { SpPermission.READ_REPOSITORY }, autoCreateTenant = false)
public void successIfHasRole() throws Exception {
void successIfHasRole() throws Exception {
mvc.perform(get("/rest/v1/distributionsets")).andExpect(result ->
assertThat(result.getResponse().getStatus()).isEqualTo(HttpStatus.OK.value()));
}
@@ -47,7 +47,7 @@ public class PreAuthorizeEnabledTest extends AbstractSecurityTest {
@Test
@Description("Tests whether request succeed if a role is granted for the user")
@WithUser(authorities = { SpRole.TENANT_ADMIN }, autoCreateTenant = false)
public void successIfHasTenantAdminRole() throws Exception {
void successIfHasTenantAdminRole() throws Exception {
mvc.perform(get("/rest/v1/distributionsets")).andExpect(result ->
assertThat(result.getResponse().getStatus()).isEqualTo(HttpStatus.OK.value()));
}
@@ -55,20 +55,19 @@ public class PreAuthorizeEnabledTest extends AbstractSecurityTest {
@Test
@Description("Tests whether read tenant config request fail if a tenant config (or read read) is not granted for the user")
@WithUser(authorities = { SpPermission.READ_TARGET }, autoCreateTenant = false)
public void onlyDSIfNoTenantConfig() throws Exception {
void onlyDSIfNoTenantConfig() throws Exception {
mvc.perform(get("/rest/v1/system/configs")).andExpect(result -> {
// returns default DS type because of READ_TARGET
assertThat(result.getResponse().getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(
new ObjectMapper().reader().readValue(result.getResponse().getContentAsString(), HashMap.class).size())
.isEqualTo(1);
assertThat(new ObjectMapper().reader().readValue(result.getResponse().getContentAsString(), HashMap.class))
.hasSize(1);
});
}
@Test
@Description("Tests whether read tenant config request succeed if a tenant config (not read explicitly) is granted for the user")
@WithUser(authorities = { SpPermission.TENANT_CONFIGURATION }, autoCreateTenant = false)
public void successIfHasTenantConfig() throws Exception {
void successIfHasTenantConfig() throws Exception {
mvc.perform(get("/rest/v1/system/configs")).andExpect(result ->
assertThat(result.getResponse().getStatus()).isEqualTo(HttpStatus.OK.value()));
}

View File

@@ -26,12 +26,12 @@ import org.springframework.http.HttpStatus;
@Feature("Integration Test - Security")
@Story("PreAuthorized enabled")
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("/rest/v1/distributionsets"))
.andExpect(result -> assertThat(result.getResponse().getStatus()).isEqualTo(HttpStatus.FORBIDDEN.value()));
}
@@ -39,7 +39,7 @@ public class PreAuthorizeEnabledTest extends AbstractSecurityTest {
@Test
@Description("Tests whether request succeed if a role is granted for the user")
@WithUser(authorities = { SpPermission.READ_REPOSITORY }, autoCreateTenant = false)
public void successIfHasRole() throws Exception {
void successIfHasRole() throws Exception {
mvc.perform(get("/rest/v1/distributionsets"))
.andExpect(result -> assertThat(result.getResponse().getStatus()).isEqualTo(HttpStatus.OK.value()));
}
@@ -47,7 +47,7 @@ public class PreAuthorizeEnabledTest extends AbstractSecurityTest {
@Test
@Description("Tests whether request succeed if a role is granted for the user")
@WithUser(authorities = { SpRole.TENANT_ADMIN }, autoCreateTenant = false)
public void successIfHasTenantAdminRole() throws Exception {
void successIfHasTenantAdminRole() throws Exception {
mvc.perform(get("/rest/v1/distributionsets"))
.andExpect(result -> assertThat(result.getResponse().getStatus()).isEqualTo(HttpStatus.OK.value()));
}
@@ -55,20 +55,20 @@ public class PreAuthorizeEnabledTest extends AbstractSecurityTest {
@Test
@Description("Tests whether read tenant config request fail if a tenant config (or read read) is not granted for the user")
@WithUser(authorities = { SpPermission.READ_TARGET }, autoCreateTenant = false)
public void onlyDSIfNoTenantConfig() throws Exception {
void onlyDSIfNoTenantConfig() throws Exception {
mvc.perform(get("/rest/v1/system/configs"))
.andExpect(result -> {
// returns default DS type because of READ_TARGET
assertThat(result.getResponse().getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(new ObjectMapper().reader().readValue(result.getResponse().getContentAsString(), HashMap.class).size())
.isEqualTo(1);
assertThat(new ObjectMapper().reader().readValue(result.getResponse().getContentAsString(), HashMap.class))
.hasSize(1);
});
}
@Test
@Description("Tests whether read tenant config request succeed if a tenant config (not read explicitly) is granted for the user")
@WithUser(authorities = { SpPermission.TENANT_CONFIGURATION }, autoCreateTenant = false)
public void successIfHasTenantConfig() throws Exception {
void successIfHasTenantConfig() throws Exception {
mvc.perform(get("/rest/v1/system/configs"))
.andExpect(result -> assertThat(result.getResponse().getStatus()).isEqualTo(HttpStatus.OK.value()));
}

View File

@@ -13,7 +13,6 @@ import java.io.Serial;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import lombok.AccessLevel;
import lombok.Data;
@@ -25,10 +24,8 @@ import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Target;
/**
* Generic deployment event for the Multi-Assignments feature. The event payload
* holds a list of controller IDs identifying the targets which are affected by
* a deployment action (e.g. a software assignment (update) or a cancellation of
* an update).
* Generic deployment event for the Multi-Assignments feature. The event payload holds a list of controller IDs identifying the targets which
* are affected by a deployment action (e.g. a software assignment (update) or a cancellation of an update).
*/
@Data
@EqualsAndHashCode(callSuper = true)
@@ -61,11 +58,10 @@ public abstract class MultiActionEvent extends RemoteTenantAwareEvent implements
}
private static List<String> getControllerIdsFromActions(final List<Action> actions) {
return actions.stream().map(Action::getTarget).map(Target::getControllerId).distinct()
.collect(Collectors.toList());
return actions.stream().map(Action::getTarget).map(Target::getControllerId).distinct().toList();
}
private static List<Long> getIdsFromActions(final List<Action> actions) {
return actions.stream().map(Identifiable::getId).collect(Collectors.toList());
return actions.stream().map(Identifiable::getId).toList();
}
}

View File

@@ -54,8 +54,8 @@ public class EventPublisherConfiguration {
ApplicationEventMulticaster applicationEventMulticaster(
@Qualifier("asyncExecutor") final Executor executor,
final SystemSecurityContext systemSecurityContext, final ApplicationEventFilter applicationEventFilter) {
final SimpleApplicationEventMulticaster simpleApplicationEventMulticaster = new TenantAwareApplicationEventPublisher(
systemSecurityContext, applicationEventFilter);
final SimpleApplicationEventMulticaster simpleApplicationEventMulticaster =
new TenantAwareApplicationEventPublisher(systemSecurityContext, applicationEventFilter);
simpleApplicationEventMulticaster.setTaskExecutor(executor);
return simpleApplicationEventMulticaster;
}
@@ -85,7 +85,6 @@ public class EventPublisherConfiguration {
private final SystemSecurityContext systemSecurityContext;
private final ApplicationEventFilter applicationEventFilter;
@Autowired(required = false)
private ServiceMatcher serviceMatcher;
protected TenantAwareApplicationEventPublisher(
@@ -94,6 +93,11 @@ public class EventPublisherConfiguration {
this.applicationEventFilter = applicationEventFilter;
}
@Autowired(required = false)
public void setServiceMatcher(final ServiceMatcher serviceMatcher) {
this.serviceMatcher = serviceMatcher;
}
/**
* Was overridden that not every event has to run within an own tenantAware.
*/

View File

@@ -15,6 +15,7 @@ import java.util.stream.Collectors;
import jakarta.persistence.AttributeConverter;
@SuppressWarnings("java:S119") // better readability
public class MapAttributeConverter<JAVA_TYPE extends Enum<JAVA_TYPE>, DB_TYPE> implements AttributeConverter<JAVA_TYPE, DB_TYPE> {
private final Map<JAVA_TYPE, DB_TYPE> javaToDbMap;

View File

@@ -33,6 +33,8 @@ public class Jpa {
log.info("JPA vendor: {}", JPA_VENDOR);
}
// intentional, if it is a constant the compiler will inline it, we want to be changed with changing the JPA vendor lib
@SuppressWarnings("java:S3400")
public static char nativeQueryParamPrefix() {
return '?';
}

View File

@@ -14,6 +14,7 @@ import java.util.Map;
import javax.sql.DataSource;
import org.eclipse.hawkbit.tenancy.TenantAware;
import org.eclipse.persistence.config.PersistenceUnitProperties;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration;
@@ -33,10 +34,14 @@ import org.springframework.transaction.jta.JtaTransactionManager;
@Configuration
public class JpaConfiguration extends JpaBaseConfiguration {
private final TenantAware tenantAware;
protected JpaConfiguration(
final DataSource dataSource, final JpaProperties properties,
final ObjectProvider<JtaTransactionManager> jtaTransactionManagerProvider) {
final ObjectProvider<JtaTransactionManager> jtaTransactionManagerProvider,
final TenantAware tenantAware) {
super(dataSource, properties, jtaTransactionManagerProvider);
this.tenantAware = tenantAware;
}
/**
@@ -48,7 +53,7 @@ public class JpaConfiguration extends JpaBaseConfiguration {
@Override
@Bean
public PlatformTransactionManager transactionManager(final ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers) {
return new MultiTenantJpaTransactionManager();
return new MultiTenantJpaTransactionManager(tenantAware);
}
@Override

View File

@@ -38,7 +38,6 @@ class MultiTenantJpaTransactionManager extends JpaTransactionManager {
@Serial
private static final long serialVersionUID = 1L;
@Autowired
private transient TenantAware tenantAware;
private static final Class<?> JPA_TARGET;
@@ -53,6 +52,10 @@ class MultiTenantJpaTransactionManager extends JpaTransactionManager {
}
}
MultiTenantJpaTransactionManager(final TenantAware tenantAware) {
this.tenantAware = tenantAware;
}
private static final EntityPropertyChangeListener ENTITY_PROPERTY_CHANGE_LISTENER = new EntityPropertyChangeListener();
@Override

View File

@@ -31,10 +31,13 @@ public class Jpa {
log.info("JPA Vendor: {}", JPA_VENDOR);
}
// intentional, if it is a constant the compiler will inline it, we want to be changed with changing the JPA vendor lib
@SuppressWarnings("java:S3400")
public static char nativeQueryParamPrefix() {
return ':';
}
@SuppressWarnings("java:S1172") // intentionally - it shall follow the common "interface"/signature of the method for all JPA providers
public static <T> String formatNativeQueryInClause(final String name, final Collection<T> collection) {
return ":" + name;
}

View File

@@ -18,6 +18,7 @@ import jakarta.validation.Validation;
import org.eclipse.hawkbit.ContextAware;
import org.eclipse.hawkbit.artifact.repository.ArtifactRepository;
import org.eclipse.hawkbit.cache.TenancyCacheManager;
import org.eclipse.hawkbit.repository.ArtifactEncryption;
import org.eclipse.hawkbit.repository.ArtifactEncryptionSecretsStore;
import org.eclipse.hawkbit.repository.ArtifactEncryptionService;
@@ -130,6 +131,8 @@ import org.eclipse.hawkbit.repository.jpa.repository.TargetMetadataRepository;
import org.eclipse.hawkbit.repository.jpa.repository.TargetRepository;
import org.eclipse.hawkbit.repository.jpa.repository.TargetTagRepository;
import org.eclipse.hawkbit.repository.jpa.repository.TargetTypeRepository;
import org.eclipse.hawkbit.repository.jpa.repository.TenantConfigurationRepository;
import org.eclipse.hawkbit.repository.jpa.repository.TenantMetaDataRepository;
import org.eclipse.hawkbit.repository.jpa.rollout.RolloutScheduler;
import org.eclipse.hawkbit.repository.jpa.rollout.condition.PauseRolloutGroupAction;
import org.eclipse.hawkbit.repository.jpa.rollout.condition.RolloutGroupActionEvaluator;
@@ -160,6 +163,7 @@ import org.eclipse.hawkbit.security.SecurityTokenGenerator;
import org.eclipse.hawkbit.security.SystemSecurityContext;
import org.eclipse.hawkbit.tenancy.TenantAware;
import org.eclipse.hawkbit.tenancy.UserAuthoritiesResolver;
import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationProperties;
import org.eclipse.hawkbit.utils.TenantConfigHelper;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
@@ -170,6 +174,8 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.cache.CacheManager;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@@ -476,8 +482,23 @@ public class RepositoryApplicationConfiguration {
*/
@Bean
@ConditionalOnMissingBean
SystemManagement systemManagement(final JpaProperties properties) {
return new JpaSystemManagement(properties);
SystemManagement systemManagement(
final TargetRepository targetRepository, final TargetTypeRepository targetTypeRepository,
final TargetTagRepository targetTagRepository, final TargetFilterQueryRepository targetFilterQueryRepository,
final SoftwareModuleRepository softwareModuleRepository, final SoftwareModuleTypeRepository softwareModuleTypeRepository,
final DistributionSetRepository distributionSetRepository, final DistributionSetTypeRepository distributionSetTypeRepository,
final DistributionSetTagRepository distributionSetTagRepository, final RolloutRepository rolloutRepository,
final TenantConfigurationRepository tenantConfigurationRepository, final TenantMetaDataRepository tenantMetaDataRepository,
final TenantStatsManagement systemStatsManagement, final SystemManagementCacheKeyGenerator currentTenantCacheKeyGenerator,
final SystemSecurityContext systemSecurityContext, final TenantAware tenantAware, final PlatformTransactionManager txManager,
final TenancyCacheManager cacheManager, final RolloutStatusCache rolloutStatusCache,
final EntityManager entityManager, final RepositoryProperties repositoryProperties,
final JpaProperties properties) {
return new JpaSystemManagement(targetRepository, targetTypeRepository, targetTagRepository,
targetFilterQueryRepository, softwareModuleRepository, softwareModuleTypeRepository, distributionSetRepository,
distributionSetTypeRepository, distributionSetTagRepository, rolloutRepository, tenantConfigurationRepository,
tenantMetaDataRepository, systemStatsManagement, currentTenantCacheKeyGenerator, systemSecurityContext,
tenantAware, txManager, cacheManager, rolloutStatusCache, entityManager, repositoryProperties, properties);
}
/**
@@ -547,8 +568,10 @@ public class RepositoryApplicationConfiguration {
*/
@Bean
@ConditionalOnMissingBean
TenantStatsManagement tenantStatsManagement() {
return new JpaTenantStatsManagement();
TenantStatsManagement tenantStatsManagement(
final TargetRepository targetRepository, final LocalArtifactRepository artifactRepository, final ActionRepository actionRepository,
final TenantAware tenantAware) {
return new JpaTenantStatsManagement(targetRepository, artifactRepository, actionRepository, tenantAware);
}
/**
@@ -558,8 +581,13 @@ public class RepositoryApplicationConfiguration {
*/
@Bean
@ConditionalOnMissingBean
TenantConfigurationManagement tenantConfigurationManagement() {
return new JpaTenantConfigurationManagement();
TenantConfigurationManagement tenantConfigurationManagement(
final TenantConfigurationRepository tenantConfigurationRepository,
final TenantConfigurationProperties tenantConfigurationProperties,
final CacheManager cacheManager, final AfterTransactionCommitExecutor afterCommitExecutor,
final ApplicationContext applicationContext) {
return new JpaTenantConfigurationManagement(tenantConfigurationRepository, tenantConfigurationProperties,
cacheManager, afterCommitExecutor, applicationContext);
}
/**

View File

@@ -587,6 +587,7 @@ public class JpaRolloutManagement implements RolloutManagement {
return rollout;
}
@SuppressWarnings("java:S2259") // java:S2259 - false positive, see the java:S2259 comment in code
private Rollout createRolloutGroups(
final int amountOfGroups, final RolloutGroupConditions conditions,
final JpaRollout rollout, final boolean isConfirmationRequired, final DynamicRolloutGroupTemplate dynamicRolloutGroupTemplate) {
@@ -651,7 +652,7 @@ public class JpaRolloutManagement implements RolloutManagement {
publishRolloutGroupCreatedEventAfterCommit(lastGroup, rollout);
}
// lastSavedGroup is never null! amountOfGroups > 0 (and has static groups) or dynamicRolloutGroupTemplate is
// java:S2259 - lastSavedGroup is never null! amountOfGroups > 0 (and has static groups) or dynamicRolloutGroupTemplate is
// not null (validated) and (validated) the rollout is dynamic, so has dynamic group
rollout.setRolloutGroupsCreated(lastGroup.isDynamic() ? amountOfGroups + 1 : amountOfGroups);
final JpaRollout savedRollout = rolloutRepository.save(rollout);

View File

@@ -54,6 +54,7 @@ import org.springframework.dao.ConcurrencyFailureException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.lang.Nullable;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
@@ -75,62 +76,76 @@ public class JpaSystemManagement implements CurrentTenantCacheKeyGenerator, Syst
private final String countArtifactQuery;
private final String countSoftwareModulesQuery;
@Autowired
private EntityManager entityManager;
@Autowired
private TargetRepository targetRepository;
@Autowired
private TargetFilterQueryRepository targetFilterQueryRepository;
@Autowired
private DistributionSetRepository distributionSetRepository;
@Autowired
private SoftwareModuleRepository softwareModuleRepository;
@Autowired
private TenantMetaDataRepository tenantMetaDataRepository;
@Autowired
private DistributionSetTypeRepository distributionSetTypeRepository;
@Autowired
private SoftwareModuleTypeRepository softwareModuleTypeRepository;
@Autowired
private TargetTagRepository targetTagRepository;
@Autowired
private TargetTypeRepository targetTypeRepository;
@Autowired
private DistributionSetTagRepository distributionSetTagRepository;
@Autowired
private TenantConfigurationRepository tenantConfigurationRepository;
@Autowired
private RolloutRepository rolloutRepository;
@Autowired
private TenantAware tenantAware;
@Autowired
private TenantStatsManagement systemStatsManagement;
@Autowired
private TenancyCacheManager cacheManager;
@Autowired
private SystemManagementCacheKeyGenerator currentTenantCacheKeyGenerator;
@Autowired
private SystemSecurityContext systemSecurityContext;
@Autowired
private PlatformTransactionManager txManager;
@Autowired
private RolloutStatusCache rolloutStatusCache;
@Autowired(required = false) // it's not required on dmf/ddi only instances
private ArtifactRepository artifactRepository;
@Autowired
private RepositoryProperties repositoryProperties;
private final TargetRepository targetRepository;
private final TargetTypeRepository targetTypeRepository;
private final TargetTagRepository targetTagRepository;
private final TargetFilterQueryRepository targetFilterQueryRepository;
private final SoftwareModuleRepository softwareModuleRepository;
private final SoftwareModuleTypeRepository softwareModuleTypeRepository;
private final DistributionSetRepository distributionSetRepository;
private final DistributionSetTypeRepository distributionSetTypeRepository;
private final DistributionSetTagRepository distributionSetTagRepository;
private final RolloutRepository rolloutRepository;
private final TenantConfigurationRepository tenantConfigurationRepository;
private final TenantMetaDataRepository tenantMetaDataRepository;
private final TenantStatsManagement systemStatsManagement;
private final SystemManagementCacheKeyGenerator currentTenantCacheKeyGenerator;
private final SystemSecurityContext systemSecurityContext;
private final TenantAware tenantAware;
private final PlatformTransactionManager txManager;
private final TenancyCacheManager cacheManager;
private final RolloutStatusCache rolloutStatusCache;
private final EntityManager entityManager;
private final RepositoryProperties repositoryProperties;
@Nullable
private ArtifactRepository artifactRepository;
@SuppressWarnings("squid:S00107")
public JpaSystemManagement(
final TargetRepository targetRepository, final TargetTypeRepository targetTypeRepository,
final TargetTagRepository targetTagRepository, final TargetFilterQueryRepository targetFilterQueryRepository,
final SoftwareModuleRepository softwareModuleRepository, final SoftwareModuleTypeRepository softwareModuleTypeRepository,
final DistributionSetRepository distributionSetRepository, final DistributionSetTypeRepository distributionSetTypeRepository,
final DistributionSetTagRepository distributionSetTagRepository, final RolloutRepository rolloutRepository,
final TenantConfigurationRepository tenantConfigurationRepository, final TenantMetaDataRepository tenantMetaDataRepository,
final TenantStatsManagement systemStatsManagement, final SystemManagementCacheKeyGenerator currentTenantCacheKeyGenerator,
final SystemSecurityContext systemSecurityContext, final TenantAware tenantAware, final PlatformTransactionManager txManager,
final TenancyCacheManager cacheManager, final RolloutStatusCache rolloutStatusCache,
final EntityManager entityManager, final RepositoryProperties repositoryProperties,
final JpaProperties properties) {
this.targetRepository = targetRepository;
this.targetTypeRepository = targetTypeRepository;
this.targetTagRepository = targetTagRepository;
this.targetFilterQueryRepository = targetFilterQueryRepository;
this.softwareModuleRepository = softwareModuleRepository;
this.softwareModuleTypeRepository = softwareModuleTypeRepository;
this.distributionSetRepository = distributionSetRepository;
this.distributionSetTypeRepository = distributionSetTypeRepository;
this.distributionSetTagRepository = distributionSetTagRepository;
this.rolloutRepository = rolloutRepository;
this.tenantConfigurationRepository = tenantConfigurationRepository;
this.tenantMetaDataRepository = tenantMetaDataRepository;
this.systemStatsManagement = systemStatsManagement;
this.currentTenantCacheKeyGenerator = currentTenantCacheKeyGenerator;
this.systemSecurityContext = systemSecurityContext;
this.tenantAware = tenantAware;
this.txManager = txManager;
this.cacheManager = cacheManager;
this.rolloutStatusCache = rolloutStatusCache;
this.entityManager = entityManager;
this.repositoryProperties = repositoryProperties;
/**
* Constructor.
*
* @param properties properties to get the underlying database
*/
public JpaSystemManagement(final JpaProperties properties) {
final String isDeleted = isPostgreSql(properties) ? "false" : "0";
countArtifactQuery = "SELECT COUNT(a.id) FROM sp_artifact a INNER JOIN sp_base_software_module sm ON a.software_module = sm.id WHERE sm.deleted = " + isDeleted;
countSoftwareModulesQuery = "select SUM(file_size) from sp_artifact a INNER JOIN sp_base_software_module sm ON a.software_module = sm.id WHERE sm.deleted = " + isDeleted;
}
@Autowired(required = false) // it's not required on dmf/ddi only instances
public void setArtifactRepository(ArtifactRepository artifactRepository) {
this.artifactRepository = artifactRepository;
}
@Override
@Transactional(propagation = Propagation.SUPPORTS)
public KeyGenerator currentTenantKeyGenerator() {

View File

@@ -44,7 +44,6 @@ import org.eclipse.hawkbit.security.SystemSecurityContext;
import org.eclipse.hawkbit.tenancy.configuration.DurationHelper;
import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationProperties;
import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationProperties.TenantConfigurationKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
@@ -68,16 +67,23 @@ public class JpaTenantConfigurationManagement implements TenantConfigurationMana
private static final ConfigurableConversionService CONVERSION_SERVICE = new DefaultConversionService();
@Autowired
private TenantConfigurationRepository tenantConfigurationRepository;
@Autowired
private TenantConfigurationProperties tenantConfigurationProperties;
@Autowired
private ApplicationContext applicationContext;
@Autowired
private CacheManager cacheManager;
@Autowired
private AfterTransactionCommitExecutor afterCommitExecutor;
private final TenantConfigurationRepository tenantConfigurationRepository;
private final TenantConfigurationProperties tenantConfigurationProperties;
private final ApplicationContext applicationContext;
private final CacheManager cacheManager;
private final AfterTransactionCommitExecutor afterCommitExecutor;
public JpaTenantConfigurationManagement(
final TenantConfigurationRepository tenantConfigurationRepository,
final TenantConfigurationProperties tenantConfigurationProperties,
final CacheManager cacheManager, final AfterTransactionCommitExecutor afterCommitExecutor,
final ApplicationContext applicationContext) {
this.tenantConfigurationRepository = tenantConfigurationRepository;
this.tenantConfigurationProperties = tenantConfigurationProperties;
this.cacheManager = cacheManager;
this.afterCommitExecutor = afterCommitExecutor;
this.applicationContext = applicationContext;
}
@Override
@CacheEvict(value = "tenantConfiguration", key = "#configurationKeyName")

View File

@@ -26,14 +26,19 @@ import org.springframework.validation.annotation.Validated;
@Validated
public class JpaTenantStatsManagement implements TenantStatsManagement {
@Autowired
private TargetRepository targetRepository;
@Autowired
private LocalArtifactRepository artifactRepository;
@Autowired
private ActionRepository actionRepository;
@Autowired
private TenantAware tenantAware;
private final TargetRepository targetRepository;
private final LocalArtifactRepository artifactRepository;
private final ActionRepository actionRepository;
private final TenantAware tenantAware;
public JpaTenantStatsManagement(
final TargetRepository targetRepository, final LocalArtifactRepository artifactRepository, final ActionRepository actionRepository,
final TenantAware tenantAware) {
this.targetRepository = targetRepository;
this.artifactRepository = artifactRepository;
this.actionRepository = actionRepository;
this.tenantAware = tenantAware;
}
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)

View File

@@ -15,7 +15,6 @@ import java.util.List;
import java.util.Set;
import java.util.function.BooleanSupplier;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.commons.collections4.ListUtils;
import org.eclipse.hawkbit.repository.QuotaManagement;
@@ -87,7 +86,7 @@ public class OfflineDsAssignmentStrategy extends AbstractDsAssignmentStrategy {
TargetSpecifications.notEqualToTargetUpdateStatus(TargetUpdateStatus.PENDING))));
}
return ListUtils.partition(controllerIDs, Constants.MAX_ENTRIES_IN_STATEMENT).stream().map(mapper)
.flatMap(List::stream).collect(Collectors.toList());
.flatMap(List::stream).toList();
}
@Override

View File

@@ -112,7 +112,7 @@ public class OnlineDsAssignmentStrategy extends AbstractDsAssignmentStrategy {
.findAll(TargetSpecifications.hasControllerIdAndAssignedDistributionSetIdNot(ids, setId));
}
return ListUtils.partition(controllerIDs, Constants.MAX_ENTRIES_IN_STATEMENT).stream().map(mapper)
.flatMap(List::stream).collect(Collectors.toList());
.flatMap(List::stream).toList();
}
@Override
@@ -170,8 +170,7 @@ public class OnlineDsAssignmentStrategy extends AbstractDsAssignmentStrategy {
@Override
public void sendDeploymentEvents(final List<DistributionSetAssignmentResult> assignmentResults) {
if (isMultiAssignmentsEnabled()) {
sendDeploymentEvent(assignmentResults.stream().flatMap(result -> result.getAssignedEntity().stream())
.collect(Collectors.toList()));
sendDeploymentEvent(assignmentResults.stream().flatMap(result -> result.getAssignedEntity().stream()).toList());
} else {
assignmentResults.forEach(this::sendDistributionSetAssignedEvent);
}
@@ -196,7 +195,7 @@ public class OnlineDsAssignmentStrategy extends AbstractDsAssignmentStrategy {
if (actions == null || actions.isEmpty()) {
return Collections.emptyList();
}
return filterCancellations(actions).collect(Collectors.toList());
return filterCancellations(actions).toList();
}
private void sendMultiActionCancelEvent(final Action action) {
@@ -214,8 +213,7 @@ public class OnlineDsAssignmentStrategy extends AbstractDsAssignmentStrategy {
private DistributionSetAssignmentResult sendDistributionSetAssignedEvent(
final DistributionSetAssignmentResult assignmentResult) {
final List<Action> filteredActions = filterCancellations(assignmentResult.getAssignedEntity())
.collect(Collectors.toList());
final List<Action> filteredActions = filterCancellations(assignmentResult.getAssignedEntity()).toList();
final DistributionSet set = assignmentResult.getDistributionSet();
sendTargetAssignDistributionSetEvent(set.getTenant(), set.getId(), filteredActions);
return assignmentResult;

View File

@@ -96,7 +96,8 @@ import org.springframework.util.ObjectUtils;
@NamedEntityGraph(name = "Target.actions", attributeNodes = { @NamedAttributeNode("actions") }),
})
// exception squid:S2160 - BaseEntity equals/hashcode is handling correctly for sub entities
@SuppressWarnings("squid:S2160")
// java:S1710 - not possible to use without group annotation
@SuppressWarnings({ "squid:S2160", "java:S1710" })
public class JpaTarget extends AbstractJpaNamedEntity implements Target, EventAwareEntity {
@Serial

View File

@@ -20,12 +20,11 @@ import org.junit.jupiter.api.Test;
@Feature("Unit Tests - Repository")
@Story("Repository Model")
public class ModelEqualsHashcodeTest extends AbstractJpaIntegrationTest {
class ModelEqualsHashcodeTest extends AbstractJpaIntegrationTest {
@Test
@Description("Verifies that different objects even with identical primary key, version and tenant "
+ "return different hash codes.")
public void differentEntitiesReturnDifferentHashCodes() {
@Description("Verifies that different objects even with identical primary key, version and tenant return different hash codes.")
void differentEntitiesReturnDifferentHashCodes() {
assertThat(new JpaAction().hashCode()).as("action should have different hashcode than action status")
.isNotEqualTo(new JpaActionStatus().hashCode());
assertThat(new JpaDistributionSet().hashCode())
@@ -40,9 +39,8 @@ public class ModelEqualsHashcodeTest extends AbstractJpaIntegrationTest {
}
@Test
@Description("Verifies that different object even with identical primary key, version and tenant "
+ "are not equal.")
public void differentEntitiesAreNotEqual() {
@Description("Verifies that different object even with identical primary key, version and tenant are not equal.")
void differentEntitiesAreNotEqual() {
assertThat(new JpaAction().equals(new JpaActionStatus())).as("action equals action status").isFalse();
assertThat(new JpaDistributionSet().equals(new JpaSoftwareModule()))
.as("Distribution set equals software module").isFalse();
@@ -54,7 +52,7 @@ public class ModelEqualsHashcodeTest extends AbstractJpaIntegrationTest {
@Test
@Description("Verifies that updated entities are not equal.")
public void changedEntitiesAreNotEqual() {
void changedEntitiesAreNotEqual() {
final SoftwareModuleType type = softwareModuleTypeManagement
.create(entityFactory.softwareModuleType().create().key("test").name("test"));
assertThat(type).as("persited entity is not equal to regular object")
@@ -67,7 +65,7 @@ public class ModelEqualsHashcodeTest extends AbstractJpaIntegrationTest {
@Test
@Description("Verify that no proxy of the entity manager has an influence on the equals or hashcode result.")
public void managedEntityIsEqualToUnamangedObjectWithSameKey() {
void managedEntityIsEqualToUnamangedObjectWithSameKey() {
final SoftwareModuleType type = softwareModuleTypeManagement.create(
entityFactory.softwareModuleType().create().key("test").name("test").description("test"));
@@ -77,8 +75,9 @@ public class ModelEqualsHashcodeTest extends AbstractJpaIntegrationTest {
mock.setTenant(type.getTenant());
assertThat(type).as("managed entity is equal to regular object with same content").isEqualTo(mock);
assertThat(type.hashCode()).as("managed entity has same hash code as regular object with same content")
.isEqualTo(mock.hashCode());
assertThat(type)
.as("managed entity has same hash code as regular object with same content")
.hasSameHashCodeAs(mock.hashCode());
}
}

View File

@@ -10,7 +10,7 @@
package org.eclipse.hawkbit.repository.jpa.rsql;
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 io.qameta.allure.Description;
import io.qameta.allure.Feature;
@@ -32,13 +32,13 @@ import org.springframework.orm.jpa.vendor.Database;
@Feature("Component Tests - Repository")
@Story("RSQL filter actions")
public class RSQLActionFieldsTest extends AbstractJpaIntegrationTest {
class RSQLActionFieldsTest extends AbstractJpaIntegrationTest {
private JpaTarget target;
private JpaAction action;
@BeforeEach
public void setupBeforeTest() {
void setupBeforeTest() {
final DistributionSet dsA = testdataFactory.createDistributionSet("daA");
target = (JpaTarget) targetManagement
.create(entityFactory.target().create().controllerId("targetId123").description("targetId123"));
@@ -51,7 +51,7 @@ public class RSQLActionFieldsTest extends AbstractJpaIntegrationTest {
@Test
@Description("Test filter action by id")
public void testFilterByParameterId() {
void testFilterByParameterId() {
assertRSQLQuery(ActionFields.ID.name() + "==" + action.getId(), 1);
assertRSQLQuery(ActionFields.ID.name() + "!=" + action.getId(), 10);
assertRSQLQuery(ActionFields.ID.name() + "==" + -1, 0);
@@ -68,23 +68,21 @@ public class RSQLActionFieldsTest extends AbstractJpaIntegrationTest {
@Test
@Description("Test action by status")
public void testFilterByParameterStatus() {
void testFilterByParameterStatus() {
assertRSQLQuery(ActionFields.STATUS.name() + "==pending", 5);
assertRSQLQuery(ActionFields.STATUS.name() + "!=pending", 6);
assertRSQLQuery(ActionFields.STATUS.name() + "=in=(pending)", 5);
assertRSQLQuery(ActionFields.STATUS.name() + "=out=(pending)", 6);
try {
assertRSQLQuery(ActionFields.STATUS.name() + "==true", 5);
fail("Missing expected RSQLParameterUnsupportedFieldException because status cannot be compared with 'true'");
} catch (final RSQLParameterUnsupportedFieldException e) {
}
final String rsql = ActionFields.STATUS.name() + "==true";
assertThatExceptionOfType(RSQLParameterUnsupportedFieldException.class)
.as("RSQLParameterUnsupportedFieldException because status cannot be compared with 'true'")
.isThrownBy(() -> assertRSQLQuery(rsql, 5));
}
@Test
@Description("Test action by status")
public void testFilterByParameterExtRef() {
void testFilterByParameterExtRef() {
assertRSQLQuery(ActionFields.EXTERNALREF.name() + "==extRef", 5);
assertRSQLQuery(ActionFields.EXTERNALREF.name() + "!=extRef", 6);
assertRSQLQuery(ActionFields.EXTERNALREF.name() + "==extRef*", 10);
@@ -114,7 +112,7 @@ public class RSQLActionFieldsTest extends AbstractJpaIntegrationTest {
PageRequest.of(0, 100));
final long countAllEntities = deploymentManagement.countActionsByTarget(rsqlParam, target.getControllerId());
assertThat(findEntity).isNotNull();
assertThat(findEntity.getContent().size()).isEqualTo(expectedEntities);
assertThat(findEntity.getContent()).hasSize((int)expectedEntities);
assertThat(countAllEntities).isEqualTo(expectedEntities);
}
}

View File

@@ -11,7 +11,6 @@ package org.eclipse.hawkbit.repository.jpa.rsql;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.Arrays;
import java.util.Collections;
@@ -134,11 +133,9 @@ class RSQLDistributionSetFieldTest extends AbstractJpaIntegrationTest {
@Description("Test filter distribution set by complete property")
void testFilterByAttributeComplete() {
assertRSQLQuery(DistributionSetFields.COMPLETE.name() + "==true", 3);
try {
assertRSQLQuery(DistributionSetFields.COMPLETE.name() + "==noExist*", 0);
fail("Expected RSQLParameterSyntaxException");
} catch (final RSQLParameterSyntaxException e) {
}
final String noExistStar = DistributionSetFields.COMPLETE.name() + "==noExist*";
assertThatExceptionOfType(RSQLParameterSyntaxException.class)
.isThrownBy(() -> assertRSQLQuery(noExistStar, 0));
assertRSQLQuery(DistributionSetFields.COMPLETE.name() + "=in=(true)", 3);
assertRSQLQuery(DistributionSetFields.COMPLETE.name() + "=out=(true)", 2);
}
@@ -148,8 +145,9 @@ class RSQLDistributionSetFieldTest extends AbstractJpaIntegrationTest {
void testFilterByAttributeValid() {
assertRSQLQuery(DistributionSetFields.VALID.name() + "==true", 4);
assertRSQLQuery(DistributionSetFields.VALID.name() + "==false", 1);
final String rsqlNoExistStar = DistributionSetFields.VALID.name() + "==noExist*";
assertThatExceptionOfType(RSQLParameterSyntaxException.class)
.isThrownBy(() -> assertRSQLQuery(DistributionSetFields.VALID.name() + "==noExist*", 0));
.isThrownBy(() -> assertRSQLQuery(rsqlNoExistStar, 0));
assertRSQLQuery(DistributionSetFields.VALID.name() + "=in=(true)", 4);
assertRSQLQuery(DistributionSetFields.VALID.name() + "=out=(true)", 1);
}

View File

@@ -30,12 +30,12 @@ import org.springframework.data.domain.PageRequest;
@Feature("Component Tests - Repository")
@Story("RSQL filter distribution set metadata")
public class RSQLDistributionSetMetadataFieldsTest extends AbstractJpaIntegrationTest {
class RSQLDistributionSetMetadataFieldsTest extends AbstractJpaIntegrationTest {
private Long distributionSetId;
@BeforeEach
public void setupBeforeTest() {
void setupBeforeTest() {
final DistributionSet distributionSet = testdataFactory.createDistributionSet("DS");
distributionSetId = distributionSet.getId();
@@ -52,7 +52,7 @@ public class RSQLDistributionSetMetadataFieldsTest extends AbstractJpaIntegratio
@Test
@Description("Test filter distribution set metadata by key")
public void testFilterByParameterKey() {
void testFilterByParameterKey() {
assertRSQLQuery(DistributionSetMetadataFields.KEY.name() + "==1", 1);
assertRSQLQuery(DistributionSetMetadataFields.KEY.name() + "!=1", 5);
assertRSQLQuery(DistributionSetMetadataFields.KEY.name() + "=in=(1,2)", 2);
@@ -61,7 +61,7 @@ public class RSQLDistributionSetMetadataFieldsTest extends AbstractJpaIntegratio
@Test
@Description("Test filter distribution set metadata by value")
public void testFilterByParameterValue() {
void testFilterByParameterValue() {
assertRSQLQuery(DistributionSetMetadataFields.VALUE.name() + "==''", 1);
assertRSQLQuery(DistributionSetMetadataFields.VALUE.name() + "!=''", 5);
assertRSQLQuery(DistributionSetMetadataFields.VALUE.name() + "==1", 1);

View File

@@ -13,7 +13,6 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
@@ -28,7 +27,7 @@ import org.springframework.beans.factory.annotation.Autowired;
@Feature("Component Tests - Repository")
@Story("RSQL filter suggestion")
@SuppressWarnings("java:S6813") // constructor injects are not possible for test classes
public class RSQLParserValidationOracleTest extends AbstractJpaIntegrationTest {
class RSQLParserValidationOracleTest extends AbstractJpaIntegrationTest {
private static final String[] OP_SUGGESTIONS = new String[] { "==", "!=", "=ge=", "=le=", "=gt=", "=lt=", "=in=",
"=out=" };
@@ -42,7 +41,7 @@ public class RSQLParserValidationOracleTest extends AbstractJpaIntegrationTest {
@Test
@Description("Verifies that suggestions contains all possible field names")
public void suggestionContainsAllFieldNames() {
void suggestionContainsAllFieldNames() {
final String rsqlQuery = "na";
final List<String> currentSuggestions = getSuggestions(rsqlQuery);
assertThat(currentSuggestions).containsOnly(FIELD_SUGGESTIONS);
@@ -50,7 +49,7 @@ public class RSQLParserValidationOracleTest extends AbstractJpaIntegrationTest {
@Test
@Description("Verifies that suggestions only contains the allowed operators")
public void suggestionContainsOnlyOperators() {
void suggestionContainsOnlyOperators() {
final String rsqlQuery = "name";
final List<String> currentSuggestions = getSuggestions(rsqlQuery);
assertThat(currentSuggestions).containsOnly(OP_SUGGESTIONS);
@@ -58,7 +57,7 @@ public class RSQLParserValidationOracleTest extends AbstractJpaIntegrationTest {
@Test
@Description("Verifies that suggestions only contains operator to combine RSQL filters (and, or)")
public void suggestionContainsOnlyAndOrOperator() {
void suggestionContainsOnlyAndOrOperator() {
final String rsqlQuery = "name==a ";
final List<String> currentSuggestions = getSuggestions(rsqlQuery);
assertThat(currentSuggestions).containsOnly(AND_OR_SUGGESTIONS);
@@ -66,7 +65,7 @@ public class RSQLParserValidationOracleTest extends AbstractJpaIntegrationTest {
@Test
@Description("Verifies that sub suggestions are shown")
public void suggestionContainsSubFieldSuggestions() {
void suggestionContainsSubFieldSuggestions() {
final String rsqlQuery = "assignedds.";
final List<String> currentSuggestions = getSuggestions(rsqlQuery);
assertThat(currentSuggestions).containsOnly(NAME_VERSION_SUGGESTIONS);
@@ -76,6 +75,6 @@ public class RSQLParserValidationOracleTest extends AbstractJpaIntegrationTest {
return rsqlValidationOracle
.suggest(rsqlQuery, -1).getSuggestionContext().getSuggestions().stream()
.map(SuggestToken::getSuggestion)
.collect(Collectors.toList());
.toList();
}
}

View File

@@ -29,13 +29,13 @@ import org.springframework.orm.jpa.vendor.Database;
@Feature("Component Tests - Repository")
@Story("RSQL filter rollout group")
public class RSQLRolloutGroupFieldTest extends AbstractJpaIntegrationTest {
class RSQLRolloutGroupFieldTest extends AbstractJpaIntegrationTest {
private Long rolloutGroupId;
private Rollout rollout;
@BeforeEach
public void setupBeforeTest() {
void setupBeforeTest() {
final int amountTargets = 20;
testdataFactory.createTargets(amountTargets, "rollout", "rollout");
final DistributionSet dsA = testdataFactory.createDistributionSet("");
@@ -47,7 +47,7 @@ public class RSQLRolloutGroupFieldTest extends AbstractJpaIntegrationTest {
@Test
@Description("Test filter rollout group by id")
public void testFilterByParameterId() {
void testFilterByParameterId() {
assertRSQLQuery(RolloutGroupFields.ID.name() + "==" + rolloutGroupId, 1);
assertRSQLQuery(RolloutGroupFields.ID.name() + "!=" + rolloutGroupId, 3);
assertRSQLQuery(RolloutGroupFields.ID.name() + "==" + -1, 0);
@@ -64,7 +64,7 @@ public class RSQLRolloutGroupFieldTest extends AbstractJpaIntegrationTest {
@Test
@Description("Test filter rollout group by name")
public void testFilterByParameterName() {
void testFilterByParameterName() {
assertRSQLQuery(RolloutGroupFields.NAME.name() + "==group-1", 1);
assertRSQLQuery(RolloutGroupFields.NAME.name() + "!=group-1", 3);
assertRSQLQuery(RolloutGroupFields.NAME.name() + "==*", 4);
@@ -75,7 +75,7 @@ public class RSQLRolloutGroupFieldTest extends AbstractJpaIntegrationTest {
@Test
@Description("Test filter rollout group by description")
public void testFilterByParameterDescription() {
void testFilterByParameterDescription() {
assertRSQLQuery(RolloutGroupFields.DESCRIPTION.name() + "==group-1", 1);
assertRSQLQuery(RolloutGroupFields.DESCRIPTION.name() + "!=group-1", 3);
assertRSQLQuery(RolloutGroupFields.DESCRIPTION.name() + "==group*", 4);

View File

@@ -28,12 +28,12 @@ import org.springframework.orm.jpa.vendor.Database;
@Feature("Component Tests - Repository")
@Story("RSQL filter software module")
public class RSQLSoftwareModuleFieldTest extends AbstractJpaIntegrationTest {
class RSQLSoftwareModuleFieldTest extends AbstractJpaIntegrationTest {
private SoftwareModule ah;
@BeforeEach
public void setupBeforeTest() {
void setupBeforeTest() {
ah = softwareModuleManagement.create(entityFactory.softwareModule().create().type(appType).name("agent-hub")
.version("1.0.1").description("agent-hub"));
softwareModuleManagement.create(entityFactory.softwareModule().create().type(runtimeType).name("oracle-jre")
@@ -60,7 +60,7 @@ public class RSQLSoftwareModuleFieldTest extends AbstractJpaIntegrationTest {
@Test
@Description("Test filter software module by id")
public void testFilterByParameterId() {
void testFilterByParameterId() {
assertRSQLQuery(SoftwareModuleFields.ID.name() + "==" + ah.getId(), 1);
assertRSQLQuery(SoftwareModuleFields.ID.name() + "!=" + ah.getId(), 5);
assertRSQLQuery(SoftwareModuleFields.ID.name() + "==" + -1, 0);
@@ -77,7 +77,7 @@ public class RSQLSoftwareModuleFieldTest extends AbstractJpaIntegrationTest {
@Test
@Description("Test filter software module by name")
public void testFilterByParameterName() {
void testFilterByParameterName() {
assertRSQLQuery(SoftwareModuleFields.NAME.name() + "==agent-hub", 1);
assertRSQLQuery(SoftwareModuleFields.NAME.name() + "!=agent-hub", 5);
assertRSQLQuery(SoftwareModuleFields.NAME.name() + "==agent-hub*", 2);
@@ -98,7 +98,7 @@ public class RSQLSoftwareModuleFieldTest extends AbstractJpaIntegrationTest {
@Test
@Description("Test filter software module by name which contain mutated vowels ")
public void testFilterByParameterNameWithUmlaut() {
void testFilterByParameterNameWithUmlaut() {
assertRSQLQuery(SoftwareModuleFields.NAME.name() + "==*Ö*", 1);
assertRSQLQuery(SoftwareModuleFields.NAME.name() + "==*Ä*", 1);
assertRSQLQuery(SoftwareModuleFields.NAME.name() + "==*Ü*", 1);
@@ -106,7 +106,7 @@ public class RSQLSoftwareModuleFieldTest extends AbstractJpaIntegrationTest {
@Test
@Description("Test filter software module by description")
public void testFilterByParameterDescription() {
void testFilterByParameterDescription() {
assertRSQLQuery(SoftwareModuleFields.DESCRIPTION.name() + "==''", 1);
assertRSQLQuery(SoftwareModuleFields.DESCRIPTION.name() + "!=''", 5);
assertRSQLQuery(SoftwareModuleFields.DESCRIPTION.name() + "==agent-hub", 1);
@@ -118,7 +118,7 @@ public class RSQLSoftwareModuleFieldTest extends AbstractJpaIntegrationTest {
@Test
@Description("Test filter software module by version")
public void testFilterByParameterVersion() {
void testFilterByParameterVersion() {
assertRSQLQuery(SoftwareModuleFields.VERSION.name() + "==1.0.1", 2);
assertRSQLQuery(SoftwareModuleFields.VERSION.name() + "!=v1.0", 6);
assertRSQLQuery(SoftwareModuleFields.VERSION.name() + "=in=(1.0.1,1.0.2)", 2);
@@ -127,7 +127,7 @@ public class RSQLSoftwareModuleFieldTest extends AbstractJpaIntegrationTest {
@Test
@Description("Test filter software module by type key")
public void testFilterByType() {
void testFilterByType() {
assertRSQLQuery(SoftwareModuleFields.TYPE.name() + "==" + TestdataFactory.SM_TYPE_APP, 2);
assertRSQLQuery(SoftwareModuleFields.TYPE.name() + "!=" + TestdataFactory.SM_TYPE_APP, 4);
assertRSQLQuery(SoftwareModuleFields.TYPE.name() + "==noExist*", 0);
@@ -137,7 +137,7 @@ public class RSQLSoftwareModuleFieldTest extends AbstractJpaIntegrationTest {
@Test
@Description("Test filter software module by metadata")
public void testFilterByMetadata() {
void testFilterByMetadata() {
assertRSQLQuery(SoftwareModuleFields.METADATA.name() + ".metaKey==metaValue", 1);
assertRSQLQuery(SoftwareModuleFields.METADATA.name() + ".metaKey!=metaValue", 1);
assertRSQLQuery(SoftwareModuleFields.METADATA.name() + ".metaKey!=notexist", 2);

View File

@@ -30,12 +30,12 @@ import org.springframework.data.domain.PageRequest;
@Feature("Component Tests - Repository")
@Story("RSQL filter software module metadata")
public class RSQLSoftwareModuleMetadataFieldsTest extends AbstractJpaIntegrationTest {
class RSQLSoftwareModuleMetadataFieldsTest extends AbstractJpaIntegrationTest {
private Long softwareModuleId;
@BeforeEach
public void setupBeforeTest() {
void setupBeforeTest() {
final SoftwareModule softwareModule = testdataFactory.createSoftwareModule(TestdataFactory.SM_TYPE_APP);
softwareModuleId = softwareModule.getId();
@@ -57,7 +57,7 @@ public class RSQLSoftwareModuleMetadataFieldsTest extends AbstractJpaIntegration
@Test
@Description("Test filter software module metadata by key")
public void testFilterByParameterKey() {
void testFilterByParameterKey() {
assertRSQLQuery(SoftwareModuleMetadataFields.KEY.name() + "==1", 1);
assertRSQLQuery(SoftwareModuleMetadataFields.KEY.name() + "!=1", 6);
assertRSQLQuery(SoftwareModuleMetadataFields.KEY.name() + "=in=(1,2)", 2);
@@ -66,7 +66,7 @@ public class RSQLSoftwareModuleMetadataFieldsTest extends AbstractJpaIntegration
@Test
@Description("Test fitler software module metadata by value")
public void testFilterByParameterValue() {
void testFilterByParameterValue() {
assertRSQLQuery(SoftwareModuleMetadataFields.VALUE.name() + "==''", 1);
assertRSQLQuery(SoftwareModuleMetadataFields.VALUE.name() + "!=''", 6);
assertRSQLQuery(SoftwareModuleMetadataFields.VALUE.name() + "==1", 1);
@@ -77,7 +77,7 @@ public class RSQLSoftwareModuleMetadataFieldsTest extends AbstractJpaIntegration
@Test
@Description("Test fitler software module metadata by target visible")
public void testFilterByParameterTargetVisible() {
void testFilterByParameterTargetVisible() {
assertRSQLQuery(SoftwareModuleMetadataFields.TARGETVISIBLE.name() + "==true", 2);
assertRSQLQuery(SoftwareModuleMetadataFields.TARGETVISIBLE.name() + "==false", 5);
assertRSQLQuery(SoftwareModuleMetadataFields.TARGETVISIBLE.name() + "!=false", 2);

View File

@@ -25,11 +25,11 @@ import org.springframework.orm.jpa.vendor.Database;
@Feature("Component Tests - Repository")
@Story("RSQL filter software module test type")
public class RSQLSoftwareModuleTypeFieldsTest extends AbstractJpaIntegrationTest {
class RSQLSoftwareModuleTypeFieldsTest extends AbstractJpaIntegrationTest {
@Test
@Description("Test filter software module test type by id")
public void testFilterByParameterId() {
void testFilterByParameterId() {
assertRSQLQuery(SoftwareModuleTypeFields.ID.name() + "==" + osType.getId(), 1);
assertRSQLQuery(SoftwareModuleTypeFields.ID.name() + "!=" + osType.getId(), 2);
assertRSQLQuery(SoftwareModuleTypeFields.ID.name() + "==" + -1, 0);
@@ -46,14 +46,14 @@ public class RSQLSoftwareModuleTypeFieldsTest extends AbstractJpaIntegrationTest
@Test
@Description("Test filter software module test type by name")
public void testFilterByParameterName() {
void testFilterByParameterName() {
assertRSQLQuery(SoftwareModuleTypeFields.NAME.name() + "==" + Constants.SMT_DEFAULT_OS_NAME, 1);
assertRSQLQuery(SoftwareModuleTypeFields.NAME.name() + "!=" + Constants.SMT_DEFAULT_OS_NAME, 2);
}
@Test
@Description("Test filter software module test type by description")
public void testFilterByParameterDescription() {
void testFilterByParameterDescription() {
assertRSQLQuery(SoftwareModuleTypeFields.DESCRIPTION.name() + "==''", 0);
assertRSQLQuery(SoftwareModuleTypeFields.DESCRIPTION.name() + "!=''", 3);
assertRSQLQuery(SoftwareModuleTypeFields.DESCRIPTION.name() + "==Updated*", 3);
@@ -63,7 +63,7 @@ public class RSQLSoftwareModuleTypeFieldsTest extends AbstractJpaIntegrationTest
@Test
@Description("Test filter software module test type by key")
public void testFilterByParameterKey() {
void testFilterByParameterKey() {
assertRSQLQuery(SoftwareModuleTypeFields.KEY.name() + "==os", 1);
assertRSQLQuery(SoftwareModuleTypeFields.KEY.name() + "!=os", 2);
assertRSQLQuery(SoftwareModuleTypeFields.KEY.name() + "=in=(os)", 1);
@@ -72,7 +72,7 @@ public class RSQLSoftwareModuleTypeFieldsTest extends AbstractJpaIntegrationTest
@Test
@Description("Test filter software module test type by max")
public void testFilterByMaxAssignment() {
void testFilterByMaxAssignment() {
assertRSQLQuery(SoftwareModuleTypeFields.MAXASSIGNMENTS.name() + "==1", 2);
assertRSQLQuery(SoftwareModuleTypeFields.MAXASSIGNMENTS.name() + "!=1", 1);
}

View File

@@ -26,14 +26,14 @@ import org.springframework.data.domain.PageRequest;
@Feature("Component Tests - Repository")
@Story("RSQL filter target and distribution set tags")
public class RSQLTagFieldsTest extends AbstractJpaIntegrationTest {
class RSQLTagFieldsTest extends AbstractJpaIntegrationTest {
@BeforeEach
public void seuptBeforeTest() {
void seuptBeforeTest() {
for (int i = 0; i < 5; i++) {
final TagCreate targetTag = entityFactory.tag().create().name(Integer.toString(i))
.description(Integer.toString(i)).colour(i % 2 == 0 ? "red" : "blue");
final TagCreate targetTag = entityFactory.tag().create()
.name(Integer.toString(i)).description(Integer.toString(i)).colour(i % 2 == 0 ? "red" : "blue");
targetTagManagement.create(targetTag);
distributionSetTagManagement.create(targetTag);
}
@@ -41,7 +41,7 @@ public class RSQLTagFieldsTest extends AbstractJpaIntegrationTest {
@Test
@Description("Test filter target tag by name")
public void testFilterTargetTagByParameterName() {
void testFilterTargetTagByParameterName() {
assertRSQLQueryTarget(TagFields.NAME.name() + "==''", 0);
assertRSQLQueryTarget(TagFields.NAME.name() + "!=''", 5);
assertRSQLQueryTarget(TagFields.NAME.name() + "==1", 1);
@@ -54,7 +54,7 @@ public class RSQLTagFieldsTest extends AbstractJpaIntegrationTest {
@Test
@Description("Test filter target tag by description")
public void testFilterTargetTagByParameterDescription() {
void testFilterTargetTagByParameterDescription() {
assertRSQLQueryTarget(TagFields.DESCRIPTION.name() + "==''", 0);
assertRSQLQueryTarget(TagFields.DESCRIPTION.name() + "!=''", 5);
assertRSQLQueryTarget(TagFields.DESCRIPTION.name() + "==1", 1);
@@ -67,7 +67,7 @@ public class RSQLTagFieldsTest extends AbstractJpaIntegrationTest {
@Test
@Description("Test filter target tag by colour")
public void testFilterTargetTagByParameterColour() {
void testFilterTargetTagByParameterColour() {
assertRSQLQueryTarget(TagFields.COLOUR.name() + "==''", 0);
assertRSQLQueryTarget(TagFields.COLOUR.name() + "!=''", 5);
assertRSQLQueryTarget(TagFields.COLOUR.name() + "==red", 3);
@@ -80,7 +80,7 @@ public class RSQLTagFieldsTest extends AbstractJpaIntegrationTest {
@Test
@Description("Test filter distribution set tag by name")
public void testFilterDistributionSetTagByParameterName() {
void testFilterDistributionSetTagByParameterName() {
assertRSQLQueryDistributionSet(TagFields.NAME.name() + "==''", 0);
assertRSQLQueryDistributionSet(TagFields.NAME.name() + "!=''", 5);
assertRSQLQueryDistributionSet(TagFields.NAME.name() + "==1", 1);
@@ -93,7 +93,7 @@ public class RSQLTagFieldsTest extends AbstractJpaIntegrationTest {
@Test
@Description("Test filter distribution set by description")
public void testFilterDistributionSetTagByParameterDescription() {
void testFilterDistributionSetTagByParameterDescription() {
assertRSQLQueryDistributionSet(TagFields.DESCRIPTION.name() + "==''", 0);
assertRSQLQueryDistributionSet(TagFields.DESCRIPTION.name() + "!=''", 5);
assertRSQLQueryDistributionSet(TagFields.DESCRIPTION.name() + "==1", 1);
@@ -106,7 +106,7 @@ public class RSQLTagFieldsTest extends AbstractJpaIntegrationTest {
@Test
@Description("Test filter distribution set by colour")
public void testFilterDistributionSetTagByParameterColour() {
void testFilterDistributionSetTagByParameterColour() {
assertRSQLQueryDistributionSet(TagFields.COLOUR.name() + "==''", 0);
assertRSQLQueryDistributionSet(TagFields.COLOUR.name() + "!=''", 5);
assertRSQLQueryDistributionSet(TagFields.COLOUR.name() + "==red", 3);

View File

@@ -149,12 +149,10 @@ class RSQLTargetFieldTest extends AbstractJpaIntegrationTest {
void testFilterByParameterUpdateStatus() {
assertRSQLQuery(TargetFields.UPDATESTATUS.name() + "==pending", 1);
assertRSQLQuery(TargetFields.UPDATESTATUS.name() + "!=pending", 4);
try {
assertRSQLQuery(TargetFields.UPDATESTATUS.name() + "==noExist*", 0);
fail("RSQLParameterUnsupportedFieldException was expected since update status unknown");
} catch (final RSQLParameterUnsupportedFieldException e) {
// test ok - exception was excepted
}
final String rsqlNoExistStar = TargetFields.UPDATESTATUS.name() + "==noExist*";
assertThatExceptionOfType(RSQLParameterUnsupportedFieldException.class)
.as("update status unknown")
.isThrownBy(() -> assertRSQLQuery(rsqlNoExistStar, 0));
assertRSQLQuery(TargetFields.UPDATESTATUS.name() + "=in=(pending,error)", 1);
assertRSQLQuery(TargetFields.UPDATESTATUS.name() + "=out=(pending,error)", 4);
}

View File

@@ -28,13 +28,13 @@ import org.springframework.orm.jpa.vendor.Database;
@Feature("Component Tests - Repository")
@Story("RSQL filter target filter query")
public class RSQLTargetFilterQueryFieldsTest extends AbstractJpaIntegrationTest {
class RSQLTargetFilterQueryFieldsTest extends AbstractJpaIntegrationTest {
private TargetFilterQuery filter1;
private TargetFilterQuery filter2;
@BeforeEach
public void setupBeforeTest() {
void setupBeforeTest() {
final String filterName1 = "filter_a";
final String filterName2 = "filter_b";
final String filterName3 = "filter_c";
@@ -54,7 +54,7 @@ public class RSQLTargetFilterQueryFieldsTest extends AbstractJpaIntegrationTest
@Test
@Description("Test filter target filter query by id")
public void testFilterByParameterId() {
void testFilterByParameterId() {
assertRSQLQuery(TargetFilterQueryFields.ID.name() + "==" + filter1.getId(), 1);
assertRSQLQuery(TargetFilterQueryFields.ID.name() + "!=" + filter1.getId(), 2);
assertRSQLQuery(TargetFilterQueryFields.ID.name() + "==" + -1, 0);
@@ -72,7 +72,7 @@ public class RSQLTargetFilterQueryFieldsTest extends AbstractJpaIntegrationTest
@Test
@Description("Test filter target filter query by name")
public void testFilterByParameterName() {
void testFilterByParameterName() {
assertRSQLQuery(TargetFilterQueryFields.NAME.name() + "==" + filter1.getName(), 1);
assertRSQLQuery(TargetFilterQueryFields.NAME.name() + "==" + filter2.getName(), 1);
assertRSQLQuery(TargetFilterQueryFields.NAME.name() + "==filter_*", 3);
@@ -83,7 +83,7 @@ public class RSQLTargetFilterQueryFieldsTest extends AbstractJpaIntegrationTest
@Test
@Description("Test filter target filter query by auto assigned ds name")
public void testFilterByAutoAssignedDsName() {
void testFilterByAutoAssignedDsName() {
assertRSQLQuery(TargetFilterQueryFields.AUTOASSIGNDISTRIBUTIONSET.name() + ".name=="
+ filter1.getAutoAssignDistributionSet().getName(), 1);
assertRSQLQuery(TargetFilterQueryFields.AUTOASSIGNDISTRIBUTIONSET.name() + ".name=="
@@ -98,7 +98,7 @@ public class RSQLTargetFilterQueryFieldsTest extends AbstractJpaIntegrationTest
@Test
@Description("Test filter target filter query by auto assigned ds version")
public void testFilterByAutoAssignedDsVersion() {
void testFilterByAutoAssignedDsVersion() {
assertRSQLQuery(TargetFilterQueryFields.AUTOASSIGNDISTRIBUTIONSET.name() + ".version=="
+ TestdataFactory.DEFAULT_VERSION, 2);
assertRSQLQuery(TargetFilterQueryFields.AUTOASSIGNDISTRIBUTIONSET.name() + ".version==*1*", 2);

View File

@@ -30,12 +30,12 @@ import org.springframework.data.domain.PageRequest;
@Feature("Component Tests - Repository")
@Story("RSQL filter target metadata")
public class RSQLTargetMetadataFieldsTest extends AbstractJpaIntegrationTest {
class RSQLTargetMetadataFieldsTest extends AbstractJpaIntegrationTest {
private String controllerId;
@BeforeEach
public void setupBeforeTest() {
void setupBeforeTest() {
final Target target = testdataFactory.createTarget("target");
controllerId = target.getControllerId();
@@ -52,7 +52,7 @@ public class RSQLTargetMetadataFieldsTest extends AbstractJpaIntegrationTest {
@Test
@Description("Test filter target metadata by key")
public void testFilterByParameterKey() {
void testFilterByParameterKey() {
assertRSQLQuery(TargetMetadataFields.KEY.name() + "==1", 1);
assertRSQLQuery(TargetMetadataFields.KEY.name() + "!=1", 5);
assertRSQLQuery(TargetMetadataFields.KEY.name() + "=in=(1,2)", 2);
@@ -61,7 +61,7 @@ public class RSQLTargetMetadataFieldsTest extends AbstractJpaIntegrationTest {
@Test
@Description("Test filter target metadata by value")
public void testFilterByParameterValue() {
void testFilterByParameterValue() {
assertRSQLQuery(TargetMetadataFields.VALUE.name() + "==''", 1);
assertRSQLQuery(TargetMetadataFields.VALUE.name() + "!=''", 5);
assertRSQLQuery(TargetMetadataFields.VALUE.name() + "==1", 1);

View File

@@ -36,6 +36,7 @@ import org.springframework.test.context.ContextConfiguration;
@ContextConfiguration(classes = { RepositoryApplicationConfiguration.class, TestConfiguration.class })
@Import(TestChannelBinderConfiguration.class)
@Disabled("For manual run only, while playing around with RSQL to SQL")
@SuppressWarnings("java:S2699") // java:S2699 - manual test, don't actually does assertions
class RSQLToSQLTest {
private RSQLToSQL rsqlToSQL;

View File

@@ -12,8 +12,8 @@ package org.eclipse.hawkbit.repository.jpa.tenancy;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import io.qameta.allure.Description;
@@ -75,7 +75,7 @@ class MultiTenancyEntityTest extends AbstractJpaIntegrationTest {
// find all targets for current tenant "mytenant"
final Slice<Target> findTargetsAll = targetManagement.findAll(PAGE);
// no target has been created for "mytenant"
assertThat(findTargetsAll).hasSize(0);
assertThat(findTargetsAll).isEmpty();
// find all targets for anotherTenant
final Slice<Target> findTargetsForTenant = findTargetsForTenant(anotherTenant);
@@ -126,11 +126,11 @@ class MultiTenancyEntityTest extends AbstractJpaIntegrationTest {
// create target for another tenant
final String anotherTenant = "anotherTenant";
final String controllerAnotherTenant = "anotherController";
final Target createTargetForTenant = createTargetForTenant(controllerAnotherTenant, anotherTenant);
final List<Long> createTargetForTenant = List.of(createTargetForTenant(controllerAnotherTenant, anotherTenant).getId());
// ensure target cannot be deleted by 'mytenant'
try {
targetManagement.delete(Arrays.asList(createTargetForTenant.getId()));
targetManagement.delete(createTargetForTenant);
fail("mytenant should not have been able to delete target of anotherTenant");
} catch (final EntityNotFoundException ex) {
// ok
@@ -140,9 +140,9 @@ class MultiTenancyEntityTest extends AbstractJpaIntegrationTest {
assertThat(targetsForAnotherTenant).hasSize(1);
// ensure another tenant can delete the target
deleteTargetsForTenant(anotherTenant, Arrays.asList(createTargetForTenant.getId()));
deleteTargetsForTenant(anotherTenant, createTargetForTenant);
targetsForAnotherTenant = findTargetsForTenant(anotherTenant);
assertThat(targetsForAnotherTenant).hasSize(0);
assertThat(targetsForAnotherTenant).isEmpty();
}
@Test

View File

@@ -16,8 +16,7 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include;
import lombok.Data;
/**
* A exception model rest representation with JSON annotations for response
* bodies in case of RESTful exception occurrence.
* An exception model rest representation with JSON annotations for response bodies in case of RESTful exception occurrence.
*/
@Data
@JsonInclude(Include.NON_EMPTY)
@@ -26,5 +25,5 @@ public class ExceptionInfo {
private String exceptionClass;
private String errorCode;
private String message;
private transient Map<String, Object> info;
private Map<String, Object> info;
}

View File

@@ -145,19 +145,19 @@ public class PreAuthTokenSourceTrustAuthenticationProvider implements Authentica
// request coming
// from a trustful source, like the reverse proxy.
if (authorizedSourceIps != null) {
if (!(tokenDetails instanceof TenantAwareWebAuthenticationDetails)) {
if (tokenDetails instanceof TenantAwareWebAuthenticationDetails tenantAwareWebAuthenticationDetails) {
remoteAddress = tenantAwareWebAuthenticationDetails.getRemoteAddress();
if (authorizedSourceIps.contains(remoteAddress)) {
// source ip matches the given pattern -> authenticated
success = true;
}
} else {
// is not of type WebAuthenticationDetails, then we cannot
// determine the remote address!
log.error(
"Cannot determine the controller remote-ip-address based on the given authentication token - {} , token details are not TenantAwareWebAuthenticationDetails! ",
tokenDetails);
success = false;
} else {
remoteAddress = ((TenantAwareWebAuthenticationDetails) tokenDetails).getRemoteAddress();
if (authorizedSourceIps.contains(remoteAddress)) {
// source ip matches the given pattern -> authenticated
success = true;
}
}
}

View File

@@ -31,7 +31,9 @@ import org.springframework.security.web.access.intercept.AuthorizationFilter;
import org.springframework.web.filter.OncePerRequestFilter;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@SuppressWarnings("java:S6548") // java:S6548 - singleton holder ensures static access to spring resources in some places
// java:S6548 - singleton holder ensures static access to spring resources in some places
// java:S112 - it is generic class so a generic exception is fine
@SuppressWarnings({ "java:S6548", "java:S112" })
public class MdcHandler {
public static final String MDC_KEY_TENANT = "tenant";