Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sonar Fixes #2234

Merged
merged 1 commit into from
Jan 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
import java.io.IOException;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.eclipse.hawkbit.mgmt.json.model.PagedList;
import org.eclipse.hawkbit.mgmt.json.model.artifact.MgmtArtifact;
import org.eclipse.hawkbit.rest.json.model.ExceptionInfo;

Expand All @@ -30,8 +29,4 @@ public static ExceptionInfo convertException(final String jsonExceptionResponse)
public static MgmtArtifact convertArtifactResponse(final String jsonResponse) throws IOException {
return OBJECT_MAPPER.readValue(jsonResponse, MgmtArtifact.class);
}

public static <T> PagedList<T> mapResponse(final Class<T> clazz, final String responseBody) throws IOException {
return OBJECT_MAPPER.readValue(responseBody, PagedList.class);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public class RemoteTenantAwareEvent extends RemoteApplicationEvent implements Te
*/
public RemoteTenantAwareEvent(final Object source, final String tenant, final String applicationId) {
// due to a bug in Spring Cloud, we cannot pass null for applicationId
super(source, applicationId != null ? applicationId : StringUtils.EMPTY);
super(source, applicationId != null ? applicationId : StringUtils.EMPTY, DEFAULT_DESTINATION_FACTORY.getDestination(null));
this.tenant = tenant;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AccessLevel;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.hawkbit.repository.event.remote.EventEntityManagerHolder;
Expand All @@ -26,6 +27,7 @@
* @param <E> the type of the entity
*/
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@EqualsAndHashCode(callSuper = true)
@Slf4j
public class RemoteEntityEvent<E extends TenantAwareBaseEntity> extends RemoteIdEvent {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,14 @@ public final class RsqlConfigHolder {
*/
@Value("${hawkbit.rsql.caseInsensitiveDB:false}")
private boolean caseInsensitiveDB;
@Autowired

private RsqlVisitorFactory rsqlVisitorFactory;

@Autowired
public void setRsqlVisitorFactory(final RsqlVisitorFactory rsqlVisitorFactory) {
this.rsqlVisitorFactory = rsqlVisitorFactory;
}

/**
* @deprecated in favour of G2 RSQL visitor. since 0.6.0
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,15 @@

@Feature("Unit Tests - Repository")
@Story("Regular expression helper")
public class RegexCharTest {
class RegexCharTest {

private static final int INDEX_FIRST_PRINTABLE_ASCII_CHAR = 32;
private static final int INDEX_LAST_PRINTABLE_ASCII_CHAR = 127;
private static final String TEST_STRING = getPrintableAsciiCharacters();

@Test
@Description("Verifies every RegexChar can be used to exclusively find the desired characters in a String.")
public void allRegexCharsOnlyFindExpectedChars() {
void allRegexCharsOnlyFindExpectedChars() {
for (final RegexChar character : RegexChar.values()) {
switch (character) {
case DIGITS:
Expand All @@ -51,7 +51,7 @@ public void allRegexCharsOnlyFindExpectedChars() {

@Test
@Description("Verifies that combinations of RegexChars can be used to find the desired characters in a String.")
public void combinedRegexCharsFindExpectedChars() {
void combinedRegexCharsFindExpectedChars() {
final RegexCharacterCollection greaterAndLessThan = new RegexCharacterCollection(RegexChar.GREATER_THAN,
RegexChar.LESS_THAN);
final RegexCharacterCollection equalsAndQuestionMark = new RegexCharacterCollection(RegexChar.EQUALS_SYMBOL,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,14 @@

@Feature("Unit Tests - Repository")
@Story("Security Test")
public class RepositoryManagementMethodPreAuthorizeAnnotatedTest {
class RepositoryManagementMethodPreAuthorizeAnnotatedTest {

// if some methods are to be excluded
private static final Set<Method> METHOD_SECURITY_EXCLUSION = new HashSet<>();

@Test
@Description("Verifies that repository methods are @PreAuthorize annotated")
public void repositoryManagementMethodsArePreAuthorizedAnnotated() {
void repositoryManagementMethodsArePreAuthorizedAnnotated() {
final String packageName = getClass().getPackage().getName();
try (final ScanResult scanResult = new ClassGraph().acceptPackages(packageName).scan()) {
final List<? extends Class<?>> matchingClasses = scanResult.getAllClasses()
Expand All @@ -59,7 +59,7 @@ public void repositoryManagementMethodsArePreAuthorizedAnnotated() {
* checked. The following methods are excluded due inherited from
* {@link Object}, like equals() or toString().
*
* @param clazz the class to retrieve the public declared methods
* @param clazz the class to retrieve the declared methods
*/
private static void assertDeclaredMethodsContainsPreAuthorizeAnnotations(final Class<?> clazz) {
final Method[] declaredMethods = clazz.getDeclaredMethods();
Expand All @@ -72,7 +72,7 @@ private static void assertDeclaredMethodsContainsPreAuthorizeAnnotations(final C
}
final PreAuthorize annotation = method.getAnnotation(PreAuthorize.class);
assertThat(annotation)
.as("The public method " + method.getName() + " in class " + clazz.getName() +
.as("The method " + method.getName() + " in class " + clazz.getName() +
" is not annotated with @PreAuthorize, security leak?")
.isNotNull();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
import org.eclipse.hawkbit.repository.model.Rollout;
import org.eclipse.hawkbit.repository.model.RolloutGroup;
import org.eclipse.hawkbit.repository.model.RolloutGroupConditions;
import org.springframework.util.StringUtils;
import org.springframework.util.ObjectUtils;

/**
* A collection of static helper methods for the {@link RolloutManagement}
Expand Down Expand Up @@ -135,10 +135,10 @@ public static void verifyRolloutInStatus(final Rollout rollout, final Rollout.Ro
* @param group the group to add
* @return list of groups
*/
public static List<Long> getGroupsByStatusIncludingGroup(final List<RolloutGroup> groups,
final RolloutGroup.RolloutGroupStatus status, final RolloutGroup group) {
public static List<Long> getGroupsByStatusIncludingGroup(
final List<RolloutGroup> groups, final RolloutGroup.RolloutGroupStatus status, final RolloutGroup group) {
return groups.stream().filter(innerGroup -> innerGroup.getStatus() == status || innerGroup.equals(group))
.map(RolloutGroup::getId).collect(Collectors.toList());
.map(RolloutGroup::getId).toList();
}

/**
Expand All @@ -149,7 +149,7 @@ public static List<Long> getGroupsByStatusIncludingGroup(final List<RolloutGroup
* @return RSQL string without base filter of the Rollout. Can be an empty string.
*/
public static String getAllGroupsTargetFilter(final List<RolloutGroup> groups) {
if (groups.stream().anyMatch(group -> StringUtils.isEmpty(group.getTargetFilterQuery()))) {
if (groups.stream().anyMatch(group -> ObjectUtils.isEmpty(group.getTargetFilterQuery()))) {
return "";
}

Expand All @@ -175,13 +175,13 @@ public static String getOverlappingWithGroupsTargetFilter(final String baseFilte
return concatAndTargetFilters(baseFilter, groupFilter);
}
final String previousGroupFilters = getAllGroupsTargetFilter(groups);
if (!StringUtils.isEmpty(previousGroupFilters)) {
if (!StringUtils.isEmpty(groupFilter)) {
if (!ObjectUtils.isEmpty(previousGroupFilters)) {
if (!ObjectUtils.isEmpty(groupFilter)) {
return concatAndTargetFilters(baseFilter, groupFilter, previousGroupFilters);
}
return concatAndTargetFilters(baseFilter, previousGroupFilters);
}
if (!StringUtils.isEmpty(groupFilter)) {
if (!ObjectUtils.isEmpty(groupFilter)) {
return concatAndTargetFilters(baseFilter, groupFilter);
}
return baseFilter;
Expand All @@ -193,7 +193,7 @@ public static String getOverlappingWithGroupsTargetFilter(final String baseFilte
* @return the final target filter query for a rollout group
*/
public static String getGroupTargetFilter(final String baseFilter, final RolloutGroup group) {
if (StringUtils.isEmpty(group.getTargetFilterQuery())) {
if (ObjectUtils.isEmpty(group.getTargetFilterQuery())) {
return baseFilter;
}
return concatAndTargetFilters(baseFilter, group.getTargetFilterQuery());
Expand Down Expand Up @@ -246,8 +246,8 @@ public static String getIdFromRetriedTargetFilter(final String targetFilter) {
}

private static boolean isTargetFilterInGroups(final String groupFilter, final List<RolloutGroup> groups) {
return !StringUtils.isEmpty(groupFilter)
&& groups.stream().anyMatch(prevGroup -> !StringUtils.isEmpty(prevGroup.getTargetFilterQuery())
return !ObjectUtils.isEmpty(groupFilter)
&& groups.stream().anyMatch(prevGroup -> !ObjectUtils.isEmpty(prevGroup.getTargetFilterQuery())
&& prevGroup.getTargetFilterQuery().equals(groupFilter));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ public void evictCaches(final String tenant) {
return ids.stream()
.map(id -> cache.get(id, CachedTotalTargetCountActionStatus.class))
.filter(Objects::nonNull)
.collect(Collectors.toMap(CachedTotalTargetCountActionStatus::getId, CachedTotalTargetCountActionStatus::getStatus));
.collect(Collectors.toMap(CachedTotalTargetCountActionStatus::id, CachedTotalTargetCountActionStatus::status));
}

private List<TotalTargetCountActionStatus> retrieveFromCache(final Long id, @NotNull final Cache cache) {
Expand All @@ -213,7 +213,7 @@ private List<TotalTargetCountActionStatus> retrieveFromCache(final Long id, @Not
return Collections.emptyList();
}

return cacheItem.getStatus();
return cacheItem.status();
}

private void putIntoCache(final Long id, final List<TotalTargetCountActionStatus> status,
Expand All @@ -233,22 +233,5 @@ private void putIntoCache(final Map<Long, List<TotalTargetCountActionStatus>> pu
return Objects.requireNonNull(cacheManager.getCache(CACHE_GR_NAME), "Cache '" + CACHE_RO_NAME + "' is null!");
}

private static final class CachedTotalTargetCountActionStatus {

private final long id;
private final List<TotalTargetCountActionStatus> status;

private CachedTotalTargetCountActionStatus(final long id, final List<TotalTargetCountActionStatus> status) {
this.id = id;
this.status = status;
}

public long getId() {
return id;
}

public List<TotalTargetCountActionStatus> getStatus() {
return status;
}
}
private record CachedTotalTargetCountActionStatus(long id, List<TotalTargetCountActionStatus> status) {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
@Slf4j
public class RsqlParserValidationOracle implements RsqlValidationOracle {

@SuppressWarnings("java:S1872") // intentionally don't use class but name - class could be unavailable
@Override
public ValidationOracleContext suggest(final String rsqlQuery, final int cursorPosition) {
final List<SuggestToken> expectedTokens = new ArrayList<>();
Expand Down Expand Up @@ -149,7 +150,7 @@ private static List<SuggestToken> getComparatorOperatorSuggestions(final String
final int currentQueryLength = rsqlQuery.length() - 1;
final Collection<String> tokenImages = TokenDescription.getTokenImage(TokenDescription.COMPARATOR);
return tokenImages.stream().map(tokenImage -> new SuggestToken(currentQueryLength,
currentQueryLength + tokenImage.length(), null, tokenImage)).collect(Collectors.toList());
currentQueryLength + tokenImage.length(), null, tokenImage)).toList();
}

return Collections.emptyList();
Expand Down Expand Up @@ -213,8 +214,8 @@ private static Optional<List<SuggestToken>> handleSubtokenSuggestion(final Strin
}

private static ParseException findParseException(final Throwable e) {
if (e instanceof ParseException) {
return (ParseException) e;
if (e instanceof ParseException parseException) {
return parseException;
} else if (e.getCause() != null) {
return findParseException(e.getCause());
}
Expand Down Expand Up @@ -306,15 +307,15 @@ private static List<SuggestToken> toTopSuggestToken(final int beginToken, final
final String tokenImageName) {
return FIELD_NAMES.stream()
.map(field -> new SuggestToken(beginToken, endToken, tokenImageName, field.toLowerCase()))
.collect(Collectors.toList());
.toList();
}

private static List<SuggestToken> toSubSuggestToken(final int beginToken, final int endToken,
final String topToken, final String tokenImageName) {
return Arrays.stream(TargetFields.values()).filter(field -> field.toString().equalsIgnoreCase(topToken))
.map(TargetFields::getSubEntityAttributes).flatMap(List::stream)
.map(subentity -> new SuggestToken(beginToken, endToken, tokenImageName, subentity))
.collect(Collectors.toList());
.map(subEntity -> new SuggestToken(beginToken, endToken, tokenImageName, subEntity))
.toList();
}

private static boolean containsValue(final String imageName) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@

import jakarta.persistence.criteria.Predicate;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.eclipse.hawkbit.repository.jpa.model.AbstractJpaNamedEntity_;
import org.eclipse.hawkbit.repository.jpa.model.JpaRollout;
import org.eclipse.hawkbit.repository.jpa.model.JpaRollout_;
import org.eclipse.hawkbit.repository.model.Rollout;
Expand All @@ -19,15 +22,11 @@
import org.springframework.data.jpa.repository.query.QueryUtils;

/**
* Specifications class for {@link Rollout}s. The class provides Spring Data
* JPQL Specifications.
* Specifications class for {@link Rollout}s. The class provides Spring Data JPQL Specifications.
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class RolloutSpecification {

private RolloutSpecification() {
// utility class
}

/**
* {@link Specification} for retrieving {@link Rollout}s by its <code>deleted</code> attribute.
*
Expand All @@ -54,7 +53,7 @@ public static Specification<JpaRollout> likeName(final String searchText, final
return (rolloutRoot, query, criteriaBuilder) -> {
final String searchTextToLower = searchText.toLowerCase();
return criteriaBuilder.and(
criteriaBuilder.like(criteriaBuilder.lower(rolloutRoot.get(JpaRollout_.name)), searchTextToLower),
criteriaBuilder.like(criteriaBuilder.lower(rolloutRoot.get(AbstractJpaNamedEntity_.name)), searchTextToLower),
criteriaBuilder.equal(rolloutRoot.get(JpaRollout_.deleted), isDeleted));
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,55 +27,50 @@
*/
@Feature("Component Tests - Repository")
@Story("Entity Id Events")
public class RemoteIdEventTest extends AbstractRemoteEventTest {
class RemoteIdEventTest extends AbstractRemoteEventTest {

private static final long ENTITY_ID = 1L;

private static String TENANT = "tenant";

private static Class<? extends TenantAwareBaseEntity> ENTITY_CLASS = JpaAction.class;

private static String NODE = "Node";

private static String CONTROLLER_ID = "controller911";

private static String ADDRESS = "amqp://anyhost";
private static final String TENANT = "tenant";
private static final Class<? extends TenantAwareBaseEntity> ENTITY_CLASS = JpaAction.class;
private static final String NODE = "Node";
private static final String CONTROLLER_ID = "controller911";
private static final String ADDRESS = "amqp://anyhost";

@Test
@Description("Verifies that the ds id is correct reloaded")
public void testDistributionSetDeletedEvent() {
void testDistributionSetDeletedEvent() {
assertAndCreateRemoteEvent(DistributionSetDeletedEvent.class);
}

@Test
@Description("Verifies that the ds tag id is correct reloaded")
public void testDistributionSetTagDeletedEvent() {
void testDistributionSetTagDeletedEvent() {
assertAndCreateRemoteEvent(DistributionSetTagDeletedEvent.class);
}

@Test
@Description("Verifies that the target id is correct reloaded")
public void testTargetDeletedEvent() {
void testTargetDeletedEvent() {
final TargetDeletedEvent deletedEvent = new TargetDeletedEvent(TENANT, ENTITY_ID, CONTROLLER_ID, ADDRESS,
ENTITY_CLASS, NODE);
assertEntity(deletedEvent);
}

@Test
@Description("Verifies that the target tag id is correct reloaded")
public void testTargetTagDeletedEvent() {
void testTargetTagDeletedEvent() {
assertAndCreateRemoteEvent(TargetTagDeletedEvent.class);
}

@Test
@Description("Verifies that the software module id is correct reloaded")
public void testSoftwareModuleDeletedEvent() {
void testSoftwareModuleDeletedEvent() {
assertAndCreateRemoteEvent(SoftwareModuleDeletedEvent.class);
}

@Test
@Description("Verifies that the rollout id is correct reloaded")
public void testRolloutDeletedEvent() {
void testRolloutDeletedEvent() {
assertAndCreateRemoteEvent(RolloutDeletedEvent.class);
}

Expand Down Expand Up @@ -105,6 +100,6 @@ protected void assertEntity(final RemoteIdEvent event) {

private void assertDeserializeEvent(final RemoteIdEvent underTestCreatedEvent, final RemoteIdEvent event) {
// gets added because events inherit from of java.util.EventObject
assertThat(underTestCreatedEvent).isEqualToIgnoringGivenFields(event, "source");
assertThat(underTestCreatedEvent).usingRecursiveComparison().ignoringFields("source").isEqualTo(event);
}
}
Loading
Loading