From 1dd13bdcd78b8466fb40a0044bf825b2e73d49f6 Mon Sep 17 00:00:00 2001 From: Andrei Solntsev Date: Fri, 29 Dec 2023 16:35:52 +0200 Subject: [PATCH] refactor exception handling & closing I/O resources --- .../context/StylesheetFactoryImpl.java | 7 +- .../org/xhtmlrenderer/layout/BoxBuilder.java | 26 ++-- .../xhtmlrenderer/simple/ImageRenderer.java | 9 +- .../extend/XhtmlCssOnlyNamespaceHandler.java | 16 +- .../org/xhtmlrenderer/swing/BasicPanel.java | 6 +- .../swing/DelegatingUserAgent.java | 21 +-- .../xhtmlrenderer/swing/NaiveUserAgent.java | 48 +----- .../org/xhtmlrenderer/swing/UriResolver.java | 5 +- .../org/xhtmlrenderer/util/Configuration.java | 16 +- .../org/xhtmlrenderer/util/FSImageWriter.java | 1 - .../java/org/xhtmlrenderer/util/IOUtil.java | 127 +++++++++++----- .../xhtmlrenderer/util/StreamResource.java | 11 +- .../java/org/xhtmlrenderer/util/Zipper.java | 39 +++-- .../src/test/java/eeze/Eeze.java | 143 ++++++++---------- .../src/main/java/FontScaleJPanelRender.java | 5 +- .../src/main/java/JPanelRender.java | 5 +- .../src/main/java/PDFRender.java | 34 +---- .../main/java/PDFRenderToMultiplePages.java | 31 ++-- .../src/main/java/ReplaceRender.java | 5 +- .../demo/aboutbox/DemoUserAgent.java | 35 +---- .../demo/browser/BrowserMenuBar.java | 19 +-- .../demo/browser/BrowserPanel.java | 11 +- .../demo/browser/PanelManager.java | 24 +-- .../fop/nbsp/NonBreakPointsLoaderImpl.java | 12 +- .../xhtmlrenderer/pdf/CheckboxFormField.java | 39 ++--- .../org/xhtmlrenderer/pdf/ITextUserAgent.java | 7 +- .../xhtmlrenderer/pdf/SelectFormField.java | 8 +- .../org/xhtmlrenderer/pdf/TextFormField.java | 73 +++------ .../java/org/xhtmlrenderer/pdf/ToPDF.java | 26 +--- .../org/xhtmlrenderer/simple/PDFRenderer.java | 25 +-- .../xhtmlrenderer/pdf/CheckboxFormField.java | 19 +-- .../org/xhtmlrenderer/pdf/ITextUserAgent.java | 10 +- .../xhtmlrenderer/pdf/SelectFormField.java | 9 +- .../org/xhtmlrenderer/pdf/TextFormField.java | 4 +- .../java/org/xhtmlrenderer/pdf/ToPDF.java | 24 +-- .../demo/browser/swt/BrowserUserAgent.java | 13 +- .../demo/browser/swt/DemosNavigation.java | 21 +-- .../org/xhtmlrenderer/swt/NaiveUserAgent.java | 83 +++------- www/faq.html | 26 +--- www/faq.xil | 26 +--- 40 files changed, 359 insertions(+), 710 deletions(-) diff --git a/flying-saucer-core/src/main/java/org/xhtmlrenderer/context/StylesheetFactoryImpl.java b/flying-saucer-core/src/main/java/org/xhtmlrenderer/context/StylesheetFactoryImpl.java index 3f1f15cfc..47c53c528 100644 --- a/flying-saucer-core/src/main/java/org/xhtmlrenderer/context/StylesheetFactoryImpl.java +++ b/flying-saucer-core/src/main/java/org/xhtmlrenderer/context/StylesheetFactoryImpl.java @@ -27,6 +27,7 @@ import org.xhtmlrenderer.extend.UserAgentCallback; import org.xhtmlrenderer.resource.CSSResource; import org.xhtmlrenderer.util.Configuration; +import org.xhtmlrenderer.util.IOUtil; import org.xhtmlrenderer.util.XRLog; import org.xml.sax.InputSource; @@ -91,11 +92,7 @@ private Stylesheet parse(StylesheetInfo info) { // Shouldn't happen throw new RuntimeException(e.getMessage(), e); } finally { - try { - is.close(); - } catch (IOException e) { - // ignore - } + IOUtil.close(is); } } diff --git a/flying-saucer-core/src/main/java/org/xhtmlrenderer/layout/BoxBuilder.java b/flying-saucer-core/src/main/java/org/xhtmlrenderer/layout/BoxBuilder.java index 3571f0f38..9ab5d3218 100644 --- a/flying-saucer-core/src/main/java/org/xhtmlrenderer/layout/BoxBuilder.java +++ b/flying-saucer-core/src/main/java/org/xhtmlrenderer/layout/BoxBuilder.java @@ -280,7 +280,7 @@ private static TableCellBox createMarginBox( stripAllWhitespace(children); } - if (children.size() == 0 && style.isAutoWidth() && ! alwaysCreate) { + if (children.isEmpty() && style.isAutoWidth() && ! alwaysCreate) { return null; } @@ -291,14 +291,14 @@ private static TableCellBox createMarginBox( private static void resolveChildren( LayoutContext c, BlockBox owner, List children, ChildBoxInfo info) { - if (children.size() > 0) { + if (!children.isEmpty()) { if (info.isContainsBlockLevelContent()) { insertAnonymousBlocks( c.getSharedContext(), owner, children, info.isLayoutRunningBlocks()); owner.setChildrenContentType(BlockBox.CONTENT_BLOCK); } else { WhitespaceStripper.stripInlineContent(children); - if (children.size() > 0) { + if (!children.isEmpty()) { owner.setInlineContent(children); owner.setChildrenContentType(BlockBox.CONTENT_INLINE); } else { @@ -339,7 +339,7 @@ private static void resolveChildTableContent( if (matchesTableLevel(target, styleable.getStyle().getIdent(CSSName.DISPLAY))) { childrenForAnonymous.add(styleable); } else { - if (childrenForAnonymous.size() > 0) { + if (!childrenForAnonymous.isEmpty()) { createAnonymousTableContent(c, (BlockBox) childrenForAnonymous.get(0), nextUp, childrenForAnonymous, childrenWithAnonymous); @@ -349,7 +349,7 @@ private static void resolveChildTableContent( } } - if (childrenForAnonymous.size() > 0) { + if (!childrenForAnonymous.isEmpty()) { createAnonymousTableContent(c, (BlockBox) childrenForAnonymous.get(0), nextUp, childrenForAnonymous, childrenWithAnonymous); } @@ -449,7 +449,7 @@ private static void resolveTableContent( IdentValue childDisplay = child.getStyle().getIdent(CSSName.DISPLAY); if (isProperTableNesting(parentDisplay, childDisplay)) { - if (childrenForAnonymous.size() > 0) { + if (!childrenForAnonymous.isEmpty()) { createAnonymousTableContent(c, parent, next, childrenForAnonymous, childrenWithAnonymous); @@ -461,7 +461,7 @@ private static void resolveTableContent( } } - if (childrenForAnonymous.size() > 0) { + if (!childrenForAnonymous.isEmpty()) { createAnonymousTableContent(c, parent, next, childrenForAnonymous, childrenWithAnonymous); } @@ -558,7 +558,7 @@ private static BlockBox reorderTableContent(LayoutContext c, TableBox table) { table.addChild(footer); } - if (topCaptions.size() == 0 && bottomCaptions.size() == 0) { + if (topCaptions.isEmpty() && bottomCaptions.isEmpty()) { return table; } else { // If we have a floated table with a caption, we need to float the @@ -680,7 +680,7 @@ private static boolean isAttrFunction(FSFunction function) { public static boolean isElementFunction(FSFunction function) { if (function.getName().equals("element")) { List params = function.getParameters(); - if (params.size() < 1 || params.size() > 2) { + if (params.isEmpty() || params.size() > 2) { return false; } PropertyValue value1 = params.get(0); @@ -699,7 +699,7 @@ public static boolean isElementFunction(FSFunction function) { private static CounterFunction makeCounterFunction(FSFunction function, LayoutContext c, CalculatedStyle style) { if (function.getName().equals("counter")) { List params = function.getParameters(); - if (params.size() < 1 || params.size() > 2) { + if (params.isEmpty() || params.size() > 2) { return null; } @@ -1259,7 +1259,7 @@ private static void insertAnonymousBlocks( } } } else { - if (inline.size() > 0) { + if (!inline.isEmpty()) { createAnonymousBlock(parent, inline, savedParents); inline = new ArrayList<>(); savedParents = new ArrayList<>(parents); @@ -1273,11 +1273,11 @@ private static void insertAnonymousBlocks( private static void createAnonymousBlock(Box parent, List inline, List savedParents) { WhitespaceStripper.stripInlineContent(inline); - if (inline.size() > 0) { + if (!inline.isEmpty()) { AnonymousBlockBox anon = new AnonymousBlockBox(parent.getElement()); anon.setStyle(parent.getStyle().createAnonymousStyle(IdentValue.BLOCK)); anon.setAnonymous(true); - if (savedParents != null && savedParents.size() > 0) { + if (savedParents != null && !savedParents.isEmpty()) { anon.setOpenInlineBoxes(savedParents); } parent.addChild(anon); diff --git a/flying-saucer-core/src/main/java/org/xhtmlrenderer/simple/ImageRenderer.java b/flying-saucer-core/src/main/java/org/xhtmlrenderer/simple/ImageRenderer.java index c27541471..1b80d51b6 100644 --- a/flying-saucer-core/src/main/java/org/xhtmlrenderer/simple/ImageRenderer.java +++ b/flying-saucer-core/src/main/java/org/xhtmlrenderer/simple/ImageRenderer.java @@ -21,6 +21,7 @@ import org.xhtmlrenderer.swing.Java2DRenderer; import org.xhtmlrenderer.util.FSImageWriter; +import org.xhtmlrenderer.util.IOUtil; import java.awt.image.BufferedImage; import java.io.BufferedOutputStream; @@ -138,13 +139,7 @@ public static BufferedImage renderImageToOutput(String url, FSImageWriter fsw, S return image; } finally { - if (os != null) { - try { - os.close(); - } catch (IOException e) { - // ignore - } - } + IOUtil.close(os); } } diff --git a/flying-saucer-core/src/main/java/org/xhtmlrenderer/simple/extend/XhtmlCssOnlyNamespaceHandler.java b/flying-saucer-core/src/main/java/org/xhtmlrenderer/simple/extend/XhtmlCssOnlyNamespaceHandler.java index 65826b026..c044cff7e 100644 --- a/flying-saucer-core/src/main/java/org/xhtmlrenderer/simple/extend/XhtmlCssOnlyNamespaceHandler.java +++ b/flying-saucer-core/src/main/java/org/xhtmlrenderer/simple/extend/XhtmlCssOnlyNamespaceHandler.java @@ -378,30 +378,16 @@ public StylesheetInfo getDefaultStylesheet(StylesheetFactory factory) { info.setMedia("all"); info.setType("text/css"); - InputStream is = null; - try { - is = getDefaultStylesheetStream(); - + try (InputStream is = getDefaultStylesheetStream()) { if (_defaultStylesheetError) { return null; } Stylesheet sheet = factory.parse(new InputStreamReader(is), info); info.setStylesheet(sheet); - - is.close(); - is = null; } catch (IOException e) { _defaultStylesheetError = true; XRLog.exception("Could not parse default stylesheet", e); - } finally { - if (is != null) { - try { - is.close(); - } catch (IOException e) { - // ignore - } - } } _defaultStylesheet = info; diff --git a/flying-saucer-core/src/main/java/org/xhtmlrenderer/swing/BasicPanel.java b/flying-saucer-core/src/main/java/org/xhtmlrenderer/swing/BasicPanel.java index 093d13b06..0b037bad3 100644 --- a/flying-saucer-core/src/main/java/org/xhtmlrenderer/swing/BasicPanel.java +++ b/flying-saucer-core/src/main/java/org/xhtmlrenderer/swing/BasicPanel.java @@ -423,13 +423,11 @@ public void reloadDocument(Document doc) { } public URL getURL() { - URL base = null; try { - base = new URL(getSharedContext().getUac().getBaseURL()); + return new URL(getSharedContext().getUac().getBaseURL()); } catch (MalformedURLException e) { - e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. + throw new RuntimeException(e); } - return base; } public Document getDocument() { diff --git a/flying-saucer-core/src/main/java/org/xhtmlrenderer/swing/DelegatingUserAgent.java b/flying-saucer-core/src/main/java/org/xhtmlrenderer/swing/DelegatingUserAgent.java index aac58ab7f..3ab3eebad 100644 --- a/flying-saucer-core/src/main/java/org/xhtmlrenderer/swing/DelegatingUserAgent.java +++ b/flying-saucer-core/src/main/java/org/xhtmlrenderer/swing/DelegatingUserAgent.java @@ -31,7 +31,6 @@ import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; import java.io.BufferedInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; @@ -126,15 +125,12 @@ public ImageResource getImageResource(String uri) { */ public XMLResource getXMLResource(String uri) { String ruri = _uriResolver.resolve(uri); - StreamResource sr = new StreamResource(ruri); - try { + try (StreamResource sr = new StreamResource(ruri)) { sr.connect(); BufferedInputStream bis = sr.bufferedStream(); return XMLResource.load(bis); } catch (IOException e) { return null; - } finally { - sr.close(); } } @@ -142,22 +138,11 @@ public XMLResource getXMLResource(String uri) { @CheckReturnValue public byte[] getBinaryResource(String uri) { String ruri = _uriResolver.resolve(uri); - StreamResource sr = new StreamResource(ruri); - try { + try (StreamResource sr = new StreamResource(ruri)) { sr.connect(); - BufferedInputStream bis = sr.bufferedStream(); - ByteArrayOutputStream result = new ByteArrayOutputStream(sr.hasStreamLength() ? sr.streamLength() : 4 * 1024); - byte[] buf = new byte[10240]; - int i; - while ((i = bis.read(buf)) != -1) { - result.write(buf, 0, i); - } - - return result.toByteArray(); + return IOUtil.readBytes(sr.bufferedStream()); } catch (IOException e) { return null; - } finally { - sr.close(); } } diff --git a/flying-saucer-core/src/main/java/org/xhtmlrenderer/swing/NaiveUserAgent.java b/flying-saucer-core/src/main/java/org/xhtmlrenderer/swing/NaiveUserAgent.java index 90dff6a5b..8770f19e5 100644 --- a/flying-saucer-core/src/main/java/org/xhtmlrenderer/swing/NaiveUserAgent.java +++ b/flying-saucer-core/src/main/java/org/xhtmlrenderer/swing/NaiveUserAgent.java @@ -25,6 +25,7 @@ import org.xhtmlrenderer.resource.ImageResource; import org.xhtmlrenderer.resource.XMLResource; import org.xhtmlrenderer.util.FontUtil; +import org.xhtmlrenderer.util.IOUtil; import org.xhtmlrenderer.util.ImageUtil; import org.xhtmlrenderer.util.XRLog; @@ -34,7 +35,6 @@ import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; @@ -256,11 +256,7 @@ public ImageResource getImageResource(String uri) { } catch (IOException e) { XRLog.exception("Can't read image file; unexpected problem for URI '" + uri + "'", e); } finally { - try { - is.close(); - } catch (IOException e) { - // ignore - } + IOUtil.close(is); } } } @@ -293,49 +289,21 @@ protected ImageResource createImageResource(String uri, @Nullable Image img) { */ @Override public XMLResource getXMLResource(String uri) { - InputStream inputStream = resolveAndOpenStream(uri); - XMLResource xmlResource; - try { - xmlResource = XMLResource.load(inputStream); - } finally { - if (inputStream != null) { - try { - inputStream.close(); - } catch (IOException e) { - // swallow - } - } + try (InputStream inputStream = resolveAndOpenStream(uri)) { + return XMLResource.load(inputStream); + } catch (IOException ignore) { + return null; } - return xmlResource; } @Override @Nullable @CheckReturnValue public byte[] getBinaryResource(String uri) { - InputStream is = resolveAndOpenStream(uri); - if (is==null) return null; - try { - ByteArrayOutputStream result = new ByteArrayOutputStream(); - byte[] buf = new byte[10240]; - int i; - while ((i = is.read(buf)) != -1) { - result.write(buf, 0, i); - } - is.close(); - is = null; - - return result.toByteArray(); + try (InputStream is = resolveAndOpenStream(uri)) { + return is == null ? null : IOUtil.readBytes(is); } catch (IOException e) { return null; - } finally { - if (is != null) { - try { - is.close(); - } catch (IOException e) { - // ignore - } - } } } diff --git a/flying-saucer-core/src/main/java/org/xhtmlrenderer/swing/UriResolver.java b/flying-saucer-core/src/main/java/org/xhtmlrenderer/swing/UriResolver.java index 1b4decf93..710c525d6 100644 --- a/flying-saucer-core/src/main/java/org/xhtmlrenderer/swing/UriResolver.java +++ b/flying-saucer-core/src/main/java/org/xhtmlrenderer/swing/UriResolver.java @@ -32,9 +32,8 @@ public String resolveUri(final String uri) { } catch (MalformedURLException e) { try { setBaseUri(new File(".").toURI().toURL().toExternalForm()); - } catch (Exception e1) { - XRLog.exception("The default NaiveUserAgent doesn't know how to resolve the base URL for " + uri); - return null; + } catch (MalformedURLException e1) { + throw new IllegalStateException("The default NaiveUserAgent doesn't know how to resolve the base URL for " + uri, e1); } } } diff --git a/flying-saucer-core/src/main/java/org/xhtmlrenderer/util/Configuration.java b/flying-saucer-core/src/main/java/org/xhtmlrenderer/util/Configuration.java index 7b9a192ac..13378a696 100644 --- a/flying-saucer-core/src/main/java/org/xhtmlrenderer/util/Configuration.java +++ b/flying-saucer-core/src/main/java/org/xhtmlrenderer/util/Configuration.java @@ -306,24 +306,18 @@ private void loadOverrideProperties(String uri) { return; } } else { - InputStream in = null; try { URL url = new URL(uri); - in = new BufferedInputStream(url.openStream()); - info("Found config override URI " + uri); - temp.load(in); + try (InputStream in = new BufferedInputStream(url.openStream())) { + info("Found config override URI " + uri); + temp.load(in); + } } catch (MalformedURLException e) { warning("URI for override properties is malformed, skipping: " + uri); return; } catch (IOException e) { warning("Overridden properties could not be loaded from URI: " + uri, e); return; - } finally { - if (in != null ) try { - in.close(); - } catch (IOException e) { - // swallow - } } } @@ -552,7 +546,7 @@ public static int valueAsInt(String key, int defaultVal) { * * @param key Name of the property * @param defaultVal Default value to return - * @returnValue assigned to the key, as a character + * @return Value assigned to the key, as a character */ public static char valueAsChar(String key, char defaultVal) { String val = valueFor(key); diff --git a/flying-saucer-core/src/main/java/org/xhtmlrenderer/util/FSImageWriter.java b/flying-saucer-core/src/main/java/org/xhtmlrenderer/util/FSImageWriter.java index 5c9a09f88..b563f72e7 100644 --- a/flying-saucer-core/src/main/java/org/xhtmlrenderer/util/FSImageWriter.java +++ b/flying-saucer-core/src/main/java/org/xhtmlrenderer/util/FSImageWriter.java @@ -128,7 +128,6 @@ public void write(BufferedImage image, String filePath) throws IOException { try (OutputStream fos = new BufferedOutputStream(newOutputStream(file.toPath()))) { write(image, fos); } - // ignore } /** diff --git a/flying-saucer-core/src/main/java/org/xhtmlrenderer/util/IOUtil.java b/flying-saucer-core/src/main/java/org/xhtmlrenderer/util/IOUtil.java index d0f7f463e..6968ac4a6 100644 --- a/flying-saucer-core/src/main/java/org/xhtmlrenderer/util/IOUtil.java +++ b/flying-saucer-core/src/main/java/org/xhtmlrenderer/util/IOUtil.java @@ -1,56 +1,56 @@ package org.xhtmlrenderer.util; -import java.io.*; +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import javax.annotation.ParametersAreNonnullByDefault; +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.ByteArrayOutputStream; +import java.io.Closeable; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; import java.net.URL; import java.net.URLConnection; +import java.util.logging.Level; + +import static java.nio.file.Files.newInputStream; +import static java.nio.file.Files.newOutputStream; /** * @author patrick */ +@ParametersAreNonnullByDefault public class IOUtil { - public static File copyFile(File page, File outputDir) throws IOException { - InputStream in = null; - OutputStream out = null; - try { - in = new BufferedInputStream(new FileInputStream(page)); - File outputFile; - outputFile = new File(outputDir, page.getName()); - out = new BufferedOutputStream(new FileOutputStream(outputFile)); - - // Transfer bytes from in to out - byte[] buf = new byte[1024]; - int len; - while ((len = in.read(buf)) > 0) { - out.write(buf, 0, len); + public static void copyFile(File page, File outputDir) throws IOException { + File outputFile = new File(outputDir, page.getName()); + + try (OutputStream out = new BufferedOutputStream(newOutputStream(outputFile.toPath()))) { + try (InputStream in = new BufferedInputStream(newInputStream(page.toPath()))) { + copyBytes(in, out); } - in.close(); out.flush(); - out.close(); - return outputFile; - } finally { - if (in != null) { - try { - in.close(); - } catch (IOException e) { - // swallow - } - } - if (out != null) { - try { - out.close(); - } catch (IOException e) { - // swallow - } - } + } + } + + private static void copyBytes(InputStream in, OutputStream out) throws IOException { + byte[] buf = new byte[1024]; + int len; + while ((len = in.read(buf)) >= 0) { + out.write(buf, 0, len); } } public static void deleteAllFiles(final File dir) throws IOException { File[] files = dir.listFiles(); - for (int i = 0; i < files.length; i++) { - File file = files[i]; - if (!file.delete()) { - throw new IOException("Cleanup directory " + dir + ", can't delete file " + file); + if (files != null) { + for (File file : files) { + if (!file.delete()) { + throw new IOException("Cleanup directory " + dir + ", can't delete file " + file); + } } } } @@ -61,7 +61,6 @@ public static void deleteAllFiles(final File dir) throws IOException { * buffer the stream. */ public static InputStream openStreamAtUrl(String uri) { - InputStream is = null; try { final URLConnection uc = new URL(uri).openConnection(); @@ -82,7 +81,7 @@ public static InputStream openStreamAtUrl(String uri) { uc.connect(); - is = uc.getInputStream(); + return uc.getInputStream(); } catch (java.net.MalformedURLException e) { XRLog.exception("bad URL given: " + uri, e); } catch (FileNotFoundException e) { @@ -91,7 +90,55 @@ public static InputStream openStreamAtUrl(String uri) { XRLog.exception("IO problem for " + uri, e); } - return is; + return null; + } + + /** + * Gets a Reader for the resource identified + * + * @return The stylesheet value + */ + @Nullable + @CheckReturnValue + public static InputStream getInputStream(String uri) { + try { + return new URL(uri).openStream(); + } catch (java.net.MalformedURLException e) { + XRLog.exception("bad URL given: " + uri, e); + } catch (java.io.FileNotFoundException e) { + XRLog.exception("item at URI " + uri + " not found"); + } catch (java.io.IOException e) { + XRLog.exception("IO problem for " + uri, e); + } + return null; + } + + @Nullable + @CheckReturnValue + public static byte[] readBytes(String uri) { + try (InputStream is = getInputStream(uri)) { + if (is == null) return null; + return readBytes(is); + } catch (IOException e) { + XRLog.load(Level.WARNING, "Unable to read " + uri, e); + return null; + } + } + @Nonnull + @CheckReturnValue + public static byte[] readBytes(InputStream is) throws IOException { + ByteArrayOutputStream result = new ByteArrayOutputStream(); + copyBytes(is, result); + return result.toByteArray(); + } + + public static void close(@Nullable Closeable in) { + if (in != null) { + try { + in.close(); + } catch (IOException ignore) { + } + } } } diff --git a/flying-saucer-core/src/main/java/org/xhtmlrenderer/util/StreamResource.java b/flying-saucer-core/src/main/java/org/xhtmlrenderer/util/StreamResource.java index 2320b66c4..25a3823ca 100644 --- a/flying-saucer-core/src/main/java/org/xhtmlrenderer/util/StreamResource.java +++ b/flying-saucer-core/src/main/java/org/xhtmlrenderer/util/StreamResource.java @@ -11,7 +11,7 @@ * User: pdoubleya * Date: May 15, 2009 */ -public class StreamResource { +public class StreamResource implements AutoCloseable { private final String _uri; private URLConnection _conn; private int _slen; @@ -64,13 +64,8 @@ public BufferedInputStream bufferedStream() throws IOException { return new BufferedInputStream(_inputStream); } + @Override public void close() { - if (_inputStream != null) { - try { - _inputStream.close(); - } catch (IOException e) { - // swallow - } - } + IOUtil.close(_inputStream); } } diff --git a/flying-saucer-core/src/main/java/org/xhtmlrenderer/util/Zipper.java b/flying-saucer-core/src/main/java/org/xhtmlrenderer/util/Zipper.java index 2e6d65307..5fef9f18f 100644 --- a/flying-saucer-core/src/main/java/org/xhtmlrenderer/util/Zipper.java +++ b/flying-saucer-core/src/main/java/org/xhtmlrenderer/util/Zipper.java @@ -21,12 +21,13 @@ import java.io.BufferedInputStream; import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; +import static java.nio.file.Files.newInputStream; +import static java.nio.file.Files.newOutputStream; + /** * Create a ZIP-format file from the contents of some directory. All files * in the directory are included. To use, instantiate with a reference to @@ -48,45 +49,39 @@ public Zipper(File sourceDir, File outputFile) { } } - public static void main(String[] args) { + public static void main(String[] args) throws IOException { File sourceDir = getSourceDir(args); File outputFile = new File(System.getProperty("user.home") + File.separator + sourceDir.getName() + ".zip"); - try { - new Zipper(sourceDir, outputFile).zipDirectory(); - } catch (IOException e) { - e.printStackTrace(); - } + new Zipper(sourceDir, outputFile).zipDirectory(); System.out.println("Created zip file " + outputFile.getPath()); } public File zipDirectory() throws IOException { - ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outputFile)); - recurseAndZip(sourceDir, zos); - zos.close(); - return outputFile; + try (ZipOutputStream zos = new ZipOutputStream(newOutputStream(outputFile.toPath()))) { + recurseAndZip(sourceDir, zos); + return outputFile; + } } private static void recurseAndZip(File file, ZipOutputStream zos) throws IOException { if (file.isDirectory()) { File[] files = file.listFiles(); if (files != null) { - for (int i = 0; i < files.length; i++) { - File file1 = files[i]; - recurseAndZip(file1, zos); + for (File f : files) { + recurseAndZip(f, zos); } } } else { byte[] buf = new byte[1024]; int len; ZipEntry entry = new ZipEntry(file.getName()); - FileInputStream fis = new FileInputStream(file); - BufferedInputStream bis = new BufferedInputStream(fis); - zos.putNextEntry(entry); - while ((len = bis.read(buf)) >= 0) { - zos.write(buf, 0, len); + try (BufferedInputStream bis = new BufferedInputStream(newInputStream(file.toPath()))) { + zos.putNextEntry(entry); + while ((len = bis.read(buf)) >= 0) { + zos.write(buf, 0, len); + } + zos.closeEntry(); } - bis.close(); - zos.closeEntry(); } } diff --git a/flying-saucer-core/src/test/java/eeze/Eeze.java b/flying-saucer-core/src/test/java/eeze/Eeze.java index 3a489cfd5..f8947b168 100644 --- a/flying-saucer-core/src/test/java/eeze/Eeze.java +++ b/flying-saucer-core/src/test/java/eeze/Eeze.java @@ -38,14 +38,16 @@ import java.io.File; import java.io.FileFilter; import java.io.IOException; +import java.net.MalformedURLException; import java.net.URL; -import java.util.Arrays; import java.util.Iterator; import java.util.List; import static java.awt.Frame.NORMAL; import static java.awt.event.InputEvent.ALT_MASK; import static java.awt.event.InputEvent.CTRL_MASK; +import static java.util.Arrays.asList; +import static java.util.Collections.emptyList; /** @@ -93,17 +95,15 @@ private void run() { html.getSharedContext().setFontMapping("Ahem", Font.createFont(Font.TRUETYPE_FONT, fontFile.toURL().openStream())); } - } catch (FontFormatException e) { - e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. - } catch (IOException e) { - e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. + } catch (FontFormatException | IOException e) { + throw new RuntimeException(e); } }); testFiles = buildFileList(); try { SwingUtilities.invokeLater(this::showHelpPage); } catch (Exception ex) { - ex.printStackTrace(); + throw new RuntimeException(ex); } } @@ -126,76 +126,69 @@ private void parseArgs(String[] args) { } private List buildFileList() { - List fileList = null; try { File[] list = directory.listFiles(HTML_FILE_FILTER); - fileList = Arrays.asList(list); + return list == null ? emptyList() : asList(list); } catch (Exception ex) { - ex.printStackTrace(); + throw new RuntimeException(ex); } - return fileList; } private void buildFrame() { - try { - eezeFrame = new JFrame("FS Eeze"); - final JFrame frame = eezeFrame; - frame.setExtendedState(NORMAL); - frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - - SwingUtilities.invokeLater(() -> { - html = new XHTMLPanel(); - scroll = new FSScrollPane(html); - frame.getContentPane().add(scroll); - frame.pack(); - frame.setSize(1024, 768); - frame.setVisible(true); - - frame.addComponentListener(new ComponentAdapter() { - @Override - public void componentResized(ComponentEvent e) { - html.relayout(); - } - }); + eezeFrame = new JFrame("FS Eeze"); + final JFrame frame = eezeFrame; + frame.setExtendedState(NORMAL); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - nextDemoAction = new NextDemoAction(); - reloadPageAction = new ReloadPageAction(); - chooseDemoAction = new ChooseDemoAction(); - growAction = new GrowAction(); - shrinkAction = new ShrinkAction(); - - increase_font = new FontSizeAction(FontSizeAction.INCREMENT, KeyStroke.getKeyStroke(KeyEvent.VK_I, CTRL_MASK)); - reset_font = new FontSizeAction(FontSizeAction.RESET, KeyStroke.getKeyStroke(KeyEvent.VK_0, CTRL_MASK)); - decrease_font = new FontSizeAction(FontSizeAction.DECREMENT, KeyStroke.getKeyStroke(KeyEvent.VK_D, CTRL_MASK)); - - reloadFileList = new ReloadFileListAction(); - showGrid = new ShowGridAction(); - showHelp = new ShowHelpAction(); - saveAsImg = new SaveAsImageAction(); - overlayImage = new CompareImageAction(); - - frame.setJMenuBar(new JMenuBar()); - JMenu doMenu = new JMenu("Do"); - doMenu.add(reloadPageAction); - doMenu.add(nextDemoAction); - doMenu.add(chooseDemoAction); - doMenu.add(growAction); - doMenu.add(shrinkAction); - doMenu.add(increase_font); - doMenu.add(reset_font); - doMenu.add(decrease_font); - doMenu.add(showGrid); - doMenu.add(saveAsImg); - doMenu.add(overlayImage); - doMenu.add(reloadFileList); - doMenu.add(showHelp); - doMenu.setVisible(false); - frame.getJMenuBar().add(doMenu); + SwingUtilities.invokeLater(() -> { + html = new XHTMLPanel(); + scroll = new FSScrollPane(html); + frame.getContentPane().add(scroll); + frame.pack(); + frame.setSize(1024, 768); + frame.setVisible(true); + + frame.addComponentListener(new ComponentAdapter() { + @Override + public void componentResized(ComponentEvent e) { + html.relayout(); + } }); - } catch (Exception ex) { - ex.printStackTrace(); - } + nextDemoAction = new NextDemoAction(); + reloadPageAction = new ReloadPageAction(); + chooseDemoAction = new ChooseDemoAction(); + growAction = new GrowAction(); + shrinkAction = new ShrinkAction(); + + increase_font = new FontSizeAction(FontSizeAction.INCREMENT, KeyStroke.getKeyStroke(KeyEvent.VK_I, CTRL_MASK)); + reset_font = new FontSizeAction(FontSizeAction.RESET, KeyStroke.getKeyStroke(KeyEvent.VK_0, CTRL_MASK)); + decrease_font = new FontSizeAction(FontSizeAction.DECREMENT, KeyStroke.getKeyStroke(KeyEvent.VK_D, CTRL_MASK)); + + reloadFileList = new ReloadFileListAction(); + showGrid = new ShowGridAction(); + showHelp = new ShowHelpAction(); + saveAsImg = new SaveAsImageAction(); + overlayImage = new CompareImageAction(); + + frame.setJMenuBar(new JMenuBar()); + JMenu doMenu = new JMenu("Do"); + doMenu.add(reloadPageAction); + doMenu.add(nextDemoAction); + doMenu.add(chooseDemoAction); + doMenu.add(growAction); + doMenu.add(shrinkAction); + doMenu.add(increase_font); + doMenu.add(reset_font); + doMenu.add(decrease_font); + doMenu.add(showGrid); + doMenu.add(saveAsImg); + doMenu.add(overlayImage); + doMenu.add(reloadFileList); + doMenu.add(showHelp); + doMenu.setVisible(false); + frame.getJMenuBar().add(doMenu); + }); } private void switchPage(File file, boolean reload) { @@ -214,8 +207,8 @@ private void switchPage(File file, boolean reload) { imagePanel.imageWasLoaded(); imagePanel.repaint(); }); - } catch (Exception ex) { - ex.printStackTrace(); + } catch (MalformedURLException ex) { + throw new RuntimeException(ex); } finally { eezeFrame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } @@ -227,8 +220,8 @@ private void showHelpPage() { URL help = eezeHelp(); html.setDocument(help.openStream(), help.toString()); changeTitle(html.getDocumentTitle()); - } catch (Exception ex) { - ex.printStackTrace(); + } catch (IOException ex) { + throw new RuntimeException(ex); } finally { eezeFrame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } @@ -331,7 +324,7 @@ private Image loadImageForPage() { "Save As Image", JOptionPane.ERROR_MESSAGE ); - e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. + throw new RuntimeException(e1); } return img; } @@ -590,11 +583,7 @@ public void actionPerformed(ActionEvent e) { nextPage = iter.next(); } - try { - switchPage(nextPage, false); - } catch (Exception ex) { - ex.printStackTrace(); - } + switchPage(nextPage, false); } } @@ -652,7 +641,7 @@ public void actionPerformed(ActionEvent e) { "Save As Image", JOptionPane.ERROR_MESSAGE ); - e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. + e1.printStackTrace(); } } } diff --git a/flying-saucer-examples/src/main/java/FontScaleJPanelRender.java b/flying-saucer-examples/src/main/java/FontScaleJPanelRender.java index aa01d7089..402be7b65 100644 --- a/flying-saucer-examples/src/main/java/FontScaleJPanelRender.java +++ b/flying-saucer-examples/src/main/java/FontScaleJPanelRender.java @@ -23,6 +23,7 @@ import javax.swing.*; import java.awt.*; import java.io.File; +import java.net.MalformedURLException; /** * This example shows rendering a page where the font size can be adjusted dynamically once the page is loaded using @@ -55,8 +56,8 @@ private void run(String[] args) { // are a variety of overloads for setDocument(). try { panel.setDocument(new File(fileName)); - } catch (Exception e) { - e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. + } catch (MalformedURLException e) { + throw new RuntimeException(e); } // Put our panel in a scrolling pane. You can use diff --git a/flying-saucer-examples/src/main/java/JPanelRender.java b/flying-saucer-examples/src/main/java/JPanelRender.java index 5035aaf60..3a0d2c240 100644 --- a/flying-saucer-examples/src/main/java/JPanelRender.java +++ b/flying-saucer-examples/src/main/java/JPanelRender.java @@ -22,6 +22,7 @@ import javax.swing.*; import java.io.File; +import java.net.MalformedURLException; /** * This example shows the most basic use of Flying Saucer, to @@ -53,8 +54,8 @@ private void run(String[] args) { // are a variety of overloads for setDocument(). try { panel.setDocument(new File(fileName)); - } catch (Exception e) { - e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. + } catch (MalformedURLException e) { + throw new RuntimeException(e); } // Put our panel in a scrolling pane. You can use diff --git a/flying-saucer-examples/src/main/java/PDFRender.java b/flying-saucer-examples/src/main/java/PDFRender.java index f541218ee..ef99cddc1 100644 --- a/flying-saucer-examples/src/main/java/PDFRender.java +++ b/flying-saucer-examples/src/main/java/PDFRender.java @@ -26,10 +26,12 @@ import org.xml.sax.InputSource; import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.nio.file.Paths; + +import static java.nio.file.Files.newOutputStream; public class PDFRender { public static void main(String[] args) throws IOException, DocumentException { @@ -48,20 +50,8 @@ public static void main(String[] args) throws IOException, DocumentException { createPDF(url, args[1]); } - public static void createPDF(String url, String pdf) - throws IOException, DocumentException { - OutputStream os = null; - try { - os = new FileOutputStream(pdf); - - /* standard approach - ITextRenderer renderer = new ITextRenderer(); - - renderer.setDocument(url); - renderer.layout(); - renderer.createPDF(os); - */ - + public static void createPDF(String url, String pdf) throws IOException, DocumentException { + try (OutputStream os = newOutputStream(Paths.get(pdf))) { ITextRenderer renderer = new ITextRenderer(); ResourceLoaderUserAgent callback = new ResourceLoaderUserAgent(renderer.getOutputDevice()); callback.setSharedContext(renderer.getSharedContext()); @@ -72,22 +62,10 @@ public static void createPDF(String url, String pdf) renderer.setDocument(doc, url); renderer.layout(); renderer.createPDF(os); - - os.close(); - os = null; - } finally { - if (os != null) { - try { - os.close(); - } catch (IOException e) { - // ignore - } - } } } - private static class ResourceLoaderUserAgent extends ITextUserAgent - { + private static class ResourceLoaderUserAgent extends ITextUserAgent { private ResourceLoaderUserAgent(ITextOutputDevice outputDevice) { super(outputDevice); } diff --git a/flying-saucer-examples/src/main/java/PDFRenderToMultiplePages.java b/flying-saucer-examples/src/main/java/PDFRenderToMultiplePages.java index 735fde95e..842e76518 100644 --- a/flying-saucer-examples/src/main/java/PDFRenderToMultiplePages.java +++ b/flying-saucer-examples/src/main/java/PDFRenderToMultiplePages.java @@ -22,28 +22,26 @@ import org.xhtmlrenderer.pdf.ITextRenderer; import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; import java.io.OutputStream; +import static java.nio.file.Files.newOutputStream; + /** * This sample shows how to create a single PDF document from multiple input documents. */ public class PDFRenderToMultiplePages { public static void main(String[] args) throws Exception { - OutputStream os = null; - try { - // create some simple, fake documents; nothing special about these, anything that Flying Saucer - // can otherwise render - final String[] inputs = new String[]{ - newPageHtml(1, "red"), - newPageHtml(2, "blue"), - newPageHtml(3, "green") - }; + // create some simple, fake documents; nothing special about these, anything that Flying Saucer + // can otherwise render + final String[] inputs = new String[]{ + newPageHtml(1, "red"), + newPageHtml(2, "blue"), + newPageHtml(3, "green") + }; - final File outputFile = File.createTempFile("FlyingSacuer.PDFRenderToMultiplePages", ".pdf"); - os = new FileOutputStream(outputFile); + final File outputFile = File.createTempFile("FlyingSaucer.PDFRenderToMultiplePages", ".pdf"); + try (OutputStream os = newOutputStream(outputFile.toPath())) { ITextRenderer renderer = new ITextRenderer(); @@ -65,13 +63,6 @@ public static void main(String[] args) throws Exception { System.out.println("Sample file with " + inputs.length + " documents rendered as PDF to " + outputFile); } - finally { - if (os != null) { - try { - os.close(); - } catch (IOException e) { /*ignore*/ } - } - } } private static String newPageHtml(int pageNo, String color) { diff --git a/flying-saucer-examples/src/main/java/ReplaceRender.java b/flying-saucer-examples/src/main/java/ReplaceRender.java index 456d373df..43b44ad4d 100644 --- a/flying-saucer-examples/src/main/java/ReplaceRender.java +++ b/flying-saucer-examples/src/main/java/ReplaceRender.java @@ -26,6 +26,7 @@ import java.awt.*; import java.awt.event.ActionEvent; import java.io.File; +import java.net.MalformedURLException; /** * This example shows the most basic use of Flying Saucer, to @@ -57,8 +58,8 @@ private void run(String[] args) { // are a variety of overloads for setDocument(). try { panel.setDocument(new File(fileName)); - } catch (Exception e) { - e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. + } catch (MalformedURLException e) { + throw new RuntimeException(e); } // Put our panel in a scrolling pane. You can use diff --git a/flying-saucer-examples/src/main/java/org/xhtmlrenderer/demo/aboutbox/DemoUserAgent.java b/flying-saucer-examples/src/main/java/org/xhtmlrenderer/demo/aboutbox/DemoUserAgent.java index a1a0a0829..2b517daec 100644 --- a/flying-saucer-examples/src/main/java/org/xhtmlrenderer/demo/aboutbox/DemoUserAgent.java +++ b/flying-saucer-examples/src/main/java/org/xhtmlrenderer/demo/aboutbox/DemoUserAgent.java @@ -24,6 +24,7 @@ import org.xhtmlrenderer.resource.ImageResource; import org.xhtmlrenderer.resource.XMLResource; import org.xhtmlrenderer.swing.AWTFSImage; +import org.xhtmlrenderer.util.IOUtil; import org.xhtmlrenderer.util.Uu; import org.xhtmlrenderer.util.XRLog; @@ -32,7 +33,6 @@ import javax.annotation.ParametersAreNonnullByDefault; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -120,32 +120,7 @@ public ImageResource getImageResource(String uri) { @Nullable @CheckReturnValue public byte[] getBinaryResource(String uri) { - InputStream is = null; - try { - URL url = new URL(uri); - URLConnection conn = url.openConnection(); - is = conn.getInputStream(); - ByteArrayOutputStream result = new ByteArrayOutputStream(); - byte[] buf = new byte[10240]; - int i; - while ( (i = is.read(buf)) != -1) { - result.write(buf, 0, i); - } - is.close(); - is = null; - - return result.toByteArray(); - } catch (IOException e) { - return null; - } finally { - if (is != null) { - try { - is.close(); - } catch (IOException e) { - // ignore - } - } - } + return IOUtil.readBytes(uri); } @Override @@ -171,11 +146,7 @@ public XMLResource getXMLResource(String uri) { } catch (IOException e) { XRLog.exception("IO problem for " + uri, e); } finally { - if ( inputStream != null ) try { - inputStream.close(); - } catch (IOException e) { - // swallow - } + IOUtil.close(inputStream); } if (xr == null) { String notFound = "

Document not found

"; diff --git a/flying-saucer-examples/src/main/java/org/xhtmlrenderer/demo/browser/BrowserMenuBar.java b/flying-saucer-examples/src/main/java/org/xhtmlrenderer/demo/browser/BrowserMenuBar.java index 2b57330d8..5d7a3cd31 100755 --- a/flying-saucer-examples/src/main/java/org/xhtmlrenderer/demo/browser/BrowserMenuBar.java +++ b/flying-saucer-examples/src/main/java/org/xhtmlrenderer/demo/browser/BrowserMenuBar.java @@ -207,31 +207,18 @@ public void actionPerformed(ActionEvent evt) { private void populateDemoList() { List demoList = new ArrayList<>(); URL url = BrowserMenuBar.class.getResource("/demos/file-list.txt"); - InputStream is = null; - + if (url != null) { - try { - is = url.openStream(); + try (InputStream is = url.openStream()) { InputStreamReader reader = new InputStreamReader(is); try (LineNumberReader lnr = new LineNumberReader(reader)) { String line; while ((line = lnr.readLine()) != null) { demoList.add(line); } - } catch (IOException e) { - e.printStackTrace(); } - // swallow } catch (IOException e) { - e.printStackTrace(); - } finally { - if (is != null) { - try { - is.close(); - } catch (IOException e) { - // swallow - } - } + throw new RuntimeException(e); } for (String s : demoList) { diff --git a/flying-saucer-examples/src/main/java/org/xhtmlrenderer/demo/browser/BrowserPanel.java b/flying-saucer-examples/src/main/java/org/xhtmlrenderer/demo/browser/BrowserPanel.java index abcf8bbc0..c2c2e3717 100755 --- a/flying-saucer-examples/src/main/java/org/xhtmlrenderer/demo/browser/BrowserPanel.java +++ b/flying-saucer-examples/src/main/java/org/xhtmlrenderer/demo/browser/BrowserPanel.java @@ -42,7 +42,6 @@ import java.awt.*; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; -import java.io.IOException; import java.io.OutputStream; import java.io.StringReader; import java.nio.file.Files; @@ -316,16 +315,10 @@ public void exportToPdf( String path ) XRLog.general(Level.SEVERE, "Could not export PDF.", e); e.printStackTrace(); setStatus( "Error exporting to PDF." ); - } finally { - try { - os.close(); - } catch (IOException e) { - // swallow - } - } + } } catch (Exception e) { e.printStackTrace(); - } + } } } diff --git a/flying-saucer-examples/src/main/java/org/xhtmlrenderer/demo/browser/PanelManager.java b/flying-saucer-examples/src/main/java/org/xhtmlrenderer/demo/browser/PanelManager.java index 5bc23c644..caac90db4 100644 --- a/flying-saucer-examples/src/main/java/org/xhtmlrenderer/demo/browser/PanelManager.java +++ b/flying-saucer-examples/src/main/java/org/xhtmlrenderer/demo/browser/PanelManager.java @@ -126,36 +126,28 @@ public XMLResource getXMLResource(String uri) { } } XMLResource xr = null; - URLConnection uc; - InputStream inputStream = null; try { - uc = new URL(uri).openConnection(); + URLConnection uc = new URL(uri).openConnection(); uc.connect(); String contentType = uc.getContentType(); //Maybe should pop up a choice when content/unknown! if (contentType.equals("text/plain") || contentType.equals("content/unknown")) { - inputStream = uc.getInputStream(); - SAXSource source = new SAXSource(new PlainTextXMLReader(inputStream), new InputSource()); - xr = XMLResource.load(source); + try (InputStream inputStream = uc.getInputStream()) { + SAXSource source = new SAXSource(new PlainTextXMLReader(inputStream), new InputSource()); + xr = XMLResource.load(source); + } } else if (contentType.startsWith("image")) { String doc = ""; xr = XMLResource.load(new StringReader(doc)); } else { - inputStream = uc.getInputStream(); - xr = XMLResource.load(inputStream); + try (InputStream inputStream = uc.getInputStream()) { + xr = XMLResource.load(inputStream); + } } } catch (MalformedURLException e) { XRLog.exception("bad URL given: " + uri, e); } catch (IOException e) { XRLog.exception("IO problem for " + uri, e); - } finally { - if (inputStream != null) { - try { - inputStream.close(); - } catch (IOException e) { - // swallow - } - } } if (xr == null) { diff --git a/flying-saucer-fop/src/main/java/org/xhtmlrenderer/fop/nbsp/NonBreakPointsLoaderImpl.java b/flying-saucer-fop/src/main/java/org/xhtmlrenderer/fop/nbsp/NonBreakPointsLoaderImpl.java index 172cd2a13..02de90882 100644 --- a/flying-saucer-fop/src/main/java/org/xhtmlrenderer/fop/nbsp/NonBreakPointsLoaderImpl.java +++ b/flying-saucer-fop/src/main/java/org/xhtmlrenderer/fop/nbsp/NonBreakPointsLoaderImpl.java @@ -58,9 +58,9 @@ public List loadNBSP(@Nullable String lang) { @CheckReturnValue private List loadForKey(String lang) { String path = "non-break-spaces/" + lang + ".nbsp"; - InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(path); - if (is == null) return null; - try { + + try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(path)) { + if (is == null) return null; BufferedReader r = new BufferedReader(new InputStreamReader(is, UTF_8)); List result = new ArrayList<>(); String line; @@ -71,12 +71,6 @@ private List loadForKey(String lang) { return result; } catch (IOException e) { throw new RuntimeException("Error while loading nbsp file from path " + path, e); - } finally { - try { - is.close(); - } catch (IOException e1) { - // ignore - } } } diff --git a/flying-saucer-pdf-itext5/src/main/java/org/xhtmlrenderer/pdf/CheckboxFormField.java b/flying-saucer-pdf-itext5/src/main/java/org/xhtmlrenderer/pdf/CheckboxFormField.java index 2acf84ca6..6d371e92e 100644 --- a/flying-saucer-pdf-itext5/src/main/java/org/xhtmlrenderer/pdf/CheckboxFormField.java +++ b/flying-saucer-pdf-itext5/src/main/java/org/xhtmlrenderer/pdf/CheckboxFormField.java @@ -19,20 +19,23 @@ */ package org.xhtmlrenderer.pdf; -import java.awt.Color; -import java.io.IOException; - +import com.itextpdf.text.BaseColor; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Rectangle; -import com.itextpdf.text.pdf.*; -import com.itextpdf.text.BaseColor; +import com.itextpdf.text.pdf.BaseField; +import com.itextpdf.text.pdf.PdfBorderDictionary; +import com.itextpdf.text.pdf.PdfContentByte; +import com.itextpdf.text.pdf.PdfFormField; +import com.itextpdf.text.pdf.PdfWriter; +import com.itextpdf.text.pdf.RadioCheckField; import org.w3c.dom.Element; import org.xhtmlrenderer.layout.LayoutContext; import org.xhtmlrenderer.render.BlockBox; import org.xhtmlrenderer.render.RenderingContext; -public class CheckboxFormField extends AbstractFormField -{ +import java.io.IOException; + +public class CheckboxFormField extends AbstractFormField { private static final String FIELD_TYPE = "Checkbox"; public CheckboxFormField(LayoutContext c, BlockBox box, int cssWidth, int cssHeight) @@ -45,8 +48,7 @@ protected String getFieldType() return FIELD_TYPE; } - public void paint(RenderingContext c, ITextOutputDevice outputDevice, BlockBox box) - { + public void paint(RenderingContext c, ITextOutputDevice outputDevice, BlockBox box) { PdfContentByte cb = outputDevice.getCurrentPage(); PdfWriter writer = outputDevice.getWriter(); @@ -66,31 +68,22 @@ public void paint(RenderingContext c, ITextOutputDevice outputDevice, BlockBox b field.setBorderWidth(BaseField.BORDER_WIDTH_THIN); - try - { + try { PdfFormField formField = field.getCheckField(); - if (isReadOnly(elm)) - { + if (isReadOnly(elm)) { formField.setFieldFlags(PdfFormField.FF_READ_ONLY); } writer.addAnnotation(formField); - } catch (IOException ioe) - { + } catch (IOException | DocumentException ioe) { System.out.println(ioe); - } catch (DocumentException de) - { - System.out.println(de); } - } - public int getBaseline() - { + public int getBaseline() { return 0; } - public boolean hasBaseline() - { + public boolean hasBaseline() { return false; } } diff --git a/flying-saucer-pdf-itext5/src/main/java/org/xhtmlrenderer/pdf/ITextUserAgent.java b/flying-saucer-pdf-itext5/src/main/java/org/xhtmlrenderer/pdf/ITextUserAgent.java index ff03e2db3..13c1addc7 100644 --- a/flying-saucer-pdf-itext5/src/main/java/org/xhtmlrenderer/pdf/ITextUserAgent.java +++ b/flying-saucer-pdf-itext5/src/main/java/org/xhtmlrenderer/pdf/ITextUserAgent.java @@ -30,6 +30,7 @@ import org.xhtmlrenderer.swing.NaiveUserAgent; import org.xhtmlrenderer.util.Configuration; import org.xhtmlrenderer.util.ContentTypeDetectingInputStreamWrapper; +import org.xhtmlrenderer.util.IOUtil; import org.xhtmlrenderer.util.ImageUtil; import org.xhtmlrenderer.util.XRLog; @@ -96,11 +97,7 @@ public ImageResource getImageResource(String uriStr) { } catch (Exception e) { XRLog.exception("Can't read image file; unexpected problem for URI '" + uriStr + "'", e); } finally { - try { - is.close(); - } catch (IOException e) { - // ignore - } + IOUtil.close(is); } } } diff --git a/flying-saucer-pdf-itext5/src/main/java/org/xhtmlrenderer/pdf/SelectFormField.java b/flying-saucer-pdf-itext5/src/main/java/org/xhtmlrenderer/pdf/SelectFormField.java index 81062f229..bbebfe5fe 100644 --- a/flying-saucer-pdf-itext5/src/main/java/org/xhtmlrenderer/pdf/SelectFormField.java +++ b/flying-saucer-pdf-itext5/src/main/java/org/xhtmlrenderer/pdf/SelectFormField.java @@ -156,21 +156,19 @@ protected void initDimensions(LayoutContext c, BlockBox box, int cssWidth, int c } private int getSize(Element elem) { - int result = 1; try { String v = elem.getAttribute("size").trim(); if (!v.isEmpty()) { int i = Integer.parseInt(v); if (i > 1) { - result = i; + return i; } } - } catch (NumberFormatException e) { - // ignore + } catch (NumberFormatException ignore) { } - return result; + return 1; } protected boolean isMultiple(Element e) { diff --git a/flying-saucer-pdf-itext5/src/main/java/org/xhtmlrenderer/pdf/TextFormField.java b/flying-saucer-pdf-itext5/src/main/java/org/xhtmlrenderer/pdf/TextFormField.java index 1234f347d..172b3d9fa 100644 --- a/flying-saucer-pdf-itext5/src/main/java/org/xhtmlrenderer/pdf/TextFormField.java +++ b/flying-saucer-pdf-itext5/src/main/java/org/xhtmlrenderer/pdf/TextFormField.java @@ -43,8 +43,7 @@ public class TextFormField extends AbstractFormField { private final int _baseline; - public TextFormField(LayoutContext c, BlockBox box, int cssWidth, int cssHeight) - { + public TextFormField(LayoutContext c, BlockBox box, int cssWidth, int cssHeight) { initDimensions(c, box, cssWidth, cssHeight); float fontSize = box.getStyle().getFSFont(c).getSize2D(); @@ -52,32 +51,26 @@ public TextFormField(LayoutContext c, BlockBox box, int cssWidth, int cssHeight) _baseline = (int) (getHeight() / 2 + (fontSize * 0.3f)); } - protected void initDimensions(LayoutContext c, BlockBox box, int cssWidth, int cssHeight) - { - if (cssWidth != -1) - { + protected void initDimensions(LayoutContext c, BlockBox box, int cssWidth, int cssHeight) { + if (cssWidth != -1) { setWidth(cssWidth); } - else - { + else { setWidth(c.getTextRenderer().getWidth( c.getFontContext(), box.getStyle().getFSFont(c), spaces(getSize(box.getElement())))); } - if (cssHeight != -1) - { + if (cssHeight != -1) { setHeight(cssHeight); } - else - { + else { setHeight((int) (box.getStyle().getLineHeight(c))); } } - protected String getFieldType() - { + protected String getFieldType() { return FIELD_TYPE; } @@ -101,15 +94,12 @@ public void paint(RenderingContext c, ITextOutputDevice outputDevice, BlockBox b formField.setFieldFlags(PdfFormField.FF_READ_ONLY); } writer.addAnnotation(formField); - } catch (IOException ioe) { + } catch (IOException | DocumentException ioe) { System.out.println(ioe); - } catch (DocumentException de) { - System.out.println(de); } } - private void createAppearance(RenderingContext c, ITextOutputDevice outputDevice, BlockBox box, PdfFormField field, String value) - { + private void createAppearance(RenderingContext c, ITextOutputDevice outputDevice, BlockBox box, PdfFormField field, String value) { PdfWriter writer = outputDevice.getWriter(); ITextFSFont font = (ITextFSFont) box.getStyle().getFSFont(c); @@ -140,64 +130,49 @@ private void createAppearance(RenderingContext c, ITextOutputDevice outputDevice field.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, tp); } - private int getSize(Element elem) - { + private int getSize(Element elem) { String sSize = elem.getAttribute("size"); - if (Util.isNullOrEmpty(sSize)) - { + if (Util.isNullOrEmpty(sSize)) { return DEFAULT_SIZE; } - else - { - try - { + else { + try { return Integer.parseInt(sSize.trim()); - } catch (NumberFormatException e) - { + } catch (NumberFormatException e) { return DEFAULT_SIZE; } } } - private int getMaxLength(Element elem) - { + private int getMaxLength(Element elem) { String sMaxLen = elem.getAttribute("maxlength"); - if (Util.isNullOrEmpty(sMaxLen)) - { + if (Util.isNullOrEmpty(sMaxLen)) { return 0; } - else - { - try - { + else { + try { return Integer.parseInt(sMaxLen.trim()); - } catch (NumberFormatException e) - { + } catch (NumberFormatException e) { return 0; } } } - protected String getValue(Element e) - { + protected String getValue(Element e) { String result = e.getAttribute("value"); - if (Util.isNullOrEmpty(result)) - { + if (Util.isNullOrEmpty(result)) { return ""; } - else - { + else { return result; } } - public int getBaseline() - { + public int getBaseline() { return _baseline; } - public boolean hasBaseline() - { + public boolean hasBaseline() { return true; } } diff --git a/flying-saucer-pdf-itext5/src/main/java/org/xhtmlrenderer/pdf/ToPDF.java b/flying-saucer-pdf-itext5/src/main/java/org/xhtmlrenderer/pdf/ToPDF.java index a30d3f915..86d85f37b 100644 --- a/flying-saucer-pdf-itext5/src/main/java/org/xhtmlrenderer/pdf/ToPDF.java +++ b/flying-saucer-pdf-itext5/src/main/java/org/xhtmlrenderer/pdf/ToPDF.java @@ -19,12 +19,14 @@ */ package org.xhtmlrenderer.pdf; +import com.itextpdf.text.DocumentException; + import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; +import java.nio.file.Paths; -import com.itextpdf.text.DocumentException; +import static java.nio.file.Files.newOutputStream; public class ToPDF { @@ -44,28 +46,12 @@ public static void main(String[] args) throws IOException, DocumentException { createPDF(url, args[1]); } - public static void createPDF(String url, String pdf) - throws IOException, DocumentException { - OutputStream os = null; - try { - os = new FileOutputStream(pdf); - + public static void createPDF(String url, String pdf) throws IOException, DocumentException { + try (OutputStream os = newOutputStream(Paths.get(pdf))) { ITextRenderer renderer = new ITextRenderer(); - renderer.setDocument(url); renderer.layout(); renderer.createPDF(os); - - os.close(); - os = null; - } finally { - if (os != null) { - try { - os.close(); - } catch (IOException e) { - // ignore - } - } } } } diff --git a/flying-saucer-pdf-itext5/src/main/java/org/xhtmlrenderer/simple/PDFRenderer.java b/flying-saucer-pdf-itext5/src/main/java/org/xhtmlrenderer/simple/PDFRenderer.java index 8378f50ac..d42ca63cc 100644 --- a/flying-saucer-pdf-itext5/src/main/java/org/xhtmlrenderer/simple/PDFRenderer.java +++ b/flying-saucer-pdf-itext5/src/main/java/org/xhtmlrenderer/simple/PDFRenderer.java @@ -205,29 +205,14 @@ private static void doRenderToPDF(ITextRenderer renderer, String pdf) /** * Internal use, runs the render process */ - private static byte[] doRenderToPDF(ITextRenderer renderer) - throws IOException, DocumentException { - ByteArrayOutputStream os = null; - byte[] pdf; - try { - os = new ByteArrayOutputStream(); + @Nonnull + @CheckReturnValue + private static byte[] doRenderToPDF(ITextRenderer renderer) throws IOException, DocumentException { + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { renderer.layout(); renderer.createPDF(os); - - pdf = os.toByteArray(); - - os.close(); - os = null; - } finally { - if (os != null) { - try { - os.close(); - } catch (IOException e) { - // ignore - } - } + return os.toByteArray(); } - return pdf; } /** diff --git a/flying-saucer-pdf/src/main/java/org/xhtmlrenderer/pdf/CheckboxFormField.java b/flying-saucer-pdf/src/main/java/org/xhtmlrenderer/pdf/CheckboxFormField.java index fb3cad5b3..991e3574e 100644 --- a/flying-saucer-pdf/src/main/java/org/xhtmlrenderer/pdf/CheckboxFormField.java +++ b/flying-saucer-pdf/src/main/java/org/xhtmlrenderer/pdf/CheckboxFormField.java @@ -69,31 +69,22 @@ public void paint(RenderingContext c, ITextOutputDevice outputDevice, BlockBox b field.setBorderWidth(BaseField.BORDER_WIDTH_THIN); - try - { + try { PdfFormField formField = field.getCheckField(); - if (isReadOnly(elm)) - { + if (isReadOnly(elm)) { formField.setFieldFlags(PdfFormField.FF_READ_ONLY); } writer.addAnnotation(formField); - } catch (IOException ioe) - { + } catch (IOException | DocumentException ioe) { System.out.println(ioe); - } catch (DocumentException de) - { - System.out.println(de); } - } - public int getBaseline() - { + public int getBaseline() { return 0; } - public boolean hasBaseline() - { + public boolean hasBaseline() { return false; } } diff --git a/flying-saucer-pdf/src/main/java/org/xhtmlrenderer/pdf/ITextUserAgent.java b/flying-saucer-pdf/src/main/java/org/xhtmlrenderer/pdf/ITextUserAgent.java index 3f3e2826d..46db38f8b 100644 --- a/flying-saucer-pdf/src/main/java/org/xhtmlrenderer/pdf/ITextUserAgent.java +++ b/flying-saucer-pdf/src/main/java/org/xhtmlrenderer/pdf/ITextUserAgent.java @@ -30,6 +30,7 @@ import org.xhtmlrenderer.swing.NaiveUserAgent; import org.xhtmlrenderer.util.Configuration; import org.xhtmlrenderer.util.ContentTypeDetectingInputStreamWrapper; +import org.xhtmlrenderer.util.IOUtil; import org.xhtmlrenderer.util.ImageUtil; import org.xhtmlrenderer.util.XRLog; @@ -65,11 +66,10 @@ private byte[] readStream(InputStream is) throws IOException { @Override public ImageResource getImageResource(String uriStr) { String unresolvedUri = uriStr; - ImageResource resource; if (!ImageUtil.isEmbeddedBase64Image(uriStr)) { uriStr = resolveURI(uriStr); } - resource = _imageCache.get(unresolvedUri); + ImageResource resource = _imageCache.get(unresolvedUri); if (resource == null) { if (ImageUtil.isEmbeddedBase64Image(uriStr)) { @@ -98,11 +98,7 @@ public ImageResource getImageResource(String uriStr) { } catch (BadElementException | IOException | URISyntaxException e) { XRLog.exception("Can't read image file; unexpected problem for URI '" + uriStr + "'", e); } finally { - try { - is.close(); - } catch (IOException e) { - // ignore - } + IOUtil.close(is); } } } diff --git a/flying-saucer-pdf/src/main/java/org/xhtmlrenderer/pdf/SelectFormField.java b/flying-saucer-pdf/src/main/java/org/xhtmlrenderer/pdf/SelectFormField.java index 9985278db..f924e069d 100644 --- a/flying-saucer-pdf/src/main/java/org/xhtmlrenderer/pdf/SelectFormField.java +++ b/flying-saucer-pdf/src/main/java/org/xhtmlrenderer/pdf/SelectFormField.java @@ -158,21 +158,18 @@ protected void initDimensions(LayoutContext c, BlockBox box, int cssWidth, int c } private int getSize(Element elem) { - int result = 1; try { String v = elem.getAttribute("size").trim(); if (!v.isEmpty()) { int i = Integer.parseInt(v); if (i > 1) { - result = i; + return i; } - } - } catch (NumberFormatException e) { - // ignore + } catch (NumberFormatException ignore) { } - return result; + return 1; } protected boolean isMultiple(Element e) { diff --git a/flying-saucer-pdf/src/main/java/org/xhtmlrenderer/pdf/TextFormField.java b/flying-saucer-pdf/src/main/java/org/xhtmlrenderer/pdf/TextFormField.java index 7104e069e..e58366f34 100644 --- a/flying-saucer-pdf/src/main/java/org/xhtmlrenderer/pdf/TextFormField.java +++ b/flying-saucer-pdf/src/main/java/org/xhtmlrenderer/pdf/TextFormField.java @@ -103,10 +103,8 @@ public void paint(RenderingContext c, ITextOutputDevice outputDevice, BlockBox b formField.setFieldFlags(PdfFormField.FF_READ_ONLY); } writer.addAnnotation(formField); - } catch (IOException ioe) { + } catch (IOException | DocumentException ioe) { System.out.println(ioe); - } catch (DocumentException de) { - System.out.println(de); } } diff --git a/flying-saucer-pdf/src/main/java/org/xhtmlrenderer/pdf/ToPDF.java b/flying-saucer-pdf/src/main/java/org/xhtmlrenderer/pdf/ToPDF.java index 397111ef7..ad99397ae 100644 --- a/flying-saucer-pdf/src/main/java/org/xhtmlrenderer/pdf/ToPDF.java +++ b/flying-saucer-pdf/src/main/java/org/xhtmlrenderer/pdf/ToPDF.java @@ -22,9 +22,11 @@ import com.lowagie.text.DocumentException; import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; +import java.nio.file.Paths; + +import static java.nio.file.Files.newOutputStream; public class ToPDF { @@ -44,28 +46,12 @@ public static void main(String[] args) throws IOException, DocumentException { createPDF(url, args[1]); } - private static void createPDF(String url, String pdf) - throws IOException, DocumentException { - OutputStream os = null; - try { - os = new FileOutputStream(pdf); - + private static void createPDF(String url, String pdf) throws IOException, DocumentException { + try (OutputStream os = newOutputStream(Paths.get(pdf))) { ITextRenderer renderer = new ITextRenderer(); - renderer.setDocument(url); renderer.layout(); renderer.createPDF(os); - - os.close(); - os = null; - } finally { - if (os != null) { - try { - os.close(); - } catch (IOException e) { - // ignore - } - } } } } diff --git a/flying-saucer-swt-examples/src/main/java/org/xhtmlrenderer/demo/browser/swt/BrowserUserAgent.java b/flying-saucer-swt-examples/src/main/java/org/xhtmlrenderer/demo/browser/swt/BrowserUserAgent.java index 815d0a02e..888fceaac 100644 --- a/flying-saucer-swt-examples/src/main/java/org/xhtmlrenderer/demo/browser/swt/BrowserUserAgent.java +++ b/flying-saucer-swt-examples/src/main/java/org/xhtmlrenderer/demo/browser/swt/BrowserUserAgent.java @@ -29,6 +29,7 @@ import org.xhtmlrenderer.resource.XMLResource; import org.xhtmlrenderer.swt.NaiveUserAgent; import org.xhtmlrenderer.util.GeneralUtil; +import org.xhtmlrenderer.util.IOUtil; import org.xhtmlrenderer.util.Uu; import org.xhtmlrenderer.util.XRLog; import org.xml.sax.InputSource; @@ -69,10 +70,6 @@ public String resolveURI(@Nullable String uri) { if (uri.trim().isEmpty()) return burl; //jar URLs don't resolve this right URL ref = null; - - if (uri == null) return null; - if (uri.trim().equals("")) return burl; //jar URLs don't resolve this right - if (uri.startsWith("demo:")) { DemoMarker marker = new DemoMarker(); String short_url = uri.substring(5); @@ -207,13 +204,7 @@ public XMLResource getXMLResource(String uri) { } catch (IOException e) { XRLog.exception("IO problem for " + uri, e); } finally { - if (inputStream != null) { - try { - inputStream.close(); - } catch (IOException e) { - // swallow - } - } + IOUtil.close(inputStream); } if (xr == null) { diff --git a/flying-saucer-swt-examples/src/main/java/org/xhtmlrenderer/demo/browser/swt/DemosNavigation.java b/flying-saucer-swt-examples/src/main/java/org/xhtmlrenderer/demo/browser/swt/DemosNavigation.java index 287990981..ba7e36585 100644 --- a/flying-saucer-swt-examples/src/main/java/org/xhtmlrenderer/demo/browser/swt/DemosNavigation.java +++ b/flying-saucer-swt-examples/src/main/java/org/xhtmlrenderer/demo/browser/swt/DemosNavigation.java @@ -36,25 +36,18 @@ public class DemosNavigation { private boolean _lock; public DemosNavigation(BrowserUserAgent uac) { - BufferedReader reader = null; _demos = new ArrayList<>(); try { URL url = new URL(uac.resolveFullURI(FILE_LIST_URL)); - reader = new BufferedReader(new InputStreamReader(url.openStream())); - String line; - while ((line = reader.readLine()) != null) { - String[] fields = line.split(","); - _demos.add(new Demo(fields[1], fields[0])); - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (reader != null) { - try { - reader.close(); - } catch (IOException e) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()))) { + String line; + while ((line = reader.readLine()) != null) { + String[] fields = line.split(","); + _demos.add(new Demo(fields[1], fields[0])); } } + } catch (IOException e) { + e.printStackTrace(); } _current = -1; } diff --git a/flying-saucer-swt/src/main/java/org/xhtmlrenderer/swt/NaiveUserAgent.java b/flying-saucer-swt/src/main/java/org/xhtmlrenderer/swt/NaiveUserAgent.java index 612f56bee..0dc4e210e 100644 --- a/flying-saucer-swt/src/main/java/org/xhtmlrenderer/swt/NaiveUserAgent.java +++ b/flying-saucer-swt/src/main/java/org/xhtmlrenderer/swt/NaiveUserAgent.java @@ -26,6 +26,7 @@ import org.xhtmlrenderer.resource.CSSResource; import org.xhtmlrenderer.resource.ImageResource; import org.xhtmlrenderer.resource.XMLResource; +import org.xhtmlrenderer.util.IOUtil; import org.xhtmlrenderer.util.ImageUtil; import org.xhtmlrenderer.util.XRLog; @@ -33,7 +34,6 @@ import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -44,6 +44,8 @@ import java.util.LinkedHashMap; import java.util.Map; +import static org.xhtmlrenderer.util.IOUtil.getInputStream; + /** * Naive user agent, copy of org.xhtmlrenderer.swing.NaiveUserAgent (but * modified for SWT, of course). @@ -70,30 +72,9 @@ public NaiveUserAgent(Device device) { _device = device; } - /** - * Gets a Reader for the resource identified - * - * @return The stylesheet value - */ - // TODO implement this with nio. - protected InputStream getInputStream(String uri) { - java.io.InputStream is = null; - uri = resolveURI(uri); - try { - is = new URL(uri).openStream(); - } catch (java.net.MalformedURLException e) { - XRLog.exception("bad URL given: " + uri, e); - } catch (java.io.FileNotFoundException e) { - XRLog.exception("item at URI " + uri + " not found"); - } catch (java.io.IOException e) { - XRLog.exception("IO problem for " + uri, e); - } - return is; - } - @Override public CSSResource getCSSResource(String uri) { - return new CSSResource(getInputStream(uri)); + return new CSSResource(getInputStream(resolveURI(uri))); } @Override @@ -106,29 +87,22 @@ public ImageResource getImageResource(String uri) { ir = _imageCache.get(uri); // TODO: check that cached image is still valid if (ir == null) { - InputStream is = getInputStream(uri); - if (is != null) { - try { - ir = createImageResource(uri, is); - if (_imageCache.size() >= _imageCacheCapacity) { - // prevent the cache from growing too big - ImageResource old = _imageCache - .remove(_imageCache.keySet().iterator().next()); - ((SWTFSImage) old.getImage()).getImage().dispose(); + try (InputStream is = getInputStream(resolveURI(uri))) { + if (is != null) { + ir = createImageResource(uri, is); + if (_imageCache.size() >= _imageCacheCapacity) { + // prevent the cache from growing too big + ImageResource old = _imageCache + .remove(_imageCache.keySet().iterator().next()); + ((SWTFSImage) old.getImage()).getImage().dispose(); + } + _imageCache.put(uri, ir); } - _imageCache.put(uri, ir); - } catch (SWTException e) { + } catch (SWTException | IOException e) { XRLog.exception( "Can't read image file; unexpected problem for URI '" + uri + "'", e); - } finally { - try { - is.close(); - } catch (IOException e) { - // swallow - } } - } } if (ir == null) { ir = new ImageResource(uri, null); @@ -165,7 +139,7 @@ public XMLResource getXMLResource(String uri) { XRLog.exception("null uri requested"); return null; } - try (InputStream inputStream = getInputStream(uri)) { + try (InputStream inputStream = getInputStream(resolveURI(uri))) { if (inputStream == null) { XRLog.exception("couldn't get InputStream for " + uri); return null; @@ -260,29 +234,6 @@ public void disposeCache() { @Nullable @CheckReturnValue public byte[] getBinaryResource(String uri) { - InputStream is = getInputStream(uri); - if (is==null) return null; - try { - ByteArrayOutputStream result = new ByteArrayOutputStream(); - byte[] buf = new byte[10240]; - int i; - while ((i = is.read(buf)) != -1) { - result.write(buf, 0, i); - } - is.close(); - is = null; - - return result.toByteArray(); - } catch (IOException e) { - return null; - } finally { - if (is != null) { - try { - is.close(); - } catch (IOException e) { - // ignore - } - } - } + return IOUtil.readBytes(resolveURI(uri)); } } diff --git a/www/faq.html b/www/faq.html index 27b8bc721..039b92601 100755 --- a/www/faq.html +++ b/www/faq.html @@ -242,11 +242,7 @@

How can I print multiple "input3.html" }; String output = "output.pdf"; -OutputStream os = null; -try -{ - os = new FileOutputStream(new File(root, output)); - +try (OutputStream os = new FileOutputStream(new File(root, output))) { ITextRenderer renderer = new ITextRenderer(); renderer.setDocument(new File(root, inputs[0])); @@ -254,31 +250,13 @@

How can I print multiple renderer.createPDF(os, false); - for (int i = 1; i < inputs.length; i++) - { + for (int i = 1; i < inputs.length; i++) { renderer.setDocument(new File(root, inputs[i])); renderer.layout(); renderer.writeNextDocument(); } renderer.finishPDF(); - - os.close(); - os = null; -} -finally -{ - if (os != null) - { - try - { - os.close(); - } - catch (IOException e) - { - // ignore - } - } } diff --git a/www/faq.xil b/www/faq.xil index b44087c29..52f48de8c 100644 --- a/www/faq.xil +++ b/www/faq.xil @@ -164,11 +164,7 @@ String[] inputs = new String[] { "input1.html", "input2.html", "input3.html" }; String output = "output.pdf"; -OutputStream os = null; -try -{ - os = new FileOutputStream(new File(root, output)); - +try (OutputStream os = new FileOutputStream(new File(root, output))) { ITextRenderer renderer = new ITextRenderer(); renderer.setDocument(new File(root, inputs[0])); @@ -176,31 +172,13 @@ try renderer.createPDF(os, false); - for (int i = 1; i < inputs.length; i++) - { + for (int i = 1; i < inputs.length; i++) { renderer.setDocument(new File(root, inputs[i])); renderer.layout(); renderer.writeNextDocument(); } renderer.finishPDF(); - - os.close(); - os = null; -} -finally -{ - if (os != null) - { - try - { - os.close(); - } - catch (IOException e) - { - // ignore - } - } } }}