Browse Source

Use String.replace() instead of replaceAll() for non-regexp replacements (#105127)

* Use String.replace() instead of replaceAll() for non-regexp replacements

When arguments do not make use of regexp features replace() is a more efficient option, especially the char-variant.
Dmitry Cherniachenko 1 year ago
parent
commit
e21a4874ab
32 changed files with 60 additions and 72 deletions
  1. 1 1
      build-conventions/src/main/java/org/elasticsearch/gradle/internal/conventions/EclipseConventionPlugin.java
  2. 1 1
      build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/DependenciesInfoTask.java
  3. 1 2
      build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/ElasticsearchJavadocPlugin.java
  4. 1 1
      build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/release/ChangelogEntry.java
  5. 7 7
      build-tools/src/testFixtures/java/org/elasticsearch/gradle/internal/test/TestUtils.java
  6. 3 9
      libs/x-content/src/main/java/org/elasticsearch/xcontent/support/filtering/FilterPath.java
  7. 2 4
      modules/aggregations/src/main/java/org/elasticsearch/aggregations/metric/InternalMatrixStats.java
  8. 1 1
      modules/apm/src/main/java/org/elasticsearch/telemetry/apm/internal/tracing/APMTracer.java
  9. 1 1
      modules/rank-eval/src/main/java/org/elasticsearch/index/rankeval/RatedRequest.java
  10. 1 1
      plugins/analysis-phonetic/src/main/java/org/elasticsearch/plugin/analysis/phonetic/KoelnerPhonetik.java
  11. 2 2
      server/src/main/java/org/elasticsearch/common/logging/HeaderWarning.java
  12. 2 2
      server/src/main/java/org/elasticsearch/indices/AssociatedIndexDescriptor.java
  13. 2 2
      server/src/main/java/org/elasticsearch/indices/SystemIndexDescriptor.java
  14. 1 1
      test/fixtures/old-elasticsearch/src/main/java/oldes/OldElasticsearch.java
  15. 1 1
      test/framework/src/main/java/org/elasticsearch/test/XContentTestUtils.java
  16. 2 2
      test/yaml-rest-runner/src/main/java/org/elasticsearch/test/rest/yaml/BlacklistedPathPatternMatcher.java
  17. 1 1
      test/yaml-rest-runner/src/main/java/org/elasticsearch/test/rest/yaml/ClientYamlTestClient.java
  18. 1 2
      x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ilm/LifecyclePolicyUtils.java
  19. 1 1
      x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/CommandLineHttpClient.java
  20. 1 2
      x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/template/TemplateUtils.java
  21. 2 2
      x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/EsqlFunctionRegistry.java
  22. 1 1
      x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/inference/nlp/TextExpansionProcessor.java
  23. 8 9
      x-pack/plugin/monitoring/src/main/java/org/elasticsearch/xpack/monitoring/exporter/ClusterAlertsUtil.java
  24. 1 1
      x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/esnative/tool/SetupPasswordTool.java
  25. 2 2
      x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/enrollment/ExternalEnrollmentTokenGenerator.java
  26. 3 3
      x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/transport/filter/PatternRule.java
  27. 4 4
      x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/esnative/tool/SetupPasswordToolTests.java
  28. 1 1
      x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTimeFormatProcessor.java
  29. 1 1
      x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/common/http/HttpResponse.java
  30. 2 2
      x-pack/qa/security-tools-tests/src/test/java/org/elasticsearch/xpack/security/authc/esnative/tool/ResetPasswordToolTests.java
  31. 1 1
      x-pack/qa/security-tools-tests/src/test/java/org/elasticsearch/xpack/security/enrollment/tool/CreateEnrollmentTokenToolTests.java
  32. 1 1
      x-pack/qa/security-tools-tests/src/test/java/org/elasticsearch/xpack/security/tool/BaseRunAsSuperuserCommandTests.java

+ 1 - 1
build-conventions/src/main/java/org/elasticsearch/gradle/internal/conventions/EclipseConventionPlugin.java

@@ -78,7 +78,7 @@ public class EclipseConventionPlugin implements Plugin<Project> {
                 copy.filter(new Transformer<String, String>() {
                     @Override
                     public String transform(String s) {
-                        return s.replaceAll("@@LICENSE_HEADER_TEXT@@", finalLicenseHeader);
+                        return s.replace("@@LICENSE_HEADER_TEXT@@", finalLicenseHeader);
                     }
                 });
         });

+ 1 - 1
build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/DependenciesInfoTask.java

@@ -172,7 +172,7 @@ public class DependenciesInfoTask extends ConventionTask {
      */
     protected String createURL(final String group, final String name, final String version) {
         final String baseURL = "https://repo1.maven.org/maven2";
-        return baseURL + "/" + group.replaceAll("\\.", "/") + "/" + name + "/" + version;
+        return baseURL + "/" + group.replace('.', '/') + "/" + name + "/" + version;
     }
 
     /**

+ 1 - 2
build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/ElasticsearchJavadocPlugin.java

@@ -107,8 +107,7 @@ public class ElasticsearchJavadocPlugin implements Plugin<Project> {
                 // Link to non-shadowed dependant projects
                 javadoc.dependsOn(upstreamProject.getPath() + ":javadoc");
                 String externalLinkName = upstreamProject.getExtensions().getByType(BasePluginExtension.class).getArchivesName().get();
-                String artifactPath = dep.getGroup().replaceAll("\\.", "/") + '/' + externalLinkName.replaceAll("\\.", "/") + '/' + dep
-                    .getVersion();
+                String artifactPath = dep.getGroup().replace('.', '/') + '/' + externalLinkName.replace('.', '/') + '/' + dep.getVersion();
                 var options = (StandardJavadocDocletOptions) javadoc.getOptions();
                 options.linksOffline(
                     artifactHost(project) + "/javadoc/" + artifactPath,

+ 1 - 1
build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/release/ChangelogEntry.java

@@ -330,7 +330,7 @@ public class ChangelogEntry {
         final List<String> excludes = List.of("the", "is", "a", "and", "now", "that");
 
         final String[] words = input.toLowerCase(Locale.ROOT)
-            .replaceAll("'", "")
+            .replace("'", "")
             .replaceAll("[^\\w]+", "_")
             .replaceFirst("^_+", "")
             .replaceFirst("_+$", "")

+ 7 - 7
build-tools/src/testFixtures/java/org/elasticsearch/gradle/internal/test/TestUtils.java

@@ -16,16 +16,16 @@ public class TestUtils {
 
     public static String normalizeString(String input, File projectRootDir) {
         try {
-            String cannonicalNormalizedPathPrefix = projectRootDir.getCanonicalPath().replace("\\", "/");
-            String normalizedPathPrefix = projectRootDir.getAbsolutePath().replace("\\", "/");
+            String canonicalNormalizedPathPrefix = projectRootDir.getCanonicalPath().replace('\\', '/');
+            String normalizedPathPrefix = projectRootDir.getAbsolutePath().replace('\\', '/');
             return input.lines()
                 .filter(it -> it.startsWith("Picked up JAVA_TOOL_OPTIONS") == false)
-                .map(it -> it.replace("\\", "/"))
+                .map(it -> it.replace('\\', '/'))
                 .map(it -> it.replaceAll("\\d+\\.\\d\\ds", "0.00s"))
-                .map(it -> it.replaceAll(cannonicalNormalizedPathPrefix, "."))
-                .map(it -> it.replaceAll(normalizedPathPrefix, "."))
-                .map(it -> it.replaceAll("file:/./", "file:./"))
-                .map(it -> it.replaceAll("Gradle Test Executor \\d", "Gradle Test Executor 1"))
+                .map(it -> it.replace(canonicalNormalizedPathPrefix, "."))
+                .map(it -> it.replace(normalizedPathPrefix, "."))
+                .map(it -> it.replace("file:/./", "file:./"))
+                .map(it -> it.replaceAll("Gradle Test Executor \\d+", "Gradle Test Executor 1"))
                 .collect(Collectors.joining("\n"));
         } catch (IOException e) {
             throw new RuntimeException(e);

+ 3 - 9
libs/x-content/src/main/java/org/elasticsearch/xcontent/support/filtering/FilterPath.java

@@ -167,19 +167,13 @@ public class FilterPath {
             }
 
             if (splitPosition > 0) {
-                String field = findEscapes
-                    ? filter.substring(0, splitPosition).replaceAll("\\\\.", ".")
-                    : filter.substring(0, splitPosition);
-                BuildNode child = node.children.get(field);
-                if (child == null) {
-                    child = new BuildNode(false);
-                    node.children.put(field, child);
-                }
+                String field = findEscapes ? filter.substring(0, splitPosition).replace("\\.", ".") : filter.substring(0, splitPosition);
+                BuildNode child = node.children.computeIfAbsent(field, f -> new BuildNode(false));
                 if (false == child.isFinalNode) {
                     insertNode(filter.substring(splitPosition + 1), child);
                 }
             } else {
-                String field = findEscapes ? filter.replaceAll("\\\\.", ".") : filter;
+                String field = findEscapes ? filter.replace("\\.", ".") : filter;
                 node.children.put(field, new BuildNode(true));
             }
         }

+ 2 - 4
modules/aggregations/src/main/java/org/elasticsearch/aggregations/metric/InternalMatrixStats.java

@@ -202,10 +202,8 @@ public class InternalMatrixStats extends InternalAggregation {
                 return emptyMap();
             }
             final String field = path.get(0)
-                .replaceAll("^\"", "") // remove leading "
-                .replaceAll("^'", "") // remove leading '
-                .replaceAll("\"$", "") // remove trailing "
-                .replaceAll("'$", ""); // remove trailing '
+                .replaceAll("^[\"']+", "") // remove leading " and '
+                .replaceAll("[\"']+$", ""); // remove trailing " and '
             final String element = path.get(1);
             return switch (element) {
                 case "counts" -> results.getFieldCount(field);

+ 1 - 1
modules/apm/src/main/java/org/elasticsearch/telemetry/apm/internal/tracing/APMTracer.java

@@ -443,7 +443,7 @@ public class APMTracer extends AbstractLifecycleComponent implements org.elastic
 
     private static Automaton patternsToAutomaton(List<String> patterns) {
         final List<Automaton> automata = patterns.stream().map(s -> {
-            final String regex = s.replaceAll("\\.", "\\\\.").replaceAll("\\*", ".*");
+            final String regex = s.replace(".", "\\.").replace("*", ".*");
             return new RegExp(regex).toAutomaton();
         }).toList();
         if (automata.isEmpty()) {

+ 1 - 1
modules/rank-eval/src/main/java/org/elasticsearch/index/rankeval/RatedRequest.java

@@ -130,7 +130,7 @@ public class RatedRequest implements Writeable, ToXContentObject {
         Set<DocumentKey> docKeys = new HashSet<>();
         for (RatedDocument doc : ratedDocs) {
             if (docKeys.add(doc.getKey()) == false) {
-                String docKeyToString = doc.getKey().toString().replaceAll("\n", "").replaceAll("  ", " ");
+                String docKeyToString = doc.getKey().toString().replace("\n", "").replace("  ", " ");
                 throw new IllegalArgumentException(
                     "Found duplicate rated document key [" + docKeyToString + "] in evaluation request [" + id + "]"
                 );

+ 1 - 1
plugins/analysis-phonetic/src/main/java/org/elasticsearch/plugin/analysis/phonetic/KoelnerPhonetik.java

@@ -262,7 +262,7 @@ public class KoelnerPhonetik implements StringEncoder {
     }
 
     private static String expandUmlauts(String str) {
-        return str.replaceAll("\u00C4", "AE").replaceAll("\u00D6", "OE").replaceAll("\u00DC", "UE");
+        return str.replace("\u00C4", "AE").replace("\u00D6", "OE").replace("\u00DC", "UE");
     }
 
     private static String removeSequences(String str) {

+ 2 - 2
server/src/main/java/org/elasticsearch/common/logging/HeaderWarning.java

@@ -263,8 +263,8 @@ public class HeaderWarning {
     }
 
     private static boolean matchesQuotedString(String qdtext) {
-        qdtext = qdtext.replaceAll("\\\\\"", "");
-        qdtext = qdtext.replaceAll("\\\\", "");
+        qdtext = qdtext.replace("\"", "");
+        qdtext = qdtext.replace("\\", "");
         return qdtext.chars().allMatch(c -> qdTextChars.get(c));
     }
 

+ 2 - 2
server/src/main/java/org/elasticsearch/indices/AssociatedIndexDescriptor.java

@@ -91,8 +91,8 @@ public class AssociatedIndexDescriptor implements IndexPatternMatcher {
      */
     static Automaton buildAutomaton(String pattern) {
         String output = pattern;
-        output = output.replaceAll("\\.", "\\\\.");
-        output = output.replaceAll("\\*", ".*");
+        output = output.replace(".", "\\.");
+        output = output.replace("*", ".*");
         return new RegExp(output).toAutomaton();
     }
 

+ 2 - 2
server/src/main/java/org/elasticsearch/indices/SystemIndexDescriptor.java

@@ -901,8 +901,8 @@ public class SystemIndexDescriptor implements IndexPatternMatcher, Comparable<Sy
      */
     private static String patternToRegex(String input) {
         String output = input;
-        output = output.replaceAll("\\.", "\\\\.");
-        output = output.replaceAll("\\*", ".*");
+        output = output.replace(".", "\\.");
+        output = output.replace("*", ".*");
         return output;
     }
 

+ 1 - 1
test/fixtures/old-elasticsearch/src/main/java/oldes/OldElasticsearch.java

@@ -90,7 +90,7 @@ public class OldElasticsearch {
         }
         command.add("-p");
         Path pidPath = baseDir.relativize(baseDir.resolve("pid"));
-        command.add(pidPath.toString().replaceAll("&", "\\&"));
+        command.add(pidPath.toString().replace("&", "\\&"));
         ProcessBuilder subprocess = new ProcessBuilder(command);
         Process process = subprocess.start();
         System.out.println("Running " + command);

+ 1 - 1
test/framework/src/main/java/org/elasticsearch/test/XContentTestUtils.java

@@ -277,7 +277,7 @@ public final class XContentTestUtils {
         // parser.currentName() can be null for root object and unnamed objects in arrays
         if (parser.currentName() != null) {
             // dots in randomized field names need to be escaped, we use that character as the path separator
-            currentPath.addLast(parser.currentName().replaceAll("\\.", "\\\\."));
+            currentPath.addLast(parser.currentName().replace(".", "\\."));
         }
         if (parser.currentToken() == XContentParser.Token.START_OBJECT) {
             validPaths.add(String.join(".", currentPath));

+ 2 - 2
test/yaml-rest-runner/src/main/java/org/elasticsearch/test/rest/yaml/BlacklistedPathPatternMatcher.java

@@ -41,8 +41,8 @@ final class BlacklistedPathPatternMatcher {
         String sanitizedPattern = p.replaceAll("([\\[\\]\\{\\}\\(\\)\\?\\.])", "\\\\$1");
 
         // very simple transformation from wildcard to a proper regex
-        String finalPattern = sanitizedPattern.replaceAll("\\*", "[^/]*") // support wildcard matches (within a single path segment)
-            .replaceAll("\\\\,", ",");  // restore previously escaped ',' in paths.
+        String finalPattern = sanitizedPattern.replace("*", "[^/]*") // support wildcard matches (within a single path segment)
+            .replace("\\,", ",");  // restore previously escaped ',' in paths.
 
         // suffix match
         pattern = Pattern.compile(".*" + finalPattern);

+ 1 - 1
test/yaml-rest-runner/src/main/java/org/elasticsearch/test/rest/yaml/ClientYamlTestClient.java

@@ -151,7 +151,7 @@ public class ClientYamlTestClient implements Closeable {
                 // We prepend "/" to the path part to handle parts that start with - or other invalid characters.
                 URI uri = new URI(null, null, null, -1, "/" + pathPart.getValue(), null, null);
                 // manually escape any slash that each part may contain
-                String encodedPathPart = uri.getRawPath().substring(1).replaceAll("/", "%2F");
+                String encodedPathPart = uri.getRawPath().substring(1).replace("/", "%2F");
                 finalPath = finalPath.replace("{" + pathPart.getKey() + "}", encodedPathPart);
             } catch (URISyntaxException e) {
                 throw new RuntimeException("unable to build uri", e);

+ 1 - 2
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ilm/LifecyclePolicyUtils.java

@@ -25,7 +25,6 @@ import org.elasticsearch.xpack.core.template.resources.TemplateResources;
 
 import java.util.List;
 import java.util.Map;
-import java.util.regex.Pattern;
 import java.util.stream.Collectors;
 
 /**
@@ -73,7 +72,7 @@ public class LifecyclePolicyUtils {
      * Replaces all occurrences of given variable with the value
      */
     public static String replaceVariable(String input, String variable, String value) {
-        return Pattern.compile("${" + variable + "}", Pattern.LITERAL).matcher(input).replaceAll(value);
+        return input.replace("${" + variable + "}", value);
     }
 
     /**

+ 1 - 1
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/CommandLineHttpClient.java

@@ -318,7 +318,7 @@ public class CommandLineHttpClient {
     }
 
     public static URL createURL(URL url, String path, String query) throws MalformedURLException, URISyntaxException {
-        return new URL(url, (url.toURI().getPath() + path).replaceAll("/+", "/") + query);
+        return new URL(url, (url.toURI().getPath() + path).replaceAll("//+", "/") + query);
     }
 
     public static String apiKeyHeaderValue(SecureString apiKey) {

+ 1 - 2
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/template/TemplateUtils.java

@@ -26,7 +26,6 @@ import java.io.IOException;
 import java.util.Collections;
 import java.util.Map;
 import java.util.function.Predicate;
-import java.util.regex.Pattern;
 
 import static org.elasticsearch.common.xcontent.XContentHelper.convertToMap;
 
@@ -110,7 +109,7 @@ public class TemplateUtils {
      * Replaces all occurrences of given variable with the value
      */
     public static String replaceVariable(String input, String variable, String value) {
-        return Pattern.compile("${" + variable + "}", Pattern.LITERAL).matcher(input).replaceAll(value);
+        return input.replace("${" + variable + "}", value);
     }
 
     /**

+ 2 - 2
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/EsqlFunctionRegistry.java

@@ -269,7 +269,7 @@ public final class EsqlFunctionRegistry extends FunctionRegistry {
         }
         Constructor<?> constructor = constructors[0];
         FunctionInfo functionInfo = constructor.getAnnotation(FunctionInfo.class);
-        String functionDescription = functionInfo == null ? "" : functionInfo.description().replaceAll("\n", " ");
+        String functionDescription = functionInfo == null ? "" : functionInfo.description().replace('\n', ' ');
         String[] returnType = functionInfo == null ? new String[] { "?" } : functionInfo.returnType();
         var params = constructor.getParameters(); // no multiple c'tors supported
 
@@ -282,7 +282,7 @@ public final class EsqlFunctionRegistry extends FunctionRegistry {
                 String name = paramInfo == null ? params[i].getName() : paramInfo.name();
                 variadic |= List.class.isAssignableFrom(params[i].getType());
                 String[] type = paramInfo == null ? new String[] { "?" } : paramInfo.type();
-                String desc = paramInfo == null ? "" : paramInfo.description().replaceAll("\n", " ");
+                String desc = paramInfo == null ? "" : paramInfo.description().replace('\n', ' ');
                 boolean optional = paramInfo == null ? false : paramInfo.optional();
 
                 args.add(new EsqlFunctionRegistry.ArgSignature(name, type, desc, optional));

+ 1 - 1
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/inference/nlp/TextExpansionProcessor.java

@@ -38,7 +38,7 @@ public class TextExpansionProcessor extends NlpTask.Processor {
         Map<Integer, String> sanitized = new HashMap<>();
         for (int i = 0; i < inputVocab.size(); i++) {
             if (inputVocab.get(i).contains(".")) {
-                sanitized.put(i, inputVocab.get(i).replaceAll("\\.", "__"));
+                sanitized.put(i, inputVocab.get(i).replace(".", "__"));
             }
         }
         return sanitized;

+ 8 - 9
x-pack/plugin/monitoring/src/main/java/org/elasticsearch/xpack/monitoring/exporter/ClusterAlertsUtil.java

@@ -16,7 +16,6 @@ import java.util.Arrays;
 import java.util.List;
 import java.util.Locale;
 import java.util.Set;
-import java.util.regex.Pattern;
 import java.util.stream.Collectors;
 
 import static org.elasticsearch.xpack.monitoring.exporter.Exporter.CLUSTER_ALERTS_BLACKLIST_SETTING;
@@ -34,24 +33,24 @@ public class ClusterAlertsUtil {
     /**
      * Replace the <code>${monitoring.watch.cluster_uuid}</code> field in the watches.
      */
-    private static final Pattern CLUSTER_UUID_PROPERTY = Pattern.compile(Pattern.quote("${monitoring.watch.cluster_uuid}"));
+    private static final String CLUSTER_UUID_PROPERTY = "${monitoring.watch.cluster_uuid}";
     /**
      * Replace the <code>${monitoring.watch.id}</code> field in the watches.
      */
-    private static final Pattern WATCH_ID_PROPERTY = Pattern.compile(Pattern.quote("${monitoring.watch.id}"));
+    private static final String WATCH_ID_PROPERTY = "${monitoring.watch.id}";
     /**
      * Replace the <code>${monitoring.watch.unique_id}</code> field in the watches.
      *
      * @see #createUniqueWatchId(ClusterService, String)
      */
-    private static final Pattern UNIQUE_WATCH_ID_PROPERTY = Pattern.compile(Pattern.quote("${monitoring.watch.unique_id}"));
+    private static final String UNIQUE_WATCH_ID_PROPERTY = "${monitoring.watch.unique_id}";
 
     /**
      * Replace the <code>${monitoring.watch.unique_id}</code> field in the watches.
      *
      * @see #createUniqueWatchId(ClusterService, String)
      */
-    private static final Pattern VERSION_CREATED_PROPERTY = Pattern.compile(Pattern.quote("${monitoring.version_created}"));
+    private static final String VERSION_CREATED_PROPERTY = "${monitoring.version_created}";
 
     /**
      * The last time that all watches were updated. For now, all watches have been updated in the same version and should all be replaced
@@ -113,10 +112,10 @@ public class ClusterAlertsUtil {
             // load the resource as-is
             String source = loadResource(resource).utf8ToString();
 
-            source = CLUSTER_UUID_PROPERTY.matcher(source).replaceAll(clusterUuid);
-            source = WATCH_ID_PROPERTY.matcher(source).replaceAll(watchId);
-            source = UNIQUE_WATCH_ID_PROPERTY.matcher(source).replaceAll(uniqueWatchId);
-            source = VERSION_CREATED_PROPERTY.matcher(source).replaceAll(Integer.toString(LAST_UPDATED_VERSION));
+            source = source.replace(CLUSTER_UUID_PROPERTY, clusterUuid);
+            source = source.replace(WATCH_ID_PROPERTY, watchId);
+            source = source.replace(UNIQUE_WATCH_ID_PROPERTY, uniqueWatchId);
+            source = source.replace(VERSION_CREATED_PROPERTY, Integer.toString(LAST_UPDATED_VERSION));
 
             return source;
         } catch (final IOException e) {

+ 1 - 1
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/esnative/tool/SetupPasswordTool.java

@@ -634,7 +634,7 @@ class SetupPasswordTool extends MultiCommand {
         }
 
         private static URL createURL(URL url, String path, String query) throws MalformedURLException, URISyntaxException {
-            return new URL(url, (url.toURI().getPath() + path).replaceAll("/+", "/") + query);
+            return new URL(url, (url.toURI().getPath() + path).replaceAll("//+", "/") + query);
         }
     }
 

+ 2 - 2
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/enrollment/ExternalEnrollmentTokenGenerator.java

@@ -88,11 +88,11 @@ public class ExternalEnrollmentTokenGenerator extends BaseEnrollmentTokenGenerat
     }
 
     protected static URL createAPIKeyUrl(URL baseUrl) throws MalformedURLException, URISyntaxException {
-        return new URL(baseUrl, (baseUrl.toURI().getPath() + "/_security/api_key").replaceAll("/+", "/"));
+        return new URL(baseUrl, (baseUrl.toURI().getPath() + "/_security/api_key").replaceAll("//+", "/"));
     }
 
     protected static URL getHttpInfoUrl(URL baseUrl) throws MalformedURLException, URISyntaxException {
-        return new URL(baseUrl, (baseUrl.toURI().getPath() + "/_nodes/_local/http").replaceAll("/+", "/"));
+        return new URL(baseUrl, (baseUrl.toURI().getPath() + "/_nodes/_local/http").replaceAll("//+", "/"));
     }
 
     @SuppressWarnings("unchecked")

+ 3 - 3
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/transport/filter/PatternRule.java

@@ -105,9 +105,9 @@ final class PatternRule implements IpFilterRule {
         if (pattern.length() != 0) {
             pattern += "|";
         }
-        rule = rule.replaceAll("\\.", "\\\\.");
-        rule = rule.replaceAll("\\*", ".*");
-        rule = rule.replaceAll("\\?", ".");
+        rule = rule.replace(".", "\\.");
+        rule = rule.replace("*", ".*");
+        rule = rule.replace("?", ".");
         pattern += '(' + rule + ')';
         return pattern;
     }

+ 4 - 4
x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/esnative/tool/SetupPasswordToolTests.java

@@ -644,19 +644,19 @@ public class SetupPasswordToolTests extends CommandTestCase {
     }
 
     private URL authenticateUrl(URL url) throws MalformedURLException, URISyntaxException {
-        return new URL(url, (url.toURI().getPath() + "/_security/_authenticate").replaceAll("/+", "/") + "?pretty");
+        return new URL(url, (url.toURI().getPath() + "/_security/_authenticate").replaceAll("//+", "/") + "?pretty");
     }
 
     private URL passwordUrl(URL url, String user) throws MalformedURLException, URISyntaxException {
-        return new URL(url, (url.toURI().getPath() + "/_security/user/" + user + "/_password").replaceAll("/+", "/") + "?pretty");
+        return new URL(url, (url.toURI().getPath() + "/_security/user/" + user + "/_password").replaceAll("//+", "/") + "?pretty");
     }
 
     private URL clusterHealthUrl(URL url) throws MalformedURLException, URISyntaxException {
-        return new URL(url, (url.toURI().getPath() + "/_cluster/health").replaceAll("/+", "/") + "?pretty");
+        return new URL(url, (url.toURI().getPath() + "/_cluster/health").replaceAll("//+", "/") + "?pretty");
     }
 
     private URL queryXPackSecurityFeatureConfigURL(URL url) throws MalformedURLException, URISyntaxException {
-        return new URL(url, (url.toURI().getPath() + "/_xpack").replaceAll("/+", "/") + "?categories=features&human=false&pretty");
+        return new URL(url, (url.toURI().getPath() + "/_xpack").replaceAll("//+", "/") + "?categories=features&human=false&pretty");
     }
 
     private HttpResponse createHttpResponse(final int httpStatus, final String responseJson) throws IOException {

+ 1 - 1
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTimeFormatProcessor.java

@@ -192,7 +192,7 @@ public class DateTimeFormatProcessor extends BinaryDateTimeProcessor {
 
         private static void quoteAndAppend(StringBuilder mainBuffer, StringBuilder fragmentToQuote) {
             mainBuffer.append("'");
-            mainBuffer.append(fragmentToQuote.toString().replaceAll("'", "''"));
+            mainBuffer.append(fragmentToQuote.toString().replace("'", "''"));
             mainBuffer.append("'");
         }
 

+ 1 - 1
x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/common/http/HttpResponse.java

@@ -166,7 +166,7 @@ public class HttpResponse implements ToXContentObject {
             for (Map.Entry<String, String[]> header : headers.entrySet()) {
                 // in order to prevent dots in field names, that might occur in headers, we simply de_dot those header names
                 // when writing toXContent
-                builder.array(header.getKey().replaceAll("\\.", "_"), header.getValue());
+                builder.array(header.getKey().replace('.', '_'), header.getValue());
             }
             builder.endObject();
         }

+ 2 - 2
x-pack/qa/security-tools-tests/src/test/java/org/elasticsearch/xpack/security/authc/esnative/tool/ResetPasswordToolTests.java

@@ -304,10 +304,10 @@ public class ResetPasswordToolTests extends CommandTestCase {
     }
 
     private URL changePasswordUrl(URL url, String user) throws MalformedURLException, URISyntaxException {
-        return new URL(url, (url.toURI().getPath() + "/_security/user/" + user + "/_password").replaceAll("/+", "/") + "?pretty");
+        return new URL(url, (url.toURI().getPath() + "/_security/user/" + user + "/_password").replaceAll("//+", "/") + "?pretty");
     }
 
     private URL clusterHealthUrl(URL url) throws MalformedURLException, URISyntaxException {
-        return new URL(url, (url.toURI().getPath() + "/_cluster/health").replaceAll("/+", "/") + "?pretty");
+        return new URL(url, (url.toURI().getPath() + "/_cluster/health").replaceAll("//+", "/") + "?pretty");
     }
 }

+ 1 - 1
x-pack/qa/security-tools-tests/src/test/java/org/elasticsearch/xpack/security/enrollment/tool/CreateEnrollmentTokenToolTests.java

@@ -257,6 +257,6 @@ public class CreateEnrollmentTokenToolTests extends CommandTestCase {
     }
 
     private URL clusterHealthUrl(URL url) throws MalformedURLException, URISyntaxException {
-        return new URL(url, (url.toURI().getPath() + "/_cluster/health").replaceAll("/+", "/") + "?pretty");
+        return new URL(url, (url.toURI().getPath() + "/_cluster/health").replaceAll("//+", "/") + "?pretty");
     }
 }

+ 1 - 1
x-pack/qa/security-tools-tests/src/test/java/org/elasticsearch/xpack/security/tool/BaseRunAsSuperuserCommandTests.java

@@ -282,7 +282,7 @@ public class BaseRunAsSuperuserCommandTests extends CommandTestCase {
     }
 
     private URL clusterHealthUrl(URL url) throws MalformedURLException, URISyntaxException {
-        return new URL(url, (url.toURI().getPath() + "/_cluster/health").replaceAll("/+", "/") + "?pretty");
+        return new URL(url, (url.toURI().getPath() + "/_cluster/health").replaceAll("//+", "/") + "?pretty");
     }
 
     /**