From 8983be48591f6486932af6ba18c7640e31bad7b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Kubitz?= Date: Tue, 6 Jun 2023 09:52:10 +0200 Subject: [PATCH] use try-with-resource and java.io.InputStream convenience methods --- .../internal/boot/PlatformURLConnection.java | 35 +--- .../org/eclipse/equinox/launcher/Main.java | 54 +++-- .../core/internal/registry/TableWriter.java | 195 +++++++++--------- .../servletbridge/FrameworkLauncher.java | 22 +- .../internal/transforms/CSVParser.java | 63 +++--- .../xslt/XSLTStreamTransformer.java | 3 +- .../internal/debug/EclipseDebugTrace.java | 10 +- .../internal/location/EquinoxLocations.java | 4 +- .../osgi/internal/log/EquinoxLogWriter.java | 23 +-- .../src/org/eclipse/osgi/storage/Storage.java | 84 ++++---- 10 files changed, 221 insertions(+), 272 deletions(-) diff --git a/bundles/org.eclipse.equinox.common/src/org/eclipse/core/internal/boot/PlatformURLConnection.java b/bundles/org.eclipse.equinox.common/src/org/eclipse/core/internal/boot/PlatformURLConnection.java index 424683e004a..9139125c93f 100644 --- a/bundles/org.eclipse.equinox.common/src/org/eclipse/core/internal/boot/PlatformURLConnection.java +++ b/bundles/org.eclipse.equinox.common/src/org/eclipse/core/internal/boot/PlatformURLConnection.java @@ -47,7 +47,6 @@ public abstract class PlatformURLConnection extends URLConnection { private static String filePrefix; // constants - private static final int BUF_SIZE = 32768; private static final Object NOT_FOUND = new Object(); // marker private static final String CACHE_PROP = ".cache.properties"; //$NON-NLS-1$ private static final String CACHE_LOCATION_PROP = "location"; //$NON-NLS-1$ @@ -148,7 +147,6 @@ private void copyToCache() throws IOException { src = new URL(tmp); } else src = resolvedURL; - InputStream srcis = null; // cache target String tgt; @@ -163,13 +161,10 @@ private void copyToCache() throws IOException { tgt = tmp; } else tgt = cachedURL.getFile(); - File tgtFile = null; - FileOutputStream tgtos = null; - boolean error = false; long total = 0; - try { + try (InputStream srcis = src.openStream()) { if (DEBUG && DEBUG_CACHE_COPY) { if (isJar) debug("Caching jar as " + tgt); //$NON-NLS-1$ @@ -177,26 +172,12 @@ private void copyToCache() throws IOException { debug("Caching as " + tgt); //$NON-NLS-1$ } - srcis = src.openStream(); - byte[] buf = new byte[BUF_SIZE]; - int count = srcis.read(buf); - - tgtFile = new File(tgt); - tgtos = new FileOutputStream(tgtFile); - - while (count != -1) { - total += count; - tgtos.write(buf, 0, count); - count = srcis.read(buf); + File tgtFile = new File(tgt); + try (FileOutputStream tgtos = new FileOutputStream(tgtFile)) { + srcis.transferTo(tgtos); + tgtos.flush(); + tgtos.getFD().sync(); } - - srcis.close(); - srcis = null; - tgtos.flush(); - tgtos.getFD().sync(); - tgtos.close(); - tgtos = null; - // add cache entry cacheIndex.put(key, tgt); isInCache = true; @@ -210,10 +191,6 @@ private void copyToCache() throws IOException { } finally { if (!error && DEBUG && DEBUG_CACHE_COPY) debug(total + " bytes copied"); //$NON-NLS-1$ - if (srcis != null) - srcis.close(); - if (tgtos != null) - tgtos.close(); } } diff --git a/bundles/org.eclipse.equinox.launcher/src/org/eclipse/equinox/launcher/Main.java b/bundles/org.eclipse.equinox.launcher/src/org/eclipse/equinox/launcher/Main.java index 3cb2fab5375..cd693bb4eb1 100644 --- a/bundles/org.eclipse.equinox.launcher/src/org/eclipse/equinox/launcher/Main.java +++ b/bundles/org.eclipse.equinox.launcher/src/org/eclipse/equinox/launcher/Main.java @@ -508,39 +508,31 @@ private String getLibraryFromFragment(String fragment) { if (frag.isDirectory()) return searchFor("eclipse", fragment); //$NON-NLS-1$; - ZipFile fragmentJar = null; - try { - fragmentJar = new ZipFile(frag); - } catch (IOException e) { - log("Exception opening JAR file: " + fragment); //$NON-NLS-1$ - log(e); - return null; - } - - Enumeration entries = fragmentJar.entries(); - String entry = null; - while (entries.hasMoreElements()) { - ZipEntry zipEntry = entries.nextElement(); - if (zipEntry.getName().startsWith("eclipse_")) { //$NON-NLS-1$ - entry = zipEntry.getName(); - try { - fragmentJar.close(); - } catch (IOException e) { - //ignore + try (ZipFile fragmentJar = new ZipFile(frag)) { + Enumeration entries = fragmentJar.entries(); + String entry = null; + while (entries.hasMoreElements()) { + ZipEntry zipEntry = entries.nextElement(); + if (zipEntry.getName().startsWith("eclipse_")) { //$NON-NLS-1$ + entry = zipEntry.getName(); + break; } - break; } - } - if (entry != null) { - String lib = extractFromJAR(fragment, entry); - if (!getOS().equals("win32")) { //$NON-NLS-1$ - try { - Runtime.getRuntime().exec(new String[] {"chmod", "755", lib}).waitFor(); //$NON-NLS-1$ //$NON-NLS-2$ - } catch (Throwable e) { - //ignore + if (entry != null) { + String lib = extractFromJAR(fragment, entry); + if (!getOS().equals("win32")) { //$NON-NLS-1$ + try { + Runtime.getRuntime().exec(new String[] {"chmod", "755", lib}).waitFor(); //$NON-NLS-1$ //$NON-NLS-2$ + } catch (Throwable e) { + //ignore + } } + return lib; } - return lib; + } catch (IOException e) { + log("Exception opening JAR file: " + fragment); //$NON-NLS-1$ + log(e); + return null; } return null; } @@ -1342,8 +1334,8 @@ private String computeDefaultUserAreaLocation(String pathAppendage) { File eclipseProduct = new File(installDir, PRODUCT_SITE_MARKER); if (eclipseProduct.exists()) { Properties props = new Properties(); - try { - props.load(new FileInputStream(eclipseProduct)); + try (FileInputStream inStream = new FileInputStream(eclipseProduct)) { + props.load(inStream); String appId = props.getProperty(PRODUCT_SITE_ID); if (appId == null || appId.trim().length() == 0) appId = ECLIPSE; diff --git a/bundles/org.eclipse.equinox.registry/src/org/eclipse/core/internal/registry/TableWriter.java b/bundles/org.eclipse.equinox.registry/src/org/eclipse/core/internal/registry/TableWriter.java index 18643477009..93abb253794 100644 --- a/bundles/org.eclipse.equinox.registry/src/org/eclipse/core/internal/registry/TableWriter.java +++ b/bundles/org.eclipse.equinox.registry/src/org/eclipse/core/internal/registry/TableWriter.java @@ -156,42 +156,42 @@ private void saveExtensionRegistry(long timestamp) throws IOException { } private void saveContributions(KeyedHashSet[] contributions) throws IOException { - FileOutputStream fosNamespace = new FileOutputStream(contributionsFile); - DataOutputStream outputNamespace = new DataOutputStream(new BufferedOutputStream(fosNamespace)); - KeyedElement[] newElements = contributions[0].elements(); - KeyedElement[] formerElements = contributions[1].elements(); - - // get count of contributions that will be cached - int cacheSize = 0; - for (KeyedElement newElement : newElements) { - if (((Contribution) newElement).shouldPersist()) { - cacheSize++; + try (FileOutputStream fosNamespace = new FileOutputStream(contributionsFile); + DataOutputStream outputNamespace = new DataOutputStream(new BufferedOutputStream(fosNamespace))) { + KeyedElement[] newElements = contributions[0].elements(); + KeyedElement[] formerElements = contributions[1].elements(); + + // get count of contributions that will be cached + int cacheSize = 0; + for (KeyedElement newElement : newElements) { + if (((Contribution) newElement).shouldPersist()) { + cacheSize++; + } } - } - for (KeyedElement formerElement : formerElements) { - if (((Contribution) formerElement).shouldPersist()) { - cacheSize++; + for (KeyedElement formerElement : formerElements) { + if (((Contribution) formerElement).shouldPersist()) { + cacheSize++; + } } - } - outputNamespace.writeInt(cacheSize); + outputNamespace.writeInt(cacheSize); - for (KeyedElement newElement : newElements) { - Contribution element = (Contribution) newElement; - if (element.shouldPersist()) { - writeStringOrNull(element.getContributorId(), outputNamespace); - saveArray(filterContributionChildren(element), outputNamespace); + for (KeyedElement newElement : newElements) { + Contribution element = (Contribution) newElement; + if (element.shouldPersist()) { + writeStringOrNull(element.getContributorId(), outputNamespace); + saveArray(filterContributionChildren(element), outputNamespace); + } } - } - for (KeyedElement formerElement : formerElements) { - Contribution element = (Contribution) formerElement; - if (element.shouldPersist()) { - writeStringOrNull(element.getContributorId(), outputNamespace); - saveArray(filterContributionChildren(element), outputNamespace); + for (KeyedElement formerElement : formerElements) { + Contribution element = (Contribution) formerElement; + if (element.shouldPersist()) { + writeStringOrNull(element.getContributorId(), outputNamespace); + saveArray(filterContributionChildren(element), outputNamespace); + } } + outputNamespace.flush(); + fosNamespace.getFD().sync(); } - outputNamespace.flush(); - fosNamespace.getFD().sync(); - outputNamespace.close(); } // Contribution has raw children in a unique format that combines extensions and extension points. @@ -208,65 +208,70 @@ private int[] filterContributionChildren(Contribution element) { } private void saveNamespaces(KeyedHashSet namespacesIndex) throws IOException { - FileOutputStream fosNamespace = new FileOutputStream(namespacesFile); - DataOutputStream outputNamespace = new DataOutputStream(new BufferedOutputStream(fosNamespace)); - KeyedElement[] elements = namespacesIndex.elements(); - - KeyedElement[] cachedElements = new KeyedElement[elements.length]; - int cacheSize = 0; - for (KeyedElement e : elements) { - RegistryIndexElement element = (RegistryIndexElement) e; - int[] extensionPoints = filter(element.getExtensionPoints()); - int[] extensions = filter(element.getExtensions()); - if (extensionPoints.length == 0 && extensions.length == 0) - continue; - RegistryIndexElement cachedElement = new RegistryIndexElement((String) element.getKey(), extensionPoints, extensions); - cachedElements[cacheSize] = cachedElement; - cacheSize++; - } + try (FileOutputStream fosNamespace = new FileOutputStream(namespacesFile); + DataOutputStream outputNamespace = new DataOutputStream(new BufferedOutputStream(fosNamespace))) { + KeyedElement[] elements = namespacesIndex.elements(); + + KeyedElement[] cachedElements = new KeyedElement[elements.length]; + int cacheSize = 0; + for (KeyedElement e : elements) { + RegistryIndexElement element = (RegistryIndexElement) e; + int[] extensionPoints = filter(element.getExtensionPoints()); + int[] extensions = filter(element.getExtensions()); + if (extensionPoints.length == 0 && extensions.length == 0) + continue; + RegistryIndexElement cachedElement = new RegistryIndexElement((String) element.getKey(), + extensionPoints, extensions); + cachedElements[cacheSize] = cachedElement; + cacheSize++; + } - outputNamespace.writeInt(cacheSize); - for (int i = 0; i < cacheSize; i++) { - RegistryIndexElement element = (RegistryIndexElement) cachedElements[i]; - writeStringOrNull((String) element.getKey(), outputNamespace); - saveArray(element.getExtensionPoints(), outputNamespace); // it was pre-filtered as we counted the number of elements - saveArray(element.getExtensions(), outputNamespace); // it was pre-filtered as we counted the number of elements + outputNamespace.writeInt(cacheSize); + for (int i = 0; i < cacheSize; i++) { + RegistryIndexElement element = (RegistryIndexElement) cachedElements[i]; + writeStringOrNull((String) element.getKey(), outputNamespace); + saveArray(element.getExtensionPoints(), outputNamespace); // it was pre-filtered as we counted the + // number of + // elements + saveArray(element.getExtensions(), outputNamespace); // it was pre-filtered as we counted the number of + // elements + } + outputNamespace.flush(); + fosNamespace.getFD().sync(); } - outputNamespace.flush(); - fosNamespace.getFD().sync(); - outputNamespace.close(); } private void saveContributors(HashMap contributors) throws IOException { - FileOutputStream fosContributors = new FileOutputStream(contributorsFile); - DataOutputStream outputContributors = new DataOutputStream(new BufferedOutputStream(fosContributors)); - - Collection entries = contributors.values(); - outputContributors.writeInt(entries.size()); - - for (Object entry : entries) { - RegistryContributor contributor = (RegistryContributor) entry; - writeStringOrNull(contributor.getActualId(), outputContributors); - writeStringOrNull(contributor.getActualName(), outputContributors); - writeStringOrNull(contributor.getId(), outputContributors); - writeStringOrNull(contributor.getName(), outputContributors); - } + try (FileOutputStream fosContributors = new FileOutputStream(contributorsFile); + DataOutputStream outputContributors = new DataOutputStream(new BufferedOutputStream(fosContributors))) { + + Collection entries = contributors.values(); + outputContributors.writeInt(entries.size()); + + for (Object entry : entries) { + RegistryContributor contributor = (RegistryContributor) entry; + writeStringOrNull(contributor.getActualId(), outputContributors); + writeStringOrNull(contributor.getActualName(), outputContributors); + writeStringOrNull(contributor.getId(), outputContributors); + writeStringOrNull(contributor.getName(), outputContributors); + } - outputContributors.flush(); - fosContributors.getFD().sync(); - outputContributors.close(); + outputContributors.flush(); + fosContributors.getFD().sync(); + outputContributors.close(); + } } private void saveTables(long registryTimeStamp) throws IOException { - FileOutputStream fosTable = new FileOutputStream(tableFile); - DataOutputStream outputTable = new DataOutputStream(new BufferedOutputStream(fosTable)); - writeCacheHeader(outputTable, registryTimeStamp); - outputTable.writeInt(objectManager.getNextId()); - offsets.save(outputTable); - objectManager.getExtensionPoints().save(outputTable, objectManager); // uses writer to filter contents - outputTable.flush(); - fosTable.getFD().sync(); - outputTable.close(); + try (FileOutputStream fosTable = new FileOutputStream(tableFile); + DataOutputStream outputTable = new DataOutputStream(new BufferedOutputStream(fosTable))) { + writeCacheHeader(outputTable, registryTimeStamp); + outputTable.writeInt(objectManager.getNextId()); + offsets.save(outputTable); + objectManager.getExtensionPoints().save(outputTable, objectManager); // uses writer to filter contents + outputTable.flush(); + fosTable.getFD().sync(); + } } private void writeCacheHeader(DataOutputStream output, long registryTimeStamp) throws IOException { @@ -444,21 +449,23 @@ private void saveOrphans() throws IOException { if (filteredValue.length != 0) filteredOrphans.put(entry.getKey(), filteredValue); } - FileOutputStream fosOrphan = new FileOutputStream(orphansFile); - DataOutputStream outputOrphan = new DataOutputStream(new BufferedOutputStream(fosOrphan)); - outputOrphan.writeInt(filteredOrphans.size()); - Set> elements = filteredOrphans.entrySet(); - for (Entry entry : elements) { - outputOrphan.writeUTF(entry.getKey()); - saveArray(entry.getValue(), outputOrphan); - } - for (Entry entry : elements) { - mainOutput.writeInt(entry.getValue().length); - saveExtensions((IExtension[]) objectManager.getHandles(entry.getValue(), RegistryObjectManager.EXTENSION), mainOutput); + try (FileOutputStream fosOrphan = new FileOutputStream(orphansFile); + DataOutputStream outputOrphan = new DataOutputStream(new BufferedOutputStream(fosOrphan))) { + outputOrphan.writeInt(filteredOrphans.size()); + Set> elements = filteredOrphans.entrySet(); + for (Entry entry : elements) { + outputOrphan.writeUTF(entry.getKey()); + saveArray(entry.getValue(), outputOrphan); + } + for (Entry entry : elements) { + mainOutput.writeInt(entry.getValue().length); + saveExtensions( + (IExtension[]) objectManager.getHandles(entry.getValue(), RegistryObjectManager.EXTENSION), + mainOutput); + } + outputOrphan.flush(); + fosOrphan.getFD().sync(); } - outputOrphan.flush(); - fosOrphan.getFD().sync(); - outputOrphan.close(); } private void log(Status status) { diff --git a/bundles/org.eclipse.equinox.servletbridge/src/org/eclipse/equinox/servletbridge/FrameworkLauncher.java b/bundles/org.eclipse.equinox.servletbridge/src/org/eclipse/equinox/servletbridge/FrameworkLauncher.java index 7a33a715207..e788291b623 100644 --- a/bundles/org.eclipse.equinox.servletbridge/src/org/eclipse/equinox/servletbridge/FrameworkLauncher.java +++ b/bundles/org.eclipse.equinox.servletbridge/src/org/eclipse/equinox/servletbridge/FrameworkLauncher.java @@ -20,6 +20,8 @@ import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; import java.security.*; import java.util.*; import java.util.jar.*; @@ -776,25 +778,11 @@ protected void copyResource(String resourcePath, File target) { } else { try { if (target.createNewFile()) { - InputStream is = null; - OutputStream os = null; - try { - is = context.getResourceAsStream(resourcePath); - if (is == null) + try (InputStream is = context.getResourceAsStream(resourcePath)){ + if (is == null) { return; - os = new FileOutputStream(target); - byte[] buffer = new byte[8192]; - int bytesRead = is.read(buffer); - while (bytesRead != -1) { - os.write(buffer, 0, bytesRead); - bytesRead = is.read(buffer); } - } finally { - if (is != null) - is.close(); - - if (os != null) - os.close(); + Files.copy(is, target.toPath(), StandardCopyOption.REPLACE_EXISTING); } } } catch (IOException e) { diff --git a/bundles/org.eclipse.equinox.transforms.hook/src/org/eclipse/equinox/internal/transforms/CSVParser.java b/bundles/org.eclipse.equinox.transforms.hook/src/org/eclipse/equinox/internal/transforms/CSVParser.java index 50a70bec1d8..f54925eec1d 100644 --- a/bundles/org.eclipse.equinox.transforms.hook/src/org/eclipse/equinox/internal/transforms/CSVParser.java +++ b/bundles/org.eclipse.equinox.transforms.hook/src/org/eclipse/equinox/internal/transforms/CSVParser.java @@ -39,41 +39,44 @@ public class CSVParser { * @throws IOException thrown if there are issues parsing the file */ public static TransformTuple[] parse(URL transformMapURL, EquinoxLogServices logServices) throws IOException { - BufferedReader reader = new BufferedReader(new InputStreamReader(transformMapURL.openStream())); - String currentLine = null; List list = new ArrayList<>(); - while ((currentLine = reader.readLine()) != null) { - if (currentLine.startsWith("#")) { //$NON-NLS-1$ - continue; - } - currentLine = currentLine.trim(); - if (currentLine.length() == 0) - continue; - StringTokenizer toker = new StringTokenizer(currentLine, ","); //$NON-NLS-1$ - try { - String bundlePatternString = toker.nextToken().trim(); - String pathPatternString = toker.nextToken().trim(); - String transformPath = toker.nextToken().trim(); + try (BufferedReader reader = new BufferedReader(new InputStreamReader(transformMapURL.openStream()))) { + String currentLine = null; + while ((currentLine = reader.readLine()) != null) { + if (currentLine.startsWith("#")) { //$NON-NLS-1$ + continue; + } + currentLine = currentLine.trim(); + if (currentLine.length() == 0) + continue; + StringTokenizer toker = new StringTokenizer(currentLine, ","); //$NON-NLS-1$ try { - Pattern bundlePattern = Pattern.compile(bundlePatternString); - Pattern pathPattern = Pattern.compile(pathPatternString); - URL transformerURL = new URL(transformMapURL, transformPath); + String bundlePatternString = toker.nextToken().trim(); + String pathPatternString = toker.nextToken().trim(); + String transformPath = toker.nextToken().trim(); try { - transformerURL.openStream(); - TransformTuple tuple = new TransformTuple(); - tuple.bundlePattern = bundlePattern; - tuple.pathPattern = pathPattern; - tuple.transformerUrl = transformerURL; - list.add(tuple); - } catch (IOException e) { - logServices.log(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, "Could not add transform :" + transformerURL.toString(), e); //$NON-NLS-1$ + Pattern bundlePattern = Pattern.compile(bundlePatternString); + Pattern pathPattern = Pattern.compile(pathPatternString); + URL transformerURL = new URL(transformMapURL, transformPath); + try (InputStream exitsCheck = transformerURL.openStream()) { + TransformTuple tuple = new TransformTuple(); + tuple.bundlePattern = bundlePattern; + tuple.pathPattern = pathPattern; + tuple.transformerUrl = transformerURL; + list.add(tuple); + } catch (IOException e) { + logServices.log(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, + "Could not add transform :" + transformerURL.toString(), e); //$NON-NLS-1$ + } + } catch (PatternSyntaxException e) { + logServices.log(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, + "Could not add compile transform matching regular expression", e); //$NON-NLS-1$ } - } catch (PatternSyntaxException e) { - logServices.log(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, "Could not add compile transform matching regular expression", e); //$NON-NLS-1$ - } - } catch (NoSuchElementException e) { - logServices.log(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, "Could not parse transform file record :" + currentLine, e); //$NON-NLS-1$ + } catch (NoSuchElementException e) { + logServices.log(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, + "Could not parse transform file record :" + currentLine, e); //$NON-NLS-1$ + } } } return list.toArray(new TransformTuple[list.size()]); diff --git a/bundles/org.eclipse.equinox.transforms.xslt/src/org/eclipse/equinox/internal/transforms/xslt/XSLTStreamTransformer.java b/bundles/org.eclipse.equinox.transforms.xslt/src/org/eclipse/equinox/internal/transforms/xslt/XSLTStreamTransformer.java index fcd8b1d7e1b..393d524af2b 100644 --- a/bundles/org.eclipse.equinox.transforms.xslt/src/org/eclipse/equinox/internal/transforms/xslt/XSLTStreamTransformer.java +++ b/bundles/org.eclipse.equinox.transforms.xslt/src/org/eclipse/equinox/internal/transforms/xslt/XSLTStreamTransformer.java @@ -144,8 +144,7 @@ private synchronized Templates getTemplate(URL transformerURL) { if (templates != null) return templates; - try { - InputStream xsltStream = transformerURL.openStream(); + try (InputStream xsltStream = transformerURL.openStream()) { TransformerFactory tFactory = null; try { tFactory = TransformerFactory.newInstance(); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/debug/EclipseDebugTrace.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/debug/EclipseDebugTrace.java index 2607e94f706..e5cc211dcd0 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/debug/EclipseDebugTrace.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/debug/EclipseDebugTrace.java @@ -504,16 +504,10 @@ private final String getFormattedThrowable(Throwable error) { String result = null; if (error != null) { - PrintStream throwableStream = null; - try { - ByteArrayOutputStream throwableByteOutputStream = new ByteArrayOutputStream(); - throwableStream = new PrintStream(throwableByteOutputStream, false); + ByteArrayOutputStream throwableByteOutputStream = new ByteArrayOutputStream(); + try (PrintStream throwableStream = new PrintStream(throwableByteOutputStream, false)) { error.printStackTrace(throwableStream); result = encodeText(throwableByteOutputStream.toString()); - } finally { - if (throwableStream != null) { - throwableStream.close(); - } } } return result; diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/location/EquinoxLocations.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/location/EquinoxLocations.java index 53a7ddb1ad6..9773a0846f8 100755 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/location/EquinoxLocations.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/location/EquinoxLocations.java @@ -304,8 +304,8 @@ private String computeDefaultUserAreaLocation(String pathAppendage) { File eclipseProduct = new File(installDir, PRODUCT_SITE_MARKER); if (eclipseProduct.exists()) { Properties props = new Properties(); - try { - props.load(new FileInputStream(eclipseProduct)); + try (FileInputStream productStream = new FileInputStream(eclipseProduct)) { + props.load(productStream); String appId = props.getProperty(PRODUCT_SITE_ID); if (appId == null || appId.trim().length() == 0) appId = ECLIPSE; diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/EquinoxLogWriter.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/EquinoxLogWriter.java index 57e5d0bec09..b0aee6d42f5 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/EquinoxLogWriter.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/EquinoxLogWriter.java @@ -367,33 +367,24 @@ private void setOutput(File newOutFile, Writer newWriter, boolean append) { File oldOutFile = this.outFile; this.outFile = newOutFile; this.writer = newWriter; - boolean copyFailed = false; if (append && oldOutFile != null && oldOutFile.isFile()) { - Reader fileIn = null; - try { - openFile(); - fileIn = new InputStreamReader(ExtendedLogServiceFactory.secureAction.getFileInputStream(oldOutFile), StandardCharsets.UTF_8); + openFile(); + try (Reader fileIn = new InputStreamReader( + ExtendedLogServiceFactory.secureAction.getFileInputStream(oldOutFile), + StandardCharsets.UTF_8)) { copyReader(fileIn, this.writer); + // delete the old file if copying didn't fail + oldOutFile.delete(); } catch (IOException e) { - copyFailed = true; e.printStackTrace(); } finally { - if (fileIn != null) { - try { - fileIn.close(); - } catch (IOException e) { - e.printStackTrace(); - } - // delete the old file if copying didn't fail - if (!copyFailed) - oldOutFile.delete(); - } closeFile(); } } } } + /* XXX from JDK >=9 better use: reader.transferTo(this.aWriter); */ private void copyReader(Reader reader, Writer aWriter) throws IOException { char buffer[] = new char[1024]; int count; diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/Storage.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/Storage.java index 0c45927e54e..5d980c34a43 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/Storage.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/Storage.java @@ -1740,29 +1740,13 @@ private Properties findVMProfile(Generation systemGeneration) { result = new Properties(); vmProfile = JAVASE + embeddedProfileName + javaSpecVersion; - InputStream profileIn = null; - if (vmProfile != null) { - // look for a profile in the system bundle based on the vm profile - String javaProfile = vmProfile + PROFILE_EXT; - profileIn = findInSystemBundle(systemGeneration, javaProfile); - if (profileIn == null) - profileIn = getNextBestProfile(systemGeneration, JAVASE, runtimeVersion, embeddedProfileName); - } - if (profileIn == null) - // the profile url is still null then use the min profile the framework can use - profileIn = findInSystemBundle(systemGeneration, "JavaSE-1.8.profile"); //$NON-NLS-1$ - if (profileIn != null) { - try { - result.load(new BufferedInputStream(profileIn)); - } catch (IOException e) { - // TODO consider logging ... - } finally { - try { - profileIn.close(); - } catch (IOException ee) { - // do nothing - } + try (InputStream profileIn = createProfileStream(systemGeneration, vmProfile, embeddedProfileName)) { + if (profileIn != null) { + result.load(profileIn); } + } catch (IOException e) { + // ignore + // TODO consider logging ... } } finally { // set the profile name if it does not provide one @@ -1778,37 +1762,51 @@ private Properties findVMProfile(Generation systemGeneration) { return result; } + private InputStream createProfileStream(Generation systemGeneration, String vmProfile, + String embeddedProfileName) { + InputStream profileIn = null; + if (vmProfile != null) { + // look for a profile in the system bundle based on the vm profile + String javaProfile = vmProfile + PROFILE_EXT; + profileIn = findInSystemBundle(systemGeneration, javaProfile); + if (profileIn == null) { + profileIn = getNextBestProfile(systemGeneration, JAVASE, runtimeVersion, embeddedProfileName); + } + } + if (profileIn == null) { + // the profile url is still null then use the min profile the framework can use + profileIn = findInSystemBundle(systemGeneration, "JavaSE-1.8.profile"); //$NON-NLS-1$ + } + return profileIn; + } + private Properties readConfiguredJavaProfile(Generation systemGeneration) { // check for the java profile property for a url String propJavaProfile = equinoxContainer.getConfiguration().getConfiguration(EquinoxConfiguration.PROP_OSGI_JAVA_PROFILE); if (propJavaProfile != null) { - InputStream profileIn = null; - try { - // we assume a URL - profileIn = new URL(propJavaProfile).openStream(); - } catch (IOException e) { - // try using a relative path in the system bundle - profileIn = findInSystemBundle(systemGeneration, propJavaProfile); - } - if (profileIn != null) { - Properties result = new Properties(); - try { - result.load(new BufferedInputStream(profileIn)); - } catch (IOException e) { - // consider logging - } finally { - try { - profileIn.close(); - } catch (IOException e) { - // nothing to do - } + try (InputStream profileIn = createPropStream(systemGeneration, propJavaProfile)){ + if (profileIn != null) { + Properties result = new Properties(); + result.load(profileIn); + return result; } - return result; + } catch (IOException e) { + // consider logging } } return null; } + private InputStream createPropStream(Generation systemGeneration, String propJavaProfile) { + try { + // we assume a URL + return new URL(propJavaProfile).openStream(); + } catch (IOException e) { + // try using a relative path in the system bundle + return findInSystemBundle(systemGeneration, propJavaProfile); + } + } + @SuppressWarnings("deprecation") private Properties calculateVMProfile(Version javaVersion) { String systemPackages = calculateVMPackages();