Fix sonar findings (2) (#3016)

Signed-off-by: Avgustin Marinov <Avgustin.Marinov@bosch.com>
This commit is contained in:
Avgustin Marinov
2026-04-15 14:39:28 +03:00
committed by GitHub
parent a00374f455
commit 8015b0e3f1
6 changed files with 73 additions and 81 deletions

View File

@@ -66,10 +66,10 @@ public class AccessContext {
* @return the current tenant
*/
public static String tenant() {
final SecurityContext context = SecurityContextHolder.getContext();
if (context.getAuthentication() != null) {
final Object principal = context.getAuthentication().getPrincipal();
if (context.getAuthentication().getDetails() instanceof TenantAwareAuthenticationDetails tenantAwareAuthenticationDetails) {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
final Object principal = authentication.getPrincipal();
if (authentication.getDetails() instanceof TenantAwareAuthenticationDetails tenantAwareAuthenticationDetails) {
return tenantAwareAuthenticationDetails.tenant();
} else if (principal instanceof TenantAwareUser tenantAwareUser) {
return tenantAwareUser.getTenant();
@@ -283,7 +283,7 @@ public class AccessContext {
if (principal instanceof OidcUser oidcUser) {
return oidcUser.getPreferredUsername();
}
return principal.toString();
return principal == null ? null : principal.toString();
}
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
@@ -337,7 +337,9 @@ public class AccessContext {
private String[] authorities;
private SecCtxInfo(final SecurityContext securityContext) {
final Authentication authentication = securityContext.getAuthentication();
final Authentication authentication = Objects.requireNonNull(
securityContext.getAuthentication(),
"Authentication must be non-null to serialize security context");
if (!authentication.isAuthenticated()) {
throw new IllegalStateException("Only authenticated context could be serialized");
}
@@ -361,8 +363,7 @@ public class AccessContext {
final SecurityContext ctx = SecurityContextHolder.createEmptyContext();
final Object details = tenant == null ? null : new TenantAwareAuthenticationDetails(tenant, false);
final ActorAware principal = () -> auditor;
final Collection<? extends GrantedAuthority> grantedAuthorities =
Stream.of(authorities).map(SimpleGrantedAuthority::new).toList();
final Collection<? extends GrantedAuthority> grantedAuthorities = Stream.of(authorities).map(SimpleGrantedAuthority::new).toList();
ctx.setAuthentication(new Authentication() {
@Override

View File

@@ -9,8 +9,6 @@
*/
package org.eclipse.hawkbit.repository.jpa;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import lombok.AccessLevel;
@@ -37,9 +35,9 @@ public class DefaultRolloutApprovalStrategy implements RolloutApprovalStrategy {
*/
@Override
public boolean isApprovalNeeded(final Rollout rollout) {
return TenantConfigHelper.getAsSystem(TenantConfigurationKey.ROLLOUT_APPROVAL_ENABLED, Boolean.class)
&& hasNoApproveRolloutPermission(getCurrentAuthentication().map(Authentication::getAuthorities).orElseGet(List::of).stream()
.map(GrantedAuthority::getAuthority).toList());
return TenantConfigHelper.getAsSystem(TenantConfigurationKey.ROLLOUT_APPROVAL_ENABLED, Boolean.class) // if approval enabled for tenant
&& !getCurrentAuthentication().map(Authentication::getAuthorities).map(grantedAuthorities -> grantedAuthorities.stream()
.map(GrantedAuthority::getAuthority).anyMatch(SpPermission.APPROVE_ROLLOUT::equals)).orElse(false);
}
@Override
@@ -55,8 +53,4 @@ public class DefaultRolloutApprovalStrategy implements RolloutApprovalStrategy {
private static Optional<Authentication> getCurrentAuthentication() {
return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication());
}
private static boolean hasNoApproveRolloutPermission(final Collection<String> authorities) {
return authorities.stream().noneMatch(SpPermission.APPROVE_ROLLOUT::equals);
}
}

View File

@@ -266,7 +266,7 @@ public class BaseEntityRepositoryACM<T extends AbstractJpaBaseEntity> implements
@NonNull
public List<T> findAll(final Operation operation, @Nullable final Specification<T> spec) {
if (operation == null) {
return repository.findAll(spec);
return spec == null ? repository.findAll() : repository.findAll(spec);
} else {
return repository.findAll(accessController.appendAccessRules(operation, spec));
}

View File

@@ -66,7 +66,7 @@ public final class HawkbitBaseRepository<T, ID extends Serializable> extends Sim
@Override
public Slice<T> findAllWithoutCount(@Nullable final Specification<T> spec, final Pageable pageable) {
final TypedQuery<T> query = getQuery(spec, pageable);
final TypedQuery<T> query = getQuery(spec == null ? Specification.unrestricted() : spec, pageable);
return pageable.isUnpaged() ? new PageImpl<>(query.getResultList()) : readPageWithoutCount(query, pageable);
}
@@ -104,7 +104,7 @@ public final class HawkbitBaseRepository<T, ID extends Serializable> extends Sim
@Override
public long count(@Nullable final Operation operation, @Nullable final Specification<T> spec) {
return count(spec);
return spec == null ? count() : count(spec);
}
@Override

View File

@@ -46,41 +46,42 @@ public final class ConfigView extends VerticalLayout {
public ConfigView(final HawkbitMgmtClient hawkbitClient) {
setSpacing(false);
final Button saveButton = new Button("Save");
Optional.ofNullable(
hawkbitClient.getTenantManagementRestApi().getTenantConfiguration().getBody()).ifPresent(config ->
Optional.ofNullable(hawkbitClient.getTenantManagementRestApi().getTenantConfiguration().getBody()).ifPresent(config ->
config.forEach((k, v) -> {
if (v.getValue() instanceof String strValue) {
final TextField tf = new TextField(k, strValue, event -> {
final MgmtSystemTenantConfigurationValueRequest vre = new MgmtSystemTenantConfigurationValueRequest();
vre.setValue(event.getValue());
configValue.put(k, vre);
});
tf.getElement().getStyle().set(WIDTH, PX_300);
add(tf);
} else if (v.getValue() instanceof Boolean boolValue) {
add(new Checkbox(k, boolValue, event -> {
switch (v.getValue()) {
case String strValue -> {
final TextField tf = new TextField(k, strValue, event -> {
final MgmtSystemTenantConfigurationValueRequest vre = new MgmtSystemTenantConfigurationValueRequest();
vre.setValue(event.getValue());
configValue.put(k, vre);
});
tf.getElement().getStyle().set(WIDTH, PX_300);
add(tf);
}
case Boolean boolValue -> add(new Checkbox(k, boolValue, event -> {
final MgmtSystemTenantConfigurationValueRequest vre = new MgmtSystemTenantConfigurationValueRequest();
vre.setValue(event.getValue());
configValue.put(k, vre);
}));
} else if (v.getValue() instanceof Long longValue) {
final NumberField nf = new NumberField(k, (double) longValue, event -> {
final MgmtSystemTenantConfigurationValueRequest vre = new MgmtSystemTenantConfigurationValueRequest();
vre.setValue(event.getValue());
configValue.put(k, vre);
});
nf.getElement().getStyle().set(WIDTH, PX_300);
add(nf);
} else if (v.getValue() instanceof Integer intValue) {
final NumberField nf = new NumberField(k, (double) intValue, event -> {
MgmtSystemTenantConfigurationValueRequest vre = new MgmtSystemTenantConfigurationValueRequest();
vre.setValue(event.getValue());
configValue.put(k, vre);
});
nf.getElement().getStyle().set(WIDTH, PX_300);
add(nf);
} else {
log.debug("Unexpected value type: {} -> {} (class: {})",
case Long longValue -> {
final NumberField nf = new NumberField(k, (double) longValue, event -> {
final MgmtSystemTenantConfigurationValueRequest vre = new MgmtSystemTenantConfigurationValueRequest();
vre.setValue(event.getValue());
configValue.put(k, vre);
});
nf.getElement().getStyle().set(WIDTH, PX_300);
add(nf);
}
case Integer intValue -> {
final NumberField nf = new NumberField(k, (double) intValue, event -> {
MgmtSystemTenantConfigurationValueRequest vre = new MgmtSystemTenantConfigurationValueRequest();
vre.setValue(event.getValue());
configValue.put(k, vre);
});
nf.getElement().getStyle().set(WIDTH, PX_300);
add(nf);
}
default -> log.debug("Unexpected value type: {} -> {} (class: {})",
k, v.getValue(), v.getValue() == null ? "null" : v.getValue().getClass());
}
}));

View File

@@ -255,13 +255,10 @@ public final class TargetView extends TableView<TargetView.TargetWithDs, String>
}
private static List<MgmtTargetFilterQuery> listFilters(HawkbitMgmtClient hawkbitClient) {
return Optional
.ofNullable(
hawkbitClient.getTargetFilterQueryRestApi()
.getFilters(null, 0, 30, null, null)
.getBody()
.getContent())
.orElse(Collections.emptyList());
return Optional.ofNullable(hawkbitClient.getTargetFilterQueryRestApi()
.getFilters(null, 0, 30, null, null).getBody())
.map(PagedList<MgmtTargetFilterQuery>::getContent)
.orElseGet(List::of);
}
private ComponentEventListener<ClickEvent<Button>> createBtnListener(HawkbitMgmtClient hawkbitClient) {
@@ -409,11 +406,11 @@ public final class TargetView extends TableView<TargetView.TargetWithDs, String>
this.hawkbitClient = hawkbitClient;
description.setMinLength(2);
Stream.of(
description,
createdBy, createdAt,
lastModifiedBy, lastModifiedAt,
securityToken, lastPoll, group, targetAddress, targetAttributes
)
description,
createdBy, createdAt,
lastModifiedBy, lastModifiedAt,
securityToken, lastPoll, group, targetAddress, targetAttributes
)
.forEach(field -> {
field.setReadOnly(true);
add(field);
@@ -483,18 +480,18 @@ public final class TargetView extends TableView<TargetView.TargetWithDs, String>
Optional.ofNullable(supplier.get())
.map(ResponseEntity<MgmtDistributionSet>::getBody)
.ifPresentOrElse(value -> {
final String description = """
Name: %s
Version: %s
%s
""".replace("\n", System.lineSeparator());
textArea.setValueWithLink(description.formatted(
value.getName(),
value.getVersion(),
value.getModules().stream().map(module -> module.getTypeName() + ": " + module.getVersion())
.collect(Collectors.joining(System.lineSeparator()))
), "q=id%3D%3D" + value.getId().toString());
},
final String description = """
Name: %s
Version: %s
%s
""".replace("\n", System.lineSeparator());
textArea.setValueWithLink(description.formatted(
value.getName(),
value.getVersion(),
value.getModules().stream().map(module -> module.getTypeName() + ": " + module.getVersion())
.collect(Collectors.joining(System.lineSeparator()))
), "q=id%3D%3D" + value.getId().toString());
},
() -> textArea.setValueWithLink("", null));
}
}
@@ -603,7 +600,7 @@ public final class TargetView extends TableView<TargetView.TargetWithDs, String>
int offset = 0;
do {
List<MgmtTag> page = Optional.ofNullable(
hawkbitClient.getTargetTagRestApi().getTargetTags(null, offset, 50, Constants.NAME_ASC).getBody())
hawkbitClient.getTargetTagRestApi().getTargetTags(null, offset, 50, Constants.NAME_ASC).getBody())
.map(PagedList::getContent)
.orElse(Collections.emptyList());
tags.addAll(page);
@@ -647,7 +644,7 @@ public final class TargetView extends TableView<TargetView.TargetWithDs, String>
final Button addBtn = new Button("Add");
addBtn.addClickListener(e -> new AddMetadataDialog(hawkbitClient, target, this::refreshMetadatas).result());
addBtn.setEnabled(true);
final HorizontalLayout tools = new HorizontalLayout();
final HorizontalLayout tools = new HorizontalLayout();
tools.setWidthFull();
tools.add(addBtn);
add(tools);
@@ -665,7 +662,7 @@ public final class TargetView extends TableView<TargetView.TargetWithDs, String>
private void refreshMetadatas() {
metadataArea.setItems(
Optional.ofNullable(
hawkbitClient.getTargetRestApi().getMetadata(target.getControllerId()).getBody())
hawkbitClient.getTargetRestApi().getMetadata(target.getControllerId()).getBody())
.map(PagedList::getContent)
.orElse(Collections.emptyList()));
}
@@ -845,7 +842,7 @@ public final class TargetView extends TableView<TargetView.TargetWithDs, String>
request.setTargetType(type.getValue().getId());
}
hawkbitClient.getTargetRestApi().createTargets(
List.of(request))
List.of(request))
.getBody()
.stream()
.findFirst()
@@ -1091,9 +1088,8 @@ public final class TargetView extends TableView<TargetView.TargetWithDs, String>
public static TargetWithDs from(final HawkbitMgmtClient hawkbitClient, MgmtTarget target) {
TargetWithDs targetWithDs = objectMapper.convertValue(target, TargetWithDs.class);
targetWithDs.ds = Optional.ofNullable(hawkbitClient.getTargetRestApi().getInstalledDistributionSet(targetWithDs
.getControllerId())
.getBody());
targetWithDs.ds = Optional.ofNullable(hawkbitClient.getTargetRestApi()
.getInstalledDistributionSet(targetWithDs.getControllerId()).getBody());
return targetWithDs;
}