Skip to content

Commit

Permalink
TIKA-1719: Utilize try-with-resources where it is trivial
Browse files Browse the repository at this point in the history
Patch by Yaniv Kunda


git-svn-id: https://svn.apache.org/repos/asf/tika/trunk@1700195 13f79535-47bb-0310-9956-ffa450edef68
  • Loading branch information
jukka committed Aug 31, 2015
1 parent 24b8c2a commit 8938fdf
Show file tree
Hide file tree
Showing 105 changed files with 833 additions and 1,745 deletions.
33 changes: 8 additions & 25 deletions tika-app/src/main/java/org/apache/tika/cli/TikaCLI.java
Original file line number Diff line number Diff line change
Expand Up @@ -467,12 +467,9 @@ public void process(String arg) throws Exception {
if (serverMode) {
new TikaServer(Integer.parseInt(arg)).start();
} else if (arg.equals("-")) {
InputStream stream =
TikaInputStream.get(new CloseShieldInputStream(System.in));
try {
try (InputStream stream = TikaInputStream.get(
new CloseShieldInputStream(System.in))) {
type.process(stream, System.out, new Metadata());
} finally {
stream.close();
}
} else {
URL url;
Expand All @@ -486,11 +483,10 @@ public void process(String arg) throws Exception {
handleRecursiveJson(url, System.out);
} else {
Metadata metadata = new Metadata();
InputStream input = TikaInputStream.get(url, metadata);
try {
try (InputStream input =
TikaInputStream.get(url, metadata)) {
type.process(input, System.out, metadata);
} finally {
input.close();
System.out.flush();
}
}
Expand All @@ -500,12 +496,9 @@ public void process(String arg) throws Exception {

private void handleRecursiveJson(URL url, OutputStream output) throws IOException, SAXException, TikaException {
Metadata metadata = new Metadata();
InputStream input = TikaInputStream.get(url, metadata);
RecursiveParserWrapper wrapper = new RecursiveParserWrapper(parser, getContentHandlerFactory(type));
try {
try (InputStream input = TikaInputStream.get(url, metadata)) {
wrapper.parse(input, null, metadata, context);
} finally {
input.close();
}
JsonMetadataList.setPrettyPrinting(prettyPrint);
Writer writer = getOutputWriter(output, encoding);
Expand Down Expand Up @@ -1049,11 +1042,7 @@ public void parseEmbedded(InputStream inputStream, ContentHandler contentHandler
}
System.out.println("Extracting '"+name+"' ("+contentType+") to " + outputFile);

FileOutputStream os = null;

try {
os = new FileOutputStream(outputFile);

try (FileOutputStream os = new FileOutputStream(outputFile)) {
if (inputStream instanceof TikaInputStream) {
TikaInputStream tin = (TikaInputStream) inputStream;

Expand All @@ -1079,10 +1068,6 @@ public void parseEmbedded(InputStream inputStream, ContentHandler contentHandler
);
System.err.println(msg);
logger.warn(msg, e);
} finally {
if (os != null) {
os.close();
}
}
}

Expand All @@ -1095,11 +1080,9 @@ protected void copy(DirectoryEntry sourceDir, DirectoryEntry destDir)
copy((DirectoryEntry) entry, newDir);
} else {
// Copy entry
InputStream contents = new DocumentInputStream((DocumentEntry) entry);
try {
try (InputStream contents =
new DocumentInputStream((DocumentEntry) entry)) {
destDir.createDocument(entry.getName(), contents);
} finally {
contents.close();
}
}
}
Expand Down
15 changes: 3 additions & 12 deletions tika-app/src/main/java/org/apache/tika/gui/TikaGUI.java
Original file line number Diff line number Diff line change
Expand Up @@ -304,11 +304,8 @@ public void actionPerformed(ActionEvent e) {
public void openFile(File file) {
try {
Metadata metadata = new Metadata();
TikaInputStream stream = TikaInputStream.get(file, metadata);
try {
try (TikaInputStream stream = TikaInputStream.get(file, metadata)) {
handleStream(stream, metadata);
} finally {
stream.close();
}
} catch (Throwable t) {
handleError(file.getPath(), t);
Expand All @@ -318,11 +315,8 @@ public void openFile(File file) {
public void openURL(URL url) {
try {
Metadata metadata = new Metadata();
TikaInputStream stream = TikaInputStream.get(url, metadata);
try {
try (TikaInputStream stream = TikaInputStream.get(url, metadata)) {
handleStream(stream, metadata);
} finally {
stream.close();
}
} catch (Throwable t) {
handleError(url.toString(), t);
Expand Down Expand Up @@ -477,8 +471,7 @@ public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == EventType.ACTIVATED) {
try {
URL url = e.getURL();
InputStream stream = url.openStream();
try {
try (InputStream stream = url.openStream()) {
JEditorPane editor =
new JEditorPane("text/plain", IOUtils.toString(stream, UTF_8));
editor.setEditable(false);
Expand All @@ -493,8 +486,6 @@ public void hyperlinkUpdate(HyperlinkEvent e) {
dialog.add(new JScrollPane(editor));
dialog.pack();
dialog.setVisible(true);
} finally {
stream.close();
}
} catch (IOException exception) {
exception.printStackTrace();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -247,12 +247,9 @@ public void testTikaBundle() throws Exception {
ParseContext context = new ParseContext();
context.set(Parser.class, parser);

InputStream stream
= new FileInputStream("src/test/resources/test-documents.zip");
try {
try (InputStream stream =
new FileInputStream("src/test/resources/test-documents.zip")) {
parser.parse(stream, handler, new Metadata(), context);
} finally {
stream.close();
}

String content = handler.toString();
Expand Down
30 changes: 8 additions & 22 deletions tika-core/src/main/java/org/apache/tika/Tika.java
Original file line number Diff line number Diff line change
Expand Up @@ -218,11 +218,8 @@ public String detect(InputStream stream) throws IOException {
*/
public String detect(byte[] prefix, String name) {
try {
InputStream stream = TikaInputStream.get(prefix);
try {
try (InputStream stream = TikaInputStream.get(prefix)) {
return detect(stream, name);
} finally {
stream.close();
}
} catch (IOException e) {
throw new IllegalStateException("Unexpected IOException", e);
Expand All @@ -244,11 +241,8 @@ public String detect(byte[] prefix, String name) {
*/
public String detect(byte[] prefix) {
try {
InputStream stream = TikaInputStream.get(prefix);
try {
try (InputStream stream = TikaInputStream.get(prefix)) {
return detect(stream);
} finally {
stream.close();
}
} catch (IOException e) {
throw new IllegalStateException("Unexpected IOException", e);
Expand Down Expand Up @@ -287,11 +281,8 @@ public String detect(File file) throws IOException {
*/
public String detect(URL url) throws IOException {
Metadata metadata = new Metadata();
InputStream stream = TikaInputStream.get(url, metadata);
try {
try (InputStream stream = TikaInputStream.get(url, metadata)) {
return detect(stream, metadata);
} finally {
stream.close();
}
}

Expand Down Expand Up @@ -642,17 +633,12 @@ public Translator getTranslator() {
public String toString() {
String version = null;

try {
InputStream stream = Tika.class.getResourceAsStream(
"/META-INF/maven/org.apache.tika/tika-core/pom.properties");
try (InputStream stream = Tika.class.getResourceAsStream(
"/META-INF/maven/org.apache.tika/tika-core/pom.properties")) {
if (stream != null) {
try {
Properties properties = new Properties();
properties.load(stream);
version = properties.getProperty("version");
} finally {
stream.close();
}
Properties properties = new Properties();
properties.load(stream);
version = properties.getProperty("version");
}
} catch (Exception ignore) {
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -343,10 +343,9 @@ public <T> List<T> loadStaticServiceProviders(Class<T> iface) {

private void collectServiceClassNames(URL resource, Collection<String> names)
throws IOException {
InputStream stream = resource.openStream();
try {
try (InputStream stream = resource.openStream()) {
BufferedReader reader =
new BufferedReader(new InputStreamReader(stream, UTF_8));
new BufferedReader(new InputStreamReader(stream, UTF_8));
String line = reader.readLine();
while (line != null) {
line = COMMENT.matcher(line).replaceFirst("");
Expand All @@ -356,8 +355,6 @@ private void collectServiceClassNames(URL resource, Collection<String> names)
}
line = reader.readLine();
}
} finally {
stream.close();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,11 +122,8 @@ public void parse(
File file = tis.getFile();

// Let the handler process the embedded resource
InputStream input = TikaInputStream.get(file);
try {
try (InputStream input = TikaInputStream.get(file)) {
handler.handle(filename, type, input);
} finally {
input.close();
}

// Recurse
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,7 @@ public void parseEmbedded(
}

// Use the delegate parser to parse this entry
TemporaryResources tmp = new TemporaryResources();
try {
try (TemporaryResources tmp = new TemporaryResources()) {
final TikaInputStream newStream = TikaInputStream.get(new CloseShieldInputStream(stream), tmp);
if (stream instanceof TikaInputStream) {
final Object container = ((TikaInputStream) stream).getOpenContainer();
Expand All @@ -110,8 +109,6 @@ public void parseEmbedded(
} catch (TikaException e) {
// TODO: can we log a warning somehow?
// Could not parse the entry, just skip the content
} finally {
tmp.close();
}

if(outputHtml) {
Expand Down
13 changes: 4 additions & 9 deletions tika-core/src/main/java/org/apache/tika/fork/ForkClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -258,10 +258,10 @@ private static File createBootstrapJar() throws IOException {
* @throws IOException if the bootstrap archive could not be created
*/
private static void fillBootstrapJar(File file) throws IOException {
JarOutputStream jar = new JarOutputStream(new FileOutputStream(file));
try {
try (JarOutputStream jar =
new JarOutputStream(new FileOutputStream(file))) {
String manifest =
"Main-Class: " + ForkServer.class.getName() + "\n";
"Main-Class: " + ForkServer.class.getName() + "\n";
jar.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF"));
jar.write(manifest.getBytes(UTF_8));

Expand All @@ -276,16 +276,11 @@ private static void fillBootstrapJar(File file) throws IOException {
ClassLoader loader = ForkServer.class.getClassLoader();
for (Class<?> klass : bootstrap) {
String path = klass.getName().replace('.', '/') + ".class";
InputStream input = loader.getResourceAsStream(path);
try {
try (InputStream input = loader.getResourceAsStream(path)) {
jar.putNextEntry(new JarEntry(path));
IOUtils.copy(input, jar);
} finally {
input.close();
}
}
} finally {
jar.close();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,8 @@
* <p>
* The recommended usage pattern of this class is:
* <pre>
* InputStream lookahead = new LookaheadInputStream(stream, n);
* try {
* try (InputStream lookahead = new LookaheadInputStream(stream, n)) {
* processStream(lookahead);
* } finally {
* lookahead.close();
* }
* </pre>
* <p>
Expand Down
23 changes: 7 additions & 16 deletions tika-core/src/main/java/org/apache/tika/io/TikaInputStream.java
Original file line number Diff line number Diff line change
Expand Up @@ -85,19 +85,16 @@ public static boolean isTikaInputStream(InputStream stream) {
* when you <em>don't</em> explicitly close the returned stream. The
* recommended access pattern is:
* <pre>
* TemporaryResources tmp = new TemporaryResources();
* try {
* try (TemporaryResources tmp = new TemporaryResources()) {
* TikaInputStream stream = TikaInputStream.get(..., tmp);
* // process stream but don't close it
* } finally {
* tmp.close();
* }
* </pre>
* <p>
* The given stream instance will <em>not</em> be closed when the
* {@link TemporaryResources#close()} method is called. The caller
* is expected to explicitly close the original stream when it's no
* longer used.
* {@link TemporaryResources#close()} method is called by the
* try-with-resources statement. The caller is expected to explicitly
* close the original stream when it's no longer used.
*
* @since Apache Tika 0.10
* @param stream normal input stream
Expand Down Expand Up @@ -131,17 +128,14 @@ public static TikaInputStream get(
* <em>do</em> explicitly close the returned stream. The recommended
* access pattern is:
* <pre>
* TikaInputStream stream = TikaInputStream.get(...);
* try {
* try (TikaInputStream stream = TikaInputStream.get(...)) {
* // process stream
* } finally {
* stream.close();
* }
* </pre>
* <p>
* The given stream instance will be closed along with any other resources
* associated with the returned TikaInputStream instance when the
* {@link #close()} method is called.
* {@link #close()} method is called by the try-with-resources statement.
*
* @param stream normal input stream
* @return a TikaInputStream instance
Expand Down Expand Up @@ -531,11 +525,8 @@ public File getFile() throws IOException {
} else {
// Spool the entire stream into a temporary file
file = tmp.createTemporaryFile();
OutputStream out = new FileOutputStream(file);
try {
try (OutputStream out = new FileOutputStream(file)) {
IOUtils.copy(in, out);
} finally {
out.close();
}

// Create a new input stream and make sure it'll get closed
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,9 @@ private static void addProfile(String language) throws Exception {
try {
LanguageProfile profile = new LanguageProfile();

InputStream stream =
LanguageIdentifier.class.getResourceAsStream(language + PROFILE_SUFFIX);
try {
try (InputStream stream =
LanguageIdentifier.class.getResourceAsStream(
language + PROFILE_SUFFIX)) {
BufferedReader reader =
new BufferedReader(new InputStreamReader(stream, UTF_8));
String line = reader.readLine();
Expand All @@ -88,8 +88,6 @@ private static void addProfile(String language) throws Exception {
}
line = reader.readLine();
}
} finally {
stream.close();
}

addProfile(language, profile);
Expand Down
Loading

0 comments on commit 8938fdf

Please sign in to comment.