Sonar Fixes (7) (#2215)

Signed-off-by: Avgustin Marinov <Avgustin.Marinov@bosch.com>
This commit is contained in:
Avgustin Marinov
2025-01-21 16:40:16 +02:00
committed by GitHub
parent bbb5f40207
commit f09db20b71
15 changed files with 77 additions and 60 deletions

View File

@@ -198,11 +198,12 @@ public class RolloutStatusCache {
cacheManager.evictCaches(tenant);
}
private Map<Long, List<TotalTargetCountActionStatus>> retrieveFromCache(final List<Long> ids,
private @NotNull Map<Long, List<TotalTargetCountActionStatus>> retrieveFromCache(final List<Long> ids,
@NotNull final Cache cache) {
return ids.stream().map(id -> cache.get(id, CachedTotalTargetCountActionStatus.class)).filter(Objects::nonNull)
.collect(Collectors.toMap(CachedTotalTargetCountActionStatus::getId,
CachedTotalTargetCountActionStatus::getStatus));
return ids.stream()
.map(id -> cache.get(id, CachedTotalTargetCountActionStatus.class))
.filter(Objects::nonNull)
.collect(Collectors.toMap(CachedTotalTargetCountActionStatus::getId, CachedTotalTargetCountActionStatus::getStatus));
}
private List<TotalTargetCountActionStatus> retrieveFromCache(final Long id, @NotNull final Cache cache) {

View File

@@ -30,7 +30,6 @@ import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetMetadata;
import org.eclipse.hawkbit.repository.jpa.model.JpaTargetMetadata;
import org.eclipse.hawkbit.repository.model.MetaData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
/**
@@ -68,12 +67,12 @@ public class JpaEntityFactory implements EntityFactory {
@Override
public MetaData generateDsMetadata(final String key, final String value) {
return new JpaDistributionSetMetadata(key, StringUtils.trimWhitespace(value));
return new JpaDistributionSetMetadata(key, value == null ? null : value.strip());
}
@Override
public MetaData generateTargetMetadata(final String key, final String value) {
return new JpaTargetMetadata(key, StringUtils.trimWhitespace(value));
return new JpaTargetMetadata(key, value == null ? null : value.strip());
}
@Override

View File

@@ -106,7 +106,7 @@ public final class JpaManagementHelper {
: (filterString + "%");
final String filterVersion = semicolonIndex != -1 ? (filterString.substring(semicolonIndex + 1) + "%") : "%";
return new String[] { !StringUtils.isEmpty(filterName) ? filterName : "%", filterVersion };
return new String[] { ObjectUtils.isEmpty(filterName) ? "%" : filterName, filterVersion };
}
}

View File

@@ -317,9 +317,7 @@ public class JpaRolloutExecutor implements RolloutExecutor {
rollout.setStatus(RolloutStatus.FINISHED);
rolloutRepository.save(rollout);
final List<Long> groupIds = rollout.getRolloutGroups().stream().map(RolloutGroup::getId)
.collect(Collectors.toList());
final List<Long> groupIds = rollout.getRolloutGroups().stream().map(RolloutGroup::getId).toList();
afterCommit.afterCommit(() -> eventPublisherHolder.getEventPublisher().publishEvent(new RolloutStoppedEvent(
tenantAware.getCurrentTenant(), eventPublisherHolder.getApplicationId(), rollout.getId(), groupIds)));
}

View File

@@ -99,7 +99,7 @@ public class JpaRolloutHandler implements RolloutHandler {
private void handleRolloutInNewTransaction(final long rolloutId, final String handlerId) {
DeploymentHelper.runInNewTransaction(txManager, handlerId + "-" + rolloutId, status -> {
rolloutManagement.get(rolloutId).ifPresentOrElse(
rollout -> {
rollout ->
// auditor is retrieved and set on transaction commit
// if not overridden, the system user will be the auditor
rollout.getAccessControlContext().ifPresentOrElse(
@@ -113,9 +113,7 @@ public class JpaRolloutHandler implements RolloutHandler {
rollout.getCreatedBy(), () -> {
rolloutExecutor.execute(rollout);
return null;
})
);
},
})),
() -> log.error("Could not retrieve rollout with id {}. Will not continue with execution.",
rolloutId));
return 0L;

View File

@@ -24,8 +24,6 @@ import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetType;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
/**
* Create/build implementation.
@@ -47,7 +45,7 @@ public class JpaDistributionSetCreate extends AbstractDistributionSetUpdateCreat
@Override
public DistributionSetCreate type(final String type) {
this.type = ObjectUtils.isEmpty(type) ? type : type.strip();
this.type = type == null ? null : type.strip();
return this;
}

View File

@@ -59,7 +59,7 @@ public class JpaRolloutCreate extends AbstractNamedEntityBuilder<RolloutCreate>
* @return this builder
*/
public RolloutCreate targetFilterQuery(final String targetFilterQuery) {
this.targetFilterQuery = StringUtils.trimWhitespace(targetFilterQuery);
this.targetFilterQuery = targetFilterQuery == null ? null : targetFilterQuery.strip();
return this;
}

View File

@@ -332,7 +332,8 @@ public class JpaControllerManagement extends JpaActionManagement implements Cont
}
private Target findOrRegisterTargetIfItDoesNotExist0(final String controllerId, final URI address, final String name, final String type) {
final Specification<JpaTarget> spec = (targetRoot, query, cb) -> cb.equal(targetRoot.get(JpaTarget_.controllerId), controllerId);
return targetRepository.findOne(spec).map(target -> updateTarget(target, address, name, type))
return targetRepository.findOne(spec)
.map(target -> updateTarget(target, address, name, type))
.orElseGet(() -> createTarget(controllerId, address, name, type));
}

View File

@@ -195,13 +195,18 @@ public class JpaDeploymentManagement extends JpaActionManagement implements Depl
@Override
@Transactional(isolation = Isolation.READ_COMMITTED)
public List<DistributionSetAssignmentResult> assignDistributionSets(final List<DeploymentRequest> deploymentRequests) {
return assignDistributionSets(tenantAware.getCurrentUsername(), deploymentRequests, null);
return assignDistributionSets0(tenantAware.getCurrentUsername(), deploymentRequests, null);
}
@Override
@Transactional(isolation = Isolation.READ_COMMITTED)
public List<DistributionSetAssignmentResult> assignDistributionSets(
final String initiatedBy, final List<DeploymentRequest> deploymentRequests, final String actionMessage) {
return assignDistributionSets0(initiatedBy, deploymentRequests, actionMessage);
}
private List<DistributionSetAssignmentResult> assignDistributionSets0(
final String initiatedBy, final List<DeploymentRequest> deploymentRequests, final String actionMessage) {
WeightValidationHelper.usingContext(systemSecurityContext, tenantConfigurationManagement).validate(deploymentRequests);
return assignDistributionSets(initiatedBy, deploymentRequests, actionMessage, onlineDsAssignmentStrategy);
}
@@ -232,6 +237,10 @@ public class JpaDeploymentManagement extends JpaActionManagement implements Depl
@Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX,
backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public Action cancelAction(final long actionId) {
return cancelAction0(actionId);
}
private Action cancelAction0(final long actionId) {
log.debug("cancelAction({})", actionId);
final JpaAction action = actionRepository.findById(actionId)
@@ -393,6 +402,10 @@ public class JpaDeploymentManagement extends JpaActionManagement implements Depl
@Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX,
backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public Action forceQuitAction(final long actionId) {
return forceQuitAction0(actionId);
}
private Action forceQuitAction0(final long actionId) {
final JpaAction action = actionRepository.findById(actionId)
.orElseThrow(() -> new EntityNotFoundException(Action.class, actionId));
@@ -495,12 +508,14 @@ public class JpaDeploymentManagement extends JpaActionManagement implements Depl
@Override
public Optional<DistributionSet> getAssignedDistributionSet(final String controllerId) {
return targetRepository.findWithDetailsByControllerId(controllerId, JpaTarget_.GRAPH_TARGET_ASSIGNED_DISTRIBUTION_SET).map(JpaTarget::getAssignedDistributionSet);
return targetRepository.findWithDetailsByControllerId(controllerId, JpaTarget_.GRAPH_TARGET_ASSIGNED_DISTRIBUTION_SET)
.map(JpaTarget::getAssignedDistributionSet);
}
@Override
public Optional<DistributionSet> getInstalledDistributionSet(final String controllerId) {
return targetRepository.findWithDetailsByControllerId(controllerId, JpaTarget_.GRAPH_TARGET_INSTALLED_DISTRIBUTION_SET).map(JpaTarget::getInstalledDistributionSet);
return targetRepository.findWithDetailsByControllerId(controllerId, JpaTarget_.GRAPH_TARGET_INSTALLED_DISTRIBUTION_SET)
.map(JpaTarget::getInstalledDistributionSet);
}
@Override
@@ -542,7 +557,7 @@ public class JpaDeploymentManagement extends JpaActionManagement implements Depl
.forEach(action -> {
try {
assertTargetUpdateAllowed(action);
cancelAction(action.getId());
cancelAction0(action.getId());
log.debug("Action {} canceled", action.getId());
} catch (final InsufficientPermissionException e) {
log.trace("Could not cancel action {} due to insufficient permissions.", action.getId(), e);
@@ -555,7 +570,7 @@ public class JpaDeploymentManagement extends JpaActionManagement implements Depl
.forEach(action -> {
try {
assertTargetUpdateAllowed(action);
forceQuitAction(action.getId());
forceQuitAction0(action.getId());
log.debug("Action {} force canceled (force)", action.getId());
} catch (final InsufficientPermissionException e) {
log.trace("Could not cancel action {} due to insufficient permissions.", action.getId(), e);
@@ -588,7 +603,7 @@ public class JpaDeploymentManagement extends JpaActionManagement implements Depl
* statements
*/
private static List<List<Long>> getTargetEntitiesAsChunks(final List<JpaTarget> targetEntities) {
return ListUtils.partition(targetEntities.stream().map(Target::getId).collect(Collectors.toList()), Constants.MAX_ENTRIES_IN_STATEMENT);
return ListUtils.partition(targetEntities.stream().map(Target::getId).toList(), Constants.MAX_ENTRIES_IN_STATEMENT);
}
private static DistributionSetAssignmentResult buildAssignmentResult(
@@ -855,8 +870,7 @@ public class JpaDeploymentManagement extends JpaActionManagement implements Depl
quota, Action.class, Target.class, actionRepository::countByTargetControllerId));
}
private void closeOrCancelActiveActions(final AbstractDsAssignmentStrategy assignmentStrategy,
final List<List<Long>> targetIdsChunks) {
private void closeOrCancelActiveActions(final AbstractDsAssignmentStrategy assignmentStrategy, final List<List<Long>> targetIdsChunks) {
if (isActionsAutocloseEnabled()) {
assignmentStrategy.closeActiveActions(targetIdsChunks);
} else {
@@ -864,7 +878,8 @@ public class JpaDeploymentManagement extends JpaActionManagement implements Depl
}
}
private void setAssignedDistributionSetAndTargetUpdateStatus(final AbstractDsAssignmentStrategy assignmentStrategy,
private void setAssignedDistributionSetAndTargetUpdateStatus(
final AbstractDsAssignmentStrategy assignmentStrategy,
final JpaDistributionSet set, final List<List<Long>> targetIdsChunks) {
final String currentUser = auditorProvider.getCurrentAuditor().orElse(null);
assignmentStrategy.setAssignedDistributionSetAndTargetStatus(set, targetIdsChunks, currentUser);
@@ -970,8 +985,7 @@ public class JpaDeploymentManagement extends JpaActionManagement implements Depl
}
private void closeOrCancelOpenDeviceActions(final List<JpaAction> actions) {
final List<Long> targetIds = actions.stream().map(JpaAction::getTarget).map(Target::getId)
.collect(Collectors.toList());
final List<Long> targetIds = actions.stream().map(JpaAction::getTarget).map(Target::getId).toList();
if (isActionsAutocloseEnabled()) {
onlineDsAssignmentStrategy.closeObsoleteUpdateActions(targetIds);
} else {
@@ -999,7 +1013,7 @@ public class JpaDeploymentManagement extends JpaActionManagement implements Depl
mergedTarget.setAssignedDistributionSet((JpaDistributionSet) savedAction.getDistributionSet());
mergedTarget.setUpdateStatus(TargetUpdateStatus.PENDING);
return mergedTarget;
}).collect(Collectors.toList());
}).toList();
targetRepository.saveAll(assignedDsTargets);
}
@@ -1041,12 +1055,12 @@ public class JpaDeploymentManagement extends JpaActionManagement implements Depl
}
private JpaAction assertTargetUpdateAllowed(final JpaAction action) {
targetRepository.findOne(TargetSpecifications.hasId(action.getTarget().getId())).ifPresentOrElse(target -> {
targetRepository.getAccessController()
.ifPresent(acm -> acm.assertOperationAllowed(AccessController.Operation.UPDATE, target));
}, () -> {
throw new EntityNotFoundException(Action.class, action);
});
targetRepository.findOne(TargetSpecifications.hasId(action.getTarget().getId())).ifPresentOrElse(
target -> targetRepository.getAccessController()
.ifPresent(acm -> acm.assertOperationAllowed(AccessController.Operation.UPDATE, target)),
() -> {
throw new EntityNotFoundException(Action.class, action);
});
return action;
}

View File

@@ -210,7 +210,7 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
@Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX,
backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public void delete(final long id) {
delete(List.of(id));
delete0(List.of(id));
}
@Override
@@ -218,6 +218,9 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
@Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX,
backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public void delete(final Collection<Long> distributionSetIDs) {
delete0(distributionSetIDs);
}
private void delete0(final Collection<Long> distributionSetIDs) {
getDistributionSets(distributionSetIDs); // throws EntityNotFoundException if any of these do not exists
final List<JpaDistributionSet> setsFound = distributionSetRepository.findAll(
AccessController.Operation.DELETE, distributionSetRepository.byIdsSpec(distributionSetIDs));
@@ -418,8 +421,7 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
// touch it to update the lock revision because we are modifying the
// DS indirectly, it will, also check UPDATE access
JpaManagementHelper.touch(entityManager, distributionSetRepository,
(JpaDistributionSet) metadata.getDistributionSet());
JpaManagementHelper.touch(entityManager, distributionSetRepository, metadata.getDistributionSet());
distributionSetMetadataRepository.deleteById(metadata.getId());
}

View File

@@ -124,8 +124,9 @@ public class JpaDistributionSetTagManagement implements DistributionSetTagManage
final List<JpaDistributionSetTag> setsFound = distributionSetTagRepository.findAllById(ids);
if (setsFound.size() < ids.size()) {
throw new EntityNotFoundException(DistributionSetTag.class, ids,
setsFound.stream().map(DistributionSetTag::getId).collect(Collectors.toList()));
throw new EntityNotFoundException(
DistributionSetTag.class, ids,
setsFound.stream().map(DistributionSetTag::getId).toList());
}
distributionSetTagRepository.deleteAll(setsFound);

View File

@@ -184,6 +184,11 @@ public class JpaRolloutManagement implements RolloutManagement {
public Rollout create(
final RolloutCreate rollout, final int amountGroup, final boolean confirmationRequired,
final RolloutGroupConditions conditions, final DynamicRolloutGroupTemplate dynamicRolloutGroupTemplate) {
return create0(rollout, amountGroup, confirmationRequired, conditions, dynamicRolloutGroupTemplate);
}
private Rollout create0(
final RolloutCreate rollout, final int amountGroup, final boolean confirmationRequired,
final RolloutGroupConditions conditions, final DynamicRolloutGroupTemplate dynamicRolloutGroupTemplate) {
if (amountGroup < 0) {
throw new ValidationException("The amount of groups cannot be lower than or equal to zero for static rollouts");
} else if (amountGroup == 0) {
@@ -208,17 +213,17 @@ public class JpaRolloutManagement implements RolloutManagement {
@Transactional
@Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX,
backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public Rollout create(@NotNull @Valid RolloutCreate create, int amountGroup, boolean confirmationRequired,
public Rollout create(
@NotNull @Valid RolloutCreate create, int amountGroup, boolean confirmationRequired,
@NotNull RolloutGroupConditions conditions) {
return create(create, amountGroup, confirmationRequired, conditions, null);
return create0(create, amountGroup, confirmationRequired, conditions, null);
}
@Override
@Transactional
@Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX,
backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public Rollout create(final RolloutCreate rollout, final List<RolloutGroupCreate> groups,
final RolloutGroupConditions conditions) {
public Rollout create(final RolloutCreate rollout, final List<RolloutGroupCreate> groups, final RolloutGroupConditions conditions) {
if (groups.isEmpty()) {
throw new ValidationException("The amount of groups cannot be 0");
}
@@ -353,7 +358,7 @@ public class JpaRolloutManagement implements RolloutManagement {
@Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX,
backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public Rollout approveOrDeny(final long rolloutId, final Rollout.ApprovalDecision decision) {
return this.approveOrDeny(rolloutId, decision, null);
return approveOrDeny0(rolloutId, decision, null);
}
@Override
@@ -361,6 +366,9 @@ public class JpaRolloutManagement implements RolloutManagement {
@Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX,
backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public Rollout approveOrDeny(final long rolloutId, final Rollout.ApprovalDecision decision, final String remark) {
return approveOrDeny0(rolloutId, decision, remark);
}
private Rollout approveOrDeny0(final long rolloutId, final Rollout.ApprovalDecision decision, final String remark) {
log.debug("approveOrDeny rollout called for rollout {} with decision {}", rolloutId, decision);
final JpaRollout rollout = getRolloutOrThrowExceptionIfNotFound(rolloutId);
RolloutHelper.verifyRolloutInStatus(rollout, RolloutStatus.WAITING_FOR_APPROVAL);
@@ -474,10 +482,10 @@ public class JpaRolloutManagement implements RolloutManagement {
@Override
public void setRolloutStatusDetails(final Slice<Rollout> rollouts) {
final List<Long> rolloutIds = rollouts.getContent().stream().map(Rollout::getId).collect(Collectors.toList());
final List<Long> rolloutIds = rollouts.getContent().stream().map(Rollout::getId).toList();
final Map<Long, List<TotalTargetCountActionStatus>> allStatesForRollout = getStatusCountItemForRollout(rolloutIds);
if (allStatesForRollout != null) {
if (!allStatesForRollout.isEmpty()) {
rollouts.forEach(rollout -> {
final TotalTargetCountStatus totalTargetCountStatus = new TotalTargetCountStatus(
allStatesForRollout.get(rollout.getId()), rollout.getTotalTargets(), rollout.getActionType());
@@ -703,9 +711,9 @@ public class JpaRolloutManagement implements RolloutManagement {
.orElseThrow(() -> new EntityNotFoundException(Rollout.class, rolloutId));
}
private Map<Long, List<TotalTargetCountActionStatus>> getStatusCountItemForRollout(final List<Long> rollouts) {
private @NotNull Map<Long, List<TotalTargetCountActionStatus>> getStatusCountItemForRollout(final List<Long> rollouts) {
if (rollouts.isEmpty()) {
return null;
return Collections.emptyMap();
}
final Map<Long, List<TotalTargetCountActionStatus>> fromCache = rolloutStatusCache.getRolloutStatus(rollouts);

View File

@@ -124,8 +124,7 @@ public class OnlineDsAssignmentStrategy extends AbstractDsAssignmentStrategy {
}
@Override
public void setAssignedDistributionSetAndTargetStatus(final JpaDistributionSet set, final List<List<Long>> targetIds,
final String currentUser) {
public void setAssignedDistributionSetAndTargetStatus(final JpaDistributionSet set, final List<List<Long>> targetIds, final String currentUser) {
final long now = System.currentTimeMillis();
targetIds.forEach(targetIdsChunk -> {
if (targetRepository.count(AccessController.Operation.UPDATE,
@@ -151,8 +150,7 @@ public class OnlineDsAssignmentStrategy extends AbstractDsAssignmentStrategy {
@Override
public Set<Long> cancelActiveActions(final List<List<Long>> targetIds) {
return targetIds.stream().map(this::overrideObsoleteUpdateActions).flatMap(Collection::stream)
.collect(Collectors.toSet());
return targetIds.stream().map(this::overrideObsoleteUpdateActions).flatMap(Collection::stream).collect(Collectors.toSet());
}
@Override

View File

@@ -14,7 +14,6 @@ import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -376,7 +375,7 @@ public class JpaAction extends AbstractJpaTenantAwareBaseEntity implements Actio
public static class StatusConverter extends MapAttributeConverter<Status, Integer> {
public StatusConverter() {
super(new EnumMap<>(new HashMap<>() {{
super(new HashMap<>() {{
put(Status.FINISHED, 0);
put(Status.ERROR, 1);
put(Status.WARNING, 2);
@@ -389,7 +388,7 @@ public class JpaAction extends AbstractJpaTenantAwareBaseEntity implements Actio
put(Status.CANCEL_REJECTED, 9);
put(Status.DOWNLOADED, 10);
put(Status.WAIT_FOR_CONFIRMATION, 11);
}}), null);
}}, null);
}
}
}

View File

@@ -585,7 +585,7 @@ public class JpaQueryRsqlVisitor<A extends Enum<A> & RsqlQueryField, T> extends
private Predicate in(final Expression<String> expressionToCompare, final List<Object> transformedValues) {
final List<String> inParams = transformedValues.stream().filter(String.class::isInstance)
.map(String.class::cast).map(this::caseWise).collect(Collectors.toList());
.map(String.class::cast).map(this::caseWise).toList();
return inParams.isEmpty() ? expressionToCompare.in(transformedValues) : caseWise(cb, expressionToCompare).in(inParams);
}