Ban ImmutableMap$Builder in core's main

Almost there!
This commit is contained in:
Nik Everett 2015-10-05 15:42:17 -04:00
parent ba68a8df63
commit 380dbbfb23
37 changed files with 376 additions and 301 deletions

View File

@ -19,14 +19,19 @@
package org.apache.lucene.queryparser.classic; package org.apache.lucene.queryparser.classic;
import com.google.common.collect.ImmutableMap;
import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.index.Term; import org.apache.lucene.index.Term;
import org.apache.lucene.search.*; import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.util.automaton.RegExp; import org.apache.lucene.search.DisjunctionMaxQuery;
import org.apache.lucene.search.FuzzyQuery;
import org.apache.lucene.search.MatchNoDocsQuery;
import org.apache.lucene.search.MultiPhraseQuery;
import org.apache.lucene.search.PhraseQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.util.IOUtils; import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.automaton.RegExp;
import org.elasticsearch.common.lucene.search.Queries; import org.elasticsearch.common.lucene.search.Queries;
import org.elasticsearch.common.unit.Fuzziness; import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.mapper.MappedFieldType; import org.elasticsearch.index.mapper.MappedFieldType;
@ -38,9 +43,12 @@ import org.elasticsearch.index.query.support.QueryParsers;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Objects; import java.util.Objects;
import static java.util.Collections.unmodifiableMap;
import static org.elasticsearch.common.lucene.search.Queries.fixNegativeQueryIfNeeded; import static org.elasticsearch.common.lucene.search.Queries.fixNegativeQueryIfNeeded;
/** /**
@ -52,13 +60,13 @@ import static org.elasticsearch.common.lucene.search.Queries.fixNegativeQueryIfN
*/ */
public class MapperQueryParser extends QueryParser { public class MapperQueryParser extends QueryParser {
public static final ImmutableMap<String, FieldQueryExtension> fieldQueryExtensions; public static final Map<String, FieldQueryExtension> FIELD_QUERY_EXTENSIONS;
static { static {
fieldQueryExtensions = ImmutableMap.<String, FieldQueryExtension>builder() Map<String, FieldQueryExtension> fieldQueryExtensions = new HashMap<>();
.put(ExistsFieldQueryExtension.NAME, new ExistsFieldQueryExtension()) fieldQueryExtensions.put(ExistsFieldQueryExtension.NAME, new ExistsFieldQueryExtension());
.put(MissingFieldQueryExtension.NAME, new MissingFieldQueryExtension()) fieldQueryExtensions.put(MissingFieldQueryExtension.NAME, new MissingFieldQueryExtension());
.build(); FIELD_QUERY_EXTENSIONS = unmodifiableMap(fieldQueryExtensions);
} }
private final QueryShardContext context; private final QueryShardContext context;
@ -124,7 +132,7 @@ public class MapperQueryParser extends QueryParser {
@Override @Override
public Query getFieldQuery(String field, String queryText, boolean quoted) throws ParseException { public Query getFieldQuery(String field, String queryText, boolean quoted) throws ParseException {
FieldQueryExtension fieldQueryExtension = fieldQueryExtensions.get(field); FieldQueryExtension fieldQueryExtension = FIELD_QUERY_EXTENSIONS.get(field);
if (fieldQueryExtension != null) { if (fieldQueryExtension != null) {
return fieldQueryExtension.query(context, queryText); return fieldQueryExtension.query(context, queryText);
} }
@ -540,7 +548,7 @@ public class MapperQueryParser extends QueryParser {
return newMatchAllDocsQuery(); return newMatchAllDocsQuery();
} }
// effectively, we check if a field exists or not // effectively, we check if a field exists or not
return fieldQueryExtensions.get(ExistsFieldQueryExtension.NAME).query(context, actualField); return FIELD_QUERY_EXTENSIONS.get(ExistsFieldQueryExtension.NAME).query(context, actualField);
} }
} }
if (lowercaseExpandedTerms) { if (lowercaseExpandedTerms) {

View File

@ -19,8 +19,6 @@
package org.elasticsearch.action.admin.cluster.node.info; package org.elasticsearch.action.admin.cluster.node.info;
import com.google.common.collect.ImmutableMap;
import org.elasticsearch.Build; import org.elasticsearch.Build;
import org.elasticsearch.Version; import org.elasticsearch.Version;
import org.elasticsearch.action.support.nodes.BaseNodeResponse; import org.elasticsearch.action.support.nodes.BaseNodeResponse;
@ -37,8 +35,11 @@ import org.elasticsearch.threadpool.ThreadPoolInfo;
import org.elasticsearch.transport.TransportInfo; import org.elasticsearch.transport.TransportInfo;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import static java.util.Collections.unmodifiableMap;
/** /**
* Node information (static, does not change over time). * Node information (static, does not change over time).
*/ */
@ -187,12 +188,12 @@ public class NodeInfo extends BaseNodeResponse {
version = Version.readVersion(in); version = Version.readVersion(in);
build = Build.readBuild(in); build = Build.readBuild(in);
if (in.readBoolean()) { if (in.readBoolean()) {
ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); Map<String, String> builder = new HashMap<>();
int size = in.readVInt(); int size = in.readVInt();
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
builder.put(in.readString(), in.readString()); builder.put(in.readString(), in.readString());
} }
serviceAttributes = builder.build(); serviceAttributes = unmodifiableMap(builder);
} }
if (in.readBoolean()) { if (in.readBoolean()) {
settings = Settings.readSettingsFromStream(in); settings = Settings.readSettingsFromStream(in);

View File

@ -19,6 +19,8 @@
package org.elasticsearch.action.admin.cluster.node.info; package org.elasticsearch.action.admin.cluster.node.info;
import com.carrotsearch.hppc.cursors.ObjectObjectCursor;
import org.elasticsearch.action.support.nodes.BaseNodesResponse; import org.elasticsearch.action.support.nodes.BaseNodesResponse;
import org.elasticsearch.cluster.ClusterName; import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamInput;
@ -85,8 +87,8 @@ public class NodesInfoResponse extends BaseNodesResponse<NodeInfo> implements To
if (!nodeInfo.getNode().attributes().isEmpty()) { if (!nodeInfo.getNode().attributes().isEmpty()) {
builder.startObject("attributes"); builder.startObject("attributes");
for (Map.Entry<String, String> attr : nodeInfo.getNode().attributes().entrySet()) { for (ObjectObjectCursor<String, String> attr : nodeInfo.getNode().attributes()) {
builder.field(attr.getKey(), attr.getValue(), XContentBuilder.FieldCaseConversion.NONE); builder.field(attr.key, attr.value, XContentBuilder.FieldCaseConversion.NONE);
} }
builder.endObject(); builder.endObject();
} }

View File

@ -19,6 +19,8 @@
package org.elasticsearch.action.admin.cluster.node.stats; package org.elasticsearch.action.admin.cluster.node.stats;
import com.carrotsearch.hppc.cursors.ObjectObjectCursor;
import org.elasticsearch.action.support.nodes.BaseNodeResponse; import org.elasticsearch.action.support.nodes.BaseNodeResponse;
import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Nullable;
@ -38,7 +40,6 @@ import org.elasticsearch.threadpool.ThreadPoolStats;
import org.elasticsearch.transport.TransportStats; import org.elasticsearch.transport.TransportStats;
import java.io.IOException; import java.io.IOException;
import java.util.Map;
/** /**
* Node statistics (dynamic, changes depending on when created). * Node statistics (dynamic, changes depending on when created).
@ -281,8 +282,8 @@ public class NodeStats extends BaseNodeResponse implements ToXContent {
if (!getNode().attributes().isEmpty()) { if (!getNode().attributes().isEmpty()) {
builder.startObject("attributes"); builder.startObject("attributes");
for (Map.Entry<String, String> attr : getNode().attributes().entrySet()) { for (ObjectObjectCursor<String, String> attr : getNode().attributes()) {
builder.field(attr.getKey(), attr.getValue(), XContentBuilder.FieldCaseConversion.NONE); builder.field(attr.key, attr.value, XContentBuilder.FieldCaseConversion.NONE);
} }
builder.endObject(); builder.endObject();
} }

View File

@ -19,16 +19,18 @@
package org.elasticsearch.action.admin.cluster.snapshots.status; package org.elasticsearch.action.admin.cluster.snapshots.status;
import com.google.common.collect.ImmutableMap;
import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentBuilderString; import org.elasticsearch.common.xcontent.XContentBuilderString;
import java.io.IOException; import java.io.IOException;
import java.util.Collection; import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
import static java.util.Collections.unmodifiableMap;
/** /**
* Represents snapshot status of all shards in the index * Represents snapshot status of all shards in the index
*/ */
@ -45,14 +47,14 @@ public class SnapshotIndexStatus implements Iterable<SnapshotIndexShardStatus>,
SnapshotIndexStatus(String index, Collection<SnapshotIndexShardStatus> shards) { SnapshotIndexStatus(String index, Collection<SnapshotIndexShardStatus> shards) {
this.index = index; this.index = index;
ImmutableMap.Builder<Integer, SnapshotIndexShardStatus> builder = ImmutableMap.builder(); Map<Integer, SnapshotIndexShardStatus> indexShards = new HashMap<>();
stats = new SnapshotStats(); stats = new SnapshotStats();
for (SnapshotIndexShardStatus shard : shards) { for (SnapshotIndexShardStatus shard : shards) {
builder.put(shard.getShardId(), shard); indexShards.put(shard.getShardId(), shard);
stats.add(shard.getStats()); stats.add(shard.getStats());
} }
shardsStats = new SnapshotShardsStats(shards); shardsStats = new SnapshotShardsStats(shards);
indexShards = builder.build(); this.indexShards = unmodifiableMap(indexShards);
} }
/** /**

View File

@ -19,7 +19,6 @@
package org.elasticsearch.action.admin.cluster.snapshots.status; package org.elasticsearch.action.admin.cluster.snapshots.status;
import com.google.common.collect.ImmutableMap;
import org.elasticsearch.cluster.SnapshotsInProgress.State; import org.elasticsearch.cluster.SnapshotsInProgress.State;
import org.elasticsearch.cluster.metadata.SnapshotId; import org.elasticsearch.cluster.metadata.SnapshotId;
import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamInput;
@ -33,11 +32,14 @@ import org.elasticsearch.common.xcontent.XContentFactory;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import static java.util.Collections.unmodifiableMap;
/** /**
* Status of a snapshot * Status of a snapshot
*/ */
@ -49,7 +51,7 @@ public class SnapshotStatus implements ToXContent, Streamable {
private List<SnapshotIndexShardStatus> shards; private List<SnapshotIndexShardStatus> shards;
private ImmutableMap<String, SnapshotIndexStatus> indicesStatus; private Map<String, SnapshotIndexStatus> indicesStatus;
private SnapshotShardsStats shardsStats; private SnapshotShardsStats shardsStats;
@ -100,7 +102,7 @@ public class SnapshotStatus implements ToXContent, Streamable {
return this.indicesStatus; return this.indicesStatus;
} }
ImmutableMap.Builder<String, SnapshotIndexStatus> indicesStatus = ImmutableMap.builder(); Map<String, SnapshotIndexStatus> indicesStatus = new HashMap<>();
Set<String> indices = new HashSet<>(); Set<String> indices = new HashSet<>();
for (SnapshotIndexShardStatus shard : shards) { for (SnapshotIndexShardStatus shard : shards) {
@ -116,7 +118,7 @@ public class SnapshotStatus implements ToXContent, Streamable {
} }
indicesStatus.put(index, new SnapshotIndexStatus(index, shards)); indicesStatus.put(index, new SnapshotIndexStatus(index, shards));
} }
this.indicesStatus = indicesStatus.build(); this.indicesStatus = unmodifiableMap(indicesStatus);
return this.indicesStatus; return this.indicesStatus;
} }

View File

@ -19,7 +19,6 @@
package org.elasticsearch.action.admin.indices.stats; package org.elasticsearch.action.admin.indices.stats;
import com.google.common.collect.ImmutableMap;
import org.elasticsearch.action.ShardOperationFailedException; import org.elasticsearch.action.ShardOperationFailedException;
import org.elasticsearch.action.support.broadcast.BroadcastResponse; import org.elasticsearch.action.support.broadcast.BroadcastResponse;
import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.cluster.routing.ShardRouting;
@ -38,13 +37,15 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import static java.util.Collections.unmodifiableMap;
/** /**
*/ */
public class IndicesStatsResponse extends BroadcastResponse implements ToXContent { public class IndicesStatsResponse extends BroadcastResponse implements ToXContent {
private ShardStats[] shards; private ShardStats[] shards;
private ImmutableMap<ShardRouting, CommonStats> shardStatsMap; private Map<ShardRouting, CommonStats> shardStatsMap;
IndicesStatsResponse() { IndicesStatsResponse() {
@ -55,16 +56,15 @@ public class IndicesStatsResponse extends BroadcastResponse implements ToXConten
this.shards = shards; this.shards = shards;
} }
public ImmutableMap<ShardRouting, CommonStats> asMap() { public Map<ShardRouting, CommonStats> asMap() {
if (shardStatsMap == null) { if (this.shardStatsMap == null) {
ImmutableMap.Builder<ShardRouting, CommonStats> mb = ImmutableMap.builder(); Map<ShardRouting, CommonStats> shardStatsMap = new HashMap<>();
for (ShardStats ss : shards) { for (ShardStats ss : shards) {
mb.put(ss.getShardRouting(), ss.getStats()); shardStatsMap.put(ss.getShardRouting(), ss.getStats());
} }
this.shardStatsMap = unmodifiableMap(shardStatsMap);
shardStatsMap = mb.build();
} }
return shardStatsMap; return this.shardStatsMap;
} }
public ShardStats[] getShards() { public ShardStats[] getShards() {

View File

@ -389,9 +389,9 @@ public class ClusterState implements ToXContent, Diffable<ClusterState> {
if (!blocks().indices().isEmpty()) { if (!blocks().indices().isEmpty()) {
builder.startObject("indices"); builder.startObject("indices");
for (Map.Entry<String, Set<ClusterBlock>> entry : blocks().indices().entrySet()) { for (ObjectObjectCursor<String, Set<ClusterBlock>> entry : blocks().indices()) {
builder.startObject(entry.getKey()); builder.startObject(entry.key);
for (ClusterBlock block : entry.getValue()) { for (ClusterBlock block : entry.value) {
block.toXContent(builder, params); block.toXContent(builder, params);
} }
builder.endObject(); builder.endObject();

View File

@ -19,7 +19,7 @@
package org.elasticsearch.cluster.block; package org.elasticsearch.cluster.block;
import com.google.common.collect.ImmutableMap; import com.carrotsearch.hppc.cursors.ObjectObjectCursor;
import org.elasticsearch.cluster.AbstractDiffable; import org.elasticsearch.cluster.AbstractDiffable;
import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.metadata.IndexMetaData;
@ -38,7 +38,6 @@ import java.util.function.Function;
import java.util.function.Predicate; import java.util.function.Predicate;
import java.util.stream.Stream; import java.util.stream.Stream;
import static java.util.Collections.emptyMap;
import static java.util.Collections.emptySet; import static java.util.Collections.emptySet;
import static java.util.Collections.unmodifiableSet; import static java.util.Collections.unmodifiableSet;
import static java.util.stream.Collectors.toSet; import static java.util.stream.Collectors.toSet;
@ -48,17 +47,17 @@ import static java.util.stream.Stream.concat;
* Represents current cluster level blocks to block dirty operations done against the cluster. * Represents current cluster level blocks to block dirty operations done against the cluster.
*/ */
public class ClusterBlocks extends AbstractDiffable<ClusterBlocks> { public class ClusterBlocks extends AbstractDiffable<ClusterBlocks> {
public static final ClusterBlocks EMPTY_CLUSTER_BLOCK = new ClusterBlocks(emptySet(), emptyMap()); public static final ClusterBlocks EMPTY_CLUSTER_BLOCK = new ClusterBlocks(emptySet(), ImmutableOpenMap.of());
public static final ClusterBlocks PROTO = EMPTY_CLUSTER_BLOCK; public static final ClusterBlocks PROTO = EMPTY_CLUSTER_BLOCK;
private final Set<ClusterBlock> global; private final Set<ClusterBlock> global;
private final Map<String, Set<ClusterBlock>> indicesBlocks; private final ImmutableOpenMap<String, Set<ClusterBlock>> indicesBlocks;
private final ImmutableLevelHolder[] levelHolders; private final ImmutableLevelHolder[] levelHolders;
ClusterBlocks(Set<ClusterBlock> global, Map<String, Set<ClusterBlock>> indicesBlocks) { ClusterBlocks(Set<ClusterBlock> global, ImmutableOpenMap<String, Set<ClusterBlock>> indicesBlocks) {
this.global = global; this.global = global;
this.indicesBlocks = indicesBlocks; this.indicesBlocks = indicesBlocks;
@ -70,8 +69,8 @@ public class ClusterBlocks extends AbstractDiffable<ClusterBlocks> {
.collect(toSet())); .collect(toSet()));
ImmutableOpenMap.Builder<String, Set<ClusterBlock>> indicesBuilder = ImmutableOpenMap.builder(); ImmutableOpenMap.Builder<String, Set<ClusterBlock>> indicesBuilder = ImmutableOpenMap.builder();
for (Map.Entry<String, Set<ClusterBlock>> entry : indicesBlocks.entrySet()) { for (ObjectObjectCursor<String, Set<ClusterBlock>> entry : indicesBlocks) {
indicesBuilder.put(entry.getKey(), unmodifiableSet(entry.getValue().stream() indicesBuilder.put(entry.key, unmodifiableSet(entry.value.stream()
.filter(containsLevel) .filter(containsLevel)
.collect(toSet()))); .collect(toSet())));
} }
@ -84,7 +83,7 @@ public class ClusterBlocks extends AbstractDiffable<ClusterBlocks> {
return global; return global;
} }
public Map<String, Set<ClusterBlock>> indices() { public ImmutableOpenMap<String, Set<ClusterBlock>> indices() {
return indicesBlocks; return indicesBlocks;
} }
@ -204,9 +203,9 @@ public class ClusterBlocks extends AbstractDiffable<ClusterBlocks> {
public void writeTo(StreamOutput out) throws IOException { public void writeTo(StreamOutput out) throws IOException {
writeBlockSet(global, out); writeBlockSet(global, out);
out.writeVInt(indicesBlocks.size()); out.writeVInt(indicesBlocks.size());
for (Map.Entry<String, Set<ClusterBlock>> entry : indicesBlocks.entrySet()) { for (ObjectObjectCursor<String, Set<ClusterBlock>> entry : indicesBlocks) {
out.writeString(entry.getKey()); out.writeString(entry.key);
writeBlockSet(entry.getValue(), out); writeBlockSet(entry.value, out);
} }
} }
@ -220,8 +219,8 @@ public class ClusterBlocks extends AbstractDiffable<ClusterBlocks> {
@Override @Override
public ClusterBlocks readFrom(StreamInput in) throws IOException { public ClusterBlocks readFrom(StreamInput in) throws IOException {
Set<ClusterBlock> global = readBlockSet(in); Set<ClusterBlock> global = readBlockSet(in);
ImmutableMap.Builder<String, Set<ClusterBlock>> indicesBuilder = ImmutableMap.builder();
int size = in.readVInt(); int size = in.readVInt();
ImmutableOpenMap.Builder<String, Set<ClusterBlock>> indicesBuilder = ImmutableOpenMap.builder(size);
for (int j = 0; j < size; j++) { for (int j = 0; j < size; j++) {
indicesBuilder.put(in.readString().intern(), readBlockSet(in)); indicesBuilder.put(in.readString().intern(), readBlockSet(in));
} }
@ -273,11 +272,11 @@ public class ClusterBlocks extends AbstractDiffable<ClusterBlocks> {
public Builder blocks(ClusterBlocks blocks) { public Builder blocks(ClusterBlocks blocks) {
global.addAll(blocks.global()); global.addAll(blocks.global());
for (Map.Entry<String, Set<ClusterBlock>> entry : blocks.indices().entrySet()) { for (ObjectObjectCursor<String, Set<ClusterBlock>> entry : blocks.indices()) {
if (!indices.containsKey(entry.getKey())) { if (!indices.containsKey(entry.key)) {
indices.put(entry.getKey(), new HashSet<>()); indices.put(entry.key, new HashSet<>());
} }
indices.get(entry.getKey()).addAll(entry.getValue()); indices.get(entry.key).addAll(entry.value);
} }
return this; return this;
} }
@ -340,7 +339,7 @@ public class ClusterBlocks extends AbstractDiffable<ClusterBlocks> {
public ClusterBlocks build() { public ClusterBlocks build() {
// We copy the block sets here in case of the builder is modified after build is called // We copy the block sets here in case of the builder is modified after build is called
ImmutableMap.Builder<String, Set<ClusterBlock>> indicesBuilder = ImmutableMap.builder(); ImmutableOpenMap.Builder<String, Set<ClusterBlock>> indicesBuilder = ImmutableOpenMap.builder(indices.size());
for (Map.Entry<String, Set<ClusterBlock>> entry : indices.entrySet()) { for (Map.Entry<String, Set<ClusterBlock>> entry : indices.entrySet()) {
indicesBuilder.put(entry.getKey(), unmodifiableSet(new HashSet<>(entry.getValue()))); indicesBuilder.put(entry.getKey(), unmodifiableSet(new HashSet<>(entry.getValue())));
} }

View File

@ -19,13 +19,15 @@
package org.elasticsearch.cluster.node; package org.elasticsearch.cluster.node;
import com.google.common.collect.ImmutableMap; import com.carrotsearch.hppc.cursors.ObjectObjectCursor;
import org.elasticsearch.Version; import org.elasticsearch.Version;
import org.elasticsearch.common.Booleans; import org.elasticsearch.common.Booleans;
import org.elasticsearch.common.Strings; import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.*; import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.common.network.NetworkUtils; import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Streamable;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.transport.TransportAddressSerializers; import org.elasticsearch.common.transport.TransportAddressSerializers;
@ -33,7 +35,6 @@ import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import java.io.IOException; import java.io.IOException;
import java.net.InetAddress;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -100,7 +101,7 @@ public class DiscoveryNode implements Streamable, ToXContent {
private String hostName; private String hostName;
private String hostAddress; private String hostAddress;
private TransportAddress address; private TransportAddress address;
private Map<String, String> attributes; private ImmutableOpenMap<String, String> attributes;
private Version version = Version.CURRENT; private Version version = Version.CURRENT;
DiscoveryNode() { DiscoveryNode() {
@ -143,7 +144,7 @@ public class DiscoveryNode implements Streamable, ToXContent {
} }
/** /**
* Creates a new {@link DiscoveryNode} * Creates a new {@link DiscoveryNode}.
* <p> * <p>
* <b>Note:</b> if the version of the node is unknown {@link #MINIMUM_DISCOVERY_NODE_VERSION} should be used. * <b>Note:</b> if the version of the node is unknown {@link #MINIMUM_DISCOVERY_NODE_VERSION} should be used.
* it corresponds to the minimum version this elasticsearch version can communicate with. If a higher version is used * it corresponds to the minimum version this elasticsearch version can communicate with. If a higher version is used
@ -163,7 +164,7 @@ public class DiscoveryNode implements Streamable, ToXContent {
if (nodeName != null) { if (nodeName != null) {
this.nodeName = nodeName.intern(); this.nodeName = nodeName.intern();
} }
ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); ImmutableOpenMap.Builder<String, String> builder = ImmutableOpenMap.builder();
for (Map.Entry<String, String> entry : attributes.entrySet()) { for (Map.Entry<String, String> entry : attributes.entrySet()) {
builder.put(entry.getKey().intern(), entry.getValue().intern()); builder.put(entry.getKey().intern(), entry.getValue().intern());
} }
@ -175,6 +176,39 @@ public class DiscoveryNode implements Streamable, ToXContent {
this.version = version; this.version = version;
} }
/**
* Creates a new {@link DiscoveryNode}.
* <p>
* <b>Note:</b> if the version of the node is unknown {@link #MINIMUM_DISCOVERY_NODE_VERSION} should be used.
* it corresponds to the minimum version this elasticsearch version can communicate with. If a higher version is used
* the node might not be able to communicate with the remove node. After initial handshakes node versions will be discovered
* and updated.
* </p>
*
* @param nodeName the nodes name
* @param nodeId the nodes unique id.
* @param hostName the nodes hostname
* @param hostAddress the nodes host address
* @param address the nodes transport address
* @param attributes node attributes
* @param version the version of the node.
*/
public DiscoveryNode(String nodeName, String nodeId, String hostName, String hostAddress, TransportAddress address, ImmutableOpenMap<String, String> attributes, Version version) {
if (nodeName != null) {
this.nodeName = nodeName.intern();
}
ImmutableOpenMap.Builder<String, String> builder = ImmutableOpenMap.builder();
for (ObjectObjectCursor<String, String> entry : attributes) {
builder.put(entry.key.intern(), entry.value.intern());
}
this.attributes = builder.build();
this.nodeId = nodeId.intern();
this.hostName = hostName.intern();
this.hostAddress = hostAddress.intern();
this.address = address;
this.version = version;
}
/** /**
* Should this node form a connection to the provided node. * Should this node form a connection to the provided node.
*/ */
@ -230,14 +264,14 @@ public class DiscoveryNode implements Streamable, ToXContent {
/** /**
* The node attributes. * The node attributes.
*/ */
public Map<String, String> attributes() { public ImmutableOpenMap<String, String> attributes() {
return this.attributes; return this.attributes;
} }
/** /**
* The node attributes. * The node attributes.
*/ */
public Map<String, String> getAttributes() { public ImmutableOpenMap<String, String> getAttributes() {
return attributes(); return attributes();
} }
@ -319,11 +353,11 @@ public class DiscoveryNode implements Streamable, ToXContent {
hostAddress = in.readString().intern(); hostAddress = in.readString().intern();
address = TransportAddressSerializers.addressFromStream(in); address = TransportAddressSerializers.addressFromStream(in);
int size = in.readVInt(); int size = in.readVInt();
ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); ImmutableOpenMap.Builder<String, String> attributes = ImmutableOpenMap.builder(size);
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
builder.put(in.readString().intern(), in.readString().intern()); attributes.put(in.readString().intern(), in.readString().intern());
} }
attributes = builder.build(); this.attributes = attributes.build();
version = Version.readVersion(in); version = Version.readVersion(in);
} }
@ -335,9 +369,9 @@ public class DiscoveryNode implements Streamable, ToXContent {
out.writeString(hostAddress); out.writeString(hostAddress);
addressToStream(out, address); addressToStream(out, address);
out.writeVInt(attributes.size()); out.writeVInt(attributes.size());
for (Map.Entry<String, String> entry : attributes.entrySet()) { for (ObjectObjectCursor<String, String> entry : attributes) {
out.writeString(entry.getKey()); out.writeString(entry.key);
out.writeString(entry.getValue()); out.writeString(entry.value);
} }
Version.writeVersion(version, out); Version.writeVersion(version, out);
} }
@ -385,8 +419,8 @@ public class DiscoveryNode implements Streamable, ToXContent {
builder.field("transport_address", address().toString()); builder.field("transport_address", address().toString());
builder.startObject("attributes"); builder.startObject("attributes");
for (Map.Entry<String, String> attr : attributes().entrySet()) { for (ObjectObjectCursor<String, String> attr : attributes) {
builder.field(attr.getKey(), attr.getValue()); builder.field(attr.key, attr.value);
} }
builder.endObject(); builder.endObject();

View File

@ -22,6 +22,7 @@ package org.elasticsearch.cluster.node;
import com.carrotsearch.hppc.ObjectHashSet; import com.carrotsearch.hppc.ObjectHashSet;
import com.carrotsearch.hppc.cursors.ObjectCursor; import com.carrotsearch.hppc.cursors.ObjectCursor;
import com.carrotsearch.hppc.cursors.ObjectObjectCursor; import com.carrotsearch.hppc.cursors.ObjectObjectCursor;
import org.elasticsearch.Version; import org.elasticsearch.Version;
import org.elasticsearch.cluster.AbstractDiffable; import org.elasticsearch.cluster.AbstractDiffable;
import org.elasticsearch.common.Booleans; import org.elasticsearch.common.Booleans;
@ -33,7 +34,12 @@ import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.common.transport.TransportAddress;
import java.io.IOException; import java.io.IOException;
import java.util.*; import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** /**
* This class holds all {@link DiscoveryNode} in the cluster and provides convenience methods to * This class holds all {@link DiscoveryNode} in the cluster and provides convenience methods to
@ -374,9 +380,9 @@ public class DiscoveryNodes extends AbstractDiffable<DiscoveryNodes> implements
} }
} else { } else {
for (DiscoveryNode node : this) { for (DiscoveryNode node : this) {
for (Map.Entry<String, String> entry : node.attributes().entrySet()) { for (ObjectObjectCursor<String, String> entry : node.attributes()) {
String attrName = entry.getKey(); String attrName = entry.key;
String attrValue = entry.getValue(); String attrValue = entry.value;
if (Regex.simpleMatch(matchAttrName, attrName) && Regex.simpleMatch(matchAttrValue, attrValue)) { if (Regex.simpleMatch(matchAttrName, attrName) && Regex.simpleMatch(matchAttrValue, attrValue)) {
resolvedNodesIds.add(node.id()); resolvedNodesIds.add(node.id());
} }
@ -563,6 +569,7 @@ public class DiscoveryNodes extends AbstractDiffable<DiscoveryNodes> implements
} }
} }
@Override
public void writeTo(StreamOutput out) throws IOException { public void writeTo(StreamOutput out) throws IOException {
if (masterNodeId == null) { if (masterNodeId == null) {
out.writeBoolean(false); out.writeBoolean(false);

View File

@ -16,8 +16,6 @@
package org.elasticsearch.common.inject.assistedinject; package org.elasticsearch.common.inject.assistedinject;
import com.google.common.collect.ImmutableMap;
import org.elasticsearch.common.inject.AbstractModule; import org.elasticsearch.common.inject.AbstractModule;
import org.elasticsearch.common.inject.Binder; import org.elasticsearch.common.inject.Binder;
import org.elasticsearch.common.inject.Binding; import org.elasticsearch.common.inject.Binding;
@ -41,9 +39,11 @@ import java.lang.reflect.Proxy;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import static java.util.Collections.unmodifiableMap;
import static org.elasticsearch.common.inject.internal.Annotations.getKey; import static org.elasticsearch.common.inject.internal.Annotations.getKey;
/** /**
@ -91,7 +91,7 @@ public final class FactoryProvider2<F> implements InvocationHandler, Provider<F>
*/ */
private final Key<?> producedType; private final Key<?> producedType;
private final Map<Method, Key<?>> returnTypesByMethod; private final Map<Method, Key<?>> returnTypesByMethod;
private final ImmutableMap<Method, List<Key<?>>> paramTypes; private final Map<Method, List<Key<?>>> paramTypes;
/** /**
* the hosting injector, or null if we haven't been initialized yet * the hosting injector, or null if we haven't been initialized yet
@ -117,9 +117,8 @@ public final class FactoryProvider2<F> implements InvocationHandler, Provider<F>
Class<F> factoryRawType = (Class) factoryType.getRawType(); Class<F> factoryRawType = (Class) factoryType.getRawType();
try { try {
ImmutableMap.Builder<Method, Key<?>> returnTypesBuilder = ImmutableMap.builder(); Map<Method, Key<?>> returnTypesBuilder = new HashMap<>();
ImmutableMap.Builder<Method, List<Key<?>>> paramTypesBuilder Map<Method, List<Key<?>>> paramTypesBuilder = new HashMap<>();
= ImmutableMap.builder();
// TODO: also grab methods from superinterfaces // TODO: also grab methods from superinterfaces
for (Method method : factoryRawType.getMethods()) { for (Method method : factoryRawType.getMethods()) {
Key<?> returnType = getKey( Key<?> returnType = getKey(
@ -135,8 +134,8 @@ public final class FactoryProvider2<F> implements InvocationHandler, Provider<F>
} }
paramTypesBuilder.put(method, Collections.unmodifiableList(keys)); paramTypesBuilder.put(method, Collections.unmodifiableList(keys));
} }
returnTypesByMethod = returnTypesBuilder.build(); returnTypesByMethod = unmodifiableMap(returnTypesBuilder);
paramTypes = paramTypesBuilder.build(); paramTypes = unmodifiableMap(paramTypesBuilder);
} catch (ErrorsException e) { } catch (ErrorsException e) {
throw new ConfigurationException(e.getErrors().getMessages()); throw new ConfigurationException(e.getErrors().getMessages());
} }

View File

@ -17,8 +17,6 @@
package org.elasticsearch.common.inject.internal; package org.elasticsearch.common.inject.internal;
import com.google.common.collect.ImmutableMap;
import org.elasticsearch.common.inject.ConfigurationException; import org.elasticsearch.common.inject.ConfigurationException;
import org.elasticsearch.common.inject.TypeLiteral; import org.elasticsearch.common.inject.TypeLiteral;
import org.elasticsearch.common.inject.spi.Message; import org.elasticsearch.common.inject.spi.Message;
@ -35,11 +33,13 @@ import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable; import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType; import java.lang.reflect.WildcardType;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Objects; import java.util.Objects;
import static java.util.Collections.singleton; import static java.util.Collections.singleton;
import static java.util.Collections.unmodifiableMap;
/** /**
* Static methods for working with types that we aren't publishing in the * Static methods for working with types that we aren't publishing in the
@ -54,18 +54,20 @@ public class MoreTypes {
private MoreTypes() { private MoreTypes() {
} }
private static final Map<TypeLiteral<?>, TypeLiteral<?>> PRIMITIVE_TO_WRAPPER private static final Map<TypeLiteral<?>, TypeLiteral<?>> PRIMITIVE_TO_WRAPPER;
= new ImmutableMap.Builder<TypeLiteral<?>, TypeLiteral<?>>() static {
.put(TypeLiteral.get(boolean.class), TypeLiteral.get(Boolean.class)) Map<TypeLiteral<?>, TypeLiteral<?>> primitiveToWrapper = new HashMap<>();
.put(TypeLiteral.get(byte.class), TypeLiteral.get(Byte.class)) primitiveToWrapper.put(TypeLiteral.get(boolean.class), TypeLiteral.get(Boolean.class));
.put(TypeLiteral.get(short.class), TypeLiteral.get(Short.class)) primitiveToWrapper.put(TypeLiteral.get(byte.class), TypeLiteral.get(Byte.class));
.put(TypeLiteral.get(int.class), TypeLiteral.get(Integer.class)) primitiveToWrapper.put(TypeLiteral.get(short.class), TypeLiteral.get(Short.class));
.put(TypeLiteral.get(long.class), TypeLiteral.get(Long.class)) primitiveToWrapper.put(TypeLiteral.get(int.class), TypeLiteral.get(Integer.class));
.put(TypeLiteral.get(float.class), TypeLiteral.get(Float.class)) primitiveToWrapper.put(TypeLiteral.get(long.class), TypeLiteral.get(Long.class));
.put(TypeLiteral.get(double.class), TypeLiteral.get(Double.class)) primitiveToWrapper.put(TypeLiteral.get(float.class), TypeLiteral.get(Float.class));
.put(TypeLiteral.get(char.class), TypeLiteral.get(Character.class)) primitiveToWrapper.put(TypeLiteral.get(double.class), TypeLiteral.get(Double.class));
.put(TypeLiteral.get(void.class), TypeLiteral.get(Void.class)) primitiveToWrapper.put(TypeLiteral.get(char.class), TypeLiteral.get(Character.class));
.build(); primitiveToWrapper.put(TypeLiteral.get(void.class), TypeLiteral.get(Void.class));
PRIMITIVE_TO_WRAPPER = unmodifiableMap(primitiveToWrapper);
}
/** /**
* Returns an equivalent type that's safe for use in a key. The returned type will be free of * Returns an equivalent type that's safe for use in a key. The returned type will be free of

View File

@ -19,12 +19,10 @@
package org.elasticsearch.index.analysis; package org.elasticsearch.index.analysis;
import com.google.common.collect.ImmutableMap;
import org.apache.lucene.analysis.Tokenizer; import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.ngram.Lucene43NGramTokenizer; import org.apache.lucene.analysis.ngram.Lucene43NGramTokenizer;
import org.apache.lucene.analysis.ngram.NGramTokenizer; import org.apache.lucene.analysis.ngram.NGramTokenizer;
import org.apache.lucene.util.Version; import org.apache.lucene.util.Version;
import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.inject.assistedinject.Assisted; import org.elasticsearch.common.inject.assistedinject.Assisted;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
@ -33,9 +31,12 @@ import org.elasticsearch.index.settings.IndexSettings;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import static java.util.Collections.unmodifiableMap;
/** /**
* *
*/ */
@ -49,12 +50,12 @@ public class NGramTokenizerFactory extends AbstractTokenizerFactory {
static final Map<String, CharMatcher> MATCHERS; static final Map<String, CharMatcher> MATCHERS;
static { static {
ImmutableMap.Builder<String, CharMatcher> builder = ImmutableMap.builder(); Map<String, CharMatcher> matchers = new HashMap<>();
builder.put("letter", CharMatcher.Basic.LETTER); matchers.put("letter", CharMatcher.Basic.LETTER);
builder.put("digit", CharMatcher.Basic.DIGIT); matchers.put("digit", CharMatcher.Basic.DIGIT);
builder.put("whitespace", CharMatcher.Basic.WHITESPACE); matchers.put("whitespace", CharMatcher.Basic.WHITESPACE);
builder.put("punctuation", CharMatcher.Basic.PUNCTUATION); matchers.put("punctuation", CharMatcher.Basic.PUNCTUATION);
builder.put("symbol", CharMatcher.Basic.SYMBOL); matchers.put("symbol", CharMatcher.Basic.SYMBOL);
// Populate with unicode categories from java.lang.Character // Populate with unicode categories from java.lang.Character
for (Field field : Character.class.getFields()) { for (Field field : Character.class.getFields()) {
if (!field.getName().startsWith("DIRECTIONALITY") if (!field.getName().startsWith("DIRECTIONALITY")
@ -62,14 +63,14 @@ public class NGramTokenizerFactory extends AbstractTokenizerFactory {
&& Modifier.isStatic(field.getModifiers()) && Modifier.isStatic(field.getModifiers())
&& field.getType() == byte.class) { && field.getType() == byte.class) {
try { try {
builder.put(field.getName().toLowerCase(Locale.ROOT), CharMatcher.ByUnicodeCategory.of(field.getByte(null))); matchers.put(field.getName().toLowerCase(Locale.ROOT), CharMatcher.ByUnicodeCategory.of(field.getByte(null)));
} catch (Exception e) { } catch (Exception e) {
// just ignore // just ignore
continue; continue;
} }
} }
} }
MATCHERS = builder.build(); MATCHERS = unmodifiableMap(matchers);
} }
static CharMatcher parseTokenChars(String[] characterClasses) { static CharMatcher parseTokenChars(String[] characterClasses) {

View File

@ -19,8 +19,6 @@
package org.elasticsearch.index.mapper; package org.elasticsearch.index.mapper;
import com.google.common.collect.ImmutableMap;
import org.elasticsearch.Version; import org.elasticsearch.Version;
import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
@ -30,10 +28,12 @@ import org.elasticsearch.index.mapper.object.RootObjectMapper;
import java.io.IOException; import java.io.IOException;
import java.util.Arrays; import java.util.Arrays;
import java.util.Comparator; import java.util.Comparator;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import static java.util.Collections.emptyMap; import static java.util.Collections.emptyMap;
import static java.util.Collections.unmodifiableMap;
/** /**
* Wrapper around everything that defines a mapping, without references to * Wrapper around everything that defines a mapping, without references to
@ -58,7 +58,7 @@ public final class Mapping implements ToXContent {
final Version indexCreated; final Version indexCreated;
final RootObjectMapper root; final RootObjectMapper root;
final MetadataFieldMapper[] metadataMappers; final MetadataFieldMapper[] metadataMappers;
final ImmutableMap<Class<? extends MetadataFieldMapper>, MetadataFieldMapper> rootMappersMap; final Map<Class<? extends MetadataFieldMapper>, MetadataFieldMapper> rootMappersMap;
final SourceTransform[] sourceTransforms; final SourceTransform[] sourceTransforms;
volatile Map<String, Object> meta; volatile Map<String, Object> meta;
@ -66,12 +66,12 @@ public final class Mapping implements ToXContent {
this.indexCreated = indexCreated; this.indexCreated = indexCreated;
this.root = rootObjectMapper; this.root = rootObjectMapper;
this.metadataMappers = metadataMappers; this.metadataMappers = metadataMappers;
ImmutableMap.Builder<Class<? extends MetadataFieldMapper>, MetadataFieldMapper> builder = ImmutableMap.builder(); Map<Class<? extends MetadataFieldMapper>, MetadataFieldMapper> rootMappersMap = new HashMap<>();
for (MetadataFieldMapper metadataMapper : metadataMappers) { for (MetadataFieldMapper metadataMapper : metadataMappers) {
if (indexCreated.before(Version.V_2_0_0_beta1) && LEGACY_INCLUDE_IN_OBJECT.contains(metadataMapper.name())) { if (indexCreated.before(Version.V_2_0_0_beta1) && LEGACY_INCLUDE_IN_OBJECT.contains(metadataMapper.name())) {
root.putMapper(metadataMapper); root.putMapper(metadataMapper);
} }
builder.put(metadataMapper.getClass(), metadataMapper); rootMappersMap.put(metadataMapper.getClass(), metadataMapper);
} }
// keep root mappers sorted for consistent serialization // keep root mappers sorted for consistent serialization
Arrays.sort(metadataMappers, new Comparator<Mapper>() { Arrays.sort(metadataMappers, new Comparator<Mapper>() {
@ -80,7 +80,7 @@ public final class Mapping implements ToXContent {
return o1.name().compareTo(o2.name()); return o1.name().compareTo(o2.name());
} }
}); });
this.rootMappersMap = builder.build(); this.rootMappersMap = unmodifiableMap(rootMappersMap);
this.sourceTransforms = sourceTransforms; this.sourceTransforms = sourceTransforms;
this.meta = meta; this.meta = meta;
} }

View File

@ -19,8 +19,6 @@
package org.elasticsearch.index.store; package org.elasticsearch.index.store;
import com.google.common.collect.ImmutableMap;
import org.apache.lucene.codecs.CodecUtil; import org.apache.lucene.codecs.CodecUtil;
import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexCommit; import org.apache.lucene.index.IndexCommit;
@ -97,6 +95,7 @@ import java.util.zip.CRC32;
import java.util.zip.Checksum; import java.util.zip.Checksum;
import static java.util.Collections.emptyMap; import static java.util.Collections.emptyMap;
import static java.util.Collections.unmodifiableMap;
/** /**
* A Store provides plain access to files written by an elasticsearch index shard. Each shard * A Store provides plain access to files written by an elasticsearch index shard. Each shard
@ -798,19 +797,19 @@ public class Store extends AbstractIndexShardComponent implements Closeable, Ref
public MetadataSnapshot(StreamInput in) throws IOException { public MetadataSnapshot(StreamInput in) throws IOException {
final int size = in.readVInt(); final int size = in.readVInt();
final ImmutableMap.Builder<String, StoreFileMetaData> metadataBuilder = ImmutableMap.builder(); Map<String, StoreFileMetaData> metadata = new HashMap<>();
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
StoreFileMetaData meta = StoreFileMetaData.readStoreFileMetaData(in); StoreFileMetaData meta = StoreFileMetaData.readStoreFileMetaData(in);
metadataBuilder.put(meta.name(), meta); metadata.put(meta.name(), meta);
} }
final ImmutableMap.Builder<String, String> commitUserDataBuilder = ImmutableMap.builder(); Map<String, String> commitUserData = new HashMap<>();
int num = in.readVInt(); int num = in.readVInt();
for (int i = num; i > 0; i--) { for (int i = num; i > 0; i--) {
commitUserDataBuilder.put(in.readString(), in.readString()); commitUserData.put(in.readString(), in.readString());
} }
this.commitUserData = commitUserDataBuilder.build(); this.metadata = unmodifiableMap(metadata);
this.metadata = metadataBuilder.build(); this.commitUserData = unmodifiableMap(commitUserData);
this.numDocs = in.readLong(); this.numDocs = in.readLong();
assert metadata.isEmpty() || numSegmentFiles() == 1 : "numSegmentFiles: " + numSegmentFiles(); assert metadata.isEmpty() || numSegmentFiles() == 1 : "numSegmentFiles: " + numSegmentFiles();
} }
@ -823,11 +822,11 @@ public class Store extends AbstractIndexShardComponent implements Closeable, Ref
} }
static class LoadedMetadata { static class LoadedMetadata {
final ImmutableMap<String, StoreFileMetaData> fileMetadata; final Map<String, StoreFileMetaData> fileMetadata;
final ImmutableMap<String, String> userData; final Map<String, String> userData;
final long numDocs; final long numDocs;
LoadedMetadata(ImmutableMap<String, StoreFileMetaData> fileMetadata, ImmutableMap<String, String> userData, long numDocs) { LoadedMetadata(Map<String, StoreFileMetaData> fileMetadata, Map<String, String> userData, long numDocs) {
this.fileMetadata = fileMetadata; this.fileMetadata = fileMetadata;
this.userData = userData; this.userData = userData;
this.numDocs = numDocs; this.numDocs = numDocs;
@ -836,9 +835,9 @@ public class Store extends AbstractIndexShardComponent implements Closeable, Ref
static LoadedMetadata loadMetadata(IndexCommit commit, Directory directory, ESLogger logger) throws IOException { static LoadedMetadata loadMetadata(IndexCommit commit, Directory directory, ESLogger logger) throws IOException {
long numDocs; long numDocs;
ImmutableMap.Builder<String, StoreFileMetaData> builder = ImmutableMap.builder(); Map<String, StoreFileMetaData> builder = new HashMap<>();
Map<String, String> checksumMap = readLegacyChecksums(directory).v1(); Map<String, String> checksumMap = readLegacyChecksums(directory).v1();
ImmutableMap.Builder<String, String> commitUserDataBuilder = ImmutableMap.builder(); Map<String, String> commitUserDataBuilder = new HashMap<>();
try { try {
final SegmentInfos segmentCommitInfos = Store.readSegmentsInfo(commit, directory); final SegmentInfos segmentCommitInfos = Store.readSegmentsInfo(commit, directory);
numDocs = Lucene.getNumDocs(segmentCommitInfos); numDocs = Lucene.getNumDocs(segmentCommitInfos);
@ -895,7 +894,7 @@ public class Store extends AbstractIndexShardComponent implements Closeable, Ref
throw ex; throw ex;
} }
return new LoadedMetadata(builder.build(), commitUserDataBuilder.build(), numDocs); return new LoadedMetadata(unmodifiableMap(builder), unmodifiableMap(commitUserDataBuilder), numDocs);
} }
/** /**
@ -952,7 +951,8 @@ public class Store extends AbstractIndexShardComponent implements Closeable, Ref
} }
} }
private static void checksumFromLuceneFile(Directory directory, String file, ImmutableMap.Builder<String, StoreFileMetaData> builder, ESLogger logger, Version version, boolean readFileAsHash) throws IOException { private static void checksumFromLuceneFile(Directory directory, String file, Map<String, StoreFileMetaData> builder,
ESLogger logger, Version version, boolean readFileAsHash) throws IOException {
final String checksum; final String checksum;
final BytesRefBuilder fileHash = new BytesRefBuilder(); final BytesRefBuilder fileHash = new BytesRefBuilder();
try (final IndexInput in = directory.openInput(file, IOContext.READONCE)) { try (final IndexInput in = directory.openInput(file, IOContext.READONCE)) {

View File

@ -18,8 +18,6 @@
*/ */
package org.elasticsearch.indices.flush; package org.elasticsearch.indices.flush;
import com.google.common.collect.ImmutableMap;
import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.index.shard.ShardId;
@ -27,6 +25,7 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
import static java.util.Collections.emptyMap; import static java.util.Collections.emptyMap;
import static java.util.Collections.unmodifiableMap;
/** /**
* Result for all copies of a shard * Result for all copies of a shard
@ -62,8 +61,7 @@ public class ShardsSyncedFlushResult {
*/ */
public ShardsSyncedFlushResult(ShardId shardId, String syncId, int totalShards, Map<ShardRouting, SyncedFlushService.SyncedFlushResponse> shardResponses) { public ShardsSyncedFlushResult(ShardId shardId, String syncId, int totalShards, Map<ShardRouting, SyncedFlushService.SyncedFlushResponse> shardResponses) {
this.failureReason = null; this.failureReason = null;
ImmutableMap.Builder<ShardRouting, SyncedFlushService.SyncedFlushResponse> builder = ImmutableMap.builder(); this.shardResponses = unmodifiableMap(new HashMap<>(shardResponses));
this.shardResponses = builder.putAll(shardResponses).build();
this.syncId = syncId; this.syncId = syncId;
this.totalShards = totalShards; this.totalShards = totalShards;
this.shardId = shardId; this.shardId = shardId;

View File

@ -48,7 +48,13 @@ import org.elasticsearch.indices.IndexClosedException;
import org.elasticsearch.indices.IndicesLifecycle; import org.elasticsearch.indices.IndicesLifecycle;
import org.elasticsearch.indices.IndicesService; import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.*; import org.elasticsearch.transport.BaseTransportResponseHandler;
import org.elasticsearch.transport.TransportChannel;
import org.elasticsearch.transport.TransportException;
import org.elasticsearch.transport.TransportRequest;
import org.elasticsearch.transport.TransportRequestHandler;
import org.elasticsearch.transport.TransportResponse;
import org.elasticsearch.transport.TransportService;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
@ -341,8 +347,7 @@ public class SyncedFlushService extends AbstractComponent {
} }
private void contDownAndSendResponseIfDone(String syncId, List<ShardRouting> shards, ShardId shardId, int totalShards, private void contDownAndSendResponseIfDone(String syncId, List<ShardRouting> shards, ShardId shardId, int totalShards,
ActionListener<ShardsSyncedFlushResult> listener, CountDown countDown, Map<ShardRouting, ActionListener<ShardsSyncedFlushResult> listener, CountDown countDown, Map<ShardRouting, SyncedFlushResponse> results) {
SyncedFlushResponse> results) {
if (countDown.countDown()) { if (countDown.countDown()) {
assert results.size() == shards.size(); assert results.size() == shards.size();
listener.onResponse(new ShardsSyncedFlushResult(shardId, syncId, totalShards, results)); listener.onResponse(new ShardsSyncedFlushResult(shardId, syncId, totalShards, results));

View File

@ -19,17 +19,17 @@
package org.elasticsearch.monitor.jvm; package org.elasticsearch.monitor.jvm;
import com.google.common.collect.ImmutableMap;
import java.lang.management.ManagementFactory; import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo; import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean; import java.lang.management.ThreadMXBean;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import static java.util.Collections.unmodifiableMap;
import static java.util.Collections.unmodifiableSet; import static java.util.Collections.unmodifiableSet;
/** /**
@ -55,7 +55,7 @@ public class DeadlockAnalyzer {
if (deadlockedThreads == null || deadlockedThreads.length == 0) { if (deadlockedThreads == null || deadlockedThreads.length == 0) {
return NULL_RESULT; return NULL_RESULT;
} }
ImmutableMap<Long, ThreadInfo> threadInfoMap = createThreadInfoMap(deadlockedThreads); Map<Long, ThreadInfo> threadInfoMap = createThreadInfoMap(deadlockedThreads);
Set<LinkedHashSet<ThreadInfo>> cycles = calculateCycles(threadInfoMap); Set<LinkedHashSet<ThreadInfo>> cycles = calculateCycles(threadInfoMap);
Set<LinkedHashSet<ThreadInfo>> chains = calculateCycleDeadlockChains(threadInfoMap, cycles); Set<LinkedHashSet<ThreadInfo>> chains = calculateCycleDeadlockChains(threadInfoMap, cycles);
cycles.addAll(chains); cycles.addAll(chains);
@ -89,7 +89,7 @@ public class DeadlockAnalyzer {
} }
private Set<LinkedHashSet<ThreadInfo>> calculateCycleDeadlockChains(ImmutableMap<Long, ThreadInfo> threadInfoMap, Set<LinkedHashSet<ThreadInfo>> cycles) { private Set<LinkedHashSet<ThreadInfo>> calculateCycleDeadlockChains(Map<Long, ThreadInfo> threadInfoMap, Set<LinkedHashSet<ThreadInfo>> cycles) {
ThreadInfo allThreads[] = threadBean.getThreadInfo(threadBean.getAllThreadIds()); ThreadInfo allThreads[] = threadBean.getThreadInfo(threadBean.getAllThreadIds());
Set<LinkedHashSet<ThreadInfo>> deadlockChain = new HashSet<>(); Set<LinkedHashSet<ThreadInfo>> deadlockChain = new HashSet<>();
Set<Long> knownDeadlockedThreads = threadInfoMap.keySet(); Set<Long> knownDeadlockedThreads = threadInfoMap.keySet();
@ -113,13 +113,13 @@ public class DeadlockAnalyzer {
} }
private ImmutableMap<Long, ThreadInfo> createThreadInfoMap(long threadIds[]) { private Map<Long, ThreadInfo> createThreadInfoMap(long threadIds[]) {
ThreadInfo threadInfos[] = threadBean.getThreadInfo(threadIds); ThreadInfo threadInfos[] = threadBean.getThreadInfo(threadIds);
ImmutableMap.Builder<Long, ThreadInfo> threadInfoMap = ImmutableMap.builder(); Map<Long, ThreadInfo> threadInfoMap = new HashMap<>();
for (ThreadInfo threadInfo : threadInfos) { for (ThreadInfo threadInfo : threadInfos) {
threadInfoMap.put(threadInfo.getThreadId(), threadInfo); threadInfoMap.put(threadInfo.getThreadId(), threadInfo);
} }
return threadInfoMap.build(); return unmodifiableMap(threadInfoMap);
} }
public static class Deadlock { public static class Deadlock {

View File

@ -18,6 +18,8 @@
*/ */
package org.elasticsearch.rest.action.cat; package org.elasticsearch.rest.action.cat;
import com.carrotsearch.hppc.cursors.ObjectObjectCursor;
import org.elasticsearch.action.admin.cluster.node.info.NodeInfo; import org.elasticsearch.action.admin.cluster.node.info.NodeInfo;
import org.elasticsearch.action.admin.cluster.node.info.NodesInfoRequest; import org.elasticsearch.action.admin.cluster.node.info.NodesInfoRequest;
import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse; import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse;
@ -41,8 +43,6 @@ import org.elasticsearch.rest.action.support.RestActionListener;
import org.elasticsearch.rest.action.support.RestResponseListener; import org.elasticsearch.rest.action.support.RestResponseListener;
import org.elasticsearch.rest.action.support.RestTable; import org.elasticsearch.rest.action.support.RestTable;
import java.util.Map;
import static org.elasticsearch.rest.RestRequest.Method.GET; import static org.elasticsearch.rest.RestRequest.Method.GET;
public class RestNodeAttrsAction extends AbstractCatAction { public class RestNodeAttrsAction extends AbstractCatAction {
@ -111,8 +111,7 @@ public class RestNodeAttrsAction extends AbstractCatAction {
for (DiscoveryNode node : nodes) { for (DiscoveryNode node : nodes) {
NodeInfo info = nodesInfo.getNodesMap().get(node.id()); NodeInfo info = nodesInfo.getNodesMap().get(node.id());
Map<String, String> attrs = node.getAttributes(); for(ObjectObjectCursor<String, String> att : node.attributes()) {
for(String att : attrs.keySet()) {
table.startRow(); table.startRow();
table.addCell(node.name()); table.addCell(node.name());
table.addCell(fullId ? node.id() : Strings.substring(node.getId(), 0, 4)); table.addCell(fullId ? node.id() : Strings.substring(node.getId(), 0, 4));
@ -124,8 +123,8 @@ public class RestNodeAttrsAction extends AbstractCatAction {
} else { } else {
table.addCell("-"); table.addCell("-");
} }
table.addCell(att); table.addCell(att.key);
table.addCell(attrs.containsKey(att) ? attrs.get(att) : null); table.addCell(att.value);
table.endRow(); table.endRow();
} }
} }

View File

@ -19,12 +19,10 @@
package org.elasticsearch.script; package org.elasticsearch.script;
import java.nio.charset.StandardCharsets;
import com.google.common.cache.Cache; import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener; import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification; import com.google.common.cache.RemovalNotification;
import com.google.common.collect.ImmutableMap;
import org.apache.lucene.util.IOUtils; import org.apache.lucene.util.IOUtils;
import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.ActionListener;
@ -67,14 +65,18 @@ import org.elasticsearch.watcher.ResourceWatcherService;
import java.io.Closeable; import java.io.Closeable;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.HashMap;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import static java.util.Collections.unmodifiableMap;
/** /**
* *
*/ */
@ -93,8 +95,8 @@ public class ScriptService extends AbstractComponent implements Closeable {
private final String defaultLang; private final String defaultLang;
private final Set<ScriptEngineService> scriptEngines; private final Set<ScriptEngineService> scriptEngines;
private final ImmutableMap<String, ScriptEngineService> scriptEnginesByLang; private final Map<String, ScriptEngineService> scriptEnginesByLang;
private final ImmutableMap<String, ScriptEngineService> scriptEnginesByExt; private final Map<String, ScriptEngineService> scriptEnginesByExt;
private final ConcurrentMap<String, CompiledScript> staticCache = ConcurrentCollections.newConcurrentMap(); private final ConcurrentMap<String, CompiledScript> staticCache = ConcurrentCollections.newConcurrentMap();
@ -162,8 +164,8 @@ public class ScriptService extends AbstractComponent implements Closeable {
} }
this.cache = cacheBuilder.removalListener(new ScriptCacheRemovalListener()).build(); this.cache = cacheBuilder.removalListener(new ScriptCacheRemovalListener()).build();
ImmutableMap.Builder<String, ScriptEngineService> enginesByLangBuilder = ImmutableMap.builder(); Map<String, ScriptEngineService> enginesByLangBuilder = new HashMap<>();
ImmutableMap.Builder<String, ScriptEngineService> enginesByExtBuilder = ImmutableMap.builder(); Map<String, ScriptEngineService> enginesByExtBuilder = new HashMap<>();
for (ScriptEngineService scriptEngine : scriptEngines) { for (ScriptEngineService scriptEngine : scriptEngines) {
for (String type : scriptEngine.types()) { for (String type : scriptEngine.types()) {
enginesByLangBuilder.put(type, scriptEngine); enginesByLangBuilder.put(type, scriptEngine);
@ -172,8 +174,8 @@ public class ScriptService extends AbstractComponent implements Closeable {
enginesByExtBuilder.put(ext, scriptEngine); enginesByExtBuilder.put(ext, scriptEngine);
} }
} }
this.scriptEnginesByLang = enginesByLangBuilder.build(); this.scriptEnginesByLang = unmodifiableMap(enginesByLangBuilder);
this.scriptEnginesByExt = enginesByExtBuilder.build(); this.scriptEnginesByExt = unmodifiableMap(enginesByExtBuilder);
this.scriptModes = new ScriptModes(this.scriptEnginesByLang, scriptContextRegistry, settings); this.scriptModes = new ScriptModes(this.scriptEnginesByLang, scriptContextRegistry, settings);

View File

@ -18,7 +18,6 @@
*/ */
package org.elasticsearch.search.aggregations; package org.elasticsearch.search.aggregations;
import com.google.common.collect.ImmutableMap;
import org.apache.lucene.search.BooleanClause.Occur; import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Query; import org.apache.lucene.search.Query;
@ -35,34 +34,33 @@ import org.elasticsearch.search.query.QueryPhaseExecutionException;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import static java.util.Collections.unmodifiableMap;
/** /**
* *
*/ */
public class AggregationPhase implements SearchPhase { public class AggregationPhase implements SearchPhase {
private final Map<String, SearchParseElement> parseElements;
private final AggregationParseElement parseElement;
private final AggregationBinaryParseElement binaryParseElement;
@Inject @Inject
public AggregationPhase(AggregationParseElement parseElement, AggregationBinaryParseElement binaryParseElement) { public AggregationPhase(AggregationParseElement parseElement, AggregationBinaryParseElement binaryParseElement) {
this.parseElement = parseElement; Map<String, SearchParseElement> parseElements = new HashMap<>();
this.binaryParseElement = binaryParseElement; parseElements.put("aggregations", parseElement);
parseElements.put("aggs", parseElement);
parseElements.put("aggregations_binary", binaryParseElement);
parseElements.put("aggregationsBinary", binaryParseElement);
parseElements.put("aggs_binary", binaryParseElement);
parseElements.put("aggsBinary", binaryParseElement);
this.parseElements = unmodifiableMap(parseElements);
} }
@Override @Override
public Map<String, ? extends SearchParseElement> parseElements() { public Map<String, ? extends SearchParseElement> parseElements() {
return ImmutableMap.<String, SearchParseElement>builder() return parseElements;
.put("aggregations", parseElement)
.put("aggs", parseElement)
.put("aggregations_binary", binaryParseElement)
.put("aggregationsBinary", binaryParseElement)
.put("aggs_binary", binaryParseElement)
.put("aggsBinary", binaryParseElement)
.build();
} }
@Override @Override

View File

@ -19,7 +19,6 @@
package org.elasticsearch.search.fetch; package org.elasticsearch.search.fetch;
import com.google.common.collect.ImmutableMap;
import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.ReaderUtil; import org.apache.lucene.index.ReaderUtil;
import org.apache.lucene.search.DocIdSet; import org.apache.lucene.search.DocIdSet;
@ -64,6 +63,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import static java.util.Collections.unmodifiableMap;
import static org.elasticsearch.common.xcontent.XContentFactory.contentBuilder; import static org.elasticsearch.common.xcontent.XContentFactory.contentBuilder;
/** /**
@ -82,12 +82,12 @@ public class FetchPhase implements SearchPhase {
@Override @Override
public Map<String, ? extends SearchParseElement> parseElements() { public Map<String, ? extends SearchParseElement> parseElements() {
ImmutableMap.Builder<String, SearchParseElement> parseElements = ImmutableMap.builder(); Map<String, SearchParseElement> parseElements = new HashMap<>();
parseElements.put("fields", new FieldsParseElement()); parseElements.put("fields", new FieldsParseElement());
for (FetchSubPhase fetchSubPhase : fetchSubPhases) { for (FetchSubPhase fetchSubPhase : fetchSubPhases) {
parseElements.putAll(fetchSubPhase.parseElements()); parseElements.putAll(fetchSubPhase.parseElements());
} }
return parseElements.build(); return unmodifiableMap(parseElements);
} }
@Override @Override

View File

@ -18,16 +18,13 @@
*/ */
package org.elasticsearch.search.fetch.fielddata; package org.elasticsearch.search.fetch.fielddata;
import com.google.common.collect.ImmutableMap;
import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.index.fielddata.AtomicFieldData; import org.elasticsearch.index.fielddata.AtomicFieldData;
import org.elasticsearch.index.fielddata.ScriptDocValues; import org.elasticsearch.index.fielddata.ScriptDocValues;
import org.elasticsearch.index.mapper.FieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType; import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.search.SearchHitField; import org.elasticsearch.search.SearchHitField;
import org.elasticsearch.search.SearchParseElement; import org.elasticsearch.search.SearchParseElement;
import org.elasticsearch.search.fetch.FetchSubPhase; import org.elasticsearch.search.fetch.FetchSubPhase;
import org.elasticsearch.search.fetch.FetchSubPhaseContext;
import org.elasticsearch.search.internal.InternalSearchHit; import org.elasticsearch.search.internal.InternalSearchHit;
import org.elasticsearch.search.internal.InternalSearchHitField; import org.elasticsearch.search.internal.InternalSearchHitField;
import org.elasticsearch.search.internal.SearchContext; import org.elasticsearch.search.internal.SearchContext;
@ -36,6 +33,8 @@ import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import static java.util.Collections.unmodifiableMap;
/** /**
* Query sub phase which pulls data from field data (using the cache if * Query sub phase which pulls data from field data (using the cache if
* available, building it if not). * available, building it if not).
@ -64,10 +63,10 @@ public class FieldDataFieldsFetchSubPhase implements FetchSubPhase {
@Override @Override
public Map<String, ? extends SearchParseElement> parseElements() { public Map<String, ? extends SearchParseElement> parseElements() {
ImmutableMap.Builder<String, SearchParseElement> parseElements = ImmutableMap.builder(); Map<String, SearchParseElement> parseElements = new HashMap<>();
parseElements.put("fielddata_fields", new FieldDataFieldsParseElement()) parseElements.put("fielddata_fields", new FieldDataFieldsParseElement());
.put("fielddataFields", new FieldDataFieldsParseElement()); parseElements.put("fielddataFields", new FieldDataFieldsParseElement());
return parseElements.build(); return unmodifiableMap(parseElements);
} }
@Override @Override

View File

@ -18,10 +18,6 @@
*/ */
package org.elasticsearch.search.fetch.script; package org.elasticsearch.search.fetch.script;
import com.google.common.collect.ImmutableMap;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.script.LeafSearchScript; import org.elasticsearch.script.LeafSearchScript;
import org.elasticsearch.search.SearchHitField; import org.elasticsearch.search.SearchHitField;
import org.elasticsearch.search.SearchParseElement; import org.elasticsearch.search.SearchParseElement;
@ -38,21 +34,23 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import static java.util.Collections.unmodifiableMap;
/** /**
* *
*/ */
public class ScriptFieldsFetchSubPhase implements FetchSubPhase { public class ScriptFieldsFetchSubPhase implements FetchSubPhase {
private static final Map<String, SearchParseElement> PARSE_ELEMENTS;
@Inject static {
public ScriptFieldsFetchSubPhase() { Map<String, SearchParseElement> parseElements = new HashMap<>();
parseElements.put("script_fields", new ScriptFieldsParseElement());
parseElements.put("scriptFields", new ScriptFieldsParseElement());
PARSE_ELEMENTS = unmodifiableMap(parseElements);
} }
@Override @Override
public Map<String, ? extends SearchParseElement> parseElements() { public Map<String, ? extends SearchParseElement> parseElements() {
ImmutableMap.Builder<String, SearchParseElement> parseElements = ImmutableMap.builder(); return PARSE_ELEMENTS;
parseElements.put("script_fields", new ScriptFieldsParseElement())
.put("scriptFields", new ScriptFieldsParseElement());
return parseElements.build();
} }
@Override @Override

View File

@ -19,12 +19,9 @@
package org.elasticsearch.search.fetch.source; package org.elasticsearch.search.fetch.source;
import com.google.common.collect.ImmutableMap;
import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.search.SearchParseElement; import org.elasticsearch.search.SearchParseElement;
import org.elasticsearch.search.fetch.FetchSubPhase; import org.elasticsearch.search.fetch.FetchSubPhase;
import org.elasticsearch.search.internal.InternalSearchHit; import org.elasticsearch.search.internal.InternalSearchHit;
@ -34,20 +31,16 @@ import org.elasticsearch.search.lookup.SourceLookup;
import java.io.IOException; import java.io.IOException;
import java.util.Map; import java.util.Map;
import static java.util.Collections.singletonMap;
/** /**
*/ */
public class FetchSourceSubPhase implements FetchSubPhase { public class FetchSourceSubPhase implements FetchSubPhase {
private static final Map<String, SearchParseElement> PARSE_ELEMENTS = singletonMap("_source", new FetchSourceParseElement());
@Inject
public FetchSourceSubPhase() {
}
@Override @Override
public Map<String, ? extends SearchParseElement> parseElements() { public Map<String, ? extends SearchParseElement> parseElements() {
ImmutableMap.Builder<String, SearchParseElement> parseElements = ImmutableMap.builder(); return PARSE_ELEMENTS;
parseElements.put("_source", new FetchSourceParseElement());
return parseElements.build();
} }
@Override @Override

View File

@ -18,12 +18,24 @@
*/ */
package org.elasticsearch.search.lookup; package org.elasticsearch.search.lookup;
import com.google.common.collect.ImmutableMap.Builder;
import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.index.LeafReaderContext;
public class IndexLookup { import java.util.HashMap;
import java.util.Map;
import static java.util.Collections.unmodifiableMap;
public class IndexLookup {
public static final Map<String, Object> NAMES;
static {
Map<String, Object> names = new HashMap<>();
names.put("_FREQUENCIES", IndexLookup.FLAG_FREQUENCIES);
names.put("_POSITIONS", IndexLookup.FLAG_POSITIONS);
names.put("_OFFSETS", IndexLookup.FLAG_OFFSETS);
names.put("_PAYLOADS", IndexLookup.FLAG_PAYLOADS);
names.put("_CACHE", IndexLookup.FLAG_CACHE);
NAMES = unmodifiableMap(names);
}
/** /**
* Flag to pass to {@link IndexField#get(Object, int)} if you require * Flag to pass to {@link IndexField#get(Object, int)} if you require
* offsets in the returned {@link IndexFieldTerm}. * offsets in the returned {@link IndexFieldTerm}.
@ -55,15 +67,7 @@ public class IndexLookup {
*/ */
public static final int FLAG_CACHE = 32; public static final int FLAG_CACHE = 32;
public IndexLookup(Builder<String, Object> builder) { public static LeafIndexLookup getLeafIndexLookup(LeafReaderContext context) {
builder.put("_FREQUENCIES", IndexLookup.FLAG_FREQUENCIES);
builder.put("_POSITIONS", IndexLookup.FLAG_POSITIONS);
builder.put("_OFFSETS", IndexLookup.FLAG_OFFSETS);
builder.put("_PAYLOADS", IndexLookup.FLAG_PAYLOADS);
builder.put("_CACHE", IndexLookup.FLAG_CACHE);
}
public LeafIndexLookup getLeafIndexLookup(LeafReaderContext context) {
return new LeafIndexLookup(context); return new LeafIndexLookup(context);
} }

View File

@ -19,7 +19,6 @@
package org.elasticsearch.search.lookup; package org.elasticsearch.search.lookup;
import com.google.common.collect.ImmutableMap;
import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.index.LeafReaderContext;
import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Nullable;
import org.elasticsearch.index.fielddata.IndexFieldDataService; import org.elasticsearch.index.fielddata.IndexFieldDataService;
@ -36,17 +35,10 @@ public class SearchLookup {
final FieldsLookup fieldsLookup; final FieldsLookup fieldsLookup;
final IndexLookup indexLookup;
final ImmutableMap<String, Object> asMap;
public SearchLookup(MapperService mapperService, IndexFieldDataService fieldDataService, @Nullable String[] types) { public SearchLookup(MapperService mapperService, IndexFieldDataService fieldDataService, @Nullable String[] types) {
ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();
docMap = new DocLookup(mapperService, fieldDataService, types); docMap = new DocLookup(mapperService, fieldDataService, types);
sourceLookup = new SourceLookup(); sourceLookup = new SourceLookup();
fieldsLookup = new FieldsLookup(mapperService, types); fieldsLookup = new FieldsLookup(mapperService, types);
indexLookup = new IndexLookup(builder);
asMap = builder.build();
} }
public LeafSearchLookup getLeafSearchLookup(LeafReaderContext context) { public LeafSearchLookup getLeafSearchLookup(LeafReaderContext context) {
@ -54,8 +46,8 @@ public class SearchLookup {
docMap.getLeafDocLookup(context), docMap.getLeafDocLookup(context),
sourceLookup, sourceLookup,
fieldsLookup.getLeafFieldsLookup(context), fieldsLookup.getLeafFieldsLookup(context),
indexLookup.getLeafIndexLookup(context), IndexLookup.getLeafIndexLookup(context),
asMap); IndexLookup.NAMES);
} }
public DocLookup doc() { public DocLookup doc() {

View File

@ -19,12 +19,28 @@
package org.elasticsearch.search.query; package org.elasticsearch.search.query;
import com.google.common.collect.ImmutableMap;
import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.Term; import org.apache.lucene.index.Term;
import org.apache.lucene.queries.MinDocQuery; import org.apache.lucene.queries.MinDocQuery;
import org.apache.lucene.search.*; import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Collector;
import org.apache.lucene.search.ConstantScoreQuery;
import org.apache.lucene.search.FieldDoc;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.MultiCollector;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TimeLimitingCollector;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.TopDocsCollector;
import org.apache.lucene.search.TopFieldCollector;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.search.TotalHitCountCollector;
import org.apache.lucene.search.Weight;
import org.elasticsearch.action.search.SearchType; import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.lucene.Lucene; import org.elasticsearch.common.lucene.Lucene;
@ -43,10 +59,13 @@ import org.elasticsearch.search.sort.TrackScoresParseElement;
import org.elasticsearch.search.suggest.SuggestPhase; import org.elasticsearch.search.suggest.SuggestPhase;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import static java.util.Collections.unmodifiableMap;
/** /**
* *
*/ */
@ -65,29 +84,30 @@ public class QueryPhase implements SearchPhase {
@Override @Override
public Map<String, ? extends SearchParseElement> parseElements() { public Map<String, ? extends SearchParseElement> parseElements() {
ImmutableMap.Builder<String, SearchParseElement> parseElements = ImmutableMap.builder(); Map<String, SearchParseElement> parseElements = new HashMap<>();
parseElements.put("from", new FromParseElement()).put("size", new SizeParseElement()) parseElements.put("from", new FromParseElement());
.put("indices_boost", new IndicesBoostParseElement()) parseElements.put("size", new SizeParseElement());
.put("indicesBoost", new IndicesBoostParseElement()) parseElements.put("indices_boost", new IndicesBoostParseElement());
.put("query", new QueryParseElement()) parseElements.put("indicesBoost", new IndicesBoostParseElement());
.put("queryBinary", new QueryBinaryParseElement()) parseElements.put("query", new QueryParseElement());
.put("query_binary", new QueryBinaryParseElement()) parseElements.put("queryBinary", new QueryBinaryParseElement());
.put("filter", new PostFilterParseElement()) // For bw comp reason, should be removed in version 1.1 parseElements.put("query_binary", new QueryBinaryParseElement());
.put("post_filter", new PostFilterParseElement()) parseElements.put("filter", new PostFilterParseElement()); // For bw comp reason, should be removed in version 1.1
.put("postFilter", new PostFilterParseElement()) parseElements.put("post_filter", new PostFilterParseElement());
.put("filterBinary", new FilterBinaryParseElement()) parseElements.put("postFilter", new PostFilterParseElement());
.put("filter_binary", new FilterBinaryParseElement()) parseElements.put("filterBinary", new FilterBinaryParseElement());
.put("sort", new SortParseElement()) parseElements.put("filter_binary", new FilterBinaryParseElement());
.put("trackScores", new TrackScoresParseElement()) parseElements.put("sort", new SortParseElement());
.put("track_scores", new TrackScoresParseElement()) parseElements.put("trackScores", new TrackScoresParseElement());
.put("min_score", new MinScoreParseElement()) parseElements.put("track_scores", new TrackScoresParseElement());
.put("minScore", new MinScoreParseElement()) parseElements.put("min_score", new MinScoreParseElement());
.put("timeout", new TimeoutParseElement()) parseElements.put("minScore", new MinScoreParseElement());
.put("terminate_after", new TerminateAfterParseElement()) parseElements.put("timeout", new TimeoutParseElement());
.putAll(aggregationPhase.parseElements()) parseElements.put("terminate_after", new TerminateAfterParseElement());
.putAll(suggestPhase.parseElements()) parseElements.putAll(aggregationPhase.parseElements());
.putAll(rescorePhase.parseElements()); parseElements.putAll(suggestPhase.parseElements());
return parseElements.build(); parseElements.putAll(rescorePhase.parseElements());
return unmodifiableMap(parseElements);
} }
@Override @Override

View File

@ -19,8 +19,6 @@
package org.elasticsearch.search.rescore; package org.elasticsearch.search.rescore;
import com.google.common.collect.ImmutableMap;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.TopDocs;
import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.component.AbstractComponent; import org.elasticsearch.common.component.AbstractComponent;
@ -33,9 +31,12 @@ import org.elasticsearch.search.internal.SearchContext;
import java.io.IOException; import java.io.IOException;
import java.util.Map; import java.util.Map;
import static java.util.Collections.singletonMap;
/** /**
*/ */
public class RescorePhase extends AbstractComponent implements SearchPhase { public class RescorePhase extends AbstractComponent implements SearchPhase {
private static final Map<String, SearchParseElement> PARSE_ELEMENTS = singletonMap("rescore", new RescoreParseElement());
@Inject @Inject
public RescorePhase(Settings settings) { public RescorePhase(Settings settings) {
@ -44,9 +45,7 @@ public class RescorePhase extends AbstractComponent implements SearchPhase {
@Override @Override
public Map<String, ? extends SearchParseElement> parseElements() { public Map<String, ? extends SearchParseElement> parseElements() {
ImmutableMap.Builder<String, SearchParseElement> parseElements = ImmutableMap.builder(); return PARSE_ELEMENTS;
parseElements.put("rescore", new RescoreParseElement());
return parseElements.build();
} }
@Override @Override

View File

@ -19,8 +19,6 @@
package org.elasticsearch.search.sort; package org.elasticsearch.search.sort;
import com.google.common.collect.ImmutableMap;
import org.apache.lucene.search.Filter; import org.apache.lucene.search.Filter;
import org.apache.lucene.search.QueryWrapperFilter; import org.apache.lucene.search.QueryWrapperFilter;
import org.apache.lucene.search.Sort; import org.apache.lucene.search.Sort;
@ -34,17 +32,19 @@ import org.elasticsearch.index.fielddata.IndexFieldData;
import org.elasticsearch.index.fielddata.IndexFieldData.XFieldComparatorSource.Nested; import org.elasticsearch.index.fielddata.IndexFieldData.XFieldComparatorSource.Nested;
import org.elasticsearch.index.mapper.MappedFieldType; import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.core.LongFieldMapper; import org.elasticsearch.index.mapper.core.LongFieldMapper;
import org.elasticsearch.index.mapper.object.ObjectMapper;
import org.elasticsearch.index.query.support.NestedInnerQueryParseSupport; import org.elasticsearch.index.query.support.NestedInnerQueryParseSupport;
import org.elasticsearch.search.MultiValueMode; import org.elasticsearch.search.MultiValueMode;
import org.elasticsearch.search.SearchParseElement; import org.elasticsearch.search.SearchParseElement;
import org.elasticsearch.search.SearchParseException; import org.elasticsearch.search.SearchParseException;
import org.elasticsearch.search.internal.SearchContext; import org.elasticsearch.search.internal.SearchContext;
import org.elasticsearch.search.internal.SubSearchContext;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import static java.util.Collections.unmodifiableMap;
/** /**
* *
@ -62,16 +62,16 @@ public class SortParseElement implements SearchParseElement {
public static final String SCORE_FIELD_NAME = "_score"; public static final String SCORE_FIELD_NAME = "_score";
public static final String DOC_FIELD_NAME = "_doc"; public static final String DOC_FIELD_NAME = "_doc";
private final ImmutableMap<String, SortParser> parsers; private static final Map<String, SortParser> PARSERS;
public SortParseElement() { static {
ImmutableMap.Builder<String, SortParser> builder = ImmutableMap.builder(); Map<String, SortParser> parsers = new HashMap<>();
addParser(builder, new ScriptSortParser()); addParser(parsers, new ScriptSortParser());
addParser(builder, new GeoDistanceSortParser()); addParser(parsers, new GeoDistanceSortParser());
this.parsers = builder.build(); PARSERS = unmodifiableMap(parsers);
} }
private void addParser(ImmutableMap.Builder<String, SortParser> parsers, SortParser parser) { private static void addParser(Map<String, SortParser> parsers, SortParser parser) {
for (String name : parser.names()) { for (String name : parser.names()) {
parsers.put(name, parser); parsers.put(name, parser);
} }
@ -140,8 +140,8 @@ public class SortParseElement implements SearchParseElement {
} }
addSortField(context, sortFields, fieldName, reverse, unmappedType, missing, sortMode, nestedFilterParseHelper); addSortField(context, sortFields, fieldName, reverse, unmappedType, missing, sortMode, nestedFilterParseHelper);
} else { } else {
if (parsers.containsKey(fieldName)) { if (PARSERS.containsKey(fieldName)) {
sortFields.add(parsers.get(fieldName).parse(parser, context)); sortFields.add(PARSERS.get(fieldName).parse(parser, context));
} else { } else {
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) { if (token == XContentParser.Token.FIELD_NAME) {

View File

@ -18,7 +18,6 @@
*/ */
package org.elasticsearch.search.suggest; package org.elasticsearch.search.suggest;
import com.google.common.collect.ImmutableMap;
import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.util.CharsRefBuilder; import org.apache.lucene.util.CharsRefBuilder;
import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ElasticsearchException;
@ -38,23 +37,24 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import static java.util.Collections.singletonMap;
/** /**
*/ */
public class SuggestPhase extends AbstractComponent implements SearchPhase { public class SuggestPhase extends AbstractComponent implements SearchPhase {
private final Map<String, SearchParseElement> parseElements;
private final SuggestParseElement parseElement; private final SuggestParseElement parseElement;
@Inject @Inject
public SuggestPhase(Settings settings, SuggestParseElement suggestParseElement) { public SuggestPhase(Settings settings, SuggestParseElement suggestParseElement) {
super(settings); super(settings);
this.parseElement = suggestParseElement; this.parseElement = suggestParseElement;
parseElements = singletonMap("suggest", parseElement);
} }
@Override @Override
public Map<String, ? extends SearchParseElement> parseElements() { public Map<String, ? extends SearchParseElement> parseElements() {
ImmutableMap.Builder<String, SearchParseElement> parseElements = ImmutableMap.builder(); return parseElements;
parseElements.put("suggest", parseElement);
return parseElements.build();
} }
public SuggestParseElement parseElement() { public SuggestParseElement parseElement() {

View File

@ -18,8 +18,6 @@
*/ */
package org.elasticsearch.search.suggest.completion; package org.elasticsearch.search.suggest.completion;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import org.apache.lucene.codecs.CodecUtil; import org.apache.lucene.codecs.CodecUtil;
import org.apache.lucene.codecs.FieldsConsumer; import org.apache.lucene.codecs.FieldsConsumer;
import org.apache.lucene.codecs.FieldsProducer; import org.apache.lucene.codecs.FieldsProducer;
@ -59,6 +57,8 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import static java.util.Collections.singletonMap;
/** /**
* This {@link PostingsFormat} is basically a T-Sink for a default postings * This {@link PostingsFormat} is basically a T-Sink for a default postings
* format that is used to store postings on disk fitting the lucene APIs and * format that is used to store postings on disk fitting the lucene APIs and
@ -75,18 +75,12 @@ public class Completion090PostingsFormat extends PostingsFormat {
public static final int SUGGEST_VERSION_CURRENT = SUGGEST_CODEC_VERSION; public static final int SUGGEST_VERSION_CURRENT = SUGGEST_CODEC_VERSION;
public static final String EXTENSION = "cmp"; public static final String EXTENSION = "cmp";
private final static ESLogger logger = Loggers.getLogger(Completion090PostingsFormat.class); private static final ESLogger logger = Loggers.getLogger(Completion090PostingsFormat.class);
private static final CompletionLookupProvider LOOKUP_PROVIDER = new AnalyzingCompletionLookupProvider(true, false, true, false);
private static final Map<String, CompletionLookupProvider> PROVIDERS = singletonMap(LOOKUP_PROVIDER.getName(), LOOKUP_PROVIDER);
private PostingsFormat delegatePostingsFormat; private PostingsFormat delegatePostingsFormat;
private final static Map<String, CompletionLookupProvider> providers;
private CompletionLookupProvider writeProvider; private CompletionLookupProvider writeProvider;
static {
final CompletionLookupProvider provider = new AnalyzingCompletionLookupProvider(true, false, true, false);
final Builder<String, CompletionLookupProvider> builder = ImmutableMap.builder();
providers = builder.put(provider.getName(), provider).build();
}
public Completion090PostingsFormat(PostingsFormat delegatePostingsFormat, CompletionLookupProvider provider) { public Completion090PostingsFormat(PostingsFormat delegatePostingsFormat, CompletionLookupProvider provider) {
super(CODEC_NAME); super(CODEC_NAME);
this.delegatePostingsFormat = delegatePostingsFormat; this.delegatePostingsFormat = delegatePostingsFormat;
@ -173,7 +167,7 @@ public class Completion090PostingsFormat extends PostingsFormat {
try { try {
PostingsFormat delegatePostingsFormat = PostingsFormat.forName(input.readString()); PostingsFormat delegatePostingsFormat = PostingsFormat.forName(input.readString());
String providerName = input.readString(); String providerName = input.readString();
CompletionLookupProvider completionLookupProvider = providers.get(providerName); CompletionLookupProvider completionLookupProvider = PROVIDERS.get(providerName);
if (completionLookupProvider == null) { if (completionLookupProvider == null) {
throw new IllegalStateException("no provider with name [" + providerName + "] registered"); throw new IllegalStateException("no provider with name [" + providerName + "] registered");
} }

View File

@ -21,7 +21,6 @@ package org.elasticsearch.snapshots;
import com.carrotsearch.hppc.cursors.ObjectCursor; import com.carrotsearch.hppc.cursors.ObjectCursor;
import com.carrotsearch.hppc.cursors.ObjectObjectCursor; import com.carrotsearch.hppc.cursors.ObjectObjectCursor;
import com.google.common.collect.ImmutableMap;
import org.apache.lucene.util.CollectionUtil; import org.apache.lucene.util.CollectionUtil;
import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.ExceptionsHelper;
@ -66,12 +65,15 @@ import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
import static java.util.Collections.unmodifiableMap;
import static org.elasticsearch.cluster.SnapshotsInProgress.completed; import static org.elasticsearch.cluster.SnapshotsInProgress.completed;
/** /**
@ -466,9 +468,9 @@ public class SnapshotsService extends AbstractLifecycleComponent<SnapshotsServic
* @param snapshotId snapshot id * @param snapshotId snapshot id
* @return map of shard id to snapshot status * @return map of shard id to snapshot status
*/ */
public ImmutableMap<ShardId, IndexShardSnapshotStatus> snapshotShards(SnapshotId snapshotId) throws IOException { public Map<ShardId, IndexShardSnapshotStatus> snapshotShards(SnapshotId snapshotId) throws IOException {
validate(snapshotId); validate(snapshotId);
ImmutableMap.Builder<ShardId, IndexShardSnapshotStatus> shardStatusBuilder = ImmutableMap.builder(); Map<ShardId, IndexShardSnapshotStatus> shardStatus = new HashMap<>();
Repository repository = repositoriesService.repository(snapshotId.getRepository()); Repository repository = repositoriesService.repository(snapshotId.getRepository());
IndexShardRepository indexShardRepository = repositoriesService.indexShardRepository(snapshotId.getRepository()); IndexShardRepository indexShardRepository = repositoriesService.indexShardRepository(snapshotId.getRepository());
Snapshot snapshot = repository.readSnapshot(snapshotId); Snapshot snapshot = repository.readSnapshot(snapshotId);
@ -484,15 +486,15 @@ public class SnapshotsService extends AbstractLifecycleComponent<SnapshotsServic
IndexShardSnapshotStatus shardSnapshotStatus = new IndexShardSnapshotStatus(); IndexShardSnapshotStatus shardSnapshotStatus = new IndexShardSnapshotStatus();
shardSnapshotStatus.updateStage(IndexShardSnapshotStatus.Stage.FAILURE); shardSnapshotStatus.updateStage(IndexShardSnapshotStatus.Stage.FAILURE);
shardSnapshotStatus.failure(shardFailure.reason()); shardSnapshotStatus.failure(shardFailure.reason());
shardStatusBuilder.put(shardId, shardSnapshotStatus); shardStatus.put(shardId, shardSnapshotStatus);
} else { } else {
IndexShardSnapshotStatus shardSnapshotStatus = indexShardRepository.snapshotStatus(snapshotId, snapshot.version(), shardId); IndexShardSnapshotStatus shardSnapshotStatus = indexShardRepository.snapshotStatus(snapshotId, snapshot.version(), shardId);
shardStatusBuilder.put(shardId, shardSnapshotStatus); shardStatus.put(shardId, shardSnapshotStatus);
} }
} }
} }
} }
return shardStatusBuilder.build(); return unmodifiableMap(shardStatus);
} }

View File

@ -19,6 +19,8 @@
package org.elasticsearch.tribe; package org.elasticsearch.tribe;
import com.carrotsearch.hppc.cursors.ObjectObjectCursor;
import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.support.master.TransportMasterNodeReadAction; import org.elasticsearch.action.support.master.TransportMasterNodeReadAction;
import org.elasticsearch.cluster.ClusterChangedEvent; import org.elasticsearch.cluster.ClusterChangedEvent;
@ -242,7 +244,10 @@ public class TribeService extends AbstractLifecycleComponent<TribeService> {
for (DiscoveryNode tribe : tribeState.nodes()) { for (DiscoveryNode tribe : tribeState.nodes()) {
if (currentState.nodes().get(tribe.id()) == null) { if (currentState.nodes().get(tribe.id()) == null) {
// a new node, add it, but also add the tribe name to the attributes // a new node, add it, but also add the tribe name to the attributes
Map<String, String> tribeAttr = new HashMap<>(tribe.attributes()); Map<String, String> tribeAttr = new HashMap<>();
for (ObjectObjectCursor<String, String> attr : tribe.attributes()) {
tribeAttr.put(attr.key, attr.value);
}
tribeAttr.put(TRIBE_NAME, tribeName); tribeAttr.put(TRIBE_NAME, tribeName);
DiscoveryNode discoNode = new DiscoveryNode(tribe.name(), tribe.id(), tribe.getHostName(), tribe.getHostAddress(), tribe.address(), unmodifiableMap(tribeAttr), tribe.version()); DiscoveryNode discoNode = new DiscoveryNode(tribe.name(), tribe.id(), tribe.getHostName(), tribe.getHostAddress(), tribe.address(), unmodifiableMap(tribeAttr), tribe.version());
logger.info("[{}] adding node [{}]", tribeName, discoNode); logger.info("[{}] adding node [{}]", tribeName, discoNode);

View File

@ -140,6 +140,7 @@ com.google.common.collect.ImmutableMap#of(java.lang.Object, java.lang.Object, ja
com.google.common.collect.ImmutableMap#of(java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object) com.google.common.collect.ImmutableMap#of(java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object)
com.google.common.collect.ImmutableMap#of(java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object) com.google.common.collect.ImmutableMap#of(java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object)
com.google.common.collect.ImmutableMap#copyOf(java.util.Map) com.google.common.collect.ImmutableMap#copyOf(java.util.Map)
com.google.common.collect.ImmutableMap$Builder
@defaultMessage Do not violate java's access system @defaultMessage Do not violate java's access system
java.lang.reflect.AccessibleObject#setAccessible(boolean) java.lang.reflect.AccessibleObject#setAccessible(boolean)

View File

@ -19,6 +19,8 @@
package org.elasticsearch.plugin.discovery.multicast; package org.elasticsearch.plugin.discovery.multicast;
import com.carrotsearch.hppc.cursors.ObjectObjectCursor;
import org.apache.lucene.util.Constants; import org.apache.lucene.util.Constants;
import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.Version; import org.elasticsearch.Version;
@ -44,7 +46,13 @@ import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.discovery.zen.ping.PingContextProvider; import org.elasticsearch.discovery.zen.ping.PingContextProvider;
import org.elasticsearch.discovery.zen.ping.ZenPing; import org.elasticsearch.discovery.zen.ping.ZenPing;
import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.*; import org.elasticsearch.transport.EmptyTransportResponseHandler;
import org.elasticsearch.transport.TransportChannel;
import org.elasticsearch.transport.TransportException;
import org.elasticsearch.transport.TransportRequest;
import org.elasticsearch.transport.TransportRequestHandler;
import org.elasticsearch.transport.TransportResponse;
import org.elasticsearch.transport.TransportService;
import java.io.IOException; import java.io.IOException;
import java.net.SocketAddress; import java.net.SocketAddress;
@ -483,8 +491,8 @@ public class MulticastZenPing extends AbstractLifecycleComponent<ZenPing> implem
} }
builder.startObject("attributes"); builder.startObject("attributes");
for (Map.Entry<String, String> attr : localNode.attributes().entrySet()) { for (ObjectObjectCursor<String, String> attr : localNode.attributes()) {
builder.field(attr.getKey(), attr.getValue()); builder.field(attr.key, attr.value);
} }
builder.endObject(); builder.endObject();