Skip to content

Commit

Permalink
Merge pull request elastic#18110 from jasontedor/strings-split-as-array
Browse files Browse the repository at this point in the history
Remove Strings#splitStringToArray

Remove arbitrary separator/wildcard from PathTrie
  • Loading branch information
jasontedor committed May 4, 2016
2 parents 247b5c8 + 9fe5ce9 commit 78d615f
Show file tree
Hide file tree
Showing 16 changed files with 29 additions and 110 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.common.Base64;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.util.concurrent.AtomicArray;
import org.elasticsearch.search.SearchPhaseResult;
import org.elasticsearch.search.internal.InternalScrollSearchRequest;
Expand Down Expand Up @@ -89,7 +88,7 @@ static ParsedScrollId parseScrollId(String scrollId) {
} catch (Exception e) {
throw new IllegalArgumentException("Failed to decode scrollId", e);
}
String[] elements = Strings.splitStringToArray(spare.get(), ';');
String[] elements = spare.get().toString().split(";");
if (elements.length < 2) {
throw new IllegalArgumentException("Malformed scrollId [" + scrollId + "]");
}
Expand Down
40 changes: 2 additions & 38 deletions core/src/main/java/org/elasticsearch/common/Strings.java
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
Expand Down Expand Up @@ -557,7 +556,8 @@ public static Set<String> splitStringByCommaToSet(final String s) {
}

public static String[] splitStringByCommaToArray(final String s) {
return splitStringToArray(s, ',');
if (s == null || s.isEmpty()) return Strings.EMPTY_ARRAY;
else return s.split(",");
}

public static Set<String> splitStringToSet(final String s, final char c) {
Expand Down Expand Up @@ -588,42 +588,6 @@ public static Set<String> splitStringToSet(final String s, final char c) {
return result;
}

public static String[] splitStringToArray(final CharSequence s, final char c) {
if (s == null || s.length() == 0) {
return Strings.EMPTY_ARRAY;
}
int count = 1;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == c) {
count++;
}
}
final String[] result = new String[count];
final StringBuilder builder = new StringBuilder();
int res = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == c) {
if (builder.length() > 0) {
result[res++] = builder.toString();
builder.setLength(0);
}

} else {
builder.append(s.charAt(i));
}
}
if (builder.length() > 0) {
result[res++] = builder.toString();
}
if (res != count) {
// we have empty strings, copy over to a new array
String[] result1 = new String[res];
System.arraycopy(result, 0, result1, 0, res);
return result1;
}
return result;
}

/**
* Split a String at the first occurrence of the delimiter.
* Does not include the delimiter in the result.
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/java/org/elasticsearch/common/Table.java
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ public Table addCell(Object value, String attributes) {
// get the attributes of the header cell we are going to add
mAttr.putAll(headers.get(currentCells.size()).attr);
}
String[] sAttrs = Strings.splitStringToArray(attributes, ';');
String[] sAttrs = attributes.split(";");
for (String sAttr : sAttrs) {
if (sAttr.length() == 0) {
continue;
Expand Down
20 changes: 6 additions & 14 deletions core/src/main/java/org/elasticsearch/common/path/PathTrie.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,12 @@

package org.elasticsearch.common.path;

import org.elasticsearch.common.Strings;

import java.util.HashMap;
import java.util.Map;

import static java.util.Collections.emptyMap;
import static java.util.Collections.unmodifiableMap;

/**
*
*/
public class PathTrie<T> {

public interface Decoder {
Expand All @@ -38,17 +33,14 @@ public interface Decoder {

private final Decoder decoder;
private final TrieNode root;
private final char separator;
private T rootValue;

public PathTrie(Decoder decoder) {
this('/', "*", decoder);
}
private static final String SEPARATOR = "/";
private static final String WILDCARD = "*";

public PathTrie(char separator, String wildcard, Decoder decoder) {
public PathTrie(Decoder decoder) {
this.decoder = decoder;
this.separator = separator;
root = new TrieNode(new String(new char[]{separator}), null, wildcard);
root = new TrieNode(SEPARATOR, null, WILDCARD);
}

public class TrieNode {
Expand Down Expand Up @@ -196,7 +188,7 @@ public String toString() {
}

public void insert(String path, T value) {
String[] strings = Strings.splitStringToArray(path, separator);
String[] strings = path.split(SEPARATOR);
if (strings.length == 0) {
rootValue = value;
return;
Expand All @@ -217,7 +209,7 @@ public T retrieve(String path, Map<String, String> params) {
if (path.length() == 0) {
return rootValue;
}
String[] strings = Strings.splitStringToArray(path, separator);
String[] strings = path.split(SEPARATOR);
if (strings.length == 0) {
return rootValue;
}
Expand Down
13 changes: 0 additions & 13 deletions core/src/main/java/org/elasticsearch/common/settings/Settings.java
Original file line number Diff line number Diff line change
Expand Up @@ -899,19 +899,6 @@ public Builder put(Dictionary<Object,Object> properties) {
return this;
}

public Builder loadFromDelimitedString(String value, char delimiter) {
String[] values = Strings.splitStringToArray(value, delimiter);
for (String s : values) {
int index = s.indexOf('=');
if (index == -1) {
throw new IllegalArgumentException(
"value [" + s + "] for settings loaded with delimiter [" + delimiter + "] is malformed, missing =");
}
map.put(s.substring(0, index), s.substring(index + 1));
}
return this;
}

/**
* Loads settings from the actual string content that represents them using the
* {@link SettingsLoaderFactory#loaderFromSource(String)}.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.RamUsageEstimator;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.hash.MurmurHash3;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
Expand Down Expand Up @@ -75,7 +74,7 @@ public static Factory buildFromString(@Nullable String config) {
if (config == null) {
return buildDefault();
}
String[] sEntries = Strings.splitStringToArray(config, ',');
String[] sEntries = config.split(",");
if (sEntries.length == 0) {
if (config.length() > 0) {
return new Factory(new Entry[]{new Entry(0, Double.parseDouble(config))});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public class XContentMapValues {
*/
public static List<Object> extractRawValues(String path, Map<String, Object> map) {
List<Object> values = new ArrayList<>();
String[] pathElements = Strings.splitStringToArray(path, '.');
String[] pathElements = path.split("\\.");
if (pathElements.length == 0) {
return values;
}
Expand Down Expand Up @@ -93,7 +93,7 @@ private static void extractRawValues(List values, List<Object> part, String[] pa
}

public static Object extractValue(String path, Map<String, Object> map) {
String[] pathElements = Strings.splitStringToArray(path, '.');
String[] pathElements = path.split("\\.");
if (pathElements.length == 0) {
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,6 @@

package org.elasticsearch.index.mapper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexableField;
import org.elasticsearch.Version;
Expand All @@ -51,6 +44,13 @@
import org.elasticsearch.index.mapper.object.ArrayValueMapperParser;
import org.elasticsearch.index.mapper.object.ObjectMapper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/** A parser for documents, given mappings from a DocumentMapper */
final class DocumentParser {

Expand Down Expand Up @@ -829,8 +829,7 @@ private static void parseCopy(String field, ParseContext context) throws IOExcep
// The path of the dest field might be completely different from the current one so we need to reset it
context = context.overridePath(new ContentPath(0));

// TODO: why Strings.splitStringToArray instead of String.split?
final String[] paths = Strings.splitStringToArray(field, '.');
final String[] paths = field.split("\\.");
final String fieldName = paths[paths.length-1];
ObjectMapper mapper = context.root();
ObjectMapper[] mappers = new ObjectMapper[paths.length-1];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
import org.elasticsearch.client.Client;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.geo.ShapeRelation;
import org.elasticsearch.common.geo.ShapesAvailability;
import org.elasticsearch.common.geo.SpatialStrategy;
Expand Down Expand Up @@ -379,7 +378,7 @@ private ShapeBuilder fetch(Client client, GetRequest getRequest, String path) th
throw new IllegalArgumentException("Shape with ID [" + getRequest.id() + "] in type [" + getRequest.type() + "] not found");
}

String[] pathElements = Strings.splitStringToArray(path, '.');
String[] pathElements = path.split("\\.");
int currentPathSlot = 0;

try (XContentParser parser = XContentHelper.createParser(response.getSourceAsBytesRef())) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -622,8 +622,8 @@ private FieldPath(String path) {
newPath = path;
}
}
this.pathElements = Strings.splitStringToArray(newPath, '.');
if (pathElements.length == 0) {
this.pathElements = newPath.split("\\.");
if (pathElements.length == 1 && pathElements[0].isEmpty()) {
throw new IllegalArgumentException("path [" + path + "] is not valid");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -492,7 +492,7 @@ public void tearDown() throws Exception {
private void registerTaskManageListeners(String actionMasks) {
for (String nodeName : internalCluster().getNodeNames()) {
DiscoveryNode node = internalCluster().getInstance(ClusterService.class, nodeName).localNode();
RecordingTaskManagerListener listener = new RecordingTaskManagerListener(node, Strings.splitStringToArray(actionMasks, ','));
RecordingTaskManagerListener listener = new RecordingTaskManagerListener(node, actionMasks.split(","));
((MockTaskManager) internalCluster().getInstance(TransportService.class, nodeName).getTaskManager()).addListener(listener);
RecordingTaskManagerListener oldListener = listeners.put(new Tuple<>(node.getName(), actionMasks), listener);
assertNull(oldListener);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,24 +38,6 @@

public class SettingsTests extends ESTestCase {

public void testLoadFromDelimitedString() {
Settings settings = Settings.builder()
.loadFromDelimitedString("key1=value1;key2=value2", ';')
.build();
assertThat(settings.get("key1"), equalTo("value1"));
assertThat(settings.get("key2"), equalTo("value2"));
assertThat(settings.getAsMap().size(), equalTo(2));
assertThat(settings.toDelimitedString(';'), equalTo("key1=value1;key2=value2;"));

settings = Settings.builder()
.loadFromDelimitedString("key1=value1;key2=value2;", ';')
.build();
assertThat(settings.get("key1"), equalTo("value1"));
assertThat(settings.get("key2"), equalTo("value2"));
assertThat(settings.getAsMap().size(), equalTo(2));
assertThat(settings.toDelimitedString(';'), equalTo("key1=value1;key2=value2;"));
}

public void testReplacePropertiesPlaceholderSystemProperty() {
String value = System.getProperty("java.home");
assertFalse(value.isEmpty());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ private InetAddress[] resolve(String value) throws IOException {
} else if (value.startsWith(GceAddressResolverType.PRIVATE_IP.configName)) {
// We extract the network interface from gce:privateIp:XX
String network = "0";
String[] privateIpConfig = Strings.splitStringToArray(value, ':');
String[] privateIpConfig = value.split(":");
if (privateIpConfig != null && privateIpConfig.length == 3) {
network = privateIpConfig[2];
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ public AzureRepository(RepositoryName name, RepositorySettings repositorySetting
// Remove starting / if any
basePath = Strings.trimLeadingCharacter(basePath, '/');
BlobPath path = new BlobPath();
for(String elem : Strings.splitStringToArray(basePath, '/')) {
for(String elem : basePath.split("/")) {
path = path.add(elem);
}
this.basePath = path;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ public S3Repository(RepositoryName name, RepositorySettings repositorySettings,
String basePath = getValue(repositorySettings, Repository.BASE_PATH_SETTING, Repositories.BASE_PATH_SETTING);
if (Strings.hasLength(basePath)) {
BlobPath path = new BlobPath();
for(String elem : Strings.splitStringToArray(basePath, '/')) {
for(String elem : basePath.split("/")) {
path = path.add(elem);
}
this.basePath = path;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@
import com.carrotsearch.randomizedtesting.generators.RandomInts;
import com.carrotsearch.randomizedtesting.generators.RandomPicks;
import com.carrotsearch.randomizedtesting.generators.RandomStrings;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.ingest.core.IngestDocument;

import java.util.ArrayList;
Expand Down Expand Up @@ -105,7 +103,7 @@ public static String addRandomField(Random random, IngestDocument ingestDocument
* that each node of the tree either doesn't exist or is a map, otherwise new fields cannot be added.
*/
public static boolean canAddField(String path, IngestDocument ingestDocument) {
String[] pathElements = Strings.splitStringToArray(path, '.');
String[] pathElements = path.split("\\.");
Map<String, Object> innerMap = ingestDocument.getSourceAndMetadata();
if (pathElements.length > 1) {
for (int i = 0; i < pathElements.length - 1; i++) {
Expand Down

0 comments on commit 78d615f

Please sign in to comment.