Skip to content

Commit 2868991

Browse files
author
Vincent Potucek
committed
try can use automatic resource management
1 parent 32d9512 commit 2868991

File tree

10 files changed

+87
-132
lines changed

10 files changed

+87
-132
lines changed

compat/maven-embedder/src/main/java/org/apache/maven/cli/props/MavenProperties.java

Lines changed: 24 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -486,39 +486,40 @@ public void substitute(UnaryOperator<String> callback) {
486486
* @throws IOException if an error occurs
487487
*/
488488
protected void saveLayout(Writer out, boolean typed) throws IOException {
489-
PropertiesWriter writer = new PropertiesWriter(out, typed);
490-
if (header != null) {
491-
for (String s : header) {
492-
writer.writeln(s);
493-
}
494-
}
489+
try (PropertiesWriter writer = new PropertiesWriter(out, typed)) {
495490

496-
for (String key : storage.keySet()) {
497-
Layout l = layout.get(key);
498-
if (l != null && l.getCommentLines() != null) {
499-
for (String s : l.getCommentLines()) {
491+
if (header != null) {
492+
for (String s : header) {
500493
writer.writeln(s);
501494
}
502495
}
503-
if (l != null && l.getValueLines() != null) {
504-
for (int i = 0; i < l.getValueLines().size(); i++) {
505-
String s = l.getValueLines().get(i);
506-
if (i < l.getValueLines().size() - 1) {
507-
writer.writeln(s + "\\");
508-
} else {
496+
497+
for (String key : storage.keySet()) {
498+
Layout l = layout.get(key);
499+
if (l != null && l.getCommentLines() != null) {
500+
for (String s : l.getCommentLines()) {
509501
writer.writeln(s);
510502
}
511503
}
512-
} else {
513-
writer.writeProperty(key, storage.get(key));
504+
if (l != null && l.getValueLines() != null) {
505+
for (int i = 0; i < l.getValueLines().size(); i++) {
506+
String s = l.getValueLines().get(i);
507+
if (i < l.getValueLines().size() - 1) {
508+
writer.writeln(s + "\\");
509+
} else {
510+
writer.writeln(s);
511+
}
512+
}
513+
} else {
514+
writer.writeProperty(key, storage.get(key));
515+
}
514516
}
515-
}
516-
if (footer != null) {
517-
for (String s : footer) {
518-
writer.writeln(s);
517+
if (footer != null) {
518+
for (String s : footer) {
519+
writer.writeln(s);
520+
}
519521
}
520522
}
521-
writer.flush();
522523
}
523524

524525
/**

impl/maven-cli/src/main/java/org/apache/maven/cling/MavenShellCling.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ public static void main(String[] args) throws IOException {
4747
/**
4848
* ClassWorld Launcher "enhanced" entry point: returning exitCode and accepts Class World.
4949
*/
50-
public static int main(String[] args, ClassWorld world) throws IOException {
50+
public static int main(String[] args, ClassWorld ignored) throws IOException {
5151
return new MavenShellCling().run(args, null, null, null, false);
5252
}
5353

impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/CommonsCliOptions.java

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -473,18 +473,18 @@ public void displayHelp(String command, Consumer<String> pw) {
473473
pw.accept("");
474474

475475
StringWriter sw = new StringWriter();
476-
PrintWriter pw2 = new PrintWriter(sw);
477-
formatter.printHelp(
478-
pw2,
479-
width,
480-
commandLineSyntax(command),
481-
System.lineSeparator() + "Options:",
482-
options,
483-
HelpFormatter.DEFAULT_LEFT_PAD,
484-
HelpFormatter.DEFAULT_DESC_PAD,
485-
System.lineSeparator(),
486-
false);
487-
pw2.flush();
476+
try (PrintWriter writer = new PrintWriter(sw)) {
477+
formatter.printHelp(
478+
writer,
479+
width,
480+
commandLineSyntax(command),
481+
System.lineSeparator() + "Options:",
482+
options,
483+
HelpFormatter.DEFAULT_LEFT_PAD,
484+
HelpFormatter.DEFAULT_DESC_PAD,
485+
System.lineSeparator(),
486+
false);
487+
}
488488
for (String s : sw.toString().split(System.lineSeparator())) {
489489
pw.accept(s);
490490
}

impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/LookupInvoker.java

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -407,11 +407,7 @@ protected Consumer<String> doDetermineWriter(C context) {
407407
} else {
408408
// Given the terminal creation has been offloaded to a different thread,
409409
// do not pass directly the terminal writer
410-
return msg -> {
411-
PrintWriter pw = context.terminal.writer();
412-
pw.println(msg);
413-
pw.flush();
414-
};
410+
return msg -> context.terminal.writer().println(msg);
415411
}
416412
}
417413

@@ -442,10 +438,9 @@ protected void activateLogging(C context) throws Exception {
442438
}
443439

444440
// at this point logging is set up, reply so far accumulated logs, if any and swap logger with real one
445-
Logger logger =
441+
context.logger =
446442
new Slf4jLogger(context.loggerFactory.getLogger(getClass().getName()));
447-
context.logger.drain().forEach(e -> logger.log(e.level(), e.message(), e.error()));
448-
context.logger = logger;
443+
context.logger.drain().forEach(e -> context.logger.log(e.level(), e.message(), e.error()));
449444
}
450445

451446
protected void helpOrVersionAndMayExit(C context) throws Exception {

impl/maven-cli/src/main/java/org/apache/maven/cling/props/MavenProperties.java

Lines changed: 24 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -485,39 +485,39 @@ public void substitute(UnaryOperator<String> callback) {
485485
* @throws IOException if an error occurs
486486
*/
487487
protected void saveLayout(Writer out, boolean typed) throws IOException {
488-
PropertiesWriter writer = new PropertiesWriter(out, typed);
489-
if (header != null) {
490-
for (String s : header) {
491-
writer.writeln(s);
492-
}
493-
}
494-
495-
for (String key : storage.keySet()) {
496-
Layout l = layout.get(key);
497-
if (l != null && l.getCommentLines() != null) {
498-
for (String s : l.getCommentLines()) {
488+
try (PropertiesWriter writer = new PropertiesWriter(out, typed)) {
489+
if (header != null) {
490+
for (String s : header) {
499491
writer.writeln(s);
500492
}
501493
}
502-
if (l != null && l.getValueLines() != null) {
503-
for (int i = 0; i < l.getValueLines().size(); i++) {
504-
String s = l.getValueLines().get(i);
505-
if (i < l.getValueLines().size() - 1) {
506-
writer.writeln(s + "\\");
507-
} else {
494+
495+
for (String key : storage.keySet()) {
496+
Layout l = layout.get(key);
497+
if (l != null && l.getCommentLines() != null) {
498+
for (String s : l.getCommentLines()) {
508499
writer.writeln(s);
509500
}
510501
}
511-
} else {
512-
writer.writeProperty(key, storage.get(key));
502+
if (l != null && l.getValueLines() != null) {
503+
for (int i = 0; i < l.getValueLines().size(); i++) {
504+
String s = l.getValueLines().get(i);
505+
if (i < l.getValueLines().size() - 1) {
506+
writer.writeln(s + "\\");
507+
} else {
508+
writer.writeln(s);
509+
}
510+
}
511+
} else {
512+
writer.writeProperty(key, storage.get(key));
513+
}
513514
}
514-
}
515-
if (footer != null) {
516-
for (String s : footer) {
517-
writer.writeln(s);
515+
if (footer != null) {
516+
for (String s : footer) {
517+
writer.writeln(s);
518+
}
518519
}
519520
}
520-
writer.flush();
521521
}
522522

523523
/**

impl/maven-cli/src/main/java/org/apache/maven/cling/transfer/ConsoleMavenTransferListener.java

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -50,14 +50,14 @@ public ConsoleMavenTransferListener(
5050

5151
@Override
5252
public void transferInitiated(TransferEvent event) {
53-
overridePreviousTransfer(event);
53+
overridePreviousTransfer();
5454

5555
super.transferInitiated(event);
5656
}
5757

5858
@Override
5959
public void transferCorrupted(TransferEvent event) throws TransferCancelledException {
60-
overridePreviousTransfer(event);
60+
overridePreviousTransfer();
6161

6262
super.transferCorrupted(event);
6363
}
@@ -123,20 +123,20 @@ private void pad(StringBuilder buffer, int spaces) {
123123
@Override
124124
public void transferSucceeded(TransferEvent event) {
125125
transfers.remove(new TransferResourceIdentifier(event.getResource()));
126-
overridePreviousTransfer(event);
126+
overridePreviousTransfer();
127127

128128
super.transferSucceeded(event);
129129
}
130130

131131
@Override
132132
public void transferFailed(TransferEvent event) {
133133
transfers.remove(new TransferResourceIdentifier(event.getResource()));
134-
overridePreviousTransfer(event);
134+
overridePreviousTransfer();
135135

136136
super.transferFailed(event);
137137
}
138138

139-
private void overridePreviousTransfer(TransferEvent event) {
139+
private void overridePreviousTransfer() {
140140
if (lastLength > 0) {
141141
pad(buffer, lastLength);
142142
buffer.append('\r');

impl/maven-cli/src/test/java/org/apache/maven/cling/invoker/mvn/MavenInvokerTest.java

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -206,13 +206,11 @@ void conflictingSettings(
206206
</settings>""";
207207
Path dotMvn = cwd.resolve(".mvn");
208208
Files.createDirectories(dotMvn);
209-
Path projectExtensions = dotMvn.resolve("settings.xml");
210-
Files.writeString(projectExtensions, settingsXml);
209+
Files.writeString(dotMvn.resolve("settings.xml"), settingsXml);
211210

212211
Path userConf = userHome.resolve(".m2");
213212
Files.createDirectories(userConf);
214-
Path userExtensions = userConf.resolve("settings.xml");
215-
Files.writeString(userExtensions, settingsXml);
213+
Files.writeString(userConf.resolve("settings.xml"), settingsXml);
216214

217215
// we just execute a Mojo for downloading it only and to assert from which URL it came
218216
Map<String, String> logs = invoke(

impl/maven-executor/src/main/java/org/apache/maven/cling/executor/forked/ForkedMavenExecutor.java

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -163,10 +163,8 @@ protected CountDownLatch pump(Process p, ExecutorRequest executorRequest) {
163163
CountDownLatch latch = new CountDownLatch(3);
164164
String suffix = "-pump-" + p.pid();
165165
Thread stdoutPump = new Thread(() -> {
166-
try {
167-
OutputStream stdout = executorRequest.stdOut().orElse(OutputStream.nullOutputStream());
166+
try (OutputStream stdout = executorRequest.stdOut().orElse(OutputStream.nullOutputStream())) {
168167
p.getInputStream().transferTo(stdout);
169-
stdout.flush();
170168
} catch (IOException e) {
171169
throw new UncheckedIOException(e);
172170
} finally {
@@ -176,10 +174,8 @@ protected CountDownLatch pump(Process p, ExecutorRequest executorRequest) {
176174
stdoutPump.setName("stdout" + suffix);
177175
stdoutPump.start();
178176
Thread stderrPump = new Thread(() -> {
179-
try {
180-
OutputStream stderr = executorRequest.stdErr().orElse(OutputStream.nullOutputStream());
177+
try (OutputStream stderr = executorRequest.stdErr().orElse(OutputStream.nullOutputStream())) {
181178
p.getErrorStream().transferTo(stderr);
182-
stderr.flush();
183179
} catch (IOException e) {
184180
throw new UncheckedIOException(e);
185181
} finally {
@@ -189,10 +185,8 @@ protected CountDownLatch pump(Process p, ExecutorRequest executorRequest) {
189185
stderrPump.setName("stderr" + suffix);
190186
stderrPump.start();
191187
Thread stdinPump = new Thread(() -> {
192-
try {
193-
OutputStream in = p.getOutputStream();
188+
try (OutputStream in = p.getOutputStream()) {
194189
executorRequest.stdIn().orElse(InputStream.nullInputStream()).transferTo(in);
195-
in.flush();
196190
} catch (IOException e) {
197191
throw new UncheckedIOException(e);
198192
} finally {

its/core-it-support/core-it-plugins/maven-it-plugin-context-passing/src/main/java/org/apache/maven/plugin/coreit/CatchMojo.java

Lines changed: 1 addition & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -58,23 +58,10 @@ public void execute() throws MojoExecutionException {
5858

5959
File outfile = new File(outDir, value);
6060

61-
Writer writer = null;
62-
try {
63-
writer = new FileWriter(outfile);
64-
61+
try (Writer writer = new FileWriter(outfile)) {
6562
writer.write(value);
66-
67-
writer.flush();
6863
} catch (IOException e) {
6964
throw new MojoExecutionException("Cannot write output file: " + outfile, e);
70-
} finally {
71-
if (writer != null) {
72-
try {
73-
writer.close();
74-
} catch (IOException e) {
75-
// ignore
76-
}
77-
}
7865
}
7966
}
8067
}

its/core-it-support/core-it-plugins/maven-it-plugin-log-file/src/main/java/org/apache/maven/plugin/coreit/AbstractLogMojo.java

Lines changed: 12 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,7 @@
1818
*/
1919
package org.apache.maven.plugin.coreit;
2020

21-
import java.io.BufferedWriter;
22-
import java.io.File;
23-
import java.io.FileOutputStream;
24-
import java.io.IOException;
25-
import java.io.OutputStream;
26-
import java.io.OutputStreamWriter;
21+
import java.io.*;
2722

2823
import org.apache.maven.plugin.AbstractMojo;
2924
import org.apache.maven.plugin.MojoExecutionException;
@@ -78,25 +73,14 @@ protected void append(Object value) throws MojoExecutionException {
7873
File file = getLogFile();
7974
getLog().info("[MAVEN-CORE-IT-LOG] Updating log file: " + file);
8075
getLog().info("[MAVEN-CORE-IT-LOG] " + value);
81-
try {
82-
file.getParentFile().mkdirs();
83-
OutputStream out = new FileOutputStream(file, true);
84-
try {
85-
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, encoding));
86-
if (value != null) {
87-
writer.write(value.toString());
88-
writer.newLine();
89-
writer.flush();
90-
}
91-
} finally {
92-
try {
93-
out.close();
94-
} catch (IOException e) {
95-
// just ignore, we tried our best to clean up
96-
}
76+
if (value != null && file.getParentFile().mkdirs()) {
77+
try (BufferedWriter w =
78+
new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), encoding))) {
79+
w.write(value.toString());
80+
w.newLine();
81+
} catch (IOException e) {
82+
throw new MojoExecutionException("Failed to update log file " + logFile, e);
9783
}
98-
} catch (IOException e) {
99-
throw new MojoExecutionException("Failed to update log file " + logFile, e);
10084
}
10185
}
10286

@@ -108,19 +92,15 @@ protected void append(Object value) throws MojoExecutionException {
10892
protected void reset() throws MojoExecutionException {
10993
File file = getLogFile();
11094
getLog().info("[MAVEN-CORE-IT-LOG] Resetting log file: " + file);
111-
try {
95+
if (file.getParentFile().mkdirs()) {
11296
/*
11397
* NOTE: Intentionally don't delete the file but create a new empty one to check the plugin was executed.
11498
*/
115-
file.getParentFile().mkdirs();
116-
OutputStream out = new FileOutputStream(file);
11799
try {
118-
out.close();
119-
} catch (IOException e) {
120-
// just ignore, we tried our best to clean up
100+
new FileOutputStream(file).close();
101+
} catch (IOException ignore) {
102+
// tried our best to clean up
121103
}
122-
} catch (IOException e) {
123-
throw new MojoExecutionException("Failed to reset log file " + logFile, e);
124104
}
125105
}
126106
}

0 commit comments

Comments
 (0)