Prefer using Splitter to String.split

String.split(String) has surprising behaviour [1]:

String[] nothing = "".split(":"); // results in [""]
String[] bunchOfNothing = ":".split(":"); // results in []

More examples:

input  | input.split(":")  | Splitter.on(':').split(input)
=======|===================|==============================
""     | [""]              | [""]
":"    | []                | ["", ""]
":::"  | []                | ["", "", "", ""]
"a:::" | ["a"]             | ["a", "", "", ""]
":::b" | ["", "", "", "b"] | ["", "", "", "b"]

In addition using Splitter makes the code more readable as Splitter has
nicer methods that make it clearer which high-level operation should be
performed. E.g. in some places we can use
Splitter.on(CharMatcher.anyOf(something)) instead of matching on
patterns.

Tests and classes that are used by the GWT UI are not adapted.

[1] http://konigsberg.blogspot.com/2009/11/final-thoughts-java-puzzler-splitting.html

Change-Id: I6f141fb492e2fb94544089d794f245d0885f8649
Signed-off-by: Edwin Kempin <ekempin@google.com>
This commit is contained in:
Edwin Kempin
2018-02-09 16:49:35 +01:00
parent 2bf19ee6ee
commit 5174d2d95e
19 changed files with 99 additions and 75 deletions

View File

@@ -17,6 +17,8 @@ package com.google.gerrit.sshd;
import static com.google.gerrit.extensions.registration.PrivateInternals_DynamicTypes.registerInParentInjectors;
import static com.google.inject.Scopes.SINGLETON;
import com.google.common.base.CharMatcher;
import com.google.common.base.Splitter;
import com.google.gerrit.extensions.registration.DynamicMap;
import com.google.gerrit.lifecycle.LifecycleModule;
import com.google.gerrit.server.DynamicOptions;
@@ -37,6 +39,7 @@ import com.google.inject.internal.UniqueAnnotations;
import com.google.inject.servlet.RequestScoped;
import java.net.SocketAddress;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import org.apache.sshd.server.CommandFactory;
@@ -108,10 +111,10 @@ public class SshModule extends LifecycleModule {
CommandName gerrit = Commands.named("gerrit");
for (Map.Entry<String, String> e : aliases.entrySet()) {
String name = e.getKey();
String[] dest = e.getValue().split("[ \\t]+");
CommandName cmd = Commands.named(dest[0]);
for (int i = 1; i < dest.length; i++) {
cmd = Commands.named(cmd, dest[i]);
List<String> dest = Splitter.on(CharMatcher.whitespace()).splitToList(e.getValue());
CommandName cmd = Commands.named(dest.get(0));
for (int i = 1; i < dest.size(); i++) {
cmd = Commands.named(cmd, dest.get(i));
}
bind(Commands.key(gerrit, name)).toProvider(new AliasCommandProvider(cmd));
}