1
0
mirror of https://github.com/octoleo/plantuml.git synced 2024-11-26 14:56:28 +00:00

Refactor some code to use AutoCloseable / try-with-resources

This commit is contained in:
matthew16550 2021-09-11 00:52:29 +10:00
parent 51e95b113b
commit 08dfd191ba
21 changed files with 104 additions and 194 deletions

View File

@ -60,8 +60,7 @@ public class AFileZipEntry implements AFile {
public InputStream openFile() {
final InputStream tmp = zipFile.openFile();
if (tmp != null)
try {
final ZipInputStream zis = new ZipInputStream(tmp);
try (final ZipInputStream zis = new ZipInputStream(tmp)) {
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
@ -73,7 +72,6 @@ public class AFileZipEntry implements AFile {
ze = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
} catch (IOException e) {
e.printStackTrace();
}

View File

@ -64,19 +64,15 @@ public final class BlockUmlBuilder implements DefinitionsContainer {
public BlockUmlBuilder(List<String> config, String charset, Defines defines, Reader readerInit, SFile newCurrentDir,
String desc) throws IOException {
ReadLineNumbered includer = null;
this.defines = defines;
this.charset = charset;
try {
this.reader = new UncommentReadLine(ReadLineReader.create(readerInit, desc));
this.importedFiles = ImportedFiles.createImportedFiles(new AParentFolderRegular(newCurrentDir));
includer = new Preprocessor(config, reader);
this.reader = new UncommentReadLine(ReadLineReader.create(readerInit, desc));
this.importedFiles = ImportedFiles.createImportedFiles(new AParentFolderRegular(newCurrentDir));
try (ReadLineNumbered includer = new Preprocessor(config, reader)) {
init(includer);
} finally {
if (includer != null) {
includer.close();
// usedFiles = includer.getFilesUsedTOBEREMOVED();
}
readerInit.close();
}
}

View File

@ -139,9 +139,9 @@ public class FileUtils {
}
static public void copyToFile(byte[] src, SFile dest) throws IOException {
final OutputStream fos = dest.createBufferedOutputStream();
fos.write(src);
fos.close();
try (OutputStream fos = dest.createBufferedOutputStream()) {
fos.write(src);
}
}
static public String readSvg(SFile svgFile) throws IOException {

View File

@ -210,9 +210,7 @@ public class OptionFlags {
return;
}
// final PSystemError systemError = (PSystemError) system;
PrintStream ps = null;
try {
ps = SecurityUtils.createPrintStream(logData.createFileOutputStream(true));
try (PrintStream ps = SecurityUtils.createPrintStream(logData.createFileOutputStream(true))) {
ps.println("Start of " + file.getName());
ps.println(warnOrError);
ps.println("End of " + file.getName());
@ -220,10 +218,6 @@ public class OptionFlags {
} catch (FileNotFoundException e) {
Log.error("Cannot open " + logData);
e.printStackTrace();
} finally {
if (ps != null) {
ps.close();
}
}
}
}
@ -231,17 +225,11 @@ public class OptionFlags {
public final void setLogData(SFile logData) {
this.logData = logData;
logData.delete();
PrintStream ps = null;
try {
ps = SecurityUtils.createPrintStream(logData.createFileOutputStream());
try (PrintStream ps = SecurityUtils.createPrintStream(logData.createFileOutputStream())) {
ps.println();
} catch (FileNotFoundException e) {
Log.error("Cannot open " + logData);
e.printStackTrace();
} finally {
if (ps != null) {
ps.close();
}
}
}

View File

@ -297,17 +297,10 @@ public class Run {
return;
}
InputStream stream = null;
final BufferedImage im;
try {
stream = source.openStream();
try (InputStream stream = source.openStream()) {
im = ImageIO.read(stream);
} finally {
if (stream != null) {
stream.close();
}
}
final String name = getSpriteName(fileName);
final String s = compressed ? SpriteUtils.encodeCompressed(im, name, level)
: SpriteUtils.encode(im, name, level);
@ -545,24 +538,24 @@ public class Run {
.withPreprocFormat();
final SFile file = suggested.getFile(0);
Log.info("Export preprocessing source to " + file.getPrintablePath());
final PrintWriter pw = charset == null ? file.createPrintWriter() : file.createPrintWriter(charset);
int level = 0;
for (CharSequence cs : blockUml.getDefinition(true)) {
String s = cs.toString();
if (cypher != null) {
if (s.contains("skinparam") && s.contains("{")) {
level++;
}
if (level == 0 && s.contains("skinparam") == false) {
s = cypher.cypher(s);
}
if (level > 0 && s.contains("}")) {
level--;
try (final PrintWriter pw = charset == null ? file.createPrintWriter() : file.createPrintWriter(charset)) {
int level = 0;
for (CharSequence cs : blockUml.getDefinition(true)) {
String s = cs.toString();
if (cypher != null) {
if (s.contains("skinparam") && s.contains("{")) {
level++;
}
if (level == 0 && s.contains("skinparam") == false) {
s = cypher.cypher(s);
}
if (level > 0 && s.contains("}")) {
level--;
}
}
pw.println(s);
}
pw.println(s);
}
pw.close();
}
}

View File

@ -143,11 +143,8 @@ public class SignatureUtils {
}
public static String getSignatureSha512(SFile f) throws IOException {
final InputStream is = f.openFile();
try {
try (InputStream is = f.openFile()) {
return getSignatureSha512(is);
} finally {
is.close();
}
}
@ -183,9 +180,8 @@ public class SignatureUtils {
}
public static synchronized String getSignature(SFile f) throws IOException {
try {
try (final InputStream is = f.openFile()) {
final MessageDigest msgDigest = MessageDigest.getInstance("MD5");
final InputStream is = f.openFile();
if (is == null) {
throw new FileNotFoundException();
}
@ -193,7 +189,6 @@ public class SignatureUtils {
while ((read = is.read()) != -1) {
msgDigest.update((byte) read);
}
is.close();
final byte[] digest = msgDigest.digest();
return toString(digest);
} catch (NoSuchAlgorithmException e) {

View File

@ -108,17 +108,10 @@ public abstract class SourceFileReaderAbstract implements ISourceFileReader {
private List<GeneratedImage> getCrashedImage(BlockUml blockUml, Throwable t, SFile outputFile) throws IOException {
final GeneratedImage image = new GeneratedImageImpl(outputFile, "Crash Error", blockUml, FileImageData.CRASH);
OutputStream os = null;
try {
os = outputFile.createBufferedOutputStream();
try (OutputStream os = outputFile.createBufferedOutputStream()) {
UmlDiagram.exportDiagramError(os, t, fileFormatOption, 42, null, blockUml.getFlashData(),
UmlDiagram.getFailureText2(t, blockUml.getFlashData()));
} finally {
if (os != null) {
os.close();
}
}
return Collections.singletonList(image);
}
@ -128,9 +121,9 @@ public abstract class SourceFileReaderAbstract implements ISourceFileReader {
if (warnOrError != null) {
final String name = f.getName().substring(0, f.getName().length() - 4) + ".err";
final SFile errorFile = f.getParentFile().file(name);
final PrintStream ps = SecurityUtils.createPrintStream(errorFile.createFileOutputStream());
ps.print(warnOrError);
ps.close();
try (PrintStream ps = SecurityUtils.createPrintStream(errorFile.createFileOutputStream())) {
ps.print(warnOrError);
}
}
}
}

View File

@ -110,14 +110,9 @@ public class SourceStringReader {
}
public DiagramDescription outputImage(SFile f) throws IOException {
final OutputStream os = f.createBufferedOutputStream();
DiagramDescription result = null;
try {
result = outputImage(os, 0);
} finally {
os.close();
try (OutputStream os = f.createBufferedOutputStream()) {
return outputImage(os, 0);
}
return result;
}
@Deprecated

View File

@ -282,9 +282,10 @@ public abstract class UmlDiagram extends TitledDiagram implements Diagram, Annot
private ImageData exportDiagramInternalPdf(OutputStream os, int index) throws IOException {
final File svg = FileUtils.createTempFileLegacy("pdf", ".svf");
final File pdfFile = FileUtils.createTempFileLegacy("pdf", ".pdf");
final OutputStream fos = new BufferedOutputStream(new FileOutputStream(svg));
final ImageData result = exportDiagram(fos, index, new FileFormatOption(FileFormat.SVG));
fos.close();
final ImageData result;
try (OutputStream fos = new BufferedOutputStream(new FileOutputStream(svg))) {
result = exportDiagram(fos, index, new FileFormatOption(FileFormat.SVG));
}
PdfConverter.convert(svg, pdfFile);
FileUtils.copyToStream(pdfFile, os);
return result;
@ -297,18 +298,11 @@ public abstract class UmlDiagram extends TitledDiagram implements Diagram, Annot
throws FileNotFoundException {
final String name = changeName(suggestedFile.getFile(index).getAbsolutePath());
final SFile cmapFile = new SFile(name);
PrintWriter pw = null;
try {
try (PrintWriter pw = cmapFile.createPrintWriter()) {
if (PSystemUtils.canFileBeWritten(cmapFile) == false) {
return;
}
pw = cmapFile.createPrintWriter();
pw.print(cmapdata.getCMapData(cmapFile.getName().substring(0, cmapFile.getName().length() - 6)));
pw.close();
} finally {
if (pw != null) {
pw.close();
}
}
}

View File

@ -112,24 +112,24 @@ public class CheckZipTask extends Task {
private void loadZipFile(SFile file) throws IOException {
this.entries.clear();
final PrintWriter pw = SecurityUtils.createPrintWriter("tmp.txt");
final InputStream tmp = file.openFile();
if (tmp == null) {
throw new FileNotFoundException();
}
final ZipInputStream zis = new ZipInputStream(tmp);
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
final String fileName = ze.getName();
this.entries.add(fileName);
if (fileName.endsWith("/") == false) {
pw.println("<file name=\"" + fileName + "\" />");
try (
final PrintWriter pw = SecurityUtils.createPrintWriter("tmp.txt");
final ZipInputStream zis = new ZipInputStream(tmp);
) {
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
final String fileName = ze.getName();
this.entries.add(fileName);
if (fileName.endsWith("/") == false) {
pw.println("<file name=\"" + fileName + "\" />");
}
ze = zis.getNextEntry();
}
ze = zis.getNextEntry();
}
pw.close();
zis.close();
}
private synchronized void myLog(String s) {

View File

@ -49,12 +49,11 @@ public class CompressionBrotli implements Compression {
}
public ByteArray decompress(byte[] in) throws NoPlantumlCompressionException {
try {
final BrotliInputStream brotli = new BrotliInputStream(new ByteArrayInputStream(in));
final ByteArrayOutputStream result = new ByteArrayOutputStream();
try (
final BrotliInputStream brotli = new BrotliInputStream(new ByteArrayInputStream(in));
final ByteArrayOutputStream result = new ByteArrayOutputStream();
) {
FileUtils.copyToStream(brotli, result);
brotli.close();
result.close();
return ByteArray.from(result.toByteArray());
} catch (IOException e) {
e.printStackTrace();

View File

@ -85,12 +85,10 @@ public class GroupPrinter {
}
public static void print(SFile f, IGroup rootGroup) {
try {
final PrintWriter pw = f.createPrintWriter();
try (PrintWriter pw = f.createPrintWriter()) {
pw.println("<html>");
new GroupPrinter(pw).printGroup(rootGroup);
pw.println("</html>");
pw.close();
} catch (IOException e) {
e.printStackTrace();
}

View File

@ -85,30 +85,28 @@ public class OpenIcon {
private OpenIcon(InputStream is, String id) throws IOException {
this.id = id;
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String s = null;
while ((s = br.readLine()) != null) {
rawData.add(s);
if (s.contains("<path")) {
final int x1 = s.indexOf('"');
final int x2 = s.indexOf('"', x1 + 1);
svgPath = new SvgPath(s.substring(x1 + 1, x2));
try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
String s = null;
while ((s = br.readLine()) != null) {
rawData.add(s);
if (s.contains("<path")) {
final int x1 = s.indexOf('"');
final int x2 = s.indexOf('"', x1 + 1);
svgPath = new SvgPath(s.substring(x1 + 1, x2));
}
}
}
br.close();
is.close();
if (rawData.size() != 3 && rawData.size() != 4) {
throw new IllegalStateException();
}
}
void saveCopy(SFile fnew) throws IOException {
final PrintWriter pw = fnew.createPrintWriter();
pw.println(rawData.get(0));
pw.println(svgPath.toSvg());
pw.println(rawData.get(rawData.size() - 1));
pw.close();
try(PrintWriter pw = fnew.createPrintWriter()) {
pw.println(rawData.get(0));
pw.println(svgPath.toSvg());
pw.println(rawData.get(rawData.size() - 1));
}
}
private Dimension2D getDimension(double factor) {

View File

@ -66,14 +66,14 @@ public class PSystemListOpenIconic extends PlainDiagram {
lines.add("<i>Credit to");
lines.add("https://useiconic.com/open");
lines.add(" ");
final BufferedReader br = new BufferedReader(new InputStreamReader(getRessourceAllTxt()));
String s = null;
while ((s = br.readLine()) != null) {
// lines.add("<&yen> " + s);
// System.err.println("s=" + s);
lines.add("<&" + s + "> " + s);
try (BufferedReader br = new BufferedReader(new InputStreamReader(getRessourceAllTxt()))) {
String s = null;
while ((s = br.readLine()) != null) {
// lines.add("<&yen> " + s);
// System.err.println("s=" + s);
lines.add("<&" + s + "> " + s);
}
}
br.close();
final List<TextBlock> cols = PSystemDonors.getCols(lines, 7, 0);
return new TextBlockHorizontal(cols, VerticalAlignment.TOP);
}

View File

@ -248,16 +248,10 @@ public class PicoWebServerTest {
}
private static String httpRaw(String request) throws Exception {
Socket socket = null;
try {
socket = socketConnection();
try (Socket socket = socketConnection()) {
socket.getOutputStream().write(request.getBytes(UTF_8));
socket.shutdownOutput();
return readStreamAsString(socket.getInputStream()).replaceAll("\r\n", "\n");
} finally {
if (socket != null) {
socket.close();
}
}
}

View File

@ -56,14 +56,8 @@ public class PngIO {
}
public static void write(RenderedImage image, SFile file, String metadata, int dpi) throws IOException {
OutputStream os = null;
try {
os = file.createBufferedOutputStream();
try (OutputStream os = file.createBufferedOutputStream()) {
write(image, os, metadata, dpi);
} finally {
if (os != null) {
os.close();
}
}
Log.debug("File is " + file);
Log.debug("File size " + file.length());

View File

@ -222,11 +222,11 @@ public class GraphvizSolverB {
private void exportPng(final String dotString, SFile f) throws IOException {
final Graphviz graphviz = GraphvizUtils.create(null, dotString, "png");
final OutputStream os = f.createBufferedOutputStream();
final ProcessState state = graphviz.createFile3(os);
os.close();
if (state.differs(ProcessState.TERMINATED_OK())) {
throw new IllegalStateException("Timeout3 " + state);
try (OutputStream os = f.createBufferedOutputStream()) {
final ProcessState state = graphviz.createFile3(os);
if (state.differs(ProcessState.TERMINATED_OK())) {
throw new IllegalStateException("Timeout3 " + state);
}
}
}

View File

@ -166,27 +166,15 @@ public class StatsUtils {
}
static void htmlOutput(Stats stats) throws FileNotFoundException {
PrintWriter pw = null;
try {
pw = SecurityUtils.createPrintWriter("plantuml-stats.html");
try (PrintWriter pw = SecurityUtils.createPrintWriter("plantuml-stats.html")) {
pw.print(new HtmlConverter(stats).toHtml());
} finally {
if (pw != null) {
pw.close();
}
}
}
static void xmlOutput(Stats stats)
throws FileNotFoundException, TransformerException, ParserConfigurationException, IOException {
OutputStream os = null;
try {
os = SecurityUtils.createFileOutputStream("plantuml-stats.xml");
throws TransformerException, ParserConfigurationException, IOException {
try (OutputStream os = SecurityUtils.createFileOutputStream("plantuml-stats.xml")) {
new XmlConverter(stats).createXml(os);
} finally {
if (os != null) {
os.close();
}
}
}

View File

@ -47,15 +47,9 @@ import net.sourceforge.plantuml.security.SFile;
public class SvekUtils {
static public void traceString(final SFile f, String text) throws IOException {
PrintWriter pw = null;
try {
Log.info("Creating intermediate file " + f.getPrintablePath());
pw = f.createPrintWriter();
Log.info("Creating intermediate file " + f.getPrintablePath());
try (PrintWriter pw = f.createPrintWriter()) {
pw.print(text);
} finally {
if (pw != null) {
pw.close();
}
}
}

View File

@ -47,7 +47,6 @@ import net.sourceforge.plantuml.OptionFlags;
import net.sourceforge.plantuml.OptionPrint;
import net.sourceforge.plantuml.PlainStringsDiagram;
import net.sourceforge.plantuml.Run;
import net.sourceforge.plantuml.StringLocated;
import net.sourceforge.plantuml.core.DiagramDescription;
import net.sourceforge.plantuml.core.UmlSource;
import net.sourceforge.plantuml.cucadiagram.dot.GraphvizUtils;
@ -127,11 +126,8 @@ public class PSystemVersion extends PlainStringsDiagram {
}
private static BufferedImage getImageWebp(final String name) {
try {
final InputStream is = PSystemVersion.class.getResourceAsStream(name);
final BufferedImage image = PSystemDedication.getBufferedImage(is);
is.close();
return image;
try (InputStream is = PSystemVersion.class.getResourceAsStream(name)) {
return PSystemDedication.getBufferedImage(is);
} catch (IOException e) {
e.printStackTrace();
}

View File

@ -85,28 +85,25 @@ public final class WindowsDotArchive {
private static void extract(File dir) throws IOException {
final InputStream raw = WindowsDotArchive.class.getResourceAsStream("graphviz.dat");
final BrotliInputStream is = new BrotliInputStream(raw);
while (true) {
final String name = readString(is);
if (name.length() == 0)
break;
final int size = readNumber(is);
final OutputStream fos = new BufferedOutputStream(new FileOutputStream(new File(dir, name)));
for (int i = 0; i < size; i++) {
fos.write(is.read());
try (final BrotliInputStream is = new BrotliInputStream(raw)) {
while (true) {
final String name = readString(is);
if (name.length() == 0)
break;
final int size = readNumber(is);
try (final OutputStream fos = new BufferedOutputStream(new FileOutputStream(new File(dir, name)))) {
for (int i = 0; i < size; i++) {
fos.write(is.read());
}
}
}
fos.close();
}
is.close();
}
public synchronized boolean isThereArchive() {
if (isThereArchive == null)
try {
final InputStream raw = WindowsDotArchive.class.getResourceAsStream("graphviz.dat");
try (InputStream raw = WindowsDotArchive.class.getResourceAsStream("graphviz.dat")) {
isThereArchive = raw != null;
raw.close();
} catch (Exception e) {
isThereArchive = false;
}