Skip to content

Commit

Permalink
refactor: clean-up (#2325)
Browse files Browse the repository at this point in the history
Signed-off-by: Chris Laprun <claprun@redhat.com>
Co-authored-by: Attila Mészáros <csviri@gmail.com>
Signed-off-by: Attila Mészáros <csviri@gmail.com>
  • Loading branch information
metacosm and csviri committed Jun 17, 2024
1 parent 397d93a commit c1fcabe
Show file tree
Hide file tree
Showing 30 changed files with 169 additions and 131 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public class Bootstrapper {

private static final Logger log = LoggerFactory.getLogger(Bootstrapper.class);

private MustacheFactory mustacheFactory = new DefaultMustacheFactory();
private final MustacheFactory mustacheFactory = new DefaultMustacheFactory();

// .gitignore gets excluded from resource, using here a prefixed version
private static final Map<String, String> TOP_LEVEL_STATIC_FILES =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public final class BuilderUtils {
// prevent instantiation of util class
private BuilderUtils() {}

public static final <T, B> B newBuilder(Class<B> builderType, T item) {
public static <T, B> B newBuilder(Class<B> builderType, T item) {
Class<T> builderTargetType = builderTargetType(builderType);
try {
Constructor<B> constructor = builderType.getDeclaredConstructor(builderTargetType);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import java.util.Objects;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import io.fabric8.kubernetes.api.builder.Builder;
import io.fabric8.kubernetes.api.model.GenericKubernetesResource;
Expand Down Expand Up @@ -126,8 +125,7 @@ public static boolean specsEqual(HasMetadata r1, HasMetadata r2) {
// will be replaced with: https://github.com/fabric8io/kubernetes-client/issues/3816
public static Object getSpec(HasMetadata resource) {
// optimize CustomResource case
if (resource instanceof CustomResource) {
CustomResource cr = (CustomResource) resource;
if (resource instanceof CustomResource cr) {
return cr.getSpec();
}

Expand All @@ -142,8 +140,7 @@ public static Object getSpec(HasMetadata resource) {
@SuppressWarnings("unchecked")
public static Object setSpec(HasMetadata resource, Object spec) {
// optimize CustomResource case
if (resource instanceof CustomResource) {
CustomResource cr = (CustomResource) resource;
if (resource instanceof CustomResource cr) {
cr.setSpec(spec);
return null;
}
Expand Down Expand Up @@ -191,8 +188,7 @@ public static void handleKubernetesClientException(Exception e, String resourceT
throw ((MissingCRDException) e);
}

if (e instanceof KubernetesClientException) {
KubernetesClientException ke = (KubernetesClientException) e;
if (e instanceof KubernetesClientException ke) {
// only throw MissingCRDException if the 404 error occurs on the target CRD
if (404 == ke.getCode() &&
(resourceTypeName.equals(ke.getFullResourceName())
Expand All @@ -217,7 +213,7 @@ private static boolean matchesResourceType(String resourceTypeName,
group = group.substring(0, group.length() - 1);
}
final var segments = Arrays.stream(group.split("/")).filter(Predicate.not(String::isEmpty))
.collect(Collectors.toUnmodifiableList());
.toList();
if (segments.size() != 3) {
return false;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -260,8 +260,7 @@ private static <T> Configurator<T> configuratorFor(Class<T> instanceType,

@SuppressWarnings({"unchecked", "rawtypes"})
private static void configureFromAnnotatedReconciler(Object instance, Reconciler<?> reconciler) {
if (instance instanceof AnnotationConfigurable) {
AnnotationConfigurable configurable = (AnnotationConfigurable) instance;
if (instance instanceof AnnotationConfigurable configurable) {
final Class<? extends Annotation> configurationClass =
(Class<? extends Annotation>) Utils.getFirstTypeArgumentFromSuperClassOrInterface(
instance.getClass(), AnnotationConfigurable.class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.client.informers.cache.ItemStore;
import io.javaoperatorsdk.operator.api.config.dependent.DependentResourceSpec;
import io.javaoperatorsdk.operator.api.config.workflow.WorkflowSpec;
import io.javaoperatorsdk.operator.processing.event.rate.RateLimiter;
import io.javaoperatorsdk.operator.processing.event.source.filter.GenericFilter;
import io.javaoperatorsdk.operator.processing.event.source.filter.OnAddFilter;
Expand Down Expand Up @@ -39,7 +38,6 @@ public class ControllerConfigurationOverrider<R extends HasMetadata> {
private String name;
private String fieldManager;
private Long informerListLimit;
private WorkflowSpec workflowSpec;

private ControllerConfigurationOverrider(ControllerConfiguration<R> original) {
this.finalizer = original.getFinalizerName();
Expand All @@ -57,7 +55,6 @@ private ControllerConfigurationOverrider(ControllerConfiguration<R> original) {
this.fieldManager = original.fieldManager();
this.informerListLimit = original.getInformerListLimit().orElse(null);
this.itemStore = original.getItemStore().orElse(null);
this.workflowSpec = original.getWorkflowSpec().orElse(null);
}

public ControllerConfigurationOverrider<R> withFinalizer(String finalizer) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@

import static io.javaoperatorsdk.operator.api.config.LeaderElectionConfiguration.*;

@SuppressWarnings("unused")
public final class LeaderElectionConfigurationBuilder {

private String leaseName;
private final String leaseName;
private String leaseNamespace;
private String identity;
private Duration leaseDuration = LEASE_DURATION_DEFAULT_VALUE;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package io.javaoperatorsdk.operator.api.config;

import java.time.Duration;
import java.util.*;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import io.fabric8.kubernetes.api.model.HasMetadata;
Expand Down Expand Up @@ -105,7 +108,6 @@ protected ResolvedControllerConfiguration(Class<P> resourceClass, String name,
this.finalizer =
ControllerConfiguration.ensureValidFinalizerName(finalizer, getResourceTypeName());
this.fieldManager = fieldManager;
this.workflowSpec = workflowSpec;
}

protected ResolvedControllerConfiguration(Class<P> resourceClass, String name,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,7 @@ private DependentResourceConfigurationResolver() {}

public static <C extends ControllerConfiguration<? extends HasMetadata>> void configure(
DependentResource dependentResource, DependentResourceSpec spec, C parentConfiguration) {
if (dependentResource instanceof DependentResourceConfigurator) {
final var configurator = (DependentResourceConfigurator) dependentResource;
if (dependentResource instanceof DependentResourceConfigurator configurator) {
final var config = configurationFor(spec, parentConfiguration);
configurator.configureWith(config);
}
Expand All @@ -33,8 +32,7 @@ public static <C extends ControllerConfiguration<? extends HasMetadata>> Object
DependentResourceSpec spec, C parentConfiguration) {

// first check if the parent configuration has potentially already resolved the configuration
if (parentConfiguration instanceof DependentResourceConfigurationProvider) {
final var provider = (DependentResourceConfigurationProvider) parentConfiguration;
if (parentConfiguration instanceof DependentResourceConfigurationProvider provider) {
final var configuration = provider.getConfigurationFor(spec);
if (configuration != null) {
return configuration;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -239,8 +239,7 @@ public void initAndRegisterEventSources(EventSourceContext<P> context) {
final var size = dependentResourcesByName.size();
if (size > 0) {
dependentResourcesByName.forEach((key, dependentResource) -> {
if (dependentResource instanceof EventSourceProvider) {
final var provider = (EventSourceProvider) dependentResource;
if (dependentResource instanceof EventSourceProvider provider) {
final var source = provider.initEventSource(context);
eventSourceManager.registerEventSource(key, source);
} else {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@
package io.javaoperatorsdk.operator.processing.dependent.kubernetes;

import java.util.*;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import java.util.Optional;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand All @@ -22,7 +31,7 @@
* <p>
* The basis of algorithm is to extract the fields managed we convert resources to Map/List
* composition. The actual resource (from the server) is pruned, all the fields which are not
* mentioed in managedFields of the target manager is removed. Some irrelevant fields are also
* mentioned in managedFields of the target manager is removed. Some irrelevant fields are also
* removed from desired. And the two resulted Maps are compared for equality. The implementation is
* a bit nasty since have to deal with some specific cases of managedFields format.
* </p>
Expand Down Expand Up @@ -104,10 +113,8 @@ public boolean matches(R actual, R desired, Context<?> context) {
/**
* Correct for known issue with SSA
*/
@SuppressWarnings("unchecked")
private void sanitizeState(R actual, R desired, Map<String, Object> actualMap) {
if (desired instanceof StatefulSet) {
StatefulSet desiredStatefulSet = (StatefulSet) desired;
if (desired instanceof StatefulSet desiredStatefulSet) {
StatefulSet actualStatefulSet = (StatefulSet) actual;
int claims = desiredStatefulSet.getSpec().getVolumeClaimTemplates().size();
if (claims == actualStatefulSet.getSpec().getVolumeClaimTemplates().size()) {
Expand Down Expand Up @@ -321,12 +328,12 @@ private static java.util.Map.Entry<Integer, Map<String, Object>> selectListEntry
}
if (possibleTargets.isEmpty()) {
throw new IllegalStateException("Cannot find list element for key:" + key + ", in map: "
+ values.stream().map(Map::keySet).collect(Collectors.toList()));
+ values.stream().map(Map::keySet).toList());
}
if (possibleTargets.size() > 1) {
throw new IllegalStateException(
"More targets found in list element for key:" + key + ", in map: "
+ values.stream().map(Map::keySet).collect(Collectors.toList()));
+ values.stream().map(Map::keySet).toList());
}
final var finalIndex = index;
return new AbstractMap.SimpleEntry<>(finalIndex, possibleTargets.get(0));
Expand All @@ -339,7 +346,7 @@ private Optional<ManagedFieldsEntry> checkIfFieldManagerExists(R actual, String
// field manager name.
.filter(
f -> f.getManager().equals(fieldManager) && f.getOperation().equals(APPLY_OPERATION))
.collect(Collectors.toList());
.toList();
if (targetManagedFields.isEmpty()) {
log.debug("No field manager exists for resource {} with name: {} and operation Apply ",
actual.getKind(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -166,8 +166,7 @@ private void submitReconciliationExecution(ResourceState state) {

private void handleEventMarking(Event event, ResourceState state) {
final var relatedCustomResourceID = event.getRelatedCustomResourceID();
if (event instanceof ResourceEvent) {
var resourceEvent = (ResourceEvent) event;
if (event instanceof ResourceEvent resourceEvent) {
if (resourceEvent.getAction() == ResourceAction.DELETED) {
log.debug("Marking delete event received for: {}", relatedCustomResourceID);
state.markDeleteEventReceived();
Expand Down Expand Up @@ -331,8 +330,8 @@ private void handleRetryOnException(
private void retryAwareErrorLogging(RetryExecution retry, boolean eventPresent,
Exception exception,
ExecutionScope<P> executionScope) {
if (!eventPresent && !retry.isLastAttempt() && exception instanceof KubernetesClientException) {
KubernetesClientException ex = (KubernetesClientException) exception;
if (!eventPresent && !retry.isLastAttempt()
&& exception instanceof KubernetesClientException ex) {
if (ex.getCode() == HttpURLConnection.HTTP_CONFLICT) {
log.debug("Full client conflict error during event processing {}", executionScope,
exception);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
package io.javaoperatorsdk.operator.processing.event;

import java.util.*;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
Expand Down Expand Up @@ -104,8 +109,7 @@ public synchronized void stop() {
@SuppressWarnings("rawtypes")
private void logEventSourceEvent(NamedEventSource eventSource, String event) {
if (log.isDebugEnabled()) {
if (eventSource.original() instanceof ResourceEventSource) {
ResourceEventSource source = (ResourceEventSource) eventSource.original();
if (eventSource.original() instanceof ResourceEventSource source) {
log.debug("{} event source {} for {}", event,
eventSource.isNameSet() ? eventSource.name() : eventSource,
source.resourceType());
Expand Down Expand Up @@ -152,8 +156,7 @@ public final synchronized void registerEventSource(String name, EventSource even
if (name == null || name.isBlank()) {
name = EventSourceUtils.generateNameFor(eventSource);
}
if (eventSource instanceof ManagedInformerEventSource) {
var managedInformerEventSource = ((ManagedInformerEventSource) eventSource);
if (eventSource instanceof ManagedInformerEventSource managedInformerEventSource) {
managedInformerEventSource.setConfigurationService(
controller.getConfiguration().getConfigurationService());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,7 @@ public Class<?> type() {
@Override
@SuppressWarnings({"rawtypes", "unchecked"})
public Optional<Class<?>> resourceType() {
if (original instanceof ResourceEventSource) {
ResourceEventSource resourceEventSource = (ResourceEventSource) original;
if (original instanceof ResourceEventSource resourceEventSource) {
return Optional.of(resourceEventSource.resourceType());
}
return Optional.empty();
Expand All @@ -59,8 +58,7 @@ public Optional<Class<?>> resourceType() {
@Override
@SuppressWarnings("rawtypes")
public Optional<?> configuration() {
if (original instanceof Configurable) {
Configurable configurable = (Configurable) original;
if (original instanceof Configurable configurable) {
return Optional.ofNullable(configurable.configuration());
}
return Optional.empty();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,10 @@ public LinearRateLimiter(Duration refreshPeriod, int limitForPeriod) {

@Override
public Optional<Duration> isLimited(RateLimitState rateLimitState) {
if (!isActivated() || !(rateLimitState instanceof RateState)) {
if (!isActivated() || !(rateLimitState instanceof RateState actualState)) {
return Optional.empty();
}

var actualState = (RateState) rateLimitState;
if (actualState.getCount() < limitForPeriod) {
actualState.increaseCount();
return Optional.empty();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
package io.javaoperatorsdk.operator.processing.event.source;

import java.util.*;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
Expand Down Expand Up @@ -90,8 +97,7 @@ protected synchronized void handleResources(ResourceID primaryID, Set<R> newReso
}

protected synchronized void handleResources(Map<ResourceID, Set<R>> allNewResources) {
var toDelete = cache.keySet().stream().filter(k -> !allNewResources.containsKey(k))
.collect(Collectors.toList());
var toDelete = cache.keySet().stream().filter(k -> !allNewResources.containsKey(k)).toList();
toDelete.forEach(this::handleDelete);
allNewResources.forEach(this::handleResources);
}
Expand Down Expand Up @@ -153,21 +159,15 @@ private boolean acceptedByFiler(Map<String, R> cachedResourceMap,
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

if (onUpdateFilter != null || genericFilter != null) {
var anyUpdated = possibleUpdatedResources.entrySet().stream()
return possibleUpdatedResources.entrySet().stream()
.anyMatch(
entry -> {
var newResource = newResourcesMap.get(entry.getKey());
return acceptedByGenericFiler(newResource) &&
onUpdateFilter.accept(newResource, entry.getValue());
});
if (anyUpdated) {
return true;
}
} else if (!possibleUpdatedResources.isEmpty()) {
return true;
}

return false;
} else
return !possibleUpdatedResources.isEmpty();
}

private boolean acceptedByGenericFiler(R resource) {
Expand Down
Loading

0 comments on commit c1fcabe

Please sign in to comment.