]> source.dussan.org Git - jgit.git/commitdiff
Open auto-closeable resources in try-with-resource 86/119286/4
authorDavid Pursehouse <david.pursehouse@gmail.com>
Tue, 13 Mar 2018 02:44:23 +0000 (11:44 +0900)
committerMatthias Sohn <matthias.sohn@sap.com>
Tue, 13 Mar 2018 21:16:06 +0000 (22:16 +0100)
When an auto-closeable resources is not opened in try-with-resource,
the warning "should be managed by try-with-resource" is emitted by
Eclipse.

Fix the ones that can be silenced simply by moving the declaration of
the variable into a try-with-resource.

In cases where we explicitly call the close() method, for example in
tests where we are testing specific behavior caused by the close(),
suppress the warning.

Leave the ones that will require more significant refcactoring to fix.
They can be done in separate commits that can be reviewed and tested
in isolation.

Change-Id: I9682cd20fb15167d3c7f9027cecdc82bc50b83c4
Signed-off-by: David Pursehouse <david.pursehouse@gmail.com>
47 files changed:
org.eclipse.jgit.http.server/src/org/eclipse/jgit/http/server/ServletUtils.java
org.eclipse.jgit.http.server/src/org/eclipse/jgit/http/server/SmartOutputStream.java
org.eclipse.jgit.http.test/tst/org/eclipse/jgit/http/test/ProtocolErrorTest.java
org.eclipse.jgit.http.test/tst/org/eclipse/jgit/http/test/SetAdditionalHeadersTest.java
org.eclipse.jgit.http.test/tst/org/eclipse/jgit/http/test/SmartClientSmartServerTest.java
org.eclipse.jgit.junit/src/org/eclipse/jgit/junit/RepositoryTestCase.java
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Version.java
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/debug/TextHashFunctions.java
org.eclipse.jgit.test/tst/org/eclipse/jgit/api/ResetCommandTest.java
org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/PackFileTest.java
org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/PackWriterTest.java
org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/T0003_BasicTest.java
org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/UnpackedObjectTest.java
org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/WindowCacheGetTest.java
org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/RacyGitTests.java
org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/RefTest.java
org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/RepositoryCacheTest.java
org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/SquashCommitMsgTest.java
org.eclipse.jgit.test/tst/org/eclipse/jgit/merge/ResolveMergerTest.java
org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/PatchCcErrorTest.java
org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/PatchCcTest.java
org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/PatchErrorTest.java
org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/PatchTest.java
org.eclipse.jgit.test/tst/org/eclipse/jgit/submodule/SubmoduleAddTest.java
org.eclipse.jgit.test/tst/org/eclipse/jgit/submodule/SubmoduleSyncTest.java
org.eclipse.jgit.test/tst/org/eclipse/jgit/submodule/SubmoduleUpdateTest.java
org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/NetRCTest.java
org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/PackParserTest.java
org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/WalkEncryptionTest.java
org.eclipse.jgit.test/tst/org/eclipse/jgit/treewalk/filter/NotTreeFilterTest.java
org.eclipse.jgit.test/tst/org/eclipse/jgit/util/TemporaryBufferTest.java
org.eclipse.jgit.test/tst/org/eclipse/jgit/util/io/AutoCRLFOutputStreamTest.java
org.eclipse.jgit.test/tst/org/eclipse/jgit/util/io/UnionInputStreamTest.java
org.eclipse.jgit/src/org/eclipse/jgit/api/CloneCommand.java
org.eclipse.jgit/src/org/eclipse/jgit/api/RebaseCommand.java
org.eclipse.jgit/src/org/eclipse/jgit/api/StashCreateCommand.java
org.eclipse.jgit/src/org/eclipse/jgit/diff/SimilarityIndex.java
org.eclipse.jgit/src/org/eclipse/jgit/gitrepo/RepoProject.java
org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/dfs/DfsPackFile.java
org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/file/ObjectDirectoryPackParser.java
org.eclipse.jgit/src/org/eclipse/jgit/lib/ObjectLoader.java
org.eclipse.jgit/src/org/eclipse/jgit/lib/Repository.java
org.eclipse.jgit/src/org/eclipse/jgit/transport/PackParser.java
org.eclipse.jgit/src/org/eclipse/jgit/transport/TransportAmazonS3.java
org.eclipse.jgit/src/org/eclipse/jgit/transport/WalkFetchConnection.java
org.eclipse.jgit/src/org/eclipse/jgit/treewalk/WorkingTreeIterator.java
org.eclipse.jgit/src/org/eclipse/jgit/util/TemporaryBuffer.java

index f1ff547ea742305e98af0eb1e13e43a9e190709f..272edc68794a523f2c33ca162a502fcbb7b4c15f 100644 (file)
@@ -220,12 +220,9 @@ public final class ServletUtils {
        public static void send(byte[] content, final HttpServletRequest req,
                        final HttpServletResponse rsp) throws IOException {
                content = sendInit(content, req, rsp);
-               final OutputStream out = rsp.getOutputStream();
-               try {
+               try (OutputStream out = rsp.getOutputStream()) {
                        out.write(content);
                        out.flush();
-               } finally {
-                       out.close();
                }
        }
 
index 4eb94a3a22bdde9310f176c6d22c3da2906b751d..ad5e8d479e09ec7bd743a6e6246c5daf74f65b33 100644 (file)
@@ -110,11 +110,8 @@ class SmartOutputStream extends TemporaryBuffer {
                        if (256 < out.length() && acceptsGzipEncoding(req)) {
                                TemporaryBuffer gzbuf = new TemporaryBuffer.Heap(LIMIT);
                                try {
-                                       GZIPOutputStream gzip = new GZIPOutputStream(gzbuf);
-                                       try {
+                                       try (GZIPOutputStream gzip = new GZIPOutputStream(gzbuf)) {
                                                out.writeTo(gzip, null);
-                                       } finally {
-                                               gzip.close();
                                        }
                                        if (gzbuf.length() < out.length()) {
                                                out = gzbuf;
@@ -131,12 +128,9 @@ class SmartOutputStream extends TemporaryBuffer {
                        // hardcoded LIMIT constant above assures us we wouldn't store
                        // more than 2 GiB of content in memory.
                        rsp.setContentLength((int) out.length());
-                       final OutputStream os = rsp.getOutputStream();
-                       try {
+                       try (OutputStream os = rsp.getOutputStream()) {
                                out.writeTo(os, null);
                                os.flush();
-                       } finally {
-                               os.close();
                        }
                }
        }
index 87d0bad85cec72c15ca0d42606c4d702abedd208..a1baae3b26f3e418ce461e6d7ce5b2485b1c84e5 100644 (file)
@@ -149,19 +149,15 @@ public class ProtocolErrorTest extends HttpTestCase {
                        c.setRequestProperty("Content-Type",
                                        GitSmartHttpTools.RECEIVE_PACK_REQUEST_TYPE);
                        c.setFixedLengthStreamingMode(reqbin.length);
-                       OutputStream out = c.getOutputStream();
-                       try {
+                       try (OutputStream out = c.getOutputStream()) {
                                out.write(reqbin);
-                       } finally {
-                               out.close();
                        }
 
                        assertEquals(200, c.getResponseCode());
                        assertEquals(GitSmartHttpTools.RECEIVE_PACK_RESULT_TYPE,
                                        c.getContentType());
 
-                       InputStream rawin = c.getInputStream();
-                       try {
+                       try (InputStream rawin = c.getInputStream()) {
                                PacketLineIn pckin = new PacketLineIn(rawin);
                                assertEquals("unpack error "
                                                + JGitText.get().packfileIsTruncatedNoParam,
@@ -169,8 +165,6 @@ public class ProtocolErrorTest extends HttpTestCase {
                                assertEquals("ng refs/objects/A n/a (unpacker error)",
                                                pckin.readString());
                                assertSame(PacketLineIn.END, pckin.readString());
-                       } finally {
-                               rawin.close();
                        }
                } finally {
                        c.disconnect();
index ef8daec31f01078c2029f42166c1790bed315f3c..fbc54f38722ed1d3bb93fc556f5145c47c9d7b65 100644 (file)
@@ -107,8 +107,7 @@ public class SetAdditionalHeadersTest extends HttpTestCase {
 
                assertEquals("http", remoteURI.getScheme());
 
-               Transport t = Transport.open(dst, remoteURI);
-               try {
+               try (Transport t = Transport.open(dst, remoteURI)) {
                        assertTrue("isa TransportHttp", t instanceof TransportHttp);
                        assertTrue("isa HttpTransport", t instanceof HttpTransport);
 
@@ -117,8 +116,6 @@ public class SetAdditionalHeadersTest extends HttpTestCase {
                        headers.put("AnotherKey", "someValue");
                        ((TransportHttp) t).setAdditionalHeaders(headers);
                        t.openFetch();
-               } finally {
-                       t.close();
                }
 
                List<AccessEvent> requests = getRequests();
index 6ded21f8cc0a2a736c16f19f8f397ef3e97988fb..d8541aa13de357d9adeb4540bcbeca5d4386157c 100644 (file)
@@ -267,9 +267,9 @@ public class SmartClientSmartServerTest extends HttpTestCase {
                                final HttpServletResponse r = (HttpServletResponse) response;
                                r.setContentType("text/plain");
                                r.setCharacterEncoding("UTF-8");
-                               PrintWriter w = r.getWriter();
-                               w.print("OK");
-                               w.close();
+                               try (PrintWriter w = r.getWriter()) {
+                                       w.print("OK");
+                               }
                        }
 
                        @Override
@@ -397,11 +397,8 @@ public class SmartClientSmartServerTest extends HttpTestCase {
                        assertTrue("isa TransportHttp", t instanceof TransportHttp);
                        assertTrue("isa HttpTransport", t instanceof HttpTransport);
 
-                       FetchConnection c = t.openFetch();
-                       try {
+                       try (FetchConnection c = t.openFetch()) {
                                map = c.getRefsMap();
-                       } finally {
-                               c.close();
                        }
                }
 
index 5a83a1f4929a1845df2c55ca7665cbd98a6d4b56..93fc771cb34e0aed4eb695d8495b7ccbf39b54b8 100644 (file)
@@ -94,20 +94,13 @@ public abstract class RepositoryTestCase extends LocalDiskRepositoryTestCase {
         */
        protected static void copyFile(final File src, final File dst)
                        throws IOException {
-               final FileInputStream fis = new FileInputStream(src);
-               try {
-                       final FileOutputStream fos = new FileOutputStream(dst);
-                       try {
-                               final byte[] buf = new byte[4096];
-                               int r;
-                               while ((r = fis.read(buf)) > 0) {
-                                       fos.write(buf, 0, r);
-                               }
-                       } finally {
-                               fos.close();
+               try (FileInputStream fis = new FileInputStream(src);
+                               FileOutputStream fos = new FileOutputStream(dst)) {
+                       final byte[] buf = new byte[4096];
+                       int r;
+                       while ((r = fis.read(buf)) > 0) {
+                               fos.write(buf, 0, r);
                        }
-               } finally {
-                       fis.close();
                }
        }
 
@@ -293,10 +286,11 @@ public abstract class RepositoryTestCase extends LocalDiskRepositoryTestCase {
                                dce.setFileMode(treeItr.getEntryFileMode());
                                dce.setLastModified(treeItr.getEntryLastModified());
                                dce.setLength((int) len);
-                               FileInputStream in = new FileInputStream(
-                                               treeItr.getEntryFile());
-                               dce.setObjectId(inserter.insert(Constants.OBJ_BLOB, len, in));
-                               in.close();
+                               try (FileInputStream in = new FileInputStream(
+                                               treeItr.getEntryFile())) {
+                                       dce.setObjectId(
+                                                       inserter.insert(Constants.OBJ_BLOB, len, in));
+                               }
                                builder.add(dce);
                                treeItr.next(1);
                        }
@@ -380,8 +374,9 @@ public abstract class RepositoryTestCase extends LocalDiskRepositoryTestCase {
                        while (actTime <= startTime) {
                                Thread.sleep(sleepTime);
                                sleepTime *= 2;
-                               FileOutputStream fos = new FileOutputStream(tmp);
-                               fos.close();
+                               try (FileOutputStream fos = new FileOutputStream(tmp)) {
+                                       // Do nothing
+                               }
                                actTime = fs.lastModified(tmp);
                        }
                        return actTime;
index 5efc03b287d705c66b7898632aff16315cfe4a5f..58acc5cafd9890fdb4d6234152421d8a06d1cfad 100644 (file)
@@ -96,14 +96,9 @@ class Version extends TextBuiltin {
        }
 
        private static String getBundleVersion(URL url) {
-               try {
-                       InputStream is = url.openStream();
-                       try {
-                               Manifest manifest = new Manifest(is);
-                               return manifest.getMainAttributes().getValue("Bundle-Version"); //$NON-NLS-1$
-                       } finally {
-                               is.close();
-                       }
+               try (InputStream is = url.openStream()) {
+                       Manifest manifest = new Manifest(is);
+                       return manifest.getMainAttributes().getValue("Bundle-Version"); //$NON-NLS-1$
                } catch (IOException e) {
                        // do nothing - will return null
                }
index 83b7bcea26be871e5f31fed0812138f92971cf99..6378e8d2201e0df390fda9cfd69fe889db256d2e 100644 (file)
@@ -288,11 +288,8 @@ class TextHashFunctions extends TextBuiltin {
                        else
                                rb.findGitDir(dir);
 
-                       Repository repo = rb.build();
-                       try {
+                       try (Repository repo = rb.build()) {
                                run(repo);
-                       } finally {
-                               repo.close();
                        }
                }
        }
index ba51881ffdb0ee2b84b2248def89d0c9e4e62789..8f56a9270e2861c43fbb090ff14bcbcf83066ce9 100644 (file)
@@ -100,39 +100,39 @@ public class ResetCommandTest extends RepositoryTestCase {
                File nestedFile = new File(dir, "b.txt");
                FileUtils.createNewFile(nestedFile);
 
-               PrintWriter nesterFileWriter = new PrintWriter(nestedFile);
-               nesterFileWriter.print("content");
-               nesterFileWriter.flush();
-
-               // create file
-               indexFile = new File(db.getWorkTree(), "a.txt");
-               FileUtils.createNewFile(indexFile);
-               PrintWriter writer = new PrintWriter(indexFile);
-               writer.print("content");
-               writer.flush();
-
-               // add file and commit it
-               git.add().addFilepattern("dir").addFilepattern("a.txt").call();
-               secondCommit = git.commit().setMessage("adding a.txt and dir/b.txt")
-                               .call();
-
-               prestage = DirCache.read(db.getIndexFile(), db.getFS()).getEntry(
-                               indexFile.getName());
-
-               // modify file and add to index
-               writer.print("new content");
-               writer.close();
-               nesterFileWriter.print("new content");
-               nesterFileWriter.close();
+               try (PrintWriter nestedFileWriter = new PrintWriter(nestedFile)) {
+                       nestedFileWriter.print("content");
+                       nestedFileWriter.flush();
+
+                       // create file
+                       indexFile = new File(db.getWorkTree(), "a.txt");
+                       FileUtils.createNewFile(indexFile);
+                       try (PrintWriter writer = new PrintWriter(indexFile)) {
+                               writer.print("content");
+                               writer.flush();
+
+                               // add file and commit it
+                               git.add().addFilepattern("dir").addFilepattern("a.txt").call();
+                               secondCommit = git.commit()
+                                               .setMessage("adding a.txt and dir/b.txt").call();
+
+                               prestage = DirCache.read(db.getIndexFile(), db.getFS())
+                                               .getEntry(indexFile.getName());
+
+                               // modify file and add to index
+                               writer.print("new content");
+                       }
+                       nestedFileWriter.print("new content");
+               }
                git.add().addFilepattern("a.txt").addFilepattern("dir").call();
 
                // create a file not added to the index
                untrackedFile = new File(db.getWorkTree(),
                                "notAddedToIndex.txt");
                FileUtils.createNewFile(untrackedFile);
-               PrintWriter writer2 = new PrintWriter(untrackedFile);
-               writer2.print("content");
-               writer2.close();
+               try (PrintWriter writer2 = new PrintWriter(untrackedFile)) {
+                       writer2.print("content");
+               }
        }
 
        @Test
index 91bd5239752fe45646c8c334fe5205603d876647..128c1edde11c2032dd16ecff06eeae1aa25505e0 100644 (file)
@@ -146,15 +146,15 @@ public class PackFileTest extends LocalDiskRepositoryTestCase {
                assertFalse("is not large", ol.isLarge());
                assertTrue("same content", Arrays.equals(data, ol.getCachedBytes()));
 
-               ObjectStream in = ol.openStream();
-               assertNotNull("have stream", in);
-               assertEquals(type, in.getType());
-               assertEquals(data.length, in.getSize());
-               byte[] data2 = new byte[data.length];
-               IO.readFully(in, data2, 0, data.length);
-               assertTrue("same content", Arrays.equals(data2, data));
-               assertEquals("stream at EOF", -1, in.read());
-               in.close();
+               try (ObjectStream in = ol.openStream()) {
+                       assertNotNull("have stream", in);
+                       assertEquals(type, in.getType());
+                       assertEquals(data.length, in.getSize());
+                       byte[] data2 = new byte[data.length];
+                       IO.readFully(in, data2, 0, data.length);
+                       assertTrue("same content", Arrays.equals(data2, data));
+                       assertEquals("stream at EOF", -1, in.read());
+               }
        }
 
        @Test
@@ -180,15 +180,15 @@ public class PackFileTest extends LocalDiskRepositoryTestCase {
                                        .getMessage());
                }
 
-               ObjectStream in = ol.openStream();
-               assertNotNull("have stream", in);
-               assertEquals(type, in.getType());
-               assertEquals(data.length, in.getSize());
-               byte[] data2 = new byte[data.length];
-               IO.readFully(in, data2, 0, data.length);
-               assertTrue("same content", Arrays.equals(data2, data));
-               assertEquals("stream at EOF", -1, in.read());
-               in.close();
+               try (ObjectStream in = ol.openStream()) {
+                       assertNotNull("have stream", in);
+                       assertEquals(type, in.getType());
+                       assertEquals(data.length, in.getSize());
+                       byte[] data2 = new byte[data.length];
+                       IO.readFully(in, data2, 0, data.length);
+                       assertTrue("same content", Arrays.equals(data2, data));
+                       assertEquals("stream at EOF", -1, in.read());
+               }
        }
 
        @Test
@@ -239,15 +239,15 @@ public class PackFileTest extends LocalDiskRepositoryTestCase {
                        assertNotNull(ol.getCachedBytes());
                        assertArrayEquals(data3, ol.getCachedBytes());
 
-                       ObjectStream in = ol.openStream();
-                       assertNotNull("have stream", in);
-                       assertEquals(Constants.OBJ_BLOB, in.getType());
-                       assertEquals(data3.length, in.getSize());
-                       byte[] act = new byte[data3.length];
-                       IO.readFully(in, act, 0, data3.length);
-                       assertTrue("same content", Arrays.equals(act, data3));
-                       assertEquals("stream at EOF", -1, in.read());
-                       in.close();
+                       try (ObjectStream in = ol.openStream()) {
+                               assertNotNull("have stream", in);
+                               assertEquals(Constants.OBJ_BLOB, in.getType());
+                               assertEquals(data3.length, in.getSize());
+                               byte[] act = new byte[data3.length];
+                               IO.readFully(in, act, 0, data3.length);
+                               assertTrue("same content", Arrays.equals(act, data3));
+                               assertEquals("stream at EOF", -1, in.read());
+                       }
                }
        }
 
@@ -282,22 +282,16 @@ public class PackFileTest extends LocalDiskRepositoryTestCase {
                        File packName = new File(dir, idA.name() + ".pack");
                        File idxName = new File(dir, idA.name() + ".idx");
 
-                       FileOutputStream f = new FileOutputStream(packName);
-                       try {
+                       try (FileOutputStream f = new FileOutputStream(packName)) {
                                f.write(pack.toByteArray());
-                       } finally {
-                               f.close();
                        }
 
-                       f = new FileOutputStream(idxName);
-                       try {
+                       try (FileOutputStream f = new FileOutputStream(idxName)) {
                                List<PackedObjectInfo> list = new ArrayList<>();
                                list.add(a);
                                list.add(b);
                                Collections.sort(list);
                                new PackIndexWriterV1(f).write(list, footer);
-                       } finally {
-                               f.close();
                        }
 
                        PackFile packFile = new PackFile(packName, PackExt.INDEX.getBit());
@@ -321,16 +315,17 @@ public class PackFileTest extends LocalDiskRepositoryTestCase {
                assertTrue("has blob", wc.has(id));
 
                ObjectLoader ol = wc.open(id);
-               ObjectStream in = ol.openStream();
-               assertTrue(in instanceof ObjectStream.SmallStream);
-               assertEquals(300, in.available());
-               in.close();
+               try (ObjectStream in = ol.openStream()) {
+                       assertTrue(in instanceof ObjectStream.SmallStream);
+                       assertEquals(300, in.available());
+               }
 
                wc.setStreamFileThreshold(299);
                ol = wc.open(id);
-               in = ol.openStream();
-               assertTrue(in instanceof ObjectStream.Filter);
-               assertEquals(1, in.available());
+               try (ObjectStream in = ol.openStream()) {
+                       assertTrue(in instanceof ObjectStream.Filter);
+                       assertEquals(1, in.available());
+               }
        }
 
        private static byte[] clone(int first, byte[] base) {
index 379432ddbb8c1c867be4ae54184869c6f3e6510c..3711f83656cb0e5bd55edc7ccd6e7121d357b17f 100644 (file)
@@ -515,11 +515,8 @@ public class PackWriterTest extends SampleDataRepositoryTestCase {
 
                // Validate that an index written by PackWriter is the same.
                final File idx2File = new File(indexFile.getAbsolutePath() + ".2");
-               final FileOutputStream is = new FileOutputStream(idx2File);
-               try {
+               try (FileOutputStream is = new FileOutputStream(idx2File)) {
                        writer.writeIndex(is);
-               } finally {
-                       is.close();
                }
                final PackIndex idx2 = PackIndex.open(idx2File);
                assertTrue(idx2 instanceof PackIndexV2);
@@ -715,14 +712,14 @@ public class PackWriterTest extends SampleDataRepositoryTestCase {
                        String id = pw.computeName().getName();
                        File packdir = repo.getObjectDatabase().getPackDirectory();
                        File packFile = new File(packdir, "pack-" + id + ".pack");
-                       FileOutputStream packOS = new FileOutputStream(packFile);
-                       pw.writePack(NullProgressMonitor.INSTANCE,
-                                       NullProgressMonitor.INSTANCE, packOS);
-                       packOS.close();
+                       try (FileOutputStream packOS = new FileOutputStream(packFile)) {
+                               pw.writePack(NullProgressMonitor.INSTANCE,
+                                               NullProgressMonitor.INSTANCE, packOS);
+                       }
                        File idxFile = new File(packdir, "pack-" + id + ".idx");
-                       FileOutputStream idxOS = new FileOutputStream(idxFile);
-                       pw.writeIndex(idxOS);
-                       idxOS.close();
+                       try (FileOutputStream idxOS = new FileOutputStream(idxFile)) {
+                               pw.writeIndex(idxOS);
+                       }
                        return PackIndex.open(idxFile);
                }
        }
index b5d6485604e1df4145b47d5c172cd70b07fa6f60..91255007ef7b254b1a60baa8569f7f31935aaf0f 100644 (file)
@@ -137,10 +137,10 @@ public class T0003_BasicTest extends SampleDataRepositoryTestCase {
        @Test
        public void test000_openrepo_default_gitDirSet() throws IOException {
                File repo1Parent = new File(trash.getParentFile(), "r1");
-               Repository repo1initial = new FileRepository(new File(repo1Parent,
-                               Constants.DOT_GIT));
-               repo1initial.create();
-               repo1initial.close();
+               try (Repository repo1initial = new FileRepository(
+                               new File(repo1Parent, Constants.DOT_GIT))) {
+                       repo1initial.create();
+               }
 
                File theDir = new File(repo1Parent, Constants.DOT_GIT);
                FileRepository r = (FileRepository) new FileRepositoryBuilder()
@@ -162,10 +162,10 @@ public class T0003_BasicTest extends SampleDataRepositoryTestCase {
        public void test000_openrepo_default_gitDirAndWorkTreeSet()
                        throws IOException {
                File repo1Parent = new File(trash.getParentFile(), "r1");
-               Repository repo1initial = new FileRepository(new File(repo1Parent,
-                               Constants.DOT_GIT));
-               repo1initial.create();
-               repo1initial.close();
+               try (Repository repo1initial = new FileRepository(
+                               new File(repo1Parent, Constants.DOT_GIT))) {
+                       repo1initial.create();
+               }
 
                File theDir = new File(repo1Parent, Constants.DOT_GIT);
                FileRepository r = (FileRepository) new FileRepositoryBuilder()
@@ -187,10 +187,10 @@ public class T0003_BasicTest extends SampleDataRepositoryTestCase {
        @Test
        public void test000_openrepo_default_workDirSet() throws IOException {
                File repo1Parent = new File(trash.getParentFile(), "r1");
-               Repository repo1initial = new FileRepository(new File(repo1Parent,
-                               Constants.DOT_GIT));
-               repo1initial.create();
-               repo1initial.close();
+               try (Repository repo1initial = new FileRepository(
+                               new File(repo1Parent, Constants.DOT_GIT))) {
+                       repo1initial.create();
+               }
 
                File theDir = new File(repo1Parent, Constants.DOT_GIT);
                FileRepository r = (FileRepository) new FileRepositoryBuilder()
@@ -213,13 +213,13 @@ public class T0003_BasicTest extends SampleDataRepositoryTestCase {
                File repo1Parent = new File(trash.getParentFile(), "r1");
                File workdir = new File(trash.getParentFile(), "rw");
                FileUtils.mkdir(workdir);
-               FileRepository repo1initial = new FileRepository(new File(repo1Parent,
-                               Constants.DOT_GIT));
-               repo1initial.create();
-               final FileBasedConfig cfg = repo1initial.getConfig();
-               cfg.setString("core", null, "worktree", workdir.getAbsolutePath());
-               cfg.save();
-               repo1initial.close();
+               try (FileRepository repo1initial = new FileRepository(
+                               new File(repo1Parent, Constants.DOT_GIT))) {
+                       repo1initial.create();
+                       final FileBasedConfig cfg = repo1initial.getConfig();
+                       cfg.setString("core", null, "worktree", workdir.getAbsolutePath());
+                       cfg.save();
+               }
 
                File theDir = new File(repo1Parent, Constants.DOT_GIT);
                FileRepository r = (FileRepository) new FileRepositoryBuilder()
@@ -242,13 +242,13 @@ public class T0003_BasicTest extends SampleDataRepositoryTestCase {
                File repo1Parent = new File(trash.getParentFile(), "r1");
                File workdir = new File(trash.getParentFile(), "rw");
                FileUtils.mkdir(workdir);
-               FileRepository repo1initial = new FileRepository(new File(repo1Parent,
-                               Constants.DOT_GIT));
-               repo1initial.create();
-               final FileBasedConfig cfg = repo1initial.getConfig();
-               cfg.setString("core", null, "worktree", "../../rw");
-               cfg.save();
-               repo1initial.close();
+               try (FileRepository repo1initial = new FileRepository(
+                               new File(repo1Parent, Constants.DOT_GIT))) {
+                       repo1initial.create();
+                       final FileBasedConfig cfg = repo1initial.getConfig();
+                       cfg.setString("core", null, "worktree", "../../rw");
+                       cfg.save();
+               }
 
                File theDir = new File(repo1Parent, Constants.DOT_GIT);
                FileRepository r = (FileRepository) new FileRepositoryBuilder()
@@ -273,26 +273,24 @@ public class T0003_BasicTest extends SampleDataRepositoryTestCase {
                File indexFile = new File(trash, "idx");
                File objDir = new File(trash, "../obj");
                File altObjDir = db.getObjectDatabase().getDirectory();
-               Repository repo1initial = new FileRepository(new File(repo1Parent,
-                               Constants.DOT_GIT));
-               repo1initial.create();
-               repo1initial.close();
+               try (Repository repo1initial = new FileRepository(
+                               new File(repo1Parent, Constants.DOT_GIT))) {
+                       repo1initial.create();
+               }
 
                File theDir = new File(repo1Parent, Constants.DOT_GIT);
-               FileRepository r = (FileRepository) new FileRepositoryBuilder() //
+               try (FileRepository r = (FileRepository) new FileRepositoryBuilder() //
                                .setGitDir(theDir).setObjectDirectory(objDir) //
                                .addAlternateObjectDirectory(altObjDir) //
                                .setIndexFile(indexFile) //
-                               .build();
-               assertEqualsPath(theDir, r.getDirectory());
-               assertEqualsPath(theDir.getParentFile(), r.getWorkTree());
-               assertEqualsPath(indexFile, r.getIndexFile());
-               assertEqualsPath(objDir, r.getObjectDatabase().getDirectory());
-               assertNotNull(r.open(ObjectId
-                               .fromString("6db9c2ebf75590eef973081736730a9ea169a0c4")));
-               // Must close or the default repo pack files created by this test gets
-               // locked via the alternate object directories on Windows.
-               r.close();
+                               .build()) {
+                       assertEqualsPath(theDir, r.getDirectory());
+                       assertEqualsPath(theDir.getParentFile(), r.getWorkTree());
+                       assertEqualsPath(indexFile, r.getIndexFile());
+                       assertEqualsPath(objDir, r.getObjectDatabase().getDirectory());
+                       assertNotNull(r.open(ObjectId
+                                       .fromString("6db9c2ebf75590eef973081736730a9ea169a0c4")));
+               }
        }
 
        protected void assertEqualsPath(File expected, File actual)
@@ -417,14 +415,11 @@ public class T0003_BasicTest extends SampleDataRepositoryTestCase {
                // Verify the commit we just wrote is in the correct format.
                ObjectDatabase odb = db.getObjectDatabase();
                assertTrue("is ObjectDirectory", odb instanceof ObjectDirectory);
-               final XInputStream xis = new XInputStream(new FileInputStream(
-                               ((ObjectDirectory) odb).fileFor(cmtid)));
-               try {
+               try (XInputStream xis = new XInputStream(
+                               new FileInputStream(((ObjectDirectory) odb).fileFor(cmtid)))) {
                        assertEquals(0x78, xis.readUInt8());
                        assertEquals(0x9c, xis.readUInt8());
                        assertEquals(0, 0x789c % 31);
-               } finally {
-                       xis.close();
                }
 
                // Verify we can read it.
index c5ab766838faeea03f31eee043a66d6adce8be1a..98ff04e15eaf100e1390f929fb7798e8854c2a16 100644 (file)
@@ -130,15 +130,15 @@ public class UnpackedObjectTest extends LocalDiskRepositoryTestCase {
                assertFalse("is not large", ol.isLarge());
                assertTrue("same content", Arrays.equals(data, ol.getCachedBytes()));
 
-               ObjectStream in = ol.openStream();
-               assertNotNull("have stream", in);
-               assertEquals(type, in.getType());
-               assertEquals(data.length, in.getSize());
-               byte[] data2 = new byte[data.length];
-               IO.readFully(in, data2, 0, data.length);
-               assertTrue("same content", Arrays.equals(data2, data));
-               assertEquals("stream at EOF", -1, in.read());
-               in.close();
+               try (ObjectStream in = ol.openStream()) {
+                       assertNotNull("have stream", in);
+                       assertEquals(type, in.getType());
+                       assertEquals(data.length, in.getSize());
+                       byte[] data2 = new byte[data.length];
+                       IO.readFully(in, data2, 0, data.length);
+                       assertTrue("same content", Arrays.equals(data2, data));
+                       assertEquals("stream at EOF", -1, in.read());
+               }
        }
 
        @Test
@@ -150,11 +150,8 @@ public class UnpackedObjectTest extends LocalDiskRepositoryTestCase {
 
                ObjectLoader ol;
                {
-                       FileInputStream fs = new FileInputStream(path(id));
-                       try {
+                       try (FileInputStream fs = new FileInputStream(path(id))) {
                                ol = UnpackedObject.open(fs, path(id), id, wc);
-                       } finally {
-                               fs.close();
                        }
                }
 
@@ -171,15 +168,15 @@ public class UnpackedObjectTest extends LocalDiskRepositoryTestCase {
                                        .getMessage());
                }
 
-               ObjectStream in = ol.openStream();
-               assertNotNull("have stream", in);
-               assertEquals(type, in.getType());
-               assertEquals(data.length, in.getSize());
-               byte[] data2 = new byte[data.length];
-               IO.readFully(in, data2, 0, data.length);
-               assertTrue("same content", Arrays.equals(data2, data));
-               assertEquals("stream at EOF", -1, in.read());
-               in.close();
+               try (ObjectStream in = ol.openStream()) {
+                       assertNotNull("have stream", in);
+                       assertEquals(type, in.getType());
+                       assertEquals(data.length, in.getSize());
+                       byte[] data2 = new byte[data.length];
+                       IO.readFully(in, data2, 0, data.length);
+                       assertTrue("same content", Arrays.equals(data2, data));
+                       assertEquals("stream at EOF", -1, in.read());
+               }
        }
 
        @Test
@@ -316,23 +313,13 @@ public class UnpackedObjectTest extends LocalDiskRepositoryTestCase {
                write(id, gz);
 
                ObjectLoader ol;
-               {
-                       FileInputStream fs = new FileInputStream(path(id));
-                       try {
-                               ol = UnpackedObject.open(fs, path(id), id, wc);
-                       } finally {
-                               fs.close();
-                       }
+               try (FileInputStream fs = new FileInputStream(path(id))) {
+                       ol = UnpackedObject.open(fs, path(id), id, wc);
                }
 
-               try {
-                       byte[] tmp = new byte[data.length];
-                       InputStream in = ol.openStream();
-                       try {
-                               IO.readFully(in, tmp, 0, tmp.length);
-                       } finally {
-                               in.close();
-                       }
+               byte[] tmp = new byte[data.length];
+               try (InputStream in = ol.openStream()) {
+                       IO.readFully(in, tmp, 0, tmp.length);
                        fail("Did not throw CorruptObjectException");
                } catch (CorruptObjectException coe) {
                        assertEquals(MessageFormat.format(JGitText.get().objectIsCorrupt,
@@ -354,16 +341,12 @@ public class UnpackedObjectTest extends LocalDiskRepositoryTestCase {
                write(id, tr);
 
                ObjectLoader ol;
-               {
-                       FileInputStream fs = new FileInputStream(path(id));
-                       try {
-                               ol = UnpackedObject.open(fs, path(id), id, wc);
-                       } finally {
-                               fs.close();
-                       }
+               try (FileInputStream fs = new FileInputStream(path(id))) {
+                       ol = UnpackedObject.open(fs, path(id), id, wc);
                }
 
                byte[] tmp = new byte[data.length];
+               @SuppressWarnings("resource") // We are testing that the close() method throws
                InputStream in = ol.openStream();
                IO.readFully(in, tmp, 0, tmp.length);
                try {
@@ -389,16 +372,12 @@ public class UnpackedObjectTest extends LocalDiskRepositoryTestCase {
                write(id, tr);
 
                ObjectLoader ol;
-               {
-                       FileInputStream fs = new FileInputStream(path(id));
-                       try {
-                               ol = UnpackedObject.open(fs, path(id), id, wc);
-                       } finally {
-                               fs.close();
-                       }
+               try (FileInputStream fs = new FileInputStream(path(id))) {
+                       ol = UnpackedObject.open(fs, path(id), id, wc);
                }
 
                byte[] tmp = new byte[data.length];
+               @SuppressWarnings("resource") // We are testing that the close() method throws
                InputStream in = ol.openStream();
                IO.readFully(in, tmp, 0, tmp.length);
                try {
@@ -426,14 +405,15 @@ public class UnpackedObjectTest extends LocalDiskRepositoryTestCase {
                assertFalse("is not large", ol.isLarge());
                assertTrue("same content", Arrays.equals(data, ol.getCachedBytes()));
 
-               ObjectStream in = ol.openStream();
-               assertNotNull("have stream", in);
-               assertEquals(type, in.getType());
-               assertEquals(data.length, in.getSize());
-               byte[] data2 = new byte[data.length];
-               IO.readFully(in, data2, 0, data.length);
-               assertTrue("same content", Arrays.equals(data, ol.getCachedBytes()));
-               in.close();
+               try (ObjectStream in = ol.openStream()) {
+                       assertNotNull("have stream", in);
+                       assertEquals(type, in.getType());
+                       assertEquals(data.length, in.getSize());
+                       byte[] data2 = new byte[data.length];
+                       IO.readFully(in, data2, 0, data.length);
+                       assertTrue("same content",
+                                       Arrays.equals(data, ol.getCachedBytes()));
+               }
        }
 
        @Test
@@ -444,13 +424,8 @@ public class UnpackedObjectTest extends LocalDiskRepositoryTestCase {
                write(id, compressPackFormat(type, data));
 
                ObjectLoader ol;
-               {
-                       FileInputStream fs = new FileInputStream(path(id));
-                       try {
-                               ol = UnpackedObject.open(fs, path(id), id, wc);
-                       } finally {
-                               fs.close();
-                       }
+               try (FileInputStream fs = new FileInputStream(path(id))) {
+                       ol = UnpackedObject.open(fs, path(id), id, wc);
                }
 
                assertNotNull("created loader", ol);
@@ -466,15 +441,15 @@ public class UnpackedObjectTest extends LocalDiskRepositoryTestCase {
                                        .getMessage());
                }
 
-               ObjectStream in = ol.openStream();
-               assertNotNull("have stream", in);
-               assertEquals(type, in.getType());
-               assertEquals(data.length, in.getSize());
-               byte[] data2 = new byte[data.length];
-               IO.readFully(in, data2, 0, data.length);
-               assertTrue("same content", Arrays.equals(data2, data));
-               assertEquals("stream at EOF", -1, in.read());
-               in.close();
+               try (ObjectStream in = ol.openStream()) {
+                       assertNotNull("have stream", in);
+                       assertEquals(type, in.getType());
+                       assertEquals(data.length, in.getSize());
+                       byte[] data2 = new byte[data.length];
+                       IO.readFully(in, data2, 0, data.length);
+                       assertTrue("same content", Arrays.equals(data2, data));
+                       assertEquals("stream at EOF", -1, in.read());
+               }
        }
 
        @Test
@@ -573,11 +548,8 @@ public class UnpackedObjectTest extends LocalDiskRepositoryTestCase {
        private void write(ObjectId id, byte[] data) throws IOException {
                File path = path(id);
                FileUtils.mkdirs(path.getParentFile());
-               FileOutputStream out = new FileOutputStream(path);
-               try {
+               try (FileOutputStream out = new FileOutputStream(path)) {
                        out.write(data);
-               } finally {
-                       out.close();
                }
        }
 
index cc348388cf240f9e74e0624fa5c238f5292e0f1a..9ac794ed8e2bdf7eb8ac8b570c9261490acfdd3f 100644 (file)
@@ -74,11 +74,10 @@ public class WindowCacheGetTest extends SampleDataRepositoryTestCase {
                super.setUp();
 
                toLoad = new ArrayList<>();
-               final BufferedReader br = new BufferedReader(new InputStreamReader(
+               try (BufferedReader br = new BufferedReader(new InputStreamReader(
                                new FileInputStream(JGitTestUtil
                                                .getTestResourceFile("all_packed_objects.txt")),
-                               Constants.CHARSET));
-               try {
+                               Constants.CHARSET))) {
                        String line;
                        while ((line = br.readLine()) != null) {
                                final String[] parts = line.split(" {1,}");
@@ -90,8 +89,6 @@ public class WindowCacheGetTest extends SampleDataRepositoryTestCase {
                                // parts[4] is the offset in the pack
                                toLoad.add(o);
                        }
-               } finally {
-                       br.close();
                }
                assertEquals(96, toLoad.size());
        }
index 9236b4e8214ab976fa59e41e06de7426083baf5e..8d9ccab1bd8c170f560dbb5b226fa49960dab4e7 100644 (file)
@@ -176,12 +176,9 @@ public class RacyGitTests extends RepositoryTestCase {
 
        private File addToWorkDir(String path, String content) throws IOException {
                File f = new File(db.getWorkTree(), path);
-               FileOutputStream fos = new FileOutputStream(f);
-               try {
+               try (FileOutputStream fos = new FileOutputStream(f)) {
                        fos.write(content.getBytes(Constants.CHARACTER_ENCODING));
                        return f;
-               } finally {
-                       fos.close();
                }
        }
 }
index 7fb3309982e8fe5992446e4d1f8672fc80c5ca76..e93867829ad7db3b03d6aae413c2014e91366e1a 100644 (file)
@@ -253,11 +253,11 @@ public class RefTest extends SampleDataRepositoryTestCase {
                        InterruptedException {
                Ref ref = db.exactRef("refs/heads/master");
                assertEquals(Storage.PACKED, ref.getStorage());
-               FileOutputStream os = new FileOutputStream(new File(db.getDirectory(),
-                               "refs/heads/master"));
-               os.write(ref.getObjectId().name().getBytes());
-               os.write('\n');
-               os.close();
+               try (FileOutputStream os = new FileOutputStream(
+                               new File(db.getDirectory(), "refs/heads/master"))) {
+                       os.write(ref.getObjectId().name().getBytes());
+                       os.write('\n');
+               }
 
                ref = db.exactRef("refs/heads/master");
                assertEquals(Storage.LOOSE, ref.getStorage());
index 1107c2c69b807f7ccd7d6ce858883e8223f99d24..58b005c282329c8f7302fff27a1b64da0ba1da2b 100644 (file)
@@ -94,24 +94,25 @@ public class RepositoryCacheTest extends RepositoryTestCase {
 
        @Test
        public void testFileKeyOpenExisting() throws IOException {
-               Repository r;
-
-               r = new FileKey(db.getDirectory(), db.getFS()).open(true);
-               assertNotNull(r);
-               assertEqualsFile(db.getDirectory(), r.getDirectory());
-               r.close();
+               try (Repository r = new FileKey(db.getDirectory(), db.getFS())
+                               .open(true)) {
+                       assertNotNull(r);
+                       assertEqualsFile(db.getDirectory(), r.getDirectory());
+               }
 
-               r = new FileKey(db.getDirectory(), db.getFS()).open(false);
-               assertNotNull(r);
-               assertEqualsFile(db.getDirectory(), r.getDirectory());
-               r.close();
+               try (Repository r = new FileKey(db.getDirectory(), db.getFS())
+                               .open(false)) {
+                       assertNotNull(r);
+                       assertEqualsFile(db.getDirectory(), r.getDirectory());
+               }
        }
 
        @Test
        public void testFileKeyOpenNew() throws IOException {
-               final Repository n = createRepository(true, false);
-               final File gitdir = n.getDirectory();
-               n.close();
+               File gitdir;
+               try (Repository n = createRepository(true, false)) {
+                       gitdir = n.getDirectory();
+               }
                recursiveDelete(gitdir);
                assertFalse(gitdir.exists());
 
@@ -143,6 +144,7 @@ public class RepositoryCacheTest extends RepositoryTestCase {
        @Test
        public void testCacheOpen() throws Exception {
                final FileKey loc = FileKey.exact(db.getDirectory(), db.getFS());
+               @SuppressWarnings("resource") // We are testing the close() method
                final Repository d2 = RepositoryCache.open(loc);
                assertNotSame(db, d2);
                assertSame(d2, RepositoryCache.open(FileKey.exact(loc.getFile(), db.getFS())));
@@ -176,6 +178,7 @@ public class RepositoryCacheTest extends RepositoryTestCase {
        @Test
        public void testRepositoryUsageCount() throws Exception {
                FileKey loc = FileKey.exact(db.getDirectory(), db.getFS());
+               @SuppressWarnings("resource") // We are testing the close() method
                Repository d2 = RepositoryCache.open(loc);
                assertEquals(1, d2.useCnt.get());
                RepositoryCache.open(FileKey.exact(loc.getFile(), db.getFS()));
@@ -189,6 +192,7 @@ public class RepositoryCacheTest extends RepositoryTestCase {
        @Test
        public void testRepositoryUsageCountWithRegisteredRepository()
                        throws IOException {
+               @SuppressWarnings("resource") // We are testing the close() method
                Repository repo = createRepository(false, false);
                assertEquals(1, repo.useCnt.get());
                RepositoryCache.register(repo);
@@ -200,6 +204,7 @@ public class RepositoryCacheTest extends RepositoryTestCase {
        @Test
        public void testRepositoryNotUnregisteringWhenClosing() throws Exception {
                FileKey loc = FileKey.exact(db.getDirectory(), db.getFS());
+               @SuppressWarnings("resource") // We are testing the close() method
                Repository d2 = RepositoryCache.open(loc);
                assertEquals(1, d2.useCnt.get());
                assertThat(RepositoryCache.getRegisteredKeys(),
@@ -214,6 +219,7 @@ public class RepositoryCacheTest extends RepositoryTestCase {
        @Test
        public void testRepositoryUnregisteringWhenExpiredAndUsageCountNegative()
                        throws Exception {
+               @SuppressWarnings("resource") // We are testing the close() method
                Repository repoA = createBareRepository();
                RepositoryCache.register(repoA);
 
@@ -234,7 +240,9 @@ public class RepositoryCacheTest extends RepositoryTestCase {
 
        @Test
        public void testRepositoryUnregisteringWhenExpired() throws Exception {
+               @SuppressWarnings("resource") // We are testing the close() method
                Repository repoA = createRepository(true, false);
+               @SuppressWarnings("resource") // We are testing the close() method
                Repository repoB = createRepository(true, false);
                Repository repoC = createBareRepository();
                RepositoryCache.register(repoA);
@@ -268,6 +276,7 @@ public class RepositoryCacheTest extends RepositoryTestCase {
 
        @Test
        public void testReconfigure() throws InterruptedException, IOException {
+               @SuppressWarnings("resource") // We are testing the close() method
                Repository repo = createRepository(false, false);
                RepositoryCache.register(repo);
                assertTrue(RepositoryCache.isCached(repo));
index 3bcd787f81de0ba94fc1d5260ca6d33a277581c9..203c00e28aa82fb087a4d9e9a887a98c5b8ef189 100644 (file)
@@ -66,12 +66,9 @@ public class SquashCommitMsgTest extends RepositoryTestCase {
                db.writeSquashCommitMsg(null);
                assertEquals(db.readSquashCommitMsg(), null);
                assertFalse(new File(db.getDirectory(), Constants.SQUASH_MSG).exists());
-               FileOutputStream fos = new FileOutputStream(new File(db.getDirectory(),
-                               Constants.SQUASH_MSG));
-               try {
+               try (FileOutputStream fos = new FileOutputStream(
+                               new File(db.getDirectory(), Constants.SQUASH_MSG))) {
                        fos.write(squashMsg.getBytes(Constants.CHARACTER_ENCODING));
-               } finally {
-                       fos.close();
                }
                assertEquals(db.readSquashCommitMsg(), squashMsg);
        }
index 9734ac851c7a839b6da1ffa790c41531036c6f7b..75b87447d4908c35abe6c59e636cae9d1c40b461 100644 (file)
@@ -1033,19 +1033,21 @@ public class ResolveMergerTest extends RepositoryTestCase {
                git.commit().setMessage("added c.txt").call();
 
                // Get a handle to the the file so on windows it can't be deleted.
-               FileInputStream fis = new FileInputStream(new File(db.getWorkTree(),
-                               "b.txt"));
-               MergeResult mergeRes = git.merge().setStrategy(strategy)
-                               .include(masterCommit).call();
-               if (mergeRes.getMergeStatus().equals(MergeStatus.FAILED)) {
-                       // probably windows
-                       assertEquals(1, mergeRes.getFailingPaths().size());
-                       assertEquals(MergeFailureReason.COULD_NOT_DELETE, mergeRes
-                                       .getFailingPaths().get("b.txt"));
+               try (FileInputStream fis = new FileInputStream(
+                               new File(db.getWorkTree(), "b.txt"))) {
+                       MergeResult mergeRes = git.merge().setStrategy(strategy)
+                                       .include(masterCommit).call();
+                       if (mergeRes.getMergeStatus().equals(MergeStatus.FAILED)) {
+                               // probably windows
+                               assertEquals(1, mergeRes.getFailingPaths().size());
+                               assertEquals(MergeFailureReason.COULD_NOT_DELETE,
+                                               mergeRes.getFailingPaths().get("b.txt"));
+                       }
+                       assertEquals(
+                                       "[a.txt, mode:100644, content:master]"
+                                                       + "[c.txt, mode:100644, content:side]",
+                                       indexState(CONTENT));
                }
-               assertEquals("[a.txt, mode:100644, content:master]"
-                               + "[c.txt, mode:100644, content:side]", indexState(CONTENT));
-               fis.close();
        }
 
        @Theory
index e4b43172d6a92fcf321729cb4830bce9770e6f8e..6989343362fcf5bd8ecff5c3fd7d2f5af63172b0 100644 (file)
@@ -96,17 +96,14 @@ public class PatchCcErrorTest {
 
        private Patch parseTestPatchFile() throws IOException {
                final String patchFile = JGitTestUtil.getName() + ".patch";
-               final InputStream in = getClass().getResourceAsStream(patchFile);
-               if (in == null) {
-                       fail("No " + patchFile + " test vector");
-                       return null; // Never happens
-               }
-               try {
+               try (InputStream in = getClass().getResourceAsStream(patchFile)) {
+                       if (in == null) {
+                               fail("No " + patchFile + " test vector");
+                               return null; // Never happens
+                       }
                        final Patch p = new Patch();
                        p.parse(in);
                        return p;
-               } finally {
-                       in.close();
                }
        }
 
index 837414b054488fd78f5bda0aa6caad3a7ab0660a..4a26d50e494f21f04935f9408b1a0752303dd53f 100644 (file)
@@ -199,17 +199,14 @@ public class PatchCcTest {
 
        private Patch parseTestPatchFile() throws IOException {
                final String patchFile = JGitTestUtil.getName() + ".patch";
-               final InputStream in = getClass().getResourceAsStream(patchFile);
-               if (in == null) {
-                       fail("No " + patchFile + " test vector");
-                       return null; // Never happens
-               }
-               try {
+               try (InputStream in = getClass().getResourceAsStream(patchFile)) {
+                       if (in == null) {
+                               fail("No " + patchFile + " test vector");
+                               return null; // Never happens
+                       }
                        final Patch p = new Patch();
                        p.parse(in);
                        return p;
-               } finally {
-                       in.close();
                }
        }
 }
index 52e3874b6c544d3904191eae55122b2ccdad1826..3bdf852167a9ac6d09f9c88c77565273a0204688 100644 (file)
@@ -177,17 +177,14 @@ public class PatchErrorTest {
 
        private Patch parseTestPatchFile() throws IOException {
                final String patchFile = JGitTestUtil.getName() + ".patch";
-               final InputStream in = getClass().getResourceAsStream(patchFile);
-               if (in == null) {
-                       fail("No " + patchFile + " test vector");
-                       return null; // Never happens
-               }
-               try {
+               try (InputStream in = getClass().getResourceAsStream(patchFile)) {
+                       if (in == null) {
+                               fail("No " + patchFile + " test vector");
+                               return null; // Never happens
+                       }
                        final Patch p = new Patch();
                        p.parse(in);
                        return p;
-               } finally {
-                       in.close();
                }
        }
 }
index 9f57ab98c092b04548b9cf098c70b1f7b98e9ed6..6a09a4919e2d50da73bef8bc0045977f62850e20 100644 (file)
@@ -357,17 +357,14 @@ public class PatchTest {
 
        private Patch parseTestPatchFile() throws IOException {
                final String patchFile = JGitTestUtil.getName() + ".patch";
-               final InputStream in = getClass().getResourceAsStream(patchFile);
-               if (in == null) {
-                       fail("No " + patchFile + " test vector");
-                       return null; // Never happens
-               }
-               try {
+               try (InputStream in = getClass().getResourceAsStream(patchFile)) {
+                       if (in == null) {
+                               fail("No " + patchFile + " test vector");
+                               return null; // Never happens
+                       }
                        final Patch p = new Patch();
                        p.parse(in);
                        return p;
-               } finally {
-                       in.close();
                }
        }
 }
index f42dd02814b59be7f7398c8c662072413b2816c4..1a67e41976103fec355bc9db9e00feeb632483a5 100644 (file)
@@ -129,10 +129,11 @@ public class SubmoduleAddTest extends RepositoryTestCase {
                        command.setPath(path);
                        String uri = db.getDirectory().toURI().toString();
                        command.setURI(uri);
-                       Repository repo = command.call();
-                       assertNotNull(repo);
-                       ObjectId subCommit = repo.resolve(Constants.HEAD);
-                       repo.close();
+                       ObjectId subCommit;
+                       try (Repository repo = command.call()) {
+                               assertNotNull(repo);
+                               subCommit = repo.resolve(Constants.HEAD);
+                       }
 
                        SubmoduleWalk generator = SubmoduleWalk.forIndex(db);
                        assertTrue(generator.next());
@@ -141,10 +142,10 @@ public class SubmoduleAddTest extends RepositoryTestCase {
                        assertEquals(uri, generator.getModulesUrl());
                        assertEquals(path, generator.getModulesPath());
                        assertEquals(uri, generator.getConfigUrl());
-                       Repository subModRepo = generator.getRepository();
-                       assertNotNull(subModRepo);
-                       assertEquals(subCommit, commit);
-                       subModRepo.close();
+                       try (Repository subModRepo = generator.getRepository()) {
+                               assertNotNull(subModRepo);
+                               assertEquals(subCommit, commit);
+                       }
 
                        Status status = Git.wrap(db).status().call();
                        assertTrue(status.getAdded().contains(Constants.DOT_GIT_MODULES));
@@ -209,16 +210,14 @@ public class SubmoduleAddTest extends RepositoryTestCase {
                                fullUri = fullUri.replace('\\', '/');
                        }
                        assertEquals(fullUri, generator.getConfigUrl());
-                       Repository subModRepo = generator.getRepository();
-                       assertNotNull(subModRepo);
-                       assertEquals(
-                                       fullUri,
-                                       subModRepo
-                                                       .getConfig()
-                                                       .getString(ConfigConstants.CONFIG_REMOTE_SECTION,
-                                                                       Constants.DEFAULT_REMOTE_NAME,
-                                                                       ConfigConstants.CONFIG_KEY_URL));
-                       subModRepo.close();
+                       try (Repository subModRepo = generator.getRepository()) {
+                               assertNotNull(subModRepo);
+                               assertEquals(fullUri,
+                                               subModRepo.getConfig().getString(
+                                                               ConfigConstants.CONFIG_REMOTE_SECTION,
+                                                               Constants.DEFAULT_REMOTE_NAME,
+                                                               ConfigConstants.CONFIG_KEY_URL));
+                       }
                        assertEquals(commit, repo.resolve(Constants.HEAD));
 
                        Status status = Git.wrap(db).status().call();
index 13db44a9c5e874761dd6b60089e45c62266dc8a8..6f3b52f7bbd7e9b7fcbdf0047ab8d37217cd5029 100644 (file)
@@ -135,12 +135,14 @@ public class SubmoduleSyncTest extends RepositoryTestCase {
                generator = SubmoduleWalk.forIndex(db);
                assertTrue(generator.next());
                assertEquals(url, generator.getConfigUrl());
-               Repository subModRepository = generator.getRepository();
-               StoredConfig submoduleConfig = subModRepository.getConfig();
-               subModRepository.close();
-               assertEquals(url, submoduleConfig.getString(
-                               ConfigConstants.CONFIG_REMOTE_SECTION,
-                               Constants.DEFAULT_REMOTE_NAME, ConfigConstants.CONFIG_KEY_URL));
+               try (Repository subModRepository = generator.getRepository()) {
+                       StoredConfig submoduleConfig = subModRepository.getConfig();
+                       assertEquals(url,
+                                       submoduleConfig.getString(
+                                                       ConfigConstants.CONFIG_REMOTE_SECTION,
+                                                       Constants.DEFAULT_REMOTE_NAME,
+                                                       ConfigConstants.CONFIG_KEY_URL));
+               }
        }
 
        @Test
@@ -208,11 +210,13 @@ public class SubmoduleSyncTest extends RepositoryTestCase {
                generator = SubmoduleWalk.forIndex(db);
                assertTrue(generator.next());
                assertEquals("git://server/sub.git", generator.getConfigUrl());
-               Repository subModRepository1 = generator.getRepository();
-               StoredConfig submoduleConfig = subModRepository1.getConfig();
-               subModRepository1.close();
-               assertEquals("git://server/sub.git", submoduleConfig.getString(
-                               ConfigConstants.CONFIG_REMOTE_SECTION,
-                               Constants.DEFAULT_REMOTE_NAME, ConfigConstants.CONFIG_KEY_URL));
+               try (Repository subModRepository1 = generator.getRepository()) {
+                       StoredConfig submoduleConfig = subModRepository1.getConfig();
+                       assertEquals("git://server/sub.git",
+                                       submoduleConfig.getString(
+                                                       ConfigConstants.CONFIG_REMOTE_SECTION,
+                                                       Constants.DEFAULT_REMOTE_NAME,
+                                                       ConfigConstants.CONFIG_KEY_URL));
+               }
        }
 }
index 7064f6097bc8849afdc0cd35fd011fb7715af6c4..bbce413ef366847fdebb79f32cfb5c7a79067ee2 100644 (file)
@@ -121,10 +121,10 @@ public class SubmoduleUpdateTest extends RepositoryTestCase {
 
                SubmoduleWalk generator = SubmoduleWalk.forIndex(db);
                assertTrue(generator.next());
-               Repository subRepo = generator.getRepository();
-               assertNotNull(subRepo);
-               assertEquals(commit, subRepo.resolve(Constants.HEAD));
-               subRepo.close();
+               try (Repository subRepo = generator.getRepository()) {
+                       assertNotNull(subRepo);
+                       assertEquals(commit, subRepo.resolve(Constants.HEAD));
+               }
        }
 
        @Test
index 2fea8a92ac4ec8ef5903f25342d3ab8be2d3a4b4..77cb726f1e62c98d542f66a29bd4e95cf124b252 100644 (file)
@@ -74,10 +74,10 @@ public class NetRCTest extends RepositoryTestCase {
        }
 
        private void config(final String data) throws IOException {
-               final OutputStreamWriter fw = new OutputStreamWriter(
-                               new FileOutputStream(configFile), "UTF-8");
-               fw.write(data);
-               fw.close();
+               try (OutputStreamWriter fw = new OutputStreamWriter(
+                               new FileOutputStream(configFile), "UTF-8")) {
+                       fw.write(data);
+               }
        }
 
        @Test
index 5d9bdbdbadbc1bb899a98c8789477520577d638b..b6d0611437047117bba14748eed9d98cc8002523 100644 (file)
@@ -93,8 +93,7 @@ public class PackParserTest extends RepositoryTestCase {
        @Test
        public void test1() throws  IOException {
                File packFile = JGitTestUtil.getTestResourceFile("pack-34be9032ac282b11fa9babdc2b2a93ca996c9c2f.pack");
-               final InputStream is = new FileInputStream(packFile);
-               try {
+               try (InputStream is = new FileInputStream(packFile)) {
                        ObjectDirectoryPackParser p = (ObjectDirectoryPackParser) index(is);
                        p.parse(NullProgressMonitor.INSTANCE);
                        PackFile file = p.getPackFile();
@@ -107,8 +106,6 @@ public class PackParserTest extends RepositoryTestCase {
                        assertTrue(file.hasObject(ObjectId.fromString("902d5476fa249b7abc9d84c611577a81381f0327")));
                        assertTrue(file.hasObject(ObjectId.fromString("aabf2ffaec9b497f0950352b3e582d73035c2035")));
                        assertTrue(file.hasObject(ObjectId.fromString("c59759f143fb1fe21c197981df75a7ee00290799")));
-               } finally {
-                       is.close();
                }
        }
 
@@ -121,8 +118,7 @@ public class PackParserTest extends RepositoryTestCase {
        @Test
        public void test2() throws  IOException {
                File packFile = JGitTestUtil.getTestResourceFile("pack-df2982f284bbabb6bdb59ee3fcc6eb0983e20371.pack");
-               final InputStream is = new FileInputStream(packFile);
-               try {
+               try (InputStream is = new FileInputStream(packFile)) {
                        ObjectDirectoryPackParser p = (ObjectDirectoryPackParser) index(is);
                        p.parse(NullProgressMonitor.INSTANCE);
                        PackFile file = p.getPackFile();
@@ -140,8 +136,6 @@ public class PackParserTest extends RepositoryTestCase {
                        assertTrue(file.hasObject(ObjectId.fromString("20a8ade77639491ea0bd667bf95de8abf3a434c8")));
                        assertTrue(file.hasObject(ObjectId.fromString("2675188fd86978d5bc4d7211698b2118ae3bf658")));
                        // and lots more...
-               } finally {
-                       is.close();
                }
        }
 
index 2251a3dc66e592e2c8f4ffc94aa9c9cbb0753b64..33e252973161fd80039a828c55dce3adc5c71c4a 100644 (file)
@@ -419,12 +419,9 @@ public class WalkEncryptionTest {
                                URLConnection c = url.openConnection();
                                c.setConnectTimeout(500);
                                c.setReadTimeout(500);
-                               BufferedReader reader = new BufferedReader(
-                                               new InputStreamReader(c.getInputStream()));
-                               try {
+                               try (BufferedReader reader = new BufferedReader(
+                                               new InputStreamReader(c.getInputStream()))) {
                                        return reader.readLine();
-                               } finally {
-                                       reader.close();
                                }
                        } catch (UnknownHostException | SocketTimeoutException e) {
                                return "Can't reach http://checkip.amazonaws.com to"
@@ -654,9 +651,9 @@ public class WalkEncryptionTest {
                        Properties props = Props.discover();
                        props.put(AmazonS3.Keys.PASSWORD, JGIT_PASS);
                        props.put(AmazonS3.Keys.CRYPTO_ALG, algorithm);
-                       PrintWriter writer = new PrintWriter(JGIT_CONF_FILE);
-                       props.store(writer, "JGIT S3 connection configuration file.");
-                       writer.close();
+                       try (PrintWriter writer = new PrintWriter(JGIT_CONF_FILE)) {
+                               props.store(writer, "JGIT S3 connection configuration file.");
+                       }
                }
 
                /**
@@ -668,9 +665,9 @@ public class WalkEncryptionTest {
                static void configCreate(Properties source) throws Exception {
                        Properties target = Props.discover();
                        target.putAll(source);
-                       PrintWriter writer = new PrintWriter(JGIT_CONF_FILE);
-                       target.store(writer, "JGIT S3 connection configuration file.");
-                       writer.close();
+                       try (PrintWriter writer = new PrintWriter(JGIT_CONF_FILE)) {
+                               target.store(writer, "JGIT S3 connection configuration file.");
+                       }
                }
 
                /**
@@ -836,10 +833,10 @@ public class WalkEncryptionTest {
                        {
                                byte[] origin = sourceText.getBytes(charset);
                                ByteArrayOutputStream target = new ByteArrayOutputStream();
-                               OutputStream source = crypto.encrypt(target);
-                               source.write(origin);
-                               source.flush();
-                               source.close();
+                               try (OutputStream source = crypto.encrypt(target)) {
+                                       source.write(origin);
+                                       source.flush();
+                               }
                                cipherText = target.toByteArray();
                        }
                        {
@@ -1074,10 +1071,10 @@ public class WalkEncryptionTest {
                                remoteConfig.update(config);
                                config.save();
 
-                               Git git = Git.open(dirOne);
-                               git.checkout().setName("master").call();
-                               git.push().setRemote(remote).setRefSpecs(specs).call();
-                               git.close();
+                               try (Git git = Git.open(dirOne)) {
+                                       git.checkout().setName("master").call();
+                                       git.push().setRemote(remote).setRefSpecs(specs).call();
+                               }
 
                                File fileStatic = new File(dirOne, nameStatic);
                                assertTrue("Provided by setup", fileStatic.exists());
@@ -1089,11 +1086,11 @@ public class WalkEncryptionTest {
                                File fileStatic = new File(dirTwo, nameStatic);
                                assertFalse("Not Provided by setup", fileStatic.exists());
 
-                               Git git = Git.cloneRepository().setURI(uri).setDirectory(dirTwo)
-                                               .call();
-                               git.close();
+                               try (Git git = Git.cloneRepository().setURI(uri)
+                                               .setDirectory(dirTwo).call()) {
+                                       assertTrue("Provided by clone", fileStatic.exists());
+                               }
 
-                               assertTrue("Provided by clone", fileStatic.exists());
                        }
 
                        { // Verify static file content.
@@ -1111,11 +1108,11 @@ public class WalkEncryptionTest {
                                assertTrue("Provided by create", fileDynamic.exists());
                                assertTrue("Need content to encrypt", fileDynamic.length() > 0);
 
-                               Git git = Git.open(dirOne);
-                               git.add().addFilepattern(nameDynamic).call();
-                               git.commit().setMessage(nameDynamic).call();
-                               git.push().setRemote(remote).setRefSpecs(specs).call();
-                               git.close();
+                               try (Git git = Git.open(dirOne)) {
+                                       git.add().addFilepattern(nameDynamic).call();
+                                       git.commit().setMessage(nameDynamic).call();
+                                       git.push().setRemote(remote).setRefSpecs(specs).call();
+                               }
 
                        }
 
@@ -1124,9 +1121,9 @@ public class WalkEncryptionTest {
                                File fileDynamic = new File(dirTwo, nameDynamic);
                                assertFalse("Not Provided by setup", fileDynamic.exists());
 
-                               Git git = Git.open(dirTwo);
-                               git.pull().call();
-                               git.close();
+                               try (Git git = Git.open(dirTwo)) {
+                                       git.pull().call();
+                               }
 
                                assertTrue("Provided by pull", fileDynamic.exists());
                        }
index f7a7fb8a976cd233627cb384c836687aaf5e4075..c6389fb1aebcaed367dbb24ef6594259af78f4f4 100644 (file)
@@ -57,12 +57,13 @@ import org.junit.Test;
 public class NotTreeFilterTest extends RepositoryTestCase {
        @Test
        public void testWrap() throws Exception {
-               final TreeWalk tw = new TreeWalk(db);
-               final TreeFilter a = TreeFilter.ALL;
-               final TreeFilter n = NotTreeFilter.create(a);
-               assertNotNull(n);
-               assertTrue(a.include(tw));
-               assertFalse(n.include(tw));
+               try (TreeWalk tw = new TreeWalk(db)) {
+                       final TreeFilter a = TreeFilter.ALL;
+                       final TreeFilter n = NotTreeFilter.create(a);
+                       assertNotNull(n);
+                       assertTrue(a.include(tw));
+                       assertFalse(n.include(tw));
+               }
        }
 
        @Test
index d978804d579e6e72a7ecb511c98eadb40037dd4a..327ee279a18a694778e990bebdcb591745cf221d 100644 (file)
@@ -87,10 +87,8 @@ public class TemporaryBufferTest {
                                assertEquals(1, r.length);
                                assertEquals(test, r[0]);
                        }
-                       {
-                               final ByteArrayOutputStream o = new ByteArrayOutputStream();
+                       try (ByteArrayOutputStream o = new ByteArrayOutputStream()) {
                                b.writeTo(o, null);
-                               o.close();
                                final byte[] r = o.toByteArray();
                                assertEquals(1, r.length);
                                assertEquals(test, r[0]);
@@ -118,10 +116,8 @@ public class TemporaryBufferTest {
                                assertEquals(test.length, r.length);
                                assertArrayEquals(test, r);
                        }
-                       {
-                               final ByteArrayOutputStream o = new ByteArrayOutputStream();
+                       try (ByteArrayOutputStream o = new ByteArrayOutputStream()) {
                                b.writeTo(o, null);
-                               o.close();
                                final byte[] r = o.toByteArray();
                                assertEquals(test.length, r.length);
                                assertArrayEquals(test, r);
@@ -149,10 +145,8 @@ public class TemporaryBufferTest {
                                assertEquals(test.length, r.length);
                                assertArrayEquals(test, r);
                        }
-                       {
-                               final ByteArrayOutputStream o = new ByteArrayOutputStream();
+                       try (ByteArrayOutputStream o = new ByteArrayOutputStream()) {
                                b.writeTo(o, null);
-                               o.close();
                                final byte[] r = o.toByteArray();
                                assertEquals(test.length, r.length);
                                assertArrayEquals(test, r);
@@ -178,10 +172,8 @@ public class TemporaryBufferTest {
                                assertEquals(test.length, r.length);
                                assertArrayEquals(test, r);
                        }
-                       {
-                               final ByteArrayOutputStream o = new ByteArrayOutputStream();
+                       try (ByteArrayOutputStream o = new ByteArrayOutputStream()) {
                                b.writeTo(o, null);
-                               o.close();
                                final byte[] r = o.toByteArray();
                                assertEquals(test.length, r.length);
                                assertArrayEquals(test, r);
@@ -208,10 +200,8 @@ public class TemporaryBufferTest {
                                assertEquals(test.length, r.length);
                                assertArrayEquals(test, r);
                        }
-                       {
-                               final ByteArrayOutputStream o = new ByteArrayOutputStream();
+                       try (ByteArrayOutputStream o = new ByteArrayOutputStream()) {
                                b.writeTo(o, null);
-                               o.close();
                                final byte[] r = o.toByteArray();
                                assertEquals(test.length, r.length);
                                assertArrayEquals(test, r);
@@ -236,10 +226,8 @@ public class TemporaryBufferTest {
                                assertEquals(test.length, r.length);
                                assertArrayEquals(test, r);
                        }
-                       {
-                               final ByteArrayOutputStream o = new ByteArrayOutputStream();
+                       try (ByteArrayOutputStream o = new ByteArrayOutputStream()) {
                                b.writeTo(o, null);
-                               o.close();
                                final byte[] r = o.toByteArray();
                                assertEquals(test.length, r.length);
                                assertArrayEquals(test, r);
@@ -253,14 +241,13 @@ public class TemporaryBufferTest {
        public void testInCoreInputStream() throws IOException {
                final int cnt = 256;
                final byte[] test = new TestRng(getName()).nextBytes(cnt);
-               final TemporaryBuffer.Heap b = new TemporaryBuffer.Heap(cnt + 4);
-               b.write(test);
-               b.close();
-
-               InputStream in = b.openInputStream();
-               byte[] act = new byte[cnt];
-               IO.readFully(in, act, 0, cnt);
-               assertArrayEquals(test, act);
+               try (final TemporaryBuffer.Heap b = new TemporaryBuffer.Heap(cnt + 4)) {
+                       b.write(test);
+                       InputStream in = b.openInputStream();
+                       byte[] act = new byte[cnt];
+                       IO.readFully(in, act, 0, cnt);
+                       assertArrayEquals(test, act);
+               }
        }
 
        @Test
@@ -279,10 +266,8 @@ public class TemporaryBufferTest {
                                assertEquals(test.length, r.length);
                                assertArrayEquals(test, r);
                        }
-                       {
-                               final ByteArrayOutputStream o = new ByteArrayOutputStream();
+                       try (ByteArrayOutputStream o = new ByteArrayOutputStream()) {
                                b.writeTo(o, null);
-                               o.close();
                                final byte[] r = o.toByteArray();
                                assertEquals(test.length, r.length);
                                assertArrayEquals(test, r);
@@ -308,10 +293,8 @@ public class TemporaryBufferTest {
                                assertEquals(test.length, r.length);
                                assertArrayEquals(test, r);
                        }
-                       {
-                               final ByteArrayOutputStream o = new ByteArrayOutputStream();
+                       try (ByteArrayOutputStream o = new ByteArrayOutputStream()) {
                                b.writeTo(o, null);
-                               o.close();
                                final byte[] r = o.toByteArray();
                                assertEquals(test.length, r.length);
                                assertArrayEquals(test, r);
@@ -340,10 +323,8 @@ public class TemporaryBufferTest {
                                assertEquals(test.length, r.length);
                                assertArrayEquals(test, r);
                        }
-                       {
-                               final ByteArrayOutputStream o = new ByteArrayOutputStream();
+                       try (ByteArrayOutputStream o = new ByteArrayOutputStream()) {
                                b.writeTo(o, null);
-                               o.close();
                                final byte[] r = o.toByteArray();
                                assertEquals(test.length, r.length);
                                assertArrayEquals(test, r);
@@ -399,10 +380,8 @@ public class TemporaryBufferTest {
                                assertEquals(expect.length, r.length);
                                assertArrayEquals(expect, r);
                        }
-                       {
-                               final ByteArrayOutputStream o = new ByteArrayOutputStream();
+                       try (ByteArrayOutputStream o = new ByteArrayOutputStream()) {
                                b.writeTo(o, null);
-                               o.close();
                                final byte[] r = o.toByteArray();
                                assertEquals(expect.length, r.length);
                                assertArrayEquals(expect, r);
index a72d33cd5127581e2401087450e466ea6f591327..0655827310305afb488405ec7d1c9c402ea4e783 100644 (file)
@@ -96,32 +96,31 @@ public class AutoCRLFOutputStreamTest {
                for (int i = -4; i < 5; ++i) {
                        int size = Math.abs(i);
                        byte[] buf = new byte[size];
-                       InputStream in = new ByteArrayInputStream(inbytes);
-                       ByteArrayOutputStream bos = new ByteArrayOutputStream();
-                       OutputStream out = new AutoCRLFOutputStream(bos);
-                       if (i > 0) {
-                               int n;
-                               while ((n = in.read(buf)) >= 0) {
-                                       out.write(buf, 0, n);
+                       try (InputStream in = new ByteArrayInputStream(inbytes);
+                                       ByteArrayOutputStream bos = new ByteArrayOutputStream();
+                                       OutputStream out = new AutoCRLFOutputStream(bos)) {
+                               if (i > 0) {
+                                       int n;
+                                       while ((n = in.read(buf)) >= 0) {
+                                               out.write(buf, 0, n);
+                                       }
+                               } else if (i < 0) {
+                                       int n;
+                                       while ((n = in.read(buf)) >= 0) {
+                                               byte[] b = new byte[n];
+                                               System.arraycopy(buf, 0, b, 0, n);
+                                               out.write(b);
+                                       }
+                               } else {
+                                       int c;
+                                       while ((c = in.read()) != -1)
+                                               out.write(c);
                                }
-                       } else if (i < 0) {
-                               int n;
-                               while ((n = in.read(buf)) >= 0) {
-                                       byte[] b = new byte[n];
-                                       System.arraycopy(buf, 0, b, 0, n);
-                                       out.write(b);
-                               }
-                       } else {
-                               int c;
-                               while ((c = in.read()) != -1)
-                                       out.write(c);
+                               out.flush();
+                               byte[] actualBytes = bos.toByteArray();
+                               Assert.assertEquals("bufsize=" + size, encode(expectBytes),
+                                               encode(actualBytes));
                        }
-                       out.flush();
-                       in.close();
-                       out.close();
-                       byte[] actualBytes = bos.toByteArray();
-                       Assert.assertEquals("bufsize=" + size, encode(expectBytes),
-                                       encode(actualBytes));
                }
        }
 
index 6b5ef7ec64aaa51c2e696c0fe775bd2ae7a15d56..b824fae9fdd24afe6a1a3695d721d6d8e981fe6f 100644 (file)
@@ -58,13 +58,13 @@ import org.junit.Test;
 public class UnionInputStreamTest {
        @Test
        public void testEmptyStream() throws IOException {
-               final UnionInputStream u = new UnionInputStream();
-               assertTrue(u.isEmpty());
-               assertEquals(-1, u.read());
-               assertEquals(-1, u.read(new byte[1], 0, 1));
-               assertEquals(0, u.available());
-               assertEquals(0, u.skip(1));
-               u.close();
+               try (UnionInputStream u = new UnionInputStream()) {
+                       assertTrue(u.isEmpty());
+                       assertEquals(-1, u.read());
+                       assertEquals(-1, u.read(new byte[1], 0, 1));
+                       assertEquals(0, u.available());
+                       assertEquals(0, u.skip(1));
+               }
        }
 
        @Test
@@ -211,25 +211,24 @@ public class UnionInputStreamTest {
 
        @Test
        public void testCloseDuringClose() throws IOException {
-               final UnionInputStream u = new UnionInputStream();
                final boolean closed[] = new boolean[2];
-               u.add(new ByteArrayInputStream(new byte[] { 1 }) {
-                       @Override
-                       public void close() {
-                               closed[0] = true;
-                       }
-               });
-               u.add(new ByteArrayInputStream(new byte[] { 2 }) {
-                       @Override
-                       public void close() {
-                               closed[1] = true;
-                       }
-               });
+               try (UnionInputStream u = new UnionInputStream()) {
+                       u.add(new ByteArrayInputStream(new byte[] { 1 }) {
+                               @Override
+                               public void close() {
+                                       closed[0] = true;
+                               }
+                       });
+                       u.add(new ByteArrayInputStream(new byte[] { 2 }) {
+                               @Override
+                               public void close() {
+                                       closed[1] = true;
+                               }
+                       });
 
-               assertFalse(closed[0]);
-               assertFalse(closed[1]);
-
-               u.close();
+                       assertFalse(closed[0]);
+                       assertFalse(closed[1]);
+               }
 
                assertTrue(closed[0]);
                assertTrue(closed[1]);
@@ -237,6 +236,7 @@ public class UnionInputStreamTest {
 
        @Test
        public void testExceptionDuringClose() {
+               @SuppressWarnings("resource") // We are testing the close() method
                final UnionInputStream u = new UnionInputStream();
                u.add(new ByteArrayInputStream(new byte[] { 1 }) {
                        @Override
index 79b0efbe6d2a32f2d0193ba570415fadfcaab07f..f368e836aed60ed53274198e4666e29595b23bcd 100644 (file)
@@ -386,12 +386,9 @@ public class CloneCommand extends TransportCommand<CloneCommand, Git> {
                if (!update.call().isEmpty()) {
                        SubmoduleWalk walk = SubmoduleWalk.forIndex(clonedRepo);
                        while (walk.next()) {
-                               Repository subRepo = walk.getRepository();
-                               if (subRepo != null) {
-                                       try {
+                               try (Repository subRepo = walk.getRepository()) {
+                                       if (subRepo != null) {
                                                cloneSubmodules(subRepo);
-                                       } finally {
-                                               subRepo.close();
                                        }
                                }
                        }
index da1ff06ae542129400d1bf6442ad56fd3569e774..98c16b893175b88132425f4d978632699a0b8d0b 100644 (file)
@@ -1734,23 +1734,17 @@ public class RebaseCommand extends GitCommand<RebaseResult> {
                                String content)
                                throws IOException {
                        File file = new File(parentDir, name);
-                       FileOutputStream fos = new FileOutputStream(file);
-                       try {
+                       try (FileOutputStream fos = new FileOutputStream(file)) {
                                fos.write(content.getBytes(Constants.CHARACTER_ENCODING));
                                fos.write('\n');
-                       } finally {
-                               fos.close();
                        }
                }
 
                private static void appendToFile(File file, String content)
                                throws IOException {
-                       FileOutputStream fos = new FileOutputStream(file, true);
-                       try {
+                       try (FileOutputStream fos = new FileOutputStream(file, true)) {
                                fos.write(content.getBytes(Constants.CHARACTER_ENCODING));
                                fos.write('\n');
-                       } finally {
-                               fos.close();
                        }
                }
        }
index 3495ff8a9dbb076ba21861def78779223ba67779..82c7a4b6c721763861da7483dd2d76f1df3c6719 100644 (file)
@@ -303,12 +303,9 @@ public class StashCreateCommand extends GitCommand<RevCommit> {
                                                entry.setLastModified(wtIter.getEntryLastModified());
                                                entry.setFileMode(wtIter.getEntryFileMode());
                                                long contentLength = wtIter.getEntryContentLength();
-                                               InputStream in = wtIter.openEntryStream();
-                                               try {
+                                               try (InputStream in = wtIter.openEntryStream()) {
                                                        entry.setObjectId(inserter.insert(
                                                                        Constants.OBJ_BLOB, contentLength, in));
-                                               } finally {
-                                                       in.close();
                                                }
 
                                                if (indexIter == null && headIter == null)
index 8b4d2ec8fc0d6b6c8c1a24381f39fe26ec5a78d0..09c0351b804fa054f16ed9046622ba5e7741dd7d 100644 (file)
@@ -147,19 +147,13 @@ public class SimilarityIndex {
 
        private void hashLargeObject(ObjectLoader obj) throws IOException,
                        TableFullException {
-               ObjectStream in1 = obj.openStream();
                boolean text;
-               try {
+               try (ObjectStream in1 = obj.openStream()) {
                        text = !RawText.isBinary(in1);
-               } finally {
-                       in1.close();
                }
 
-               ObjectStream in2 = obj.openStream();
-               try {
+               try (ObjectStream in2 = obj.openStream()) {
                        hash(in2, in2.getSize(), text);
-               } finally {
-                       in2.close();
                }
        }
 
index e827612d234ee83b8a540178749a893bcc344cde..7ba83c7cbf2636fa650186f1a0784d3a7e7447c4 100644 (file)
@@ -131,18 +131,10 @@ public class RepoProject implements Comparable<RepoProject> {
                        File srcFile = new File(repo.getWorkTree(),
                                        path + "/" + src); //$NON-NLS-1$
                        File destFile = new File(repo.getWorkTree(), dest);
-                       FileInputStream input = new FileInputStream(srcFile);
-                       try {
-                               FileOutputStream output = new FileOutputStream(destFile);
-                               try {
-                                       FileChannel channel = input.getChannel();
-                                       output.getChannel().transferFrom(
-                                                       channel, 0, channel.size());
-                               } finally {
-                                       output.close();
-                               }
-                       } finally {
-                               input.close();
+                       try (FileInputStream input = new FileInputStream(srcFile);
+                                       FileOutputStream output = new FileOutputStream(destFile)) {
+                               FileChannel channel = input.getChannel();
+                               output.getChannel().transferFrom(channel, 0, channel.size());
                        }
                }
        }
index 7e360421ac64329bf427948bd2b3f54613177f46..87419c780cf5b0f8334534cdcadc517b33d0cec3 100644 (file)
@@ -209,8 +209,7 @@ public final class DfsPackFile extends BlockBasedFile {
                        try {
                                ctx.stats.readIdx++;
                                long start = System.nanoTime();
-                               ReadableChannel rc = ctx.db.openFile(desc, INDEX);
-                               try {
+                               try (ReadableChannel rc = ctx.db.openFile(desc, INDEX)) {
                                        InputStream in = Channels.newInputStream(rc);
                                        int wantSize = 8192;
                                        int bs = rc.blockSize();
@@ -221,7 +220,6 @@ public final class DfsPackFile extends BlockBasedFile {
                                        idx = PackIndex.read(new BufferedInputStream(in, bs));
                                        ctx.stats.readIdxBytes += rc.position();
                                } finally {
-                                       rc.close();
                                        ctx.stats.readIdxMicros += elapsedMicros(start);
                                }
                        } catch (EOFException e) {
index 5dcba6001accc3193192c89cd1109e5c8fc4cfb6..b5a4d5c3fdebb89b5a9a3173e6eac7681364cc3e 100644 (file)
@@ -429,8 +429,7 @@ public class ObjectDirectoryPackParser extends PackParser {
 
        private void writeIdx() throws IOException {
                List<PackedObjectInfo> list = getSortedObjectList(null /* by ObjectId */);
-               final FileOutputStream os = new FileOutputStream(tmpIdx);
-               try {
+               try (FileOutputStream os = new FileOutputStream(tmpIdx)) {
                        final PackIndexWriter iw;
                        if (indexVersion <= 0)
                                iw = PackIndexWriter.createOldestPossible(os, list);
@@ -438,8 +437,6 @@ public class ObjectDirectoryPackParser extends PackParser {
                                iw = PackIndexWriter.createVersion(os, indexVersion);
                        iw.write(list, packHash);
                        os.getChannel().force(true);
-               } finally {
-                       os.close();
                }
        }
 
index 432f5a6cd97ee2c8bf686feec9af8f2a62947035..64f2a6fc6dbf5ed3b0889eb974ecfa01b7193021 100644 (file)
@@ -194,8 +194,7 @@ public abstract class ObjectLoader {
                if (!isLarge())
                        return getCachedBytes();
 
-               ObjectStream in = openStream();
-               try {
+               try (ObjectStream in = openStream()) {
                        long sz = in.getSize();
                        if (sizeLimit < sz)
                                throw new LargeObjectException.ExceedsLimit(sizeLimit, sz);
@@ -212,8 +211,6 @@ public abstract class ObjectLoader {
 
                        IO.readFully(in, buf, 0, buf.length);
                        return buf;
-               } finally {
-                       in.close();
                }
        }
 
@@ -255,8 +252,7 @@ public abstract class ObjectLoader {
        public void copyTo(OutputStream out) throws MissingObjectException,
                        IOException {
                if (isLarge()) {
-                       ObjectStream in = openStream();
-                       try {
+                       try (ObjectStream in = openStream()) {
                                final long sz = in.getSize();
                                byte[] tmp = new byte[8192];
                                long copied = 0;
@@ -269,8 +265,6 @@ public abstract class ObjectLoader {
                                }
                                if (0 <= in.read())
                                        throw new EOFException();
-                       } finally {
-                               in.close();
                        }
                } else {
                        out.write(getCachedBytes());
index 42ca24845972effcedb739100eb08ad81b9012bc..c43037ea0ed05cc72a36e552050f047999e4ce87 100644 (file)
@@ -1946,11 +1946,8 @@ public abstract class Repository implements AutoCloseable {
 
        private void writeCommitMsg(File msgFile, String msg) throws IOException {
                if (msg != null) {
-                       FileOutputStream fos = new FileOutputStream(msgFile);
-                       try {
+                       try (FileOutputStream fos = new FileOutputStream(msgFile)) {
                                fos.write(msg.getBytes(Constants.CHARACTER_ENCODING));
-                       } finally {
-                               fos.close();
                        }
                } else {
                        FileUtils.delete(msgFile, FileUtils.SKIP_MISSING);
index af5a0b7c989c7020c97207f72fd84ff7fecacd15..a487252eef7cc4e31c32f0edd301f3a97a2fdc38 100644 (file)
@@ -1642,17 +1642,17 @@ public abstract class PackParser {
 
        private void inflateAndSkip(final Source src, final long inflatedSize)
                        throws IOException {
-               final InputStream inf = inflate(src, inflatedSize);
-               IO.skipFully(inf, inflatedSize);
-               inf.close();
+               try (InputStream inf = inflate(src, inflatedSize)) {
+                       IO.skipFully(inf, inflatedSize);
+               }
        }
 
        private byte[] inflateAndReturn(final Source src, final long inflatedSize)
                        throws IOException {
                final byte[] dst = new byte[(int) inflatedSize];
-               final InputStream inf = inflate(src, inflatedSize);
-               IO.readFully(inf, dst, 0, dst.length);
-               inf.close();
+               try (InputStream inf = inflate(src, inflatedSize)) {
+                       IO.readFully(inf, dst, 0, dst.length);
+               }
                return dst;
        }
 
index c6191eceb06e40af97db70c2a93a0a2b722486ac..ac68ba2fdd59b254307e744a4e2bdc9803ef5808 100644 (file)
@@ -339,11 +339,8 @@ public class TransportAmazonS3 extends HttpTransport implements WalkTransport {
                        final String s;
                        String ref = ROOT_DIR + rn;
                        try {
-                               final BufferedReader br = openReader(ref);
-                               try {
+                               try (BufferedReader br = openReader(ref)) {
                                        s = br.readLine();
-                               } finally {
-                                       br.close();
                                }
                        } catch (FileNotFoundException noRef) {
                                return null;
index 6708964d5efddd60e707ceebf5290d9f5a0bc83a..46fd5cf1d6ffe0c8bf732f4718c5a2a875f77fdd 100644 (file)
@@ -853,17 +853,12 @@ class WalkFetchConnection extends BaseFetchConnection {
                        pm.beginTask("Get " + idxName.substring(0, 12) + "..idx", //$NON-NLS-1$ //$NON-NLS-2$
                                        s.length < 0 ? ProgressMonitor.UNKNOWN
                                                        : (int) (s.length / 1024));
-                       try {
-                               final FileOutputStream fos = new FileOutputStream(tmpIdx);
-                               try {
-                                       final byte[] buf = new byte[2048];
-                                       int cnt;
-                                       while (!pm.isCancelled() && (cnt = s.in.read(buf)) >= 0) {
-                                               fos.write(buf, 0, cnt);
-                                               pm.update(cnt / 1024);
-                                       }
-                               } finally {
-                                       fos.close();
+                       try (final FileOutputStream fos = new FileOutputStream(tmpIdx)) {
+                               final byte[] buf = new byte[2048];
+                               int cnt;
+                               while (!pm.isCancelled() && (cnt = s.in.read(buf)) >= 0) {
+                                       fos.write(buf, 0, cnt);
+                                       pm.update(cnt / 1024);
                                }
                        } catch (IOException err) {
                                FileUtils.delete(tmpIdx);
index 68cc7cb580619ef38efca4dd851e293f8a9e2e74..bb022e0a92e8a617aabce73d38fe0565f90a9a11 100644 (file)
@@ -1280,11 +1280,8 @@ public abstract class WorkingTreeIterator extends AbstractTreeIterator {
 
                IgnoreNode load() throws IOException {
                        IgnoreNode r = new IgnoreNode();
-                       InputStream in = entry.openInputStream();
-                       try {
+                       try (InputStream in = entry.openInputStream()) {
                                r.parse(in);
-                       } finally {
-                               in.close();
                        }
                        return r.getRules().isEmpty() ? null : r;
                }
@@ -1332,11 +1329,8 @@ public abstract class WorkingTreeIterator extends AbstractTreeIterator {
                private static void loadRulesFromFile(IgnoreNode r, File exclude)
                                throws FileNotFoundException, IOException {
                        if (FS.DETECTED.exists(exclude)) {
-                               FileInputStream in = new FileInputStream(exclude);
-                               try {
+                               try (FileInputStream in = new FileInputStream(exclude)) {
                                        r.parse(in);
-                               } finally {
-                                       in.close();
                                }
                        }
                }
@@ -1353,11 +1347,8 @@ public abstract class WorkingTreeIterator extends AbstractTreeIterator {
 
                AttributesNode load() throws IOException {
                        AttributesNode r = new AttributesNode();
-                       InputStream in = entry.openInputStream();
-                       try {
+                       try (InputStream in = entry.openInputStream()) {
                                r.parse(in);
-                       } finally {
-                               in.close();
                        }
                        return r.getRules().isEmpty() ? null : r;
                }
index dd933a02944d45f8b9732bc697fff659ed535bfa..887f69b87cc94a44f6fb6f744d5e433a5d7bb9af 100644 (file)
@@ -487,11 +487,8 @@ public abstract class TemporaryBuffer extends OutputStream {
                        if (Integer.MAX_VALUE < len)
                                throw new OutOfMemoryError(JGitText.get().lengthExceedsMaximumArraySize);
                        final byte[] out = new byte[(int) len];
-                       final FileInputStream in = new FileInputStream(onDiskFile);
-                       try {
+                       try (FileInputStream in = new FileInputStream(onDiskFile)) {
                                IO.readFully(in, out, 0, (int) len);
-                       } finally {
-                               in.close();
                        }
                        return out;
                }
@@ -505,16 +502,13 @@ public abstract class TemporaryBuffer extends OutputStream {
                        }
                        if (pm == null)
                                pm = NullProgressMonitor.INSTANCE;
-                       final FileInputStream in = new FileInputStream(onDiskFile);
-                       try {
+                       try (FileInputStream in = new FileInputStream(onDiskFile)) {
                                int cnt;
                                final byte[] buf = new byte[Block.SZ];
                                while ((cnt = in.read(buf)) >= 0) {
                                        os.write(buf, 0, cnt);
                                        pm.update(cnt / 1024);
                                }
-                       } finally {
-                               in.close();
                        }
                }