Browse Source

Open auto-closeable resources in try-with-resource

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>
stable-5.0
David Pursehouse 7 years ago committed by Matthias Sohn
parent
commit
5c70be0085
  1. 5
      org.eclipse.jgit.http.server/src/org/eclipse/jgit/http/server/ServletUtils.java
  2. 10
      org.eclipse.jgit.http.server/src/org/eclipse/jgit/http/server/SmartOutputStream.java
  3. 10
      org.eclipse.jgit.http.test/tst/org/eclipse/jgit/http/test/ProtocolErrorTest.java
  4. 5
      org.eclipse.jgit.http.test/tst/org/eclipse/jgit/http/test/SetAdditionalHeadersTest.java
  5. 11
      org.eclipse.jgit.http.test/tst/org/eclipse/jgit/http/test/SmartClientSmartServerTest.java
  6. 33
      org.eclipse.jgit.junit/src/org/eclipse/jgit/junit/RepositoryTestCase.java
  7. 11
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Version.java
  8. 5
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/debug/TextHashFunctions.java
  9. 54
      org.eclipse.jgit.test/tst/org/eclipse/jgit/api/ResetCommandTest.java
  10. 79
      org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/PackFileTest.java
  11. 19
      org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/PackWriterTest.java
  12. 87
      org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/T0003_BasicTest.java
  13. 130
      org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/UnpackedObjectTest.java
  14. 7
      org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/WindowCacheGetTest.java
  15. 5
      org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/RacyGitTests.java
  16. 10
      org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/RefTest.java
  17. 35
      org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/RepositoryCacheTest.java
  18. 7
      org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/SquashCommitMsgTest.java
  19. 26
      org.eclipse.jgit.test/tst/org/eclipse/jgit/merge/ResolveMergerTest.java
  20. 13
      org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/PatchCcErrorTest.java
  21. 13
      org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/PatchCcTest.java
  22. 13
      org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/PatchErrorTest.java
  23. 13
      org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/PatchTest.java
  24. 35
      org.eclipse.jgit.test/tst/org/eclipse/jgit/submodule/SubmoduleAddTest.java
  25. 28
      org.eclipse.jgit.test/tst/org/eclipse/jgit/submodule/SubmoduleSyncTest.java
  26. 8
      org.eclipse.jgit.test/tst/org/eclipse/jgit/submodule/SubmoduleUpdateTest.java
  27. 8
      org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/NetRCTest.java
  28. 10
      org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/PackParserTest.java
  29. 59
      org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/WalkEncryptionTest.java
  30. 13
      org.eclipse.jgit.test/tst/org/eclipse/jgit/treewalk/filter/NotTreeFilterTest.java
  31. 55
      org.eclipse.jgit.test/tst/org/eclipse/jgit/util/TemporaryBufferTest.java
  32. 47
      org.eclipse.jgit.test/tst/org/eclipse/jgit/util/io/AutoCRLFOutputStreamTest.java
  33. 48
      org.eclipse.jgit.test/tst/org/eclipse/jgit/util/io/UnionInputStreamTest.java
  34. 7
      org.eclipse.jgit/src/org/eclipse/jgit/api/CloneCommand.java
  35. 10
      org.eclipse.jgit/src/org/eclipse/jgit/api/RebaseCommand.java
  36. 5
      org.eclipse.jgit/src/org/eclipse/jgit/api/StashCreateCommand.java
  37. 10
      org.eclipse.jgit/src/org/eclipse/jgit/diff/SimilarityIndex.java
  38. 16
      org.eclipse.jgit/src/org/eclipse/jgit/gitrepo/RepoProject.java
  39. 4
      org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/dfs/DfsPackFile.java
  40. 5
      org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/file/ObjectDirectoryPackParser.java
  41. 10
      org.eclipse.jgit/src/org/eclipse/jgit/lib/ObjectLoader.java
  42. 5
      org.eclipse.jgit/src/org/eclipse/jgit/lib/Repository.java
  43. 12
      org.eclipse.jgit/src/org/eclipse/jgit/transport/PackParser.java
  44. 5
      org.eclipse.jgit/src/org/eclipse/jgit/transport/TransportAmazonS3.java
  45. 17
      org.eclipse.jgit/src/org/eclipse/jgit/transport/WalkFetchConnection.java
  46. 15
      org.eclipse.jgit/src/org/eclipse/jgit/treewalk/WorkingTreeIterator.java
  47. 10
      org.eclipse.jgit/src/org/eclipse/jgit/util/TemporaryBuffer.java

5
org.eclipse.jgit.http.server/src/org/eclipse/jgit/http/server/ServletUtils.java

@ -220,12 +220,9 @@ public final class ServletUtils {
public static void send(byte[] content, final HttpServletRequest req, public static void send(byte[] content, final HttpServletRequest req,
final HttpServletResponse rsp) throws IOException { final HttpServletResponse rsp) throws IOException {
content = sendInit(content, req, rsp); content = sendInit(content, req, rsp);
final OutputStream out = rsp.getOutputStream(); try (OutputStream out = rsp.getOutputStream()) {
try {
out.write(content); out.write(content);
out.flush(); out.flush();
} finally {
out.close();
} }
} }

10
org.eclipse.jgit.http.server/src/org/eclipse/jgit/http/server/SmartOutputStream.java

@ -110,11 +110,8 @@ class SmartOutputStream extends TemporaryBuffer {
if (256 < out.length() && acceptsGzipEncoding(req)) { if (256 < out.length() && acceptsGzipEncoding(req)) {
TemporaryBuffer gzbuf = new TemporaryBuffer.Heap(LIMIT); TemporaryBuffer gzbuf = new TemporaryBuffer.Heap(LIMIT);
try { try {
GZIPOutputStream gzip = new GZIPOutputStream(gzbuf); try (GZIPOutputStream gzip = new GZIPOutputStream(gzbuf)) {
try {
out.writeTo(gzip, null); out.writeTo(gzip, null);
} finally {
gzip.close();
} }
if (gzbuf.length() < out.length()) { if (gzbuf.length() < out.length()) {
out = gzbuf; out = gzbuf;
@ -131,12 +128,9 @@ class SmartOutputStream extends TemporaryBuffer {
// hardcoded LIMIT constant above assures us we wouldn't store // hardcoded LIMIT constant above assures us we wouldn't store
// more than 2 GiB of content in memory. // more than 2 GiB of content in memory.
rsp.setContentLength((int) out.length()); rsp.setContentLength((int) out.length());
final OutputStream os = rsp.getOutputStream(); try (OutputStream os = rsp.getOutputStream()) {
try {
out.writeTo(os, null); out.writeTo(os, null);
os.flush(); os.flush();
} finally {
os.close();
} }
} }
} }

10
org.eclipse.jgit.http.test/tst/org/eclipse/jgit/http/test/ProtocolErrorTest.java

@ -149,19 +149,15 @@ public class ProtocolErrorTest extends HttpTestCase {
c.setRequestProperty("Content-Type", c.setRequestProperty("Content-Type",
GitSmartHttpTools.RECEIVE_PACK_REQUEST_TYPE); GitSmartHttpTools.RECEIVE_PACK_REQUEST_TYPE);
c.setFixedLengthStreamingMode(reqbin.length); c.setFixedLengthStreamingMode(reqbin.length);
OutputStream out = c.getOutputStream(); try (OutputStream out = c.getOutputStream()) {
try {
out.write(reqbin); out.write(reqbin);
} finally {
out.close();
} }
assertEquals(200, c.getResponseCode()); assertEquals(200, c.getResponseCode());
assertEquals(GitSmartHttpTools.RECEIVE_PACK_RESULT_TYPE, assertEquals(GitSmartHttpTools.RECEIVE_PACK_RESULT_TYPE,
c.getContentType()); c.getContentType());
InputStream rawin = c.getInputStream(); try (InputStream rawin = c.getInputStream()) {
try {
PacketLineIn pckin = new PacketLineIn(rawin); PacketLineIn pckin = new PacketLineIn(rawin);
assertEquals("unpack error " assertEquals("unpack error "
+ JGitText.get().packfileIsTruncatedNoParam, + JGitText.get().packfileIsTruncatedNoParam,
@ -169,8 +165,6 @@ public class ProtocolErrorTest extends HttpTestCase {
assertEquals("ng refs/objects/A n/a (unpacker error)", assertEquals("ng refs/objects/A n/a (unpacker error)",
pckin.readString()); pckin.readString());
assertSame(PacketLineIn.END, pckin.readString()); assertSame(PacketLineIn.END, pckin.readString());
} finally {
rawin.close();
} }
} finally { } finally {
c.disconnect(); c.disconnect();

5
org.eclipse.jgit.http.test/tst/org/eclipse/jgit/http/test/SetAdditionalHeadersTest.java

@ -107,8 +107,7 @@ public class SetAdditionalHeadersTest extends HttpTestCase {
assertEquals("http", remoteURI.getScheme()); assertEquals("http", remoteURI.getScheme());
Transport t = Transport.open(dst, remoteURI); try (Transport t = Transport.open(dst, remoteURI)) {
try {
assertTrue("isa TransportHttp", t instanceof TransportHttp); assertTrue("isa TransportHttp", t instanceof TransportHttp);
assertTrue("isa HttpTransport", t instanceof HttpTransport); assertTrue("isa HttpTransport", t instanceof HttpTransport);
@ -117,8 +116,6 @@ public class SetAdditionalHeadersTest extends HttpTestCase {
headers.put("AnotherKey", "someValue"); headers.put("AnotherKey", "someValue");
((TransportHttp) t).setAdditionalHeaders(headers); ((TransportHttp) t).setAdditionalHeaders(headers);
t.openFetch(); t.openFetch();
} finally {
t.close();
} }
List<AccessEvent> requests = getRequests(); List<AccessEvent> requests = getRequests();

11
org.eclipse.jgit.http.test/tst/org/eclipse/jgit/http/test/SmartClientSmartServerTest.java

@ -267,9 +267,9 @@ public class SmartClientSmartServerTest extends HttpTestCase {
final HttpServletResponse r = (HttpServletResponse) response; final HttpServletResponse r = (HttpServletResponse) response;
r.setContentType("text/plain"); r.setContentType("text/plain");
r.setCharacterEncoding("UTF-8"); r.setCharacterEncoding("UTF-8");
PrintWriter w = r.getWriter(); try (PrintWriter w = r.getWriter()) {
w.print("OK"); w.print("OK");
w.close(); }
} }
@Override @Override
@ -397,11 +397,8 @@ public class SmartClientSmartServerTest extends HttpTestCase {
assertTrue("isa TransportHttp", t instanceof TransportHttp); assertTrue("isa TransportHttp", t instanceof TransportHttp);
assertTrue("isa HttpTransport", t instanceof HttpTransport); assertTrue("isa HttpTransport", t instanceof HttpTransport);
FetchConnection c = t.openFetch(); try (FetchConnection c = t.openFetch()) {
try {
map = c.getRefsMap(); map = c.getRefsMap();
} finally {
c.close();
} }
} }

33
org.eclipse.jgit.junit/src/org/eclipse/jgit/junit/RepositoryTestCase.java

@ -94,20 +94,13 @@ public abstract class RepositoryTestCase extends LocalDiskRepositoryTestCase {
*/ */
protected static void copyFile(final File src, final File dst) protected static void copyFile(final File src, final File dst)
throws IOException { throws IOException {
final FileInputStream fis = new FileInputStream(src); try (FileInputStream fis = new FileInputStream(src);
try { FileOutputStream fos = new FileOutputStream(dst)) {
final FileOutputStream fos = new FileOutputStream(dst); final byte[] buf = new byte[4096];
try { int r;
final byte[] buf = new byte[4096]; while ((r = fis.read(buf)) > 0) {
int r; fos.write(buf, 0, r);
while ((r = fis.read(buf)) > 0) {
fos.write(buf, 0, r);
}
} finally {
fos.close();
} }
} finally {
fis.close();
} }
} }
@ -293,10 +286,11 @@ public abstract class RepositoryTestCase extends LocalDiskRepositoryTestCase {
dce.setFileMode(treeItr.getEntryFileMode()); dce.setFileMode(treeItr.getEntryFileMode());
dce.setLastModified(treeItr.getEntryLastModified()); dce.setLastModified(treeItr.getEntryLastModified());
dce.setLength((int) len); dce.setLength((int) len);
FileInputStream in = new FileInputStream( try (FileInputStream in = new FileInputStream(
treeItr.getEntryFile()); treeItr.getEntryFile())) {
dce.setObjectId(inserter.insert(Constants.OBJ_BLOB, len, in)); dce.setObjectId(
in.close(); inserter.insert(Constants.OBJ_BLOB, len, in));
}
builder.add(dce); builder.add(dce);
treeItr.next(1); treeItr.next(1);
} }
@ -380,8 +374,9 @@ public abstract class RepositoryTestCase extends LocalDiskRepositoryTestCase {
while (actTime <= startTime) { while (actTime <= startTime) {
Thread.sleep(sleepTime); Thread.sleep(sleepTime);
sleepTime *= 2; sleepTime *= 2;
FileOutputStream fos = new FileOutputStream(tmp); try (FileOutputStream fos = new FileOutputStream(tmp)) {
fos.close(); // Do nothing
}
actTime = fs.lastModified(tmp); actTime = fs.lastModified(tmp);
} }
return actTime; return actTime;

11
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Version.java

@ -96,14 +96,9 @@ class Version extends TextBuiltin {
} }
private static String getBundleVersion(URL url) { private static String getBundleVersion(URL url) {
try { try (InputStream is = url.openStream()) {
InputStream is = url.openStream(); Manifest manifest = new Manifest(is);
try { return manifest.getMainAttributes().getValue("Bundle-Version"); //$NON-NLS-1$
Manifest manifest = new Manifest(is);
return manifest.getMainAttributes().getValue("Bundle-Version"); //$NON-NLS-1$
} finally {
is.close();
}
} catch (IOException e) { } catch (IOException e) {
// do nothing - will return null // do nothing - will return null
} }

5
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/debug/TextHashFunctions.java

@ -288,11 +288,8 @@ class TextHashFunctions extends TextBuiltin {
else else
rb.findGitDir(dir); rb.findGitDir(dir);
Repository repo = rb.build(); try (Repository repo = rb.build()) {
try {
run(repo); run(repo);
} finally {
repo.close();
} }
} }
} }

54
org.eclipse.jgit.test/tst/org/eclipse/jgit/api/ResetCommandTest.java

@ -100,39 +100,39 @@ public class ResetCommandTest extends RepositoryTestCase {
File nestedFile = new File(dir, "b.txt"); File nestedFile = new File(dir, "b.txt");
FileUtils.createNewFile(nestedFile); FileUtils.createNewFile(nestedFile);
PrintWriter nesterFileWriter = new PrintWriter(nestedFile); try (PrintWriter nestedFileWriter = new PrintWriter(nestedFile)) {
nesterFileWriter.print("content"); nestedFileWriter.print("content");
nesterFileWriter.flush(); nestedFileWriter.flush();
// create file // create file
indexFile = new File(db.getWorkTree(), "a.txt"); indexFile = new File(db.getWorkTree(), "a.txt");
FileUtils.createNewFile(indexFile); FileUtils.createNewFile(indexFile);
PrintWriter writer = new PrintWriter(indexFile); try (PrintWriter writer = new PrintWriter(indexFile)) {
writer.print("content"); writer.print("content");
writer.flush(); writer.flush();
// add file and commit it // add file and commit it
git.add().addFilepattern("dir").addFilepattern("a.txt").call(); git.add().addFilepattern("dir").addFilepattern("a.txt").call();
secondCommit = git.commit().setMessage("adding a.txt and dir/b.txt") secondCommit = git.commit()
.call(); .setMessage("adding a.txt and dir/b.txt").call();
prestage = DirCache.read(db.getIndexFile(), db.getFS()).getEntry( prestage = DirCache.read(db.getIndexFile(), db.getFS())
indexFile.getName()); .getEntry(indexFile.getName());
// modify file and add to index // modify file and add to index
writer.print("new content"); writer.print("new content");
writer.close(); }
nesterFileWriter.print("new content"); nestedFileWriter.print("new content");
nesterFileWriter.close(); }
git.add().addFilepattern("a.txt").addFilepattern("dir").call(); git.add().addFilepattern("a.txt").addFilepattern("dir").call();
// create a file not added to the index // create a file not added to the index
untrackedFile = new File(db.getWorkTree(), untrackedFile = new File(db.getWorkTree(),
"notAddedToIndex.txt"); "notAddedToIndex.txt");
FileUtils.createNewFile(untrackedFile); FileUtils.createNewFile(untrackedFile);
PrintWriter writer2 = new PrintWriter(untrackedFile); try (PrintWriter writer2 = new PrintWriter(untrackedFile)) {
writer2.print("content"); writer2.print("content");
writer2.close(); }
} }
@Test @Test

79
org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/PackFileTest.java

@ -146,15 +146,15 @@ public class PackFileTest extends LocalDiskRepositoryTestCase {
assertFalse("is not large", ol.isLarge()); assertFalse("is not large", ol.isLarge());
assertTrue("same content", Arrays.equals(data, ol.getCachedBytes())); assertTrue("same content", Arrays.equals(data, ol.getCachedBytes()));
ObjectStream in = ol.openStream(); try (ObjectStream in = ol.openStream()) {
assertNotNull("have stream", in); assertNotNull("have stream", in);
assertEquals(type, in.getType()); assertEquals(type, in.getType());
assertEquals(data.length, in.getSize()); assertEquals(data.length, in.getSize());
byte[] data2 = new byte[data.length]; byte[] data2 = new byte[data.length];
IO.readFully(in, data2, 0, data.length); IO.readFully(in, data2, 0, data.length);
assertTrue("same content", Arrays.equals(data2, data)); assertTrue("same content", Arrays.equals(data2, data));
assertEquals("stream at EOF", -1, in.read()); assertEquals("stream at EOF", -1, in.read());
in.close(); }
} }
@Test @Test
@ -180,15 +180,15 @@ public class PackFileTest extends LocalDiskRepositoryTestCase {
.getMessage()); .getMessage());
} }
ObjectStream in = ol.openStream(); try (ObjectStream in = ol.openStream()) {
assertNotNull("have stream", in); assertNotNull("have stream", in);
assertEquals(type, in.getType()); assertEquals(type, in.getType());
assertEquals(data.length, in.getSize()); assertEquals(data.length, in.getSize());
byte[] data2 = new byte[data.length]; byte[] data2 = new byte[data.length];
IO.readFully(in, data2, 0, data.length); IO.readFully(in, data2, 0, data.length);
assertTrue("same content", Arrays.equals(data2, data)); assertTrue("same content", Arrays.equals(data2, data));
assertEquals("stream at EOF", -1, in.read()); assertEquals("stream at EOF", -1, in.read());
in.close(); }
} }
@Test @Test
@ -239,15 +239,15 @@ public class PackFileTest extends LocalDiskRepositoryTestCase {
assertNotNull(ol.getCachedBytes()); assertNotNull(ol.getCachedBytes());
assertArrayEquals(data3, ol.getCachedBytes()); assertArrayEquals(data3, ol.getCachedBytes());
ObjectStream in = ol.openStream(); try (ObjectStream in = ol.openStream()) {
assertNotNull("have stream", in); assertNotNull("have stream", in);
assertEquals(Constants.OBJ_BLOB, in.getType()); assertEquals(Constants.OBJ_BLOB, in.getType());
assertEquals(data3.length, in.getSize()); assertEquals(data3.length, in.getSize());
byte[] act = new byte[data3.length]; byte[] act = new byte[data3.length];
IO.readFully(in, act, 0, data3.length); IO.readFully(in, act, 0, data3.length);
assertTrue("same content", Arrays.equals(act, data3)); assertTrue("same content", Arrays.equals(act, data3));
assertEquals("stream at EOF", -1, in.read()); assertEquals("stream at EOF", -1, in.read());
in.close(); }
} }
} }
@ -282,22 +282,16 @@ public class PackFileTest extends LocalDiskRepositoryTestCase {
File packName = new File(dir, idA.name() + ".pack"); File packName = new File(dir, idA.name() + ".pack");
File idxName = new File(dir, idA.name() + ".idx"); File idxName = new File(dir, idA.name() + ".idx");
FileOutputStream f = new FileOutputStream(packName); try (FileOutputStream f = new FileOutputStream(packName)) {
try {
f.write(pack.toByteArray()); f.write(pack.toByteArray());
} finally {
f.close();
} }
f = new FileOutputStream(idxName); try (FileOutputStream f = new FileOutputStream(idxName)) {
try {
List<PackedObjectInfo> list = new ArrayList<>(); List<PackedObjectInfo> list = new ArrayList<>();
list.add(a); list.add(a);
list.add(b); list.add(b);
Collections.sort(list); Collections.sort(list);
new PackIndexWriterV1(f).write(list, footer); new PackIndexWriterV1(f).write(list, footer);
} finally {
f.close();
} }
PackFile packFile = new PackFile(packName, PackExt.INDEX.getBit()); PackFile packFile = new PackFile(packName, PackExt.INDEX.getBit());
@ -321,16 +315,17 @@ public class PackFileTest extends LocalDiskRepositoryTestCase {
assertTrue("has blob", wc.has(id)); assertTrue("has blob", wc.has(id));
ObjectLoader ol = wc.open(id); ObjectLoader ol = wc.open(id);
ObjectStream in = ol.openStream(); try (ObjectStream in = ol.openStream()) {
assertTrue(in instanceof ObjectStream.SmallStream); assertTrue(in instanceof ObjectStream.SmallStream);
assertEquals(300, in.available()); assertEquals(300, in.available());
in.close(); }
wc.setStreamFileThreshold(299); wc.setStreamFileThreshold(299);
ol = wc.open(id); ol = wc.open(id);
in = ol.openStream(); try (ObjectStream in = ol.openStream()) {
assertTrue(in instanceof ObjectStream.Filter); assertTrue(in instanceof ObjectStream.Filter);
assertEquals(1, in.available()); assertEquals(1, in.available());
}
} }
private static byte[] clone(int first, byte[] base) { private static byte[] clone(int first, byte[] base) {

19
org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/PackWriterTest.java

@ -515,11 +515,8 @@ public class PackWriterTest extends SampleDataRepositoryTestCase {
// Validate that an index written by PackWriter is the same. // Validate that an index written by PackWriter is the same.
final File idx2File = new File(indexFile.getAbsolutePath() + ".2"); final File idx2File = new File(indexFile.getAbsolutePath() + ".2");
final FileOutputStream is = new FileOutputStream(idx2File); try (FileOutputStream is = new FileOutputStream(idx2File)) {
try {
writer.writeIndex(is); writer.writeIndex(is);
} finally {
is.close();
} }
final PackIndex idx2 = PackIndex.open(idx2File); final PackIndex idx2 = PackIndex.open(idx2File);
assertTrue(idx2 instanceof PackIndexV2); assertTrue(idx2 instanceof PackIndexV2);
@ -715,14 +712,14 @@ public class PackWriterTest extends SampleDataRepositoryTestCase {
String id = pw.computeName().getName(); String id = pw.computeName().getName();
File packdir = repo.getObjectDatabase().getPackDirectory(); File packdir = repo.getObjectDatabase().getPackDirectory();
File packFile = new File(packdir, "pack-" + id + ".pack"); File packFile = new File(packdir, "pack-" + id + ".pack");
FileOutputStream packOS = new FileOutputStream(packFile); try (FileOutputStream packOS = new FileOutputStream(packFile)) {
pw.writePack(NullProgressMonitor.INSTANCE, pw.writePack(NullProgressMonitor.INSTANCE,
NullProgressMonitor.INSTANCE, packOS); NullProgressMonitor.INSTANCE, packOS);
packOS.close(); }
File idxFile = new File(packdir, "pack-" + id + ".idx"); File idxFile = new File(packdir, "pack-" + id + ".idx");
FileOutputStream idxOS = new FileOutputStream(idxFile); try (FileOutputStream idxOS = new FileOutputStream(idxFile)) {
pw.writeIndex(idxOS); pw.writeIndex(idxOS);
idxOS.close(); }
return PackIndex.open(idxFile); return PackIndex.open(idxFile);
} }
} }

87
org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/T0003_BasicTest.java

@ -137,10 +137,10 @@ public class T0003_BasicTest extends SampleDataRepositoryTestCase {
@Test @Test
public void test000_openrepo_default_gitDirSet() throws IOException { public void test000_openrepo_default_gitDirSet() throws IOException {
File repo1Parent = new File(trash.getParentFile(), "r1"); File repo1Parent = new File(trash.getParentFile(), "r1");
Repository repo1initial = new FileRepository(new File(repo1Parent, try (Repository repo1initial = new FileRepository(
Constants.DOT_GIT)); new File(repo1Parent, Constants.DOT_GIT))) {
repo1initial.create(); repo1initial.create();
repo1initial.close(); }
File theDir = new File(repo1Parent, Constants.DOT_GIT); File theDir = new File(repo1Parent, Constants.DOT_GIT);
FileRepository r = (FileRepository) new FileRepositoryBuilder() FileRepository r = (FileRepository) new FileRepositoryBuilder()
@ -162,10 +162,10 @@ public class T0003_BasicTest extends SampleDataRepositoryTestCase {
public void test000_openrepo_default_gitDirAndWorkTreeSet() public void test000_openrepo_default_gitDirAndWorkTreeSet()
throws IOException { throws IOException {
File repo1Parent = new File(trash.getParentFile(), "r1"); File repo1Parent = new File(trash.getParentFile(), "r1");
Repository repo1initial = new FileRepository(new File(repo1Parent, try (Repository repo1initial = new FileRepository(
Constants.DOT_GIT)); new File(repo1Parent, Constants.DOT_GIT))) {
repo1initial.create(); repo1initial.create();
repo1initial.close(); }
File theDir = new File(repo1Parent, Constants.DOT_GIT); File theDir = new File(repo1Parent, Constants.DOT_GIT);
FileRepository r = (FileRepository) new FileRepositoryBuilder() FileRepository r = (FileRepository) new FileRepositoryBuilder()
@ -187,10 +187,10 @@ public class T0003_BasicTest extends SampleDataRepositoryTestCase {
@Test @Test
public void test000_openrepo_default_workDirSet() throws IOException { public void test000_openrepo_default_workDirSet() throws IOException {
File repo1Parent = new File(trash.getParentFile(), "r1"); File repo1Parent = new File(trash.getParentFile(), "r1");
Repository repo1initial = new FileRepository(new File(repo1Parent, try (Repository repo1initial = new FileRepository(
Constants.DOT_GIT)); new File(repo1Parent, Constants.DOT_GIT))) {
repo1initial.create(); repo1initial.create();
repo1initial.close(); }
File theDir = new File(repo1Parent, Constants.DOT_GIT); File theDir = new File(repo1Parent, Constants.DOT_GIT);
FileRepository r = (FileRepository) new FileRepositoryBuilder() FileRepository r = (FileRepository) new FileRepositoryBuilder()
@ -213,13 +213,13 @@ public class T0003_BasicTest extends SampleDataRepositoryTestCase {
File repo1Parent = new File(trash.getParentFile(), "r1"); File repo1Parent = new File(trash.getParentFile(), "r1");
File workdir = new File(trash.getParentFile(), "rw"); File workdir = new File(trash.getParentFile(), "rw");
FileUtils.mkdir(workdir); FileUtils.mkdir(workdir);
FileRepository repo1initial = new FileRepository(new File(repo1Parent, try (FileRepository repo1initial = new FileRepository(
Constants.DOT_GIT)); new File(repo1Parent, Constants.DOT_GIT))) {
repo1initial.create(); repo1initial.create();
final FileBasedConfig cfg = repo1initial.getConfig(); final FileBasedConfig cfg = repo1initial.getConfig();
cfg.setString("core", null, "worktree", workdir.getAbsolutePath()); cfg.setString("core", null, "worktree", workdir.getAbsolutePath());
cfg.save(); cfg.save();
repo1initial.close(); }
File theDir = new File(repo1Parent, Constants.DOT_GIT); File theDir = new File(repo1Parent, Constants.DOT_GIT);
FileRepository r = (FileRepository) new FileRepositoryBuilder() FileRepository r = (FileRepository) new FileRepositoryBuilder()
@ -242,13 +242,13 @@ public class T0003_BasicTest extends SampleDataRepositoryTestCase {
File repo1Parent = new File(trash.getParentFile(), "r1"); File repo1Parent = new File(trash.getParentFile(), "r1");
File workdir = new File(trash.getParentFile(), "rw"); File workdir = new File(trash.getParentFile(), "rw");
FileUtils.mkdir(workdir); FileUtils.mkdir(workdir);
FileRepository repo1initial = new FileRepository(new File(repo1Parent, try (FileRepository repo1initial = new FileRepository(
Constants.DOT_GIT)); new File(repo1Parent, Constants.DOT_GIT))) {
repo1initial.create(); repo1initial.create();
final FileBasedConfig cfg = repo1initial.getConfig(); final FileBasedConfig cfg = repo1initial.getConfig();
cfg.setString("core", null, "worktree", "../../rw"); cfg.setString("core", null, "worktree", "../../rw");
cfg.save(); cfg.save();
repo1initial.close(); }
File theDir = new File(repo1Parent, Constants.DOT_GIT); File theDir = new File(repo1Parent, Constants.DOT_GIT);
FileRepository r = (FileRepository) new FileRepositoryBuilder() FileRepository r = (FileRepository) new FileRepositoryBuilder()
@ -273,26 +273,24 @@ public class T0003_BasicTest extends SampleDataRepositoryTestCase {
File indexFile = new File(trash, "idx"); File indexFile = new File(trash, "idx");
File objDir = new File(trash, "../obj"); File objDir = new File(trash, "../obj");
File altObjDir = db.getObjectDatabase().getDirectory(); File altObjDir = db.getObjectDatabase().getDirectory();
Repository repo1initial = new FileRepository(new File(repo1Parent, try (Repository repo1initial = new FileRepository(
Constants.DOT_GIT)); new File(repo1Parent, Constants.DOT_GIT))) {
repo1initial.create(); repo1initial.create();
repo1initial.close(); }
File theDir = new File(repo1Parent, Constants.DOT_GIT); File theDir = new File(repo1Parent, Constants.DOT_GIT);
FileRepository r = (FileRepository) new FileRepositoryBuilder() // try (FileRepository r = (FileRepository) new FileRepositoryBuilder() //
.setGitDir(theDir).setObjectDirectory(objDir) // .setGitDir(theDir).setObjectDirectory(objDir) //
.addAlternateObjectDirectory(altObjDir) // .addAlternateObjectDirectory(altObjDir) //
.setIndexFile(indexFile) // .setIndexFile(indexFile) //
.build(); .build()) {
assertEqualsPath(theDir, r.getDirectory()); assertEqualsPath(theDir, r.getDirectory());
assertEqualsPath(theDir.getParentFile(), r.getWorkTree()); assertEqualsPath(theDir.getParentFile(), r.getWorkTree());
assertEqualsPath(indexFile, r.getIndexFile()); assertEqualsPath(indexFile, r.getIndexFile());
assertEqualsPath(objDir, r.getObjectDatabase().getDirectory()); assertEqualsPath(objDir, r.getObjectDatabase().getDirectory());
assertNotNull(r.open(ObjectId assertNotNull(r.open(ObjectId
.fromString("6db9c2ebf75590eef973081736730a9ea169a0c4"))); .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();
} }
protected void assertEqualsPath(File expected, File actual) 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. // Verify the commit we just wrote is in the correct format.
ObjectDatabase odb = db.getObjectDatabase(); ObjectDatabase odb = db.getObjectDatabase();
assertTrue("is ObjectDirectory", odb instanceof ObjectDirectory); assertTrue("is ObjectDirectory", odb instanceof ObjectDirectory);
final XInputStream xis = new XInputStream(new FileInputStream( try (XInputStream xis = new XInputStream(
((ObjectDirectory) odb).fileFor(cmtid))); new FileInputStream(((ObjectDirectory) odb).fileFor(cmtid)))) {
try {
assertEquals(0x78, xis.readUInt8()); assertEquals(0x78, xis.readUInt8());
assertEquals(0x9c, xis.readUInt8()); assertEquals(0x9c, xis.readUInt8());
assertEquals(0, 0x789c % 31); assertEquals(0, 0x789c % 31);
} finally {
xis.close();
} }
// Verify we can read it. // Verify we can read it.

130
org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/UnpackedObjectTest.java

@ -130,15 +130,15 @@ public class UnpackedObjectTest extends LocalDiskRepositoryTestCase {
assertFalse("is not large", ol.isLarge()); assertFalse("is not large", ol.isLarge());
assertTrue("same content", Arrays.equals(data, ol.getCachedBytes())); assertTrue("same content", Arrays.equals(data, ol.getCachedBytes()));
ObjectStream in = ol.openStream(); try (ObjectStream in = ol.openStream()) {
assertNotNull("have stream", in); assertNotNull("have stream", in);
assertEquals(type, in.getType()); assertEquals(type, in.getType());
assertEquals(data.length, in.getSize()); assertEquals(data.length, in.getSize());
byte[] data2 = new byte[data.length]; byte[] data2 = new byte[data.length];
IO.readFully(in, data2, 0, data.length); IO.readFully(in, data2, 0, data.length);
assertTrue("same content", Arrays.equals(data2, data)); assertTrue("same content", Arrays.equals(data2, data));
assertEquals("stream at EOF", -1, in.read()); assertEquals("stream at EOF", -1, in.read());
in.close(); }
} }
@Test @Test
@ -150,11 +150,8 @@ public class UnpackedObjectTest extends LocalDiskRepositoryTestCase {
ObjectLoader ol; ObjectLoader ol;
{ {
FileInputStream fs = new FileInputStream(path(id)); try (FileInputStream fs = new FileInputStream(path(id))) {
try {
ol = UnpackedObject.open(fs, path(id), id, wc); ol = UnpackedObject.open(fs, path(id), id, wc);
} finally {
fs.close();
} }
} }
@ -171,15 +168,15 @@ public class UnpackedObjectTest extends LocalDiskRepositoryTestCase {
.getMessage()); .getMessage());
} }
ObjectStream in = ol.openStream(); try (ObjectStream in = ol.openStream()) {
assertNotNull("have stream", in); assertNotNull("have stream", in);
assertEquals(type, in.getType()); assertEquals(type, in.getType());
assertEquals(data.length, in.getSize()); assertEquals(data.length, in.getSize());
byte[] data2 = new byte[data.length]; byte[] data2 = new byte[data.length];
IO.readFully(in, data2, 0, data.length); IO.readFully(in, data2, 0, data.length);
assertTrue("same content", Arrays.equals(data2, data)); assertTrue("same content", Arrays.equals(data2, data));
assertEquals("stream at EOF", -1, in.read()); assertEquals("stream at EOF", -1, in.read());
in.close(); }
} }
@Test @Test
@ -316,23 +313,13 @@ public class UnpackedObjectTest extends LocalDiskRepositoryTestCase {
write(id, gz); write(id, gz);
ObjectLoader ol; ObjectLoader ol;
{ try (FileInputStream fs = new FileInputStream(path(id))) {
FileInputStream fs = new FileInputStream(path(id)); ol = UnpackedObject.open(fs, path(id), id, wc);
try {
ol = UnpackedObject.open(fs, path(id), id, wc);
} finally {
fs.close();
}
} }
try { byte[] tmp = new byte[data.length];
byte[] tmp = new byte[data.length]; try (InputStream in = ol.openStream()) {
InputStream in = ol.openStream(); IO.readFully(in, tmp, 0, tmp.length);
try {
IO.readFully(in, tmp, 0, tmp.length);
} finally {
in.close();
}
fail("Did not throw CorruptObjectException"); fail("Did not throw CorruptObjectException");
} catch (CorruptObjectException coe) { } catch (CorruptObjectException coe) {
assertEquals(MessageFormat.format(JGitText.get().objectIsCorrupt, assertEquals(MessageFormat.format(JGitText.get().objectIsCorrupt,
@ -354,16 +341,12 @@ public class UnpackedObjectTest extends LocalDiskRepositoryTestCase {
write(id, tr); write(id, tr);
ObjectLoader ol; ObjectLoader ol;
{ try (FileInputStream fs = new FileInputStream(path(id))) {
FileInputStream fs = new FileInputStream(path(id)); ol = UnpackedObject.open(fs, path(id), id, wc);
try {
ol = UnpackedObject.open(fs, path(id), id, wc);
} finally {
fs.close();
}
} }
byte[] tmp = new byte[data.length]; byte[] tmp = new byte[data.length];
@SuppressWarnings("resource") // We are testing that the close() method throws
InputStream in = ol.openStream(); InputStream in = ol.openStream();
IO.readFully(in, tmp, 0, tmp.length); IO.readFully(in, tmp, 0, tmp.length);
try { try {
@ -389,16 +372,12 @@ public class UnpackedObjectTest extends LocalDiskRepositoryTestCase {
write(id, tr); write(id, tr);
ObjectLoader ol; ObjectLoader ol;
{ try (FileInputStream fs = new FileInputStream(path(id))) {
FileInputStream fs = new FileInputStream(path(id)); ol = UnpackedObject.open(fs, path(id), id, wc);
try {
ol = UnpackedObject.open(fs, path(id), id, wc);
} finally {
fs.close();
}
} }
byte[] tmp = new byte[data.length]; byte[] tmp = new byte[data.length];
@SuppressWarnings("resource") // We are testing that the close() method throws
InputStream in = ol.openStream(); InputStream in = ol.openStream();
IO.readFully(in, tmp, 0, tmp.length); IO.readFully(in, tmp, 0, tmp.length);
try { try {
@ -426,14 +405,15 @@ public class UnpackedObjectTest extends LocalDiskRepositoryTestCase {
assertFalse("is not large", ol.isLarge()); assertFalse("is not large", ol.isLarge());
assertTrue("same content", Arrays.equals(data, ol.getCachedBytes())); assertTrue("same content", Arrays.equals(data, ol.getCachedBytes()));
ObjectStream in = ol.openStream(); try (ObjectStream in = ol.openStream()) {
assertNotNull("have stream", in); assertNotNull("have stream", in);
assertEquals(type, in.getType()); assertEquals(type, in.getType());
assertEquals(data.length, in.getSize()); assertEquals(data.length, in.getSize());
byte[] data2 = new byte[data.length]; byte[] data2 = new byte[data.length];
IO.readFully(in, data2, 0, data.length); IO.readFully(in, data2, 0, data.length);
assertTrue("same content", Arrays.equals(data, ol.getCachedBytes())); assertTrue("same content",
in.close(); Arrays.equals(data, ol.getCachedBytes()));
}
} }
@Test @Test
@ -444,13 +424,8 @@ public class UnpackedObjectTest extends LocalDiskRepositoryTestCase {
write(id, compressPackFormat(type, data)); write(id, compressPackFormat(type, data));
ObjectLoader ol; ObjectLoader ol;
{ try (FileInputStream fs = new FileInputStream(path(id))) {
FileInputStream fs = new FileInputStream(path(id)); ol = UnpackedObject.open(fs, path(id), id, wc);
try {
ol = UnpackedObject.open(fs, path(id), id, wc);
} finally {
fs.close();
}
} }
assertNotNull("created loader", ol); assertNotNull("created loader", ol);
@ -466,15 +441,15 @@ public class UnpackedObjectTest extends LocalDiskRepositoryTestCase {
.getMessage()); .getMessage());
} }
ObjectStream in = ol.openStream(); try (ObjectStream in = ol.openStream()) {
assertNotNull("have stream", in); assertNotNull("have stream", in);
assertEquals(type, in.getType()); assertEquals(type, in.getType());
assertEquals(data.length, in.getSize()); assertEquals(data.length, in.getSize());
byte[] data2 = new byte[data.length]; byte[] data2 = new byte[data.length];
IO.readFully(in, data2, 0, data.length); IO.readFully(in, data2, 0, data.length);
assertTrue("same content", Arrays.equals(data2, data)); assertTrue("same content", Arrays.equals(data2, data));
assertEquals("stream at EOF", -1, in.read()); assertEquals("stream at EOF", -1, in.read());
in.close(); }
} }
@Test @Test
@ -573,11 +548,8 @@ public class UnpackedObjectTest extends LocalDiskRepositoryTestCase {
private void write(ObjectId id, byte[] data) throws IOException { private void write(ObjectId id, byte[] data) throws IOException {
File path = path(id); File path = path(id);
FileUtils.mkdirs(path.getParentFile()); FileUtils.mkdirs(path.getParentFile());
FileOutputStream out = new FileOutputStream(path); try (FileOutputStream out = new FileOutputStream(path)) {
try {
out.write(data); out.write(data);
} finally {
out.close();
} }
} }

7
org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/WindowCacheGetTest.java

@ -74,11 +74,10 @@ public class WindowCacheGetTest extends SampleDataRepositoryTestCase {
super.setUp(); super.setUp();
toLoad = new ArrayList<>(); toLoad = new ArrayList<>();
final BufferedReader br = new BufferedReader(new InputStreamReader( try (BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(JGitTestUtil new FileInputStream(JGitTestUtil
.getTestResourceFile("all_packed_objects.txt")), .getTestResourceFile("all_packed_objects.txt")),
Constants.CHARSET)); Constants.CHARSET))) {
try {
String line; String line;
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null) {
final String[] parts = line.split(" {1,}"); final String[] parts = line.split(" {1,}");
@ -90,8 +89,6 @@ public class WindowCacheGetTest extends SampleDataRepositoryTestCase {
// parts[4] is the offset in the pack // parts[4] is the offset in the pack
toLoad.add(o); toLoad.add(o);
} }
} finally {
br.close();
} }
assertEquals(96, toLoad.size()); assertEquals(96, toLoad.size());
} }

5
org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/RacyGitTests.java

@ -176,12 +176,9 @@ public class RacyGitTests extends RepositoryTestCase {
private File addToWorkDir(String path, String content) throws IOException { private File addToWorkDir(String path, String content) throws IOException {
File f = new File(db.getWorkTree(), path); File f = new File(db.getWorkTree(), path);
FileOutputStream fos = new FileOutputStream(f); try (FileOutputStream fos = new FileOutputStream(f)) {
try {
fos.write(content.getBytes(Constants.CHARACTER_ENCODING)); fos.write(content.getBytes(Constants.CHARACTER_ENCODING));
return f; return f;
} finally {
fos.close();
} }
} }
} }

10
org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/RefTest.java

@ -253,11 +253,11 @@ public class RefTest extends SampleDataRepositoryTestCase {
InterruptedException { InterruptedException {
Ref ref = db.exactRef("refs/heads/master"); Ref ref = db.exactRef("refs/heads/master");
assertEquals(Storage.PACKED, ref.getStorage()); assertEquals(Storage.PACKED, ref.getStorage());
FileOutputStream os = new FileOutputStream(new File(db.getDirectory(), try (FileOutputStream os = new FileOutputStream(
"refs/heads/master")); new File(db.getDirectory(), "refs/heads/master"))) {
os.write(ref.getObjectId().name().getBytes()); os.write(ref.getObjectId().name().getBytes());
os.write('\n'); os.write('\n');
os.close(); }
ref = db.exactRef("refs/heads/master"); ref = db.exactRef("refs/heads/master");
assertEquals(Storage.LOOSE, ref.getStorage()); assertEquals(Storage.LOOSE, ref.getStorage());

35
org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/RepositoryCacheTest.java

@ -94,24 +94,25 @@ public class RepositoryCacheTest extends RepositoryTestCase {
@Test @Test
public void testFileKeyOpenExisting() throws IOException { public void testFileKeyOpenExisting() throws IOException {
Repository r; try (Repository r = new FileKey(db.getDirectory(), db.getFS())
.open(true)) {
r = new FileKey(db.getDirectory(), db.getFS()).open(true); assertNotNull(r);
assertNotNull(r); assertEqualsFile(db.getDirectory(), r.getDirectory());
assertEqualsFile(db.getDirectory(), r.getDirectory()); }
r.close();
r = new FileKey(db.getDirectory(), db.getFS()).open(false); try (Repository r = new FileKey(db.getDirectory(), db.getFS())
assertNotNull(r); .open(false)) {
assertEqualsFile(db.getDirectory(), r.getDirectory()); assertNotNull(r);
r.close(); assertEqualsFile(db.getDirectory(), r.getDirectory());
}
} }
@Test @Test
public void testFileKeyOpenNew() throws IOException { public void testFileKeyOpenNew() throws IOException {
final Repository n = createRepository(true, false); File gitdir;
final File gitdir = n.getDirectory(); try (Repository n = createRepository(true, false)) {
n.close(); gitdir = n.getDirectory();
}
recursiveDelete(gitdir); recursiveDelete(gitdir);
assertFalse(gitdir.exists()); assertFalse(gitdir.exists());
@ -143,6 +144,7 @@ public class RepositoryCacheTest extends RepositoryTestCase {
@Test @Test
public void testCacheOpen() throws Exception { public void testCacheOpen() throws Exception {
final FileKey loc = FileKey.exact(db.getDirectory(), db.getFS()); final FileKey loc = FileKey.exact(db.getDirectory(), db.getFS());
@SuppressWarnings("resource") // We are testing the close() method
final Repository d2 = RepositoryCache.open(loc); final Repository d2 = RepositoryCache.open(loc);
assertNotSame(db, d2); assertNotSame(db, d2);
assertSame(d2, RepositoryCache.open(FileKey.exact(loc.getFile(), db.getFS()))); assertSame(d2, RepositoryCache.open(FileKey.exact(loc.getFile(), db.getFS())));
@ -176,6 +178,7 @@ public class RepositoryCacheTest extends RepositoryTestCase {
@Test @Test
public void testRepositoryUsageCount() throws Exception { public void testRepositoryUsageCount() throws Exception {
FileKey loc = FileKey.exact(db.getDirectory(), db.getFS()); FileKey loc = FileKey.exact(db.getDirectory(), db.getFS());
@SuppressWarnings("resource") // We are testing the close() method
Repository d2 = RepositoryCache.open(loc); Repository d2 = RepositoryCache.open(loc);
assertEquals(1, d2.useCnt.get()); assertEquals(1, d2.useCnt.get());
RepositoryCache.open(FileKey.exact(loc.getFile(), db.getFS())); RepositoryCache.open(FileKey.exact(loc.getFile(), db.getFS()));
@ -189,6 +192,7 @@ public class RepositoryCacheTest extends RepositoryTestCase {
@Test @Test
public void testRepositoryUsageCountWithRegisteredRepository() public void testRepositoryUsageCountWithRegisteredRepository()
throws IOException { throws IOException {
@SuppressWarnings("resource") // We are testing the close() method
Repository repo = createRepository(false, false); Repository repo = createRepository(false, false);
assertEquals(1, repo.useCnt.get()); assertEquals(1, repo.useCnt.get());
RepositoryCache.register(repo); RepositoryCache.register(repo);
@ -200,6 +204,7 @@ public class RepositoryCacheTest extends RepositoryTestCase {
@Test @Test
public void testRepositoryNotUnregisteringWhenClosing() throws Exception { public void testRepositoryNotUnregisteringWhenClosing() throws Exception {
FileKey loc = FileKey.exact(db.getDirectory(), db.getFS()); FileKey loc = FileKey.exact(db.getDirectory(), db.getFS());
@SuppressWarnings("resource") // We are testing the close() method
Repository d2 = RepositoryCache.open(loc); Repository d2 = RepositoryCache.open(loc);
assertEquals(1, d2.useCnt.get()); assertEquals(1, d2.useCnt.get());
assertThat(RepositoryCache.getRegisteredKeys(), assertThat(RepositoryCache.getRegisteredKeys(),
@ -214,6 +219,7 @@ public class RepositoryCacheTest extends RepositoryTestCase {
@Test @Test
public void testRepositoryUnregisteringWhenExpiredAndUsageCountNegative() public void testRepositoryUnregisteringWhenExpiredAndUsageCountNegative()
throws Exception { throws Exception {
@SuppressWarnings("resource") // We are testing the close() method
Repository repoA = createBareRepository(); Repository repoA = createBareRepository();
RepositoryCache.register(repoA); RepositoryCache.register(repoA);
@ -234,7 +240,9 @@ public class RepositoryCacheTest extends RepositoryTestCase {
@Test @Test
public void testRepositoryUnregisteringWhenExpired() throws Exception { public void testRepositoryUnregisteringWhenExpired() throws Exception {
@SuppressWarnings("resource") // We are testing the close() method
Repository repoA = createRepository(true, false); Repository repoA = createRepository(true, false);
@SuppressWarnings("resource") // We are testing the close() method
Repository repoB = createRepository(true, false); Repository repoB = createRepository(true, false);
Repository repoC = createBareRepository(); Repository repoC = createBareRepository();
RepositoryCache.register(repoA); RepositoryCache.register(repoA);
@ -268,6 +276,7 @@ public class RepositoryCacheTest extends RepositoryTestCase {
@Test @Test
public void testReconfigure() throws InterruptedException, IOException { public void testReconfigure() throws InterruptedException, IOException {
@SuppressWarnings("resource") // We are testing the close() method
Repository repo = createRepository(false, false); Repository repo = createRepository(false, false);
RepositoryCache.register(repo); RepositoryCache.register(repo);
assertTrue(RepositoryCache.isCached(repo)); assertTrue(RepositoryCache.isCached(repo));

7
org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/SquashCommitMsgTest.java

@ -66,12 +66,9 @@ public class SquashCommitMsgTest extends RepositoryTestCase {
db.writeSquashCommitMsg(null); db.writeSquashCommitMsg(null);
assertEquals(db.readSquashCommitMsg(), null); assertEquals(db.readSquashCommitMsg(), null);
assertFalse(new File(db.getDirectory(), Constants.SQUASH_MSG).exists()); assertFalse(new File(db.getDirectory(), Constants.SQUASH_MSG).exists());
FileOutputStream fos = new FileOutputStream(new File(db.getDirectory(), try (FileOutputStream fos = new FileOutputStream(
Constants.SQUASH_MSG)); new File(db.getDirectory(), Constants.SQUASH_MSG))) {
try {
fos.write(squashMsg.getBytes(Constants.CHARACTER_ENCODING)); fos.write(squashMsg.getBytes(Constants.CHARACTER_ENCODING));
} finally {
fos.close();
} }
assertEquals(db.readSquashCommitMsg(), squashMsg); assertEquals(db.readSquashCommitMsg(), squashMsg);
} }

26
org.eclipse.jgit.test/tst/org/eclipse/jgit/merge/ResolveMergerTest.java

@ -1033,19 +1033,21 @@ public class ResolveMergerTest extends RepositoryTestCase {
git.commit().setMessage("added c.txt").call(); git.commit().setMessage("added c.txt").call();
// Get a handle to the the file so on windows it can't be deleted. // Get a handle to the the file so on windows it can't be deleted.
FileInputStream fis = new FileInputStream(new File(db.getWorkTree(), try (FileInputStream fis = new FileInputStream(
"b.txt")); new File(db.getWorkTree(), "b.txt"))) {
MergeResult mergeRes = git.merge().setStrategy(strategy) MergeResult mergeRes = git.merge().setStrategy(strategy)
.include(masterCommit).call(); .include(masterCommit).call();
if (mergeRes.getMergeStatus().equals(MergeStatus.FAILED)) { if (mergeRes.getMergeStatus().equals(MergeStatus.FAILED)) {
// probably windows // probably windows
assertEquals(1, mergeRes.getFailingPaths().size()); assertEquals(1, mergeRes.getFailingPaths().size());
assertEquals(MergeFailureReason.COULD_NOT_DELETE, mergeRes assertEquals(MergeFailureReason.COULD_NOT_DELETE,
.getFailingPaths().get("b.txt")); 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 @Theory

13
org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/PatchCcErrorTest.java

@ -96,17 +96,14 @@ public class PatchCcErrorTest {
private Patch parseTestPatchFile() throws IOException { private Patch parseTestPatchFile() throws IOException {
final String patchFile = JGitTestUtil.getName() + ".patch"; final String patchFile = JGitTestUtil.getName() + ".patch";
final InputStream in = getClass().getResourceAsStream(patchFile); try (InputStream in = getClass().getResourceAsStream(patchFile)) {
if (in == null) { if (in == null) {
fail("No " + patchFile + " test vector"); fail("No " + patchFile + " test vector");
return null; // Never happens return null; // Never happens
} }
try {
final Patch p = new Patch(); final Patch p = new Patch();
p.parse(in); p.parse(in);
return p; return p;
} finally {
in.close();
} }
} }

13
org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/PatchCcTest.java

@ -199,17 +199,14 @@ public class PatchCcTest {
private Patch parseTestPatchFile() throws IOException { private Patch parseTestPatchFile() throws IOException {
final String patchFile = JGitTestUtil.getName() + ".patch"; final String patchFile = JGitTestUtil.getName() + ".patch";
final InputStream in = getClass().getResourceAsStream(patchFile); try (InputStream in = getClass().getResourceAsStream(patchFile)) {
if (in == null) { if (in == null) {
fail("No " + patchFile + " test vector"); fail("No " + patchFile + " test vector");
return null; // Never happens return null; // Never happens
} }
try {
final Patch p = new Patch(); final Patch p = new Patch();
p.parse(in); p.parse(in);
return p; return p;
} finally {
in.close();
} }
} }
} }

13
org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/PatchErrorTest.java

@ -177,17 +177,14 @@ public class PatchErrorTest {
private Patch parseTestPatchFile() throws IOException { private Patch parseTestPatchFile() throws IOException {
final String patchFile = JGitTestUtil.getName() + ".patch"; final String patchFile = JGitTestUtil.getName() + ".patch";
final InputStream in = getClass().getResourceAsStream(patchFile); try (InputStream in = getClass().getResourceAsStream(patchFile)) {
if (in == null) { if (in == null) {
fail("No " + patchFile + " test vector"); fail("No " + patchFile + " test vector");
return null; // Never happens return null; // Never happens
} }
try {
final Patch p = new Patch(); final Patch p = new Patch();
p.parse(in); p.parse(in);
return p; return p;
} finally {
in.close();
} }
} }
} }

13
org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/PatchTest.java

@ -357,17 +357,14 @@ public class PatchTest {
private Patch parseTestPatchFile() throws IOException { private Patch parseTestPatchFile() throws IOException {
final String patchFile = JGitTestUtil.getName() + ".patch"; final String patchFile = JGitTestUtil.getName() + ".patch";
final InputStream in = getClass().getResourceAsStream(patchFile); try (InputStream in = getClass().getResourceAsStream(patchFile)) {
if (in == null) { if (in == null) {
fail("No " + patchFile + " test vector"); fail("No " + patchFile + " test vector");
return null; // Never happens return null; // Never happens
} }
try {
final Patch p = new Patch(); final Patch p = new Patch();
p.parse(in); p.parse(in);
return p; return p;
} finally {
in.close();
} }
} }
} }

35
org.eclipse.jgit.test/tst/org/eclipse/jgit/submodule/SubmoduleAddTest.java

@ -129,10 +129,11 @@ public class SubmoduleAddTest extends RepositoryTestCase {
command.setPath(path); command.setPath(path);
String uri = db.getDirectory().toURI().toString(); String uri = db.getDirectory().toURI().toString();
command.setURI(uri); command.setURI(uri);
Repository repo = command.call(); ObjectId subCommit;
assertNotNull(repo); try (Repository repo = command.call()) {
ObjectId subCommit = repo.resolve(Constants.HEAD); assertNotNull(repo);
repo.close(); subCommit = repo.resolve(Constants.HEAD);
}
SubmoduleWalk generator = SubmoduleWalk.forIndex(db); SubmoduleWalk generator = SubmoduleWalk.forIndex(db);
assertTrue(generator.next()); assertTrue(generator.next());
@ -141,10 +142,10 @@ public class SubmoduleAddTest extends RepositoryTestCase {
assertEquals(uri, generator.getModulesUrl()); assertEquals(uri, generator.getModulesUrl());
assertEquals(path, generator.getModulesPath()); assertEquals(path, generator.getModulesPath());
assertEquals(uri, generator.getConfigUrl()); assertEquals(uri, generator.getConfigUrl());
Repository subModRepo = generator.getRepository(); try (Repository subModRepo = generator.getRepository()) {
assertNotNull(subModRepo); assertNotNull(subModRepo);
assertEquals(subCommit, commit); assertEquals(subCommit, commit);
subModRepo.close(); }
Status status = Git.wrap(db).status().call(); Status status = Git.wrap(db).status().call();
assertTrue(status.getAdded().contains(Constants.DOT_GIT_MODULES)); assertTrue(status.getAdded().contains(Constants.DOT_GIT_MODULES));
@ -209,16 +210,14 @@ public class SubmoduleAddTest extends RepositoryTestCase {
fullUri = fullUri.replace('\\', '/'); fullUri = fullUri.replace('\\', '/');
} }
assertEquals(fullUri, generator.getConfigUrl()); assertEquals(fullUri, generator.getConfigUrl());
Repository subModRepo = generator.getRepository(); try (Repository subModRepo = generator.getRepository()) {
assertNotNull(subModRepo); assertNotNull(subModRepo);
assertEquals( assertEquals(fullUri,
fullUri, subModRepo.getConfig().getString(
subModRepo ConfigConstants.CONFIG_REMOTE_SECTION,
.getConfig() Constants.DEFAULT_REMOTE_NAME,
.getString(ConfigConstants.CONFIG_REMOTE_SECTION, ConfigConstants.CONFIG_KEY_URL));
Constants.DEFAULT_REMOTE_NAME, }
ConfigConstants.CONFIG_KEY_URL));
subModRepo.close();
assertEquals(commit, repo.resolve(Constants.HEAD)); assertEquals(commit, repo.resolve(Constants.HEAD));
Status status = Git.wrap(db).status().call(); Status status = Git.wrap(db).status().call();

28
org.eclipse.jgit.test/tst/org/eclipse/jgit/submodule/SubmoduleSyncTest.java

@ -135,12 +135,14 @@ public class SubmoduleSyncTest extends RepositoryTestCase {
generator = SubmoduleWalk.forIndex(db); generator = SubmoduleWalk.forIndex(db);
assertTrue(generator.next()); assertTrue(generator.next());
assertEquals(url, generator.getConfigUrl()); assertEquals(url, generator.getConfigUrl());
Repository subModRepository = generator.getRepository(); try (Repository subModRepository = generator.getRepository()) {
StoredConfig submoduleConfig = subModRepository.getConfig(); StoredConfig submoduleConfig = subModRepository.getConfig();
subModRepository.close(); assertEquals(url,
assertEquals(url, submoduleConfig.getString( submoduleConfig.getString(
ConfigConstants.CONFIG_REMOTE_SECTION, ConfigConstants.CONFIG_REMOTE_SECTION,
Constants.DEFAULT_REMOTE_NAME, ConfigConstants.CONFIG_KEY_URL)); Constants.DEFAULT_REMOTE_NAME,
ConfigConstants.CONFIG_KEY_URL));
}
} }
@Test @Test
@ -208,11 +210,13 @@ public class SubmoduleSyncTest extends RepositoryTestCase {
generator = SubmoduleWalk.forIndex(db); generator = SubmoduleWalk.forIndex(db);
assertTrue(generator.next()); assertTrue(generator.next());
assertEquals("git://server/sub.git", generator.getConfigUrl()); assertEquals("git://server/sub.git", generator.getConfigUrl());
Repository subModRepository1 = generator.getRepository(); try (Repository subModRepository1 = generator.getRepository()) {
StoredConfig submoduleConfig = subModRepository1.getConfig(); StoredConfig submoduleConfig = subModRepository1.getConfig();
subModRepository1.close(); assertEquals("git://server/sub.git",
assertEquals("git://server/sub.git", submoduleConfig.getString( submoduleConfig.getString(
ConfigConstants.CONFIG_REMOTE_SECTION, ConfigConstants.CONFIG_REMOTE_SECTION,
Constants.DEFAULT_REMOTE_NAME, ConfigConstants.CONFIG_KEY_URL)); Constants.DEFAULT_REMOTE_NAME,
ConfigConstants.CONFIG_KEY_URL));
}
} }
} }

8
org.eclipse.jgit.test/tst/org/eclipse/jgit/submodule/SubmoduleUpdateTest.java

@ -121,10 +121,10 @@ public class SubmoduleUpdateTest extends RepositoryTestCase {
SubmoduleWalk generator = SubmoduleWalk.forIndex(db); SubmoduleWalk generator = SubmoduleWalk.forIndex(db);
assertTrue(generator.next()); assertTrue(generator.next());
Repository subRepo = generator.getRepository(); try (Repository subRepo = generator.getRepository()) {
assertNotNull(subRepo); assertNotNull(subRepo);
assertEquals(commit, subRepo.resolve(Constants.HEAD)); assertEquals(commit, subRepo.resolve(Constants.HEAD));
subRepo.close(); }
} }
@Test @Test

8
org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/NetRCTest.java

@ -74,10 +74,10 @@ public class NetRCTest extends RepositoryTestCase {
} }
private void config(final String data) throws IOException { private void config(final String data) throws IOException {
final OutputStreamWriter fw = new OutputStreamWriter( try (OutputStreamWriter fw = new OutputStreamWriter(
new FileOutputStream(configFile), "UTF-8"); new FileOutputStream(configFile), "UTF-8")) {
fw.write(data); fw.write(data);
fw.close(); }
} }
@Test @Test

10
org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/PackParserTest.java

@ -93,8 +93,7 @@ public class PackParserTest extends RepositoryTestCase {
@Test @Test
public void test1() throws IOException { public void test1() throws IOException {
File packFile = JGitTestUtil.getTestResourceFile("pack-34be9032ac282b11fa9babdc2b2a93ca996c9c2f.pack"); File packFile = JGitTestUtil.getTestResourceFile("pack-34be9032ac282b11fa9babdc2b2a93ca996c9c2f.pack");
final InputStream is = new FileInputStream(packFile); try (InputStream is = new FileInputStream(packFile)) {
try {
ObjectDirectoryPackParser p = (ObjectDirectoryPackParser) index(is); ObjectDirectoryPackParser p = (ObjectDirectoryPackParser) index(is);
p.parse(NullProgressMonitor.INSTANCE); p.parse(NullProgressMonitor.INSTANCE);
PackFile file = p.getPackFile(); PackFile file = p.getPackFile();
@ -107,8 +106,6 @@ public class PackParserTest extends RepositoryTestCase {
assertTrue(file.hasObject(ObjectId.fromString("902d5476fa249b7abc9d84c611577a81381f0327"))); assertTrue(file.hasObject(ObjectId.fromString("902d5476fa249b7abc9d84c611577a81381f0327")));
assertTrue(file.hasObject(ObjectId.fromString("aabf2ffaec9b497f0950352b3e582d73035c2035"))); assertTrue(file.hasObject(ObjectId.fromString("aabf2ffaec9b497f0950352b3e582d73035c2035")));
assertTrue(file.hasObject(ObjectId.fromString("c59759f143fb1fe21c197981df75a7ee00290799"))); assertTrue(file.hasObject(ObjectId.fromString("c59759f143fb1fe21c197981df75a7ee00290799")));
} finally {
is.close();
} }
} }
@ -121,8 +118,7 @@ public class PackParserTest extends RepositoryTestCase {
@Test @Test
public void test2() throws IOException { public void test2() throws IOException {
File packFile = JGitTestUtil.getTestResourceFile("pack-df2982f284bbabb6bdb59ee3fcc6eb0983e20371.pack"); File packFile = JGitTestUtil.getTestResourceFile("pack-df2982f284bbabb6bdb59ee3fcc6eb0983e20371.pack");
final InputStream is = new FileInputStream(packFile); try (InputStream is = new FileInputStream(packFile)) {
try {
ObjectDirectoryPackParser p = (ObjectDirectoryPackParser) index(is); ObjectDirectoryPackParser p = (ObjectDirectoryPackParser) index(is);
p.parse(NullProgressMonitor.INSTANCE); p.parse(NullProgressMonitor.INSTANCE);
PackFile file = p.getPackFile(); PackFile file = p.getPackFile();
@ -140,8 +136,6 @@ public class PackParserTest extends RepositoryTestCase {
assertTrue(file.hasObject(ObjectId.fromString("20a8ade77639491ea0bd667bf95de8abf3a434c8"))); assertTrue(file.hasObject(ObjectId.fromString("20a8ade77639491ea0bd667bf95de8abf3a434c8")));
assertTrue(file.hasObject(ObjectId.fromString("2675188fd86978d5bc4d7211698b2118ae3bf658"))); assertTrue(file.hasObject(ObjectId.fromString("2675188fd86978d5bc4d7211698b2118ae3bf658")));
// and lots more... // and lots more...
} finally {
is.close();
} }
} }

59
org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/WalkEncryptionTest.java

@ -419,12 +419,9 @@ public class WalkEncryptionTest {
URLConnection c = url.openConnection(); URLConnection c = url.openConnection();
c.setConnectTimeout(500); c.setConnectTimeout(500);
c.setReadTimeout(500); c.setReadTimeout(500);
BufferedReader reader = new BufferedReader( try (BufferedReader reader = new BufferedReader(
new InputStreamReader(c.getInputStream())); new InputStreamReader(c.getInputStream()))) {
try {
return reader.readLine(); return reader.readLine();
} finally {
reader.close();
} }
} catch (UnknownHostException | SocketTimeoutException e) { } catch (UnknownHostException | SocketTimeoutException e) {
return "Can't reach http://checkip.amazonaws.com to" return "Can't reach http://checkip.amazonaws.com to"
@ -654,9 +651,9 @@ public class WalkEncryptionTest {
Properties props = Props.discover(); Properties props = Props.discover();
props.put(AmazonS3.Keys.PASSWORD, JGIT_PASS); props.put(AmazonS3.Keys.PASSWORD, JGIT_PASS);
props.put(AmazonS3.Keys.CRYPTO_ALG, algorithm); props.put(AmazonS3.Keys.CRYPTO_ALG, algorithm);
PrintWriter writer = new PrintWriter(JGIT_CONF_FILE); try (PrintWriter writer = new PrintWriter(JGIT_CONF_FILE)) {
props.store(writer, "JGIT S3 connection configuration file."); props.store(writer, "JGIT S3 connection configuration file.");
writer.close(); }
} }
/** /**
@ -668,9 +665,9 @@ public class WalkEncryptionTest {
static void configCreate(Properties source) throws Exception { static void configCreate(Properties source) throws Exception {
Properties target = Props.discover(); Properties target = Props.discover();
target.putAll(source); target.putAll(source);
PrintWriter writer = new PrintWriter(JGIT_CONF_FILE); try (PrintWriter writer = new PrintWriter(JGIT_CONF_FILE)) {
target.store(writer, "JGIT S3 connection configuration file."); target.store(writer, "JGIT S3 connection configuration file.");
writer.close(); }
} }
/** /**
@ -836,10 +833,10 @@ public class WalkEncryptionTest {
{ {
byte[] origin = sourceText.getBytes(charset); byte[] origin = sourceText.getBytes(charset);
ByteArrayOutputStream target = new ByteArrayOutputStream(); ByteArrayOutputStream target = new ByteArrayOutputStream();
OutputStream source = crypto.encrypt(target); try (OutputStream source = crypto.encrypt(target)) {
source.write(origin); source.write(origin);
source.flush(); source.flush();
source.close(); }
cipherText = target.toByteArray(); cipherText = target.toByteArray();
} }
{ {
@ -1074,10 +1071,10 @@ public class WalkEncryptionTest {
remoteConfig.update(config); remoteConfig.update(config);
config.save(); config.save();
Git git = Git.open(dirOne); try (Git git = Git.open(dirOne)) {
git.checkout().setName("master").call(); git.checkout().setName("master").call();
git.push().setRemote(remote).setRefSpecs(specs).call(); git.push().setRemote(remote).setRefSpecs(specs).call();
git.close(); }
File fileStatic = new File(dirOne, nameStatic); File fileStatic = new File(dirOne, nameStatic);
assertTrue("Provided by setup", fileStatic.exists()); assertTrue("Provided by setup", fileStatic.exists());
@ -1089,11 +1086,11 @@ public class WalkEncryptionTest {
File fileStatic = new File(dirTwo, nameStatic); File fileStatic = new File(dirTwo, nameStatic);
assertFalse("Not Provided by setup", fileStatic.exists()); assertFalse("Not Provided by setup", fileStatic.exists());
Git git = Git.cloneRepository().setURI(uri).setDirectory(dirTwo) try (Git git = Git.cloneRepository().setURI(uri)
.call(); .setDirectory(dirTwo).call()) {
git.close(); assertTrue("Provided by clone", fileStatic.exists());
}
assertTrue("Provided by clone", fileStatic.exists());
} }
{ // Verify static file content. { // Verify static file content.
@ -1111,11 +1108,11 @@ public class WalkEncryptionTest {
assertTrue("Provided by create", fileDynamic.exists()); assertTrue("Provided by create", fileDynamic.exists());
assertTrue("Need content to encrypt", fileDynamic.length() > 0); assertTrue("Need content to encrypt", fileDynamic.length() > 0);
Git git = Git.open(dirOne); try (Git git = Git.open(dirOne)) {
git.add().addFilepattern(nameDynamic).call(); git.add().addFilepattern(nameDynamic).call();
git.commit().setMessage(nameDynamic).call(); git.commit().setMessage(nameDynamic).call();
git.push().setRemote(remote).setRefSpecs(specs).call(); git.push().setRemote(remote).setRefSpecs(specs).call();
git.close(); }
} }
@ -1124,9 +1121,9 @@ public class WalkEncryptionTest {
File fileDynamic = new File(dirTwo, nameDynamic); File fileDynamic = new File(dirTwo, nameDynamic);
assertFalse("Not Provided by setup", fileDynamic.exists()); assertFalse("Not Provided by setup", fileDynamic.exists());
Git git = Git.open(dirTwo); try (Git git = Git.open(dirTwo)) {
git.pull().call(); git.pull().call();
git.close(); }
assertTrue("Provided by pull", fileDynamic.exists()); assertTrue("Provided by pull", fileDynamic.exists());
} }

13
org.eclipse.jgit.test/tst/org/eclipse/jgit/treewalk/filter/NotTreeFilterTest.java

@ -57,12 +57,13 @@ import org.junit.Test;
public class NotTreeFilterTest extends RepositoryTestCase { public class NotTreeFilterTest extends RepositoryTestCase {
@Test @Test
public void testWrap() throws Exception { public void testWrap() throws Exception {
final TreeWalk tw = new TreeWalk(db); try (TreeWalk tw = new TreeWalk(db)) {
final TreeFilter a = TreeFilter.ALL; final TreeFilter a = TreeFilter.ALL;
final TreeFilter n = NotTreeFilter.create(a); final TreeFilter n = NotTreeFilter.create(a);
assertNotNull(n); assertNotNull(n);
assertTrue(a.include(tw)); assertTrue(a.include(tw));
assertFalse(n.include(tw)); assertFalse(n.include(tw));
}
} }
@Test @Test

55
org.eclipse.jgit.test/tst/org/eclipse/jgit/util/TemporaryBufferTest.java

@ -87,10 +87,8 @@ public class TemporaryBufferTest {
assertEquals(1, r.length); assertEquals(1, r.length);
assertEquals(test, r[0]); assertEquals(test, r[0]);
} }
{ try (ByteArrayOutputStream o = new ByteArrayOutputStream()) {
final ByteArrayOutputStream o = new ByteArrayOutputStream();
b.writeTo(o, null); b.writeTo(o, null);
o.close();
final byte[] r = o.toByteArray(); final byte[] r = o.toByteArray();
assertEquals(1, r.length); assertEquals(1, r.length);
assertEquals(test, r[0]); assertEquals(test, r[0]);
@ -118,10 +116,8 @@ public class TemporaryBufferTest {
assertEquals(test.length, r.length); assertEquals(test.length, r.length);
assertArrayEquals(test, r); assertArrayEquals(test, r);
} }
{ try (ByteArrayOutputStream o = new ByteArrayOutputStream()) {
final ByteArrayOutputStream o = new ByteArrayOutputStream();
b.writeTo(o, null); b.writeTo(o, null);
o.close();
final byte[] r = o.toByteArray(); final byte[] r = o.toByteArray();
assertEquals(test.length, r.length); assertEquals(test.length, r.length);
assertArrayEquals(test, r); assertArrayEquals(test, r);
@ -149,10 +145,8 @@ public class TemporaryBufferTest {
assertEquals(test.length, r.length); assertEquals(test.length, r.length);
assertArrayEquals(test, r); assertArrayEquals(test, r);
} }
{ try (ByteArrayOutputStream o = new ByteArrayOutputStream()) {
final ByteArrayOutputStream o = new ByteArrayOutputStream();
b.writeTo(o, null); b.writeTo(o, null);
o.close();
final byte[] r = o.toByteArray(); final byte[] r = o.toByteArray();
assertEquals(test.length, r.length); assertEquals(test.length, r.length);
assertArrayEquals(test, r); assertArrayEquals(test, r);
@ -178,10 +172,8 @@ public class TemporaryBufferTest {
assertEquals(test.length, r.length); assertEquals(test.length, r.length);
assertArrayEquals(test, r); assertArrayEquals(test, r);
} }
{ try (ByteArrayOutputStream o = new ByteArrayOutputStream()) {
final ByteArrayOutputStream o = new ByteArrayOutputStream();
b.writeTo(o, null); b.writeTo(o, null);
o.close();
final byte[] r = o.toByteArray(); final byte[] r = o.toByteArray();
assertEquals(test.length, r.length); assertEquals(test.length, r.length);
assertArrayEquals(test, r); assertArrayEquals(test, r);
@ -208,10 +200,8 @@ public class TemporaryBufferTest {
assertEquals(test.length, r.length); assertEquals(test.length, r.length);
assertArrayEquals(test, r); assertArrayEquals(test, r);
} }
{ try (ByteArrayOutputStream o = new ByteArrayOutputStream()) {
final ByteArrayOutputStream o = new ByteArrayOutputStream();
b.writeTo(o, null); b.writeTo(o, null);
o.close();
final byte[] r = o.toByteArray(); final byte[] r = o.toByteArray();
assertEquals(test.length, r.length); assertEquals(test.length, r.length);
assertArrayEquals(test, r); assertArrayEquals(test, r);
@ -236,10 +226,8 @@ public class TemporaryBufferTest {
assertEquals(test.length, r.length); assertEquals(test.length, r.length);
assertArrayEquals(test, r); assertArrayEquals(test, r);
} }
{ try (ByteArrayOutputStream o = new ByteArrayOutputStream()) {
final ByteArrayOutputStream o = new ByteArrayOutputStream();
b.writeTo(o, null); b.writeTo(o, null);
o.close();
final byte[] r = o.toByteArray(); final byte[] r = o.toByteArray();
assertEquals(test.length, r.length); assertEquals(test.length, r.length);
assertArrayEquals(test, r); assertArrayEquals(test, r);
@ -253,14 +241,13 @@ public class TemporaryBufferTest {
public void testInCoreInputStream() throws IOException { public void testInCoreInputStream() throws IOException {
final int cnt = 256; final int cnt = 256;
final byte[] test = new TestRng(getName()).nextBytes(cnt); final byte[] test = new TestRng(getName()).nextBytes(cnt);
final TemporaryBuffer.Heap b = new TemporaryBuffer.Heap(cnt + 4); try (final TemporaryBuffer.Heap b = new TemporaryBuffer.Heap(cnt + 4)) {
b.write(test); b.write(test);
b.close(); InputStream in = b.openInputStream();
byte[] act = new byte[cnt];
InputStream in = b.openInputStream(); IO.readFully(in, act, 0, cnt);
byte[] act = new byte[cnt]; assertArrayEquals(test, act);
IO.readFully(in, act, 0, cnt); }
assertArrayEquals(test, act);
} }
@Test @Test
@ -279,10 +266,8 @@ public class TemporaryBufferTest {
assertEquals(test.length, r.length); assertEquals(test.length, r.length);
assertArrayEquals(test, r); assertArrayEquals(test, r);
} }
{ try (ByteArrayOutputStream o = new ByteArrayOutputStream()) {
final ByteArrayOutputStream o = new ByteArrayOutputStream();
b.writeTo(o, null); b.writeTo(o, null);
o.close();
final byte[] r = o.toByteArray(); final byte[] r = o.toByteArray();
assertEquals(test.length, r.length); assertEquals(test.length, r.length);
assertArrayEquals(test, r); assertArrayEquals(test, r);
@ -308,10 +293,8 @@ public class TemporaryBufferTest {
assertEquals(test.length, r.length); assertEquals(test.length, r.length);
assertArrayEquals(test, r); assertArrayEquals(test, r);
} }
{ try (ByteArrayOutputStream o = new ByteArrayOutputStream()) {
final ByteArrayOutputStream o = new ByteArrayOutputStream();
b.writeTo(o, null); b.writeTo(o, null);
o.close();
final byte[] r = o.toByteArray(); final byte[] r = o.toByteArray();
assertEquals(test.length, r.length); assertEquals(test.length, r.length);
assertArrayEquals(test, r); assertArrayEquals(test, r);
@ -340,10 +323,8 @@ public class TemporaryBufferTest {
assertEquals(test.length, r.length); assertEquals(test.length, r.length);
assertArrayEquals(test, r); assertArrayEquals(test, r);
} }
{ try (ByteArrayOutputStream o = new ByteArrayOutputStream()) {
final ByteArrayOutputStream o = new ByteArrayOutputStream();
b.writeTo(o, null); b.writeTo(o, null);
o.close();
final byte[] r = o.toByteArray(); final byte[] r = o.toByteArray();
assertEquals(test.length, r.length); assertEquals(test.length, r.length);
assertArrayEquals(test, r); assertArrayEquals(test, r);
@ -399,10 +380,8 @@ public class TemporaryBufferTest {
assertEquals(expect.length, r.length); assertEquals(expect.length, r.length);
assertArrayEquals(expect, r); assertArrayEquals(expect, r);
} }
{ try (ByteArrayOutputStream o = new ByteArrayOutputStream()) {
final ByteArrayOutputStream o = new ByteArrayOutputStream();
b.writeTo(o, null); b.writeTo(o, null);
o.close();
final byte[] r = o.toByteArray(); final byte[] r = o.toByteArray();
assertEquals(expect.length, r.length); assertEquals(expect.length, r.length);
assertArrayEquals(expect, r); assertArrayEquals(expect, r);

47
org.eclipse.jgit.test/tst/org/eclipse/jgit/util/io/AutoCRLFOutputStreamTest.java

@ -96,32 +96,31 @@ public class AutoCRLFOutputStreamTest {
for (int i = -4; i < 5; ++i) { for (int i = -4; i < 5; ++i) {
int size = Math.abs(i); int size = Math.abs(i);
byte[] buf = new byte[size]; byte[] buf = new byte[size];
InputStream in = new ByteArrayInputStream(inbytes); try (InputStream in = new ByteArrayInputStream(inbytes);
ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream();
OutputStream out = new AutoCRLFOutputStream(bos); OutputStream out = new AutoCRLFOutputStream(bos)) {
if (i > 0) { if (i > 0) {
int n; int n;
while ((n = in.read(buf)) >= 0) { while ((n = in.read(buf)) >= 0) {
out.write(buf, 0, n); 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) { out.flush();
int n; byte[] actualBytes = bos.toByteArray();
while ((n = in.read(buf)) >= 0) { Assert.assertEquals("bufsize=" + size, encode(expectBytes),
byte[] b = new byte[n]; encode(actualBytes));
System.arraycopy(buf, 0, b, 0, n);
out.write(b);
}
} else {
int c;
while ((c = in.read()) != -1)
out.write(c);
} }
out.flush();
in.close();
out.close();
byte[] actualBytes = bos.toByteArray();
Assert.assertEquals("bufsize=" + size, encode(expectBytes),
encode(actualBytes));
} }
} }

48
org.eclipse.jgit.test/tst/org/eclipse/jgit/util/io/UnionInputStreamTest.java

@ -58,13 +58,13 @@ import org.junit.Test;
public class UnionInputStreamTest { public class UnionInputStreamTest {
@Test @Test
public void testEmptyStream() throws IOException { public void testEmptyStream() throws IOException {
final UnionInputStream u = new UnionInputStream(); try (UnionInputStream u = new UnionInputStream()) {
assertTrue(u.isEmpty()); assertTrue(u.isEmpty());
assertEquals(-1, u.read()); assertEquals(-1, u.read());
assertEquals(-1, u.read(new byte[1], 0, 1)); assertEquals(-1, u.read(new byte[1], 0, 1));
assertEquals(0, u.available()); assertEquals(0, u.available());
assertEquals(0, u.skip(1)); assertEquals(0, u.skip(1));
u.close(); }
} }
@Test @Test
@ -211,25 +211,24 @@ public class UnionInputStreamTest {
@Test @Test
public void testCloseDuringClose() throws IOException { public void testCloseDuringClose() throws IOException {
final UnionInputStream u = new UnionInputStream();
final boolean closed[] = new boolean[2]; final boolean closed[] = new boolean[2];
u.add(new ByteArrayInputStream(new byte[] { 1 }) { try (UnionInputStream u = new UnionInputStream()) {
@Override u.add(new ByteArrayInputStream(new byte[] { 1 }) {
public void close() { @Override
closed[0] = true; public void close() {
} closed[0] = true;
}); }
u.add(new ByteArrayInputStream(new byte[] { 2 }) { });
@Override u.add(new ByteArrayInputStream(new byte[] { 2 }) {
public void close() { @Override
closed[1] = true; public void close() {
} closed[1] = true;
}); }
});
assertFalse(closed[0]); assertFalse(closed[0]);
assertFalse(closed[1]); assertFalse(closed[1]);
}
u.close();
assertTrue(closed[0]); assertTrue(closed[0]);
assertTrue(closed[1]); assertTrue(closed[1]);
@ -237,6 +236,7 @@ public class UnionInputStreamTest {
@Test @Test
public void testExceptionDuringClose() { public void testExceptionDuringClose() {
@SuppressWarnings("resource") // We are testing the close() method
final UnionInputStream u = new UnionInputStream(); final UnionInputStream u = new UnionInputStream();
u.add(new ByteArrayInputStream(new byte[] { 1 }) { u.add(new ByteArrayInputStream(new byte[] { 1 }) {
@Override @Override

7
org.eclipse.jgit/src/org/eclipse/jgit/api/CloneCommand.java

@ -386,12 +386,9 @@ public class CloneCommand extends TransportCommand<CloneCommand, Git> {
if (!update.call().isEmpty()) { if (!update.call().isEmpty()) {
SubmoduleWalk walk = SubmoduleWalk.forIndex(clonedRepo); SubmoduleWalk walk = SubmoduleWalk.forIndex(clonedRepo);
while (walk.next()) { while (walk.next()) {
Repository subRepo = walk.getRepository(); try (Repository subRepo = walk.getRepository()) {
if (subRepo != null) { if (subRepo != null) {
try {
cloneSubmodules(subRepo); cloneSubmodules(subRepo);
} finally {
subRepo.close();
} }
} }
} }

10
org.eclipse.jgit/src/org/eclipse/jgit/api/RebaseCommand.java

@ -1734,23 +1734,17 @@ public class RebaseCommand extends GitCommand<RebaseResult> {
String content) String content)
throws IOException { throws IOException {
File file = new File(parentDir, name); File file = new File(parentDir, name);
FileOutputStream fos = new FileOutputStream(file); try (FileOutputStream fos = new FileOutputStream(file)) {
try {
fos.write(content.getBytes(Constants.CHARACTER_ENCODING)); fos.write(content.getBytes(Constants.CHARACTER_ENCODING));
fos.write('\n'); fos.write('\n');
} finally {
fos.close();
} }
} }
private static void appendToFile(File file, String content) private static void appendToFile(File file, String content)
throws IOException { throws IOException {
FileOutputStream fos = new FileOutputStream(file, true); try (FileOutputStream fos = new FileOutputStream(file, true)) {
try {
fos.write(content.getBytes(Constants.CHARACTER_ENCODING)); fos.write(content.getBytes(Constants.CHARACTER_ENCODING));
fos.write('\n'); fos.write('\n');
} finally {
fos.close();
} }
} }
} }

5
org.eclipse.jgit/src/org/eclipse/jgit/api/StashCreateCommand.java

@ -303,12 +303,9 @@ public class StashCreateCommand extends GitCommand<RevCommit> {
entry.setLastModified(wtIter.getEntryLastModified()); entry.setLastModified(wtIter.getEntryLastModified());
entry.setFileMode(wtIter.getEntryFileMode()); entry.setFileMode(wtIter.getEntryFileMode());
long contentLength = wtIter.getEntryContentLength(); long contentLength = wtIter.getEntryContentLength();
InputStream in = wtIter.openEntryStream(); try (InputStream in = wtIter.openEntryStream()) {
try {
entry.setObjectId(inserter.insert( entry.setObjectId(inserter.insert(
Constants.OBJ_BLOB, contentLength, in)); Constants.OBJ_BLOB, contentLength, in));
} finally {
in.close();
} }
if (indexIter == null && headIter == null) if (indexIter == null && headIter == null)

10
org.eclipse.jgit/src/org/eclipse/jgit/diff/SimilarityIndex.java

@ -147,19 +147,13 @@ public class SimilarityIndex {
private void hashLargeObject(ObjectLoader obj) throws IOException, private void hashLargeObject(ObjectLoader obj) throws IOException,
TableFullException { TableFullException {
ObjectStream in1 = obj.openStream();
boolean text; boolean text;
try { try (ObjectStream in1 = obj.openStream()) {
text = !RawText.isBinary(in1); text = !RawText.isBinary(in1);
} finally {
in1.close();
} }
ObjectStream in2 = obj.openStream(); try (ObjectStream in2 = obj.openStream()) {
try {
hash(in2, in2.getSize(), text); hash(in2, in2.getSize(), text);
} finally {
in2.close();
} }
} }

16
org.eclipse.jgit/src/org/eclipse/jgit/gitrepo/RepoProject.java

@ -131,18 +131,10 @@ public class RepoProject implements Comparable<RepoProject> {
File srcFile = new File(repo.getWorkTree(), File srcFile = new File(repo.getWorkTree(),
path + "/" + src); //$NON-NLS-1$ path + "/" + src); //$NON-NLS-1$
File destFile = new File(repo.getWorkTree(), dest); File destFile = new File(repo.getWorkTree(), dest);
FileInputStream input = new FileInputStream(srcFile); try (FileInputStream input = new FileInputStream(srcFile);
try { FileOutputStream output = new FileOutputStream(destFile)) {
FileOutputStream output = new FileOutputStream(destFile); FileChannel channel = input.getChannel();
try { output.getChannel().transferFrom(channel, 0, channel.size());
FileChannel channel = input.getChannel();
output.getChannel().transferFrom(
channel, 0, channel.size());
} finally {
output.close();
}
} finally {
input.close();
} }
} }
} }

4
org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/dfs/DfsPackFile.java

@ -209,8 +209,7 @@ public final class DfsPackFile extends BlockBasedFile {
try { try {
ctx.stats.readIdx++; ctx.stats.readIdx++;
long start = System.nanoTime(); long start = System.nanoTime();
ReadableChannel rc = ctx.db.openFile(desc, INDEX); try (ReadableChannel rc = ctx.db.openFile(desc, INDEX)) {
try {
InputStream in = Channels.newInputStream(rc); InputStream in = Channels.newInputStream(rc);
int wantSize = 8192; int wantSize = 8192;
int bs = rc.blockSize(); int bs = rc.blockSize();
@ -221,7 +220,6 @@ public final class DfsPackFile extends BlockBasedFile {
idx = PackIndex.read(new BufferedInputStream(in, bs)); idx = PackIndex.read(new BufferedInputStream(in, bs));
ctx.stats.readIdxBytes += rc.position(); ctx.stats.readIdxBytes += rc.position();
} finally { } finally {
rc.close();
ctx.stats.readIdxMicros += elapsedMicros(start); ctx.stats.readIdxMicros += elapsedMicros(start);
} }
} catch (EOFException e) { } catch (EOFException e) {

5
org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/file/ObjectDirectoryPackParser.java

@ -429,8 +429,7 @@ public class ObjectDirectoryPackParser extends PackParser {
private void writeIdx() throws IOException { private void writeIdx() throws IOException {
List<PackedObjectInfo> list = getSortedObjectList(null /* by ObjectId */); List<PackedObjectInfo> list = getSortedObjectList(null /* by ObjectId */);
final FileOutputStream os = new FileOutputStream(tmpIdx); try (FileOutputStream os = new FileOutputStream(tmpIdx)) {
try {
final PackIndexWriter iw; final PackIndexWriter iw;
if (indexVersion <= 0) if (indexVersion <= 0)
iw = PackIndexWriter.createOldestPossible(os, list); iw = PackIndexWriter.createOldestPossible(os, list);
@ -438,8 +437,6 @@ public class ObjectDirectoryPackParser extends PackParser {
iw = PackIndexWriter.createVersion(os, indexVersion); iw = PackIndexWriter.createVersion(os, indexVersion);
iw.write(list, packHash); iw.write(list, packHash);
os.getChannel().force(true); os.getChannel().force(true);
} finally {
os.close();
} }
} }

10
org.eclipse.jgit/src/org/eclipse/jgit/lib/ObjectLoader.java

@ -194,8 +194,7 @@ public abstract class ObjectLoader {
if (!isLarge()) if (!isLarge())
return getCachedBytes(); return getCachedBytes();
ObjectStream in = openStream(); try (ObjectStream in = openStream()) {
try {
long sz = in.getSize(); long sz = in.getSize();
if (sizeLimit < sz) if (sizeLimit < sz)
throw new LargeObjectException.ExceedsLimit(sizeLimit, sz); throw new LargeObjectException.ExceedsLimit(sizeLimit, sz);
@ -212,8 +211,6 @@ public abstract class ObjectLoader {
IO.readFully(in, buf, 0, buf.length); IO.readFully(in, buf, 0, buf.length);
return buf; return buf;
} finally {
in.close();
} }
} }
@ -255,8 +252,7 @@ public abstract class ObjectLoader {
public void copyTo(OutputStream out) throws MissingObjectException, public void copyTo(OutputStream out) throws MissingObjectException,
IOException { IOException {
if (isLarge()) { if (isLarge()) {
ObjectStream in = openStream(); try (ObjectStream in = openStream()) {
try {
final long sz = in.getSize(); final long sz = in.getSize();
byte[] tmp = new byte[8192]; byte[] tmp = new byte[8192];
long copied = 0; long copied = 0;
@ -269,8 +265,6 @@ public abstract class ObjectLoader {
} }
if (0 <= in.read()) if (0 <= in.read())
throw new EOFException(); throw new EOFException();
} finally {
in.close();
} }
} else { } else {
out.write(getCachedBytes()); out.write(getCachedBytes());

5
org.eclipse.jgit/src/org/eclipse/jgit/lib/Repository.java

@ -1946,11 +1946,8 @@ public abstract class Repository implements AutoCloseable {
private void writeCommitMsg(File msgFile, String msg) throws IOException { private void writeCommitMsg(File msgFile, String msg) throws IOException {
if (msg != null) { if (msg != null) {
FileOutputStream fos = new FileOutputStream(msgFile); try (FileOutputStream fos = new FileOutputStream(msgFile)) {
try {
fos.write(msg.getBytes(Constants.CHARACTER_ENCODING)); fos.write(msg.getBytes(Constants.CHARACTER_ENCODING));
} finally {
fos.close();
} }
} else { } else {
FileUtils.delete(msgFile, FileUtils.SKIP_MISSING); FileUtils.delete(msgFile, FileUtils.SKIP_MISSING);

12
org.eclipse.jgit/src/org/eclipse/jgit/transport/PackParser.java

@ -1642,17 +1642,17 @@ public abstract class PackParser {
private void inflateAndSkip(final Source src, final long inflatedSize) private void inflateAndSkip(final Source src, final long inflatedSize)
throws IOException { throws IOException {
final InputStream inf = inflate(src, inflatedSize); try (InputStream inf = inflate(src, inflatedSize)) {
IO.skipFully(inf, inflatedSize); IO.skipFully(inf, inflatedSize);
inf.close(); }
} }
private byte[] inflateAndReturn(final Source src, final long inflatedSize) private byte[] inflateAndReturn(final Source src, final long inflatedSize)
throws IOException { throws IOException {
final byte[] dst = new byte[(int) inflatedSize]; final byte[] dst = new byte[(int) inflatedSize];
final InputStream inf = inflate(src, inflatedSize); try (InputStream inf = inflate(src, inflatedSize)) {
IO.readFully(inf, dst, 0, dst.length); IO.readFully(inf, dst, 0, dst.length);
inf.close(); }
return dst; return dst;
} }

5
org.eclipse.jgit/src/org/eclipse/jgit/transport/TransportAmazonS3.java

@ -339,11 +339,8 @@ public class TransportAmazonS3 extends HttpTransport implements WalkTransport {
final String s; final String s;
String ref = ROOT_DIR + rn; String ref = ROOT_DIR + rn;
try { try {
final BufferedReader br = openReader(ref); try (BufferedReader br = openReader(ref)) {
try {
s = br.readLine(); s = br.readLine();
} finally {
br.close();
} }
} catch (FileNotFoundException noRef) { } catch (FileNotFoundException noRef) {
return null; return null;

17
org.eclipse.jgit/src/org/eclipse/jgit/transport/WalkFetchConnection.java

@ -853,17 +853,12 @@ class WalkFetchConnection extends BaseFetchConnection {
pm.beginTask("Get " + idxName.substring(0, 12) + "..idx", //$NON-NLS-1$ //$NON-NLS-2$ pm.beginTask("Get " + idxName.substring(0, 12) + "..idx", //$NON-NLS-1$ //$NON-NLS-2$
s.length < 0 ? ProgressMonitor.UNKNOWN s.length < 0 ? ProgressMonitor.UNKNOWN
: (int) (s.length / 1024)); : (int) (s.length / 1024));
try { try (final FileOutputStream fos = new FileOutputStream(tmpIdx)) {
final FileOutputStream fos = new FileOutputStream(tmpIdx); final byte[] buf = new byte[2048];
try { int cnt;
final byte[] buf = new byte[2048]; while (!pm.isCancelled() && (cnt = s.in.read(buf)) >= 0) {
int cnt; fos.write(buf, 0, cnt);
while (!pm.isCancelled() && (cnt = s.in.read(buf)) >= 0) { pm.update(cnt / 1024);
fos.write(buf, 0, cnt);
pm.update(cnt / 1024);
}
} finally {
fos.close();
} }
} catch (IOException err) { } catch (IOException err) {
FileUtils.delete(tmpIdx); FileUtils.delete(tmpIdx);

15
org.eclipse.jgit/src/org/eclipse/jgit/treewalk/WorkingTreeIterator.java

@ -1280,11 +1280,8 @@ public abstract class WorkingTreeIterator extends AbstractTreeIterator {
IgnoreNode load() throws IOException { IgnoreNode load() throws IOException {
IgnoreNode r = new IgnoreNode(); IgnoreNode r = new IgnoreNode();
InputStream in = entry.openInputStream(); try (InputStream in = entry.openInputStream()) {
try {
r.parse(in); r.parse(in);
} finally {
in.close();
} }
return r.getRules().isEmpty() ? null : r; return r.getRules().isEmpty() ? null : r;
} }
@ -1332,11 +1329,8 @@ public abstract class WorkingTreeIterator extends AbstractTreeIterator {
private static void loadRulesFromFile(IgnoreNode r, File exclude) private static void loadRulesFromFile(IgnoreNode r, File exclude)
throws FileNotFoundException, IOException { throws FileNotFoundException, IOException {
if (FS.DETECTED.exists(exclude)) { if (FS.DETECTED.exists(exclude)) {
FileInputStream in = new FileInputStream(exclude); try (FileInputStream in = new FileInputStream(exclude)) {
try {
r.parse(in); r.parse(in);
} finally {
in.close();
} }
} }
} }
@ -1353,11 +1347,8 @@ public abstract class WorkingTreeIterator extends AbstractTreeIterator {
AttributesNode load() throws IOException { AttributesNode load() throws IOException {
AttributesNode r = new AttributesNode(); AttributesNode r = new AttributesNode();
InputStream in = entry.openInputStream(); try (InputStream in = entry.openInputStream()) {
try {
r.parse(in); r.parse(in);
} finally {
in.close();
} }
return r.getRules().isEmpty() ? null : r; return r.getRules().isEmpty() ? null : r;
} }

10
org.eclipse.jgit/src/org/eclipse/jgit/util/TemporaryBuffer.java

@ -487,11 +487,8 @@ public abstract class TemporaryBuffer extends OutputStream {
if (Integer.MAX_VALUE < len) if (Integer.MAX_VALUE < len)
throw new OutOfMemoryError(JGitText.get().lengthExceedsMaximumArraySize); throw new OutOfMemoryError(JGitText.get().lengthExceedsMaximumArraySize);
final byte[] out = new byte[(int) len]; final byte[] out = new byte[(int) len];
final FileInputStream in = new FileInputStream(onDiskFile); try (FileInputStream in = new FileInputStream(onDiskFile)) {
try {
IO.readFully(in, out, 0, (int) len); IO.readFully(in, out, 0, (int) len);
} finally {
in.close();
} }
return out; return out;
} }
@ -505,16 +502,13 @@ public abstract class TemporaryBuffer extends OutputStream {
} }
if (pm == null) if (pm == null)
pm = NullProgressMonitor.INSTANCE; pm = NullProgressMonitor.INSTANCE;
final FileInputStream in = new FileInputStream(onDiskFile); try (FileInputStream in = new FileInputStream(onDiskFile)) {
try {
int cnt; int cnt;
final byte[] buf = new byte[Block.SZ]; final byte[] buf = new byte[Block.SZ];
while ((cnt = in.read(buf)) >= 0) { while ((cnt = in.read(buf)) >= 0) {
os.write(buf, 0, cnt); os.write(buf, 0, cnt);
pm.update(cnt / 1024); pm.update(cnt / 1024);
} }
} finally {
in.close();
} }
} }

Loading…
Cancel
Save