Skip to content

Commit

Permalink
Code cleanup
Browse files Browse the repository at this point in the history
Gradle 8.11
  • Loading branch information
altro3 committed Nov 17, 2024
1 parent b9874a5 commit 818d1f9
Show file tree
Hide file tree
Showing 32 changed files with 130 additions and 182 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -88,15 +88,15 @@ public final void execute() throws IOException {
FileCollection classpath = getOptimizerClasspath().plus(getClasspath());
spec.setClasspath(aotClasspath);
spec.getMainClass().set("io.micronaut.aot.cli.Main");
List<String> args = new ArrayList<>(Arrays.asList(
"--classpath", classpath.getAsPath(),
"--runtime", getTargetRuntime().get().name().toUpperCase(),
"--package", getTargetPackage().get()
var args = new ArrayList<>(Arrays.asList(
"--classpath", classpath.getAsPath(),
"--runtime", getTargetRuntime().get().name().toUpperCase(),
"--package", getTargetPackage().get()
));
maybeAddOptimizerClasspath(args, getClasspath());
configureExtraArguments(args);
boolean useArgFile = true;
try (PrintWriter wrt = new PrintWriter(new FileWriter(argFile))) {
try (var wrt = new PrintWriter(new FileWriter(argFile))) {
args.forEach(arg -> wrt.println(escapeArg(arg)));
} catch (IOException e) {
useArgFile = false;
Expand All @@ -107,7 +107,7 @@ public final void execute() throws IOException {
spec.args(args);
}
getLogger().info("Running AOT optimizer {} with parameters: {}", useArgFile ? "using arg file" : "directly", args);
List<String> jvmArgs = new ArrayList<>();
var jvmArgs = new ArrayList<String>();
if (Boolean.TRUE.equals(getDebug().get())) {
getLogger().info("Running with debug enabled");
jvmArgs.add("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ static void registerShadowJar(Project project,
Jar mainJar = tasks.named("jar", Jar.class).get();
shadow.getManifest().inheritFrom(mainJar.getManifest());
if (javaApplication != null) {
// This is the reason why we use an afterEvalute:
// This is the reason why we use an afterEvaluate:
// The shadow plugin apparently does something with attributes,
// breaking support for providers
shadow.getManifest().getAttributes().put("Main-Class", javaApplication.getMainClass().get());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,8 @@ public void execute() {
for (Map.Entry<String, List<File>> entry : perService.entrySet()) {
String serviceType = entry.getKey();
List<File> files = entry.getValue();
File mergedServiceFile = new File(outputDir, serviceType);
try (PrintWriter wrt = new PrintWriter(new OutputStreamWriter(new FileOutputStream(mergedServiceFile), StandardCharsets.UTF_8))) {
var mergedServiceFile = new File(outputDir, serviceType);
try (var wrt = new PrintWriter(new OutputStreamWriter(new FileOutputStream(mergedServiceFile), StandardCharsets.UTF_8))) {
for (File file : files) {
Files.readAllLines(file.toPath()).forEach(wrt::println);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,9 @@ private static void stringParameter(Properties props, String parameter, Property

@TaskAction
void writeConfigFile() {
Properties props = new Properties();
var props = new Properties();
if (getUserConfiguration().isPresent()) {
try (InputStream in = new FileInputStream(getUserConfiguration().getAsFile().get())) {
try (var in = new FileInputStream(getUserConfiguration().getAsFile().get())) {
props.load(in);
} catch (IOException e) {
throw new GradleException("Unable to parse configuration file", e);
Expand Down Expand Up @@ -152,12 +152,7 @@ void writeConfigFile() {
String content = baos.toString();
try (var writer = new PrintWriter(Files.newBufferedWriter(outputFile.toPath()))) {
content.lines()
.filter(line -> {
if (line.startsWith("#") && !line.contains(GENERATED_BY_GRADLE_COMMENT)) {
return false;
}
return true;
})
.filter(line -> !line.startsWith("#") || line.contains(GENERATED_BY_GRADLE_COMMENT))
.forEach(writer::println);
} catch (IOException e) {
throw new GradleException("Unable to write output file: " + outputFile, e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
import org.gradle.api.tasks.TaskProvider;
import org.gradle.api.tasks.application.CreateStartScripts;
import org.gradle.api.tasks.bundling.Jar;
import org.jetbrains.annotations.NotNull;

import javax.inject.Inject;
import java.io.File;
Expand Down Expand Up @@ -214,7 +215,7 @@ private void registerDockerImage(Project project, TaskProvider<Jar> optimizedJar
Attributes attrs = manifest.getAttributes();
attrs.put("Main-Class", javaApplication.getMainClass());
attrs.put("Class-Path", project.getProviders().provider(() -> {
List<String> classpath = new ArrayList<>();
var classpath = new ArrayList<String>();
Configuration runtimeClasspath = project.getConfigurations()
.getByName(RUNTIME_CLASSPATH_CONFIGURATION_NAME);

Expand Down Expand Up @@ -419,7 +420,7 @@ private JarExclusionSpec(Provider<RegularFile> filterFile,
}

@Override
public void execute(FileCopyDetails details) {
public void execute(@NotNull FileCopyDetails details) {
if (excludes == null) {
File resourceFilter = filterFile.get().getAsFile();
try {
Expand All @@ -444,15 +445,10 @@ private static String normalizePath(String path) {
}
}

private static final class Configurations {
private final Configuration aotOptimizerRuntimeClasspath;
private final Configuration aotApplication;
private final Configuration aotApplicationClasspath;

private Configurations(Configuration aotOptimizerRuntimeClasspath, Configuration aotApplication, Configuration aotApplicationClasspath) {
this.aotOptimizerRuntimeClasspath = aotOptimizerRuntimeClasspath;
this.aotApplication = aotApplication;
this.aotApplicationClasspath = aotApplicationClasspath;
}
private record Configurations(
Configuration aotOptimizerRuntimeClasspath,
Configuration aotApplication,
Configuration aotApplicationClasspath
) {
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ protected void configureExtraArguments(List<String> args) {

@Override
protected void onSuccess(File outputDir) {
File sampleFile = new File(outputDir, getTargetRuntime().map(runtime -> runtime.getSimpleName() + ".properties").orElse("sample.properties").get());
var sampleFile = new File(outputDir, getTargetRuntime().map(runtime -> runtime.getSimpleName() + ".properties").orElse("sample.properties").get());
if (sampleFile.exists()) {
getLogger().lifecycle("Sample configuration file written to {}", Strings.clickableUrl(sampleFile));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ private void setupInstructions(List<Instruction> additionalInstructions) {
getInstructions().addAll(additionalInstructions);
if (getInstructions().get().stream().noneMatch(instruction -> instruction.getKeyword().equals(EntryPointInstruction.KEYWORD))) {
entryPoint(getArgs().map(strings -> {
List<String> newList = new ArrayList<>(strings.size() + 3);
var newList = new ArrayList<String>(strings.size() + 3);
newList.add("/home/app/checkpoint.sh");
newList.addAll(strings);
return newList;
Expand All @@ -160,7 +160,7 @@ void setupDockerfileInstructions() {
*/
void setupTaskPostEvaluate() {
// Get any custom instructions the user may or may not have entered, but ignoring our 'from' placeholder
List<Instruction> additionalInstructions = new ArrayList<>(getInstructions().get().subList(1, getInstructions().get().size()));
var additionalInstructions = new ArrayList<>(getInstructions().get().subList(1, getInstructions().get().size()));
// Reset the instructions to empty
getInstructions().set(new ArrayList<>());
setupInstructions(additionalInstructions);
Expand All @@ -170,11 +170,13 @@ static void setupResources(CRaCCheckpointDockerfile task) {
String workDir = DEFAULT_WORKING_DIR;
task.workingDir(workDir);
task.instruction("# Add required libraries");
task.runCommand("apt-get update && apt-get install -y \\\n" +
" curl \\\n" +
" jq \\\n" +
" libnl-3-200 \\\n" +
" && rm -rf /var/lib/apt/lists/*");
task.runCommand("""
apt-get update && apt-get install -y \\
curl \\
jq \\
libnl-3-200 \\
&& rm -rf /var/lib/apt/lists/*
""");
task.instruction("# Install latest CRaC OpenJDK");

// Limit the architecture, Azul doesn't support x86_64 https://api.azul.com/metadata/v1/docs/swagger
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,11 @@ private void setupResources() {
String workDir = DEFAULT_WORKING_DIR;
workingDir(workDir);
instruction("# Add required libraries");
runCommand("apt-get update && apt-get install -y \\\n" +
" libnl-3-200 \\\n" +
" && rm -rf /var/lib/apt/lists/*");
runCommand("""
apt-get update && apt-get install -y \\
libnl-3-200 \\
&& rm -rf /var/lib/apt/lists/*
""");
instruction("# Copy CRaC JDK from the checkpoint image (to save a download)");
copyFile("--from=" + createCheckpointImageName(getProject()) + " /azul-crac-jdk", "/azul-crac-jdk");
instruction("# Copy layers");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@

import static io.micronaut.gradle.Strings.capitalize;

@SuppressWarnings("java:S5738") // Using deprecated getPlatform method still, until it's removal in 4.0.0
@SuppressWarnings({"java:S5738", "Convert2Lambda"}) // Using deprecated getPlatform method still, until it's removal in 4.0.0
public class MicronautCRaCPlugin implements Plugin<Project> {

public static final String CRAC_DEFAULT_BASE_IMAGE = "ubuntu:22.04";
Expand All @@ -64,7 +64,7 @@ private void configurePlugin(Project project) {
ExtensionContainer extensions = project.getExtensions();
MicronautExtension micronautExtension = extensions.getByType(MicronautExtension.class);
CRaCConfiguration configuration = createCRaCConfiguration(project);
NamedDomainObjectContainer<MicronautDockerImage> dockerImages = (NamedDomainObjectContainer<MicronautDockerImage>) micronautExtension.getExtensions().findByName("dockerImages");
var dockerImages = (NamedDomainObjectContainer<MicronautDockerImage>) micronautExtension.getExtensions().findByName("dockerImages");
createCheckpointDockerImage(project, dockerImages.findByName("main"), configuration);
}

Expand Down Expand Up @@ -233,22 +233,15 @@ static String createCheckpointImageName(Project project) {
return (project.getRootProject().getName() + project.getPath() + "-checkpoint").replace(":", "-");
}

private static class CheckpointTasksOfNote {

private final TaskProvider<CRaCCheckpointDockerfile> checkpointDockerBuild;
private final TaskProvider<DockerStartContainer> start;

private CheckpointTasksOfNote(
@Nullable TaskProvider<CRaCCheckpointDockerfile> checkpointDockerBuild,
TaskProvider<DockerStartContainer> start
) {
this.checkpointDockerBuild = checkpointDockerBuild;
this.start = start;
}
private record CheckpointTasksOfNote(
@Nullable
TaskProvider<CRaCCheckpointDockerfile> checkpointDockerBuild,
TaskProvider<DockerStartContainer> start
) {

Optional<TaskProvider<CRaCCheckpointDockerfile>> getCheckpointDockerBuild() {
return Optional.ofNullable(checkpointDockerBuild);
}
return Optional.ofNullable(checkpointDockerBuild);
}
}

private Optional<TaskProvider<CRaCFinalDockerfile>> configureFinalDockerBuild(Project project,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package io.micronaut.gradle.crac;

import org.gradle.api.logging.Logger;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.io.StringWriter;
Expand All @@ -18,7 +19,7 @@ public TeeStringWriter(Logger logger) {

@Override
@SuppressWarnings("java:S2629") // This is done by Gradle
public void write(char[] cbuf, int off, int len) {
public void write(char @NotNull [] cbuf, int off, int len) {
delegate.write(cbuf, off, len);
logger.lifecycle(new String(cbuf, off, len).trim());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,15 +57,15 @@ void perform() throws IOException {
Provider<RegularFile> checkpointFile = getOutputDir().file("checkpoint.sh");
Path checkpointScriptPath = checkpointFile.get().getAsFile().toPath();

FilterSet filterSet = new FilterSet();
var filterSet = new FilterSet();
filterSet.addFilter("READINESS", getPreCheckpointReadinessCommand().get());

try (InputStream stream = getCheckpointFile().isPresent() ?
try (var stream = getCheckpointFile().isPresent() ?
Files.newInputStream(getCheckpointFile().get().getAsFile().toPath()) :
CheckpointScriptTask.class.getResourceAsStream("/checkpoint.sh");
Reader reader = new InputStreamReader(stream);
BufferedReader bufferedReader = new BufferedReader(reader);
BufferedWriter writer = Files.newBufferedWriter(checkpointScriptPath, StandardCharsets.UTF_8)) {
var bufferedReader = new BufferedReader(new InputStreamReader(stream));
BufferedWriter writer = Files.newBufferedWriter(checkpointScriptPath, StandardCharsets.UTF_8)
) {
String line;
while ((line = bufferedReader.readLine()) != null) {
writer.write(filterSet.replaceTokens(line));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,13 @@
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;

import static io.micronaut.gradle.Strings.capitalize;
import static org.gradle.api.plugins.JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME;

@SuppressWarnings("Convert2Lambda")
public class MicronautDockerPlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
Expand Down Expand Up @@ -201,11 +200,11 @@ private TaskProvider<Jar> createMainRunnerJar(Project project, TaskContainer tas

jar.from(dirs);
jar.manifest(manifest -> {
Map<String, Object> attrs = new HashMap<>(2);
var attrs = new HashMap<String, Object>(2);
JavaApplication javaApplication = project.getExtensions().getByType(JavaApplication.class);
attrs.put("Main-Class", javaApplication.getMainClass());
attrs.put("Class-Path", project.getProviders().provider(() -> {
List<String> classpath = new ArrayList<>();
var classpath = new ArrayList<String>();
Configuration runtimeClasspath = project.getConfigurations()
.getByName(RUNTIME_CLASSPATH_CONFIGURATION_NAME);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ protected void setupInstructions(List<Instruction> additionalInstructions) {
getInstructions().addAll(additionalInstructions);
if (getInstructions().get().stream().noneMatch(instruction -> instruction.getKeyword().equals(EntryPointInstruction.KEYWORD))) {
entryPoint(getArgs().map(strings -> {
List<String> newList = new ArrayList<>(strings.size() + 3);
var newList = new ArrayList<String>(strings.size() + 3);
newList.add("java");
newList.addAll(strings);
newList.add("-jar");
Expand All @@ -185,7 +185,7 @@ public void setupDockerfileInstructions() {
*/
public void setupTaskPostEvaluate() {
// Get any custom instructions the user may or may not have entered, but ignoring our 'from' placeholder
List<Instruction> additionalInstructions = new ArrayList<>(getInstructions().get().subList(1, getInstructions().get().size()));
var additionalInstructions = new ArrayList<>(getInstructions().get().subList(1, getInstructions().get().size()));
// Reset the instructions to empty
getInstructions().set(new ArrayList<>());
setupInstructions(additionalInstructions);
Expand Down
Loading

0 comments on commit 818d1f9

Please sign in to comment.