Skip to content

Commit

Permalink
Make some practically static methods static (#97565)
Browse files Browse the repository at this point in the history
Another round of automated fixes to this, marking things that can be
made static as static. Saves some JIT cycles but also turns some lambdas
from capturing to non-capturing and makes the "utilityness" of some
classes visible.
  • Loading branch information
original-brownbear authored Oct 6, 2023
1 parent c485264 commit b7eafce
Show file tree
Hide file tree
Showing 418 changed files with 1,031 additions and 1,015 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -64,11 +64,11 @@ protected void execute(Terminal terminal, OptionSet options, ProcessInfo process
}

@SuppressForbidden(reason = "file arg for cli")
private Path getPath(String file) {
private static Path getPath(String file) {
return PathUtils.get(file);
}

private void copyTgzToTarget(Path source, Path target) throws IOException {
private static void copyTgzToTarget(Path source, Path target) throws IOException {
if (source.equals(target)) {
return;
}
Expand All @@ -79,7 +79,7 @@ private void copyTgzToTarget(Path source, Path target) throws IOException {
}
}

private void packDatabasesToTgz(Terminal terminal, Path source, Path target) throws IOException {
private static void packDatabasesToTgz(Terminal terminal, Path source, Path target) throws IOException {
try (Stream<Path> files = Files.list(source)) {
for (Path path : files.filter(p -> p.getFileName().toString().endsWith(".mmdb")).toList()) {
String fileName = path.getFileName().toString();
Expand All @@ -102,7 +102,7 @@ private void packDatabasesToTgz(Terminal terminal, Path source, Path target) thr
}
}

private void createOverviewJson(Terminal terminal, Path directory) throws IOException {
private static void createOverviewJson(Terminal terminal, Path directory) throws IOException {
Path overview = directory.resolve("overview.json");
try (
Stream<Path> files = Files.list(directory);
Expand Down Expand Up @@ -130,7 +130,7 @@ private void createOverviewJson(Terminal terminal, Path directory) throws IOExce
terminal.println("overview.json created");
}

private byte[] createTarHeader(String name, long size) {
private static byte[] createTarHeader(String name, long size) {
byte[] buf = new byte[512];
byte[] sizeBytes = String.format(Locale.ROOT, "%1$012o", size).getBytes(StandardCharsets.UTF_8);
byte[] nameBytes = name.substring(Math.max(0, name.length() - 100)).getBytes(StandardCharsets.US_ASCII);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ protected void executeCommand(Terminal terminal, OptionSet options, Environment
}

@SuppressForbidden(reason = "file arg for cli")
private Path getPath(String file) {
private static Path getPath(String file) {
return PathUtils.get(file);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,6 @@ public class InstallPluginAction implements Closeable {
private Environment env;
private boolean batch;
private Proxy proxy = null;
private NamedComponentScanner scanner = new NamedComponentScanner();

public InstallPluginAction(Terminal terminal, Environment env, boolean batch) {
this.terminal = terminal;
Expand Down Expand Up @@ -394,7 +393,7 @@ private String getElasticUrl(
return String.format(Locale.ROOT, "%s/%s-%s.zip", baseUrl, pluginId, Build.current().qualifiedVersion());
}

private String nonReleaseUrl(final String hostname, final Version version, final String stagingHash, final String pluginId) {
private static String nonReleaseUrl(final String hostname, final Version version, final String stagingHash, final String pluginId) {
return String.format(
Locale.ROOT,
"https://%s.elastic.co/%s-%s/downloads/elasticsearch-plugins/%s",
Expand Down Expand Up @@ -441,7 +440,7 @@ boolean urlExists(String urlString) throws IOException {
/**
* Returns all the official plugin names that look similar to pluginId.
**/
private List<String> checkMisspelledPlugin(String pluginId) {
private static List<String> checkMisspelledPlugin(String pluginId) {
LevenshteinDistance ld = new LevenshteinDistance();
List<Tuple<Float, String>> scoredKeys = new ArrayList<>();
for (String officialPlugin : OFFICIAL_PLUGINS) {
Expand Down Expand Up @@ -819,20 +818,20 @@ private Path unzip(Path zip, Path pluginsDir) throws IOException, UserException
return target;
}

private Path stagingDirectory(Path pluginsDir) throws IOException {
private static Path stagingDirectory(Path pluginsDir) throws IOException {
try {
return Files.createTempDirectory(pluginsDir, ".installing-", PosixFilePermissions.asFileAttribute(PLUGIN_DIR_PERMS));
} catch (UnsupportedOperationException e) {
return stagingDirectoryWithoutPosixPermissions(pluginsDir);
}
}

private Path stagingDirectoryWithoutPosixPermissions(Path pluginsDir) throws IOException {
private static Path stagingDirectoryWithoutPosixPermissions(Path pluginsDir) throws IOException {
return Files.createTempDirectory(pluginsDir, ".installing-");
}

// checking for existing version of the plugin
private void verifyPluginName(Path pluginPath, String pluginName) throws UserException, IOException {
private static void verifyPluginName(Path pluginPath, String pluginName) throws UserException, IOException {
// don't let user install plugin conflicting with module...
// they might be unavoidably in maven central and are packaged up the same way)
if (MODULES.contains(pluginName)) {
Expand Down Expand Up @@ -877,15 +876,15 @@ private PluginDescriptor loadPluginInfo(Path pluginRoot) throws Exception {
return info;
}

private void generateNameComponentFile(Path pluginRoot) throws IOException {
private static void generateNameComponentFile(Path pluginRoot) throws IOException {
Stream<ClassReader> classPath = ClassReaders.ofClassPath().stream(); // contains plugin-api
List<ClassReader> classReaders = Stream.concat(ClassReaders.ofDirWithJars(pluginRoot).stream(), classPath).toList();
Map<String, Map<String, String>> namedComponentsMap = scanner.scanForNamedClasses(classReaders);
Map<String, Map<String, String>> namedComponentsMap = NamedComponentScanner.scanForNamedClasses(classReaders);
Path outputFile = pluginRoot.resolve(PluginDescriptor.NAMED_COMPONENTS_FILENAME);
scanner.writeToFile(namedComponentsMap, outputFile);
NamedComponentScanner.writeToFile(namedComponentsMap, outputFile);
}

private boolean hasNamedComponentFile(Path pluginRoot) {
private static boolean hasNamedComponentFile(Path pluginRoot) {
return Files.exists(pluginRoot.resolve(PluginDescriptor.NAMED_COMPONENTS_FILENAME));
}

Expand Down Expand Up @@ -949,7 +948,7 @@ private PluginDescriptor installPlugin(InstallablePlugin descriptor, Path tmpRoo
/**
* Moves bin and config directories from the plugin if they exist
*/
private void installPluginSupportFiles(
private static void installPluginSupportFiles(
PluginDescriptor info,
Path tmpRoot,
Path destBinDir,
Expand All @@ -973,7 +972,7 @@ private void installPluginSupportFiles(
/**
* Moves the plugin directory into its final destination.
*/
private void movePlugin(Path tmpRoot, Path destination) throws IOException {
private static void movePlugin(Path tmpRoot, Path destination) throws IOException {
Files.move(tmpRoot, destination, StandardCopyOption.ATOMIC_MOVE);
Files.walkFileTree(destination, new SimpleFileVisitor<>() {
@Override
Expand All @@ -1000,7 +999,7 @@ public FileVisitResult postVisitDirectory(final Path dir, final IOException exc)
/**
* Copies the files from {@code tmpBinDir} into {@code destBinDir}, along with permissions from dest dirs parent.
*/
private void installBin(PluginDescriptor info, Path tmpBinDir, Path destBinDir) throws Exception {
private static void installBin(PluginDescriptor info, Path tmpBinDir, Path destBinDir) throws Exception {
if (Files.isDirectory(tmpBinDir) == false) {
throw new UserException(PLUGIN_MALFORMED, "bin in plugin " + info.getName() + " is not a directory");
}
Expand Down Expand Up @@ -1028,7 +1027,7 @@ private void installBin(PluginDescriptor info, Path tmpBinDir, Path destBinDir)
* Copies the files from {@code tmpConfigDir} into {@code destConfigDir}.
* Any files existing in both the source and destination will be skipped.
*/
private void installConfig(PluginDescriptor info, Path tmpConfigDir, Path destConfigDir) throws Exception {
private static void installConfig(PluginDescriptor info, Path tmpConfigDir, Path destConfigDir) throws Exception {
if (Files.isDirectory(tmpConfigDir) == false) {
throw new UserException(PLUGIN_MALFORMED, "config in plugin " + info.getName() + " is not a directory");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public void execute(Terminal terminal, OptionSet options, Environment env, Proce
}
}

private void printPlugin(Environment env, Terminal terminal, Path plugin, String prefix) throws IOException {
private static void printPlugin(Environment env, Terminal terminal, Path plugin, String prefix) throws IOException {
terminal.println(Terminal.Verbosity.SILENT, prefix + plugin.getFileName().toString());
PluginDescriptor info = PluginDescriptor.readFromProperties(env.pluginsFile().resolve(plugin));
terminal.println(Terminal.Verbosity.VERBOSE, info.toString(prefix));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ public void execute(Terminal terminal, OptionSet options, Environment env, Proce
}
}

private void printVersion(Terminal terminal) {
private static void printVersion(Terminal terminal) {
final String versionOutput = String.format(
Locale.ROOT,
"Version: %s, Build: %s/%s/%s, JVM: %s",
Expand Down Expand Up @@ -197,7 +197,7 @@ void syncPlugins(Terminal terminal, Environment env, ProcessInfo processInfo) th
syncPlugins.execute(terminal, syncPlugins.parseOptions(new String[0]), env, processInfo);
}

private void validatePidFile(Path pidFile) throws UserException {
private static void validatePidFile(Path pidFile) throws UserException {
Path parent = pidFile.getParent();
if (parent != null && Files.exists(parent) && Files.isDirectory(parent) == false) {
throw new UserException(ExitCodes.USAGE, "pid file parent [" + parent + "] exists but is not a directory");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ static String quote(String s) {
}

/** Determines the service id for the Elasticsearch service that should be used */
private String getServiceId(OptionSet options, Map<String, String> env) throws UserException {
private static String getServiceId(OptionSet options, Map<String, String> env) throws UserException {
List<?> args = options.nonOptionArguments();
if (args.size() > 1) {
throw new UserException(ExitCodes.USAGE, "too many arguments, expected one service id");
Expand All @@ -107,7 +107,7 @@ private String getServiceId(OptionSet options, Map<String, String> env) throws U
}

/** Determines the logging arguments that should be passed to the procrun command */
private String getLogArgs(String serviceId, Path esHome, Map<String, String> env) {
private static String getLogArgs(String serviceId, Path esHome, Map<String, String> env) {
String logArgs = env.get("LOG_OPTS");
if (logArgs != null && logArgs.isBlank() == false) {
return logArgs;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ protected URL findResource(String name) {
* url or null if not found. Iterates over all known package specific multi-release versions,
* then the root, for the given jar prefix.
*/
<T> T findResourceInLoaderPkgOrNull(JarMeta jarMeta, String pkg, String name, Function<String, T> finder) {
static <T> T findResourceInLoaderPkgOrNull(JarMeta jarMeta, String pkg, String name, Function<String, T> finder) {
List<Integer> releaseVersions = jarMeta.pkgToVersions().getOrDefault(pkg, List.of());
for (int releaseVersion : releaseVersions) {
String fullName = jarMeta.prefix() + "/" + MRJAR_VERSION_PREFIX + releaseVersion + "/" + name;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ protected ModuleQualifiedExportsService(Module module) {
.collect(Collectors.toUnmodifiableSet());
}

private <T> Map<String, List<String>> invert(
private static <T> Map<String, List<String>> invert(
Collection<T> sourcesToTargets,
Predicate<T> qualifiedPredicate,
Function<T, String> sourceGetter,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public ShapeType type() {
return ShapeType.POLYGON;
}

private void checkRing(LinearRing ring) {
private static void checkRing(LinearRing ring) {
if (ring.length() < 4) {
throw new IllegalArgumentException("at least 4 polygon points required");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ public double calculateError(PointLike left, PointLike middle, PointLike right)
}
}

private double distance(PointLike a, PointLike b) {
private static double distance(PointLike a, PointLike b) {
return SloppyMath.haversinMeters(a.y(), a.x(), b.y(), b.x());
}
}
Expand Down Expand Up @@ -115,7 +115,7 @@ public double calculateError(PointLike left, PointLike middle, PointLike right)
}
}

private double distance(PointLike a, PointLike b) {
private static double distance(PointLike a, PointLike b) {
return SloppyMath.haversinMeters(a.y(), a.x(), b.y(), b.x());
}
}
Expand Down
2 changes: 1 addition & 1 deletion libs/grok/src/main/java/org/elasticsearch/grok/Grok.java
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ private Grok(
this.captureConfig = List.copyOf(grokCaptureConfigs);
}

private String groupMatch(String name, Region region, String pattern) {
private static String groupMatch(String name, Region region, String pattern) {
int number = GROK_PATTERN_REGEX.nameToBackrefNumber(
name.getBytes(StandardCharsets.UTF_8),
0,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ static GrokCaptureType fromString(String str) {
};
}

protected final GrokCaptureExtracter rawExtracter(int[] backRefs, Consumer<? super String> emit) {
protected static GrokCaptureExtracter rawExtracter(int[] backRefs, Consumer<? super String> emit) {
return (utf8Bytes, offset, region) -> {
for (int number : backRefs) {
if (region.beg[number] >= 0) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,13 @@ public class NamedComponentScanner {
public static void main(String[] args) throws IOException {
List<ClassReader> classReaders = ClassReaders.ofClassPath();

NamedComponentScanner scanner = new NamedComponentScanner();
Map<String, Map<String, String>> namedComponentsMap = scanner.scanForNamedClasses(classReaders);
Map<String, Map<String, String>> namedComponentsMap = scanForNamedClasses(classReaders);
Path outputFile = Path.of(args[0]);
scanner.writeToFile(namedComponentsMap, outputFile);
NamedComponentScanner.writeToFile(namedComponentsMap, outputFile);
}

// scope for testing
public void writeToFile(Map<String, Map<String, String>> namedComponentsMap, Path outputFile) throws IOException {
public static void writeToFile(Map<String, Map<String, String>> namedComponentsMap, Path outputFile) throws IOException {
Files.createDirectories(outputFile.getParent());

try (OutputStream outputStream = Files.newOutputStream(outputFile)) {
Expand All @@ -58,7 +57,7 @@ public void writeToFile(Map<String, Map<String, String>> namedComponentsMap, Pat
}

// returns a Map<String, Map<String,String> - extensible interface -> map{ namedName -> className }
public Map<String, Map<String, String>> scanForNamedClasses(List<ClassReader> classReaders) {
public static Map<String, Map<String, String>> scanForNamedClasses(List<ClassReader> classReaders) {
ClassScanner extensibleClassScanner = new ClassScanner(Type.getDescriptor(Extensible.class), (classname, map) -> {
map.put(classname, classname);
return null;
Expand Down Expand Up @@ -95,7 +94,7 @@ public void visit(String key, Object value) {
return componentInfo;
}

private String pathToClassName(String classWithSlashes) {
private static String pathToClassName(String classWithSlashes) {
return classWithSlashes.replace('/', '.');
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,8 @@ private Path tmpDir() throws IOException {
return createTempDir();
}

NamedComponentScanner namedComponentScanner = new NamedComponentScanner();

public void testFindNamedComponentInSingleClass() throws URISyntaxException {
Map<String, Map<String, String>> namedComponents = namedComponentScanner.scanForNamedClasses(
Map<String, Map<String, String>> namedComponents = NamedComponentScanner.scanForNamedClasses(
classReaderStream(TestNamedComponent.class, ExtensibleInterface.class)
);

Expand Down Expand Up @@ -82,7 +80,7 @@ public class B implements ExtensibleInterface{}
)// contains plugin-api
.toList();

Map<String, Map<String, String>> namedComponents = namedComponentScanner.scanForNamedClasses(classReaderStream);
Map<String, Map<String, String>> namedComponents = NamedComponentScanner.scanForNamedClasses(classReaderStream);

org.hamcrest.MatcherAssert.assertThat(
namedComponents,
Expand Down Expand Up @@ -158,7 +156,7 @@ public class B implements CustomExtensibleInterface{}
List<ClassReader> classReaders = Stream.concat(ClassReaders.ofDirWithJars(dirWithJar).stream(), classPath)// contains plugin-api
.toList();

Map<String, Map<String, String>> namedComponents = namedComponentScanner.scanForNamedClasses(classReaders);
Map<String, Map<String, String>> namedComponents = NamedComponentScanner.scanForNamedClasses(classReaders);

org.hamcrest.MatcherAssert.assertThat(
namedComponents,
Expand Down Expand Up @@ -189,7 +187,7 @@ public void testWriteToFile() throws IOException {
mapToWrite.put(ExtensibleInterface.class.getCanonicalName(), extensibleInterfaceComponents);

Path path = tmpDir().resolve("file.json");
namedComponentScanner.writeToFile(mapToWrite, path);
NamedComponentScanner.writeToFile(mapToWrite, path);

String jsonMap = Files.readString(path);
assertThat(jsonMap, equalTo("""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ public final void add(double x) {
add(x, 1);
}

final void checkValue(double x) {
static void checkValue(double x) {
if (Double.isNaN(x) || Double.isInfinite(x)) {
throw new IllegalArgumentException("Invalid value: " + x);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ FilterPath build() {
return buildPath("", root);
}

void insertNode(String filter, BuildNode node) {
static void insertNode(String filter, BuildNode node) {
int end = filter.length();
int splitPosition = -1;
boolean findEscapes = false;
Expand Down Expand Up @@ -184,7 +184,7 @@ void insertNode(String filter, BuildNode node) {
}
}

FilterPath buildPath(String segment, BuildNode node) {
static FilterPath buildPath(String segment, BuildNode node) {
Map<String, FilterPath> termsChildren = new HashMap<>();
List<FilterPath> wildcardChildren = new ArrayList<>();
for (Map.Entry<String, BuildNode> entry : node.children.entrySet()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ public final ArrayValuesSourceAggregationBuilder<?> parse(String aggregationName
return factory;
}

private void parseMissingAndAdd(
private static void parseMissingAndAdd(
final String aggregationName,
final String currentFieldName,
XContentParser parser,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ static <M extends Map<String, Double>> double getValFromUpperTriangularMatrix(Ma
throw new IllegalArgumentException("Coefficient not computed between fields: " + fieldX + " and " + fieldY);
}

private void checkField(String field, Map<String, ?> map) {
private static void checkField(String field, Map<String, ?> map) {
if (field == null) {
throw new IllegalArgumentException("field name cannot be null");
}
Expand Down
Loading

0 comments on commit b7eafce

Please sign in to comment.