From addc9a7045ddd6551a21f5af4729bcd6aa675a5c Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Thu, 13 Dec 2018 19:13:26 +0300 Subject: [PATCH] cleanup: use try with resources --- .../jetbrains/jps/api/CmdlineProtoUtil.java | 6 +-- .../index/CompilerReferenceIndex.java | 12 ++---- .../java/dependencyView/Mappings.java | 10 +---- .../jetbrains/jps/cmdline/BuildSession.java | 14 ++++--- .../artifacts/impl/JarsBuilder.java | 15 ++++--- .../JarBasedArtifactRootDescriptor.java | 24 ++++------- .../incremental/storage/BuildDataManager.java | 14 ++----- .../storage/BuildTargetConfiguration.java | 6 +-- .../storage/BuildTargetTypeState.java | 28 +++++-------- .../storage/BuildTargetsState.java | 6 +-- .../jetbrains/jps/builders/BuildResult.java | 6 +-- .../externalSystem/model/JDKSerializer.java | 6 +-- .../manage/ExternalProjectsDataStorage.java | 25 ++--------- .../ide/browsers/firefox/FirefoxUtil.java | 13 ++---- .../com/intellij/ide/gdpr/ConsentOptions.java | 19 ++++----- .../intellij/ide/gdpr/EndUserAgreement.java | 41 +++++++------------ .../ide/plugins/RepositoryHelper.java | 12 +++--- .../ImportedToGeneralTestEventsConverter.java | 12 +----- .../changes/committed/ChangesCacheFile.java | 25 ++++------- .../changes/shelf/ShelveChangesManager.java | 10 +---- .../vcs/log/impl/HashSerializeTest.java | 6 +-- .../testFramework/vcs/TestClientRunner.java | 6 +-- .../byteCodeViewer/ByteCodeViewerManager.java | 6 +-- .../checkin/GitCheckinEnvironment.java | 6 +-- .../rebase/GitInteractiveRebaseFile.java | 12 +----- .../src/git4idea/rebase/GitRebaseUtils.java | 28 +++++-------- .../src/git4idea/ui/GitTagDialog.java | 6 +-- .../plugins/github/api/GithubConnection.java | 6 +-- .../groovy/config/AbstractConfigUtils.java | 12 +----- .../zmlx/hg4idea/execution/SocketServer.java | 6 +-- .../zmlx/hg4idea/repo/HgRepositoryReader.java | 6 +-- .../hg4idea/test/HgAnnotateCommandTest.java | 14 ++----- .../SpellCheckerDictionaryGenerator.java | 14 ++----- .../spellchecker/inspector/SplitterTest.java | 14 ++----- 34 files changed, 130 insertions(+), 316 deletions(-) diff --git a/jps/jps-builders/src/org/jetbrains/jps/api/CmdlineProtoUtil.java b/jps/jps-builders/src/org/jetbrains/jps/api/CmdlineProtoUtil.java index 0e2329fd89c9..faa7bbd8ec27 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/api/CmdlineProtoUtil.java +++ b/jps/jps-builders/src/org/jetbrains/jps/api/CmdlineProtoUtil.java @@ -117,13 +117,9 @@ public class CmdlineProtoUtil { } if (cause != null) { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - final PrintStream stream = new PrintStream(baos); - try { + try (PrintStream stream = new PrintStream(baos)) { cause.printStackTrace(stream); } - finally { - stream.close(); - } final String stacktrace = new String(baos.toByteArray()); builder.setStacktrace(stacktrace); if (description == null) { diff --git a/jps/jps-builders/src/org/jetbrains/jps/backwardRefs/index/CompilerReferenceIndex.java b/jps/jps-builders/src/org/jetbrains/jps/backwardRefs/index/CompilerReferenceIndex.java index 236a951a1d55..e41c20d071ef 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/backwardRefs/index/CompilerReferenceIndex.java +++ b/jps/jps-builders/src/org/jetbrains/jps/backwardRefs/index/CompilerReferenceIndex.java @@ -157,15 +157,9 @@ public class CompilerReferenceIndex { public void saveVersion(@NotNull File buildDir, int version) { File versionFile = new File(getIndexDir(buildDir), VERSION_FILE); - try { - FileUtil.createIfDoesntExist(versionFile); - final DataOutputStream os = new DataOutputStream(new FileOutputStream(versionFile)); - try { - os.writeInt(version); - } - finally { - os.close(); - } + FileUtil.createIfDoesntExist(versionFile); + try (DataOutputStream os = new DataOutputStream(new FileOutputStream(versionFile))) { + os.writeInt(version); } catch (IOException ex) { LOG.error(ex); diff --git a/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/Mappings.java b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/Mappings.java index 801559f356cc..46920c3dc377 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/Mappings.java +++ b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/Mappings.java @@ -3114,14 +3114,8 @@ public class Mappings { for (int i = 0; i < data.length; i++) { final File file = new File(outputRoot, info[i]); FileUtil.createIfDoesntExist(file); - try { - final PrintStream stream = new PrintStream(file); - try { - data[i].toStream(myContext, stream); - } - finally { - stream.close(); - } + try (PrintStream stream = new PrintStream(file)) { + data[i].toStream(myContext, stream); } catch (FileNotFoundException e) { e.printStackTrace(); diff --git a/jps/jps-builders/src/org/jetbrains/jps/cmdline/BuildSession.java b/jps/jps-builders/src/org/jetbrains/jps/cmdline/BuildSession.java index 25546b0e7dc6..59da8d8a4127 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/cmdline/BuildSession.java +++ b/jps/jps-builders/src/org/jetbrains/jps/cmdline/BuildSession.java @@ -507,6 +507,13 @@ final class BuildSession implements Runnable, CanceledStatus { } private static void saveOnDisk(BufferExposingByteArrayOutputStream bytes, final File file) throws IOException { + try (FileOutputStream fos = writeOrCreate(file)) { + fos.write(bytes.getInternalBuffer(), 0, bytes.size()); + } + } + + @NotNull + private static FileOutputStream writeOrCreate(@NotNull File file) throws FileNotFoundException { FileOutputStream fos = null; try { //noinspection IOResourceOpenedButNotSafelyClosed @@ -519,12 +526,7 @@ final class BuildSession implements Runnable, CanceledStatus { if (fos == null) { fos = new FileOutputStream(file); } - try { - fos.write(bytes.getInternalBuffer(), 0, bytes.size()); - } - finally { - fos.close(); - } + return fos; } @Nullable diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/artifacts/impl/JarsBuilder.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/artifacts/impl/JarsBuilder.java index eedcb6f6f979..bb60ce58ccdc 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/artifacts/impl/JarsBuilder.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/artifacts/impl/JarsBuilder.java @@ -231,7 +231,9 @@ public class JarsBuilder { if (manifestFile.exists()) { final String fullManifestPath = FileUtil.toSystemIndependentName(manifestFile.getAbsolutePath()); packedFilePaths.add(fullManifestPath); - return createManifest(new FileInputStream(manifestFile), manifestFile); + try (FileInputStream stream = new FileInputStream(manifestFile)) { + return createManifest(stream, manifestFile); + } } } else { @@ -240,7 +242,9 @@ public class JarsBuilder { @Override public void process(@Nullable InputStream inputStream, @NotNull String relativePath, ZipEntry entry) throws IOException { if (manifestRef.isNull() && relativePath.equals(manifestPath) && inputStream != null) { - manifestRef.set(createManifest(inputStream, descriptor.getRootFile())); + try (InputStream stream = inputStream) { + manifestRef.set(createManifest(stream, descriptor.getRootFile())); + } } } }); @@ -256,12 +260,7 @@ public class JarsBuilder { @Nullable private Manifest createManifest(InputStream manifestStream, File manifestFile) { try { - try { - return new Manifest(manifestStream); - } - finally { - manifestStream.close(); - } + return new Manifest(manifestStream); } catch (IOException e) { myContext.processMessage(new CompilerMessage(IncArtifactBuilder.BUILDER_NAME, BuildMessage.Kind.ERROR, diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/artifacts/instructions/JarBasedArtifactRootDescriptor.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/artifacts/instructions/JarBasedArtifactRootDescriptor.java index d3ebe3b65510..98a3b2019322 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/artifacts/instructions/JarBasedArtifactRootDescriptor.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/artifacts/instructions/JarBasedArtifactRootDescriptor.java @@ -49,25 +49,19 @@ public class JarBasedArtifactRootDescriptor extends ArtifactRootDescriptor { prefix = ""; } - try { - ZipFile zipFile = new ZipFile(myRoot); - try { - final Enumeration entries = zipFile.entries(); + try (ZipFile zipFile = new ZipFile(myRoot)) { + final Enumeration entries = zipFile.entries(); - while (entries.hasMoreElements()) { - ZipEntry entry = entries.nextElement(); - final String name = entry.getName(); - if (name.startsWith(prefix)) { - String relativePath = name.substring(prefix.length()); - if (myPathInJarFilter.value(relativePath)) { - processor.process(entry.isDirectory() ? null : zipFile.getInputStream(entry), relativePath, entry); - } + while (entries.hasMoreElements()) { + ZipEntry entry = entries.nextElement(); + final String name = entry.getName(); + if (name.startsWith(prefix)) { + String relativePath = name.substring(prefix.length()); + if (myPathInJarFilter.value(relativePath)) { + processor.process(entry.isDirectory() ? null : zipFile.getInputStream(entry), relativePath, entry); } } } - finally { - zipFile.close(); - } } catch (IOException e) { throw new IOException("Error occurred during processing zip file " + myRoot + ": " + e.getMessage(), e); diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildDataManager.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildDataManager.java index ec04a432e4f8..06d11ec6f0d0 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildDataManager.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildDataManager.java @@ -389,16 +389,10 @@ public class BuildDataManager implements StorageOwner { public void saveVersion() { final Boolean differs = myVersionDiffers; if (differs == null || differs) { - try { - FileUtil.createIfDoesntExist(myVersionFile); - final DataOutputStream os = new DataOutputStream(new FileOutputStream(myVersionFile)); - try { - os.writeInt(VERSION); - myVersionDiffers = Boolean.FALSE; - } - finally { - os.close(); - } + FileUtil.createIfDoesntExist(myVersionFile); + try (DataOutputStream os = new DataOutputStream(new FileOutputStream(myVersionFile))) { + os.writeInt(VERSION); + myVersionDiffers = Boolean.FALSE; } catch (IOException ignored) { } diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildTargetConfiguration.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildTargetConfiguration.java index 1b8fcbc30e15..484111afbb04 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildTargetConfiguration.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildTargetConfiguration.java @@ -102,14 +102,10 @@ public class BuildTargetConfiguration { try { File configFile = getConfigFile(); FileUtil.createParentDirs(configFile); - Writer out = new BufferedWriter(new FileWriter(configFile)); - try { + try (Writer out = new BufferedWriter(new FileWriter(configFile))) { out.write(data); myConfiguration = data; } - finally { - out.close(); - } } catch (IOException e) { LOG.info("Cannot save configuration of " + myConfiguration, e); diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildTargetTypeState.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildTargetTypeState.java index 45339c228730..8497805103bd 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildTargetTypeState.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildTargetTypeState.java @@ -88,25 +88,19 @@ public class BuildTargetTypeState { } public synchronized void save() { - try { - FileUtil.createParentDirs(myTargetsFile); - DataOutputStream output = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(myTargetsFile))); - try { - output.writeInt(VERSION); - output.writeInt(myTargetIds.size() + myStaleTargetIds.size()); - for (Map.Entry, Integer> entry : myTargetIds.entrySet()) { - IOUtil.writeString(entry.getKey().getId(), output); - output.writeInt(entry.getValue()); - } - for (Pair pair : myStaleTargetIds) { - IOUtil.writeString(pair.first, output); - output.writeInt(pair.second); - } - output.writeLong(myAverageTargetBuildTimeMs); + FileUtil.createParentDirs(myTargetsFile); + try (DataOutputStream output = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(myTargetsFile)))) { + output.writeInt(VERSION); + output.writeInt(myTargetIds.size() + myStaleTargetIds.size()); + for (Map.Entry, Integer> entry : myTargetIds.entrySet()) { + IOUtil.writeString(entry.getKey().getId(), output); + output.writeInt(entry.getValue()); } - finally { - output.close(); + for (Pair pair : myStaleTargetIds) { + IOUtil.writeString(pair.first, output); + output.writeInt(pair.second); } + output.writeLong(myAverageTargetBuildTimeMs); } catch (IOException e) { LOG.info("Cannot save " + myTargetType.getTypeId() + " targets data: " + e.getMessage(), e); diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildTargetsState.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildTargetsState.java index 752f9f24ce74..ddabe10df49f 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildTargetsState.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildTargetsState.java @@ -68,13 +68,9 @@ public class BuildTargetsState { try { File targetTypesFile = getTargetTypesFile(); FileUtil.createParentDirs(targetTypesFile); - DataOutputStream output = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(targetTypesFile))); - try { + try (DataOutputStream output = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(targetTypesFile)))) { output.writeInt(myMaxTargetId.get()); } - finally { - output.close(); - } } catch (IOException e) { LOG.info("Cannot save targets info: " + e.getMessage(), e); diff --git a/jps/jps-builders/testSrc/org/jetbrains/jps/builders/BuildResult.java b/jps/jps-builders/testSrc/org/jetbrains/jps/builders/BuildResult.java index c1e03e15ee4a..dfac0ed07134 100644 --- a/jps/jps-builders/testSrc/org/jetbrains/jps/builders/BuildResult.java +++ b/jps/jps-builders/testSrc/org/jetbrains/jps/builders/BuildResult.java @@ -59,14 +59,10 @@ public class BuildResult implements MessageHandler { void storeMappingsDump(ProjectDescriptor pd) throws IOException { final ByteArrayOutputStream dump = new ByteArrayOutputStream(); - final PrintStream stream = new PrintStream(dump); - try { + try (PrintStream stream = new PrintStream(dump)) { pd.dataManager.getMappings().toStream(stream); dumpSourceToOutputMappings(pd, stream); } - finally { - stream.close(); - } dump.close(); myMappingsDump = dump.toString(); diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/JDKSerializer.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/JDKSerializer.java index 3ee1d5233a1d..c4c4089bb819 100644 --- a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/JDKSerializer.java +++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/JDKSerializer.java @@ -19,14 +19,10 @@ public class JDKSerializer implements DataNodeSerializer { @Override public byte[] getBytes(T data) throws IOException { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - ObjectOutputStream oOut = new ObjectOutputStream(bOut); - try { + try (ObjectOutputStream oOut = new ObjectOutputStream(bOut)) { oOut.writeObject(data); return bOut.toByteArray(); } - finally { - oOut.close(); - } } @Override diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ExternalProjectsDataStorage.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ExternalProjectsDataStorage.java index f6bb7dcbec4b..3a834e1ea474 100644 --- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ExternalProjectsDataStorage.java +++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ExternalProjectsDataStorage.java @@ -342,22 +342,14 @@ public class ExternalProjectsDataStorage implements SettingsSavingComponent, Per }); } - DataOutputStream out = new DataOutputStream(new BufferedOutputStream(Files.newOutputStream(projectConfigurationFile))); - try { + try (DataOutputStream out = new DataOutputStream(new BufferedOutputStream(Files.newOutputStream(projectConfigurationFile)))) { out.writeUTF(STORAGE_VERSION); out.writeInt(externalProjects.size()); - ObjectOutputStream os = new ObjectOutputStream(out); - try { + try (ObjectOutputStream os = new ObjectOutputStream(out)) { for (InternalExternalProjectInfo externalProject : externalProjects) { os.writeObject(externalProject); } } - finally { - os.close(); - } - } - finally { - out.close(); } } @@ -384,15 +376,12 @@ public class ExternalProjectsDataStorage implements SettingsSavingComponent, Per throw new IOException("External projects data storage was invalidated"); } - DataInputStream in = new DataInputStream(new BufferedInputStream(Files.newInputStream(configurationFile))); - - try { + try (DataInputStream in = new DataInputStream(new BufferedInputStream(Files.newInputStream(configurationFile)))) { final String storage_version = in.readUTF(); if (!STORAGE_VERSION.equals(storage_version)) return projects; final int size = in.readInt(); - ObjectInputStream os = new ObjectInputStream(in); - try { + try (ObjectInputStream os = new ObjectInputStream(in)) { for (int i = 0; i < size; i++) { InternalExternalProjectInfo projectDataDataNode = (InternalExternalProjectInfo)os.readObject(); projects.add(projectDataDataNode); @@ -401,12 +390,6 @@ public class ExternalProjectsDataStorage implements SettingsSavingComponent, Per catch (Exception e) { throw new IOException(e); } - finally { - os.close(); - } - } - finally { - in.close(); } return projects; } diff --git a/platform/platform-api/src/com/intellij/ide/browsers/firefox/FirefoxUtil.java b/platform/platform-api/src/com/intellij/ide/browsers/firefox/FirefoxUtil.java index 4f4c94dd089a..49c842cf4f05 100644 --- a/platform/platform-api/src/com/intellij/ide/browsers/firefox/FirefoxUtil.java +++ b/platform/platform-api/src/com/intellij/ide/browsers/firefox/FirefoxUtil.java @@ -99,10 +99,7 @@ public class FirefoxUtil { return Collections.emptyList(); } - try { - BufferedReader reader; - reader = new BufferedReader(new FileReader(profilesFile)); - try { + try (BufferedReader reader = new BufferedReader(new FileReader(profilesFile))) { final List profiles = new SmartList<>(); boolean insideProfile = false; String currentName = null; @@ -147,16 +144,12 @@ public class FirefoxUtil { } else //noinspection SpellCheckingInspection if (name.equalsIgnoreCase("isrelative") && value.equals("1")) { - isRelative = true; - } + isRelative = true; + } } } return profiles; } - finally { - reader.close(); - } - } catch (IOException e) { LOG.info(e); return Collections.emptyList(); diff --git a/platform/platform-impl/src/com/intellij/ide/gdpr/ConsentOptions.java b/platform/platform-impl/src/com/intellij/ide/gdpr/ConsentOptions.java index c871bc375f7b..5a52441519d6 100644 --- a/platform/platform-impl/src/com/intellij/ide/gdpr/ConsentOptions.java +++ b/platform/platform-impl/src/com/intellij/ide/gdpr/ConsentOptions.java @@ -71,19 +71,14 @@ public final class ConsentOptions { @NotNull private String loadText(InputStream stream) { - try { - if (stream != null) { - final Reader reader = new InputStreamReader(CharsetToolkit.inputStreamSkippingBOM(new BufferedInputStream(stream)), StandardCharsets.UTF_8); - try { - return new String(FileUtil.adaptiveLoadText(reader)); - } - finally { - reader.close(); - } + if (stream != null) { + try (Reader reader = new InputStreamReader(CharsetToolkit.inputStreamSkippingBOM(new BufferedInputStream(stream)), + StandardCharsets.UTF_8)) { + return new String(FileUtil.adaptiveLoadText(reader)); + } + catch (IOException e) { + LOG.info(e); } - } - catch (IOException e) { - LOG.info(e); } return ""; } diff --git a/platform/platform-impl/src/com/intellij/ide/gdpr/EndUserAgreement.java b/platform/platform-impl/src/com/intellij/ide/gdpr/EndUserAgreement.java index 9558f88ba8bd..0f6a19f53dde 100644 --- a/platform/platform-impl/src/com/intellij/ide/gdpr/EndUserAgreement.java +++ b/platform/platform-impl/src/com/intellij/ide/gdpr/EndUserAgreement.java @@ -114,19 +114,14 @@ public final class EndUserAgreement { @NotNull private static Document loadContent(final String docName, InputStream stream) { - try { - if (stream != null) { - final Reader reader = new InputStreamReader(stream instanceof ByteArrayInputStream? stream : new BufferedInputStream(stream), StandardCharsets.UTF_8); - try { - return new Document(docName, new String(FileUtil.adaptiveLoadText(reader))); - } - finally { - reader.close(); - } + if (stream != null) { + try (Reader reader = new InputStreamReader(stream instanceof ByteArrayInputStream ? stream : new BufferedInputStream(stream), + StandardCharsets.UTF_8)) { + return new Document(docName, new String(FileUtil.adaptiveLoadText(reader))); + } + catch (IOException e) { + LOG.info(e); } - } - catch (IOException e) { - LOG.info(e); } return new Document(docName, ""); } @@ -195,23 +190,17 @@ public final class EndUserAgreement { @NotNull private static Version parseVersion(String text) { if (!StringUtil.isEmptyOrSpaces(text)) { - try { - final BufferedReader reader = new BufferedReader(new StringReader(text)); - try { - final String line = reader.readLine(); - if (line != null) { - final int startComment = line.indexOf(VERSION_COMMENT_START); - if (startComment >= 0 ) { - final int endComment = line.indexOf(VERSION_COMMENT_END); - if (endComment > startComment) { - return Version.fromString(line.substring(startComment + VERSION_COMMENT_START.length(), endComment).trim()); - } + try (BufferedReader reader = new BufferedReader(new StringReader(text))) { + final String line = reader.readLine(); + if (line != null) { + final int startComment = line.indexOf(VERSION_COMMENT_START); + if (startComment >= 0) { + final int endComment = line.indexOf(VERSION_COMMENT_END); + if (endComment > startComment) { + return Version.fromString(line.substring(startComment + VERSION_COMMENT_START.length(), endComment).trim()); } } } - finally { - reader.close(); - } } catch (IOException e) { LOG.info(e); diff --git a/platform/platform-impl/src/com/intellij/ide/plugins/RepositoryHelper.java b/platform/platform-impl/src/com/intellij/ide/plugins/RepositoryHelper.java index 2ae55077f5a2..4aabacbbde7c 100644 --- a/platform/platform-impl/src/com/intellij/ide/plugins/RepositoryHelper.java +++ b/platform/platform-impl/src/com/intellij/ide/plugins/RepositoryHelper.java @@ -153,7 +153,9 @@ public class RepositoryHelper { } } else { - return parsePluginList(request.getReader()); + try (BufferedReader reader = request.getReader()) { + return parsePluginList(reader); + } } }); @@ -207,7 +209,10 @@ public class RepositoryHelper { } private static List loadPluginList(File file) throws IOException { - return parsePluginList(new InputStreamReader(new BufferedInputStream(new FileInputStream(file)), CharsetToolkit.UTF8_CHARSET)); + try (InputStreamReader reader = new InputStreamReader(new BufferedInputStream(new FileInputStream(file)), + CharsetToolkit.UTF8_CHARSET)) { + return parsePluginList(reader); + } } private static List parsePluginList(Reader reader) throws IOException { @@ -220,9 +225,6 @@ public class RepositoryHelper { catch (ParserConfigurationException | SAXException | RuntimeException e) { throw new IOException(e); } - finally { - reader.close(); - } } private static List process(String repositoryUrl, List list) { diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/history/ImportedToGeneralTestEventsConverter.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/history/ImportedToGeneralTestEventsConverter.java index 536d938f9167..78e71035919f 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/history/ImportedToGeneralTestEventsConverter.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/history/ImportedToGeneralTestEventsConverter.java @@ -25,7 +25,6 @@ import com.intellij.openapi.vfs.CharsetToolkit; import org.jetbrains.annotations.NotNull; import org.xml.sax.InputSource; import org.xml.sax.SAXException; -import org.xml.sax.helpers.DefaultHandler; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; @@ -76,19 +75,12 @@ public class ImportedToGeneralTestEventsConverter extends OutputToGeneralTestEve } public static void parseTestResults(Supplier readerSupplier, GeneralTestEventsProcessor processor) throws IOException { - parseTestResults(readerSupplier.get(), ImportTestOutputExtension.findHandler(readerSupplier, processor)); - } - - public static void parseTestResults(Reader reader, final DefaultHandler contentHandler) throws IOException { - try { + try (Reader reader = readerSupplier.get()) { SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); - parser.parse(new InputSource(reader), contentHandler); + parser.parse(new InputSource(reader), ImportTestOutputExtension.findHandler(readerSupplier, processor)); } catch (ParserConfigurationException | SAXException e) { throw new IOException(e); } - finally { - reader.close(); - } } } diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/ChangesCacheFile.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/ChangesCacheFile.java index 803eb28743b2..511d24ccd24f 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/ChangesCacheFile.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/ChangesCacheFile.java @@ -300,8 +300,7 @@ public class ChangesCacheFile { private void loadHeader() throws IOException { if (!myHeaderLoaded) { - RandomAccessFile stream = new RandomAccessFile(myPath, "r"); - try { + try (RandomAccessFile stream = new RandomAccessFile(myPath, "r")) { int version = stream.readInt(); if (version != VERSION) { throw new VersionMismatchException(); @@ -318,9 +317,6 @@ public class ChangesCacheFile { myIncomingCount = stream.readInt(); assert stream.getFilePointer() == HEADER_SIZE; } - finally { - stream.close(); - } myHeaderLoaded = true; } } @@ -679,10 +675,9 @@ public class ChangesCacheFile { partialFile.delete(); } else if (accounted > 0) { - RandomAccessFile file = new RandomAccessFile(partialFile, "rw"); - try { + try (RandomAccessFile file = new RandomAccessFile(partialFile, "rw")) { file.writeInt(accounted); - for(Change c: data.accountedChanges) { + for (Change c : data.accountedChanges) { boolean isAfterRevision = true; ContentRevision revision = c.getAfterRevision(); if (revision == null) { @@ -694,9 +689,6 @@ public class ChangesCacheFile { file.writeUTF(revision.getFile().getIOFile().toString()); } } - finally { - file.close(); - } } } @@ -705,8 +697,7 @@ public class ChangesCacheFile { try { File partialFile = getPartialPath(data.indexEntry.offset); if (partialFile.exists()) { - RandomAccessFile file = new RandomAccessFile(partialFile, "r"); - try { + try (RandomAccessFile file = new RandomAccessFile(partialFile, "r")) { int count = file.readInt(); if (count > 0) { final Collection changes = data.changeList.getChanges(); @@ -720,14 +711,15 @@ public class ChangesCacheFile { afterPaths.put(FilePathsHelper.convertPath(change.getAfterRevision().getFile()), change); } } - for(int i=0; i, final String path, final List remainingPatches, CommitContext commitContext) { - try { - OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(path), CharsetToolkit.UTF8_CHARSET); - try { - UnifiedDiffWriter.write(project, remainingPatches, writer, "\n", commitContext); - } - finally { - writer.close(); - } + try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(path), CharsetToolkit.UTF8_CHARSET)) { + UnifiedDiffWriter.write(project, remainingPatches, writer, "\n", commitContext); } catch (IOException e) { LOG.error(e); diff --git a/platform/vcs-log/impl/test/com/intellij/vcs/log/impl/HashSerializeTest.java b/platform/vcs-log/impl/test/com/intellij/vcs/log/impl/HashSerializeTest.java index 0bb41480c4be..3b504df492a1 100644 --- a/platform/vcs-log/impl/test/com/intellij/vcs/log/impl/HashSerializeTest.java +++ b/platform/vcs-log/impl/test/com/intellij/vcs/log/impl/HashSerializeTest.java @@ -58,15 +58,11 @@ public class HashSerializeTest { @NotNull private static File writeToTempFile(@NotNull HashImpl... hashes) throws IOException { File file = FileUtil.createTempFile("", ""); - DataOutputStream out = new DataOutputStream(new FileOutputStream(file)); - try { + try (DataOutputStream out = new DataOutputStream(new FileOutputStream(file))) { for (HashImpl hash : hashes) { hash.write(out); } } - finally { - out.close(); - } return file; } diff --git a/platform/vcs-tests/src/com/intellij/testFramework/vcs/TestClientRunner.java b/platform/vcs-tests/src/com/intellij/testFramework/vcs/TestClientRunner.java index 9531f0e7003f..50b8bd186ef6 100644 --- a/platform/vcs-tests/src/com/intellij/testFramework/vcs/TestClientRunner.java +++ b/platform/vcs-tests/src/com/intellij/testFramework/vcs/TestClientRunner.java @@ -81,14 +81,10 @@ public class TestClientRunner { final Process clientProcess = builder.start(); if (stdin != null) { - final OutputStream outputStream = clientProcess.getOutputStream(); - try { + try (OutputStream outputStream = clientProcess.getOutputStream()) { final byte[] bytes = stdin.getBytes(); outputStream.write(bytes); } - finally { - outputStream.close(); - } } final CapturingProcessHandler handler = new CapturingProcessHandler(clientProcess, CharsetToolkit.getDefaultSystemCharset(), StringUtil.join(arguments, " ")); diff --git a/plugins/ByteCodeViewer/src/com/intellij/byteCodeViewer/ByteCodeViewerManager.java b/plugins/ByteCodeViewer/src/com/intellij/byteCodeViewer/ByteCodeViewerManager.java index ac99cb51af41..75538a3cf3d0 100644 --- a/plugins/ByteCodeViewer/src/com/intellij/byteCodeViewer/ByteCodeViewerManager.java +++ b/plugins/ByteCodeViewer/src/com/intellij/byteCodeViewer/ByteCodeViewerManager.java @@ -181,13 +181,9 @@ public class ByteCodeViewerManager extends DockablePopupManager entries) throws IOException { String encoding = GitConfigUtil.getLogEncoding(myProject, myRoot); - PrintWriter out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(myFile), encoding)); - try { + try (PrintWriter out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(myFile), encoding))) { for (GitRebaseEntry e : entries) { if (e.getAction() != GitRebaseEntry.Action.SKIP) { out.println(e.getAction().toString() + " " + e.getCommit() + " " + e.getSubject()); } } } - finally { - out.close(); - } } @NotNull diff --git a/plugins/git4idea/src/git4idea/rebase/GitRebaseUtils.java b/plugins/git4idea/src/git4idea/rebase/GitRebaseUtils.java index 349657ad9fd5..209b4c45d89c 100644 --- a/plugins/git4idea/src/git4idea/rebase/GitRebaseUtils.java +++ b/plugins/git4idea/src/git4idea/rebase/GitRebaseUtils.java @@ -223,24 +223,18 @@ public class GitRebaseUtils { File commitFile = new File(rebaseDir, String.format("%04d", next)); String hash = null; String subject = null; - try { - BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(commitFile), CharsetToolkit.UTF8_CHARSET)); - try { - String line; - while ((line = in.readLine()) != null) { - if (line.startsWith("From ")) { - hash = line.substring(5, 5 + 40); - } - if (line.startsWith("Subject: ")) { - subject = line.substring("Subject: ".length()); - } - if (hash != null && subject != null) { - break; - } + try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(commitFile), CharsetToolkit.UTF8_CHARSET))) { + String line; + while ((line = in.readLine()) != null) { + if (line.startsWith("From ")) { + hash = line.substring(5, 5 + 40); + } + if (line.startsWith("Subject: ")) { + subject = line.substring("Subject: ".length()); + } + if (hash != null && subject != null) { + break; } - } - finally { - in.close(); } } catch (Exception e) { diff --git a/plugins/git4idea/src/git4idea/ui/GitTagDialog.java b/plugins/git4idea/src/git4idea/ui/GitTagDialog.java index d72181c7be27..1d4756fe1e8f 100644 --- a/plugins/git4idea/src/git4idea/ui/GitTagDialog.java +++ b/plugins/git4idea/src/git4idea/ui/GitTagDialog.java @@ -161,13 +161,9 @@ public class GitTagDialog extends DialogWrapper { try { messageFile = FileUtil.createTempFile(MESSAGE_FILE_PREFIX, MESSAGE_FILE_SUFFIX); messageFile.deleteOnExit(); - Writer out = new OutputStreamWriter(new FileOutputStream(messageFile), MESSAGE_FILE_ENCODING); - try { + try (Writer out = new OutputStreamWriter(new FileOutputStream(messageFile), MESSAGE_FILE_ENCODING)) { out.write(message); } - finally { - out.close(); - } } catch (IOException ex) { Messages.showErrorDialog(myProject, GitBundle.message("tag.error.creating.message.file.message", ex.toString()), diff --git a/plugins/github/src/org/jetbrains/plugins/github/api/GithubConnection.java b/plugins/github/src/org/jetbrains/plugins/github/api/GithubConnection.java index 7e799132d5d4..8967fb28a0e9 100644 --- a/plugins/github/src/org/jetbrains/plugins/github/api/GithubConnection.java +++ b/plugins/github/src/org/jetbrains/plugins/github/api/GithubConnection.java @@ -298,16 +298,12 @@ public class GithubConnection { @NotNull private static JsonElement parseResponse(@NotNull InputStream githubResponse) throws IOException { - Reader reader = new InputStreamReader(githubResponse, CharsetToolkit.UTF8_CHARSET); - try { + try (Reader reader = new InputStreamReader(githubResponse, CharsetToolkit.UTF8_CHARSET)) { return new JsonParser().parse(reader); } catch (JsonParseException jse) { throw new GithubJsonException("Couldn't parse GitHub response", jse); } - finally { - reader.close(); - } } public static abstract class PagedRequestBase implements PagedRequest { diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/config/AbstractConfigUtils.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/config/AbstractConfigUtils.java index d6ff18232d04..18a6bc7dc586 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/config/AbstractConfigUtils.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/config/AbstractConfigUtils.java @@ -98,20 +98,15 @@ public abstract class AbstractConfigUtils { if (jars.length > 1) { Arrays.sort(jars); } - JarFile jarFile = new JarFile(jars[0]); - try { + try (JarFile jarFile = new JarFile(jars[0])) { JarEntry jarEntry = jarFile.getJarEntry(manifestPath); if (jarEntry == null) { return null; } - final InputStream inputStream = jarFile.getInputStream(jarEntry); Manifest manifest; - try { + try (InputStream inputStream = jarFile.getInputStream(jarEntry)) { manifest = new Manifest(inputStream); } - finally { - inputStream.close(); - } final String version = manifest.getMainAttributes().getValue(Attributes.Name.IMPLEMENTATION_VERSION); if (version != null) { return version; @@ -128,9 +123,6 @@ public abstract class AbstractConfigUtils { } return null; } - finally { - jarFile.close(); - } } catch (Exception e) { LOG.debug(e); diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/execution/SocketServer.java b/plugins/hg4idea/src/org/zmlx/hg4idea/execution/SocketServer.java index 35b323e7b244..8e02770b4748 100644 --- a/plugins/hg4idea/src/org/zmlx/hg4idea/execution/SocketServer.java +++ b/plugins/hg4idea/src/org/zmlx/hg4idea/execution/SocketServer.java @@ -42,13 +42,9 @@ public class SocketServer { try { boolean _continue = true; while (_continue) { - Socket socket = myServerSocket.accept(); - try { + try (Socket socket = myServerSocket.accept()) { _continue = myProtocol.handleConnection(socket); } - finally { - socket.close(); - } } } catch (SocketException e) { diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/repo/HgRepositoryReader.java b/plugins/hg4idea/src/org/zmlx/hg4idea/repo/HgRepositoryReader.java index d9924bab68cc..4d366e0d4250 100644 --- a/plugins/hg4idea/src/org/zmlx/hg4idea/repo/HgRepositoryReader.java +++ b/plugins/hg4idea/src/org/zmlx/hg4idea/repo/HgRepositoryReader.java @@ -117,13 +117,9 @@ public class HgRepositoryReader { @NotNull private static byte[] readHashBytesFromFile(@NotNull File file) throws IOException { byte[] bytes; - final InputStream stream = new FileInputStream(file); - try { + try (InputStream stream = new FileInputStream(file)) { bytes = FileUtil.loadBytes(stream, 20); } - finally { - stream.close(); - } return bytes; } diff --git a/plugins/hg4idea/testSrc/org/zmlx/hg4idea/test/HgAnnotateCommandTest.java b/plugins/hg4idea/testSrc/org/zmlx/hg4idea/test/HgAnnotateCommandTest.java index cd80a8886f3e..f6d46966ef06 100644 --- a/plugins/hg4idea/testSrc/org/zmlx/hg4idea/test/HgAnnotateCommandTest.java +++ b/plugins/hg4idea/testSrc/org/zmlx/hg4idea/test/HgAnnotateCommandTest.java @@ -46,12 +46,8 @@ public class HgAnnotateCommandTest extends HgSingleUserTest { final File etalonFile = new File(myAnnotateDataDir, "etalon"); XStream xStream = new XStream(); - FileReader reader = new FileReader(etalonFile); - try { - myAnnotations = (List) xStream.fromXML(reader); - } - finally { - reader.close(); + try (FileReader reader = new FileReader(etalonFile)) { + myAnnotations = (List)xStream.fromXML(reader); } } @@ -105,13 +101,9 @@ public class HgAnnotateCommandTest extends HgSingleUserTest { } XStream xStream = new XStream(); - FileWriter writer = new FileWriter(etalonFile); - try { + try (FileWriter writer = new FileWriter(etalonFile)) { xStream.toXML(annotationLines, writer); } - finally { - writer.close(); - } } diff --git a/spellchecker/src/com/intellij/spellchecker/generator/SpellCheckerDictionaryGenerator.java b/spellchecker/src/com/intellij/spellchecker/generator/SpellCheckerDictionaryGenerator.java index 8a7820035c90..3b7c44b58f0f 100644 --- a/spellchecker/src/com/intellij/spellchecker/generator/SpellCheckerDictionaryGenerator.java +++ b/spellchecker/src/com/intellij/spellchecker/generator/SpellCheckerDictionaryGenerator.java @@ -128,16 +128,10 @@ public abstract class SpellCheckerDictionaryGenerator { } builder.append(name); } - try { - final File dictionaryFile = new File(outFile); - FileUtil.createIfDoesntExist(dictionaryFile); - final FileWriter writer = new FileWriter(dictionaryFile.getPath()); - try { - writer.write(builder.toString()); - } - finally { - writer.close(); - } + final File dictionaryFile = new File(outFile); + FileUtil.createIfDoesntExist(dictionaryFile); + try (FileWriter writer = new FileWriter(dictionaryFile.getPath())) { + writer.write(builder.toString()); } catch (IOException e) { LOG.error(e); diff --git a/spellchecker/testSrc/com/intellij/spellchecker/inspector/SplitterTest.java b/spellchecker/testSrc/com/intellij/spellchecker/inspector/SplitterTest.java index b94bdd8c4f73..ea199e49201e 100644 --- a/spellchecker/testSrc/com/intellij/spellchecker/inspector/SplitterTest.java +++ b/spellchecker/testSrc/com/intellij/spellchecker/inspector/SplitterTest.java @@ -434,16 +434,10 @@ public class SplitterTest { if (is != null) { StringBuilder sb = new StringBuilder(); - try { - BufferedReader reader = new BufferedReader(new InputStreamReader(is, CharsetToolkit.UTF8_CHARSET)); - try { - String line; - while ((line = reader.readLine()) != null) { - sb.append(line).append('\n'); - } - } - finally { - reader.close(); + try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, CharsetToolkit.UTF8_CHARSET))) { + String line; + while ((line = reader.readLine()) != null) { + sb.append(line).append('\n'); } } catch (Exception e) {