Skip to content

Commit

Permalink
[8.0] Use Java 14 switch expressions (#82178) (#82355)
Browse files Browse the repository at this point in the history
JEP 361[https://openjdk.java.net/jeps/361] added support for switch expressions
which can be much more terse and less error-prone than switch statements.

Another useful feature of switch expressions is exhaustiveness: we can make
sure that an enum switch expression covers all the cases at compile time.

(cherry picked from commit 0699c93)

* Rollback switch expressions for the SQL plugin (#82349)

It was updated to Java 8 compatibility in #82274

(cherry picked from commit 78509f4)
  • Loading branch information
arteam authored Jan 10, 2022
1 parent ed1448b commit 358484b
Show file tree
Hide file tree
Showing 713 changed files with 7,734 additions and 13,164 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -89,16 +89,11 @@ public void buildDates() {
roundingBuilder = Rounding.builder(TimeValue.parseTimeValue(interval, "interval"));
}
Rounding rounding = roundingBuilder.timeZone(ZoneId.of(zone)).build();
switch (rounder) {
case "java time":
rounderBuilder = rounding::prepareJavaTime;
break;
case "es":
rounderBuilder = () -> rounding.prepare(min, max);
break;
default:
throw new IllegalArgumentException("Expectd rounder to be [java time] or [es]");
}
rounderBuilder = switch (rounder) {
case "java time" -> rounding::prepareJavaTime;
case "es" -> () -> rounding.prepare(min, max);
default -> throw new IllegalArgumentException("Expected rounder to be [java time] or [es]");
};
}

@Benchmark
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,28 +101,19 @@ public class ScriptScoreBenchmark {

@Setup
public void setupScript() {
switch (script) {
case "expression":
factory = scriptModule.engines.get("expression").compile("test", "doc['n'].value", ScoreScript.CONTEXT, Map.of());
break;
case "metal":
factory = bareMetalScript();
break;
case "painless_cast":
factory = scriptModule.engines.get("painless")
.compile(
"test",
"((org.elasticsearch.index.fielddata.ScriptDocValues.Longs)doc['n']).value",
ScoreScript.CONTEXT,
Map.of()
);
break;
case "painless_def":
factory = scriptModule.engines.get("painless").compile("test", "doc['n'].value", ScoreScript.CONTEXT, Map.of());
break;
default:
throw new IllegalArgumentException("Don't know how to implement script [" + script + "]");
}
factory = switch (script) {
case "expression" -> scriptModule.engines.get("expression").compile("test", "doc['n'].value", ScoreScript.CONTEXT, Map.of());
case "metal" -> bareMetalScript();
case "painless_cast" -> scriptModule.engines.get("painless")
.compile(
"test",
"((org.elasticsearch.index.fielddata.ScriptDocValues.Longs)doc['n']).value",
ScoreScript.CONTEXT,
Map.of()
);
case "painless_def" -> scriptModule.engines.get("painless").compile("test", "doc['n'].value", ScoreScript.CONTEXT, Map.of());
default -> throw new IllegalArgumentException("Don't know how to implement script [" + script + "]");
};
}

@Setup
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,20 +107,12 @@ public class AggConstructionContentionBenchmark {

@Setup
public void setup() {
switch (breaker) {
case "real":
breakerService = new HierarchyCircuitBreakerService(Settings.EMPTY, List.of(), clusterSettings);
break;
case "preallocate":
preallocateBreaker = true;
breakerService = new HierarchyCircuitBreakerService(Settings.EMPTY, List.of(), clusterSettings);
break;
case "noop":
breakerService = new NoneCircuitBreakerService();
break;
default:
throw new UnsupportedOperationException();
}
breakerService = switch (breaker) {
case "real", "preallocate" -> new HierarchyCircuitBreakerService(Settings.EMPTY, List.of(), clusterSettings);
case "noop" -> new NoneCircuitBreakerService();
default -> throw new UnsupportedOperationException();
};
preallocateBreaker = breaker.equals("preallocate");
bigArrays = new BigArrays(recycler, breakerService, "request");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,22 +53,13 @@ public class FetchSourcePhaseBenchmark {

@Setup
public void setup() throws IOException {
switch (source) {
case "tiny":
sourceBytes = new BytesArray("{\"message\": \"short\"}");
break;
case "short":
sourceBytes = read300BytesExample();
break;
case "one_4k_field":
sourceBytes = buildBigExample("huge".repeat(1024));
break;
case "one_4m_field":
sourceBytes = buildBigExample("huge".repeat(1024 * 1024));
break;
default:
throw new IllegalArgumentException("Unknown source [" + source + "]");
}
sourceBytes = switch (source) {
case "tiny" -> new BytesArray("{\"message\": \"short\"}");
case "short" -> read300BytesExample();
case "one_4k_field" -> buildBigExample("huge".repeat(1024));
case "one_4m_field" -> buildBigExample("huge".repeat(1024 * 1024));
default -> throw new IllegalArgumentException("Unknown source [" + source + "]");
};
fetchContext = new FetchSourceContext(
true,
Strings.splitStringByCommaToArray(includes),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,18 +44,11 @@ public class SymbolicLinkPreservingTar extends Tar {

@Override
protected CopyAction createCopyAction() {
final ArchiveOutputStreamFactory compressor;
switch (getCompression()) {
case BZIP2:
compressor = Bzip2Archiver.getCompressor();
break;
case GZIP:
compressor = GzipArchiver.getCompressor();
break;
default:
compressor = new SimpleCompressor();
break;
}
final ArchiveOutputStreamFactory compressor = switch (getCompression()) {
case BZIP2 -> Bzip2Archiver.getCompressor();
case GZIP -> GzipArchiver.getCompressor();
default -> new SimpleCompressor();
};
return new SymbolicLinkPreservingTarCopyAction(getArchiveFile(), compressor, isPreserveFileTimestamps());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,23 +87,17 @@ static List<String> transformConfig(List<String> lines) {
}

switch (keyParts[2]) {
case "type":
case "type" -> {
if (value.equals("RollingFile")) {
value = "Console";
}
line = key + " = " + value;
break;

case "fileName":
case "filePattern":
case "policies":
case "strategy":
}
case "fileName", "filePattern", "policies", "strategy" -> {
// No longer applicable. Omit it.
skipNext = line.endsWith("\\");
continue;

default:
break;
}
}
} else if (line.startsWith("rootLogger.appenderRef")) {
String[] parts = line.split("\\s*=\\s*");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,11 @@ public enum Architecture {

public static Architecture current() {
final String architecture = System.getProperty("os.arch", "");
switch (architecture) {
case "amd64":
case "x86_64":
return X64;
case "aarch64":
return AARCH64;
default:
throw new IllegalArgumentException("can not determine architecture from [" + architecture + "]");
}
return switch (architecture) {
case "amd64", "x86_64" -> X64;
case "aarch64" -> AARCH64;
default -> throw new IllegalArgumentException("can not determine architecture from [" + architecture + "]");
};
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -36,16 +36,12 @@ public final void run(String[] args) throws Exception {
System.exit(1);
}
switch (args[0]) {
case "search":
runSearchBenchmark(args);
break;
case "bulk":
runBulkIndexBenchmark(args);
break;
default:
case "search" -> runSearchBenchmark(args);
case "bulk" -> runBulkIndexBenchmark(args);
default -> {
System.err.println("Unknown benchmark type [" + args[0] + "]");
System.exit(1);

}
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,14 @@ public class BenchmarkMain {
@SuppressForbidden(reason = "system out is ok for a command line tool")
public static void main(String[] args) throws Exception {
String type = args[0];
AbstractBenchmark<?> benchmark = null;
switch (type) {
case "rest":
benchmark = new RestClientBenchmark();
break;
default:
AbstractBenchmark<?> benchmark = switch (type) {
case "rest" -> new RestClientBenchmark();
default -> {
System.err.println("Unknown client type [" + type + "]");
System.exit(1);
}
yield null;
}
};
benchmark.run(Arrays.copyOfRange(args, 1, args.length));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -163,14 +163,11 @@ public String getName() {
}

public static Status fromString(String value) {
switch (value) {
case "active":
return Status.ACTIVE;
case "paused":
return Status.PAUSED;
default:
throw new IllegalArgumentException("unexpected status value [" + value + "]");
}
return switch (value) {
case "active" -> Status.ACTIVE;
case "paused" -> Status.PAUSED;
default -> throw new IllegalArgumentException("unexpected status value [" + value + "]");
};
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -149,20 +149,11 @@ private static IndexEntry parseIndexEntry(XContentParser parser) throws IOExcept
parser.nextToken();
if (parser.currentToken() == Token.START_OBJECT) {
switch (parser.currentName()) {
case "aliases":
indexAliases = parseAliases(parser);
break;
case "mappings":
indexMappings = parseMappings(parser);
break;
case "settings":
indexSettings = Settings.fromXContent(parser);
break;
case "defaults":
indexDefaultSettings = Settings.fromXContent(parser);
break;
default:
parser.skipChildren();
case "aliases" -> indexAliases = parseAliases(parser);
case "mappings" -> indexMappings = parseMappings(parser);
case "settings" -> indexSettings = Settings.fromXContent(parser);
case "defaults" -> indexDefaultSettings = Settings.fromXContent(parser);
default -> parser.skipChildren();
}
} else if (parser.currentToken() == Token.VALUE_STRING) {
if (parser.currentName().equals("data_stream")) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,11 @@ public String label() {
}

public static LicenseStatus fromString(String value) {
switch (value) {
case "active":
return ACTIVE;
case "invalid":
return INVALID;
case "expired":
return EXPIRED;
default:
throw new IllegalArgumentException("unknown license status [" + value + "]");
}
return switch (value) {
case "active" -> ACTIVE;
case "invalid" -> INVALID;
case "expired" -> EXPIRED;
default -> throw new IllegalArgumentException("unknown license status [" + value + "]");
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,11 @@ public String toString() {
}

public static LicensesStatus fromString(String value) {
switch (value) {
case "valid":
return VALID;
case "invalid":
return INVALID;
case "expired":
return EXPIRED;
default:
throw new IllegalArgumentException("unknown licenses status [" + value + "]");
}
return switch (value) {
case "valid" -> VALID;
case "invalid" -> INVALID;
case "expired" -> EXPIRED;
default -> throw new IllegalArgumentException("unknown licenses status [" + value + "]");
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -164,25 +164,16 @@ private <T> List<T> parseArray(ParseField field, XContentParser parser, CheckedF
}

private Object parseFieldValue(XContentParser parser) throws IOException {
switch (parser.currentToken()) {
case VALUE_STRING:
return parser.text();

case VALUE_BOOLEAN:
return parser.booleanValue();

case VALUE_NUMBER:
return parser.longValue();

case VALUE_NULL:
return null;

default:
throw new ElasticsearchParseException(
"failed to parse rules expression. expected a field value but found [{}] instead",
parser.currentToken()
);
}
return switch (parser.currentToken()) {
case VALUE_STRING -> parser.text();
case VALUE_BOOLEAN -> parser.booleanValue();
case VALUE_NUMBER -> parser.longValue();
case VALUE_NULL -> null;
default -> throw new ElasticsearchParseException(
"failed to parse rules expression. expected a field value but found [{}] instead",
parser.currentToken()
);
};
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -75,24 +75,17 @@ public static GroupConfig fromXContent(final XContentParser parser) throws IOExc
continue;
}

SingleGroupSource groupSource = null;
switch (groupType) {
case "terms":
groupSource = TermsGroupSource.fromXContent(parser);
break;
case "histogram":
groupSource = HistogramGroupSource.fromXContent(parser);
break;
case "date_histogram":
groupSource = DateHistogramGroupSource.fromXContent(parser);
break;
case "geotile_grid":
groupSource = GeoTileGroupSource.fromXContent(parser);
break;
default:
SingleGroupSource groupSource = switch (groupType) {
case "terms" -> TermsGroupSource.fromXContent(parser);
case "histogram" -> HistogramGroupSource.fromXContent(parser);
case "date_histogram" -> DateHistogramGroupSource.fromXContent(parser);
case "geotile_grid" -> GeoTileGroupSource.fromXContent(parser);
default -> {
// not a valid group source. Consume up to the dest field end object
consumeUntilEndObject(parser, 2);
}
yield null;
}
};

if (groupSource != null) {
groups.put(destinationFieldName, groupSource);
Expand Down
Loading

0 comments on commit 358484b

Please sign in to comment.