Skip to content

Commit

Permalink
Unify on Map.of
Browse files Browse the repository at this point in the history
  • Loading branch information
baldersheim committed Apr 11, 2024
1 parent ed76cd4 commit 42a9f71
Show file tree
Hide file tree
Showing 53 changed files with 121 additions and 251 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import com.yahoo.vdslib.state.ClusterState;
import com.yahoo.vdslib.state.Node;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
Expand Down Expand Up @@ -47,7 +46,7 @@ public AnnotatedClusterState(ClusterState clusterState,
Map<Node, NodeStateReason> nodeStateReasons) {
this.clusterState = Objects.requireNonNull(clusterState, "Cluster state cannot be null");
this.clusterStateReason = Objects.requireNonNull(clusterStateReason, "Cluster state reason cannot be null");
this.nodeStateReasons = Objects.requireNonNull(nodeStateReasons, "Node state reasons cannot be null");
this.nodeStateReasons = Map.copyOf(Objects.requireNonNull(nodeStateReasons, "Node state reasons cannot be null"));
}

public static AnnotatedClusterState emptyState() {
Expand All @@ -59,15 +58,15 @@ public static AnnotatedClusterState withoutAnnotations(ClusterState state) {
}

static Map<Node, NodeStateReason> emptyNodeStateReasons() {
return Collections.emptyMap();
return Map.of();
}

public ClusterState getClusterState() {
return clusterState;
}

public Map<Node, NodeStateReason> getNodeStateReasons() {
return Collections.unmodifiableMap(nodeStateReasons);
return nodeStateReasons;
}

public Optional<ClusterStateReason> getClusterStateReason() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import com.yahoo.vdslib.state.ClusterState;

import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
Expand Down Expand Up @@ -56,7 +55,7 @@ public static class FeedBlock {
public FeedBlock(boolean blockFeedInCluster, String description) {
this.blockFeedInCluster = blockFeedInCluster;
this.description = description;
this.concreteExhaustions = Collections.emptySet();
this.concreteExhaustions = Set.of();
}

public FeedBlock(boolean blockFeedInCluster, String description,
Expand Down Expand Up @@ -165,14 +164,10 @@ public ClusterStateBundle deriveAndBuild() {
return ClusterStateBundle.ofBaselineOnly(baselineState, feedBlock, deferredActivation);
}
Map<String, AnnotatedClusterState> derived;
if (explicitDerivedStates != null) {
derived = explicitDerivedStates;
} else {
derived = bucketSpaces.stream()
.collect(Collectors.toMap(
Function.identity(),
s -> stateDeriver.derivedFrom(baselineState, s)));
}
derived = Objects.requireNonNullElseGet(explicitDerivedStates, () -> bucketSpaces.stream()
.collect(Collectors.toUnmodifiableMap(
Function.identity(),
s -> stateDeriver.derivedFrom(baselineState, s))));
return new ClusterStateBundle(baselineState, derived, feedBlock, deferredActivation);
}
}
Expand All @@ -186,7 +181,7 @@ private ClusterStateBundle(AnnotatedClusterState baselineState,
FeedBlock feedBlock,
boolean deferredActivation) {
this.baselineState = baselineState;
this.derivedBucketSpaceStates = Collections.unmodifiableMap(derivedBucketSpaceStates);
this.derivedBucketSpaceStates = Map.copyOf(derivedBucketSpaceStates);
this.feedBlock = feedBlock;
this.deferredActivation = deferredActivation;
}
Expand All @@ -209,11 +204,11 @@ public static ClusterStateBundle of(AnnotatedClusterState baselineState,
public static ClusterStateBundle ofBaselineOnly(AnnotatedClusterState baselineState,
FeedBlock feedBlock,
boolean deferredActivation) {
return new ClusterStateBundle(baselineState, Collections.emptyMap(), feedBlock, deferredActivation);
return new ClusterStateBundle(baselineState, Map.of(), feedBlock, deferredActivation);
}

public static ClusterStateBundle ofBaselineOnly(AnnotatedClusterState baselineState) {
return new ClusterStateBundle(baselineState, Collections.emptyMap());
return new ClusterStateBundle(baselineState, Map.of());
}

public static ClusterStateBundle empty() {
Expand All @@ -238,7 +233,7 @@ public ClusterStateBundle cloneWithMapper(Function<ClusterState, ClusterState> m
AnnotatedClusterState clonedBaseline = baselineState.cloneWithClusterState(
mapper.apply(baselineState.getClusterState().clone()));
Map<String, AnnotatedClusterState> clonedDerived = derivedBucketSpaceStates.entrySet().stream()
.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().cloneWithClusterState(
.collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().cloneWithClusterState(
mapper.apply(e.getValue().getClusterState().clone()))));
return new ClusterStateBundle(clonedBaseline, clonedDerived, feedBlock, deferredActivation);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@

import java.time.Duration;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
Expand Down Expand Up @@ -433,7 +432,7 @@ public static class Builder {
private double minMergeCompletionRatio = 1.0;
private int maxDivergentNodesPrintedInTaskErrorMessages = 10;
private boolean clusterFeedBlockEnabled = false;
private Map<String, Double> clusterFeedBlockLimit = Collections.emptyMap();
private Map<String, Double> clusterFeedBlockLimit = Map.of();
private double clusterFeedBlockNoiseLevel = 0.01;
private int maxNumberOfGroupsAllowedToBeDown = 1;
private Function<FleetControllerContext, DatabaseFactory> dbFactoryFn = ZooKeeperDatabaseFactory::new;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,10 @@ public EncodedClusterStateBundle encode(ClusterStateBundle stateBundle) {
// TODO add another function that is not toString for this..!
states.setString("baseline", stateBundle.getBaselineClusterState().toString());
Cursor spaces = states.setObject("spaces");
stateBundle.getDerivedBucketSpaceStates().entrySet()
.forEach(entry -> spaces.setString(entry.getKey(), entry.getValue().toString()));
stateBundle.getDerivedBucketSpaceStates().forEach((key, value) -> spaces.setString(key, value.toString()));

// Only bother to encode feed block state if cluster is actually blocked
if (stateBundle.getFeedBlock().map(fb -> fb.blockFeedInCluster()).orElse(false)) {
if (stateBundle.getFeedBlock().map(ClusterStateBundle.FeedBlock::blockFeedInCluster).orElse(false)) {
Cursor feedBlock = root.setObject("feed-block");
feedBlock.setBool("block-feed-in-cluster", true);
feedBlock.setString("description", stateBundle.getFeedBlock().get().getDescription());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@ public class ClusterStateBundleUtil {

public static ClusterStateBundle.Builder makeBundleBuilder(String baselineState, StateMapping... bucketSpaceStates) {
return ClusterStateBundle.builder(AnnotatedClusterState.withoutAnnotations(ClusterState.stateFromString(baselineState)))
.explicitDerivedStates(Stream.of(bucketSpaceStates).collect(Collectors.toMap(sm -> sm.bucketSpace,
.explicitDerivedStates(Stream.of(bucketSpaceStates).collect(Collectors.toUnmodifiableMap(sm -> sm.bucketSpace,
sm -> AnnotatedClusterState.withoutAnnotations(sm.state))));
}

public static ClusterStateBundle makeBundle(String baselineState, StateMapping... bucketSpaceStates) {
return ClusterStateBundle.of(AnnotatedClusterState.withoutAnnotations(ClusterState.stateFromString(baselineState)),
Stream.of(bucketSpaceStates).collect(Collectors.toMap(sm -> sm.bucketSpace,
Stream.of(bucketSpaceStates).collect(Collectors.toUnmodifiableMap(sm -> sm.bucketSpace,
sm -> AnnotatedClusterState.withoutAnnotations(sm.state))));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;

Expand Down Expand Up @@ -53,7 +52,7 @@ public void before() throws IOException {
statsAggregator,
1.0,
10,
Collections.emptyMap(),
Map.of(),
eventLog,
"pathPrefix",
"name");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import org.junit.jupiter.api.Test;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;

Expand Down Expand Up @@ -46,20 +46,20 @@ void disk_and_memory_utilization_is_zero_if_no_samples_are_available() {

@Test
void nodes_above_limit_is_zero_without_feed_block_status() {
var stats = ResourceUsageStats.calculateFrom(Collections.emptyList(), Collections.emptyMap(), Optional.empty());
var stats = ResourceUsageStats.calculateFrom(List.of(), Map.of(), Optional.empty());
assertEquals(0, stats.getNodesAboveLimit());
}

@Test
void nodes_above_limit_is_equal_to_node_resource_exhaustions() {
var stats = ResourceUsageStats.calculateFrom(Collections.emptyList(), Collections.emptyMap(),
var stats = ResourceUsageStats.calculateFrom(List.of(), Map.of(),
createFeedBlock(exhaustion(1, "disk"), exhaustion(2, "memory")));
assertEquals(2, stats.getNodesAboveLimit());
}

@Test
void nodes_above_limit_counts_each_node_only_once() {
var stats = ResourceUsageStats.calculateFrom(Collections.emptyList(), Collections.emptyMap(),
var stats = ResourceUsageStats.calculateFrom(List.of(), Map.of(),
createFeedBlock(exhaustion(1, "disk"), exhaustion(1, "memory")));
assertEquals(1, stats.getNodesAboveLimit());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
import java.io.IOException;
import java.io.Reader;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
Expand Down Expand Up @@ -213,11 +212,11 @@ default Optional<AllocatedHosts> getAllocatedHosts() {
}

default Map<Version, FileRegistry> getFileRegistries() {
return Collections.emptyMap();
return Map.of();
}

default Map<String, String> legacyOverrides() {
return Collections.emptyMap();
return Map.of();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import com.google.common.collect.ImmutableSet;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
Expand All @@ -25,7 +24,7 @@
*/
public class Notifications {

private static final Notifications none = new Notifications(Collections.emptyMap(), Collections.emptyMap());
private static final Notifications none = new Notifications(Map.of(), Map.of());
public static Notifications none() { return none; }

private final Map<When, List<String>> emailAddresses;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import com.yahoo.config.provision.TenantName;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
Expand All @@ -23,7 +22,7 @@ public class SuperModel {
private final boolean complete;

public SuperModel() {
this(Collections.emptyMap(), false);
this(Map.of(), false);
}

public SuperModel(Map<ApplicationId, ApplicationInfo> models, boolean complete) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import com.yahoo.vespa.config.ConfigDefinitionKey;
import com.yahoo.vespa.config.buildergen.ConfigDefinition;

import java.util.Collections;
import java.util.Map;

/**
Expand All @@ -24,7 +23,7 @@ public StaticConfigDefinitionRepo() {
this.repo = new ConfigDefinitionRepo() {
@Override
public Map<ConfigDefinitionKey, ConfigDefinition> getConfigDefinitions() {
return Collections.emptyMap();
return Map.of();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@

import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
Expand Down Expand Up @@ -75,7 +74,7 @@ private HostStatus createHostStatusFromResponse(String hostname, Request request
if (request.isError()) {
return new HostStatus(hostname,
Status.UNKNOWN,
Collections.emptyMap(),
Map.of(),
"error: " + request.errorMessage() + "(" + request.errorCode() + ")");
} else {
Map<String, Double> fileReferenceStatuses = new HashMap<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@
import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
Expand Down Expand Up @@ -131,7 +130,7 @@ public RpcServer(ConfigserverConfig config, SuperModelRequestHandler superModelR
this.superModelRequestHandler = superModelRequestHandler;
metricUpdaterFactory = metrics;
supervisor.setMaxOutputBufferSize(config.maxoutputbuffersize());
this.metrics = metrics.getOrCreateMetricUpdater(Collections.emptyMap());
this.metrics = metrics.getOrCreateMetricUpdater(Map.of());
BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(config.maxgetconfigclients());
int rpcWorkerThreads = (config.numRpcThreads() == 0) ? threadsToUse() : config.numRpcThreads();
executorService = new ThreadPoolExecutor(rpcWorkerThreads, rpcWorkerThreads,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ public TenantRepository(HostRegistry hostRegistry,
this.configserverConfig = configserverConfig;
this.curator = curator;
this.metrics = metrics;
metricUpdater = metrics.getOrCreateMetricUpdater(Collections.emptyMap());
metricUpdater = metrics.getOrCreateMetricUpdater(Map.of());
this.zkCacheExecutor = zkCacheExecutor;
this.zkApplicationWatcherExecutor = zkApplicationWatcherExecutor;
this.zkSessionWatcherExecutor = zkSessionWatcherExecutor;
Expand Down Expand Up @@ -312,7 +312,7 @@ private void bootstrapTenants() {
}
}

if (failed.size() > 0)
if (!failed.isEmpty())
throw new RuntimeException("Could not create all tenants when bootstrapping, failed to create: " + failed);

metricUpdater.setTenants(tenants.size());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
Expand Down Expand Up @@ -93,7 +92,7 @@ public void setupRepo() throws IOException {
@Ignore
@Test
public void require_that_from_parameter_cannot_be_set_if_data_in_request() throws IOException {
HttpRequest request = post(Collections.singletonMap("from", "active"));
HttpRequest request = post(Map.of("from", "active"));
HttpResponse response = createHandler().handle(request);
assertHttpStatusCodeErrorCodeAndMessage(response, BAD_REQUEST, HttpErrorResponse.ErrorCode.BAD_REQUEST, "Parameter 'from' is illegal for POST");
}
Expand All @@ -114,14 +113,14 @@ public void require_that_post_request_must_have_correct_content_type() throws IO

private void assertIllegalFromParameter(String fromValue) throws IOException {
File outFile = CompressedApplicationInputStreamTest.createTarFile(temporaryFolder.getRoot().toPath());
HttpRequest request = post(outFile, postHeaders, Collections.singletonMap("from", fromValue));
HttpRequest request = post(outFile, postHeaders, Map.of("from", fromValue));
assertHttpStatusCodeErrorCodeAndMessage(createHandler().handle(request), BAD_REQUEST, HttpErrorResponse.ErrorCode.BAD_REQUEST, "Parameter 'from' has illegal value '" + fromValue + "'");
}

@Test
public void require_that_prepare_url_is_returned_on_success() throws IOException {
File outFile = CompressedApplicationInputStreamTest.createTarFile(temporaryFolder.getRoot().toPath());
Map<String, String> parameters = Collections.singletonMap("name", "foo");
Map<String, String> parameters = Map.of("name", "foo");
HttpResponse response = createHandler().handle(post(outFile, postHeaders, parameters));
assertNotNull(response);
assertEquals(OK, response.getStatus());
Expand Down Expand Up @@ -160,7 +159,7 @@ public void require_that_handler_unpacks_application() throws IOException {
@Test
public void require_that_application_urls_can_be_given_as_from_parameter() throws Exception {
ApplicationId applicationId = ApplicationId.from(tenant.value(), "foo", "quux");
HttpRequest request = post(Collections.singletonMap(
HttpRequest request = post(Map.of(
"from",
"http://myhost:40555/application/v2/tenant/" + tenant + "/application/foo/environment/test/region/baz/instance/quux"));
assertEquals(applicationId, SessionCreateHandler.getFromApplicationId(request));
Expand All @@ -180,7 +179,7 @@ public void require_that_from_parameter_must_be_valid() throws IOException {
public void require_that_content_type_is_parsed_correctly() throws FileNotFoundException {
HttpRequest request = post(new ByteArrayInputStream("foo".getBytes(StandardCharsets.UTF_8)),
Map.of("Content-Type", "multipart/form-data; charset=ISO-8859-1; boundary=g5gJAzUWl_t6"),
Collections.emptyMap());
Map.of());

// Valid header should validate ok
SessionCreateHandler.validateDataAndHeader(request, List.of(ContentType.MULTIPART_FORM_DATA.getMimeType()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ public BundleContext getBundleContext() {

@Override
public Map<X509Certificate, List<X509Certificate>> getSignerCertificates(int signersType) {
return Collections.emptyMap();
return Map.of();
}

@SuppressWarnings("unchecked")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,7 @@ private static Map<String, String> copyProperties(Map<String, List<String>> para
Map<String, String> mask;
Map<String, String> view;

mask = Objects.requireNonNullElse(parameterMask, Collections.emptyMap());
mask = Objects.requireNonNullElse(parameterMask, Map.of());
view = new HashMap<>(parameters.size() + mask.size());
for (Map.Entry<String, List<String>> parameter : parameters.entrySet()) {
if (existsAsOriginalParameter(parameter.getValue())) {
Expand Down
Loading

0 comments on commit 42a9f71

Please sign in to comment.