Sonar Fixes (6) (#2214)
Signed-off-by: Avgustin Marinov <Avgustin.Marinov@bosch.com>
This commit is contained in:
@@ -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.
|
||||
|
||||
@@ -86,7 +86,7 @@ public class ExecutorAutoConfiguration {
|
||||
|
||||
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;
|
||||
|
||||
@@ -19,12 +19,12 @@ import io.github.classgraph.ScanResult;
|
||||
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()
|
||||
|
||||
@@ -11,12 +11,14 @@ package org.eclipse.hawkbit.repository.exception;
|
||||
|
||||
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.";
|
||||
|
||||
@@ -13,6 +13,7 @@ import java.io.Serial;
|
||||
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;
|
||||
@@ -20,9 +21,9 @@ 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
|
||||
|
||||
@@ -11,14 +11,15 @@ package org.eclipse.hawkbit.repository.exception;
|
||||
|
||||
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
|
||||
|
||||
@@ -11,15 +11,16 @@ package org.eclipse.hawkbit.repository.exception;
|
||||
|
||||
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
|
||||
|
||||
@@ -91,8 +91,8 @@ class HawkbitEclipseLinkJpaDialect extends EclipseLinkJpaDialect {
|
||||
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);
|
||||
|
||||
@@ -31,7 +31,7 @@ public class EntityPropertyChangeListener extends DescriptorEventAdapter {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -57,7 +57,7 @@ public class EntityPropertyChangeListener implements PostUpdateEventListener {
|
||||
}
|
||||
|
||||
if (hasNonIgnoredChanges || !lastTargetQueryChanged) {
|
||||
AbstractJpaBaseEntity.doNotify(() -> ((EventAwareEntity) event.getEntity()).fireUpdateEvent());
|
||||
AbstractBaseEntity.doNotify(((EventAwareEntity) event.getEntity())::fireUpdateEvent);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -200,7 +200,7 @@ public class JpaConfirmationManagement extends JpaActionManagement implements Co
|
||||
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) {
|
||||
|
||||
@@ -321,13 +321,16 @@ public class JpaControllerManagement extends JpaActionManagement implements Cont
|
||||
@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));
|
||||
|
||||
@@ -14,6 +14,7 @@ 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;
|
||||
@@ -375,7 +376,7 @@ public class JpaAction extends AbstractJpaTenantAwareBaseEntity implements Actio
|
||||
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);
|
||||
@@ -388,7 +389,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,15 +19,17 @@ import jakarta.persistence.ManyToOne;
|
||||
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")
|
||||
@@ -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
|
||||
|
||||
@@ -27,28 +27,28 @@ import org.junit.jupiter.api.Test;
|
||||
*/
|
||||
@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);
|
||||
|
||||
@@ -61,25 +61,25 @@ public class EntityInterceptorListenerTest extends AbstractJpaIntegrationTest {
|
||||
|
||||
@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());
|
||||
}
|
||||
|
||||
@@ -91,10 +91,10 @@ public class EntityInterceptorListenerTest extends AbstractJpaIntegrationTest {
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
@@ -144,17 +144,17 @@ public class EventVerifier extends AbstractTestExecutionListener {
|
||||
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);
|
||||
@@ -177,7 +177,7 @@ public class EventVerifier extends AbstractTestExecutionListener {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private ResetCounterMarkerEvent() {
|
||||
super(new Object(), "resetcounter");
|
||||
super(new Object(), "resetcounter", DEFAULT_DESTINATION_FACTORY.getDestination(null));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -196,7 +196,7 @@ public final class FileStreamingUtil {
|
||||
|
||||
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,
|
||||
|
||||
@@ -34,7 +34,7 @@ import org.mockito.junit.jupiter.MockitoExtension;
|
||||
@Feature("Unit Tests - Security")
|
||||
@Story("Exclude path aware shallow ETag filter")
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
public class ExcludePathAwareShallowETagFilterTest {
|
||||
class ExcludePathAwareShallowETagFilterTest {
|
||||
|
||||
@Mock
|
||||
private HttpServletRequest servletRequestMock;
|
||||
@@ -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/**";
|
||||
@@ -68,7 +68,7 @@ public class ExcludePathAwareShallowETagFilterTest {
|
||||
}
|
||||
|
||||
@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/**";
|
||||
|
||||
@@ -21,11 +21,11 @@ import org.junit.jupiter.api.Test;
|
||||
|
||||
@Feature("Unit Tests - Management API")
|
||||
@Story("Error Handling")
|
||||
public class ExceptionInfoTest {
|
||||
class ExceptionInfoTest {
|
||||
|
||||
@Test
|
||||
@Description("Ensures that setters and getters match on teh payload.")
|
||||
public void setterAndGetterOnExceptionInfo() {
|
||||
void setterAndGetterOnExceptionInfo() {
|
||||
final String knownExceptionClass = "hawkbit.test.exception.Class";
|
||||
final String knownErrorCode = "hawkbit.error.code.Known";
|
||||
final String knownMessage = "a known message";
|
||||
|
||||
@@ -40,8 +40,8 @@ import org.springframework.http.ResponseEntity;
|
||||
@Story("File streaming")
|
||||
class FileStreamingUtilTest {
|
||||
|
||||
private final static String CONTENT = "This is some very long string which is intended to test";
|
||||
private final static byte[] CONTENT_BYTES = CONTENT.getBytes(StandardCharsets.UTF_8);
|
||||
private static final String CONTENT = "This is some very long string which is intended to test";
|
||||
private static final byte[] CONTENT_BYTES = CONTENT.getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
private static final DbArtifact TEST_ARTIFACT = new DbArtifact() {
|
||||
|
||||
|
||||
@@ -32,29 +32,29 @@ public class HawkbitClient {
|
||||
private static final String AUTHORIZATION = "Authorization";
|
||||
public static final BiFunction<Tenant, Controller, RequestInterceptor> DEFAULT_REQUEST_INTERCEPTOR_FN =
|
||||
(tenant, controller) ->
|
||||
controller == null ?
|
||||
template -> {
|
||||
template.header(
|
||||
AUTHORIZATION,
|
||||
controller == null
|
||||
? template ->
|
||||
template.header(
|
||||
AUTHORIZATION,
|
||||
|
||||
"Basic " +
|
||||
Base64.getEncoder()
|
||||
.encodeToString(
|
||||
(Objects.requireNonNull(tenant.getUsername(), "User is null!") +
|
||||
":" +
|
||||
Objects.requireNonNull(tenant.getPassword(),
|
||||
"Password is not available!"))
|
||||
.getBytes(StandardCharsets.ISO_8859_1)));
|
||||
} :
|
||||
template -> {
|
||||
if (ObjectUtils.isEmpty(tenant.getGatewayToken())) {
|
||||
if (!ObjectUtils.isEmpty(controller.getSecurityToken())) {
|
||||
template.header(AUTHORIZATION, "TargetToken " + controller.getSecurityToken());
|
||||
} // else do not sent authentication
|
||||
} else {
|
||||
template.header(AUTHORIZATION, "GatewayToken " + tenant.getGatewayToken());
|
||||
}
|
||||
};
|
||||
"Basic " +
|
||||
Base64.getEncoder()
|
||||
.encodeToString(
|
||||
(Objects.requireNonNull(tenant.getUsername(), "User is null!") +
|
||||
":" +
|
||||
Objects.requireNonNull(tenant.getPassword(),
|
||||
"Password is not available!"))
|
||||
.getBytes(StandardCharsets.ISO_8859_1)))
|
||||
:
|
||||
template -> {
|
||||
if (ObjectUtils.isEmpty(tenant.getGatewayToken())) {
|
||||
if (!ObjectUtils.isEmpty(controller.getSecurityToken())) {
|
||||
template.header(AUTHORIZATION, "TargetToken " + controller.getSecurityToken());
|
||||
} // else do not sent authentication
|
||||
} else {
|
||||
template.header(AUTHORIZATION, "GatewayToken " + tenant.getGatewayToken());
|
||||
}
|
||||
};
|
||||
private static final ErrorDecoder DEFAULT_ERROR_DECODER_0 = new ErrorDecoder.Default();
|
||||
public static final ErrorDecoder DEFAULT_ERROR_DECODER = (methodKey, response) -> {
|
||||
final Exception e = DEFAULT_ERROR_DECODER_0.decode(methodKey, response);
|
||||
|
||||
@@ -33,7 +33,7 @@ import org.mockito.junit.jupiter.MockitoExtension;
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@Feature("Unit Tests - Security")
|
||||
@Story("IP Util Test")
|
||||
public class IpUtilTest {
|
||||
class IpUtilTest {
|
||||
|
||||
private static final String X_FORWARDED_FOR = HawkbitSecurityProperties.Clients.X_FORWARDED_FOR;
|
||||
private static final String KNOWN_REQUEST_HEADER = "bumlux";
|
||||
@@ -49,7 +49,7 @@ public class IpUtilTest {
|
||||
|
||||
@Test
|
||||
@Description("Tests create uri from request")
|
||||
public void getRemoteAddrFromRequestIfForwardedHeaderNotPresent() {
|
||||
void getRemoteAddrFromRequestIfForwardedHeaderNotPresent() {
|
||||
final URI knownRemoteClientIP = IpUtil.createHttpUri("127.0.0.1");
|
||||
when(requestMock.getRemoteAddr()).thenReturn(knownRemoteClientIP.getHost());
|
||||
|
||||
@@ -64,7 +64,7 @@ public class IpUtilTest {
|
||||
|
||||
@Test
|
||||
@Description("Tests create uri from request with masked IP when IP tracking is disabled")
|
||||
public void maskRemoteAddrIfDisabled() {
|
||||
void maskRemoteAddrIfDisabled() {
|
||||
final URI knownRemoteClientIP = IpUtil.createHttpUri("***");
|
||||
when(securityPropertyMock.getClients()).thenReturn(clientMock);
|
||||
when(clientMock.getRemoteIpHeader()).thenReturn(KNOWN_REQUEST_HEADER);
|
||||
@@ -80,7 +80,7 @@ public class IpUtilTest {
|
||||
|
||||
@Test
|
||||
@Description("Tests create uri from x forward header")
|
||||
public void getRemoteAddrFromXForwardedForHeader() {
|
||||
void getRemoteAddrFromXForwardedForHeader() {
|
||||
final URI knownRemoteClientIP = IpUtil.createHttpUri("10.99.99.1");
|
||||
when(requestMock.getHeader(X_FORWARDED_FOR)).thenReturn(knownRemoteClientIP.getHost());
|
||||
|
||||
@@ -94,7 +94,7 @@ public class IpUtilTest {
|
||||
|
||||
@Test
|
||||
@Description("Tests client uri from request")
|
||||
public void testCreateClientHttpUri() {
|
||||
void testCreateClientHttpUri() {
|
||||
checkHostInfoResolution("0:0:0:0:0:0:0:1", "[0:0:0:0:0:0:0:1]", true);
|
||||
checkHostInfoResolution("127.0.0.1", "127.0.0.1", true);
|
||||
checkHostInfoResolution("127.0.0.1:93493", "127.0.0.1", true);
|
||||
@@ -107,7 +107,7 @@ public class IpUtilTest {
|
||||
|
||||
@Test
|
||||
@Description("Tests client uri from request")
|
||||
public void testResolveClientIpFromHeader() {
|
||||
void testResolveClientIpFromHeader() {
|
||||
checkHostInfoResolution("0:0:0:0:0:0:0:1", "[0:0:0:0:0:0:0:1]", false);
|
||||
checkHostInfoResolution("127.0.0.1", "127.0.0.1", false);
|
||||
checkHostInfoResolution("127.0.0.1:93493", "127.0.0.1", false);
|
||||
@@ -117,7 +117,7 @@ public class IpUtilTest {
|
||||
|
||||
@Test
|
||||
@Description("Tests create http uri ipv4 and ipv6")
|
||||
public void testCreateHttpUri() {
|
||||
void testCreateHttpUri() {
|
||||
final String ipv4 = "10.99.99.1";
|
||||
URI httpUri = IpUtil.createHttpUri(ipv4);
|
||||
assertHttpUri(ipv4, httpUri);
|
||||
@@ -133,7 +133,7 @@ public class IpUtilTest {
|
||||
|
||||
@Test
|
||||
@Description("Tests create amqp uri ipv4 and ipv6")
|
||||
public void testCreateAmqpUri() {
|
||||
void testCreateAmqpUri() {
|
||||
final String ipv4 = "10.99.99.1";
|
||||
URI amqpUri = IpUtil.createAmqpUri(ipv4, "path");
|
||||
assertAmqpUri(ipv4, amqpUri);
|
||||
@@ -160,7 +160,7 @@ public class IpUtilTest {
|
||||
|
||||
@Test
|
||||
@Description("Tests create invalid uri")
|
||||
public void testCreateInvalidUri() {
|
||||
void testCreateInvalidUri() {
|
||||
|
||||
final String host = "10.99.99.1";
|
||||
final URI testUri = IpUtil.createUri("test", host);
|
||||
|
||||
@@ -96,7 +96,7 @@ public class Filter extends Div {
|
||||
}
|
||||
})
|
||||
.filter(e -> !(e.getValue() instanceof Collection<?> coll && coll.isEmpty()))
|
||||
.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
|
||||
if (normalized.isEmpty()) {
|
||||
return null;
|
||||
} else if (normalized.size() == 1) {
|
||||
|
||||
Reference in New Issue
Block a user