Skip to content

Commit

Permalink
Sonar Fixes (6) (#2214)
Browse files Browse the repository at this point in the history
Signed-off-by: Avgustin Marinov <Avgustin.Marinov@bosch.com>
  • Loading branch information
avgustinmm authored Jan 21, 2025
1 parent e8406af commit bbb5f40
Show file tree
Hide file tree
Showing 23 changed files with 95 additions and 109 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,35 +9,10 @@
*/
package org.eclipse.hawkbit.autoconfigure.repository.event;

import java.util.concurrent.Executor;

import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import org.eclipse.hawkbit.event.BusProtoStuffMessageConverter;
import org.eclipse.hawkbit.event.EventPublisherConfiguration;
import org.eclipse.hawkbit.repository.event.ApplicationEventFilter;
import org.eclipse.hawkbit.repository.event.remote.RemoteTenantAwareEvent;
import org.eclipse.hawkbit.repository.model.helper.EventPublisherHolder;
import org.eclipse.hawkbit.security.SystemSecurityContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.bus.BusProperties;
import org.springframework.cloud.bus.ConditionalOnBusEnabled;
import org.springframework.cloud.bus.ServiceMatcher;
import org.springframework.cloud.bus.jackson.RemoteApplicationEventScan;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.core.ResolvableType;
import org.springframework.messaging.converter.MessageConverter;

/**
* Autoconfiguration for the event bus.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ public TaskScheduler taskScheduler() {

private static ThreadFactory threadFactory(final String format) {
final AtomicLong count = new AtomicLong(0);
return (runnable) -> {
return runnable -> {
final Thread thread = Executors.defaultThreadFactory().newThread(runnable);
thread.setName(String.format(Locale.ROOT, format, count.getAndIncrement()));
return thread;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,12 @@
import io.qameta.allure.Description;
import org.junit.jupiter.api.Test;

public class FileNameFieldsTest {
class FileNameFieldsTest {

@Test
@Description("Verifies that fields classes are correctly implemented")
@SuppressWarnings("unchecked")
public void repositoryManagementMethodsArePreAuthorizedAnnotated() {
void repositoryManagementMethodsArePreAuthorizedAnnotated() {
final String packageName = getClass().getPackage().getName();
try (final ScanResult scanResult = new ClassGraph().acceptPackages(packageName).scan()) {
final List<? extends Class<? extends RsqlQueryField>> matchingClasses = scanResult.getAllClasses()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,14 @@

import static org.eclipse.hawkbit.repository.SizeConversionHelper.byteValueToReadableString;

import lombok.EqualsAndHashCode;
import org.eclipse.hawkbit.exception.AbstractServerRtException;
import org.eclipse.hawkbit.exception.SpServerError;

/**
* Thrown if file size quota is exceeded
*/
@EqualsAndHashCode(callSuper = true)
public class FileSizeQuotaExceededException extends AbstractServerRtException {

private static final String MAX_ARTIFACT_SIZE_EXCEEDED = "Maximum artifact size (%s) exceeded.";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,17 @@
import java.util.Collection;
import java.util.Collections;

import lombok.EqualsAndHashCode;
import org.eclipse.hawkbit.exception.AbstractServerRtException;
import org.eclipse.hawkbit.exception.SpServerError;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetType;

/**
* Thrown if user tries to assign a {@link DistributionSet} to a {@link Target}
* that has an incompatible {@link TargetType}
* Thrown if user tries to assign a {@link DistributionSet} to a {@link Target} that has an incompatible {@link TargetType}
*/
@EqualsAndHashCode(callSuper = true)
public class IncompatibleTargetTypeException extends AbstractServerRtException {

@Serial
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,15 @@

import java.io.Serial;

import lombok.EqualsAndHashCode;
import org.eclipse.hawkbit.exception.AbstractServerRtException;
import org.eclipse.hawkbit.exception.SpServerError;

/**
* This exception is indicating that the confirmation feedback cannot be
* processed for a specific actions for different reasons which are listed as
* enum {@link Reason}.
* This exception is indicating that the confirmation feedback cannot be processed for a specific actions for different reasons which are
* listed as enum {@link Reason}.
*/
@EqualsAndHashCode(callSuper = true)
public class InvalidConfirmationFeedbackException extends AbstractServerRtException {

@Serial
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,16 @@

import java.io.Serial;

import lombok.EqualsAndHashCode;
import org.eclipse.hawkbit.exception.AbstractServerRtException;
import org.eclipse.hawkbit.exception.SpServerError;

/**
* This exception is thrown if trying to set a maintenance schedule that is
* invalid. A maintenance schedule is considered to be valid only if schedule,
* duration and timezone are all null, or are all valid; in which case there
* should be at least one valid window after the current time.
* This exception is thrown if trying to set a maintenance schedule that is invalid. A maintenance schedule is considered to be valid only if
* schedule, duration and timezone are all null, or are all valid; in which case there should be at least one valid window after the current
* time.
*/
@EqualsAndHashCode(callSuper = true)
public class InvalidMaintenanceScheduleException extends AbstractServerRtException {

@Serial
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,8 @@ private static SQLException findSqlException(final RuntimeException jpaSystemExc
Throwable exception = jpaSystemException;
do {
final Throwable cause = exception.getCause();
if (cause instanceof SQLException) {
return (SQLException) cause;
if (cause instanceof SQLException sqlException) {
return sqlException;
}
exception = cause;
} while (exception != null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public void postUpdate(final DescriptorEvent event) {
final Object object = event.getObject();
if (((UpdateObjectQuery) event.getQuery()).getObjectChangeSet().getChangedAttributeNames().stream()
.anyMatch(field -> !TARGET_UPDATE_EVENT_IGNORE_FIELDS.contains(field))) {
AbstractJpaBaseEntity.doNotify(() -> ((EventAwareEntity) object).fireUpdateEvent());
AbstractBaseEntity.doNotify(((EventAwareEntity) object)::fireUpdateEvent);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public void onPostUpdate(final PostUpdateEvent event) {
}

if (hasNonIgnoredChanges || !lastTargetQueryChanged) {
AbstractJpaBaseEntity.doNotify(() -> ((EventAwareEntity) event.getEntity()).fireUpdateEvent());
AbstractBaseEntity.doNotify(((EventAwareEntity) event.getEntity())::fireUpdateEvent);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ private ActionStatusCreate createConfirmationActionStatus(final long actionId, f
private List<Action> giveConfirmationForActiveActions(final AutoConfirmationStatus autoConfirmationStatus) {
return findActiveActionsHavingStatus(autoConfirmationStatus.getTarget().getControllerId(), Status.WAIT_FOR_CONFIRMATION).stream()
.map(action -> autoConfirmAction(action, autoConfirmationStatus))
.collect(Collectors.toList());
.toList();
}

private Action autoConfirmAction(final JpaAction action, final AutoConfirmationStatus autoConfirmationStatus) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -321,13 +321,16 @@ public Page<ActionStatus> findActionStatusByAction(final Pageable pageReq, final
@Transactional(isolation = Isolation.READ_COMMITTED)
@Retryable(retryFor = ConcurrencyFailureException.class, noRetryFor = EntityAlreadyExistsException.class, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public Target findOrRegisterTargetIfItDoesNotExist(final String controllerId, final URI address) {
return findOrRegisterTargetIfItDoesNotExist(controllerId, address, null, null);
return findOrRegisterTargetIfItDoesNotExist0(controllerId, address, null, null);
}

@Override
@Transactional(isolation = Isolation.READ_COMMITTED)
@Retryable(retryFor = ConcurrencyFailureException.class, noRetryFor = EntityAlreadyExistsException.class, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public Target findOrRegisterTargetIfItDoesNotExist(final String controllerId, final URI address, final String name, final String type) {
return findOrRegisterTargetIfItDoesNotExist0(controllerId, address, name, type);
}
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))
.orElseGet(() -> createTarget(controllerId, address, name, type));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
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;
Expand Down Expand Up @@ -375,7 +376,7 @@ public ActionTypeConverter() {
public static class StatusConverter extends MapAttributeConverter<Status, Integer> {

public StatusConverter() {
super(new HashMap<>() {{
super(new EnumMap<>(new HashMap<>() {{
put(Status.FINISHED, 0);
put(Status.ERROR, 1);
put(Status.WARNING, 2);
Expand All @@ -388,7 +389,7 @@ public StatusConverter() {
put(Status.CANCEL_REJECTED, 9);
put(Status.DOWNLOADED, 10);
put(Status.WAIT_FOR_CONFIRMATION, 11);
}}, null);
}}), null);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,17 @@
import jakarta.persistence.Table;
import jakarta.validation.constraints.Size;

import lombok.AccessLevel;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.eclipse.hawkbit.repository.model.AutoConfirmationStatus;
import org.eclipse.hawkbit.repository.model.NamedEntity;
import org.eclipse.hawkbit.repository.model.Target;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

@NoArgsConstructor // Default constructor needed for JPA entities.
@EqualsAndHashCode(callSuper = true)
@Getter
@Entity
@Table(name = "sp_target_conf_status")
Expand All @@ -48,8 +50,8 @@ public class JpaAutoConfirmationStatus extends AbstractJpaTenantAwareBaseEntity

public JpaAutoConfirmationStatus(final String initiator, final String remark, final Target target) {
this.target = (JpaTarget) target;
this.initiator = StringUtils.isEmpty(initiator) ? null : initiator;
this.remark = StringUtils.isEmpty(remark) ? null : remark;
this.initiator = ObjectUtils.isEmpty(initiator) ? null : initiator;
this.remark = ObjectUtils.isEmpty(remark) ? null : remark;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,28 +27,28 @@
*/
@Feature("Component Tests - Repository")
@Story("Entity Listener Interceptor")
public class EntityInterceptorListenerTest extends AbstractJpaIntegrationTest {
class EntityInterceptorListenerTest extends AbstractJpaIntegrationTest {

@AfterEach
public void tearDown() {
void tearDown() {
EntityInterceptorHolder.getInstance().getEntityInterceptors().clear();
}

@Test
@Description("Verifies that the pre persist is called after a entity creation.")
public void prePersistIsCalledWhenPersistingATarget() {
void prePersistIsCalledWhenPersistingATarget() {
executePersistAndAssertCallbackResult(new PrePersistEntityListener());
}

@Test
@Description("Verifies that the post persist is called after a entity creation.")
public void postPersistIsCalledWhenPersistingATarget() {
void postPersistIsCalledWhenPersistingATarget() {
executePersistAndAssertCallbackResult(new PostPersistEntityListener());
}

@Test
@Description("Verifies that the post load is called after a entity is loaded.")
public void postLoadIsCalledWhenLoadATarget() {
void postLoadIsCalledWhenLoadATarget() {
final PostLoadEntityListener postLoadEntityListener = new PostLoadEntityListener();
EntityInterceptorHolder.getInstance().getEntityInterceptors().add(postLoadEntityListener);

Expand All @@ -61,25 +61,25 @@ public void postLoadIsCalledWhenLoadATarget() {

@Test
@Description("Verifies that the pre update is called after a entity update.")
public void preUpdateIsCalledWhenUpdateATarget() {
void preUpdateIsCalledWhenUpdateATarget() {
executeUpdateAndAssertCallbackResult(new PreUpdateEntityListener());
}

@Test
@Description("Verifies that the post update is called after a entity update.")
public void postUpdateIsCalledWhenUpdateATarget() {
void postUpdateIsCalledWhenUpdateATarget() {
executeUpdateAndAssertCallbackResult(new PostUpdateEntityListener());
}

@Test
@Description("Verifies that the pre remove is called after a entity deletion.")
public void preRemoveIsCalledWhenDeletingATarget() {
void preRemoveIsCalledWhenDeletingATarget() {
executeDeleteAndAssertCallbackResult(new PreRemoveEntityListener());
}

@Test
@Description("Verifies that the post remove is called after a entity deletion.")
public void postRemoveIsCalledWhenDeletingATarget() {
void postRemoveIsCalledWhenDeletingATarget() {
executeDeleteAndAssertCallbackResult(new PostRemoveEntityListener());
}

Expand All @@ -91,10 +91,10 @@ private void executePersistAndAssertCallbackResult(final AbstractEntityListener
}

private void executeUpdateAndAssertCallbackResult(final AbstractEntityListener entityInterceptor) {
Target updateTarget = addListenerAndCreateTarget(entityInterceptor, "targetToBeCreated");

updateTarget = targetManagement
.update(entityFactory.target().update(updateTarget.getControllerId()).name("New"));
final Target updateTarget = targetManagement.update(
entityFactory.target()
.update(addListenerAndCreateTarget(entityInterceptor, "targetToBeCreated").getControllerId())
.name("New"));

assertThat(entityInterceptor.getEntity()).isNotNull();
assertThat(entityInterceptor.getEntity()).isEqualTo(updateTarget);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,17 +144,17 @@ public void onApplicationEvent(final RemoteApplicationEvent event) {
return;
}

if (event instanceof RemoteTenantAwareEvent) {
assertThat(((RemoteTenantAwareEvent) event).getTenant()).isNotEmpty();
if (event instanceof RemoteTenantAwareEvent remoteTenantAwareEvent) {
assertThat(remoteTenantAwareEvent.getTenant()).isNotEmpty();
}

if (event instanceof RemoteIdEvent) {
assertThat(((RemoteIdEvent) event).getEntityId()).isNotNull();
if (event instanceof RemoteIdEvent remoteIdEvent) {
assertThat(remoteIdEvent.getEntityId()).isNotNull();
}

if (event instanceof TargetAssignDistributionSetEvent) {
assertThat(((TargetAssignDistributionSetEvent) event).getActions()).isNotEmpty();
assertThat(((TargetAssignDistributionSetEvent) event).getDistributionSetId()).isNotNull();
if (event instanceof TargetAssignDistributionSetEvent targetAssignDistributionSetEvent) {
assertThat(targetAssignDistributionSetEvent.getActions()).isNotEmpty();
assertThat(targetAssignDistributionSetEvent.getDistributionSetId()).isNotNull();
}

capturedEvents.compute(event.getClass(), (k, v) -> v == null ? 1 : v + 1);
Expand All @@ -177,7 +177,7 @@ private static final class ResetCounterMarkerEvent extends RemoteApplicationEven
private static final long serialVersionUID = 1L;

private ResetCounterMarkerEvent() {
super(new Object(), "resetcounter");
super(new Object(), "resetcounter", DEFAULT_DESTINATION_FACTORY.getDestination(null));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ private static ResponseEntity<InputStream> extractRange(final HttpServletRespons

private static long sublong(final String value, final int beginIndex, final int endIndex) {
final String substring = value.substring(beginIndex, endIndex);
return substring.length() > 0 ? Long.parseLong(substring) : -1;
return substring.isEmpty() ? -1 : Long.parseLong(substring);
}

private static void checkForShortcut(final HttpServletRequest request, final String etag, final long lastModified,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
@Feature("Unit Tests - Security")
@Story("Exclude path aware shallow ETag filter")
@ExtendWith(MockitoExtension.class)
public class ExcludePathAwareShallowETagFilterTest {
class ExcludePathAwareShallowETagFilterTest {

@Mock
private HttpServletRequest servletRequestMock;
Expand All @@ -46,7 +46,7 @@ public class ExcludePathAwareShallowETagFilterTest {
private FilterChain filterChainMock;

@Test
public void excludePathDoesNotCalculateETag() throws ServletException, IOException {
void excludePathDoesNotCalculateETag() throws ServletException, IOException {
final String knownContextPath = "/bumlux/test";
final String knownUri = knownContextPath + "/exclude/download";
final String antPathExclusion = "/exclude/**";
Expand All @@ -68,7 +68,7 @@ public void excludePathDoesNotCalculateETag() throws ServletException, IOExcepti
}

@Test
public void pathNotExcludedETagIsCalculated() throws ServletException, IOException {
void pathNotExcludedETagIsCalculated() throws ServletException, IOException {
final String knownContextPath = "/bumlux/test";
final String knownUri = knownContextPath + "/include/download";
final String antPathExclusion = "/exclude/**";
Expand Down
Loading

0 comments on commit bbb5f40

Please sign in to comment.