Sonar Fixes (7) (#2216)

Signed-off-by: Avgustin Marinov <Avgustin.Marinov@bosch.com>
This commit is contained in:
Avgustin Marinov
2025-01-21 22:13:54 +02:00
committed by GitHub
parent f09db20b71
commit 3d390b9ad7
21 changed files with 101 additions and 101 deletions

View File

@@ -28,11 +28,11 @@ import org.junit.jupiter.api.Test;
*/ */
@Feature("Unit Tests - Direct Device Integration API") @Feature("Unit Tests - Direct Device Integration API")
@Story("Serialization of DDI api Models") @Story("Serialization of DDI api Models")
public class JsonIgnorePropertiesAnnotationTest { class JsonIgnorePropertiesAnnotationTest {
@Test @Test
@Description("This test verifies that all model classes within the 'org.eclipse.hawkbit.ddi.json.model' package are annotated with '@JsonIgnoreProperties(ignoreUnknown = true)'") @Description("This test verifies that all model classes within the 'org.eclipse.hawkbit.ddi.json.model' package are annotated with '@JsonIgnoreProperties(ignoreUnknown = true)'")
public void shouldCheckAnnotationsForAllModelClasses() { void shouldCheckAnnotationsForAllModelClasses() {
final String packageName = getClass().getPackage().getName(); final String packageName = getClass().getPackage().getName();
try (final ScanResult scanResult = new ClassGraph().acceptPackages(packageName).scan()) { try (final ScanResult scanResult = new ClassGraph().acceptPackages(packageName).scan()) {
final List<? extends Class<?>> matchingClasses = scanResult.getAllClasses() final List<? extends Class<?>> matchingClasses = scanResult.getAllClasses()

View File

@@ -20,6 +20,8 @@ import lombok.experimental.Accessors;
/** /**
* Request Body for PUT. * Request Body for PUT.
*
* @deprecated Since 0.6.0
*/ */
@Data @Data
@Accessors(chain = true) @Accessors(chain = true)

View File

@@ -46,7 +46,7 @@ import org.springframework.test.web.servlet.ResultActions;
@Feature("Component Tests - Management API") @Feature("Component Tests - Management API")
@Story("Distribution Set Tag Resource") @Story("Distribution Set Tag Resource")
public class MgmtDeprecatedResourceTest extends AbstractManagementApiIntegrationTest { class MgmtDeprecatedResourceTest extends AbstractManagementApiIntegrationTest {
@Test @Test
@Description("Verifies that tag assignments done through toggle API command are correctly assigned or unassigned.") @Description("Verifies that tag assignments done through toggle API command are correctly assigned or unassigned.")
@@ -54,7 +54,7 @@ public class MgmtDeprecatedResourceTest extends AbstractManagementApiIntegration
@Expect(type = DistributionSetTagCreatedEvent.class, count = 1), @Expect(type = DistributionSetTagCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 2), @Expect(type = DistributionSetCreatedEvent.class, count = 2),
@Expect(type = DistributionSetUpdatedEvent.class, count = 4) }) @Expect(type = DistributionSetUpdatedEvent.class, count = 4) })
public void toggleDistributionSetTagAssignment() throws Exception { void toggleDistributionSetTagAssignment() throws Exception {
final DistributionSetTag tag = testdataFactory.createDistributionSetTags(1).get(0); final DistributionSetTag tag = testdataFactory.createDistributionSetTags(1).get(0);
final int setsAssigned = 2; final int setsAssigned = 2;
final List<DistributionSet> sets = testdataFactory.createDistributionSetsWithoutModules(setsAssigned); final List<DistributionSet> sets = testdataFactory.createDistributionSetsWithoutModules(setsAssigned);
@@ -64,8 +64,8 @@ public class MgmtDeprecatedResourceTest extends AbstractManagementApiIntegration
List<DistributionSet> updated = distributionSetManagement.findByTag(tag.getId(), PAGE).getContent(); List<DistributionSet> updated = distributionSetManagement.findByTag(tag.getId(), PAGE).getContent();
assertThat(updated.stream().map(DistributionSet::getId).collect(Collectors.toList())) assertThat(updated.stream().map(DistributionSet::getId).toList())
.containsAll(sets.stream().map(DistributionSet::getId).collect(Collectors.toList())); .containsAll(sets.stream().map(DistributionSet::getId).toList());
result.andExpect(applyBaseEntityMatcherOnArrayResult(updated.get(0), "assignedDistributionSets")) result.andExpect(applyBaseEntityMatcherOnArrayResult(updated.get(0), "assignedDistributionSets"))
.andExpect(applyBaseEntityMatcherOnArrayResult(updated.get(1), "assignedDistributionSets")); .andExpect(applyBaseEntityMatcherOnArrayResult(updated.get(1), "assignedDistributionSets"));
@@ -87,7 +87,7 @@ public class MgmtDeprecatedResourceTest extends AbstractManagementApiIntegration
@Expect(type = DistributionSetTagCreatedEvent.class, count = 1), @Expect(type = DistributionSetTagCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 2), @Expect(type = DistributionSetCreatedEvent.class, count = 2),
@Expect(type = DistributionSetUpdatedEvent.class, count = 2) }) @Expect(type = DistributionSetUpdatedEvent.class, count = 2) })
public void assignDistributionSetsWithRequestBody() throws Exception { void assignDistributionSetsWithRequestBody() throws Exception {
final DistributionSetTag tag = testdataFactory.createDistributionSetTags(1).get(0); final DistributionSetTag tag = testdataFactory.createDistributionSetTags(1).get(0);
final int setsAssigned = 2; final int setsAssigned = 2;
final List<DistributionSet> sets = testdataFactory.createDistributionSetsWithoutModules(setsAssigned); final List<DistributionSet> sets = testdataFactory.createDistributionSetsWithoutModules(setsAssigned);
@@ -104,8 +104,8 @@ public class MgmtDeprecatedResourceTest extends AbstractManagementApiIntegration
final List<DistributionSet> updated = distributionSetManagement.findByTag(tag.getId(), PAGE).getContent(); final List<DistributionSet> updated = distributionSetManagement.findByTag(tag.getId(), PAGE).getContent();
assertThat(updated.stream().map(DistributionSet::getId).collect(Collectors.toList())) assertThat(updated.stream().map(DistributionSet::getId).toList())
.containsAll(sets.stream().map(DistributionSet::getId).collect(Collectors.toList())); .containsAll(sets.stream().map(DistributionSet::getId).toList());
result.andExpect(applyBaseEntityMatcherOnArrayResult(updated.get(0))) result.andExpect(applyBaseEntityMatcherOnArrayResult(updated.get(0)))
.andExpect(applyBaseEntityMatcherOnArrayResult(updated.get(1))); .andExpect(applyBaseEntityMatcherOnArrayResult(updated.get(1)));
@@ -117,7 +117,7 @@ public class MgmtDeprecatedResourceTest extends AbstractManagementApiIntegration
@Expect(type = TargetTagCreatedEvent.class, count = 1), @Expect(type = TargetTagCreatedEvent.class, count = 1),
@Expect(type = TargetCreatedEvent.class, count = 2), @Expect(type = TargetCreatedEvent.class, count = 2),
@Expect(type = TargetUpdatedEvent.class, count = 4) }) @Expect(type = TargetUpdatedEvent.class, count = 4) })
public void toggleTargetTagAssignment() throws Exception { void toggleTargetTagAssignment() throws Exception {
final TargetTag tag = testdataFactory.createTargetTags(1, "").get(0); final TargetTag tag = testdataFactory.createTargetTags(1, "").get(0);
final int targetsAssigned = 2; final int targetsAssigned = 2;
final List<Target> targets = testdataFactory.createTargets(targetsAssigned); final List<Target> targets = testdataFactory.createTargets(targetsAssigned);
@@ -126,8 +126,8 @@ public class MgmtDeprecatedResourceTest extends AbstractManagementApiIntegration
List<Target> updated = targetManagement.findByTag(PAGE, tag.getId()).getContent(); 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())
.containsAll(targets.stream().map(Target::getControllerId).collect(Collectors.toList())); .containsAll(targets.stream().map(Target::getControllerId).toList());
result.andExpect(applyTargetEntityMatcherOnArrayResult(updated.get(0), "assignedTargets")) result.andExpect(applyTargetEntityMatcherOnArrayResult(updated.get(0), "assignedTargets"))
.andExpect(applyTargetEntityMatcherOnArrayResult(updated.get(1), "assignedTargets")); .andExpect(applyTargetEntityMatcherOnArrayResult(updated.get(1), "assignedTargets"));
@@ -148,7 +148,7 @@ public class MgmtDeprecatedResourceTest extends AbstractManagementApiIntegration
@Expect(type = TargetTagCreatedEvent.class, count = 1), @Expect(type = TargetTagCreatedEvent.class, count = 1),
@Expect(type = TargetCreatedEvent.class, count = 2), @Expect(type = TargetCreatedEvent.class, count = 2),
@Expect(type = TargetUpdatedEvent.class, count = 2) }) @Expect(type = TargetUpdatedEvent.class, count = 2) })
public void assignTargetsByRequestBody() throws Exception { void assignTargetsByRequestBody() throws Exception {
final TargetTag tag = testdataFactory.createTargetTags(1, "").get(0); final TargetTag tag = testdataFactory.createTargetTags(1, "").get(0);
final int targetsAssigned = 2; final int targetsAssigned = 2;
final List<Target> targets = testdataFactory.createTargets(targetsAssigned); final List<Target> targets = testdataFactory.createTargets(targetsAssigned);
@@ -156,7 +156,7 @@ public class MgmtDeprecatedResourceTest extends AbstractManagementApiIntegration
final ResultActions result = mvc final ResultActions result = mvc
.perform(post(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned") .perform(post(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned")
.content(controllerIdsOld( .content(controllerIdsOld(
targets.stream().map(Target::getControllerId).collect(Collectors.toList()))) targets.stream().map(Target::getControllerId).toList()))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()) .andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk()) .andExpect(status().isOk())
@@ -164,8 +164,8 @@ public class MgmtDeprecatedResourceTest extends AbstractManagementApiIntegration
final List<Target> updated = targetManagement.findByTag(PAGE, tag.getId()).getContent(); 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())
.containsAll(targets.stream().map(Target::getControllerId).collect(Collectors.toList())); .containsAll(targets.stream().map(Target::getControllerId).toList());
result.andExpect(applyTargetEntityMatcherOnArrayResult(updated.get(0))) result.andExpect(applyTargetEntityMatcherOnArrayResult(updated.get(0)))
.andExpect(applyTargetEntityMatcherOnArrayResult(updated.get(1))); .andExpect(applyTargetEntityMatcherOnArrayResult(updated.get(1)));
@@ -175,7 +175,7 @@ public class MgmtDeprecatedResourceTest extends AbstractManagementApiIntegration
return mvc return mvc
.perform(post(MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() .perform(post(MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId()
+ "/assigned/toggleTagAssignment").content( + "/assigned/toggleTagAssignment").content(
JsonBuilder.ids(sets.stream().map(DistributionSet::getId).collect(Collectors.toList()))) JsonBuilder.ids(sets.stream().map(DistributionSet::getId).toList()))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()) .andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk()) .andExpect(status().isOk())
@@ -196,7 +196,7 @@ public class MgmtDeprecatedResourceTest extends AbstractManagementApiIntegration
.perform(post(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() .perform(post(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId()
+ "/assigned/toggleTagAssignment") + "/assigned/toggleTagAssignment")
.content(controllerIdsOld( .content(controllerIdsOld(
targets.stream().map(Target::getControllerId).collect(Collectors.toList()))) targets.stream().map(Target::getControllerId).toList()))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()) .andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk()) .andExpect(status().isOk())

View File

@@ -12,7 +12,6 @@ package org.eclipse.hawkbit.mgmt.rest.resource;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
import lombok.AccessLevel; import lombok.AccessLevel;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
@@ -41,7 +40,7 @@ public final class MgmtActionMapper {
} }
return new ResponseList<>(actions.stream() return new ResponseList<>(actions.stream()
.map(action -> toResponse(action, repMode)) .map(action -> toResponse(action, repMode))
.collect(Collectors.toList())); .toList());
} }
static MgmtAction toResponse(final Action action, final MgmtRepresentationMode repMode) { static MgmtAction toResponse(final Action action, final MgmtRepresentationMode repMode) {

View File

@@ -51,7 +51,7 @@ public final class MgmtDistributionSetMapper {
*/ */
static List<DistributionSetCreate> dsFromRequest( static List<DistributionSetCreate> dsFromRequest(
final Collection<MgmtDistributionSetRequestBodyPost> sets, final EntityFactory entityFactory) { final Collection<MgmtDistributionSetRequestBodyPost> sets, final EntityFactory entityFactory) {
return sets.stream().map(dsRest -> fromRequest(dsRest, entityFactory)).collect(Collectors.toList()); return sets.stream().map(dsRest -> fromRequest(dsRest, entityFactory)).toList();
} }
static List<MetaData> fromRequestDsMetadata(final List<MgmtMetadata> metadata, final EntityFactory entityFactory) { static List<MetaData> fromRequestDsMetadata(final List<MgmtMetadata> metadata, final EntityFactory entityFactory) {
@@ -61,7 +61,7 @@ public final class MgmtDistributionSetMapper {
return metadata.stream() return metadata.stream()
.map(metadataRest -> entityFactory.generateDsMetadata(metadataRest.getKey(), metadataRest.getValue())) .map(metadataRest -> entityFactory.generateDsMetadata(metadataRest.getKey(), metadataRest.getValue()))
.collect(Collectors.toList()); .toList();
} }
static MgmtDistributionSet toResponse(final DistributionSet distributionSet) { static MgmtDistributionSet toResponse(final DistributionSet distributionSet) {
@@ -111,7 +111,7 @@ public final class MgmtDistributionSetMapper {
final MgmtTargetAssignmentResponseBody result = new MgmtTargetAssignmentResponseBody(); final MgmtTargetAssignmentResponseBody result = new MgmtTargetAssignmentResponseBody();
result.setAlreadyAssigned(dsAssignmentResult.getAlreadyAssigned()); result.setAlreadyAssigned(dsAssignmentResult.getAlreadyAssigned());
result.setAssignedActions(dsAssignmentResult.getAssignedEntity().stream() result.setAssignedActions(dsAssignmentResult.getAssignedEntity().stream()
.map(a -> new MgmtActionId(a.getTarget().getControllerId(), a.getId())).collect(Collectors.toList())); .map(a -> new MgmtActionId(a.getTarget().getControllerId(), a.getId())).toList());
return result; return result;
} }
@@ -123,7 +123,7 @@ public final class MgmtDistributionSetMapper {
final List<MgmtActionId> assignedActions = dsAssignmentResults.stream() final List<MgmtActionId> assignedActions = dsAssignmentResults.stream()
.flatMap(assignmentResult -> assignmentResult.getAssignedEntity().stream()) .flatMap(assignmentResult -> assignmentResult.getAssignedEntity().stream())
.map(action -> new MgmtActionId(action.getTarget().getControllerId(), action.getId())) .map(action -> new MgmtActionId(action.getTarget().getControllerId(), action.getId()))
.collect(Collectors.toList()); .toList();
result.setAlreadyAssigned(alreadyAssigned); result.setAlreadyAssigned(alreadyAssigned);
result.setAssignedActions(assignedActions); result.setAssignedActions(assignedActions);
return result; return result;
@@ -136,7 +136,7 @@ public final class MgmtDistributionSetMapper {
} }
return new ResponseList<>( return new ResponseList<>(
sets.stream().map(MgmtDistributionSetMapper::toResponse).collect(Collectors.toList())); sets.stream().map(MgmtDistributionSetMapper::toResponse).toList());
} }
static MgmtMetadata toResponseDsMetadata(final DistributionSetMetadata metadata) { static MgmtMetadata toResponseDsMetadata(final DistributionSetMetadata metadata) {
@@ -159,7 +159,7 @@ public final class MgmtDistributionSetMapper {
return Collections.emptyList(); return Collections.emptyList();
} }
return sets.stream().map(MgmtDistributionSetMapper::toResponse).collect(Collectors.toList()); return sets.stream().map(MgmtDistributionSetMapper::toResponse).toList();
} }
/** /**

View File

@@ -268,10 +268,9 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
: dsAssignment.getConfirmationRequired(); : dsAssignment.getConfirmationRequired();
return MgmtDeploymentRequestMapper.createAssignmentRequestBuilder(dsAssignment, distributionSetId) return MgmtDeploymentRequestMapper.createAssignmentRequestBuilder(dsAssignment, distributionSetId)
.setConfirmationRequired(isConfirmationRequired).build(); .setConfirmationRequired(isConfirmationRequired).build();
}).collect(Collectors.toList()); }).toList();
final List<DistributionSetAssignmentResult> assignmentResults = deployManagement final List<DistributionSetAssignmentResult> assignmentResults = deployManagement.assignDistributionSets(deploymentRequests);
.assignDistributionSets(deploymentRequests);
return ResponseEntity.ok(MgmtDistributionSetMapper.toResponse(assignmentResults)); return ResponseEntity.ok(MgmtDistributionSetMapper.toResponse(assignmentResults));
} }
@@ -338,7 +337,7 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
distributionSetId, distributionSetId,
softwareModuleIDs.stream() softwareModuleIDs.stream()
.map(MgmtSoftwareModuleAssignment::getId) .map(MgmtSoftwareModuleAssignment::getId)
.collect(Collectors.toList())); .toList());
return ResponseEntity.ok().build(); return ResponseEntity.ok().build();
} }

View File

@@ -455,8 +455,7 @@ class MgmtActionResourceTest extends AbstractManagementApiIntegrationTest {
void invalidRequestsOnActionResource() throws Exception { void invalidRequestsOnActionResource() throws Exception {
final String knownTargetId = "targetId"; final String knownTargetId = "targetId";
final List<Action> actions = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId); generateTargetWithTwoUpdatesWithOneOverride(knownTargetId);
final Long actionId = actions.get(0).getId();
// not allowed methods // not allowed methods
mvc.perform(post(MgmtRestConstants.ACTION_V1_REQUEST_MAPPING)) mvc.perform(post(MgmtRestConstants.ACTION_V1_REQUEST_MAPPING))

View File

@@ -74,7 +74,7 @@ import org.springframework.web.context.WebApplicationContext;
@Import(TestChannelBinderConfiguration.class) @Import(TestChannelBinderConfiguration.class)
@Feature("Component Tests - Management API") @Feature("Component Tests - Management API")
@Story("Basic auth Userinfo Resource") @Story("Basic auth Userinfo Resource")
public class MgmtBasicAuthResourceTest { class MgmtBasicAuthResourceTest {
@Autowired @Autowired
protected WebApplicationContext webApplicationContext; protected WebApplicationContext webApplicationContext;
@@ -86,7 +86,7 @@ public class MgmtBasicAuthResourceTest {
@Test @Test
@Description("Test of userinfo api with basic auth validation") @Description("Test of userinfo api with basic auth validation")
@WithUser(principal = TEST_USER) @WithUser(principal = TEST_USER)
public void validateBasicAuthWithUserDetails() throws Exception { void validateBasicAuthWithUserDetails() throws Exception {
withSecurityMock().perform(get(MgmtRestConstants.AUTH_V1_REQUEST_MAPPING)) withSecurityMock().perform(get(MgmtRestConstants.AUTH_V1_REQUEST_MAPPING))
.andDo(MockMvcResultPrinter.print()) .andDo(MockMvcResultPrinter.print())
.andDo(MockMvcResultPrinter.print()) .andDo(MockMvcResultPrinter.print())
@@ -98,7 +98,7 @@ public class MgmtBasicAuthResourceTest {
@Test @Test
@Description("Test of userinfo api with invalid basic auth fails") @Description("Test of userinfo api with invalid basic auth fails")
public void validateBasicAuthFailsWithInvalidCredentials() throws Exception { void validateBasicAuthFailsWithInvalidCredentials() throws Exception {
defaultMock.perform(get(MgmtRestConstants.AUTH_V1_REQUEST_MAPPING) defaultMock.perform(get(MgmtRestConstants.AUTH_V1_REQUEST_MAPPING)
.header(HttpHeaders.AUTHORIZATION, getBasicAuth("wrongUser", "wrongSecret"))) .header(HttpHeaders.AUTHORIZATION, getBasicAuth("wrongUser", "wrongSecret")))
.andDo(MockMvcResultPrinter.print()) .andDo(MockMvcResultPrinter.print())

View File

@@ -790,7 +790,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
@Description("Ensures that multiple DS requested are listed with expected payload.") @Description("Ensures that multiple DS requested are listed with expected payload.")
public void getDistributionSets() throws Exception { public void getDistributionSets() throws Exception {
// prepare test data // prepare test data
assertThat(distributionSetManagement.findByCompleted(PAGE, true)).hasSize(0); assertThat(distributionSetManagement.findByCompleted(PAGE, true)).isEmpty();
DistributionSet set = testdataFactory.createDistributionSet("one"); DistributionSet set = testdataFactory.createDistributionSet("one");
set = distributionSetManagement.update(entityFactory.distributionSet().update(set.getId()) set = distributionSetManagement.update(entityFactory.distributionSet().update(set.getId())
@@ -865,7 +865,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Ensures that multipe DS posted to API are created in the repository.") @Description("Ensures that multipe DS posted to API are created in the repository.")
public void createDistributionSets() throws Exception { public void createDistributionSets() throws Exception {
assertThat(distributionSetManagement.findByCompleted(PAGE, true)).hasSize(0); assertThat(distributionSetManagement.findByCompleted(PAGE, true)).isEmpty();
final SoftwareModule ah = testdataFactory.createSoftwareModule(TestdataFactory.SM_TYPE_APP); final SoftwareModule ah = testdataFactory.createSoftwareModule(TestdataFactory.SM_TYPE_APP);
final SoftwareModule jvm = testdataFactory.createSoftwareModule(TestdataFactory.SM_TYPE_RT); final SoftwareModule jvm = testdataFactory.createSoftwareModule(TestdataFactory.SM_TYPE_RT);
final SoftwareModule os = testdataFactory.createSoftwareModule(TestdataFactory.SM_TYPE_OS); final SoftwareModule os = testdataFactory.createSoftwareModule(TestdataFactory.SM_TYPE_OS);
@@ -925,7 +925,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
@Description("Ensures that DS deletion request to API is reflected by the repository.") @Description("Ensures that DS deletion request to API is reflected by the repository.")
public void deleteUnassignedistributionSet() throws Exception { public void deleteUnassignedistributionSet() throws Exception {
// prepare test data // prepare test data
assertThat(distributionSetManagement.findByCompleted(PAGE, true)).hasSize(0); assertThat(distributionSetManagement.findByCompleted(PAGE, true)).isEmpty();
final DistributionSet set = testdataFactory.createDistributionSet("one"); final DistributionSet set = testdataFactory.createDistributionSet("one");
@@ -953,7 +953,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
@Description("Ensures that assigned DS deletion request to API is reflected by the repository by means of deleted flag set.") @Description("Ensures that assigned DS deletion request to API is reflected by the repository by means of deleted flag set.")
public void deleteAssignedDistributionSet() throws Exception { public void deleteAssignedDistributionSet() throws Exception {
// prepare test data // prepare test data
assertThat(distributionSetManagement.findByCompleted(PAGE, true)).hasSize(0); assertThat(distributionSetManagement.findByCompleted(PAGE, true)).isEmpty();
final DistributionSet set = testdataFactory.createDistributionSet("one"); final DistributionSet set = testdataFactory.createDistributionSet("one");
testdataFactory.createTarget("test"); testdataFactory.createTarget("test");
@@ -976,14 +976,14 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
.andExpect(jsonPath("$.deleted", equalTo(true))); .andExpect(jsonPath("$.deleted", equalTo(true)));
// check repository content // check repository content
assertThat(distributionSetManagement.findByCompleted(PAGE, true)).hasSize(0); assertThat(distributionSetManagement.findByCompleted(PAGE, true)).isEmpty();
} }
@Test @Test
@Description("Ensures that DS property update request to API is reflected by the repository.") @Description("Ensures that DS property update request to API is reflected by the repository.")
public void updateDistributionSet() throws Exception { public void updateDistributionSet() throws Exception {
// prepare test data // prepare test data
assertThat(distributionSetManagement.findByCompleted(PAGE, true)).hasSize(0); assertThat(distributionSetManagement.findByCompleted(PAGE, true)).isEmpty();
final DistributionSet set = testdataFactory.createDistributionSet("one"); final DistributionSet set = testdataFactory.createDistributionSet("one");
assertThat(distributionSetManagement.count()).isEqualTo(1); assertThat(distributionSetManagement.count()).isEqualTo(1);
@@ -1002,10 +1002,10 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
final DistributionSet setupdated = distributionSetManagement.get(set.getId()).get(); final DistributionSet setupdated = distributionSetManagement.get(set.getId()).get();
assertThat(setupdated.isRequiredMigrationStep()).isEqualTo(true); assertThat(setupdated.isRequiredMigrationStep()).isTrue();
assertThat(setupdated.getVersion()).isEqualTo("anotherVersion"); assertThat(setupdated.getVersion()).isEqualTo("anotherVersion");
assertThat(setupdated.getName()).isEqualTo(set.getName()); assertThat(setupdated.getName()).isEqualTo(set.getName());
assertThat(setupdated.isDeleted()).isEqualTo(false); assertThat(setupdated.isDeleted()).isFalse();
} }
@Test @Test
@@ -1013,7 +1013,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
public void updateRequiredMigrationStepFailsIfDistributionSetisInUse() throws Exception { public void updateRequiredMigrationStepFailsIfDistributionSetisInUse() throws Exception {
// prepare test data // prepare test data
assertThat(distributionSetManagement.findByCompleted(PAGE, true)).hasSize(0); assertThat(distributionSetManagement.findByCompleted(PAGE, true)).isEmpty();
final DistributionSet set = testdataFactory.createDistributionSet("one"); final DistributionSet set = testdataFactory.createDistributionSet("one");
assignDistributionSet(set.getId(), testdataFactory.createTarget().getControllerId()); assignDistributionSet(set.getId(), testdataFactory.createTarget().getControllerId());
@@ -1028,7 +1028,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
final DistributionSet setupdated = distributionSetManagement.get(set.getId()).get(); final DistributionSet setupdated = distributionSetManagement.get(set.getId()).get();
assertThat(setupdated.isRequiredMigrationStep()).isEqualTo(false); assertThat(setupdated.isRequiredMigrationStep()).isFalse();
assertThat(setupdated.getVersion()).isEqualTo(set.getVersion()); assertThat(setupdated.getVersion()).isEqualTo(set.getVersion());
assertThat(setupdated.getName()).isEqualTo(set.getName()); assertThat(setupdated.getName()).isEqualTo(set.getName());
} }
@@ -1674,7 +1674,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
@Description("Tests the lock. It is verified that the distribution set can be marked as locked through update operation.") @Description("Tests the lock. It is verified that the distribution set can be marked as locked through update operation.")
void lockDistributionSet() throws Exception { void lockDistributionSet() throws Exception {
// prepare test data // prepare test data
assertThat(distributionSetManagement.findByCompleted(PAGE, true)).hasSize(0); assertThat(distributionSetManagement.findByCompleted(PAGE, true)).isEmpty();
final DistributionSet set = testdataFactory.createDistributionSet("one"); final DistributionSet set = testdataFactory.createDistributionSet("one");
assertThat(distributionSetManagement.count()).isEqualTo(1); assertThat(distributionSetManagement.count()).isEqualTo(1);
@@ -1689,14 +1689,14 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
.andExpect(jsonPath("$.locked", equalTo(true))); .andExpect(jsonPath("$.locked", equalTo(true)));
final DistributionSet updatedSet = distributionSetManagement.get(set.getId()).get(); final DistributionSet updatedSet = distributionSetManagement.get(set.getId()).get();
assertThat(updatedSet.isLocked()).isEqualTo(true); assertThat(updatedSet.isLocked()).isTrue();
} }
@Test @Test
@Description("Tests the unlock.") @Description("Tests the unlock.")
void unlockDistributionSet() throws Exception { void unlockDistributionSet() throws Exception {
// prepare test data // prepare test data
assertThat(distributionSetManagement.findByCompleted(PAGE, true)).hasSize(0); assertThat(distributionSetManagement.findByCompleted(PAGE, true)).isEmpty();
final DistributionSet set = testdataFactory.createDistributionSet("one"); final DistributionSet set = testdataFactory.createDistributionSet("one");
assertThat(distributionSetManagement.count()).isEqualTo(1); assertThat(distributionSetManagement.count()).isEqualTo(1);
@@ -1715,7 +1715,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
.andExpect(jsonPath("$.locked", equalTo(false))); .andExpect(jsonPath("$.locked", equalTo(false)));
final DistributionSet updatedSet = distributionSetManagement.get(set.getId()).get(); final DistributionSet updatedSet = distributionSetManagement.get(set.getId()).get();
assertThat(updatedSet.isLocked()).isEqualTo(false); assertThat(updatedSet.isLocked()).isFalse();
} }
private static Stream<Arguments> confirmationOptions() { private static Stream<Arguments> confirmationOptions() {

View File

@@ -22,6 +22,7 @@ import com.cronutils.model.definition.CronDefinitionBuilder;
import com.cronutils.model.time.ExecutionTime; import com.cronutils.model.time.ExecutionTime;
import com.cronutils.parser.CronParser; import com.cronutils.parser.CronParser;
import org.eclipse.hawkbit.repository.exception.InvalidMaintenanceScheduleException; import org.eclipse.hawkbit.repository.exception.InvalidMaintenanceScheduleException;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
/** /**
@@ -170,14 +171,14 @@ public final class MaintenanceScheduleHelper {
} }
private static boolean atLeastOneNotEmpty(final String cronSchedule, final String duration, final String timezone) { private static boolean atLeastOneNotEmpty(final String cronSchedule, final String duration, final String timezone) {
return !(StringUtils.isEmpty(cronSchedule) && StringUtils.isEmpty(duration) && StringUtils.isEmpty(timezone)); return !(ObjectUtils.isEmpty(cronSchedule) && ObjectUtils.isEmpty(duration) && ObjectUtils.isEmpty(timezone));
} }
private static boolean allNotEmpty(final String cronSchedule, final String duration, final String timezone) { private static boolean allNotEmpty(final String cronSchedule, final String duration, final String timezone) {
return !StringUtils.isEmpty(cronSchedule) && !StringUtils.isEmpty(duration) && !StringUtils.isEmpty(timezone); return !ObjectUtils.isEmpty(cronSchedule) && !ObjectUtils.isEmpty(duration) && !ObjectUtils.isEmpty(timezone);
} }
private static LocalTime convertDurationToLocalTime(final String timeInterval) { private static LocalTime convertDurationToLocalTime(final String timeInterval) {
return LocalTime.parse(StringUtils.trimWhitespace(timeInterval)); return LocalTime.parse(timeInterval.strip());
} }
} }

View File

@@ -24,25 +24,25 @@ import org.junit.jupiter.api.Test;
@Feature("Unit Tests - Repository") @Feature("Unit Tests - Repository")
@Story("Maintenance Schedule Utility") @Story("Maintenance Schedule Utility")
public class MaintenanceScheduleHelperTest { class MaintenanceScheduleHelperTest {
@Test @Test
@Description("Verifies that the Cron object is returned for valid cron expression") @Description("Verifies that the Cron object is returned for valid cron expression")
public void getCronFromExpressionValid() { void getCronFromExpressionValid() {
final String validCron = "0 0 0 ? * 6"; // at 00:00 every Saturday final String validCron = "0 0 0 ? * 6"; // at 00:00 every Saturday
assertThat(MaintenanceScheduleHelper.getCronFromExpression(validCron)).isNotNull().isInstanceOf(Cron.class); assertThat(MaintenanceScheduleHelper.getCronFromExpression(validCron)).isNotNull().isInstanceOf(Cron.class);
} }
@Test @Test
@Description("Verifies that the Duration object is returned for valid duration format (hh:mm or hh:mm:ss)") @Description("Verifies that the Duration object is returned for valid duration format (hh:mm or hh:mm:ss)")
public void convertToISODurationValid() { void convertToISODurationValid() {
final String duration = "00:10"; final String duration = "00:10";
assertThat(MaintenanceScheduleHelper.convertToISODuration(duration)).isNotNull().isInstanceOf(Duration.class); assertThat(MaintenanceScheduleHelper.convertToISODuration(duration)).isNotNull().isInstanceOf(Duration.class);
} }
@Test @Test
@Description("Verifies that the InvalidMaintenanceScheduleException is thrown for invalid duration format") @Description("Verifies that the InvalidMaintenanceScheduleException is thrown for invalid duration format")
public void validateDurationInvalid() { void validateDurationInvalid() {
final String duration = "10"; final String duration = "10";
assertThatThrownBy(() -> MaintenanceScheduleHelper.validateDuration(duration)) assertThatThrownBy(() -> MaintenanceScheduleHelper.validateDuration(duration))
.isInstanceOf(InvalidMaintenanceScheduleException.class).hasMessage("Provided duration is not valid") .isInstanceOf(InvalidMaintenanceScheduleException.class).hasMessage("Provided duration is not valid")
@@ -51,7 +51,7 @@ public class MaintenanceScheduleHelperTest {
@Test @Test
@Description("Verifies that the InvalidMaintenanceScheduleException is thrown for invalid cron expression") @Description("Verifies that the InvalidMaintenanceScheduleException is thrown for invalid cron expression")
public void validateCronScheduleInvalid() { void validateCronScheduleInvalid() {
final String invalidCron = "0 0 0 * * 6"; final String invalidCron = "0 0 0 * * 6";
assertThatThrownBy(() -> MaintenanceScheduleHelper.validateCronSchedule(invalidCron)) assertThatThrownBy(() -> MaintenanceScheduleHelper.validateCronSchedule(invalidCron))
.isInstanceOf(InvalidMaintenanceScheduleException.class) .isInstanceOf(InvalidMaintenanceScheduleException.class)
@@ -60,7 +60,7 @@ public class MaintenanceScheduleHelperTest {
@Test @Test
@Description("Verifies that there is a maintenance window available for correct schedule, duration and timezone") @Description("Verifies that there is a maintenance window available for correct schedule, duration and timezone")
public void getNextMaintenanceWindowValid() { void getNextMaintenanceWindowValid() {
final ZonedDateTime currentTime = ZonedDateTime.now(); final ZonedDateTime currentTime = ZonedDateTime.now();
final String cronSchedule = String.format("0 %d %d %d %d ? %d", currentTime.getMinute(), currentTime.getHour(), final String cronSchedule = String.format("0 %d %d %d %d ? %d", currentTime.getMinute(), currentTime.getHour(),
currentTime.getDayOfMonth(), currentTime.getMonthValue(), currentTime.getYear()); currentTime.getDayOfMonth(), currentTime.getMonthValue(), currentTime.getYear());
@@ -71,7 +71,7 @@ public class MaintenanceScheduleHelperTest {
@Test @Test
@Description("Verifies the maintenance schedule when only one required field is present") @Description("Verifies the maintenance schedule when only one required field is present")
public void validateMaintenanceScheduleAtLeastOneNotEmpty() { void validateMaintenanceScheduleAtLeastOneNotEmpty() {
final String duration = "00:10"; final String duration = "00:10";
assertThatThrownBy(() -> MaintenanceScheduleHelper.validateMaintenanceSchedule(null, duration, null)) assertThatThrownBy(() -> MaintenanceScheduleHelper.validateMaintenanceSchedule(null, duration, null))
.isInstanceOf(InvalidMaintenanceScheduleException.class) .isInstanceOf(InvalidMaintenanceScheduleException.class)
@@ -80,7 +80,7 @@ public class MaintenanceScheduleHelperTest {
@Test @Test
@Description("Verifies that there is no valid maintenance window available, scheduled before current time") @Description("Verifies that there is no valid maintenance window available, scheduled before current time")
public void validateMaintenanceScheduleBeforeCurrentTime() { void validateMaintenanceScheduleBeforeCurrentTime() {
ZonedDateTime currentTime = ZonedDateTime.now(); ZonedDateTime currentTime = ZonedDateTime.now();
currentTime = currentTime.plusMinutes(-30); currentTime = currentTime.plusMinutes(-30);
final String cronSchedule = String.format("0 %d %d %d %d ? %d", currentTime.getMinute(), currentTime.getHour(), final String cronSchedule = String.format("0 %d %d %d %d ? %d", currentTime.getMinute(), currentTime.getHour(),

View File

@@ -183,7 +183,7 @@ public class JpaSoftwareModuleManagement implements SoftwareModuleManagement {
@Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, @Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX,
backoff = @Backoff(delay = Constants.TX_RT_DELAY)) backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public void delete(final long id) { public void delete(final long id) {
delete(List.of(id)); delete0(List.of(id));
} }
@Override @Override
@@ -191,6 +191,9 @@ public class JpaSoftwareModuleManagement implements SoftwareModuleManagement {
@Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, @Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX,
backoff = @Backoff(delay = Constants.TX_RT_DELAY)) backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public void delete(final Collection<Long> ids) { public void delete(final Collection<Long> ids) {
delete0(ids);
}
private void delete0(final Collection<Long> ids) {
final List<JpaSoftwareModule> swModulesToDelete = softwareModuleRepository.findAllById(ids); final List<JpaSoftwareModule> swModulesToDelete = softwareModuleRepository.findAllById(ids);
if (swModulesToDelete.size() < ids.size()) { if (swModulesToDelete.size() < ids.size()) {
throw new EntityNotFoundException(SoftwareModule.class, ids, throw new EntityNotFoundException(SoftwareModule.class, ids,
@@ -283,7 +286,7 @@ public class JpaSoftwareModuleManagement implements SoftwareModuleManagement {
// touch to update revision and last modified timestamp // touch to update revision and last modified timestamp
JpaManagementHelper.touch(entityManager, softwareModuleRepository, (JpaSoftwareModule) get(id) JpaManagementHelper.touch(entityManager, softwareModuleRepository, (JpaSoftwareModule) get(id)
.orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, id))); .orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, id)));
return createJpaMetadataCreateStream(create).map(this::saveMetadata).collect(Collectors.toList()); return createJpaMetadataCreateStream(create).map(this::saveMetadata).toList();
} else { } else {
// group by software module id to minimize database access // group by software module id to minimize database access
final Map<Long, List<JpaSoftwareModuleMetadataCreate>> groups = createJpaMetadataCreateStream(create) final Map<Long, List<JpaSoftwareModuleMetadataCreate>> groups = createJpaMetadataCreateStream(create)
@@ -298,7 +301,7 @@ public class JpaSoftwareModuleManagement implements SoftwareModuleManagement {
JpaManagementHelper.touch(entityManager, softwareModuleRepository, (JpaSoftwareModule) get(id) JpaManagementHelper.touch(entityManager, softwareModuleRepository, (JpaSoftwareModule) get(id)
.orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, id))); .orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, id)));
return group.stream().map(this::saveMetadata); return group.stream().map(this::saveMetadata);
}).collect(Collectors.toList()); }).toList();
} }
} }
@@ -346,11 +349,10 @@ public class JpaSoftwareModuleManagement implements SoftwareModuleManagement {
@Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, @Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX,
backoff = @Backoff(delay = Constants.TX_RT_DELAY)) backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public void deleteMetaData(final long id, final String key) { public void deleteMetaData(final long id, final String key) {
final JpaSoftwareModuleMetadata metadata = (JpaSoftwareModuleMetadata) findMetaDataBySoftwareModuleId(id, final JpaSoftwareModuleMetadata metadata = (JpaSoftwareModuleMetadata) findMetaDataBySoftwareModuleId0(id, key)
key).orElseThrow(() -> new EntityNotFoundException(SoftwareModuleMetadata.class, id, key)); .orElseThrow(() -> new EntityNotFoundException(SoftwareModuleMetadata.class, id, key));
JpaManagementHelper.touch(entityManager, softwareModuleRepository, JpaManagementHelper.touch(entityManager, softwareModuleRepository, metadata.getSoftwareModule());
(JpaSoftwareModule) metadata.getSoftwareModule());
softwareModuleMetadataRepository.deleteById(metadata.getId()); softwareModuleMetadataRepository.deleteById(metadata.getId());
} }
@@ -427,6 +429,9 @@ public class JpaSoftwareModuleManagement implements SoftwareModuleManagement {
@Override @Override
public Optional<SoftwareModuleMetadata> findMetaDataBySoftwareModuleId(final long id, final String key) { public Optional<SoftwareModuleMetadata> findMetaDataBySoftwareModuleId(final long id, final String key) {
return findMetaDataBySoftwareModuleId0(id, key);
}
private Optional<SoftwareModuleMetadata> findMetaDataBySoftwareModuleId0(final long id, final String key) {
assertSoftwareModuleExists(id); assertSoftwareModuleExists(id);
return softwareModuleMetadataRepository.findById(new SwMetadataCompositeKey(id, key)) return softwareModuleMetadataRepository.findById(new SwMetadataCompositeKey(id, key))
@@ -510,7 +515,7 @@ public class JpaSoftwareModuleManagement implements SoftwareModuleManagement {
accessController.assertOperationAllowed(AccessController.Operation.DELETE, swModule)); accessController.assertOperationAllowed(AccessController.Operation.DELETE, swModule));
final Set<String> sha1Hashes = swModule.getArtifacts().stream().map(Artifact::getSha1Hash).collect(Collectors.toSet()); final Set<String> sha1Hashes = swModule.getArtifacts().stream().map(Artifact::getSha1Hash).collect(Collectors.toSet());
AfterTransactionCommitExecutorHolder.getInstance().getAfterCommit().afterCommit(() -> AfterTransactionCommitExecutorHolder.getInstance().getAfterCommit().afterCommit(() ->
sha1Hashes.forEach(sha1Hash -> ((JpaArtifactManagement) artifactManagement).clearArtifactBinary(sha1Hash))); sha1Hashes.forEach(((JpaArtifactManagement) artifactManagement)::clearArtifactBinary));
} }
private Specification<JpaSoftwareModule> buildSmSearchQuerySpec(final String searchText) { private Specification<JpaSoftwareModule> buildSmSearchQuerySpec(final String searchText) {

View File

@@ -176,6 +176,9 @@ public class JpaSystemManagement implements CurrentTenantCacheKeyGenerator, Syst
// Exception squid:S2229 - calling findTenants without transaction is intended in this case // Exception squid:S2229 - calling findTenants without transaction is intended in this case
@SuppressWarnings("squid:S2229") @SuppressWarnings("squid:S2229")
public void forEachTenant(final Consumer<String> consumer) { public void forEachTenant(final Consumer<String> consumer) {
forEachTenant0(consumer);
}
private void forEachTenant0(final Consumer<String> consumer) {
Page<String> tenants; Page<String> tenants;
Pageable query = PageRequest.of(0, MAX_TENANTS_QUERY); Pageable query = PageRequest.of(0, MAX_TENANTS_QUERY);
do { do {
@@ -281,7 +284,7 @@ public class JpaSystemManagement implements CurrentTenantCacheKeyGenerator, Syst
} }
private void usageStatsPerTenant(final SystemUsageReportWithTenants report) { private void usageStatsPerTenant(final SystemUsageReportWithTenants report) {
forEachTenant(tenant -> report.addTenantData(systemStatsManagement.getStatsOfTenant())); forEachTenant0(tenant -> report.addTenantData(systemStatsManagement.getStatsOfTenant()));
} }
private DistributionSetType createStandardSoftwareDataSetup() { private DistributionSetType createStandardSoftwareDataSetup() {

View File

@@ -606,9 +606,8 @@ public class JpaTargetManagement implements TargetManagement {
public Target assignType(final String controllerId, final Long targetTypeId) { public Target assignType(final String controllerId, final Long targetTypeId) {
final JpaTarget target = getByControllerIdAndThrowIfNotFound(controllerId); final JpaTarget target = getByControllerIdAndThrowIfNotFound(controllerId);
targetRepository.getAccessController().ifPresent(acm -> { targetRepository.getAccessController().ifPresent(acm ->
acm.assertOperationAllowed(AccessController.Operation.UPDATE, target); acm.assertOperationAllowed(AccessController.Operation.UPDATE, target));
});
final JpaTargetType targetType = getTargetTypeByIdAndThrowIfNotFound(targetTypeId); final JpaTargetType targetType = getTargetTypeByIdAndThrowIfNotFound(targetTypeId);
target.setTargetType(targetType); target.setTargetType(targetType);

View File

@@ -286,7 +286,7 @@ public class JpaTenantConfigurationManagement implements TenantConfigurationMana
@SuppressWarnings("squid:S1172") @SuppressWarnings("squid:S1172")
private void assertAutoCloseValueChange(final String key, final JpaTenantConfiguration valueChange) { private void assertAutoCloseValueChange(final String key, final JpaTenantConfiguration valueChange) {
if (REPOSITORY_ACTIONS_AUTOCLOSE_ENABLED.equals(key) if (REPOSITORY_ACTIONS_AUTOCLOSE_ENABLED.equals(key)
&& getConfigurationValue(MULTI_ASSIGNMENTS_ENABLED, Boolean.class).getValue()) { && Boolean.TRUE.equals(getConfigurationValue(MULTI_ASSIGNMENTS_ENABLED, Boolean.class).getValue())) {
log.debug( log.debug(
"The property '{}' must not be changed because the Multi-Assignments feature is currently enabled.", "The property '{}' must not be changed because the Multi-Assignments feature is currently enabled.",
key); key);

View File

@@ -43,6 +43,7 @@ import org.eclipse.hawkbit.repository.model.helper.EventPublisherHolder;
@Table(name = "sp_target_type", indexes = { @Table(name = "sp_target_type", indexes = {
@Index(name = "sp_idx_target_type_prim", columnList = "tenant,id") }, uniqueConstraints = { @Index(name = "sp_idx_target_type_prim", columnList = "tenant,id") }, uniqueConstraints = {
@UniqueConstraint(columnNames = { "name", "tenant" }, name = "uk_target_type_name") }) @UniqueConstraint(columnNames = { "name", "tenant" }, name = "uk_target_type_name") })
@SuppressWarnings("java:S2160") // the super class equals/hashcode shall be used
public class JpaTargetType extends AbstractJpaTypeEntity implements TargetType, EventAwareEntity { public class JpaTargetType extends AbstractJpaTypeEntity implements TargetType, EventAwareEntity {
@Serial @Serial

View File

@@ -11,19 +11,11 @@ package org.eclipse.hawkbit.repository.jpa.repository;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.function.Function;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;
import org.eclipse.hawkbit.repository.model.BaseEntity;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.repository.query.FluentQuery;
import org.springframework.lang.Nullable; import org.springframework.lang.Nullable;
/** /**

View File

@@ -32,7 +32,7 @@ import org.springframework.test.context.TestPropertySource;
@TestPropertySource(locations = "classpath:/jpa-test.properties", properties = { @TestPropertySource(locations = "classpath:/jpa-test.properties", properties = {
"hawkbit.server.repository.eagerPollPersistence=false", "hawkbit.server.repository.eagerPollPersistence=false",
"hawkbit.server.repository.pollPersistenceFlushTime=1000" }) "hawkbit.server.repository.pollPersistenceFlushTime=1000" })
public class LazyControllerManagementTest extends AbstractJpaIntegrationTest { class LazyControllerManagementTest extends AbstractJpaIntegrationTest {
@Autowired @Autowired
private RepositoryProperties repositoryProperties; private RepositoryProperties repositoryProperties;
@@ -42,7 +42,7 @@ public class LazyControllerManagementTest extends AbstractJpaIntegrationTest {
@ExpectEvents({ @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1), @Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetPollEvent.class, count = 2) }) @Expect(type = TargetPollEvent.class, count = 2) })
public void lazyFindOrRegisterTargetIfItDoesNotExist() throws InterruptedException { void lazyFindOrRegisterTargetIfItDoesNotExist() throws InterruptedException {
final Target target = controllerManagement.findOrRegisterTargetIfItDoesNotExist("AA", LOCALHOST); final Target target = controllerManagement.findOrRegisterTargetIfItDoesNotExist("AA", LOCALHOST);
assertThat(target).as("target should not be null").isNotNull(); assertThat(target).as("target should not be null").isNotNull();

View File

@@ -36,13 +36,13 @@ import org.springframework.orm.jpa.vendor.Database;
@Feature("Component Tests - Repository") @Feature("Component Tests - Repository")
@Story("RSQL filter distribution set") @Story("RSQL filter distribution set")
public class RSQLDistributionSetFieldTest extends AbstractJpaIntegrationTest { class RSQLDistributionSetFieldTest extends AbstractJpaIntegrationTest {
private DistributionSet ds; private DistributionSet ds;
private SoftwareModule sm; private SoftwareModule sm;
@BeforeEach @BeforeEach
public void setupBeforeTest() { void setupBeforeTest() {
sm = testdataFactory.createSoftwareModuleApp("SM"); sm = testdataFactory.createSoftwareModuleApp("SM");
@@ -70,7 +70,7 @@ public class RSQLDistributionSetFieldTest extends AbstractJpaIntegrationTest {
@Test @Test
@Description("Test filter distribution set by id") @Description("Test filter distribution set by id")
public void testFilterByParameterId() { void testFilterByParameterId() {
assertRSQLQuery(DistributionSetFields.ID.name() + "==" + ds.getId(), 1); assertRSQLQuery(DistributionSetFields.ID.name() + "==" + ds.getId(), 1);
assertRSQLQuery(DistributionSetFields.ID.name() + "!=" + ds.getId(), 4); assertRSQLQuery(DistributionSetFields.ID.name() + "!=" + ds.getId(), 4);
assertRSQLQuery(DistributionSetFields.ID.name() + "==" + -1, 0); assertRSQLQuery(DistributionSetFields.ID.name() + "==" + -1, 0);
@@ -87,7 +87,7 @@ public class RSQLDistributionSetFieldTest extends AbstractJpaIntegrationTest {
@Test @Test
@Description("Test filter distribution set by name") @Description("Test filter distribution set by name")
public void testFilterByParameterName() { void testFilterByParameterName() {
assertRSQLQuery(DistributionSetFields.NAME.name() + "==DS", 1); assertRSQLQuery(DistributionSetFields.NAME.name() + "==DS", 1);
assertRSQLQuery(DistributionSetFields.NAME.name() + "!=DS", 4); assertRSQLQuery(DistributionSetFields.NAME.name() + "!=DS", 4);
assertRSQLQuery(DistributionSetFields.NAME.name() + "==*DS", 4); assertRSQLQuery(DistributionSetFields.NAME.name() + "==*DS", 4);
@@ -98,7 +98,7 @@ public class RSQLDistributionSetFieldTest extends AbstractJpaIntegrationTest {
@Test @Test
@Description("Test filter distribution set by assigned software module") @Description("Test filter distribution set by assigned software module")
public void testFilterBySoftwareModule() { void testFilterBySoftwareModule() {
assertRSQLQuery(DistributionSetFields.MODULE.name() + "." + SoftwareModuleFields.NAME.name() + "==" + sm.getName(), 1); assertRSQLQuery(DistributionSetFields.MODULE.name() + "." + SoftwareModuleFields.NAME.name() + "==" + sm.getName(), 1);
assertRSQLQuery(DistributionSetFields.MODULE.name() + "." + SoftwareModuleFields.ID.name() + "==" + sm.getId(), 1); assertRSQLQuery(DistributionSetFields.MODULE.name() + "." + SoftwareModuleFields.ID.name() + "==" + sm.getId(), 1);
assertRSQLQuery(DistributionSetFields.MODULE.name() + "." + SoftwareModuleFields.NAME.name() + "==noExist", 0); assertRSQLQuery(DistributionSetFields.MODULE.name() + "." + SoftwareModuleFields.NAME.name() + "==noExist", 0);
@@ -108,7 +108,7 @@ public class RSQLDistributionSetFieldTest extends AbstractJpaIntegrationTest {
@Test @Test
@Description("Test filter distribution set by description") @Description("Test filter distribution set by description")
public void testFilterByParameterDescription() { void testFilterByParameterDescription() {
assertRSQLQuery(DistributionSetFields.DESCRIPTION.name() + "==''", 1); assertRSQLQuery(DistributionSetFields.DESCRIPTION.name() + "==''", 1);
assertRSQLQuery(DistributionSetFields.DESCRIPTION.name() + "!=''", 4); assertRSQLQuery(DistributionSetFields.DESCRIPTION.name() + "!=''", 4);
assertRSQLQuery(DistributionSetFields.DESCRIPTION.name() + "==DS", 1); assertRSQLQuery(DistributionSetFields.DESCRIPTION.name() + "==DS", 1);
@@ -123,7 +123,7 @@ public class RSQLDistributionSetFieldTest extends AbstractJpaIntegrationTest {
@Test @Test
@Description("Test filter distribution set by version") @Description("Test filter distribution set by version")
public void testFilterByParameterVersion() { void testFilterByParameterVersion() {
assertRSQLQuery(DistributionSetFields.VERSION.name() + "==" + TestdataFactory.DEFAULT_VERSION, 1); assertRSQLQuery(DistributionSetFields.VERSION.name() + "==" + TestdataFactory.DEFAULT_VERSION, 1);
assertRSQLQuery(DistributionSetFields.VERSION.name() + "!=" + TestdataFactory.DEFAULT_VERSION, 4); assertRSQLQuery(DistributionSetFields.VERSION.name() + "!=" + TestdataFactory.DEFAULT_VERSION, 4);
assertRSQLQuery(DistributionSetFields.VERSION.name() + "=in=(" + TestdataFactory.DEFAULT_VERSION + ",1.0.0,1.0.1)", 3); assertRSQLQuery(DistributionSetFields.VERSION.name() + "=in=(" + TestdataFactory.DEFAULT_VERSION + ",1.0.0,1.0.1)", 3);
@@ -132,7 +132,7 @@ public class RSQLDistributionSetFieldTest extends AbstractJpaIntegrationTest {
@Test @Test
@Description("Test filter distribution set by complete property") @Description("Test filter distribution set by complete property")
public void testFilterByAttributeComplete() { void testFilterByAttributeComplete() {
assertRSQLQuery(DistributionSetFields.COMPLETE.name() + "==true", 3); assertRSQLQuery(DistributionSetFields.COMPLETE.name() + "==true", 3);
try { try {
assertRSQLQuery(DistributionSetFields.COMPLETE.name() + "==noExist*", 0); assertRSQLQuery(DistributionSetFields.COMPLETE.name() + "==noExist*", 0);
@@ -145,7 +145,7 @@ public class RSQLDistributionSetFieldTest extends AbstractJpaIntegrationTest {
@Test @Test
@Description("Test filter distribution set by valid property") @Description("Test filter distribution set by valid property")
public void testFilterByAttributeValid() { void testFilterByAttributeValid() {
assertRSQLQuery(DistributionSetFields.VALID.name() + "==true", 4); assertRSQLQuery(DistributionSetFields.VALID.name() + "==true", 4);
assertRSQLQuery(DistributionSetFields.VALID.name() + "==false", 1); assertRSQLQuery(DistributionSetFields.VALID.name() + "==false", 1);
assertThatExceptionOfType(RSQLParameterSyntaxException.class) assertThatExceptionOfType(RSQLParameterSyntaxException.class)
@@ -156,7 +156,7 @@ public class RSQLDistributionSetFieldTest extends AbstractJpaIntegrationTest {
@Test @Test
@Description("Test filter distribution set by tag name") @Description("Test filter distribution set by tag name")
public void testFilterByTag() { void testFilterByTag() {
assertRSQLQuery(DistributionSetFields.TAG.name() + "==Tag1", 2); assertRSQLQuery(DistributionSetFields.TAG.name() + "==Tag1", 2);
assertRSQLQuery(DistributionSetFields.TAG.name() + "!=Tag1", 3); assertRSQLQuery(DistributionSetFields.TAG.name() + "!=Tag1", 3);
assertRSQLQuery(DistributionSetFields.TAG.name() + "==T*", 2); assertRSQLQuery(DistributionSetFields.TAG.name() + "==T*", 2);
@@ -167,7 +167,7 @@ public class RSQLDistributionSetFieldTest extends AbstractJpaIntegrationTest {
@Test @Test
@Description("Test filter distribution set by type key") @Description("Test filter distribution set by type key")
public void testFilterByType() { void testFilterByType() {
assertRSQLQuery(DistributionSetFields.TYPE.name() + "==" + TestdataFactory.DS_TYPE_DEFAULT, 4); assertRSQLQuery(DistributionSetFields.TYPE.name() + "==" + TestdataFactory.DS_TYPE_DEFAULT, 4);
assertRSQLQuery(DistributionSetFields.TYPE.name() + "==noExist*", 0); assertRSQLQuery(DistributionSetFields.TYPE.name() + "==noExist*", 0);
assertRSQLQuery(DistributionSetFields.TYPE.name() + "=in=(" + TestdataFactory.DS_TYPE_DEFAULT + ",ecl)", 4); assertRSQLQuery(DistributionSetFields.TYPE.name() + "=in=(" + TestdataFactory.DS_TYPE_DEFAULT + ",ecl)", 4);
@@ -176,7 +176,7 @@ public class RSQLDistributionSetFieldTest extends AbstractJpaIntegrationTest {
@Test @Test
@Description("Test filter distribution set by metadata") @Description("Test filter distribution set by metadata")
public void testFilterByMetadata() { void testFilterByMetadata() {
createDistributionSetWithMetadata("key.dot", "value.dot"); createDistributionSetWithMetadata("key.dot", "value.dot");
assertRSQLQuery(DistributionSetFields.METADATA.name() + ".metaKey==metaValue", 1); assertRSQLQuery(DistributionSetFields.METADATA.name() + ".metaKey==metaValue", 1);

View File

@@ -59,17 +59,17 @@ public class MgmtApi {
hawkbitClient.mgmtService(MgmtTenantManagementRestApi.class, tenant); hawkbitClient.mgmtService(MgmtTenantManagementRestApi.class, tenant);
final String gatewayToken = tenant.getGatewayToken(); final String gatewayToken = tenant.getGatewayToken();
if (ObjectUtils.isEmpty(gatewayToken)) { if (ObjectUtils.isEmpty(gatewayToken)) {
if (!((Boolean) Objects.requireNonNull(mgmtTenantManagementRestApi if (!(Boolean.TRUE.equals(Objects.requireNonNull(mgmtTenantManagementRestApi
.getTenantConfigurationValue(AUTHENTICATION_MODE_TARGET_SECURITY_TOKEN_ENABLED) .getTenantConfigurationValue(AUTHENTICATION_MODE_TARGET_SECURITY_TOKEN_ENABLED)
.getBody()).getValue())) { .getBody()).getValue()))) {
mgmtTenantManagementRestApi.updateTenantConfiguration( mgmtTenantManagementRestApi.updateTenantConfiguration(
Map.of(AUTHENTICATION_MODE_TARGET_SECURITY_TOKEN_ENABLED, true) Map.of(AUTHENTICATION_MODE_TARGET_SECURITY_TOKEN_ENABLED, true)
); );
} }
} else { } else {
if (!((Boolean) Objects.requireNonNull(mgmtTenantManagementRestApi if (!(Boolean.TRUE.equals(Objects.requireNonNull(mgmtTenantManagementRestApi
.getTenantConfigurationValue(AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_ENABLED) .getTenantConfigurationValue(AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_ENABLED)
.getBody()).getValue())) { .getBody()).getValue()))) {
mgmtTenantManagementRestApi.updateTenantConfiguration( mgmtTenantManagementRestApi.updateTenantConfiguration(
Map.of(AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_ENABLED, true) Map.of(AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_ENABLED, true)
); );

View File

@@ -33,8 +33,8 @@ import org.springframework.web.filter.OncePerRequestFilter;
@NoArgsConstructor(access = AccessLevel.PRIVATE) @NoArgsConstructor(access = AccessLevel.PRIVATE)
public class MdcHandler { public class MdcHandler {
public static String MDC_KEY_TENANT = "tenant"; public static final String MDC_KEY_TENANT = "tenant";
public static String MDC_KEY_USER = "user"; public static final String MDC_KEY_USER = "user";
private static final MdcHandler SINGLETON = new MdcHandler(); private static final MdcHandler SINGLETON = new MdcHandler();