diff options
author | Alexander Kurtakov | 2017-06-22 15:42:13 +0000 |
---|---|---|
committer | Alexander Kurtakov | 2017-06-22 15:42:13 +0000 |
commit | 6e0300fbe0155dd09a58b195b9310342162bc7b8 (patch) | |
tree | a6b1a743aeb93d2f3118f9eea784591e6eab99e6 | |
parent | 2db6317e308a86a23c3e7b1dd252f6583b0c5bc9 (diff) | |
download | rt.equinox.p2-6e0300fbe0155dd09a58b195b9310342162bc7b8.tar.gz rt.equinox.p2-6e0300fbe0155dd09a58b195b9310342162bc7b8.tar.xz rt.equinox.p2-6e0300fbe0155dd09a58b195b9310342162bc7b8.zip |
Bug 518587 - Modernize o.e.equinox.p2.testsI20170623-0110I20170622-2000
Use try-with-resources.
Change-Id: I6c1d3efb7f0fd4f5dd0f014d8801ec8e375355f9
Signed-off-by: Alexander Kurtakov <akurtako@redhat.com>
40 files changed, 398 insertions, 754 deletions
diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/AbstractAntProvisioningTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/AbstractAntProvisioningTest.java index ce1f277e7..92355c4be 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/AbstractAntProvisioningTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/AbstractAntProvisioningTest.java @@ -165,15 +165,10 @@ public class AbstractAntProvisioningTest extends AbstractProvisioningTest { * Write the build script to disk */ private void writeBuildScript() throws Exception { - FileOutputStream outputStream = null; - try { - outputStream = new FileOutputStream(buildScript); + try (FileOutputStream outputStream = new FileOutputStream(buildScript);) { XMLWriter writer = new XMLWriter(outputStream, null); writeElement(writer, root); writer.flush(); - } finally { - if (outputStream != null) - outputStream.close(); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/AbstractProvisioningTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/AbstractProvisioningTest.java index a12fab172..0d0bd0b35 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/AbstractProvisioningTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/AbstractProvisioningTest.java @@ -183,11 +183,7 @@ public abstract class AbstractProvisioningTest extends TestCase { copy(message, children[i], new File(target, children[i].getName())); return; } - InputStream input = null; - OutputStream output = null; - try { - input = new BufferedInputStream(new FileInputStream(source)); - output = new BufferedOutputStream(new FileOutputStream(target)); + try (InputStream input = new BufferedInputStream(new FileInputStream(source)); OutputStream output = new BufferedOutputStream(new FileOutputStream(target));) { byte[] buffer = new byte[8192]; int bytesRead = 0; @@ -195,23 +191,6 @@ public abstract class AbstractProvisioningTest extends TestCase { output.write(buffer, 0, bytesRead); } catch (IOException e) { fail(message, e); - } finally { - if (input != null) { - try { - input.close(); - } catch (IOException e) { - System.err.println("Exception while trying to close input stream on: " + source.getAbsolutePath()); - e.printStackTrace(); - } - } - if (output != null) { - try { - output.close(); - } catch (IOException e) { - System.err.println("Exception while trying to close output stream on: " + target.getAbsolutePath()); - e.printStackTrace(); - } - } } } @@ -696,26 +675,16 @@ public abstract class AbstractProvisioningTest extends TestCase { } public static void writeBuffer(File outputFile, StringBuffer buffer) throws IOException { - FileOutputStream stream = null; - try { - outputFile.getParentFile().mkdirs(); - stream = new FileOutputStream(outputFile); + outputFile.getParentFile().mkdirs(); + try (FileOutputStream stream = new FileOutputStream(outputFile)) { stream.write(buffer.toString().getBytes()); - } finally { - if (stream != null) - stream.close(); } } public static void writeProperties(File outputFile, Properties properties) throws IOException { - FileOutputStream stream = null; - try { - outputFile.getParentFile().mkdirs(); - stream = new FileOutputStream(outputFile); + outputFile.getParentFile().mkdirs(); + try (FileOutputStream stream = new FileOutputStream(outputFile)) { properties.store(stream, ""); - } finally { - if (stream != null) - stream.close(); } } @@ -1126,22 +1095,13 @@ public abstract class AbstractProvisioningTest extends TestCase { * @param content */ public static void assertFileContent(String message, File f, String content) { - BufferedReader reader = null; - try { - reader = new BufferedReader(new InputStreamReader(new FileInputStream(f))); + try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f)))) { String line = reader.readLine(); assertEquals(message, content, line); } catch (FileNotFoundException e) { fail("Getting copy target", e); } catch (IOException e) { fail("reading copy target", e); - } finally { - try { - if (reader != null) - reader.close(); - } catch (IOException e) { - //ignore - } } } @@ -1448,8 +1408,7 @@ public abstract class AbstractProvisioningTest extends TestCase { assertTrue(log.exists()); assertTrue(log.length() > 0); assertNotNull(parts); - BufferedReader reader = new BufferedReader(new FileReader(log)); - try { + try (BufferedReader reader = new BufferedReader(new FileReader(log))) { while (reader.ready()) { String line = reader.readLine(); boolean found = true; @@ -1459,8 +1418,6 @@ public abstract class AbstractProvisioningTest extends TestCase { if (found) return; } - } finally { - reader.close(); } assertTrue(false); } @@ -1483,8 +1440,7 @@ public abstract class AbstractProvisioningTest extends TestCase { assertTrue(log.length() > 0); int idx = 0; - BufferedReader reader = new BufferedReader(new FileReader(log)); - try { + try (BufferedReader reader = new BufferedReader(new FileReader(log))) { while (reader.ready()) { String line = reader.readLine(); if (line.indexOf(lines[idx]) >= 0) { @@ -1493,8 +1449,6 @@ public abstract class AbstractProvisioningTest extends TestCase { } } } - } finally { - reader.close(); } fail(String.format("Log file %s doesn't contain lines %s", log.getCanonicalPath(), Arrays.toString(lines))); } @@ -1517,8 +1471,7 @@ public abstract class AbstractProvisioningTest extends TestCase { assertTrue(log.length() > 0); int idx = 0; - BufferedReader reader = new BufferedReader(new FileReader(log)); - try { + try (BufferedReader reader = new BufferedReader(new FileReader(log))) { while (reader.ready()) { String line = reader.readLine(); if (line.indexOf(lines[idx]) >= 0) { @@ -1527,8 +1480,6 @@ public abstract class AbstractProvisioningTest extends TestCase { } } } - } finally { - reader.close(); } } @@ -1627,18 +1578,13 @@ public abstract class AbstractProvisioningTest extends TestCase { fail("File: " + file.toString() + " can't be found."); int idx = 0; try { - BufferedReader reader = null; - try { - reader = new BufferedReader(new FileReader(file)); + try (BufferedReader reader = new BufferedReader(new FileReader(file));) { while (reader.ready()) { String line = reader.readLine(); if (line.indexOf(lines[idx]) > 0) { fail("String: " + lines[idx] + " should not be in " + file.getAbsolutePath()); } } - } finally { - if (reader != null) - reader.close(); } } catch (FileNotFoundException e) { //ignore, caught before @@ -1652,9 +1598,7 @@ public abstract class AbstractProvisioningTest extends TestCase { fail("File: " + file.toString() + " can't be found."); int idx = 0; try { - BufferedReader reader = null; - try { - reader = new BufferedReader(new FileReader(file)); + try (BufferedReader reader = new BufferedReader(new FileReader(file));) { while (reader.ready()) { String line = reader.readLine(); if (line.indexOf(lines[idx]) >= 0) { @@ -1662,9 +1606,6 @@ public abstract class AbstractProvisioningTest extends TestCase { return; } } - } finally { - if (reader != null) - reader.close(); } } catch (FileNotFoundException e) { //ignore, caught before diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/GenerateTestData.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/GenerateTestData.java index 295cb7ff5..004ddecc7 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/GenerateTestData.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/GenerateTestData.java @@ -228,17 +228,8 @@ public class GenerateTestData { if (parent == null) throw new RuntimeException("Unable to write to: " + location.getAbsolutePath() + "due to null parent."); parent.mkdirs(); - OutputStream output = null; - try { - output = new BufferedOutputStream(new FileOutputStream(location)); + try (OutputStream output = new BufferedOutputStream(new FileOutputStream(location))) { output.write(data.getBytes()); - } finally { - if (output != null) - try { - output.close(); - } catch (IOException e) { - // ignore - } } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/IULoader.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/IULoader.java index ca17737bc..3fdf5b971 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/IULoader.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/IULoader.java @@ -1,11 +1,11 @@ /******************************************************************************* - * Copyright (c) 2011 Sonatype, Inc. and others. All rights reserved. + * Copyright (c) 2011, 2017 Sonatype, Inc. and others. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Sonatype, Inc. - initial implementation and ideas + * + * Contributors: + * Sonatype, Inc. - initial implementation and ideas ******************************************************************************/ package org.eclipse.equinox.p2.tests; @@ -31,11 +31,9 @@ public class IULoader { if (a[j] instanceof IUDescription) { IUDescription ml = (IUDescription) a[j]; // here it is !!! ReducedCUDFParser parser = new ReducedCUDFParser(); - InputStream is = new ByteArrayInputStream(ml.content().getBytes()); - parser.parse(is, false, null); - try { + try (InputStream is = new ByteArrayInputStream(ml.content().getBytes())) { + parser.parse(is, false, null); fields[i].set(o, parser.getIU()); - is.close(); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ant/MirrorTaskTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ant/MirrorTaskTest.java index 49a924f3a..f9c87bbb0 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ant/MirrorTaskTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ant/MirrorTaskTest.java @@ -607,22 +607,22 @@ public class MirrorTaskTest extends AbstractAntProvisioningTest { IArtifactKey key = new ArtifactKey("osgi.bundle", "a", Version.parseVersion("1.0.0")); IArtifactRepository[] repos = new IArtifactRepository[] {createArtifactRepository(base.toURI(), null), createArtifactRepository(source.toURI(), null)}; for (int i = 0; i < 2; i++) { - ZipOutputStream stream = new ZipOutputStream(repos[i].getOutputStream(repos[i].createArtifactDescriptor(key))); - ZipEntry entry = new ZipEntry("file.properties"); - stream.putNextEntry(entry); - props.store(stream, String.valueOf(i)); - stream.closeEntry(); - stream.close(); + try (ZipOutputStream stream = new ZipOutputStream(repos[i].getOutputStream(repos[i].createArtifactDescriptor(key)))) { + ZipEntry entry = new ZipEntry("file.properties"); + stream.putNextEntry(entry); + props.store(stream, String.valueOf(i)); + stream.closeEntry(); + } } key = new ArtifactKey("osgi.bundle", "b", Version.parseVersion("1.0.0")); for (int i = 0; i < 2; i++) { - ZipOutputStream stream = new ZipOutputStream(repos[i].getOutputStream(repos[i].createArtifactDescriptor(key))); - ZipEntry entry = new ZipEntry("file.properties"); - stream.putNextEntry(entry); - props.put("boo", String.valueOf(i)); - props.store(stream, String.valueOf(i)); - stream.closeEntry(); - stream.close(); + try (ZipOutputStream stream = new ZipOutputStream(repos[i].getOutputStream(repos[i].createArtifactDescriptor(key)))) { + ZipEntry entry = new ZipEntry("file.properties"); + stream.putNextEntry(entry); + props.put("boo", String.valueOf(i)); + props.store(stream, String.valueOf(i)); + stream.closeEntry(); + } } AntTaskElement mirror = createMirrorTask(TYPE_ARTIFACT); @@ -738,7 +738,7 @@ public class MirrorTaskTest extends AbstractAntProvisioningTest { PrintStream oldOut = System.out; PrintStream newOut = null; try { - (new File(destinationRepo)).mkdir(); + new File(destinationRepo).mkdir(); newErr = new PrintStream(new FileOutputStream(new File(new File(destinationRepo), "sys.err"))); newOut = new PrintStream(new FileOutputStream(new File(new File(destinationRepo), "sys.out"))); } catch (FileNotFoundException e) { diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ant/Repo2RunnableTaskTests.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ant/Repo2RunnableTaskTests.java index 85a1d177d..256e0fd97 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ant/Repo2RunnableTaskTests.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ant/Repo2RunnableTaskTests.java @@ -66,10 +66,10 @@ public class Repo2RunnableTaskTests extends AbstractAntProvisioningTest { assertTrue("Missing content.jar", new File(f, "content.jar").exists()); assertTrue("Missing artifacts.jar", new File(f, "artifacts.jar").exists()); assertTrue("Missing fragment.info", new File(f, "fragment.info").exists()); - BufferedReader br = new BufferedReader(new FileReader(new File(f, "fragment.info"))); - while (br.ready()) - System.out.println(br.readLine()); - br.close(); + try (BufferedReader br = new BufferedReader(new FileReader(new File(f, "fragment.info")))) { + while (br.ready()) + System.out.println(br.readLine()); + } } /* diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/processors/Pack200ProcessorTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/processors/Pack200ProcessorTest.java index 5bbcc5996..31500b656 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/processors/Pack200ProcessorTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/processors/Pack200ProcessorTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. + * Copyright (c) 2007, 2017 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -83,7 +83,7 @@ public class Pack200ProcessorTest extends AbstractProvisioningTest { } /** - * Tests the case where we are unpacking a file that was not packed by + * Tests the case where we are unpacking a file that was not packed by * our own pack step. In this case the eclipse.inf may not be present * and we must not attempt to modify it. * @throws IOException @@ -96,14 +96,14 @@ public class Pack200ProcessorTest extends AbstractProvisioningTest { ProcessingStep step = new Pack200ProcessorStep(); File destinationFile = new File(tempFolder, "testUnpackFileNotPackedByJarProcessor.jar"); - OutputStream destination = new BufferedOutputStream(new FileOutputStream(destinationFile)); - step.link(destination, new NullProgressMonitor()); - - // drive the source data through the step - Bundle bundle = TestActivator.getContext().getBundle(); - InputStream inputStream = bundle.getEntry("testData/optimizers/bug387557.bundle_1.0.0.201208200951.jar.pack.gz").openStream(); - FileUtils.copyStream(inputStream, true, step, true); - destination.close(); + try (OutputStream destination = new BufferedOutputStream(new FileOutputStream(destinationFile))) { + step.link(destination, new NullProgressMonitor()); + + // drive the source data through the step + Bundle bundle = TestActivator.getContext().getBundle(); + InputStream inputStream = bundle.getEntry("testData/optimizers/bug387557.bundle_1.0.0.201208200951.jar.pack.gz").openStream(); + FileUtils.copyStream(inputStream, true, step, true); + } // Get the expected result File expected = getTestData("Missing test data", "testData/optimizers/bug387557.bundle_1.0.0.201208200951.jar"); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/BatchExecuteArtifactRepositoryTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/BatchExecuteArtifactRepositoryTest.java index 7073c172a..18f12331d 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/BatchExecuteArtifactRepositoryTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/BatchExecuteArtifactRepositoryTest.java @@ -73,19 +73,16 @@ public class BatchExecuteArtifactRepositoryTest extends AbstractProvisioningTest Map properties = new HashMap(); final SimpleArtifactRepository repo = (SimpleArtifactRepository) getArtifactRepositoryManager().createRepository(repositoryURI, "My Repo", IArtifactRepositoryManager.TYPE_SIMPLE_REPOSITORY, properties); final URI artifactXML = new URI(repositoryFile.toURI().toString() + "/artifacts.xml"); - IStatus status = repo.executeBatch(new IRunnableWithProgress() { - @Override - public void run(IProgressMonitor monitor) { - repo.addDescriptor(createDescriptor("foo", "foo", Version.emptyVersion)); - repo.addDescriptor(createDescriptor("bar", "bar", Version.emptyVersion)); - repo.addDescriptor(createDescriptor("baz", "baz", Version.emptyVersion)); - try { - assertFalse("1.0", fileContainsString(artifactXML, "foo")); - assertFalse("1.0", fileContainsString(artifactXML, "bar")); - assertFalse("1.0", fileContainsString(artifactXML, "baz")); - } catch (IOException e) { - fail("0.99"); - } + IStatus status = repo.executeBatch(monitor -> { + repo.addDescriptor(createDescriptor("foo", "foo", Version.emptyVersion)); + repo.addDescriptor(createDescriptor("bar", "bar", Version.emptyVersion)); + repo.addDescriptor(createDescriptor("baz", "baz", Version.emptyVersion)); + try { + assertFalse("1.0", fileContainsString(artifactXML, "foo")); + assertFalse("1.0", fileContainsString(artifactXML, "bar")); + assertFalse("1.0", fileContainsString(artifactXML, "baz")); + } catch (IOException e) { + fail("0.99"); } }, new NullProgressMonitor()); assertTrue(status.isOK()); @@ -110,13 +107,10 @@ public class BatchExecuteArtifactRepositoryTest extends AbstractProvisioningTest Map properties = new HashMap(); final SimpleArtifactRepository repo = (SimpleArtifactRepository) getArtifactRepositoryManager().createRepository(repositoryURI, "My Repo", IArtifactRepositoryManager.TYPE_SIMPLE_REPOSITORY, properties); final URI artifactXML = new URI(repositoryFile.toURI().toString() + "/artifacts.xml"); - IStatus status = repo.executeBatch(new IRunnableWithProgress() { - @Override - public void run(IProgressMonitor monitor) { - repo.addDescriptor(createDescriptor("foo", "foo", Version.emptyVersion)); - repo.addDescriptor(createDescriptor("bar", "bar", Version.emptyVersion)); - throw new RuntimeException(); - } + IStatus status = repo.executeBatch(monitor -> { + repo.addDescriptor(createDescriptor("foo", "foo", Version.emptyVersion)); + repo.addDescriptor(createDescriptor("bar", "bar", Version.emptyVersion)); + throw new RuntimeException(); }, new NullProgressMonitor()); assertFalse(status.isOK()); assertEquals("1.0", 1, repo.query(new ArtifactKeyQuery("foo", "foo", null), new NullProgressMonitor()).toSet().size()); @@ -138,14 +132,11 @@ public class BatchExecuteArtifactRepositoryTest extends AbstractProvisioningTest Map properties = new HashMap(); final SimpleArtifactRepository repo = (SimpleArtifactRepository) getArtifactRepositoryManager().createRepository(repositoryURI, "My Repo", IArtifactRepositoryManager.TYPE_SIMPLE_REPOSITORY, properties); final URI artifactXML = new URI(repositoryFile.toURI().toString() + "/artifacts.xml"); - IStatus status = repo.executeBatch(new IRunnableWithProgress() { - @Override - public void run(IProgressMonitor monitor) { - IArtifactDescriptor foo = createDescriptor("foo", "foo", Version.emptyVersion); - repo.addDescriptor(foo); - repo.addDescriptor(createDescriptor("bar", "bar", Version.emptyVersion)); - repo.removeDescriptor(foo); - } + IStatus status = repo.executeBatch(monitor -> { + IArtifactDescriptor foo = createDescriptor("foo", "foo", Version.emptyVersion); + repo.addDescriptor(foo); + repo.addDescriptor(createDescriptor("bar", "bar", Version.emptyVersion)); + repo.removeDescriptor(foo); }, new NullProgressMonitor()); assertTrue(status.isOK()); assertEquals("1.0", 1, repo.query(new ArtifactKeyQuery("bar", "bar", null), new NullProgressMonitor()).toSet().size()); @@ -167,17 +158,14 @@ public class BatchExecuteArtifactRepositoryTest extends AbstractProvisioningTest Map properties = new HashMap(); final SimpleArtifactRepository repo = (SimpleArtifactRepository) getArtifactRepositoryManager().createRepository(repositoryURI, "My Repo", IArtifactRepositoryManager.TYPE_SIMPLE_REPOSITORY, properties); final URI artifactXML = new URI(repositoryFile.toURI().toString() + "/artifacts.xml"); - IStatus status = repo.executeBatch(new IRunnableWithProgress() { - @Override - public void run(IProgressMonitor monitor) { - repo.addDescriptor(createDescriptor("1", "1", Version.emptyVersion)); - repo.addDescriptor(createDescriptor("2", "2", Version.emptyVersion)); - repo.addDescriptor(createDescriptor("3", "3", Version.emptyVersion)); - IArtifactDescriptor foo = createDescriptor("foo", "foo", Version.emptyVersion); - repo.addDescriptor(foo); - repo.addDescriptor(createDescriptor("bar", "bar", Version.emptyVersion)); - repo.removeDescriptor(foo); - } + IStatus status = repo.executeBatch(monitor -> { + repo.addDescriptor(createDescriptor("1", "1", Version.emptyVersion)); + repo.addDescriptor(createDescriptor("2", "2", Version.emptyVersion)); + repo.addDescriptor(createDescriptor("3", "3", Version.emptyVersion)); + IArtifactDescriptor foo = createDescriptor("foo", "foo", Version.emptyVersion); + repo.addDescriptor(foo); + repo.addDescriptor(createDescriptor("bar", "bar", Version.emptyVersion)); + repo.removeDescriptor(foo); }, new NullProgressMonitor()); assertTrue(status.isOK()); assertEquals("1.0", 4, repo.query(new ArtifactKeyQuery(null, null, null), new NullProgressMonitor()).toSet().size()); @@ -189,15 +177,11 @@ public class BatchExecuteArtifactRepositoryTest extends AbstractProvisioningTest boolean fileContainsString(URI location, String string) throws IOException { StringBuffer buffer = new StringBuffer(); - BufferedReader reader = null; - try { - reader = new BufferedReader(new FileReader(new File(location))); + try (BufferedReader reader = new BufferedReader(new FileReader(new File(location)))) { + while (reader.ready()) buffer.append(reader.readLine()); return buffer.toString().contains(string); - } finally { - if (reader != null) - reader.close(); } } @@ -210,11 +194,8 @@ public class BatchExecuteArtifactRepositoryTest extends AbstractProvisioningTest repositoryURI = repositoryFile.toURI(); Map properties = new HashMap(); SimpleArtifactRepository repo = (SimpleArtifactRepository) getArtifactRepositoryManager().createRepository(repositoryURI, "My Repo", IArtifactRepositoryManager.TYPE_SIMPLE_REPOSITORY, properties); - IStatus status = repo.executeBatch(new IRunnableWithProgress() { - @Override - public void run(IProgressMonitor monitor) { - // empty - } + IStatus status = repo.executeBatch(monitor -> { + // empty }, new NullProgressMonitor()); assertTrue(status.isOK()); } catch (Exception e) { @@ -279,11 +260,8 @@ public class BatchExecuteArtifactRepositoryTest extends AbstractProvisioningTest try { SimpleArtifactRepository simpleArtifactRepository = new FailingSimpleArtifactRepository("foo", new URI("http://foo.bar"), null); - IStatus status = simpleArtifactRepository.executeBatch(new IRunnableWithProgress() { - @Override - public void run(IProgressMonitor monitor) { - throw new RuntimeException("bar"); - } + IStatus status = simpleArtifactRepository.executeBatch(monitor -> { + throw new RuntimeException("bar"); }, new NullProgressMonitor()); assertFalse(status.isOK()); assertEquals("foo", status.getException().getMessage()); @@ -301,11 +279,8 @@ public class BatchExecuteArtifactRepositoryTest extends AbstractProvisioningTest try { SimpleArtifactRepository simpleArtifactRepository = new FailingSimpleArtifactRepository("foo", new URI("http://foo.bar"), null); - IStatus status = simpleArtifactRepository.executeBatch(new IRunnableWithProgress() { - @Override - public void run(IProgressMonitor monitor) { - // empty - } + IStatus status = simpleArtifactRepository.executeBatch(monitor -> { + // empty }, new NullProgressMonitor()); assertFalse(status.isOK()); assertEquals("foo", status.getException().getMessage()); @@ -326,12 +301,9 @@ public class BatchExecuteArtifactRepositoryTest extends AbstractProvisioningTest IProgressMonitor monitor = new NullProgressMonitor(); monitor.setCanceled(true); - IStatus status = repo.executeBatch(new IRunnableWithProgress() { - @Override - public void run(IProgressMonitor monitor) { - if (monitor.isCanceled()) - throw new OperationCanceledException(); - } + IStatus status = repo.executeBatch(monitor1 -> { + if (monitor1.isCanceled()) + throw new OperationCanceledException(); }, monitor); assertTrue(status.getSeverity() == IStatus.CANCEL); @@ -347,12 +319,8 @@ public class BatchExecuteArtifactRepositoryTest extends AbstractProvisioningTest try { FailingCompositeArtifactRepository compositeArtifactRepository = new FailingCompositeArtifactRepository(getArtifactRepositoryManager(), "foo", new URI("http://foo.bar"), null); - IStatus status = compositeArtifactRepository.executeBatch(new IRunnableWithProgress() { - - @Override - public void run(IProgressMonitor monitor) { - throw new RuntimeException("bar"); - } + IStatus status = compositeArtifactRepository.executeBatch(monitor -> { + throw new RuntimeException("bar"); }, new NullProgressMonitor()); assertFalse(status.isOK()); assertEquals("foo", status.getException().getMessage()); @@ -370,11 +338,8 @@ public class BatchExecuteArtifactRepositoryTest extends AbstractProvisioningTest try { FailingCompositeArtifactRepository compositeArtifactRepository = new FailingCompositeArtifactRepository(getArtifactRepositoryManager(), "foo", new URI("http://foo.bar"), null); - IStatus status = compositeArtifactRepository.executeBatch(new IRunnableWithProgress() { - @Override - public void run(IProgressMonitor monitor) { - // empty - } + IStatus status = compositeArtifactRepository.executeBatch(monitor -> { + // empty }, new NullProgressMonitor()); assertFalse(status.isOK()); assertEquals("foo", status.getException().getMessage()); @@ -416,11 +381,8 @@ public class BatchExecuteArtifactRepositoryTest extends AbstractProvisioningTest public void testBatchProcessingTrackSaving() { try { TrackSavignSimpleArtifactRepository simpleArtifactRepository = new TrackSavignSimpleArtifactRepository("foo", new URI("http://foo.bar"), null); - simpleArtifactRepository.executeBatch(new IRunnableWithProgress() { - @Override - public void run(IProgressMonitor monitor) { - //do nothing; - } + simpleArtifactRepository.executeBatch(monitor -> { + //do nothing; }, new NullProgressMonitor()); assertTrue(simpleArtifactRepository.didSave); } catch (Exception e) { @@ -435,11 +397,8 @@ public class BatchExecuteArtifactRepositoryTest extends AbstractProvisioningTest public void testBatchProcessingTrackSavingException() { try { TrackSavignSimpleArtifactRepository simpleArtifactRepository = new TrackSavignSimpleArtifactRepository("foo", new URI("http://foo.bar"), null); - simpleArtifactRepository.executeBatch(new IRunnableWithProgress() { - @Override - public void run(IProgressMonitor monitor) { - throw new RuntimeException(); - } + simpleArtifactRepository.executeBatch(monitor -> { + throw new RuntimeException(); }, new NullProgressMonitor()); assertTrue(simpleArtifactRepository.didSave); } catch (Exception e) { @@ -457,11 +416,8 @@ public class BatchExecuteArtifactRepositoryTest extends AbstractProvisioningTest repositoryURI = repositoryFile.toURI(); Map properties = new HashMap(); SimpleArtifactRepository repo = (SimpleArtifactRepository) getArtifactRepositoryManager().createRepository(repositoryURI, "My Repo", IArtifactRepositoryManager.TYPE_SIMPLE_REPOSITORY, properties); - repo.executeBatch(new IRunnableWithProgress() { - @Override - public void run(IProgressMonitor monitor) { - throw new RuntimeException(); - } + repo.executeBatch(monitor -> { + throw new RuntimeException(); }, new NullProgressMonitor()); Field field = SimpleArtifactRepository.class.getDeclaredField("disableSave"); field.setAccessible(true); @@ -483,25 +439,22 @@ public class BatchExecuteArtifactRepositoryTest extends AbstractProvisioningTest repositoryURI = repositoryFile.toURI(); Map properties = new HashMap(); final SimpleArtifactRepository repo = (SimpleArtifactRepository) getArtifactRepositoryManager().createRepository(repositoryURI, "My Repo", IArtifactRepositoryManager.TYPE_SIMPLE_REPOSITORY, properties); - repo.executeBatch(new IRunnableWithProgress() { - @Override - public void run(IProgressMonitor monitor) { - Field field; - try { - field = SimpleArtifactRepository.class.getDeclaredField("disableSave"); - field.setAccessible(true); - boolean disableSave = field.getBoolean(repo); - assertTrue("1.0", disableSave); - } catch (SecurityException e) { - fail("1.1" + e.getMessage()); - } catch (NoSuchFieldException e) { - // TODO Auto-generated catch block - fail("1.2" + e.getMessage()); - } catch (IllegalArgumentException e) { - fail("1.2" + e.getMessage()); - } catch (IllegalAccessException e) { - fail("1.2" + e.getMessage()); - } + repo.executeBatch(monitor -> { + Field field; + try { + field = SimpleArtifactRepository.class.getDeclaredField("disableSave"); + field.setAccessible(true); + boolean disableSave = field.getBoolean(repo); + assertTrue("1.0", disableSave); + } catch (SecurityException e1) { + fail("1.1" + e1.getMessage()); + } catch (NoSuchFieldException e2) { + // TODO Auto-generated catch block + fail("1.2" + e2.getMessage()); + } catch (IllegalArgumentException e3) { + fail("1.2" + e3.getMessage()); + } catch (IllegalAccessException e4) { + fail("1.2" + e4.getMessage()); } }, new NullProgressMonitor()); @@ -520,11 +473,8 @@ public class BatchExecuteArtifactRepositoryTest extends AbstractProvisioningTest repositoryURI = repositoryFile.toURI(); Map properties = new HashMap(); CompositeArtifactRepository repo = (CompositeArtifactRepository) getArtifactRepositoryManager().createRepository(repositoryURI, "My Repo", IArtifactRepositoryManager.TYPE_COMPOSITE_REPOSITORY, properties); - repo.executeBatch(new IRunnableWithProgress() { - @Override - public void run(IProgressMonitor monitor) { - throw new RuntimeException(); - } + repo.executeBatch(monitor -> { + throw new RuntimeException(); }, new NullProgressMonitor()); Field field = CompositeArtifactRepository.class.getDeclaredField("disableSave"); field.setAccessible(true); @@ -545,25 +495,22 @@ public class BatchExecuteArtifactRepositoryTest extends AbstractProvisioningTest repositoryURI = repositoryFile.toURI(); Map properties = new HashMap(); final CompositeArtifactRepository repo = (CompositeArtifactRepository) getArtifactRepositoryManager().createRepository(repositoryURI, "My Repo", IArtifactRepositoryManager.TYPE_COMPOSITE_REPOSITORY, properties); - repo.executeBatch(new IRunnableWithProgress() { - @Override - public void run(IProgressMonitor monitor) { - Field field; - try { - field = CompositeArtifactRepository.class.getDeclaredField("disableSave"); - field.setAccessible(true); - boolean disableSave = field.getBoolean(repo); - assertTrue("1.0", disableSave); - } catch (SecurityException e) { - fail("1.1" + e.getMessage()); - } catch (NoSuchFieldException e) { - // TODO Auto-generated catch block - fail("1.2" + e.getMessage()); - } catch (IllegalArgumentException e) { - fail("1.2" + e.getMessage()); - } catch (IllegalAccessException e) { - fail("1.2" + e.getMessage()); - } + repo.executeBatch(monitor -> { + Field field; + try { + field = CompositeArtifactRepository.class.getDeclaredField("disableSave"); + field.setAccessible(true); + boolean disableSave = field.getBoolean(repo); + assertTrue("1.0", disableSave); + } catch (SecurityException e1) { + fail("1.1" + e1.getMessage()); + } catch (NoSuchFieldException e2) { + // TODO Auto-generated catch block + fail("1.2" + e2.getMessage()); + } catch (IllegalArgumentException e3) { + fail("1.2" + e3.getMessage()); + } catch (IllegalAccessException e4) { + fail("1.2" + e4.getMessage()); } }, new NullProgressMonitor()); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/CompositeArtifactRepositoryTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/CompositeArtifactRepositoryTest.java index 74f9399a8..0d8f0c657 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/CompositeArtifactRepositoryTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/CompositeArtifactRepositoryTest.java @@ -441,16 +441,10 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { properties.remove(IArtifactDescriptor.FORMAT); ((ArtifactDescriptor) newDescriptor).addProperties(properties); try { - OutputStream repositoryStream = null; - try { - //System.out.println("Getting Artifact: " + descriptors[0].getArtifactKey() + " (Descriptor: " + descriptors[0] + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - repositoryStream = destinationRepo.getOutputStream(newDescriptor); + try (OutputStream repositoryStream = destinationRepo.getOutputStream(newDescriptor);) { if (repositoryStream == null) fail("Error while obtaining OutputStream"); compRepo.getArtifact(descriptors[0], repositoryStream, new NullProgressMonitor()); - } finally { - if (repositoryStream != null) - repositoryStream.close(); } } catch (ProvisionException e) { fail("Error while obtaining OutputStream", e); @@ -546,17 +540,7 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { requests[0] = request1; requests[1] = request2; - try { - OutputStream repositoryStream = null; - try { - compRepo.getArtifacts(requests, new NullProgressMonitor()); - } finally { - if (repositoryStream != null) - repositoryStream.close(); - } - } catch (IOException e) { - fail("Error while downloading artifacts", e); - } + compRepo.getArtifacts(requests, new NullProgressMonitor()); //corresponding keys should now be in the destination assertTrue("Expected Key is not in destination", destinationRepo.contains(key1)); assertTrue("Expected Key is not in destination", destinationRepo.contains(key2)); @@ -977,11 +961,8 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { */ public void testRetryRequest() { URI childLocation = getTestData("Loading test data", "testData/artifactRepo/missingArtifact").toURI(); - File destination = null; - OutputStream out = null; - try { - destination = new File(getTempFolder(), getUniqueString()); - out = new FileOutputStream(destination); + File destination = new File(getTempFolder(), getUniqueString()); + try (OutputStream out = new FileOutputStream(destination)) { CompositeArtifactRepository repository = createRepository(new URI("memory:/in/memory"), "in memory test"); @@ -1008,12 +989,6 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { fail("Exception occurred", e); } finally { getArtifactRepositoryManager().removeRepository(childLocation); - if (out != null) - try { - out.close(); - } catch (IOException e) { - // Don't care - } if (destination != null) delete(destination.getParentFile()); } @@ -1124,11 +1099,8 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { BadSite childOne = null; BadSite dest = null; CompositeArtifactRepository source = null; - File destination = null; - OutputStream out = null; - try { - destination = new File(getTempFolder(), getUniqueString()); - out = new FileOutputStream(destination); + File destination = new File(getTempFolder(), getUniqueString()); + try (OutputStream out = new FileOutputStream(destination);) { source = createRepository(new URI("memory:/in/memory"), "in memory test"); IArtifactDescriptor descriptor = new ArtifactDescriptor(new ArtifactKey("osgi.bundle", "missingSize.asdf", Version.create("1.5.1.v200803061910"))); @@ -1161,12 +1133,6 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { } catch (Exception e) { fail("Exception occurred", e); } finally { - if (out != null) - try { - out.close(); - } catch (IOException e) { - // Don't care - } if (source != null) getArtifactRepositoryManager().removeRepository(source.getLocation()); if (childOne != null) diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/SimpleArtifactRepositoryTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/SimpleArtifactRepositoryTest.java index 7d0fbe176..231239c88 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/SimpleArtifactRepositoryTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/SimpleArtifactRepositoryTest.java @@ -28,7 +28,8 @@ import org.eclipse.equinox.p2.core.ProvisionException; import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.query.IQueryResult; import org.eclipse.equinox.p2.query.IQueryable; -import org.eclipse.equinox.p2.repository.*; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.IRepositoryManager; import org.eclipse.equinox.p2.repository.artifact.*; import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; import org.eclipse.equinox.p2.repository.artifact.spi.ProcessingStepDescriptor; @@ -359,9 +360,9 @@ public class SimpleArtifactRepositoryTest extends AbstractProvisioningTest { SimpleArtifactRepository repo = (SimpleArtifactRepository) getArtifactRepositoryManager().createRepository(repositoryURI, "My Repo", IArtifactRepositoryManager.TYPE_SIMPLE_REPOSITORY, properties); TestDescriptor descriptor = new TestDescriptor(new ArtifactKey("osgi.bundle", "aaPlugin", Version.create("1.0.0"))); - OutputStream stream = repo.getOutputStream(descriptor); - stream.write("I am an artifact\n".getBytes()); - stream.close(); + try (OutputStream stream = repo.getOutputStream(descriptor)) { + stream.write("I am an artifact\n".getBytes()); + } assertTrue(repo.contains(descriptor)); @@ -391,14 +392,10 @@ public class SimpleArtifactRepositoryTest extends AbstractProvisioningTest { final IArtifactRepository repo = getArtifactRepositoryManager().createRepository(repositoryURI, "test", IArtifactRepositoryManager.TYPE_SIMPLE_REPOSITORY, new HashMap()); long start = System.currentTimeMillis(); - repo.executeBatch(new IRunnableWithProgress() { - - @Override - public void run(IProgressMonitor monitor) throws OperationCanceledException { - for (int i = 0; i < 10000; i++) { - ArtifactDescriptor d = new ArtifactDescriptor(new ArtifactKey("osgi.bundle", "a" + i, Version.create("1.0.0"))); - repo.addDescriptor(d); - } + repo.executeBatch(monitor -> { + for (int i = 0; i < 10000; i++) { + ArtifactDescriptor d = new ArtifactDescriptor(new ArtifactKey("osgi.bundle", "a" + i, Version.create("1.0.0"))); + repo.addDescriptor(d); } }, new NullProgressMonitor()); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/StatsTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/StatsTest.java index be7ef817e..05f9f1cfb 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/StatsTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/StatsTest.java @@ -1,10 +1,10 @@ /******************************************************************************* - * Copyright (c) 2012 WindRiver Corporation and others. - * All rights reserved. This program and the accompanying materials + * Copyright (c) 2012, 2017 WindRiver Corporation and others. + * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html - * + * * Contributors: * Wind River Corporation - initial API and implementation *******************************************************************************/ @@ -135,8 +135,8 @@ public class StatsTest extends AbstractTestServerClientCase { protected void checkStatsResult(final String checkpoint) throws FileNotFoundException, CoreException, AuthenticationFailedException, IOException { final Transport transport = (Transport) getAgent().getService(Transport.SERVICE_NAME); - BufferedReader statsResult = new BufferedReader(new InputStreamReader(transport.stream(statsURL, null))); - try { + + try (BufferedReader statsResult = new BufferedReader(new InputStreamReader(transport.stream(statsURL, null)))) { String line = statsResult.readLine(); while (line != null) { if (line.startsWith(checkpoint)) @@ -144,8 +144,6 @@ public class StatsTest extends AbstractTestServerClientCase { line = statsResult.readLine(); } fail("Didn't get expected stats result."); - } finally { - statsResult.close(); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/processing/ProcessingStepHandlerTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/processing/ProcessingStepHandlerTest.java index 4489afac3..9b8762542 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/processing/ProcessingStepHandlerTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/processing/ProcessingStepHandlerTest.java @@ -34,27 +34,27 @@ public class ProcessingStepHandlerTest extends AbstractProvisioningTest { public void testExecuteNoPSs() throws IOException { IProcessingStepDescriptor[] descriptors = new IProcessingStepDescriptor[0]; OutputStream result = new ByteArrayOutputStream(10); - OutputStream testStream = handler.createAndLink(getAgent(), descriptors, null, result, monitor); - testStream.write("Test".getBytes()); - testStream.close(); + try (OutputStream testStream = handler.createAndLink(getAgent(), descriptors, null, result, monitor)) { + testStream.write("Test".getBytes()); + } assertEquals("Test", result.toString()); } public void testExecuteOneByteShifterPS() throws IOException { ProcessingStep[] steps = new ProcessingStep[] {new ByteShifter(1)}; ByteArrayOutputStream result = new ByteArrayOutputStream(10); - OutputStream testStream = handler.link(steps, result, monitor); - testStream.write(new byte[] {1}); - testStream.close(); + try (OutputStream testStream = handler.link(steps, result, monitor)) { + testStream.write(new byte[] {1}); + } assertTrue(Arrays.equals(new byte[] {2}, result.toByteArray())); } public void testExecuteTwoByteShifterPSs() throws IOException { ProcessingStep[] steps = new ProcessingStep[] {new ByteShifter(1), new ByteShifter(2)}; ByteArrayOutputStream result = new ByteArrayOutputStream(10); - OutputStream testStream = handler.link(steps, result, monitor); - testStream.write(new byte[] {1}); - testStream.close(); + try (OutputStream testStream = handler.link(steps, result, monitor)) { + testStream.write(new byte[] {1}); + } assertTrue(Arrays.equals(new byte[] {8}, result.toByteArray())); } @@ -109,19 +109,21 @@ public class ProcessingStepHandlerTest extends AbstractProvisioningTest { public void testAssureOrderingOfPSs1() throws IOException { ProcessingStep[] steps = new ProcessingStep[] {new Adder(1), new Multiplier(2)}; ByteArrayOutputStream result = new ByteArrayOutputStream(10); - OutputStream testStream = handler.link(steps, result, monitor); - testStream.write(new byte[] {1, 2, 3, 4, 5}); - testStream.close(); + try (OutputStream testStream = handler.link(steps, result, monitor)) { + testStream.write(new byte[] {1, 2, 3, 4, 5}); + } assertTrue(Arrays.equals(new byte[] {4, 6, 8, 10, 12}, result.toByteArray())); } public void testAssureOrderingOfPSs2() throws IOException { ProcessingStep[] steps = new ProcessingStep[] {new Multiplier(2), new Adder(1)}; ByteArrayOutputStream result = new ByteArrayOutputStream(10); - OutputStream testStream = handler.link(steps, result, monitor); - testStream.write(new byte[] {1, 2, 3, 4, 5}); - testStream.close(); + try (OutputStream testStream = handler.link(steps, result, monitor)) { + testStream.write(new byte[] {1, 2, 3, 4, 5}); + } + assertTrue(Arrays.equals(new byte[] {3, 5, 7, 9, 11}, result.toByteArray())); + } public void testExecuteOnePack200UnpackerPS() throws IOException { @@ -186,9 +188,9 @@ public class ProcessingStepHandlerTest extends AbstractProvisioningTest { IProcessingStepDescriptor[] descriptors = new IProcessingStepDescriptor[] {adder, multiplier}; ProcessingStep[] steps = handler.create(getAgent(), descriptors, null); ByteArrayOutputStream result = new ByteArrayOutputStream(10); - OutputStream testStream = handler.link(steps, result, monitor); - testStream.write(new byte[] {1, 2, 3, 4, 5}); - testStream.close(); + try (OutputStream testStream = handler.link(steps, result, monitor)) { + testStream.write(new byte[] {1, 2, 3, 4, 5}); + } assertTrue(Arrays.equals(new byte[] {4, 6, 8, 10, 12}, result.toByteArray())); } @@ -198,9 +200,9 @@ public class ProcessingStepHandlerTest extends AbstractProvisioningTest { IProcessingStepDescriptor[] descriptors = new IProcessingStepDescriptor[] {multiplier, adder}; ProcessingStep[] steps = handler.create(getAgent(), descriptors, null); ByteArrayOutputStream result = new ByteArrayOutputStream(10); - OutputStream testStream = handler.link(steps, result, monitor); - testStream.write(new byte[] {1, 2, 3, 4, 5}); - testStream.close(); + try (OutputStream testStream = handler.link(steps, result, monitor)) { + testStream.write(new byte[] {1, 2, 3, 4, 5}); + } assertTrue(Arrays.equals(new byte[] {3, 5, 7, 9, 11}, result.toByteArray())); } @@ -209,9 +211,9 @@ public class ProcessingStepHandlerTest extends AbstractProvisioningTest { IProcessingStepDescriptor multiplier = new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Multiplier", "2", true); IProcessingStepDescriptor[] descriptors = new IProcessingStepDescriptor[] {adder, multiplier}; ByteArrayOutputStream result = new ByteArrayOutputStream(10); - OutputStream testStream = handler.createAndLink(getAgent(), descriptors, null, result, monitor); - testStream.write(new byte[] {1, 2, 3, 4, 5}); - testStream.close(); + try (OutputStream testStream = handler.createAndLink(getAgent(), descriptors, null, result, monitor)) { + testStream.write(new byte[] {1, 2, 3, 4, 5}); + } assertTrue(Arrays.equals(new byte[] {4, 6, 8, 10, 12}, result.toByteArray())); } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/core/BackupTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/core/BackupTest.java index 00256f36d..0a8f7bcad 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/core/BackupTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/core/BackupTest.java @@ -73,11 +73,9 @@ public class BackupTest extends AbstractProvisioningTest { private void writeToFile(File file, String content) throws IOException { file.getParentFile().mkdirs(); file.createNewFile(); - Writer writer = new BufferedWriter(new FileWriter(file)); - try { + + try (Writer writer = new BufferedWriter(new FileWriter(file))) { writer.write(content); - } finally { - writer.close(); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/core/FileUtilsTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/core/FileUtilsTest.java index 0a1b2862c..9c209c7f7 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/core/FileUtilsTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/core/FileUtilsTest.java @@ -1,10 +1,10 @@ /******************************************************************************* - * Copyright (c) 2008,2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials + * Copyright (c) 2008,2017 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html - * + * * Contributors: * IBM Corporation - initial API and implementation * EclipseSource - Bug fix @@ -211,9 +211,7 @@ public class FileUtilsTest extends AbstractProvisioningTest { private static void assertExists(String message, File archive, String entry) { if (!archive.exists()) fail(message + " file does not exist."); - ZipFile zip = null; - try { - zip = new ZipFile(archive); + try (ZipFile zip = new ZipFile(archive)) { boolean found = false; for (Enumeration e = zip.entries(); !found && e.hasMoreElements();) { ZipEntry zipEntry = (ZipEntry) e.nextElement(); @@ -223,13 +221,6 @@ public class FileUtilsTest extends AbstractProvisioningTest { assertTrue(message, found); } catch (IOException e) { fail(message, e); - } finally { - if (zip != null) - try { - zip.close(); - } catch (IOException e) { - // ignore - } } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/InstallCurrentFromPrevious.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/InstallCurrentFromPrevious.java index 3f488b390..f9e6f436f 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/InstallCurrentFromPrevious.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/InstallCurrentFromPrevious.java @@ -1,10 +1,10 @@ /******************************************************************************* - * Copyright (c) 2011 IBM Corporation and others. + * Copyright (c) 2011, 2017 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html - * + * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ @@ -41,10 +41,10 @@ public class InstallCurrentFromPrevious extends AbstractReconcilerTest { File logFile = new File(installFolder, "log.log"); if (logFile.exists()) { StringBuffer fileContents = new StringBuffer(); - BufferedReader reader = new BufferedReader(new FileReader(logFile)); - while (reader.ready()) - fileContents.append(reader.readLine()); - reader.close(); + try (BufferedReader reader = new BufferedReader(new FileReader(logFile))) { + while (reader.ready()) + fileContents.append(reader.readLine()); + } fail("runDirector returned " + result + "\n" + fileContents.toString()); } else { fail("runDirector returned " + result); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/jarprocessor/JarProcessorTests.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/jarprocessor/JarProcessorTests.java index ea046c13a..c17587e2f 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/jarprocessor/JarProcessorTests.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/jarprocessor/JarProcessorTests.java @@ -65,14 +65,12 @@ public class JarProcessorTests extends AbstractProvisioningTest { File plugins = new File(install, "plugins"); PrintStream oldOut = System.out; - PrintStream newOut = new PrintStream(new FileOutputStream(workingDir + "/out.out")); - System.setOut(newOut); + try (PrintStream newOut = new PrintStream(new FileOutputStream(workingDir + "/out.out"))) { + System.setOut(newOut); - try { verifier.verify(workingDir, new String[] {plugins.getAbsolutePath()}); } finally { System.setOut(oldOut); - newOut.close(); } } @@ -108,17 +106,15 @@ public class JarProcessorTests extends AbstractProvisioningTest { options.input = input; PrintStream oldOut = System.out; - PrintStream newOut = new PrintStream(new FileOutputStream(workingDir + "/out.out")); - System.setOut(newOut); + try (PrintStream newOut = new PrintStream(new FileOutputStream(workingDir + "/out.out"))) { + System.setOut(newOut); - try { JarProcessorExecutor executor = new JarProcessorExecutor(); executor.runJarProcessor(options); Verifier.main(new String[] {"-dir", packed.getAbsolutePath(), packed.getAbsolutePath()}); } finally { System.setOut(oldOut); - newOut.close(); } } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/IUPatchPersistenceTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/IUPatchPersistenceTest.java index cbf48b80f..142e38294 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/IUPatchPersistenceTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/IUPatchPersistenceTest.java @@ -235,46 +235,45 @@ public class IUPatchPersistenceTest extends AbstractProvisioningTest { public void testIUPersistence() throws IOException { IInstallableUnit iu0 = createPersistenceTestIU(); validateIU(iu0); - ByteArrayOutputStream output0 = new ByteArrayOutputStream(3072); - IUStringWriter writer0 = new IUStringWriter(output0); - writer0.writeTest(iu0); - String iuText0 = output0.toString(); - output0.close(); - - IUStringParser parser = new IUStringParser(TestActivator.context, TestActivator.PI_PROV_TESTS); - parser.parse(iuText0); - assertTrue("Error parsing test iu: " + parser.getStatus().getMessage(), parser.getStatus().isOK()); - InstallableUnit iu1 = (InstallableUnit) parser.getRootObject(); - validateIU(iu1); - ByteArrayOutputStream output1 = new ByteArrayOutputStream(1492); - IUStringWriter writer = new IUStringWriter(output1); - writer.writeTest(iu1); - String iuText1 = output1.toString(); - output1.close(); - assertTrue("Installable unit write after read after write produced different XML", iuText1.equals(iuText0)); + try (ByteArrayOutputStream output0 = new ByteArrayOutputStream(3072)) { + IUStringWriter writer0 = new IUStringWriter(output0); + writer0.writeTest(iu0); + String iuText0 = output0.toString(); + IUStringParser parser = new IUStringParser(TestActivator.context, TestActivator.PI_PROV_TESTS); + parser.parse(iuText0); + assertTrue("Error parsing test iu: " + parser.getStatus().getMessage(), parser.getStatus().isOK()); + InstallableUnit iu1 = (InstallableUnit) parser.getRootObject(); + validateIU(iu1); + try (ByteArrayOutputStream output1 = new ByteArrayOutputStream(1492)) { + IUStringWriter writer = new IUStringWriter(output1); + writer.writeTest(iu1); + String iuText1 = output1.toString(); + assertTrue("Installable unit write after read after write produced different XML", iuText1.equals(iuText0)); + } + } } public void testIUPatchPersistence() throws IOException { IInstallableUnit iu0 = createPatchIU(); validateIU(iu0); - ByteArrayOutputStream output0 = new ByteArrayOutputStream(3072); - IUStringWriter writer0 = new IUStringWriter(output0); - writer0.writeTest(iu0); - String iuText0 = output0.toString(); - output0.close(); - - IUStringParser parser = new IUStringParser(TestActivator.context, TestActivator.PI_PROV_TESTS); - parser.parse(iuText0); - assertTrue("Error parsing test iu: " + parser.getStatus().getMessage(), parser.getStatus().isOK()); - InstallableUnitPatch iu1 = (InstallableUnitPatch) parser.getRootObject(); - validateIU(iu1); - validateIUPatch(iu1); - ByteArrayOutputStream output1 = new ByteArrayOutputStream(1492); - IUStringWriter writer = new IUStringWriter(output1); - writer.writeTest(iu1); - String iuText1 = output1.toString(); - output1.close(); - assertTrue("Installable unit write after read after write produced different XML", iuText1.equals(iuText0)); + try (ByteArrayOutputStream output0 = new ByteArrayOutputStream(3072)) { + IUStringWriter writer0 = new IUStringWriter(output0); + writer0.writeTest(iu0); + String iuText0 = output0.toString(); + + IUStringParser parser = new IUStringParser(TestActivator.context, TestActivator.PI_PROV_TESTS); + parser.parse(iuText0); + assertTrue("Error parsing test iu: " + parser.getStatus().getMessage(), parser.getStatus().isOK()); + InstallableUnitPatch iu1 = (InstallableUnitPatch) parser.getRootObject(); + validateIU(iu1); + validateIUPatch(iu1); + try (ByteArrayOutputStream output1 = new ByteArrayOutputStream(1492)) { + IUStringWriter writer = new IUStringWriter(output1); + writer.writeTest(iu1); + String iuText1 = output1.toString(); + assertTrue("Installable unit write after read after write produced different XML", iuText1.equals(iuText0)); + } + } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/IUPersistenceTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/IUPersistenceTest.java index e9bb65236..75afe5f5f 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/IUPersistenceTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/IUPersistenceTest.java @@ -341,73 +341,74 @@ public class IUPersistenceTest extends AbstractProvisioningTest { public void testIUPatchPersistence() throws IOException { IInstallableUnit iu0 = createPatchIU(); validateIU(iu0); - ByteArrayOutputStream output0 = new ByteArrayOutputStream(3072); - IUStringWriter writer0 = new IUStringWriter(output0); - writer0.writeTest(iu0); - String iuText0 = output0.toString(); - output0.close(); - - IUStringParser parser = new IUStringParser(TestActivator.context, TestActivator.PI_PROV_TESTS); - parser.parse(iuText0); - assertTrue("Error parsing test iu: " + parser.getStatus().getMessage(), parser.getStatus().isOK()); - InstallableUnitPatch iu1 = (InstallableUnitPatch) parser.getRootObject(); - validateIU(iu1); - validateIUPatch(iu1); - ByteArrayOutputStream output1 = new ByteArrayOutputStream(1492); - IUStringWriter writer = new IUStringWriter(output1); - writer.writeTest(iu1); - String iuText1 = output1.toString(); - output1.close(); - assertTrue("Installable unit write after read after write produced different XML", iuText1.equals(iuText0)); + try (ByteArrayOutputStream output0 = new ByteArrayOutputStream(3072)) { + IUStringWriter writer0 = new IUStringWriter(output0); + writer0.writeTest(iu0); + String iuText0 = output0.toString(); + + IUStringParser parser = new IUStringParser(TestActivator.context, TestActivator.PI_PROV_TESTS); + parser.parse(iuText0); + assertTrue("Error parsing test iu: " + parser.getStatus().getMessage(), parser.getStatus().isOK()); + InstallableUnitPatch iu1 = (InstallableUnitPatch) parser.getRootObject(); + validateIU(iu1); + validateIUPatch(iu1); + try (ByteArrayOutputStream output1 = new ByteArrayOutputStream(1492)) { + IUStringWriter writer = new IUStringWriter(output1); + writer.writeTest(iu1); + String iuText1 = output1.toString(); + output1.close(); + assertTrue("Installable unit write after read after write produced different XML", iuText1.equals(iuText0)); + } + } } public void testIUPatchPersistence2() throws IOException { IInstallableUnit iu0 = createPatchWithEmptyScope(); validateIU(iu0); - ByteArrayOutputStream output0 = new ByteArrayOutputStream(3072); - IUStringWriter writer0 = new IUStringWriter(output0); - writer0.writeTest(iu0); - String iuText0 = output0.toString(); - output0.close(); - - IUStringParser parser = new IUStringParser(TestActivator.context, TestActivator.PI_PROV_TESTS); - parser.parse(iuText0); - assertTrue("Error parsing test iu: " + parser.getStatus().getMessage(), parser.getStatus().isOK()); - InstallableUnitPatch iu1 = (InstallableUnitPatch) parser.getRootObject(); - validateIU(iu1); - validateIUPatchWithEmptyScope(iu1); - ByteArrayOutputStream output1 = new ByteArrayOutputStream(1492); - IUStringWriter writer = new IUStringWriter(output1); - writer.writeTest(iu1); - output1.close(); - //the content on disk is not the same but it is normal because a RequiredCapability array of RequiredCapability[0][0] is not persisted the same - // than RequiredCapability[][] {{}} - //assertTrue("Installable unit write after read after write produced different XML", iuText1.equals(iuText0)); + try (ByteArrayOutputStream output0 = new ByteArrayOutputStream(3072)) { + IUStringWriter writer0 = new IUStringWriter(output0); + writer0.writeTest(iu0); + String iuText0 = output0.toString(); + + IUStringParser parser = new IUStringParser(TestActivator.context, TestActivator.PI_PROV_TESTS); + parser.parse(iuText0); + assertTrue("Error parsing test iu: " + parser.getStatus().getMessage(), parser.getStatus().isOK()); + InstallableUnitPatch iu1 = (InstallableUnitPatch) parser.getRootObject(); + validateIU(iu1); + validateIUPatchWithEmptyScope(iu1); + try (ByteArrayOutputStream output1 = new ByteArrayOutputStream(1492)) { + IUStringWriter writer = new IUStringWriter(output1); + writer.writeTest(iu1); + } + //the content on disk is not the same but it is normal because a RequiredCapability array of RequiredCapability[0][0] is not persisted the same + // than RequiredCapability[][] {{}} + //assertTrue("Installable unit write after read after write produced different XML", iuText1.equals(iuText0)); + } } public void testIUPersistence() throws IOException { IInstallableUnit iu0 = createPersistenceTestIU(); validateIU(iu0); - ByteArrayOutputStream output0 = new ByteArrayOutputStream(3072); - IUStringWriter writer0 = new IUStringWriter(output0); - writer0.writeTest(iu0); - String iuText0 = output0.toString(); - output0.close(); - - IUStringParser parser = new IUStringParser(TestActivator.context, TestActivator.PI_PROV_TESTS); - parser.parse(iuText0); - assertTrue("Error parsing test iu: " + parser.getStatus().getMessage(), parser.getStatus().isOK()); - InstallableUnit iu1 = (InstallableUnit) parser.getRootObject(); - validateIU(iu1); - assertEquals(2, iu1.getLicenses().size()); - ByteArrayOutputStream output1 = new ByteArrayOutputStream(1492); - IUStringWriter writer = new IUStringWriter(output1); - writer.writeTest(iu1); - String iuText1 = output1.toString(); - output1.close(); - assertTrue("Installable unit write after read after write produced different XML", iuText1.equals(iuText0)); + try (ByteArrayOutputStream output0 = new ByteArrayOutputStream(3072)) { + IUStringWriter writer0 = new IUStringWriter(output0); + writer0.writeTest(iu0); + String iuText0 = output0.toString(); + + IUStringParser parser = new IUStringParser(TestActivator.context, TestActivator.PI_PROV_TESTS); + parser.parse(iuText0); + assertTrue("Error parsing test iu: " + parser.getStatus().getMessage(), parser.getStatus().isOK()); + InstallableUnit iu1 = (InstallableUnit) parser.getRootObject(); + validateIU(iu1); + assertEquals(2, iu1.getLicenses().size()); + try (ByteArrayOutputStream output1 = new ByteArrayOutputStream(1492)) { + IUStringWriter writer = new IUStringWriter(output1); + writer.writeTest(iu1); + String iuText1 = output1.toString(); + assertTrue("Installable unit write after read after write produced different XML", iuText1.equals(iuText0)); + } + } } private void validateIU(IInstallableUnit iu) { diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/expression/FilterTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/expression/FilterTest.java index f9256d084..289babcaa 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/expression/FilterTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/expression/FilterTest.java @@ -79,6 +79,7 @@ public class FilterTest extends TestCase { throw new UnsupportedOperationException(); } + @Override public Dictionary getProperties() { return new Hashtable(dictionary); } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/AllServerTests.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/AllServerTests.java index afbb003b0..6eed3b348 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/AllServerTests.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/AllServerTests.java @@ -91,13 +91,8 @@ public class AllServerTests extends TestCase { } private static int obtainFreePort() throws IOException { - ServerSocket socket = null; - try { - socket = new ServerSocket(0); + try (ServerSocket socket = new ServerSocket(0)) { return socket.getLocalPort(); - } finally { - if (socket != null) - socket.close(); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/BatchExecuteMetadataRepositoryTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/BatchExecuteMetadataRepositoryTest.java index 5e3ef3241..cd304cb69 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/BatchExecuteMetadataRepositoryTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/BatchExecuteMetadataRepositoryTest.java @@ -40,15 +40,10 @@ public class BatchExecuteMetadataRepositoryTest extends AbstractProvisioningTest boolean fileContainsString(URI location, String string) throws IOException { StringBuffer buffer = new StringBuffer(); - BufferedReader reader = null; - try { - reader = new BufferedReader(new FileReader(new File(location))); + try (BufferedReader reader = new BufferedReader(new FileReader(new File(location)));) { while (reader.ready()) buffer.append(reader.readLine()); return buffer.toString().contains(string); - } finally { - if (reader != null) - reader.close(); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/StandaloneSerializationTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/StandaloneSerializationTest.java index 0f292f5f8..468f7d335 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/StandaloneSerializationTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/StandaloneSerializationTest.java @@ -21,9 +21,9 @@ public class StandaloneSerializationTest extends TestCase { public void testNothingToWrite() { try { File f = File.createTempFile(getName(), "iu"); - OutputStream os = new FileOutputStream(f); - new IUSerializer(os).write(Collections.EMPTY_LIST); - os.close(); + try (OutputStream os = new FileOutputStream(f)) { + new IUSerializer(os).write(Collections.EMPTY_LIST); + } assertTrue(f.length() > 0); f.delete(); } catch (FileNotFoundException e) { @@ -40,9 +40,9 @@ public class StandaloneSerializationTest extends TestCase { File f = null; try { f = File.createTempFile(getName(), "iu"); - OutputStream os = new FileOutputStream(f); - new IUSerializer(os).write(Collections.EMPTY_LIST); - os.close(); + try (OutputStream os = new FileOutputStream(f)) { + new IUSerializer(os).write(Collections.EMPTY_LIST); + } } catch (FileNotFoundException e) { fail("problem writing: " + e.getCause().getMessage()); } catch (UnsupportedEncodingException e) { @@ -53,11 +53,9 @@ public class StandaloneSerializationTest extends TestCase { //Read file written boolean exceptionRaised = false; - try { - InputStream is = new FileInputStream(f); + try (InputStream is = new FileInputStream(f)) { Collection<IInstallableUnit> ius = new IUDeserializer().read(is); assertEquals(0, ius.size()); - is.close(); } catch (FileNotFoundException e) { fail("problem writing: " + e.getCause().getMessage()); } catch (UnsupportedEncodingException e) { @@ -85,9 +83,9 @@ public class StandaloneSerializationTest extends TestCase { File f = null; try { f = File.createTempFile(getName(), "iu"); - OutputStream os = new FileOutputStream(f); - new IUSerializer(os).write(ius); - os.close(); + try (OutputStream os = new FileOutputStream(f)) { + new IUSerializer(os).write(ius); + } } catch (FileNotFoundException e) { fail("problem writing: " + e.getCause().getMessage()); } catch (UnsupportedEncodingException e) { @@ -96,9 +94,7 @@ public class StandaloneSerializationTest extends TestCase { fail("problem writing: " + e.getCause().getMessage()); } - InputStream is = null; - try { - is = new FileInputStream(f); + try (InputStream is = new FileInputStream(f)) { assertEquals(2, new IUDeserializer().read(is).size()); } catch (FileNotFoundException e) { fail("problem writing: " + e.getCause().getMessage()); @@ -107,12 +103,7 @@ public class StandaloneSerializationTest extends TestCase { } catch (IOException e) { fail("problem writing: " + e.getCause().getMessage()); } finally { - try { - is.close(); - f.delete(); - } catch (IOException e) { - //ignore - } + f.delete(); } } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/mirror/ArtifactMirrorApplicationTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/mirror/ArtifactMirrorApplicationTest.java index 14a0fd02f..fb3520ea9 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/mirror/ArtifactMirrorApplicationTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/mirror/ArtifactMirrorApplicationTest.java @@ -886,20 +886,15 @@ public class ArtifactMirrorApplicationTest extends AbstractProvisioningTest { properties.remove(IArtifactDescriptor.FORMAT); ((ArtifactDescriptor) newDescriptor).addProperties(properties); //create appropriate descriptor - try { - OutputStream repositoryStream = null; - try { - //System.out.println("Mirroring: " + srcDescriptors[j].getArtifactKey() + " (Descriptor: " + srcDescriptors[j] + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - repositoryStream = destinationRepo.getOutputStream(newDescriptor); - if (repositoryStream == null) - return; - // TODO Is that ok to ignore the result? - //TODO MAKE THIS WORK PROPERLY - packedRepo.getArtifact(srcDescriptors[j], repositoryStream, new NullProgressMonitor()); - } finally { - if (repositoryStream != null) - repositoryStream.close(); - } + + try (OutputStream repositoryStream = destinationRepo.getOutputStream(newDescriptor)) { + //System.out.println("Mirroring: " + srcDescriptors[j].getArtifactKey() + " (Descriptor: " + srcDescriptors[j] + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + + if (repositoryStream == null) + return; + // TODO Is that ok to ignore the result? + //TODO MAKE THIS WORK PROPERLY + packedRepo.getArtifact(srcDescriptors[j], repositoryStream, new NullProgressMonitor()); } catch (ProvisionException e) { fail("27.1", e); } catch (IOException e) { diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/mirror/NewMirrorApplicationArtifactTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/mirror/NewMirrorApplicationArtifactTest.java index c61c2db8d..46a4d6399 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/mirror/NewMirrorApplicationArtifactTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/mirror/NewMirrorApplicationArtifactTest.java @@ -944,20 +944,14 @@ public class NewMirrorApplicationArtifactTest extends AbstractProvisioningTest { properties.remove(IArtifactDescriptor.FORMAT); ((ArtifactDescriptor) newDescriptor).addProperties(properties); //create appropriate descriptor - try { - OutputStream repositoryStream = null; - try { - //System.out.println("Mirroring: " + srcDescriptors[j].getArtifactKey() + " (Descriptor: " + srcDescriptors[j] + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - repositoryStream = destinationRepo.getOutputStream(newDescriptor); - if (repositoryStream == null) - return; - // TODO Is that ok to ignore the result? - //TODO MAKE THIS WORK PROPERLY - packedRepo.getArtifact(srcDescriptors[j], repositoryStream, new NullProgressMonitor()); - } finally { - if (repositoryStream != null) - repositoryStream.close(); - } + + try (OutputStream repositoryStream = destinationRepo.getOutputStream(newDescriptor)) { + //System.out.println("Mirroring: " + srcDescriptors[j].getArtifactKey() + " (Descriptor: " + srcDescriptors[j] + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + if (repositoryStream == null) + return; + // TODO Is that ok to ignore the result? + //TODO MAKE THIS WORK PROPERLY + packedRepo.getArtifact(srcDescriptors[j], repositoryStream, new NullProgressMonitor()); } catch (ProvisionException e) { fail("27.1", e); } catch (IOException e) { diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/VersionTesting.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/VersionTesting.java index 634c8bd10..f348a88e0 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/VersionTesting.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/VersionTesting.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009, 2010 Cloudsmith Inc. and others. + * Copyright (c) 2009, 2017 Cloudsmith Inc. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -19,7 +19,7 @@ import org.eclipse.equinox.p2.metadata.VersionRange; /** * Base class for version testing. Adds useful assert methods. - * + * */ public class VersionTesting extends TestCase { /** @@ -42,7 +42,7 @@ public class VersionTesting extends TestCase { assertFalse(message, range.isIncluded(Version.parseVersion(versionString))); } - /** + /** * A strict assertion of order. * asserts that b > a, a < b, a !=b, b != a * @param a @@ -103,24 +103,8 @@ public class VersionTesting extends TestCase { public static VersionRange getSerialized(VersionRange range) { ByteArrayOutputStream out = new ByteArrayOutputStream(); - ObjectOutputStream os = null; - try { - os = new ObjectOutputStream(out); - } catch (IOException e) { - e.printStackTrace(); - fail("IOException creating ObjectOutputStream"); - } - try { + try (ObjectOutputStream os = new ObjectOutputStream(out);) { os.writeObject(range); - - } catch (NotSerializableException e) { - fail("Impl of VersionRange is wrong - it is not serializeable"); - } catch (IOException e) { - e.printStackTrace(); - fail("write of objectfailed"); - } - try { - os.close(); } catch (IOException e1) { // TODO Auto-generated catch block fail("close of output stream failed"); @@ -156,22 +140,8 @@ public class VersionTesting extends TestCase { public static Version getSerialized(Version v) { ByteArrayOutputStream out = new ByteArrayOutputStream(); - ObjectOutputStream os = null; - try { - os = new ObjectOutputStream(out); - } catch (IOException e) { - fail("IOException creating ObjectOutputStream"); - } - try { + try (ObjectOutputStream os = new ObjectOutputStream(out);) { os.writeObject(v); - } catch (NotSerializableException e) { - e.printStackTrace(); - fail("Impl of Version is wrong - it is not serializeable"); - } catch (IOException e) { - fail("write of objectfailed"); - } - try { - os.close(); } catch (IOException e1) { // TODO Auto-generated catch block fail("close of output stream failed"); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/BundlesActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/BundlesActionTest.java index 6a525fab0..1a3d69059 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/BundlesActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/BundlesActionTest.java @@ -186,17 +186,13 @@ public class BundlesActionTest extends ActionTest { canonicalIdx = 0; } - ZipInputStream actual = artifactRepository.getZipInputStream(descriptors[canonicalIdx]); - ZipInputStream expected = new ZipInputStream(new FileInputStream(TEST_FILE2)); - TestData.assertEquals(expected, actual); - actual.close(); - expected.close(); + try (ZipInputStream actual = artifactRepository.getZipInputStream(descriptors[canonicalIdx]); ZipInputStream expected = new ZipInputStream(new FileInputStream(TEST_FILE2))) { + TestData.assertEquals(expected, actual); + } InputStream packedActual = artifactRepository.getRawInputStream(descriptors[packedIdx]); InputStream packedExpected = new BufferedInputStream(new FileInputStream(TEST_FILE2_PACKED)); TestData.assertEquals(packedExpected, packedActual); - actual.close(); - expected.close(); IArtifactKey key1 = ArtifactKey.parse("osgi.bundle,test1,0.1.0");//$NON-NLS-1$ ZipInputStream zis = artifactRepository.getZipInputStream(key1); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/EquinoxExecutableActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/EquinoxExecutableActionTest.java index 0bff49b18..2c907a827 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/EquinoxExecutableActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/EquinoxExecutableActionTest.java @@ -188,24 +188,19 @@ public class EquinoxExecutableActionTest extends ActionTest { private void checkExecutableContents(IArtifactKey key) throws IOException { File file = File.createTempFile("exec", ".zip"); - FileOutputStream fos = new FileOutputStream(file); - try { + + try (FileOutputStream fos = new FileOutputStream(file)) { IArtifactDescriptor ad = artifactRepository.createArtifactDescriptor(key); IStatus result = artifactRepository.getArtifact(ad, fos, new NullProgressMonitor()); assertTrue("executable not published?", result.isOK()); - } finally { - fos.close(); } - ZipFile zip = new ZipFile(file); - try { + try (ZipFile zip = new ZipFile(file)) { for (String path : expectedExecutablesContents) { assertNotNull("executable zip missing " + path, zip.getEntry(path)); } if (key.getId().contains("macosx")) checkInfoPlist(zip); - } finally { - zip.close(); } // cleanup @@ -247,21 +242,14 @@ public class EquinoxExecutableActionTest extends ActionTest { } private String readContentsAndClose(InputStream inputStream) throws IOException { - try { - StringBuilder sb = new StringBuilder(); - Reader is = new InputStreamReader(inputStream); + StringBuilder sb = new StringBuilder(); + try (Reader is = new InputStreamReader(inputStream)) { char[] buf = new char[1024]; int rc; while ((rc = is.read(buf)) >= 0) { sb.append(buf, 0, rc - 1); } return sb.toString(); - } finally { - try { - inputStream.close(); - } catch (IOException e) { - /* ignored */ - } } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/reconciler/dropins/AbstractReconcilerTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/reconciler/dropins/AbstractReconcilerTest.java index 2f4715fb7..d0a56fca9 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/reconciler/dropins/AbstractReconcilerTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/reconciler/dropins/AbstractReconcilerTest.java @@ -117,20 +117,18 @@ public class AbstractReconcilerTest extends AbstractProvisioningTest { protected static int run(String message, String[] commandArray, File outputFile) { PrintStream out = System.out; PrintStream err = System.err; - PrintStream fileStream = null; try { outputFile.getParentFile().mkdirs(); - fileStream = new PrintStream(new FileOutputStream(outputFile)); - System.setErr(fileStream); - System.setOut(fileStream); - return run(message, commandArray); + try (PrintStream fileStream = new PrintStream(new FileOutputStream(outputFile))) { + System.setErr(fileStream); + System.setOut(fileStream); + return run(message, commandArray); + } } catch (FileNotFoundException e) { return -1; } finally { System.setOut(out); System.setErr(err); - if (fileStream != null) - fileStream.close(); } } @@ -258,19 +256,10 @@ public class AbstractReconcilerTest extends AbstractProvisioningTest { file.getParentFile().mkdirs(); Properties properties = new Properties(); properties.put("path", extensionLocation); - OutputStream stream = null; - try { - stream = new BufferedOutputStream(new FileOutputStream(file)); + try (OutputStream stream = new BufferedOutputStream(new FileOutputStream(file));) { properties.store(stream, null); } catch (IOException e) { fail(message, e); - } finally { - try { - if (stream != null) - stream.close(); - } catch (IOException e) { - // ignore - } } } @@ -337,17 +326,8 @@ public class AbstractReconcilerTest extends AbstractProvisioningTest { public BundleInfo[] loadBundlesInfo(File location) throws IOException { SimpleConfiguratorManipulator manipulator = new SimpleConfiguratorManipulatorImpl(); - InputStream input = null; - try { - input = new BufferedInputStream(new FileInputStream(location)); + try (InputStream input = new BufferedInputStream(new FileInputStream(location));) { return manipulator.loadConfiguration(input, new File(output, "eclipse").toURI()); - } finally { - try { - if (input != null) - input.close(); - } catch (IOException e) { - // ignore - } } } @@ -672,22 +652,13 @@ public class AbstractReconcilerTest extends AbstractProvisioningTest { if (!file.exists()) return null; StringBuffer buffer = new StringBuffer(); - BufferedReader reader = null; - try { - reader = new BufferedReader(new FileReader(file)); + try (BufferedReader reader = new BufferedReader(new FileReader(file))) { for (String line = reader.readLine(); line != null; line = reader.readLine()) { buffer.append(line); buffer.append('\n'); } } catch (IOException e) { // TODO - } finally { - if (reader != null) - try { - reader.close(); - } catch (IOException e) { - // ignore - } } return buffer.toString(); } @@ -774,12 +745,8 @@ public class AbstractReconcilerTest extends AbstractProvisioningTest { return; archiveAndRepositoryProperties = new Properties(); try { - InputStream is = null; - try { - is = new BufferedInputStream(new FileInputStream(propertiesFile)); + try (InputStream is = new BufferedInputStream(new FileInputStream(propertiesFile))) { archiveAndRepositoryProperties.load(is); - } finally { - is.close(); } } catch (IOException e) { return; diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/reconciler/dropins/AbstractSharedBundleProductTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/reconciler/dropins/AbstractSharedBundleProductTest.java index 1f25e27f7..f1fdd72f3 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/reconciler/dropins/AbstractSharedBundleProductTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/reconciler/dropins/AbstractSharedBundleProductTest.java @@ -153,36 +153,18 @@ public class AbstractSharedBundleProductTest extends AbstractReconcilerTest { private void updateConfigIni(Map<String, BundleInfo> infos) { File location = new File(output, "eclipse/configuration/config.ini"); Properties ini = new Properties(); - InputStream input = null; - try { - input = new BufferedInputStream(new FileInputStream(location)); + try (InputStream input = new BufferedInputStream(new FileInputStream(location))) { ini.load(input); } catch (IOException e) { fail("Exception while loading config.ini from: " + location.getAbsolutePath(), e); - } finally { - if (input != null) - try { - input.close(); - } catch (IOException e) { - // ignore - } } BundleInfo framework = infos.get("org.eclipse.osgi"); assertNotNull("Unable to find framework in list of bootstrap bundles.", framework); ini.put("osgi.framework", framework.getLocation().toString()); - OutputStream out = null; - try { - out = new BufferedOutputStream(new FileOutputStream(location)); + try (OutputStream out = new BufferedOutputStream(new FileOutputStream(location));) { ini.store(out, null); } catch (IOException e) { fail("Exception while saving config.ini to: " + location.getAbsolutePath(), e); - } finally { - if (out != null) - try { - out.close(); - } catch (IOException e) { - // ignore - } } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/reconciler/dropins/SharedInstallTests.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/reconciler/dropins/SharedInstallTests.java index 048578b34..b6b8235f5 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/reconciler/dropins/SharedInstallTests.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/reconciler/dropins/SharedInstallTests.java @@ -1,10 +1,10 @@ /******************************************************************************* - * Copyright (c) 2008, 2013 IBM Corporation and others. + * Copyright (c) 2008, 2017 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html - * + * * Contributors: * IBM Corporation - initial API and implementation * Red Hat, Inc. - fragments support added. @@ -95,11 +95,8 @@ public class SharedInstallTests extends AbstractReconcilerTest { assertTrue("0.4", userConfigIni.exists()); Properties props = new Properties(); - InputStream is = new BufferedInputStream(new FileInputStream(userConfigIni)); - try { + try (InputStream is = new BufferedInputStream(new FileInputStream(userConfigIni))) { props.load(is); - } finally { - is.close(); } assertTrue("0.5", props.containsKey("osgi.sharedConfiguration.area")); assertTrue("0.6", props.size() == 1); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/reconciler/dropins/SharedInstallTestsProfileSpoofEnabledConfigured.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/reconciler/dropins/SharedInstallTestsProfileSpoofEnabledConfigured.java index 07ef2739f..b89da47ec 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/reconciler/dropins/SharedInstallTestsProfileSpoofEnabledConfigured.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/reconciler/dropins/SharedInstallTestsProfileSpoofEnabledConfigured.java @@ -98,11 +98,8 @@ public class SharedInstallTestsProfileSpoofEnabledConfigured extends SharedInsta assertTrue("0.4", userConfigIni.exists()); Properties props = new Properties(); - InputStream is = new BufferedInputStream(new FileInputStream(userConfigIni)); - try { + try (InputStream is = new BufferedInputStream(new FileInputStream(userConfigIni))) { props.load(is); - } finally { - is.close(); } assertTrue("0.5", props.containsKey("osgi.sharedConfiguration.area")); assertTrue("0.6", props.size() == 1); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/repository/FileReaderTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/repository/FileReaderTest.java index 2deccbcf8..7ba30e182 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/repository/FileReaderTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/repository/FileReaderTest.java @@ -1,10 +1,10 @@ /******************************************************************************* - * Copyright (c) 2009, 2010 Cloudsmith Inc and others. - * All rights reserved. This program and the accompanying materials + * Copyright (c) 2009, 2017 Cloudsmith Inc and others. + * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html - * + * * Contributors: * Cloudsmith Inc - initial API and implementation *******************************************************************************/ @@ -50,8 +50,9 @@ public class FileReaderTest extends AbstractTestServerClientCase { RepositoryTransport transport = new RepositoryTransport(); URI toDownload = new URI(getBaseURL() + "/public/index.html"); final NullProgressMonitor monitor = new NullProgressMonitor(); - InputStream stream = transport.stream(toDownload, monitor); - stream.close(); + try (InputStream stream = transport.stream(toDownload, monitor)) { + // + } assertFalse("1.0", monitor.isCanceled()); } @@ -72,5 +73,5 @@ public class FileReaderTest extends AbstractTestServerClientCase { // redirected many times = login // handling of incorrect file size - // + // } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/repository/FileReaderTest2.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/repository/FileReaderTest2.java index 8158c44e8..ef1bc96a4 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/repository/FileReaderTest2.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/repository/FileReaderTest2.java @@ -189,8 +189,6 @@ public class FileReaderTest2 extends AbstractProvisioningTest { private void doFileReaderTest(final PauseJob pauseJob, IProgressMonitor monitor) throws IOException, CoreException { final String testRemoteFileURL = "http://download.eclipse.org/releases/juno/201206270900/content.jar"; - OutputStream out = null; - OutputStream out1 = null; File tmpFolder = getTempFolder(); File tmpFile = new File(tmpFolder, "testDownloadPauseResume.zip"); File tmpFile1 = new File(tmpFolder, "testDownloadWithoutPause.zip"); @@ -209,25 +207,23 @@ public class FileReaderTest2 extends AbstractProvisioningTest { getEventBus().addListener(listener); try { tmpFile1.createNewFile(); - out1 = new FileOutputStream(tmpFile1); - FileReader readerWithoutPausing = new FileReader(null, null); - readerWithoutPausing.readInto(URI.create(testRemoteFileURL), out1, null); - assertNotNull(readerWithoutPausing.getResult()); - assertTrue(readerWithoutPausing.getResult().isOK()); - tmpFile.createNewFile(); - out = new FileOutputStream(tmpFile); - FileReader reader = pauseJob.getReader(); - reader.readInto(URI.create(testRemoteFileURL), out, monitor); - assertNotNull(reader.getResult()); - assertTrue(reader.getResult().isOK()); - assertEquals("File with pausing/resuming is not identical with file without pausing.", tmpFile1.length(), tmpFile.length()); + try (OutputStream out1 = new FileOutputStream(tmpFile1)) { + FileReader readerWithoutPausing = new FileReader(null, null); + readerWithoutPausing.readInto(URI.create(testRemoteFileURL), out1, null); + assertNotNull(readerWithoutPausing.getResult()); + assertTrue(readerWithoutPausing.getResult().isOK()); + tmpFile.createNewFile(); + try (OutputStream out = new FileOutputStream(tmpFile)) { + FileReader reader = pauseJob.getReader(); + reader.readInto(URI.create(testRemoteFileURL), out, monitor); + assertNotNull(reader.getResult()); + assertTrue(reader.getResult().isOK()); + assertEquals("File with pausing/resuming is not identical with file without pausing.", tmpFile1.length(), tmpFile.length()); + } + } } finally { getEventBus().removeListener(listener); - if (out1 != null) - out1.close(); tmpFile1.delete(); - if (out != null) - out.close(); tmpFile.delete(); delete(tmpFolder); } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/sharedinstall/AbstractSharedInstallTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/sharedinstall/AbstractSharedInstallTest.java index 119f0a766..43e573832 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/sharedinstall/AbstractSharedInstallTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/sharedinstall/AbstractSharedInstallTest.java @@ -1,10 +1,10 @@ /******************************************************************************* - * Copyright (c) 2013 Ericsson AB and others. All rights reserved. This + * Copyright (c) 2013, 2017 Ericsson AB and others. All rights reserved. This * program and the accompanying materials are made available under the terms of * the Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: + * + * Contributors: * Ericsson AB - initial API and implementation * Red Hat, Inc. - fragments support ******************************************************************************/ @@ -196,12 +196,7 @@ public abstract class AbstractSharedInstallTest extends AbstractReconcilerTest { public static void reallyReadOnly(File folder, boolean recurse) { reallyReadOnly(folder); if (folder.exists() && recurse) { - File[] dirs = folder.listFiles(new FileFilter() { - @Override - public boolean accept(File pathname) { - return pathname.isDirectory(); - } - }); + File[] dirs = folder.listFiles((FileFilter) pathname -> pathname.isDirectory()); for (File dir : dirs) { reallyReadOnly(dir, true); } @@ -228,12 +223,7 @@ public abstract class AbstractSharedInstallTest extends AbstractReconcilerTest { public static void removeReallyReadOnly(File folder, boolean recurse) { removeReallyReadOnly(folder); if (folder.exists() && recurse) { - File[] dirs = folder.listFiles(new FileFilter() { - @Override - public boolean accept(File pathname) { - return pathname.isDirectory(); - } - }); + File[] dirs = folder.listFiles((FileFilter) pathname -> pathname.isDirectory()); for (File dir : dirs) { removeReallyReadOnly(dir, true); } @@ -311,15 +301,8 @@ public abstract class AbstractSharedInstallTest extends AbstractReconcilerTest { Properties newProps = new Properties(); newProps.put("id", id); newProps.put("version", version); - OutputStream os = null; - try { - try { - os = new FileOutputStream(eclipseProductFile); - newProps.save(os, "file generated for tests " + getName()); - } finally { - if (os != null) - os.close(); - } + try (OutputStream os = new FileOutputStream(eclipseProductFile)) { + newProps.save(os, "file generated for tests " + getName()); } catch (IOException e) { fail("Failing setting up the .eclipseproduct file at:" + eclipseProductFile.getAbsolutePath()); } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/simpleconfigurator/AbstractSimpleConfiguratorTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/simpleconfigurator/AbstractSimpleConfiguratorTest.java index 3d88a4145..bd1b02eae 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/simpleconfigurator/AbstractSimpleConfiguratorTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/simpleconfigurator/AbstractSimpleConfiguratorTest.java @@ -117,16 +117,16 @@ public abstract class AbstractSimpleConfiguratorTest extends AbstractProvisionin File bundlesTxt = File.createTempFile("bundles", ".txt"); bundlesTxt.deleteOnExit(); - BufferedWriter bundlesTxtOut = new BufferedWriter(new FileWriter(bundlesTxt)); + try (BufferedWriter bundlesTxtOut = new BufferedWriter(new FileWriter(bundlesTxt))) { - for (int i = 0; i < jars.length; i++) { - File bundleJar = jars[i]; - bundlesTxtOut.write(getBundlesTxtEntry(bundleJar) + "\n"); - } - bundlesTxtOut.write(getBundlesTxtEntry(getLocation("org.eclipse.equinox.simpleconfigurator")) + "\n"); - bundlesTxtOut.write(getBundlesTxtEntry(getLocation("org.eclipse.osgi")) + "\n"); + for (int i = 0; i < jars.length; i++) { + File bundleJar = jars[i]; + bundlesTxtOut.write(getBundlesTxtEntry(bundleJar) + "\n"); + } + bundlesTxtOut.write(getBundlesTxtEntry(getLocation("org.eclipse.equinox.simpleconfigurator")) + "\n"); + bundlesTxtOut.write(getBundlesTxtEntry(getLocation("org.eclipse.osgi")) + "\n"); - bundlesTxtOut.close(); + } return bundlesTxt; } @@ -143,21 +143,14 @@ public abstract class AbstractSimpleConfiguratorTest extends AbstractProvisionin String value = null; if (bundleFile.isDirectory()) { File m = new File(bundleFile, "META-INF/MANIFEST.MF"); - InputStream os; - os = new FileInputStream(m); - Manifest mf; - mf = new Manifest(os); - value = mf.getMainAttributes().getValue(entry); - os.close(); + try (InputStream os = new FileInputStream(m)) { + Manifest mf; + mf = new Manifest(os); + value = mf.getMainAttributes().getValue(entry); + } } else { - JarFile bundleJar = null; - try { - bundleJar = new JarFile(bundleFile); + try (JarFile bundleJar = new JarFile(bundleFile)) { value = bundleJar.getManifest().getMainAttributes().getValue(entry); - } finally { - if (bundleJar != null) { - bundleJar.close(); - } } } if (value.indexOf(";") > -1) { diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/testserver/helper/TestServerController.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/testserver/helper/TestServerController.java index 892e34813..c81f93afa 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/testserver/helper/TestServerController.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/testserver/helper/TestServerController.java @@ -64,13 +64,8 @@ public class TestServerController { } private static int obtainFreePort() throws IOException { - ServerSocket socket = null; - try { - socket = new ServerSocket(0); + try (ServerSocket socket = new ServerSocket(0);) { return socket.getLocalPort(); - } finally { - if (socket != null) - socket.close(); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/BackupStoreTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/BackupStoreTest.java index a82e591ac..51d548201 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/BackupStoreTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/BackupStoreTest.java @@ -61,11 +61,9 @@ public class BackupStoreTest extends AbstractProvisioningTest { private void writeToFile(File file, String content) throws IOException { file.getParentFile().mkdirs(); file.createNewFile(); - Writer writer = new BufferedWriter(new FileWriter(file)); - try { + + try (Writer writer = new BufferedWriter(new FileWriter(file))) { writer.write(content); - } finally { - writer.close(); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/RemoveActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/RemoveActionTest.java index d61440c8d..418587bc0 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/RemoveActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/RemoveActionTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009, 2011 Cloudsmith Inc. and others. + * Copyright (c) 2009, 2017 Cloudsmith Inc. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -139,9 +139,8 @@ public class RemoveActionTest extends AbstractProvisioningTest { private static void writeToFile(File file, String content) throws IOException { file.getParentFile().mkdirs(); file.createNewFile(); - FileWriter writer = new FileWriter(file); - BufferedWriter out = new BufferedWriter(writer); - out.write(content); - out.close(); + try (FileWriter writer = new FileWriter(file); BufferedWriter out = new BufferedWriter(writer)) { + out.write(content); + } } }
\ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/UnzipActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/UnzipActionTest.java index d831b24f8..a0539cab0 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/UnzipActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/UnzipActionTest.java @@ -25,10 +25,9 @@ public class UnzipActionTest extends AbstractProvisioningTest { private static void writeToFile(File file, String content) throws IOException { file.getParentFile().mkdirs(); file.createNewFile(); - FileWriter writer = new FileWriter(file); - BufferedWriter out = new BufferedWriter(writer); - out.write(content); - out.close(); + try (FileWriter writer = new FileWriter(file); BufferedWriter out = new BufferedWriter(writer)) { + out.write(content); + } } public UnzipActionTest() { diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/updatesite/UpdateSiteTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/updatesite/UpdateSiteTest.java index a959c5fd0..6bc17784c 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/updatesite/UpdateSiteTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/updatesite/UpdateSiteTest.java @@ -1,10 +1,10 @@ /******************************************************************************* - * Copyright (c) 2008, 2010 IBM Corporation and others. + * Copyright (c) 2008, 2017 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html - * + * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ @@ -777,11 +777,9 @@ public class UpdateSiteTest extends AbstractProvisioningTest { // Should have a packed & canonical version assertEquals(2, descriptors.length); IArtifactDescriptor desc = IArtifactDescriptor.FORMAT_PACKED.equals(descriptors[0].getProperty(IArtifactDescriptor.FORMAT)) ? descriptors[0] : descriptors[1]; - OutputStream out = null; - try { - out = new FileOutputStream(output); + try (OutputStream out = new FileOutputStream(output)) { + IStatus status = repo.getRawArtifact(desc, out, new NullProgressMonitor()); - out.close(); // Transfer should succeed assertTrue(status.isOK()); // Length should be as expected @@ -790,12 +788,6 @@ public class UpdateSiteTest extends AbstractProvisioningTest { fail("Failed", e); } finally { getArtifactRepositoryManager().removeRepository(siteURI); - if (out != null) - try { - out.close(); - } catch (IOException e) { - // Don't care - } } } @@ -941,7 +933,7 @@ public class UpdateSiteTest extends AbstractProvisioningTest { || mirrorsURL.startsWith("https://") //$NON-NLS-1$ || mirrorsURL.startsWith("file://") //$NON-NLS-1$ || mirrorsURL.startsWith("ftp://") //$NON-NLS-1$ - || mirrorsURL.startsWith("jar://"))) //$NON-NLS-1$ + || mirrorsURL.startsWith("jar://"))) //$NON-NLS-1$ fail("Error processing mirrors URL: " + mirrorsURL, e); //$NON-NLS-1$ return null; } |