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

View File

@@ -9,8 +9,6 @@
*/ */
package org.eclipse.hawkbit.repository.jpa; package org.eclipse.hawkbit.repository.jpa;
import java.util.Collection;
import java.util.List;
import java.util.Optional; import java.util.Optional;
import lombok.AccessLevel; import lombok.AccessLevel;
@@ -37,9 +35,9 @@ public class DefaultRolloutApprovalStrategy implements RolloutApprovalStrategy {
*/ */
@Override @Override
public boolean isApprovalNeeded(final Rollout rollout) { public boolean isApprovalNeeded(final Rollout rollout) {
return TenantConfigHelper.getAsSystem(TenantConfigurationKey.ROLLOUT_APPROVAL_ENABLED, Boolean.class) return TenantConfigHelper.getAsSystem(TenantConfigurationKey.ROLLOUT_APPROVAL_ENABLED, Boolean.class) // if approval enabled for tenant
&& hasNoApproveRolloutPermission(getCurrentAuthentication().map(Authentication::getAuthorities).orElseGet(List::of).stream() && !getCurrentAuthentication().map(Authentication::getAuthorities).map(grantedAuthorities -> grantedAuthorities.stream()
.map(GrantedAuthority::getAuthority).toList()); .map(GrantedAuthority::getAuthority).anyMatch(SpPermission.APPROVE_ROLLOUT::equals)).orElse(false);
} }
@Override @Override
@@ -55,8 +53,4 @@ public class DefaultRolloutApprovalStrategy implements RolloutApprovalStrategy {
private static Optional<Authentication> getCurrentAuthentication() { private static Optional<Authentication> getCurrentAuthentication() {
return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication()); 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 @NonNull
public List<T> findAll(final Operation operation, @Nullable final Specification<T> spec) { public List<T> findAll(final Operation operation, @Nullable final Specification<T> spec) {
if (operation == null) { if (operation == null) {
return repository.findAll(spec); return spec == null ? repository.findAll() : repository.findAll(spec);
} else { } else {
return repository.findAll(accessController.appendAccessRules(operation, spec)); return repository.findAll(accessController.appendAccessRules(operation, spec));
} }

View File

@@ -66,7 +66,7 @@ public final class HawkbitBaseRepository<T, ID extends Serializable> extends Sim
@Override @Override
public Slice<T> findAllWithoutCount(@Nullable final Specification<T> spec, final Pageable pageable) { 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); 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 @Override
public long count(@Nullable final Operation operation, @Nullable final Specification<T> spec) { public long count(@Nullable final Operation operation, @Nullable final Specification<T> spec) {
return count(spec); return spec == null ? count() : count(spec);
} }
@Override @Override

View File

@@ -46,41 +46,42 @@ public final class ConfigView extends VerticalLayout {
public ConfigView(final HawkbitMgmtClient hawkbitClient) { public ConfigView(final HawkbitMgmtClient hawkbitClient) {
setSpacing(false); setSpacing(false);
final Button saveButton = new Button("Save"); final Button saveButton = new Button("Save");
Optional.ofNullable( Optional.ofNullable(hawkbitClient.getTenantManagementRestApi().getTenantConfiguration().getBody()).ifPresent(config ->
hawkbitClient.getTenantManagementRestApi().getTenantConfiguration().getBody()).ifPresent(config ->
config.forEach((k, v) -> { config.forEach((k, v) -> {
if (v.getValue() instanceof String strValue) { switch (v.getValue()) {
final TextField tf = new TextField(k, strValue, event -> { case String strValue -> {
final MgmtSystemTenantConfigurationValueRequest vre = new MgmtSystemTenantConfigurationValueRequest(); final TextField tf = new TextField(k, strValue, event -> {
vre.setValue(event.getValue()); final MgmtSystemTenantConfigurationValueRequest vre = new MgmtSystemTenantConfigurationValueRequest();
configValue.put(k, vre); vre.setValue(event.getValue());
}); configValue.put(k, vre);
tf.getElement().getStyle().set(WIDTH, PX_300); });
add(tf); tf.getElement().getStyle().set(WIDTH, PX_300);
} else if (v.getValue() instanceof Boolean boolValue) { add(tf);
add(new Checkbox(k, boolValue, event -> { }
case Boolean boolValue -> add(new Checkbox(k, boolValue, event -> {
final MgmtSystemTenantConfigurationValueRequest vre = new MgmtSystemTenantConfigurationValueRequest(); final MgmtSystemTenantConfigurationValueRequest vre = new MgmtSystemTenantConfigurationValueRequest();
vre.setValue(event.getValue()); vre.setValue(event.getValue());
configValue.put(k, vre); configValue.put(k, vre);
})); }));
} else if (v.getValue() instanceof Long longValue) { case Long longValue -> {
final NumberField nf = new NumberField(k, (double) longValue, event -> { final NumberField nf = new NumberField(k, (double) longValue, event -> {
final MgmtSystemTenantConfigurationValueRequest vre = new MgmtSystemTenantConfigurationValueRequest(); final MgmtSystemTenantConfigurationValueRequest vre = new MgmtSystemTenantConfigurationValueRequest();
vre.setValue(event.getValue()); vre.setValue(event.getValue());
configValue.put(k, vre); configValue.put(k, vre);
}); });
nf.getElement().getStyle().set(WIDTH, PX_300); nf.getElement().getStyle().set(WIDTH, PX_300);
add(nf); add(nf);
} else if (v.getValue() instanceof Integer intValue) { }
final NumberField nf = new NumberField(k, (double) intValue, event -> { case Integer intValue -> {
MgmtSystemTenantConfigurationValueRequest vre = new MgmtSystemTenantConfigurationValueRequest(); final NumberField nf = new NumberField(k, (double) intValue, event -> {
vre.setValue(event.getValue()); MgmtSystemTenantConfigurationValueRequest vre = new MgmtSystemTenantConfigurationValueRequest();
configValue.put(k, vre); vre.setValue(event.getValue());
}); configValue.put(k, vre);
nf.getElement().getStyle().set(WIDTH, PX_300); });
add(nf); nf.getElement().getStyle().set(WIDTH, PX_300);
} else { add(nf);
log.debug("Unexpected value type: {} -> {} (class: {})", }
default -> log.debug("Unexpected value type: {} -> {} (class: {})",
k, v.getValue(), v.getValue() == null ? "null" : v.getValue().getClass()); 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) { private static List<MgmtTargetFilterQuery> listFilters(HawkbitMgmtClient hawkbitClient) {
return Optional return Optional.ofNullable(hawkbitClient.getTargetFilterQueryRestApi()
.ofNullable( .getFilters(null, 0, 30, null, null).getBody())
hawkbitClient.getTargetFilterQueryRestApi() .map(PagedList<MgmtTargetFilterQuery>::getContent)
.getFilters(null, 0, 30, null, null) .orElseGet(List::of);
.getBody()
.getContent())
.orElse(Collections.emptyList());
} }
private ComponentEventListener<ClickEvent<Button>> createBtnListener(HawkbitMgmtClient hawkbitClient) { private ComponentEventListener<ClickEvent<Button>> createBtnListener(HawkbitMgmtClient hawkbitClient) {
@@ -409,11 +406,11 @@ public final class TargetView extends TableView<TargetView.TargetWithDs, String>
this.hawkbitClient = hawkbitClient; this.hawkbitClient = hawkbitClient;
description.setMinLength(2); description.setMinLength(2);
Stream.of( Stream.of(
description, description,
createdBy, createdAt, createdBy, createdAt,
lastModifiedBy, lastModifiedAt, lastModifiedBy, lastModifiedAt,
securityToken, lastPoll, group, targetAddress, targetAttributes securityToken, lastPoll, group, targetAddress, targetAttributes
) )
.forEach(field -> { .forEach(field -> {
field.setReadOnly(true); field.setReadOnly(true);
add(field); add(field);
@@ -483,18 +480,18 @@ public final class TargetView extends TableView<TargetView.TargetWithDs, String>
Optional.ofNullable(supplier.get()) Optional.ofNullable(supplier.get())
.map(ResponseEntity<MgmtDistributionSet>::getBody) .map(ResponseEntity<MgmtDistributionSet>::getBody)
.ifPresentOrElse(value -> { .ifPresentOrElse(value -> {
final String description = """ final String description = """
Name: %s Name: %s
Version: %s Version: %s
%s %s
""".replace("\n", System.lineSeparator()); """.replace("\n", System.lineSeparator());
textArea.setValueWithLink(description.formatted( textArea.setValueWithLink(description.formatted(
value.getName(), value.getName(),
value.getVersion(), value.getVersion(),
value.getModules().stream().map(module -> module.getTypeName() + ": " + module.getVersion()) value.getModules().stream().map(module -> module.getTypeName() + ": " + module.getVersion())
.collect(Collectors.joining(System.lineSeparator())) .collect(Collectors.joining(System.lineSeparator()))
), "q=id%3D%3D" + value.getId().toString()); ), "q=id%3D%3D" + value.getId().toString());
}, },
() -> textArea.setValueWithLink("", null)); () -> textArea.setValueWithLink("", null));
} }
} }
@@ -603,7 +600,7 @@ public final class TargetView extends TableView<TargetView.TargetWithDs, String>
int offset = 0; int offset = 0;
do { do {
List<MgmtTag> page = Optional.ofNullable( 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) .map(PagedList::getContent)
.orElse(Collections.emptyList()); .orElse(Collections.emptyList());
tags.addAll(page); tags.addAll(page);
@@ -665,7 +662,7 @@ public final class TargetView extends TableView<TargetView.TargetWithDs, String>
private void refreshMetadatas() { private void refreshMetadatas() {
metadataArea.setItems( metadataArea.setItems(
Optional.ofNullable( Optional.ofNullable(
hawkbitClient.getTargetRestApi().getMetadata(target.getControllerId()).getBody()) hawkbitClient.getTargetRestApi().getMetadata(target.getControllerId()).getBody())
.map(PagedList::getContent) .map(PagedList::getContent)
.orElse(Collections.emptyList())); .orElse(Collections.emptyList()));
} }
@@ -845,7 +842,7 @@ public final class TargetView extends TableView<TargetView.TargetWithDs, String>
request.setTargetType(type.getValue().getId()); request.setTargetType(type.getValue().getId());
} }
hawkbitClient.getTargetRestApi().createTargets( hawkbitClient.getTargetRestApi().createTargets(
List.of(request)) List.of(request))
.getBody() .getBody()
.stream() .stream()
.findFirst() .findFirst()
@@ -1091,9 +1088,8 @@ public final class TargetView extends TableView<TargetView.TargetWithDs, String>
public static TargetWithDs from(final HawkbitMgmtClient hawkbitClient, MgmtTarget target) { public static TargetWithDs from(final HawkbitMgmtClient hawkbitClient, MgmtTarget target) {
TargetWithDs targetWithDs = objectMapper.convertValue(target, TargetWithDs.class); TargetWithDs targetWithDs = objectMapper.convertValue(target, TargetWithDs.class);
targetWithDs.ds = Optional.ofNullable(hawkbitClient.getTargetRestApi().getInstalledDistributionSet(targetWithDs targetWithDs.ds = Optional.ofNullable(hawkbitClient.getTargetRestApi()
.getControllerId()) .getInstalledDistributionSet(targetWithDs.getControllerId()).getBody());
.getBody());
return targetWithDs; return targetWithDs;
} }