diff options
Diffstat (limited to 'org.eclipse.jgit.test/tst')
56 files changed, 1201 insertions, 1135 deletions
diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/ArchiveCommandTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/ArchiveCommandTest.java index edab96b971..1300f98d8a 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/ArchiveCommandTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/ArchiveCommandTest.java @@ -229,11 +229,6 @@ public class ArchiveCommandTest extends RepositoryTestCase { } @Override - public void putEntry(MockOutputStream out, String path, FileMode mode, ObjectLoader loader) { - putEntry(out, null, path, mode, loader); - } - - @Override public void putEntry(MockOutputStream out, ObjectId tree, String path, FileMode mode, ObjectLoader loader) { String content = mode != FileMode.TREE ? new String(loader.getBytes()) : null; entries.put(path, content); diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/CommitCommandTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/CommitCommandTest.java index 0dd3749337..3a13aa5a41 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/CommitCommandTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/CommitCommandTest.java @@ -54,7 +54,7 @@ import java.util.Date; import java.util.List; import java.util.TimeZone; -import org.eclipse.jgit.api.errors.EmtpyCommitException; +import org.eclipse.jgit.api.errors.EmptyCommitException; import org.eclipse.jgit.api.errors.WrongRepositoryStateException; import org.eclipse.jgit.diff.DiffEntry; import org.eclipse.jgit.dircache.DirCache; @@ -553,8 +553,8 @@ public class CommitCommandTest extends RepositoryTestCase { git.commit().setAuthor("New Author", "newauthor@example.org") .setMessage("again no change").setAllowEmpty(false) .call(); - fail("Didn't get the expected EmtpyCommitException"); - } catch (EmtpyCommitException e) { + fail("Didn't get the expected EmptyCommitException"); + } catch (EmptyCommitException e) { // expect this exception } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/EolStreamTypeUtilTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/EolStreamTypeUtilTest.java index 1e3a39aad8..bb303cc411 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/EolStreamTypeUtilTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/EolStreamTypeUtilTest.java @@ -42,7 +42,7 @@ package org.eclipse.jgit.api; -import static java.nio.charset.StandardCharsets.UTF_8; +import static org.eclipse.jgit.lib.Constants.CHARSET; import static org.eclipse.jgit.lib.CoreConfig.EolStreamType.AUTO_CRLF; import static org.eclipse.jgit.lib.CoreConfig.EolStreamType.AUTO_LF; import static org.eclipse.jgit.lib.CoreConfig.EolStreamType.DIRECT; @@ -150,8 +150,8 @@ public class EolStreamTypeUtilTest { EolStreamType streamTypeWithBinaryCheck, String output, String expectedConversion) throws Exception { ByteArrayOutputStream b; - byte[] outputBytes = output.getBytes(UTF_8); - byte[] expectedConversionBytes = expectedConversion.getBytes(UTF_8); + byte[] outputBytes = output.getBytes(CHARSET); + byte[] expectedConversionBytes = expectedConversion.getBytes(CHARSET); // test using output text and assuming it was declared TEXT b = new ByteArrayOutputStream(); @@ -277,8 +277,8 @@ public class EolStreamTypeUtilTest { private void testCheckin(EolStreamType streamTypeText, EolStreamType streamTypeWithBinaryCheck, String input, String expectedConversion) throws Exception { - byte[] inputBytes = input.getBytes(UTF_8); - byte[] expectedConversionBytes = expectedConversion.getBytes(UTF_8); + byte[] inputBytes = input.getBytes(CHARSET); + byte[] expectedConversionBytes = expectedConversion.getBytes(CHARSET); // test using input text and assuming it was declared TEXT try (InputStream in = EolStreamTypeUtil.wrapInputStream( diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/FetchCommandTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/FetchCommandTest.java index 83a0564c77..cf1afceae6 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/FetchCommandTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/FetchCommandTest.java @@ -102,6 +102,25 @@ public class FetchCommandTest extends RepositoryTestCase { } @Test + public void testForcedFetch() throws Exception { + remoteGit.commit().setMessage("commit").call(); + remoteGit.commit().setMessage("commit2").call(); + git.fetch().setRemote("test") + .setRefSpecs("refs/heads/master:refs/heads/master").call(); + + remoteGit.commit().setAmend(true).setMessage("amended").call(); + FetchResult res = git.fetch().setRemote("test") + .setRefSpecs("refs/heads/master:refs/heads/master").call(); + assertEquals(RefUpdate.Result.REJECTED, + res.getTrackingRefUpdate("refs/heads/master").getResult()); + res = git.fetch().setRemote("test") + .setRefSpecs("refs/heads/master:refs/heads/master") + .setForceUpdate(true).call(); + assertEquals(RefUpdate.Result.FORCED, + res.getTrackingRefUpdate("refs/heads/master").getResult()); + } + + @Test public void fetchShouldAutoFollowTag() throws Exception { remoteGit.commit().setMessage("commit").call(); Ref tagRef = remoteGit.tag().setName("foo").call(); diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/NotesCommandTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/NotesCommandTest.java index 6e06e9545a..e234aa339c 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/NotesCommandTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/NotesCommandTest.java @@ -42,7 +42,7 @@ */ package org.eclipse.jgit.api; -import static java.nio.charset.StandardCharsets.UTF_8; +import static org.eclipse.jgit.lib.Constants.CHARSET; import static org.junit.Assert.assertEquals; import java.util.List; @@ -88,7 +88,7 @@ public class NotesCommandTest extends RepositoryTestCase { git.notesAdd().setObjectId(commit2).setMessage("data").call(); Note note = git.notesShow().setObjectId(commit2).call(); String content = new String(db.open(note.getData()).getCachedBytes(), - UTF_8); + CHARSET); assertEquals(content, "data"); git.notesRemove().setObjectId(commit2).call(); diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/PullCommandTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/PullCommandTest.java index 9461c42500..0b0e3bf3ea 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/PullCommandTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/PullCommandTest.java @@ -42,7 +42,7 @@ */ package org.eclipse.jgit.api; -import static java.nio.charset.StandardCharsets.UTF_8; +import static org.eclipse.jgit.lib.Constants.CHARSET; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -592,7 +592,7 @@ public class PullCommandTest extends RepositoryTestCase { private static void writeToFile(File actFile, String string) throws IOException { try (FileOutputStream fos = new FileOutputStream(actFile)) { - fos.write(string.getBytes(UTF_8)); + fos.write(string.getBytes(CHARSET)); } } @@ -606,7 +606,7 @@ public class PullCommandTest extends RepositoryTestCase { bos.write(buffer, 0, read); read = fis.read(buffer); } - String content = new String(bos.toByteArray(), UTF_8); + String content = new String(bos.toByteArray(), CHARSET); assertEquals(string, content); } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/PullCommandWithRebaseTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/PullCommandWithRebaseTest.java index 913b4ac434..b349c66cab 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/PullCommandWithRebaseTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/PullCommandWithRebaseTest.java @@ -42,7 +42,7 @@ */ package org.eclipse.jgit.api; -import static java.nio.charset.StandardCharsets.UTF_8; +import static org.eclipse.jgit.lib.Constants.CHARSET; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -396,7 +396,7 @@ public class PullCommandWithRebaseTest extends RepositoryTestCase { private static void writeToFile(File actFile, String string) throws IOException { try (FileOutputStream fos = new FileOutputStream(actFile)) { - fos.write(string.getBytes(UTF_8)); + fos.write(string.getBytes(CHARSET)); } } @@ -410,7 +410,7 @@ public class PullCommandWithRebaseTest extends RepositoryTestCase { bos.write(buffer, 0, read); read = fis.read(buffer); } - String content = new String(bos.toByteArray(), UTF_8); + String content = new String(bos.toByteArray(), CHARSET); assertEquals(string, content); } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/RebaseCommandTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/RebaseCommandTest.java index 2bf91aeed8..96e7091ae1 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/RebaseCommandTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/RebaseCommandTest.java @@ -42,7 +42,7 @@ */ package org.eclipse.jgit.api; -import static java.nio.charset.StandardCharsets.UTF_8; +import static org.eclipse.jgit.lib.Constants.CHARSET; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.MatcherAssert.assertThat; @@ -1464,7 +1464,7 @@ public class RebaseCommandTest extends RepositoryTestCase { assertEquals("GIT_AUTHOR_DATE='@123456789 -0100'", lines[2]); PersonIdent parsedIdent = git.rebase().parseAuthor( - convertedAuthor.getBytes(UTF_8)); + convertedAuthor.getBytes(CHARSET)); assertEquals(ident.getName(), parsedIdent.getName()); assertEquals(ident.getEmailAddress(), parsedIdent.getEmailAddress()); // this is rounded to the last second @@ -1481,7 +1481,7 @@ public class RebaseCommandTest extends RepositoryTestCase { assertEquals("GIT_AUTHOR_DATE='@123456789 +0930'", lines[2]); parsedIdent = git.rebase().parseAuthor( - convertedAuthor.getBytes(UTF_8)); + convertedAuthor.getBytes(CHARSET)); assertEquals(ident.getName(), parsedIdent.getName()); assertEquals(ident.getEmailAddress(), parsedIdent.getEmailAddress()); assertEquals(123456789000L, parsedIdent.getWhen().getTime()); @@ -2104,7 +2104,7 @@ public class RebaseCommandTest extends RepositoryTestCase { int count = 0; File todoFile = getTodoFile(); try (BufferedReader br = new BufferedReader(new InputStreamReader( - new FileInputStream(todoFile), UTF_8))) { + new FileInputStream(todoFile), CHARSET))) { String line = br.readLine(); while (line != null) { int firstBlank = line.indexOf(' '); diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/ResetCommandTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/ResetCommandTest.java index ba51881ffd..8f56a9270e 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/ResetCommandTest.java +++ b/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"); 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 diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/diff/AbstractDiffTestCase.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/diff/AbstractDiffTestCase.java index 0f13a68b25..32f34213ec 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/diff/AbstractDiffTestCase.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/diff/AbstractDiffTestCase.java @@ -43,7 +43,7 @@ package org.eclipse.jgit.diff; -import static java.nio.charset.StandardCharsets.UTF_8; +import static org.eclipse.jgit.lib.Constants.CHARSET; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -240,6 +240,6 @@ public abstract class AbstractDiffTestCase { r.append(text.charAt(i)); r.append('\n'); } - return new RawText(r.toString().getBytes(UTF_8)); + return new RawText(r.toString().getBytes(CHARSET)); } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/diff/RawTextTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/diff/RawTextTest.java index 6ad59b9e56..69e40777cc 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/diff/RawTextTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/diff/RawTextTest.java @@ -44,7 +44,7 @@ package org.eclipse.jgit.diff; -import static java.nio.charset.StandardCharsets.UTF_8; +import static org.eclipse.jgit.lib.Constants.CHARSET; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; @@ -136,8 +136,8 @@ public class RawTextTest { e = c.reduceCommonStartEnd(t("abQxy"), t("abRxy"), e); assertEquals(new Edit(2, 3, 2, 3), e); - RawText a = new RawText("p\na b\nQ\nc d\n".getBytes(UTF_8)); - RawText b = new RawText("p\na b \nR\n c d \n".getBytes(UTF_8)); + RawText a = new RawText("p\na b\nQ\nc d\n".getBytes(CHARSET)); + RawText b = new RawText("p\na b \nR\n c d \n".getBytes(CHARSET)); e = new Edit(0, 4, 0, 4); e = RawTextComparator.WS_IGNORE_ALL.reduceCommonStartEnd(a, b, e); assertEquals(new Edit(2, 3, 2, 3), e); @@ -149,14 +149,14 @@ public class RawTextTest { RawText b; Edit e; - a = new RawText("R\n y\n".getBytes(UTF_8)); - b = new RawText("S\n\n y\n".getBytes(UTF_8)); + a = new RawText("R\n y\n".getBytes(CHARSET)); + b = new RawText("S\n\n y\n".getBytes(CHARSET)); e = new Edit(0, 2, 0, 3); e = RawTextComparator.DEFAULT.reduceCommonStartEnd(a, b, e); assertEquals(new Edit(0, 1, 0, 2), e); - a = new RawText("S\n\n y\n".getBytes(UTF_8)); - b = new RawText("R\n y\n".getBytes(UTF_8)); + a = new RawText("S\n\n y\n".getBytes(CHARSET)); + b = new RawText("R\n y\n".getBytes(CHARSET)); e = new Edit(0, 3, 0, 2); e = RawTextComparator.DEFAULT.reduceCommonStartEnd(a, b, e); assertEquals(new Edit(0, 2, 0, 1), e); @@ -167,8 +167,8 @@ public class RawTextTest { RawText a; RawText b; Edit e; - a = new RawText("start".getBytes(UTF_8)); - b = new RawText("start of line".getBytes(UTF_8)); + a = new RawText("start".getBytes(CHARSET)); + b = new RawText("start of line".getBytes(CHARSET)); e = new Edit(0, 1, 0, 1); e = RawTextComparator.DEFAULT.reduceCommonStartEnd(a, b, e); assertEquals(new Edit(0, 1, 0, 1), e); @@ -179,8 +179,8 @@ public class RawTextTest { RawText a; RawText b; Edit e; - a = new RawText("start".getBytes(UTF_8)); - b = new RawText("start of\nlastline".getBytes(UTF_8)); + a = new RawText("start".getBytes(CHARSET)); + b = new RawText("start of\nlastline".getBytes(CHARSET)); e = new Edit(0, 1, 0, 2); e = RawTextComparator.DEFAULT.reduceCommonStartEnd(a, b, e); assertEquals(new Edit(0, 1, 0, 2), e); @@ -239,6 +239,6 @@ public class RawTextTest { r.append(text.charAt(i)); r.append('\n'); } - return new RawText(r.toString().getBytes(UTF_8)); + return new RawText(r.toString().getBytes(CHARSET)); } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/diff/SimilarityIndexTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/diff/SimilarityIndexTest.java index f168e83284..51a6f8121c 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/diff/SimilarityIndexTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/diff/SimilarityIndexTest.java @@ -43,7 +43,7 @@ package org.eclipse.jgit.diff; -import static java.nio.charset.StandardCharsets.UTF_8; +import static org.eclipse.jgit.lib.Constants.CHARSET; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -82,7 +82,7 @@ public class SimilarityIndexTest { + "A\n" // + "B\n" // + "B\n" // - + "B\n").getBytes(UTF_8); + + "B\n").getBytes(CHARSET); SimilarityIndex si = new SimilarityIndex(); si.hash(new ByteArrayInputStream(in), in.length, false); assertEquals(2, si.size()); @@ -130,12 +130,12 @@ public class SimilarityIndexTest { + "D\r\n" // + "B\r\n"; SimilarityIndex src = new SimilarityIndex(); - byte[] bytes1 = text.getBytes(UTF_8); + byte[] bytes1 = text.getBytes(CHARSET); src.hash(new ByteArrayInputStream(bytes1), bytes1.length, true); src.sort(); SimilarityIndex dst = new SimilarityIndex(); - byte[] bytes2 = text.replace("\r", "").getBytes(UTF_8); + byte[] bytes2 = text.replace("\r", "").getBytes(CHARSET); dst.hash(new ByteArrayInputStream(bytes2), bytes2.length, true); dst.sort(); diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/dircache/DirCacheCGitCompatabilityTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/dircache/DirCacheCGitCompatabilityTest.java index dec17623fc..80d4329858 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/dircache/DirCacheCGitCompatabilityTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/dircache/DirCacheCGitCompatabilityTest.java @@ -43,7 +43,7 @@ package org.eclipse.jgit.dircache; -import static java.nio.charset.StandardCharsets.UTF_8; +import static org.eclipse.jgit.lib.Constants.CHARSET; import static org.eclipse.jgit.junit.Assert.assertEquals; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; @@ -236,7 +236,7 @@ public class DirCacheCGitCompatabilityTest extends LocalDiskRepositoryTestCase { private static Map<String, CGitIndexRecord> readLsFiles() throws Exception { final LinkedHashMap<String, CGitIndexRecord> r = new LinkedHashMap<>(); try (BufferedReader br = new BufferedReader(new InputStreamReader( - new FileInputStream(pathOf("gitgit.lsfiles")), UTF_8))) { + new FileInputStream(pathOf("gitgit.lsfiles")), CHARSET))) { String line; while ((line = br.readLine()) != null) { final CGitIndexRecord cr = new CGitIndexRecord(line); @@ -249,7 +249,7 @@ public class DirCacheCGitCompatabilityTest extends LocalDiskRepositoryTestCase { private static Map<String, CGitLsTreeRecord> readLsTree() throws Exception { final LinkedHashMap<String, CGitLsTreeRecord> r = new LinkedHashMap<>(); try (BufferedReader br = new BufferedReader(new InputStreamReader( - new FileInputStream(pathOf("gitgit.lstree")), UTF_8))) { + new FileInputStream(pathOf("gitgit.lstree")), CHARSET))) { String line; while ((line = br.readLine()) != null) { final CGitLsTreeRecord cr = new CGitLsTreeRecord(line); diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/gitrepo/ManifestParserTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/gitrepo/ManifestParserTest.java index c9673a6882..69a48cc4b5 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/gitrepo/ManifestParserTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/gitrepo/ManifestParserTest.java @@ -42,7 +42,7 @@ */ package org.eclipse.jgit.gitrepo; -import static java.nio.charset.StandardCharsets.UTF_8; +import static org.eclipse.jgit.lib.Constants.CHARSET; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -82,7 +82,7 @@ public class ManifestParserTest { ManifestParser parser = new ManifestParser( null, null, "master", baseUrl, null, null); - parser.read(new ByteArrayInputStream(xmlContent.toString().getBytes(UTF_8))); + parser.read(new ByteArrayInputStream(xmlContent.toString().getBytes(CHARSET))); // Unfiltered projects should have them all. results.clear(); results.add("foo"); @@ -136,7 +136,7 @@ public class ManifestParserTest { baseUrl, null, null); try { parser.read(new ByteArrayInputStream( - xmlContent.toString().getBytes(UTF_8))); + xmlContent.toString().getBytes(CHARSET))); fail("ManifestParser did not throw exception for missing fetch"); } catch (IOException e) { assertTrue(e.getCause() instanceof SAXException); diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/gitrepo/RepoCommandSymlinkTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/gitrepo/RepoCommandSymlinkTest.java index 341cc4f215..548b9033bc 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/gitrepo/RepoCommandSymlinkTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/gitrepo/RepoCommandSymlinkTest.java @@ -119,45 +119,47 @@ public class RepoCommandSymlinkTest extends RepositoryTestCase { .setURI(rootUri).call(); // Clone it File directory = createTempDirectory("testCopyFileBare"); - Repository localDb = Git.cloneRepository().setDirectory(directory) + try (Repository localDb = Git.cloneRepository() + .setDirectory(directory) .setURI(remoteDb.getDirectory().toURI().toString()).call() - .getRepository(); + .getRepository()) { - // The LinkedHello symlink should exist. - File linkedhello = new File(localDb.getWorkTree(), "LinkedHello"); - assertTrue("The LinkedHello file should exist", - localDb.getFS().exists(linkedhello)); - assertTrue("The LinkedHello file should be a symlink", - localDb.getFS().isSymLink(linkedhello)); - assertEquals("foo/hello.txt", - localDb.getFS().readSymLink(linkedhello)); + // The LinkedHello symlink should exist. + File linkedhello = new File(localDb.getWorkTree(), + "LinkedHello"); + assertTrue("The LinkedHello file should exist", + localDb.getFS().exists(linkedhello)); + assertTrue("The LinkedHello file should be a symlink", + localDb.getFS().isSymLink(linkedhello)); + assertEquals("foo/hello.txt", + localDb.getFS().readSymLink(linkedhello)); - // The foo/LinkedHello file should be skipped. - File linkedfoohello = new File(localDb.getWorkTree(), "foo/LinkedHello"); - assertFalse("The foo/LinkedHello file should be skipped", - localDb.getFS().exists(linkedfoohello)); + // The foo/LinkedHello file should be skipped. + File linkedfoohello = new File(localDb.getWorkTree(), + "foo/LinkedHello"); + assertFalse("The foo/LinkedHello file should be skipped", + localDb.getFS().exists(linkedfoohello)); - // The subdir/LinkedHello file should use a relative ../ - File linkedsubdirhello = new File(localDb.getWorkTree(), - "subdir/LinkedHello"); - assertTrue("The subdir/LinkedHello file should exist", - localDb.getFS().exists(linkedsubdirhello)); - assertTrue("The subdir/LinkedHello file should be a symlink", - localDb.getFS().isSymLink(linkedsubdirhello)); - assertEquals("../foo/hello.txt", - localDb.getFS().readSymLink(linkedsubdirhello)); + // The subdir/LinkedHello file should use a relative ../ + File linkedsubdirhello = new File(localDb.getWorkTree(), + "subdir/LinkedHello"); + assertTrue("The subdir/LinkedHello file should exist", + localDb.getFS().exists(linkedsubdirhello)); + assertTrue("The subdir/LinkedHello file should be a symlink", + localDb.getFS().isSymLink(linkedsubdirhello)); + assertEquals("../foo/hello.txt", + localDb.getFS().readSymLink(linkedsubdirhello)); - // The bar/foo/LinkedHello file should use a single relative ../ - File linkedbarfoohello = new File(localDb.getWorkTree(), - "bar/foo/LinkedHello"); - assertTrue("The bar/foo/LinkedHello file should exist", - localDb.getFS().exists(linkedbarfoohello)); - assertTrue("The bar/foo/LinkedHello file should be a symlink", - localDb.getFS().isSymLink(linkedbarfoohello)); - assertEquals("../baz/hello.txt", - localDb.getFS().readSymLink(linkedbarfoohello)); - - localDb.close(); + // The bar/foo/LinkedHello file should use a single relative ../ + File linkedbarfoohello = new File(localDb.getWorkTree(), + "bar/foo/LinkedHello"); + assertTrue("The bar/foo/LinkedHello file should exist", + localDb.getFS().exists(linkedbarfoohello)); + assertTrue("The bar/foo/LinkedHello file should be a symlink", + localDb.getFS().isSymLink(linkedbarfoohello)); + assertEquals("../baz/hello.txt", + localDb.getFS().readSymLink(linkedbarfoohello)); + } } } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/gitrepo/RepoCommandTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/gitrepo/RepoCommandTest.java index 2253a0421f..fa45214f0c 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/gitrepo/RepoCommandTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/gitrepo/RepoCommandTest.java @@ -42,7 +42,7 @@ */ package org.eclipse.jgit.gitrepo; -import static java.nio.charset.StandardCharsets.UTF_8; +import static org.eclipse.jgit.lib.Constants.CHARSET; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; @@ -185,108 +185,93 @@ public class RepoCommandTest extends RepositoryTestCase { } } + private Repository cloneRepository(Repository repo, boolean bare) + throws Exception { + Repository r = Git.cloneRepository() + .setURI(repo.getDirectory().toURI().toString()) + .setDirectory(createUniqueTestGitDir(true)).setBare(bare).call() + .getRepository(); + if (bare) { + assertTrue(r.isBare()); + } else { + assertFalse(r.isBare()); + } + return r; + } + @Test public void runTwiceIsNOP() throws Exception { - Repository child = Git.cloneRepository() - .setURI(groupADb.getDirectory().toURI().toString()) - .setDirectory(createUniqueTestGitDir(true)).setBare(true).call() - .getRepository(); - - Repository dest = Git.cloneRepository() - .setURI(db.getDirectory().toURI().toString()) - .setDirectory(createUniqueTestGitDir(true)).setBare(true).call() - .getRepository(); + try (Repository child = cloneRepository(groupADb, true); + Repository dest = cloneRepository(db, true)) { + StringBuilder xmlContent = new StringBuilder(); + xmlContent.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") + .append("<manifest>") + .append("<remote name=\"remote1\" fetch=\"..\" />") + .append("<default revision=\"master\" remote=\"remote1\" />") + .append("<project path=\"base\" name=\"platform/base\" />") + .append("</manifest>"); + RepoCommand cmd = new RepoCommand(dest); - assertTrue(dest.isBare()); - assertTrue(child.isBare()); + IndexedRepos repos = new IndexedRepos(); + repos.put("platform/base", child); - StringBuilder xmlContent = new StringBuilder(); - xmlContent.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") - .append("<manifest>") - .append("<remote name=\"remote1\" fetch=\"..\" />") - .append("<default revision=\"master\" remote=\"remote1\" />") - .append("<project path=\"base\" name=\"platform/base\" />") - .append("</manifest>"); - RepoCommand cmd = new RepoCommand(dest); - - IndexedRepos repos = new IndexedRepos(); - repos.put("platform/base", child); - - RevCommit commit = cmd - .setInputStream(new ByteArrayInputStream( - xmlContent.toString().getBytes(UTF_8))) - .setRemoteReader(repos) - .setURI("platform/") - .setTargetURI("platform/superproject") - .setRecordRemoteBranch(true) - .setRecordSubmoduleLabels(true) - .call(); + RevCommit commit = cmd + .setInputStream(new ByteArrayInputStream( + xmlContent.toString().getBytes(CHARSET))) + .setRemoteReader(repos).setURI("platform/") + .setTargetURI("platform/superproject") + .setRecordRemoteBranch(true).setRecordSubmoduleLabels(true) + .call(); - String firstIdStr = commit.getId().name() + ":" + ".gitmodules"; - commit = new RepoCommand(dest) - .setInputStream(new ByteArrayInputStream( - xmlContent.toString().getBytes(UTF_8))) - .setRemoteReader(repos) - .setURI("platform/") - .setTargetURI("platform/superproject") - .setRecordRemoteBranch(true) - .setRecordSubmoduleLabels(true) - .call(); - String idStr = commit.getId().name() + ":" + ".gitmodules"; - assertEquals(firstIdStr, idStr); - child.close(); - dest.close(); + String firstIdStr = commit.getId().name() + ":" + ".gitmodules"; + commit = new RepoCommand(dest) + .setInputStream(new ByteArrayInputStream( + xmlContent.toString().getBytes(CHARSET))) + .setRemoteReader(repos).setURI("platform/") + .setTargetURI("platform/superproject") + .setRecordRemoteBranch(true).setRecordSubmoduleLabels(true) + .call(); + String idStr = commit.getId().name() + ":" + ".gitmodules"; + assertEquals(firstIdStr, idStr); + } } @Test public void androidSetup() throws Exception { - Repository child = Git.cloneRepository() - .setURI(groupADb.getDirectory().toURI().toString()) - .setDirectory(createUniqueTestGitDir(true)).setBare(true).call() - .getRepository(); - - Repository dest = Git.cloneRepository() - .setURI(db.getDirectory().toURI().toString()) - .setDirectory(createUniqueTestGitDir(true)).setBare(true).call() - .getRepository(); + try (Repository child = cloneRepository(groupADb, true); + Repository dest = cloneRepository(db, true)) { + StringBuilder xmlContent = new StringBuilder(); + xmlContent.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") + .append("<manifest>") + .append("<remote name=\"remote1\" fetch=\"..\" />") + .append("<default revision=\"master\" remote=\"remote1\" />") + .append("<project path=\"base\" name=\"platform/base\" />") + .append("</manifest>"); + RepoCommand cmd = new RepoCommand(dest); - assertTrue(dest.isBare()); - assertTrue(child.isBare()); + IndexedRepos repos = new IndexedRepos(); + repos.put("platform/base", child); - StringBuilder xmlContent = new StringBuilder(); - xmlContent.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") - .append("<manifest>") - .append("<remote name=\"remote1\" fetch=\"..\" />") - .append("<default revision=\"master\" remote=\"remote1\" />") - .append("<project path=\"base\" name=\"platform/base\" />") - .append("</manifest>"); - RepoCommand cmd = new RepoCommand(dest); - - IndexedRepos repos = new IndexedRepos(); - repos.put("platform/base", child); - - RevCommit commit = cmd - .setInputStream(new ByteArrayInputStream(xmlContent.toString().getBytes(UTF_8))) - .setRemoteReader(repos) - .setURI("platform/") - .setTargetURI("platform/superproject") - .setRecordRemoteBranch(true) - .setRecordSubmoduleLabels(true) - .call(); + RevCommit commit = cmd + .setInputStream(new ByteArrayInputStream( + xmlContent.toString().getBytes(CHARSET))) + .setRemoteReader(repos).setURI("platform/") + .setTargetURI("platform/superproject") + .setRecordRemoteBranch(true).setRecordSubmoduleLabels(true) + .call(); - String idStr = commit.getId().name() + ":" + ".gitmodules"; - ObjectId modId = dest.resolve(idStr); + String idStr = commit.getId().name() + ":" + ".gitmodules"; + ObjectId modId = dest.resolve(idStr); - try (ObjectReader reader = dest.newObjectReader()) { - byte[] bytes = reader.open(modId).getCachedBytes(Integer.MAX_VALUE); - Config base = new Config(); - BlobBasedConfig cfg = new BlobBasedConfig(base, bytes); - String subUrl = cfg.getString("submodule", "base", "url"); - assertEquals(subUrl, "../base"); + try (ObjectReader reader = dest.newObjectReader()) { + byte[] bytes = reader.open(modId) + .getCachedBytes(Integer.MAX_VALUE); + Config base = new Config(); + BlobBasedConfig cfg = new BlobBasedConfig(base, bytes); + String subUrl = cfg.getString("submodule", "base", "url"); + assertEquals(subUrl, "../base"); + } } - - child.close(); - dest.close(); } @Test @@ -299,200 +284,174 @@ public class RepoCommandTest extends RepositoryTestCase { .append("<project path=\"base\" name=\"platform/base\" />") .append("</manifest>"); - Repository dest = Git.cloneRepository() - .setURI(db.getDirectory().toURI().toString()) - .setDirectory(createUniqueTestGitDir(true)).setBare(true).call() - .getRepository(); - - assertTrue(dest.isBare()); - - RevCommit commit = new RepoCommand(dest) - .setInputStream(new ByteArrayInputStream( - xmlContent.toString().getBytes(UTF_8))) - .setRemoteReader(new IndexedRepos()) - .setURI("platform/") - .setTargetURI("platform/superproject") - .setRecordRemoteBranch(true) - .setIgnoreRemoteFailures(true) - .setRecordSubmoduleLabels(true) - .call(); - - String idStr = commit.getId().name() + ":" + ".gitmodules"; - ObjectId modId = dest.resolve(idStr); - - try (ObjectReader reader = dest.newObjectReader()) { - byte[] bytes = reader.open(modId).getCachedBytes(Integer.MAX_VALUE); - Config base = new Config(); - BlobBasedConfig cfg = new BlobBasedConfig(base, bytes); - String subUrl = cfg.getString("submodule", "base", "url"); - assertEquals(subUrl, "https://host.com/platform/base"); + try (Repository dest = cloneRepository(db, true)) { + RevCommit commit = new RepoCommand(dest) + .setInputStream(new ByteArrayInputStream( + xmlContent.toString().getBytes(CHARSET))) + .setRemoteReader(new IndexedRepos()).setURI("platform/") + .setTargetURI("platform/superproject") + .setRecordRemoteBranch(true).setIgnoreRemoteFailures(true) + .setRecordSubmoduleLabels(true).call(); + + String idStr = commit.getId().name() + ":" + ".gitmodules"; + ObjectId modId = dest.resolve(idStr); + + try (ObjectReader reader = dest.newObjectReader()) { + byte[] bytes = reader.open(modId) + .getCachedBytes(Integer.MAX_VALUE); + Config base = new Config(); + BlobBasedConfig cfg = new BlobBasedConfig(base, bytes); + String subUrl = cfg.getString("submodule", "base", "url"); + assertEquals(subUrl, "https://host.com/platform/base"); + } } - - dest.close(); } @Test public void gerritSetup() throws Exception { - Repository child = - Git.cloneRepository().setURI(groupADb.getDirectory().toURI().toString()) - .setDirectory(createUniqueTestGitDir(true)) - .setBare(true).call().getRepository(); - - Repository dest = Git.cloneRepository() - .setURI(db.getDirectory().toURI().toString()).setDirectory(createUniqueTestGitDir(true)) - .setBare(true).call().getRepository(); + try (Repository child = cloneRepository(groupADb, true); + Repository dest = cloneRepository(db, true)) { + StringBuilder xmlContent = new StringBuilder(); + xmlContent.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") + .append("<manifest>") + .append("<remote name=\"remote1\" fetch=\".\" />") + .append("<default revision=\"master\" remote=\"remote1\" />") + .append("<project path=\"plugins/cookbook\" name=\"plugins/cookbook\" />") + .append("</manifest>"); + RepoCommand cmd = new RepoCommand(dest); - assertTrue(dest.isBare()); - assertTrue(child.isBare()); + IndexedRepos repos = new IndexedRepos(); + repos.put("plugins/cookbook", child); - StringBuilder xmlContent = new StringBuilder(); - xmlContent.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") - .append("<manifest>") - .append("<remote name=\"remote1\" fetch=\".\" />") - .append("<default revision=\"master\" remote=\"remote1\" />") - .append("<project path=\"plugins/cookbook\" name=\"plugins/cookbook\" />") - .append("</manifest>"); - RepoCommand cmd = new RepoCommand(dest); - - IndexedRepos repos = new IndexedRepos(); - repos.put("plugins/cookbook", child); - - RevCommit commit = cmd - .setInputStream(new ByteArrayInputStream(xmlContent.toString().getBytes(UTF_8))) - .setRemoteReader(repos) - .setURI("") - .setTargetURI("gerrit") - .setRecordRemoteBranch(true) - .setRecordSubmoduleLabels(true) - .call(); - - String idStr = commit.getId().name() + ":" + ".gitmodules"; - ObjectId modId = dest.resolve(idStr); + RevCommit commit = cmd + .setInputStream(new ByteArrayInputStream( + xmlContent.toString().getBytes(CHARSET))) + .setRemoteReader(repos).setURI("").setTargetURI("gerrit") + .setRecordRemoteBranch(true).setRecordSubmoduleLabels(true) + .call(); - try (ObjectReader reader = dest.newObjectReader()) { - byte[] bytes = reader.open(modId).getCachedBytes(Integer.MAX_VALUE); - Config base = new Config(); - BlobBasedConfig cfg = new BlobBasedConfig(base, bytes); - String subUrl = cfg.getString("submodule", "plugins/cookbook", "url"); - assertEquals(subUrl, "../plugins/cookbook"); + String idStr = commit.getId().name() + ":" + ".gitmodules"; + ObjectId modId = dest.resolve(idStr); + + try (ObjectReader reader = dest.newObjectReader()) { + byte[] bytes = reader.open(modId) + .getCachedBytes(Integer.MAX_VALUE); + Config base = new Config(); + BlobBasedConfig cfg = new BlobBasedConfig(base, bytes); + String subUrl = cfg.getString("submodule", "plugins/cookbook", + "url"); + assertEquals(subUrl, "../plugins/cookbook"); + } } - - child.close(); - dest.close(); } @Test public void absoluteRemoteURL() throws Exception { - Repository child = - Git.cloneRepository().setURI(groupADb.getDirectory().toURI().toString()) - .setDirectory(createUniqueTestGitDir(true)) - .setBare(true).call().getRepository(); - Repository dest = Git.cloneRepository() - .setURI(db.getDirectory().toURI().toString()).setDirectory(createUniqueTestGitDir(true)) - .setBare(true).call().getRepository(); - String abs = "https://chromium.googlesource.com"; - String repoUrl = "https://chromium.googlesource.com/chromium/src"; - boolean fetchSlash = false; - boolean baseSlash = false; - do { + try (Repository child = cloneRepository(groupADb, true); + Repository dest = cloneRepository(db, true)) { + String abs = "https://chromium.googlesource.com"; + String repoUrl = "https://chromium.googlesource.com/chromium/src"; + boolean fetchSlash = false; + boolean baseSlash = false; do { - String fetchUrl = fetchSlash ? abs + "/" : abs; - String baseUrl = baseSlash ? abs + "/" : abs; - - StringBuilder xmlContent = new StringBuilder(); - xmlContent.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") - .append("<manifest>") - .append("<remote name=\"origin\" fetch=\"" + fetchUrl + "\" />") - .append("<default revision=\"master\" remote=\"origin\" />") - .append("<project path=\"src\" name=\"chromium/src\" />") - .append("</manifest>"); - RepoCommand cmd = new RepoCommand(dest); - - IndexedRepos repos = new IndexedRepos(); - repos.put(repoUrl, child); - - RevCommit commit = cmd - .setInputStream(new ByteArrayInputStream(xmlContent.toString().getBytes(UTF_8))) - .setRemoteReader(repos) - .setURI(baseUrl) - .setTargetURI("gerrit") - .setRecordRemoteBranch(true) - .setRecordSubmoduleLabels(true) - .call(); - - String idStr = commit.getId().name() + ":" + ".gitmodules"; - ObjectId modId = dest.resolve(idStr); - - try (ObjectReader reader = dest.newObjectReader()) { - byte[] bytes = reader.open(modId).getCachedBytes(Integer.MAX_VALUE); - Config base = new Config(); - BlobBasedConfig cfg = new BlobBasedConfig(base, bytes); - String subUrl = cfg.getString("submodule", "src", "url"); - assertEquals("https://chromium.googlesource.com/chromium/src", subUrl); - } - fetchSlash = !fetchSlash; - } while (fetchSlash); - baseSlash = !baseSlash; - } while (baseSlash); - child.close(); - dest.close(); + do { + String fetchUrl = fetchSlash ? abs + "/" : abs; + String baseUrl = baseSlash ? abs + "/" : abs; + + StringBuilder xmlContent = new StringBuilder(); + xmlContent.append( + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") + .append("<manifest>") + .append("<remote name=\"origin\" fetch=\"" + + fetchUrl + "\" />") + .append("<default revision=\"master\" remote=\"origin\" />") + .append("<project path=\"src\" name=\"chromium/src\" />") + .append("</manifest>"); + RepoCommand cmd = new RepoCommand(dest); + + IndexedRepos repos = new IndexedRepos(); + repos.put(repoUrl, child); + + RevCommit commit = cmd + .setInputStream(new ByteArrayInputStream( + xmlContent.toString().getBytes(CHARSET))) + .setRemoteReader(repos).setURI(baseUrl) + .setTargetURI("gerrit").setRecordRemoteBranch(true) + .setRecordSubmoduleLabels(true).call(); + + String idStr = commit.getId().name() + ":" + ".gitmodules"; + ObjectId modId = dest.resolve(idStr); + + try (ObjectReader reader = dest.newObjectReader()) { + byte[] bytes = reader.open(modId) + .getCachedBytes(Integer.MAX_VALUE); + Config base = new Config(); + BlobBasedConfig cfg = new BlobBasedConfig(base, bytes); + String subUrl = cfg.getString("submodule", "src", + "url"); + assertEquals( + "https://chromium.googlesource.com/chromium/src", + subUrl); + } + fetchSlash = !fetchSlash; + } while (fetchSlash); + baseSlash = !baseSlash; + } while (baseSlash); + } } @Test public void absoluteRemoteURLAbsoluteTargetURL() throws Exception { - Repository child = - Git.cloneRepository().setURI(groupADb.getDirectory().toURI().toString()) - .setDirectory(createUniqueTestGitDir(true)) - .setBare(true).call().getRepository(); - Repository dest = Git.cloneRepository() - .setURI(db.getDirectory().toURI().toString()).setDirectory(createUniqueTestGitDir(true)) - .setBare(true).call().getRepository(); - String abs = "https://chromium.googlesource.com"; - String repoUrl = "https://chromium.googlesource.com/chromium/src"; - boolean fetchSlash = false; - boolean baseSlash = false; - do { + try (Repository child = cloneRepository(groupADb, true); + Repository dest = cloneRepository(db, true)) { + String abs = "https://chromium.googlesource.com"; + String repoUrl = "https://chromium.googlesource.com/chromium/src"; + boolean fetchSlash = false; + boolean baseSlash = false; do { - String fetchUrl = fetchSlash ? abs + "/" : abs; - String baseUrl = baseSlash ? abs + "/" : abs; - - StringBuilder xmlContent = new StringBuilder(); - xmlContent.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") - .append("<manifest>") - .append("<remote name=\"origin\" fetch=\"" + fetchUrl + "\" />") - .append("<default revision=\"master\" remote=\"origin\" />") - .append("<project path=\"src\" name=\"chromium/src\" />") - .append("</manifest>"); - RepoCommand cmd = new RepoCommand(dest); - - IndexedRepos repos = new IndexedRepos(); - repos.put(repoUrl, child); - - RevCommit commit = cmd - .setInputStream(new ByteArrayInputStream(xmlContent.toString().getBytes(UTF_8))) - .setRemoteReader(repos) - .setURI(baseUrl) - .setTargetURI(abs + "/superproject") - .setRecordRemoteBranch(true) - .setRecordSubmoduleLabels(true) - .call(); - - String idStr = commit.getId().name() + ":" + ".gitmodules"; - ObjectId modId = dest.resolve(idStr); - - try (ObjectReader reader = dest.newObjectReader()) { - byte[] bytes = reader.open(modId).getCachedBytes(Integer.MAX_VALUE); - Config base = new Config(); - BlobBasedConfig cfg = new BlobBasedConfig(base, bytes); - String subUrl = cfg.getString("submodule", "src", "url"); - assertEquals("../chromium/src", subUrl); - } - fetchSlash = !fetchSlash; - } while (fetchSlash); - baseSlash = !baseSlash; - } while (baseSlash); - child.close(); - dest.close(); + do { + String fetchUrl = fetchSlash ? abs + "/" : abs; + String baseUrl = baseSlash ? abs + "/" : abs; + + StringBuilder xmlContent = new StringBuilder(); + xmlContent.append( + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") + .append("<manifest>") + .append("<remote name=\"origin\" fetch=\"" + + fetchUrl + "\" />") + .append("<default revision=\"master\" remote=\"origin\" />") + .append("<project path=\"src\" name=\"chromium/src\" />") + .append("</manifest>"); + RepoCommand cmd = new RepoCommand(dest); + + IndexedRepos repos = new IndexedRepos(); + repos.put(repoUrl, child); + + RevCommit commit = cmd + .setInputStream(new ByteArrayInputStream( + xmlContent.toString().getBytes(CHARSET))) + .setRemoteReader(repos).setURI(baseUrl) + .setTargetURI(abs + "/superproject") + .setRecordRemoteBranch(true) + .setRecordSubmoduleLabels(true).call(); + + String idStr = commit.getId().name() + ":" + ".gitmodules"; + ObjectId modId = dest.resolve(idStr); + + try (ObjectReader reader = dest.newObjectReader()) { + byte[] bytes = reader.open(modId) + .getCachedBytes(Integer.MAX_VALUE); + Config base = new Config(); + BlobBasedConfig cfg = new BlobBasedConfig(base, bytes); + String subUrl = cfg.getString("submodule", "src", + "url"); + assertEquals("../chromium/src", subUrl); + } + fetchSlash = !fetchSlash; + } while (fetchSlash); + baseSlash = !baseSlash; + } while (baseSlash); + } } @Test @@ -513,11 +472,12 @@ public class RepoCommandTest extends RepositoryTestCase { .call(); File hello = new File(db.getWorkTree(), "foo/hello.txt"); assertTrue("submodule should be checked out", hello.exists()); - BufferedReader reader = new BufferedReader(new FileReader(hello)); - String content = reader.readLine(); - reader.close(); - assertEquals("submodule content should be as expected", - "master world", content); + try (BufferedReader reader = new BufferedReader( + new FileReader(hello))) { + String content = reader.readLine(); + assertEquals("submodule content should be as expected", + "master world", content); + } } @Test @@ -603,19 +563,21 @@ public class RepoCommandTest extends RepositoryTestCase { // The original file should exist File hello = new File(localDb.getWorkTree(), "foo/hello.txt"); assertTrue("The original file should exist", hello.exists()); - BufferedReader reader = new BufferedReader(new FileReader(hello)); - String content = reader.readLine(); - reader.close(); - assertEquals("The original file should have expected content", - "master world", content); + try (BufferedReader reader = new BufferedReader( + new FileReader(hello))) { + String content = reader.readLine(); + assertEquals("The original file should have expected content", + "master world", content); + } // The dest file should also exist hello = new File(localDb.getWorkTree(), "Hello"); assertTrue("The destination file should exist", hello.exists()); - reader = new BufferedReader(new FileReader(hello)); - content = reader.readLine(); - reader.close(); - assertEquals("The destination file should have expected content", - "master world", content); + try (BufferedReader reader = new BufferedReader( + new FileReader(hello))) { + String content = reader.readLine(); + assertEquals("The destination file should have expected content", + "master world", content); + } } @Test @@ -638,24 +600,27 @@ public class RepoCommandTest extends RepositoryTestCase { .setURI(rootUri).call(); // Clone it File directory = createTempDirectory("testBareRepo"); - Repository localDb = Git.cloneRepository().setDirectory(directory) + try (Repository localDb = Git.cloneRepository().setDirectory(directory) .setURI(remoteDb.getDirectory().toURI().toString()).call() - .getRepository(); - // The .gitmodules file should exist - File gitmodules = new File(localDb.getWorkTree(), ".gitmodules"); - assertTrue("The .gitmodules file should exist", gitmodules.exists()); - // The first line of .gitmodules file should be expected - BufferedReader reader = new BufferedReader(new FileReader(gitmodules)); - String content = reader.readLine(); - reader.close(); - assertEquals("The first line of .gitmodules file should be as expected", - "[submodule \"foo\"]", content); - // The gitlink should be the same as remote head sha1 - String gitlink = localDb.resolve(Constants.HEAD + ":foo").name(); - localDb.close(); - String remote = defaultDb.resolve(Constants.HEAD).name(); - assertEquals("The gitlink should be the same as remote head", remote, - gitlink); + .getRepository()) { + // The .gitmodules file should exist + File gitmodules = new File(localDb.getWorkTree(), ".gitmodules"); + assertTrue("The .gitmodules file should exist", + gitmodules.exists()); + // The first line of .gitmodules file should be expected + try (BufferedReader reader = new BufferedReader( + new FileReader(gitmodules))) { + String content = reader.readLine(); + assertEquals( + "The first line of .gitmodules file should be as expected", + "[submodule \"foo\"]", content); + } + // The gitlink should be the same as remote head sha1 + String gitlink = localDb.resolve(Constants.HEAD + ":foo").name(); + String remote = defaultDb.resolve(Constants.HEAD).name(); + assertEquals("The gitlink should be the same as remote head", + remote, gitlink); + } } @Test @@ -677,11 +642,12 @@ public class RepoCommandTest extends RepositoryTestCase { .setURI(rootUri) .call(); File hello = new File(db.getWorkTree(), "foo/hello.txt"); - BufferedReader reader = new BufferedReader(new FileReader(hello)); - String content = reader.readLine(); - reader.close(); - assertEquals("submodule content should be as expected", - "branch world", content); + try (BufferedReader reader = new BufferedReader( + new FileReader(hello))) { + String content = reader.readLine(); + assertEquals("submodule content should be as expected", + "branch world", content); + } } @Test @@ -703,11 +669,12 @@ public class RepoCommandTest extends RepositoryTestCase { .setURI(rootUri) .call(); File hello = new File(db.getWorkTree(), "foo/hello.txt"); - BufferedReader reader = new BufferedReader(new FileReader(hello)); - String content = reader.readLine(); - reader.close(); - assertEquals("submodule content should be as expected", - "branch world", content); + try (BufferedReader reader = new BufferedReader( + new FileReader(hello))) { + String content = reader.readLine(); + assertEquals("submodule content should be as expected", + "branch world", content); + } } @Test @@ -729,11 +696,12 @@ public class RepoCommandTest extends RepositoryTestCase { .setURI(rootUri) .call(); File hello = new File(db.getWorkTree(), "foo/hello.txt"); - BufferedReader reader = new BufferedReader(new FileReader(hello)); - String content = reader.readLine(); - reader.close(); - assertEquals("submodule content should be as expected", - "branch world", content); + try (BufferedReader reader = new BufferedReader( + new FileReader(hello))) { + String content = reader.readLine(); + assertEquals("submodule content should be as expected", + "branch world", content); + } } @Test @@ -757,14 +725,14 @@ public class RepoCommandTest extends RepositoryTestCase { .setURI(rootUri).call(); // Clone it File directory = createTempDirectory("testRevisionBare"); - Repository localDb = Git.cloneRepository().setDirectory(directory) + try (Repository localDb = Git.cloneRepository().setDirectory(directory) .setURI(remoteDb.getDirectory().toURI().toString()).call() - .getRepository(); - // The gitlink should be the same as oldCommitId - String gitlink = localDb.resolve(Constants.HEAD + ":foo").name(); - localDb.close(); - assertEquals("The gitlink is same as remote head", oldCommitId.name(), - gitlink); + .getRepository()) { + // The gitlink should be the same as oldCommitId + String gitlink = localDb.resolve(Constants.HEAD + ":foo").name(); + assertEquals("The gitlink is same as remote head", + oldCommitId.name(), gitlink); + } } @Test @@ -790,22 +758,24 @@ public class RepoCommandTest extends RepositoryTestCase { .setURI(rootUri).call(); // Clone it File directory = createTempDirectory("testCopyFileBare"); - Repository localDb = Git.cloneRepository().setDirectory(directory) + try (Repository localDb = Git.cloneRepository().setDirectory(directory) .setURI(remoteDb.getDirectory().toURI().toString()).call() - .getRepository(); - // The Hello file should exist - File hello = new File(localDb.getWorkTree(), "Hello"); - assertTrue("The Hello file should exist", hello.exists()); - // The foo/Hello file should be skipped. - File foohello = new File(localDb.getWorkTree(), "foo/Hello"); - assertFalse("The foo/Hello file should be skipped", foohello.exists()); - localDb.close(); - // The content of Hello file should be expected - BufferedReader reader = new BufferedReader(new FileReader(hello)); - String content = reader.readLine(); - reader.close(); - assertEquals("The Hello file should have expected content", - "branch world", content); + .getRepository()) { + // The Hello file should exist + File hello = new File(localDb.getWorkTree(), "Hello"); + assertTrue("The Hello file should exist", hello.exists()); + // The foo/Hello file should be skipped. + File foohello = new File(localDb.getWorkTree(), "foo/Hello"); + assertFalse("The foo/Hello file should be skipped", + foohello.exists()); + // The content of Hello file should be expected + try (BufferedReader reader = new BufferedReader( + new FileReader(hello))) { + String content = reader.readLine(); + assertEquals("The Hello file should have expected content", + "branch world", content); + } + } } @Test @@ -841,36 +811,38 @@ public class RepoCommandTest extends RepositoryTestCase { .setURI(rootUri).call(); // Clone it File directory = createTempDirectory("testReplaceManifestBare"); - Repository localDb = Git.cloneRepository().setDirectory(directory) + File dotmodules; + try (Repository localDb = Git.cloneRepository().setDirectory(directory) .setURI(remoteDb.getDirectory().toURI().toString()).call() - .getRepository(); - // The Hello file should not exist - File hello = new File(localDb.getWorkTree(), "Hello"); - assertFalse("The Hello file shouldn't exist", hello.exists()); - // The Hello.txt file should exist - File hellotxt = new File(localDb.getWorkTree(), "Hello.txt"); - assertTrue("The Hello.txt file should exist", hellotxt.exists()); + .getRepository()) { + // The Hello file should not exist + File hello = new File(localDb.getWorkTree(), "Hello"); + assertFalse("The Hello file shouldn't exist", hello.exists()); + // The Hello.txt file should exist + File hellotxt = new File(localDb.getWorkTree(), "Hello.txt"); + assertTrue("The Hello.txt file should exist", hellotxt.exists()); + dotmodules = new File(localDb.getWorkTree(), + Constants.DOT_GIT_MODULES); + } // The .gitmodules file should have 'submodule "bar"' and shouldn't // have // 'submodule "foo"' lines. - File dotmodules = new File(localDb.getWorkTree(), - Constants.DOT_GIT_MODULES); - localDb.close(); - BufferedReader reader = new BufferedReader(new FileReader(dotmodules)); - boolean foo = false; - boolean bar = false; - while (true) { - String line = reader.readLine(); - if (line == null) - break; - if (line.contains("submodule \"foo\"")) - foo = true; - if (line.contains("submodule \"bar\"")) - bar = true; + try (BufferedReader reader = new BufferedReader( + new FileReader(dotmodules))) { + boolean foo = false; + boolean bar = false; + while (true) { + String line = reader.readLine(); + if (line == null) + break; + if (line.contains("submodule \"foo\"")) + foo = true; + if (line.contains("submodule \"bar\"")) + bar = true; + } + assertTrue("The bar submodule should exist", bar); + assertFalse("The foo submodule shouldn't exist", foo); } - reader.close(); - assertTrue("The bar submodule should exist", bar); - assertFalse("The foo submodule shouldn't exist", foo); } @Test @@ -896,34 +868,37 @@ public class RepoCommandTest extends RepositoryTestCase { .setURI(rootUri).call(); // Clone it File directory = createTempDirectory("testRemoveOverlappingBare"); - Repository localDb = Git.cloneRepository().setDirectory(directory) + File dotmodules; + try (Repository localDb = Git.cloneRepository().setDirectory(directory) .setURI(remoteDb.getDirectory().toURI().toString()).call() - .getRepository(); + .getRepository()) { + dotmodules = new File(localDb.getWorkTree(), + Constants.DOT_GIT_MODULES); + } + // The .gitmodules file should have 'submodule "foo"' and shouldn't // have // 'submodule "foo/bar"' lines. - File dotmodules = new File(localDb.getWorkTree(), - Constants.DOT_GIT_MODULES); - localDb.close(); - BufferedReader reader = new BufferedReader(new FileReader(dotmodules)); - boolean foo = false; - boolean foobar = false; - boolean a = false; - while (true) { - String line = reader.readLine(); - if (line == null) - break; - if (line.contains("submodule \"foo\"")) - foo = true; - if (line.contains("submodule \"foo/bar\"")) - foobar = true; - if (line.contains("submodule \"a\"")) - a = true; + try (BufferedReader reader = new BufferedReader( + new FileReader(dotmodules))) { + boolean foo = false; + boolean foobar = false; + boolean a = false; + while (true) { + String line = reader.readLine(); + if (line == null) + break; + if (line.contains("submodule \"foo\"")) + foo = true; + if (line.contains("submodule \"foo/bar\"")) + foobar = true; + if (line.contains("submodule \"a\"")) + a = true; + } + assertTrue("The foo submodule should exist", foo); + assertFalse("The foo/bar submodule shouldn't exist", foobar); + assertTrue("The a submodule should exist", a); } - reader.close(); - assertTrue("The foo submodule should exist", foo); - assertFalse("The foo/bar submodule shouldn't exist", foobar); - assertTrue("The a submodule should exist", a); } @Test @@ -959,11 +934,12 @@ public class RepoCommandTest extends RepositoryTestCase { .call(); File hello = new File(localDb.getWorkTree(), "foo/hello.txt"); assertTrue("submodule should be checked out", hello.exists()); - BufferedReader reader = new BufferedReader(new FileReader(hello)); - String content = reader.readLine(); - reader.close(); - assertEquals("submodule content should be as expected", - "master world", content); + try (BufferedReader reader = new BufferedReader( + new FileReader(hello))) { + String content = reader.readLine(); + assertEquals("submodule content should be as expected", + "master world", content); + } } @Test public void testRemoteAlias() throws Exception { @@ -1165,11 +1141,12 @@ public class RepoCommandTest extends RepositoryTestCase { .setURI(rootUri) .call(); File hello = new File(db.getWorkTree(), "foo/hello.txt"); - BufferedReader reader = new BufferedReader(new FileReader(hello)); - String content = reader.readLine(); - reader.close(); - assertEquals("submodule content should be as expected", - "branch world", content); + try (BufferedReader reader = new BufferedReader( + new FileReader(hello))) { + String content = reader.readLine(); + assertEquals("submodule content should be as expected", + "branch world", content); + } } @Test @@ -1191,11 +1168,12 @@ public class RepoCommandTest extends RepositoryTestCase { .setURI(rootUri) .call(); File hello = new File(db.getWorkTree(), "foo/hello.txt"); - BufferedReader reader = new BufferedReader(new FileReader(hello)); - String content = reader.readLine(); - reader.close(); - assertEquals("submodule content should be as expected", - "branch world", content); + try (BufferedReader reader = new BufferedReader( + new FileReader(hello))) { + String content = reader.readLine(); + assertEquals("submodule content should be as expected", + "branch world", content); + } } private void resolveRelativeUris() { diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/ignore/IgnoreNodeTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/ignore/IgnoreNodeTest.java index ccc64fb468..80595feff5 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/ignore/IgnoreNodeTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/ignore/IgnoreNodeTest.java @@ -42,7 +42,7 @@ */ package org.eclipse.jgit.ignore; -import static java.nio.charset.StandardCharsets.UTF_8; +import static org.eclipse.jgit.lib.Constants.CHARSET; import static org.eclipse.jgit.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -56,7 +56,6 @@ import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; -import org.eclipse.jgit.ignore.IgnoreNode.MatchResult; import org.eclipse.jgit.junit.RepositoryTestCase; import org.eclipse.jgit.lib.FileMode; import org.eclipse.jgit.treewalk.FileTreeIterator; @@ -546,19 +545,6 @@ public class IgnoreNodeTest extends RepositoryTestCase { endWalk(); } - @SuppressWarnings("deprecation") - @Test - public void testEmptyIgnoreNode() { - // Rules are never empty: WorkingTreeIterator optimizes empty files away - // So we have to test it manually in case third party clients use - // IgnoreNode directly. - IgnoreNode node = new IgnoreNode(); - assertEquals(MatchResult.CHECK_PARENT, node.isIgnored("", false)); - assertEquals(MatchResult.CHECK_PARENT, node.isIgnored("", false, false)); - assertEquals(MatchResult.CHECK_PARENT_NEGATE_FIRST_MATCH, - node.isIgnored("", false, true)); - } - @Test public void testEmptyIgnoreRules() throws IOException { IgnoreNode node = new IgnoreNode(); @@ -779,6 +765,6 @@ public class IgnoreNodeTest extends RepositoryTestCase { for (String line : rules) { data.append(line + "\n"); } - return new ByteArrayInputStream(data.toString().getBytes(UTF_8)); + return new ByteArrayInputStream(data.toString().getBytes(CHARSET)); } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/indexdiff/IndexDiffWithSymlinkTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/indexdiff/IndexDiffWithSymlinkTest.java index d5d3857ca4..26c11c7eb7 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/indexdiff/IndexDiffWithSymlinkTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/indexdiff/IndexDiffWithSymlinkTest.java @@ -41,7 +41,7 @@ */ package org.eclipse.jgit.indexdiff; -import static java.nio.charset.StandardCharsets.UTF_8; +import static org.eclipse.jgit.lib.Constants.CHARSET; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -128,7 +128,7 @@ public class IndexDiffWithSymlinkTest extends LocalDiskRepositoryTestCase { File restoreScript = new File(testDir, name + ".sh"); try (OutputStream out = new BufferedOutputStream( new FileOutputStream(restoreScript)); - Writer writer = new OutputStreamWriter(out, UTF_8)) { + Writer writer = new OutputStreamWriter(out, CHARSET)) { writer.write("echo `which git` 1>&2\n"); writer.write("echo `git --version` 1>&2\n"); writer.write("git init " + name + " && \\\n"); diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/PackFileTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/PackFileTest.java index 91bd523975..128c1edde1 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/PackFileTest.java +++ b/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()); 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) { diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/PackWriterTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/PackWriterTest.java index 379432ddbb..3711f83656 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/PackWriterTest.java +++ b/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. 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); } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/RefUpdateTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/RefUpdateTest.java index 52861ecd53..592d0c8671 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/RefUpdateTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/RefUpdateTest.java @@ -45,7 +45,7 @@ package org.eclipse.jgit.internal.storage.file; -import static java.nio.charset.StandardCharsets.UTF_8; +import static org.eclipse.jgit.lib.Constants.CHARSET; import static org.eclipse.jgit.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -252,7 +252,7 @@ public class RefUpdateTest extends SampleDataRepositoryTestCase { ObjectId blobId; try (ObjectInserter ins = bareRepo.newObjectInserter()) { - blobId = ins.insert(Constants.OBJ_BLOB, "contents".getBytes(UTF_8)); + blobId = ins.insert(Constants.OBJ_BLOB, "contents".getBytes(CHARSET)); ins.flush(); } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/T0003_BasicTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/T0003_BasicTest.java index d7505af4cf..91255007ef 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/T0003_BasicTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/T0003_BasicTest.java @@ -47,7 +47,7 @@ package org.eclipse.jgit.internal.storage.file; import static java.nio.charset.StandardCharsets.ISO_8859_1; -import static java.nio.charset.StandardCharsets.UTF_8; +import static org.eclipse.jgit.lib.Constants.CHARSET; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -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. @@ -522,7 +517,7 @@ public class T0003_BasicTest extends SampleDataRepositoryTestCase { 4294967295000L, 60)); commit.setCommitter(new PersonIdent("Joe Hacker", "joe2@example.com", 4294967295000L, 60)); - commit.setEncoding(UTF_8); + commit.setEncoding(CHARSET); commit.setMessage("\u00dcbergeeks"); ObjectId cid = insertCommit(commit); assertEquals("4680908112778718f37e686cbebcc912730b3154", cid.name()); diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/UnpackedObjectTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/UnpackedObjectTest.java index c5ab766838..98ff04e15e 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/UnpackedObjectTest.java +++ b/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()); 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(); } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/WindowCacheGetTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/WindowCacheGetTest.java index cc348388cf..9ac794ed8e 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/WindowCacheGetTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/WindowCacheGetTest.java @@ -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()); } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/junit/TestRepositoryTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/junit/TestRepositoryTest.java index b7027f3272..965899e7a0 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/junit/TestRepositoryTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/junit/TestRepositoryTest.java @@ -43,7 +43,7 @@ package org.eclipse.jgit.junit; -import static java.nio.charset.StandardCharsets.UTF_8; +import static org.eclipse.jgit.lib.Constants.CHARSET; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; @@ -418,6 +418,6 @@ public class TestRepositoryTest { RevObject obj = tr.get(rw.parseTree(treeish), path); assertSame(RevBlob.class, obj.getClass()); ObjectLoader loader = rw.getObjectReader().open(obj); - return new String(loader.getCachedBytes(), UTF_8); + return new String(loader.getCachedBytes(), CHARSET); } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/ObjectCheckerTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/ObjectCheckerTest.java index f1c62d4be2..22c66cec16 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/ObjectCheckerTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/ObjectCheckerTest.java @@ -45,7 +45,7 @@ package org.eclipse.jgit.lib; import static java.lang.Integer.valueOf; -import static java.nio.charset.StandardCharsets.UTF_8; +import static org.eclipse.jgit.lib.Constants.CHARSET; import static org.eclipse.jgit.junit.JGitTestUtil.concat; import static org.eclipse.jgit.lib.Constants.OBJECT_ID_LENGTH; import static org.eclipse.jgit.lib.Constants.OBJ_BAD; @@ -1454,7 +1454,7 @@ public class ObjectCheckerTest { StringBuilder b = new StringBuilder(); entry(b, "100644 A"); entry(b, "100644 a"); - byte[] data = b.toString().getBytes(UTF_8); + byte[] data = b.toString().getBytes(CHARSET); checker.setSafeForWindows(true); assertCorrupt("duplicate entry names", OBJ_TREE, data); assertSkipListAccepts(OBJ_TREE, data); @@ -1468,7 +1468,7 @@ public class ObjectCheckerTest { StringBuilder b = new StringBuilder(); entry(b, "100644 A"); entry(b, "100644 a"); - byte[] data = b.toString().getBytes(UTF_8); + byte[] data = b.toString().getBytes(CHARSET); checker.setSafeForMacOS(true); assertCorrupt("duplicate entry names", OBJ_TREE, data); assertSkipListAccepts(OBJ_TREE, data); @@ -1482,7 +1482,7 @@ public class ObjectCheckerTest { StringBuilder b = new StringBuilder(); entry(b, "100644 \u0065\u0301"); entry(b, "100644 \u00e9"); - byte[] data = b.toString().getBytes(UTF_8); + byte[] data = b.toString().getBytes(CHARSET); checker.setSafeForMacOS(true); assertCorrupt("duplicate entry names", OBJ_TREE, data); assertSkipListAccepts(OBJ_TREE, data); @@ -1496,7 +1496,7 @@ public class ObjectCheckerTest { StringBuilder b = new StringBuilder(); entry(b, "100644 A"); checker.setSafeForMacOS(true); - checker.checkTree(b.toString().getBytes(UTF_8)); + checker.checkTree(b.toString().getBytes(CHARSET)); } @Test diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/RacyGitTests.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/RacyGitTests.java index 9236b4e821..8d9ccab1bd 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/RacyGitTests.java +++ b/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 { 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(); } } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/RefTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/RefTest.java index 7fb3309982..e93867829a 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/RefTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/RefTest.java @@ -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()); diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/RepositoryCacheTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/RepositoryCacheTest.java index 1107c2c69b..58b005c282 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/RepositoryCacheTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/RepositoryCacheTest.java @@ -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)); diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/SquashCommitMsgTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/SquashCommitMsgTest.java index 3bcd787f81..203c00e28a 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/SquashCommitMsgTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/SquashCommitMsgTest.java @@ -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); } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/merge/ResolveMergerTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/merge/ResolveMergerTest.java index 9322a4734e..75b87447d4 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/merge/ResolveMergerTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/merge/ResolveMergerTest.java @@ -42,7 +42,7 @@ */ package org.eclipse.jgit.merge; -import static java.nio.charset.StandardCharsets.UTF_8; +import static org.eclipse.jgit.lib.Constants.CHARSET; import static org.eclipse.jgit.lib.Constants.OBJ_BLOB; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -756,7 +756,7 @@ public class ResolveMergerTest extends RepositoryTestCase { } binary[50] = '\0'; - writeTrashFile("file", new String(binary, UTF_8)); + writeTrashFile("file", new String(binary, CHARSET)); git.add().addFilepattern("file").call(); RevCommit first = git.commit().setMessage("added file").call(); @@ -764,7 +764,7 @@ public class ResolveMergerTest extends RepositoryTestCase { int idx = LINELEN * 1200 + 1; byte save = binary[idx]; binary[idx] = '@'; - writeTrashFile("file", new String(binary, UTF_8)); + writeTrashFile("file", new String(binary, CHARSET)); binary[idx] = save; git.add().addFilepattern("file").call(); @@ -773,7 +773,7 @@ public class ResolveMergerTest extends RepositoryTestCase { git.checkout().setCreateBranch(true).setStartPoint(first).setName("side").call(); binary[LINELEN * 1500 + 1] = '!'; - writeTrashFile("file", new String(binary, UTF_8)); + writeTrashFile("file", new String(binary, CHARSET)); git.add().addFilepattern("file").call(); RevCommit sideCommit = git.commit().setAll(true) .setMessage("modified file l 1500").call(); @@ -935,7 +935,7 @@ public class ResolveMergerTest extends RepositoryTestCase { merger.getMergeResults().get("file"); try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { fmt.formatMerge(out, merger.getMergeResults().get("file"), - "BASE", "OURS", "THEIRS", UTF_8.name()); + "BASE", "OURS", "THEIRS", CHARSET.name()); String expected = "<<<<<<< OURS\n" + "1master\n" + "=======\n" @@ -943,7 +943,7 @@ public class ResolveMergerTest extends RepositoryTestCase { + ">>>>>>> THEIRS\n" + "2\n" + "3"; - assertEquals(expected, new String(out.toByteArray(), UTF_8)); + assertEquals(expected, new String(out.toByteArray(), CHARSET)); } } } @@ -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 @@ -1328,6 +1330,6 @@ public class ResolveMergerTest extends RepositoryTestCase { if (obj == null) { return null; } - return new String(rw.getObjectReader().open(obj, OBJ_BLOB).getBytes(), UTF_8); + return new String(rw.getObjectReader().open(obj, OBJ_BLOB).getBytes(), CHARSET); } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/GetTextTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/GetTextTest.java index 65375c7ae0..8da199f7c6 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/GetTextTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/GetTextTest.java @@ -44,7 +44,7 @@ package org.eclipse.jgit.patch; import static java.nio.charset.StandardCharsets.ISO_8859_1; -import static java.nio.charset.StandardCharsets.UTF_8; +import static org.eclipse.jgit.lib.Constants.CHARSET; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -83,7 +83,7 @@ public class GetTextTest { @Test public void testGetText_Convert() throws IOException { final Charset csOld = ISO_8859_1; - final Charset csNew = UTF_8; + final Charset csNew = CHARSET; final Patch p = parseTestPatchFile(); assertTrue(p.getErrors().isEmpty()); assertEquals(1, p.getFiles().size()); @@ -103,7 +103,7 @@ public class GetTextTest { @Test public void testGetText_DiffCc() throws IOException { final Charset csOld = ISO_8859_1; - final Charset csNew = UTF_8; + final Charset csNew = CHARSET; final Patch p = parseTestPatchFile(); assertTrue(p.getErrors().isEmpty()); assertEquals(1, p.getFiles().size()); diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/PatchCcErrorTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/PatchCcErrorTest.java index e4b43172d6..6989343362 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/PatchCcErrorTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/PatchCcErrorTest.java @@ -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(); } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/PatchCcTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/PatchCcTest.java index 837414b054..4a26d50e49 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/PatchCcTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/PatchCcTest.java @@ -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(); } } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/PatchErrorTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/PatchErrorTest.java index 52e3874b6c..3bdf852167 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/PatchErrorTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/PatchErrorTest.java @@ -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(); } } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/PatchTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/PatchTest.java index 9f57ab98c0..6a09a4919e 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/PatchTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/PatchTest.java @@ -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(); } } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/revwalk/RevCommitParseTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/revwalk/RevCommitParseTest.java index 88f240bb1f..9fc96212c7 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/revwalk/RevCommitParseTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/revwalk/RevCommitParseTest.java @@ -44,7 +44,7 @@ package org.eclipse.jgit.revwalk; import static java.nio.charset.StandardCharsets.ISO_8859_1; -import static java.nio.charset.StandardCharsets.UTF_8; +import static org.eclipse.jgit.lib.Constants.CHARSET; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @@ -114,7 +114,7 @@ public class RevCommitParseTest extends RepositoryTestCase { assertNull(c.getTree()); assertNull(c.parents); - c.parseCanonical(rw, body.toString().getBytes(UTF_8)); + c.parseCanonical(rw, body.toString().getBytes(CHARSET)); assertNotNull(c.getTree()); assertEquals(treeId, c.getTree().getId()); assertSame(rw.lookupTree(treeId), c.getTree()); @@ -148,7 +148,7 @@ public class RevCommitParseTest extends RepositoryTestCase { final RevCommit c; c = new RevCommit(id("9473095c4cb2f12aefe1db8a355fe3fafba42f67")); - c.parseCanonical(new RevWalk(db), b.toString().getBytes(UTF_8)); + c.parseCanonical(new RevWalk(db), b.toString().getBytes(CHARSET)); return c; } @@ -161,7 +161,7 @@ public class RevCommitParseTest extends RepositoryTestCase { final RevCommit c; c = new RevCommit(id("9473095c4cb2f12aefe1db8a355fe3fafba42f67")); - c.parseCanonical(new RevWalk(db), b.toString().getBytes(UTF_8)); + c.parseCanonical(new RevWalk(db), b.toString().getBytes(CHARSET)); assertEquals("", c.getFullMessage()); assertEquals("", c.getShortMessage()); @@ -176,7 +176,7 @@ public class RevCommitParseTest extends RepositoryTestCase { final RevCommit c; c = new RevCommit(id("9473095c4cb2f12aefe1db8a355fe3fafba42f67")); - c.parseCanonical(new RevWalk(db), b.toString().getBytes(UTF_8)); + c.parseCanonical(new RevWalk(db), b.toString().getBytes(CHARSET)); assertEquals(new PersonIdent("", "a_u_thor@example.com", 1218123387000l, 7), c.getAuthorIdent()); assertEquals(new PersonIdent("", "", 1218123390000l, -5), c.getCommitterIdent()); @@ -185,13 +185,13 @@ public class RevCommitParseTest extends RepositoryTestCase { @Test public void testParse_implicit_UTF8_encoded() throws Exception { final ByteArrayOutputStream b = new ByteArrayOutputStream(); - b.write("tree 9788669ad918b6fcce64af8882fc9a81cb6aba67\n".getBytes(UTF_8)); - b.write("author F\u00f6r fattare <a_u_thor@example.com> 1218123387 +0700\n".getBytes(UTF_8)); - b.write("committer C O. Miter <c@example.com> 1218123390 -0500\n".getBytes(UTF_8)); - b.write("\n".getBytes(UTF_8)); - b.write("Sm\u00f6rg\u00e5sbord\n".getBytes(UTF_8)); - b.write("\n".getBytes(UTF_8)); - b.write("\u304d\u308c\u3044\n".getBytes(UTF_8)); + b.write("tree 9788669ad918b6fcce64af8882fc9a81cb6aba67\n".getBytes(CHARSET)); + b.write("author F\u00f6r fattare <a_u_thor@example.com> 1218123387 +0700\n".getBytes(CHARSET)); + b.write("committer C O. Miter <c@example.com> 1218123390 -0500\n".getBytes(CHARSET)); + b.write("\n".getBytes(CHARSET)); + b.write("Sm\u00f6rg\u00e5sbord\n".getBytes(CHARSET)); + b.write("\n".getBytes(CHARSET)); + b.write("\u304d\u308c\u3044\n".getBytes(CHARSET)); final RevCommit c; c = new RevCommit(id("9473095c4cb2f12aefe1db8a355fe3fafba42f67")); // bogus id c.parseCanonical(new RevWalk(db), b.toByteArray()); @@ -205,13 +205,13 @@ public class RevCommitParseTest extends RepositoryTestCase { @Test public void testParse_implicit_mixed_encoded() throws Exception { final ByteArrayOutputStream b = new ByteArrayOutputStream(); - b.write("tree 9788669ad918b6fcce64af8882fc9a81cb6aba67\n".getBytes(UTF_8)); + b.write("tree 9788669ad918b6fcce64af8882fc9a81cb6aba67\n".getBytes(CHARSET)); b.write("author F\u00f6r fattare <a_u_thor@example.com> 1218123387 +0700\n".getBytes(ISO_8859_1)); - b.write("committer C O. Miter <c@example.com> 1218123390 -0500\n".getBytes(UTF_8)); - b.write("\n".getBytes(UTF_8)); - b.write("Sm\u00f6rg\u00e5sbord\n".getBytes(UTF_8)); - b.write("\n".getBytes(UTF_8)); - b.write("\u304d\u308c\u3044\n".getBytes(UTF_8)); + b.write("committer C O. Miter <c@example.com> 1218123390 -0500\n".getBytes(CHARSET)); + b.write("\n".getBytes(CHARSET)); + b.write("Sm\u00f6rg\u00e5sbord\n".getBytes(CHARSET)); + b.write("\n".getBytes(CHARSET)); + b.write("\u304d\u308c\u3044\n".getBytes(CHARSET)); final RevCommit c; c = new RevCommit(id("9473095c4cb2f12aefe1db8a355fe3fafba42f67")); // bogus id c.parseCanonical(new RevWalk(db), b.toByteArray()); @@ -260,14 +260,14 @@ public class RevCommitParseTest extends RepositoryTestCase { @Test public void testParse_explicit_bad_encoded() throws Exception { final ByteArrayOutputStream b = new ByteArrayOutputStream(); - b.write("tree 9788669ad918b6fcce64af8882fc9a81cb6aba67\n".getBytes(UTF_8)); + b.write("tree 9788669ad918b6fcce64af8882fc9a81cb6aba67\n".getBytes(CHARSET)); b.write("author F\u00f6r fattare <a_u_thor@example.com> 1218123387 +0700\n".getBytes(ISO_8859_1)); - b.write("committer C O. Miter <c@example.com> 1218123390 -0500\n".getBytes(UTF_8)); - b.write("encoding EUC-JP\n".getBytes(UTF_8)); - b.write("\n".getBytes(UTF_8)); - b.write("\u304d\u308c\u3044\n".getBytes(UTF_8)); - b.write("\n".getBytes(UTF_8)); - b.write("Hi\n".getBytes(UTF_8)); + b.write("committer C O. Miter <c@example.com> 1218123390 -0500\n".getBytes(CHARSET)); + b.write("encoding EUC-JP\n".getBytes(CHARSET)); + b.write("\n".getBytes(CHARSET)); + b.write("\u304d\u308c\u3044\n".getBytes(CHARSET)); + b.write("\n".getBytes(CHARSET)); + b.write("Hi\n".getBytes(CHARSET)); final RevCommit c; c = new RevCommit(id("9473095c4cb2f12aefe1db8a355fe3fafba42f67")); // bogus id c.parseCanonical(new RevWalk(db), b.toByteArray()); @@ -291,14 +291,14 @@ public class RevCommitParseTest extends RepositoryTestCase { @Test public void testParse_explicit_bad_encoded2() throws Exception { final ByteArrayOutputStream b = new ByteArrayOutputStream(); - b.write("tree 9788669ad918b6fcce64af8882fc9a81cb6aba67\n".getBytes(UTF_8)); - b.write("author F\u00f6r fattare <a_u_thor@example.com> 1218123387 +0700\n".getBytes(UTF_8)); - b.write("committer C O. Miter <c@example.com> 1218123390 -0500\n".getBytes(UTF_8)); - b.write("encoding ISO-8859-1\n".getBytes(UTF_8)); - b.write("\n".getBytes(UTF_8)); - b.write("\u304d\u308c\u3044\n".getBytes(UTF_8)); - b.write("\n".getBytes(UTF_8)); - b.write("Hi\n".getBytes(UTF_8)); + b.write("tree 9788669ad918b6fcce64af8882fc9a81cb6aba67\n".getBytes(CHARSET)); + b.write("author F\u00f6r fattare <a_u_thor@example.com> 1218123387 +0700\n".getBytes(CHARSET)); + b.write("committer C O. Miter <c@example.com> 1218123390 -0500\n".getBytes(CHARSET)); + b.write("encoding ISO-8859-1\n".getBytes(CHARSET)); + b.write("\n".getBytes(CHARSET)); + b.write("\u304d\u308c\u3044\n".getBytes(CHARSET)); + b.write("\n".getBytes(CHARSET)); + b.write("Hi\n".getBytes(CHARSET)); final RevCommit c; c = new RevCommit(id("9473095c4cb2f12aefe1db8a355fe3fafba42f67")); // bogus id c.parseCanonical(new RevWalk(db), b.toByteArray()); @@ -313,13 +313,13 @@ public class RevCommitParseTest extends RepositoryTestCase { public void testParse_incorrectUtf8Name() throws Exception { ByteArrayOutputStream b = new ByteArrayOutputStream(); b.write("tree 9788669ad918b6fcce64af8882fc9a81cb6aba67\n" - .getBytes(UTF_8)); - b.write("author au <a@example.com> 1218123387 +0700\n".getBytes(UTF_8)); + .getBytes(CHARSET)); + b.write("author au <a@example.com> 1218123387 +0700\n".getBytes(CHARSET)); b.write("committer co <c@example.com> 1218123390 -0500\n" - .getBytes(UTF_8)); - b.write("encoding 'utf8'\n".getBytes(UTF_8)); - b.write("\n".getBytes(UTF_8)); - b.write("Sm\u00f6rg\u00e5sbord\n".getBytes(UTF_8)); + .getBytes(CHARSET)); + b.write("encoding 'utf8'\n".getBytes(CHARSET)); + b.write("\n".getBytes(CHARSET)); + b.write("Sm\u00f6rg\u00e5sbord\n".getBytes(CHARSET)); RevCommit c = new RevCommit( id("9473095c4cb2f12aefe1db8a355fe3fafba42f67")); @@ -338,12 +338,12 @@ public class RevCommitParseTest extends RepositoryTestCase { @Test public void testParse_illegalEncoding() throws Exception { ByteArrayOutputStream b = new ByteArrayOutputStream(); - b.write("tree 9788669ad918b6fcce64af8882fc9a81cb6aba67\n".getBytes(UTF_8)); - b.write("author au <a@example.com> 1218123387 +0700\n".getBytes(UTF_8)); - b.write("committer co <c@example.com> 1218123390 -0500\n".getBytes(UTF_8)); - b.write("encoding utf-8logoutputencoding=gbk\n".getBytes(UTF_8)); - b.write("\n".getBytes(UTF_8)); - b.write("message\n".getBytes(UTF_8)); + b.write("tree 9788669ad918b6fcce64af8882fc9a81cb6aba67\n".getBytes(CHARSET)); + b.write("author au <a@example.com> 1218123387 +0700\n".getBytes(CHARSET)); + b.write("committer co <c@example.com> 1218123390 -0500\n".getBytes(CHARSET)); + b.write("encoding utf-8logoutputencoding=gbk\n".getBytes(CHARSET)); + b.write("\n".getBytes(CHARSET)); + b.write("message\n".getBytes(CHARSET)); RevCommit c = new RevCommit( id("9473095c4cb2f12aefe1db8a355fe3fafba42f67")); @@ -365,12 +365,12 @@ public class RevCommitParseTest extends RepositoryTestCase { @Test public void testParse_unsupportedEncoding() throws Exception { ByteArrayOutputStream b = new ByteArrayOutputStream(); - b.write("tree 9788669ad918b6fcce64af8882fc9a81cb6aba67\n".getBytes(UTF_8)); - b.write("author au <a@example.com> 1218123387 +0700\n".getBytes(UTF_8)); - b.write("committer co <c@example.com> 1218123390 -0500\n".getBytes(UTF_8)); - b.write("encoding it_IT.UTF8\n".getBytes(UTF_8)); - b.write("\n".getBytes(UTF_8)); - b.write("message\n".getBytes(UTF_8)); + b.write("tree 9788669ad918b6fcce64af8882fc9a81cb6aba67\n".getBytes(CHARSET)); + b.write("author au <a@example.com> 1218123387 +0700\n".getBytes(CHARSET)); + b.write("committer co <c@example.com> 1218123390 -0500\n".getBytes(CHARSET)); + b.write("encoding it_IT.UTF8\n".getBytes(CHARSET)); + b.write("\n".getBytes(CHARSET)); + b.write("message\n".getBytes(CHARSET)); RevCommit c = new RevCommit( id("9473095c4cb2f12aefe1db8a355fe3fafba42f67")); diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/revwalk/RevTagParseTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/revwalk/RevTagParseTest.java index 38bd371b90..8e9507961b 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/revwalk/RevTagParseTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/revwalk/RevTagParseTest.java @@ -44,7 +44,7 @@ package org.eclipse.jgit.revwalk; import static java.nio.charset.StandardCharsets.ISO_8859_1; -import static java.nio.charset.StandardCharsets.UTF_8; +import static org.eclipse.jgit.lib.Constants.CHARSET; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @@ -98,7 +98,7 @@ public class RevTagParseTest extends RepositoryTestCase { assertNull(c.getObject()); assertNull(c.getTagName()); - c.parseCanonical(rw, b.toString().getBytes(UTF_8)); + c.parseCanonical(rw, b.toString().getBytes(CHARSET)); assertNotNull(c.getObject()); assertEquals(id, c.getObject().getId()); assertSame(rw.lookupAny(id, typeCode), c.getObject()); @@ -141,7 +141,7 @@ public class RevTagParseTest extends RepositoryTestCase { assertNull(c.getObject()); assertNull(c.getTagName()); - c.parseCanonical(rw, body.toString().getBytes(UTF_8)); + c.parseCanonical(rw, body.toString().getBytes(CHARSET)); assertNotNull(c.getObject()); assertEquals(treeId, c.getObject().getId()); assertSame(rw.lookupTree(treeId), c.getObject()); @@ -189,7 +189,7 @@ public class RevTagParseTest extends RepositoryTestCase { assertNull(c.getObject()); assertNull(c.getTagName()); - c.parseCanonical(rw, body.toString().getBytes(UTF_8)); + c.parseCanonical(rw, body.toString().getBytes(CHARSET)); assertNotNull(c.getObject()); assertEquals(treeId, c.getObject().getId()); assertSame(rw.lookupTree(treeId), c.getObject()); @@ -213,7 +213,7 @@ public class RevTagParseTest extends RepositoryTestCase { final RevTag c; c = new RevTag(id("9473095c4cb2f12aefe1db8a355fe3fafba42f67")); - c.parseCanonical(new RevWalk(db), b.toString().getBytes(UTF_8)); + c.parseCanonical(new RevWalk(db), b.toString().getBytes(CHARSET)); return c; } @@ -221,17 +221,17 @@ public class RevTagParseTest extends RepositoryTestCase { public void testParse_implicit_UTF8_encoded() throws Exception { final ByteArrayOutputStream b = new ByteArrayOutputStream(); b.write("object 9788669ad918b6fcce64af8882fc9a81cb6aba67\n" - .getBytes(UTF_8)); - b.write("type tree\n".getBytes(UTF_8)); - b.write("tag v1.2.3.4.5\n".getBytes(UTF_8)); + .getBytes(CHARSET)); + b.write("type tree\n".getBytes(CHARSET)); + b.write("tag v1.2.3.4.5\n".getBytes(CHARSET)); b .write("tagger F\u00f6r fattare <a_u_thor@example.com> 1218123387 +0700\n" - .getBytes(UTF_8)); - b.write("\n".getBytes(UTF_8)); - b.write("Sm\u00f6rg\u00e5sbord\n".getBytes(UTF_8)); - b.write("\n".getBytes(UTF_8)); - b.write("\u304d\u308c\u3044\n".getBytes(UTF_8)); + .getBytes(CHARSET)); + b.write("\n".getBytes(CHARSET)); + b.write("Sm\u00f6rg\u00e5sbord\n".getBytes(CHARSET)); + b.write("\n".getBytes(CHARSET)); + b.write("\u304d\u308c\u3044\n".getBytes(CHARSET)); final RevTag c; c = new RevTag(id("9473095c4cb2f12aefe1db8a355fe3fafba42f67")); c.parseCanonical(new RevWalk(db), b.toByteArray()); @@ -246,15 +246,15 @@ public class RevTagParseTest extends RepositoryTestCase { public void testParse_implicit_mixed_encoded() throws Exception { final ByteArrayOutputStream b = new ByteArrayOutputStream(); b.write("object 9788669ad918b6fcce64af8882fc9a81cb6aba67\n" - .getBytes(UTF_8)); - b.write("type tree\n".getBytes(UTF_8)); - b.write("tag v1.2.3.4.5\n".getBytes(UTF_8)); + .getBytes(CHARSET)); + b.write("type tree\n".getBytes(CHARSET)); + b.write("tag v1.2.3.4.5\n".getBytes(CHARSET)); b.write("tagger F\u00f6r fattare <a_u_thor@example.com> 1218123387 +0700\n" .getBytes(ISO_8859_1)); - b.write("\n".getBytes(UTF_8)); - b.write("Sm\u00f6rg\u00e5sbord\n".getBytes(UTF_8)); - b.write("\n".getBytes(UTF_8)); - b.write("\u304d\u308c\u3044\n".getBytes(UTF_8)); + b.write("\n".getBytes(CHARSET)); + b.write("Sm\u00f6rg\u00e5sbord\n".getBytes(CHARSET)); + b.write("\n".getBytes(CHARSET)); + b.write("\u304d\u308c\u3044\n".getBytes(CHARSET)); final RevTag c; c = new RevTag(id("9473095c4cb2f12aefe1db8a355fe3fafba42f67")); c.parseCanonical(new RevWalk(db), b.toByteArray()); @@ -307,17 +307,17 @@ public class RevTagParseTest extends RepositoryTestCase { public void testParse_explicit_bad_encoded() throws Exception { final ByteArrayOutputStream b = new ByteArrayOutputStream(); b.write("object 9788669ad918b6fcce64af8882fc9a81cb6aba67\n" - .getBytes(UTF_8)); - b.write("type tree\n".getBytes(UTF_8)); - b.write("tag v1.2.3.4.5\n".getBytes(UTF_8)); + .getBytes(CHARSET)); + b.write("type tree\n".getBytes(CHARSET)); + b.write("tag v1.2.3.4.5\n".getBytes(CHARSET)); b .write("tagger F\u00f6r fattare <a_u_thor@example.com> 1218123387 +0700\n" .getBytes(ISO_8859_1)); - b.write("encoding EUC-JP\n".getBytes(UTF_8)); - b.write("\n".getBytes(UTF_8)); - b.write("\u304d\u308c\u3044\n".getBytes(UTF_8)); - b.write("\n".getBytes(UTF_8)); - b.write("Hi\n".getBytes(UTF_8)); + b.write("encoding EUC-JP\n".getBytes(CHARSET)); + b.write("\n".getBytes(CHARSET)); + b.write("\u304d\u308c\u3044\n".getBytes(CHARSET)); + b.write("\n".getBytes(CHARSET)); + b.write("Hi\n".getBytes(CHARSET)); final RevTag c; c = new RevTag(id("9473095c4cb2f12aefe1db8a355fe3fafba42f67")); c.parseCanonical(new RevWalk(db), b.toByteArray()); @@ -342,17 +342,17 @@ public class RevTagParseTest extends RepositoryTestCase { public void testParse_explicit_bad_encoded2() throws Exception { final ByteArrayOutputStream b = new ByteArrayOutputStream(); b.write("object 9788669ad918b6fcce64af8882fc9a81cb6aba67\n" - .getBytes(UTF_8)); - b.write("type tree\n".getBytes(UTF_8)); - b.write("tag v1.2.3.4.5\n".getBytes(UTF_8)); + .getBytes(CHARSET)); + b.write("type tree\n".getBytes(CHARSET)); + b.write("tag v1.2.3.4.5\n".getBytes(CHARSET)); b .write("tagger F\u00f6r fattare <a_u_thor@example.com> 1218123387 +0700\n" - .getBytes(UTF_8)); - b.write("encoding ISO-8859-1\n".getBytes(UTF_8)); - b.write("\n".getBytes(UTF_8)); - b.write("\u304d\u308c\u3044\n".getBytes(UTF_8)); - b.write("\n".getBytes(UTF_8)); - b.write("Hi\n".getBytes(UTF_8)); + .getBytes(CHARSET)); + b.write("encoding ISO-8859-1\n".getBytes(CHARSET)); + b.write("\n".getBytes(CHARSET)); + b.write("\u304d\u308c\u3044\n".getBytes(CHARSET)); + b.write("\n".getBytes(CHARSET)); + b.write("Hi\n".getBytes(CHARSET)); final RevTag c; c = new RevTag(id("9473095c4cb2f12aefe1db8a355fe3fafba42f67")); c.parseCanonical(new RevWalk(db), b.toByteArray()); @@ -365,13 +365,13 @@ public class RevTagParseTest extends RepositoryTestCase { @Test public void testParse_illegalEncoding() throws Exception { ByteArrayOutputStream b = new ByteArrayOutputStream(); - b.write("object 9788669ad918b6fcce64af8882fc9a81cb6aba67\n".getBytes(UTF_8)); - b.write("type tree\n".getBytes(UTF_8)); - b.write("tag v1.0\n".getBytes(UTF_8)); - b.write("tagger t <t@example.com> 1218123387 +0700\n".getBytes(UTF_8)); - b.write("encoding utf-8logoutputencoding=gbk\n".getBytes(UTF_8)); - b.write("\n".getBytes(UTF_8)); - b.write("message\n".getBytes(UTF_8)); + b.write("object 9788669ad918b6fcce64af8882fc9a81cb6aba67\n".getBytes(CHARSET)); + b.write("type tree\n".getBytes(CHARSET)); + b.write("tag v1.0\n".getBytes(CHARSET)); + b.write("tagger t <t@example.com> 1218123387 +0700\n".getBytes(CHARSET)); + b.write("encoding utf-8logoutputencoding=gbk\n".getBytes(CHARSET)); + b.write("\n".getBytes(CHARSET)); + b.write("message\n".getBytes(CHARSET)); RevTag t = new RevTag(id("9473095c4cb2f12aefe1db8a355fe3fafba42f67")); t.parseCanonical(new RevWalk(db), b.toByteArray()); @@ -384,13 +384,13 @@ public class RevTagParseTest extends RepositoryTestCase { @Test public void testParse_unsupportedEncoding() throws Exception { ByteArrayOutputStream b = new ByteArrayOutputStream(); - b.write("object 9788669ad918b6fcce64af8882fc9a81cb6aba67\n".getBytes(UTF_8)); - b.write("type tree\n".getBytes(UTF_8)); - b.write("tag v1.0\n".getBytes(UTF_8)); - b.write("tagger t <t@example.com> 1218123387 +0700\n".getBytes(UTF_8)); - b.write("encoding it_IT.UTF8\n".getBytes(UTF_8)); - b.write("\n".getBytes(UTF_8)); - b.write("message\n".getBytes(UTF_8)); + b.write("object 9788669ad918b6fcce64af8882fc9a81cb6aba67\n".getBytes(CHARSET)); + b.write("type tree\n".getBytes(CHARSET)); + b.write("tag v1.0\n".getBytes(CHARSET)); + b.write("tagger t <t@example.com> 1218123387 +0700\n".getBytes(CHARSET)); + b.write("encoding it_IT.UTF8\n".getBytes(CHARSET)); + b.write("\n".getBytes(CHARSET)); + b.write("message\n".getBytes(CHARSET)); RevTag t = new RevTag(id("9473095c4cb2f12aefe1db8a355fe3fafba42f67")); t.parseCanonical(new RevWalk(db), b.toByteArray()); diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/storage/file/FileBasedConfigTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/storage/file/FileBasedConfigTest.java index 7f0d60295c..0dea5ce97b 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/storage/file/FileBasedConfigTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/storage/file/FileBasedConfigTest.java @@ -42,7 +42,7 @@ */ package org.eclipse.jgit.storage.file; -import static java.nio.charset.StandardCharsets.UTF_8; +import static org.eclipse.jgit.lib.Constants.CHARSET; import static org.eclipse.jgit.util.FileUtils.pathToString; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; @@ -105,7 +105,7 @@ public class FileBasedConfigTest { @Test public void testUTF8withoutBOM() throws IOException, ConfigInvalidException { - final File file = createFile(CONTENT1.getBytes(UTF_8)); + final File file = createFile(CONTENT1.getBytes(CHARSET)); final FileBasedConfig config = new FileBasedConfig(file, FS.DETECTED); config.load(); assertEquals(ALICE, config.getString(USER, null, NAME)); @@ -121,7 +121,7 @@ public class FileBasedConfigTest { bos1.write(0xEF); bos1.write(0xBB); bos1.write(0xBF); - bos1.write(CONTENT1.getBytes(UTF_8)); + bos1.write(CONTENT1.getBytes(CHARSET)); final File file = createFile(bos1.toByteArray()); final FileBasedConfig config = new FileBasedConfig(file, FS.DETECTED); @@ -135,7 +135,7 @@ public class FileBasedConfigTest { bos2.write(0xEF); bos2.write(0xBB); bos2.write(0xBF); - bos2.write(CONTENT2.getBytes(UTF_8)); + bos2.write(CONTENT2.getBytes(CHARSET)); assertArrayEquals(bos2.toByteArray(), IO.readFully(file)); } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/submodule/SubmoduleAddTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/submodule/SubmoduleAddTest.java index f42dd02814..1a67e41976 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/submodule/SubmoduleAddTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/submodule/SubmoduleAddTest.java @@ -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(); diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/submodule/SubmoduleSyncTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/submodule/SubmoduleSyncTest.java index 13db44a9c5..6f3b52f7bb 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/submodule/SubmoduleSyncTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/submodule/SubmoduleSyncTest.java @@ -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)); + } } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/submodule/SubmoduleUpdateTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/submodule/SubmoduleUpdateTest.java index 7064f6097b..bbce413ef3 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/submodule/SubmoduleUpdateTest.java +++ b/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); 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 diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/BundleWriterTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/BundleWriterTest.java index 658b971acb..d30ac840a6 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/BundleWriterTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/BundleWriterTest.java @@ -45,7 +45,7 @@ package org.eclipse.jgit.transport; -import static java.nio.charset.StandardCharsets.UTF_8; +import static org.eclipse.jgit.lib.Constants.CHARSET; import static org.eclipse.jgit.lib.Constants.OBJ_BLOB; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -199,7 +199,7 @@ public class BundleWriterTest extends SampleDataRepositoryTestCase { Ref ref = repo.exactRef(refName); assertNotNull(ref); assertEquals(id, ref.getObjectId()); - assertEquals(data, new String(repo.open(id, OBJ_BLOB).getBytes(), UTF_8)); + assertEquals(data, new String(repo.open(id, OBJ_BLOB).getBytes(), CHARSET)); } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/NetRCTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/NetRCTest.java index 2fea8a92ac..76404aba91 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/NetRCTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/NetRCTest.java @@ -42,6 +42,7 @@ package org.eclipse.jgit.transport; +import static org.eclipse.jgit.lib.Constants.CHARSET; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; @@ -74,10 +75,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), CHARSET)) { + fw.write(data); + } } @Test diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/OpenSshConfigTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/OpenSshConfigTest.java index d604751fef..886f577d98 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/OpenSshConfigTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/OpenSshConfigTest.java @@ -43,6 +43,7 @@ package org.eclipse.jgit.transport; +import static org.eclipse.jgit.lib.Constants.CHARSET; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -93,7 +94,7 @@ public class OpenSshConfigTest extends RepositoryTestCase { long lastMtime = configFile.lastModified(); do { try (final OutputStreamWriter fw = new OutputStreamWriter( - new FileOutputStream(configFile), "UTF-8")) { + new FileOutputStream(configFile), CHARSET)) { fw.write(data); } } while (lastMtime == configFile.lastModified()); diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/PackParserTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/PackParserTest.java index 5d9bdbdbad..b6d0611437 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/PackParserTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/PackParserTest.java @@ -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(); } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/ReceivePackAdvertiseRefsHookTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/ReceivePackAdvertiseRefsHookTest.java index 8ef87cb3c1..7aae7b0c32 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/ReceivePackAdvertiseRefsHookTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/ReceivePackAdvertiseRefsHookTest.java @@ -199,6 +199,23 @@ public class ReceivePackAdvertiseRefsHookTest extends LocalDiskRepositoryTestCas assertFalse(haves.get().contains(P)); } + private TransportLocal newTransportLocalWithStrictValidation() + throws Exception { + return new TransportLocal(src, uriOf(dst), dst.getDirectory()) { + @Override + ReceivePack createReceivePack(final Repository db) { + db.close(); + dst.incrementOpen(); + + final ReceivePack rp = super.createReceivePack(dst); + rp.setCheckReceivedObjects(true); + rp.setCheckReferencedObjectsAreReachable(true); + rp.setAdvertiseRefsHook(new HidePrivateHook()); + return rp; + } + }; + } + @Test public void testSuccess() throws Exception { // Manually force a delta of an object so we reuse it later. @@ -230,19 +247,7 @@ public class ReceivePackAdvertiseRefsHookTest extends LocalDiskRepositoryTestCas // Push this new content to the remote, doing strict validation. // - TransportLocal t = new TransportLocal(src, uriOf(dst), dst.getDirectory()) { - @Override - ReceivePack createReceivePack(final Repository db) { - db.close(); - dst.incrementOpen(); - - final ReceivePack rp = super.createReceivePack(dst); - rp.setCheckReceivedObjects(true); - rp.setCheckReferencedObjectsAreReachable(true); - rp.setAdvertiseRefsHook(new HidePrivateHook()); - return rp; - } - }; + PushResult r; RemoteRefUpdate u = new RemoteRefUpdate( // src, // R_MASTER, // src name @@ -251,12 +256,9 @@ public class ReceivePackAdvertiseRefsHookTest extends LocalDiskRepositoryTestCas null, // local tracking branch null // expected id ); - PushResult r; - try { + try (TransportLocal t = newTransportLocalWithStrictValidation()) { t.setPushThin(true); r = t.push(PM, Collections.singleton(u)); - } finally { - t.close(); } assertNotNull("have result", r); diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/UploadPackTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/UploadPackTest.java index a8127abd36..17f21d6858 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/UploadPackTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/UploadPackTest.java @@ -13,6 +13,7 @@ import org.eclipse.jgit.lib.NullProgressMonitor; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevBlob; import org.eclipse.jgit.revwalk.RevCommit; +import org.eclipse.jgit.revwalk.RevTree; import org.eclipse.jgit.transport.UploadPack.RequestPolicy; import org.eclipse.jgit.transport.resolver.ServiceNotAuthorizedException; import org.eclipse.jgit.transport.resolver.ServiceNotEnabledException; @@ -170,4 +171,149 @@ public class UploadPackTest { Collections.singletonList(new RefSpec(blob.name()))); } } + + @Test + public void testFetchWithBlobNoneFilter() throws Exception { + InMemoryRepository server2 = newRepo("server2"); + TestRepository<InMemoryRepository> remote = + new TestRepository<>(server2); + RevBlob blob1 = remote.blob("foobar"); + RevBlob blob2 = remote.blob("fooba"); + RevTree tree = remote.tree( + remote.file("1", blob1), remote.file("2", blob2)); + RevCommit commit = remote.commit(tree); + remote.update("master", commit); + + server2.getConfig().setBoolean("uploadpack", null, "allowfilter", true); + + testProtocol = new TestProtocol<>( + new UploadPackFactory<Object>() { + @Override + public UploadPack create(Object req, Repository db) + throws ServiceNotEnabledException, + ServiceNotAuthorizedException { + UploadPack up = new UploadPack(db); + return up; + } + }, null); + uri = testProtocol.register(ctx, server2); + + try (Transport tn = testProtocol.open(uri, client, "server2")) { + tn.setFilterBlobLimit(0); + tn.fetch(NullProgressMonitor.INSTANCE, + Collections.singletonList(new RefSpec(commit.name()))); + assertTrue(client.hasObject(tree.toObjectId())); + assertFalse(client.hasObject(blob1.toObjectId())); + assertFalse(client.hasObject(blob2.toObjectId())); + } + } + + @Test + public void testFetchWithBlobLimitFilter() throws Exception { + InMemoryRepository server2 = newRepo("server2"); + TestRepository<InMemoryRepository> remote = + new TestRepository<>(server2); + RevBlob longBlob = remote.blob("foobar"); + RevBlob shortBlob = remote.blob("fooba"); + RevTree tree = remote.tree( + remote.file("1", longBlob), remote.file("2", shortBlob)); + RevCommit commit = remote.commit(tree); + remote.update("master", commit); + + server2.getConfig().setBoolean("uploadpack", null, "allowfilter", true); + + testProtocol = new TestProtocol<>( + new UploadPackFactory<Object>() { + @Override + public UploadPack create(Object req, Repository db) + throws ServiceNotEnabledException, + ServiceNotAuthorizedException { + UploadPack up = new UploadPack(db); + return up; + } + }, null); + uri = testProtocol.register(ctx, server2); + + try (Transport tn = testProtocol.open(uri, client, "server2")) { + tn.setFilterBlobLimit(5); + tn.fetch(NullProgressMonitor.INSTANCE, + Collections.singletonList(new RefSpec(commit.name()))); + assertFalse(client.hasObject(longBlob.toObjectId())); + assertTrue(client.hasObject(shortBlob.toObjectId())); + } + } + + @Test + public void testFetchWithBlobLimitFilterAndBitmaps() throws Exception { + InMemoryRepository server2 = newRepo("server2"); + TestRepository<InMemoryRepository> remote = + new TestRepository<>(server2); + RevBlob longBlob = remote.blob("foobar"); + RevBlob shortBlob = remote.blob("fooba"); + RevTree tree = remote.tree( + remote.file("1", longBlob), remote.file("2", shortBlob)); + RevCommit commit = remote.commit(tree); + remote.update("master", commit); + + server2.getConfig().setBoolean("uploadpack", null, "allowfilter", true); + + // generate bitmaps + new DfsGarbageCollector(server2).pack(null); + server2.scanForRepoChanges(); + + testProtocol = new TestProtocol<>( + new UploadPackFactory<Object>() { + @Override + public UploadPack create(Object req, Repository db) + throws ServiceNotEnabledException, + ServiceNotAuthorizedException { + UploadPack up = new UploadPack(db); + return up; + } + }, null); + uri = testProtocol.register(ctx, server2); + + try (Transport tn = testProtocol.open(uri, client, "server2")) { + tn.setFilterBlobLimit(5); + tn.fetch(NullProgressMonitor.INSTANCE, + Collections.singletonList(new RefSpec(commit.name()))); + assertFalse(client.hasObject(longBlob.toObjectId())); + assertTrue(client.hasObject(shortBlob.toObjectId())); + } + } + + @Test + public void testFetchWithNonSupportingServer() throws Exception { + InMemoryRepository server2 = newRepo("server2"); + TestRepository<InMemoryRepository> remote = + new TestRepository<>(server2); + RevBlob blob = remote.blob("foo"); + RevTree tree = remote.tree(remote.file("1", blob)); + RevCommit commit = remote.commit(tree); + remote.update("master", commit); + + server2.getConfig().setBoolean("uploadpack", null, "allowfilter", false); + + testProtocol = new TestProtocol<>( + new UploadPackFactory<Object>() { + @Override + public UploadPack create(Object req, Repository db) + throws ServiceNotEnabledException, + ServiceNotAuthorizedException { + UploadPack up = new UploadPack(db); + return up; + } + }, null); + uri = testProtocol.register(ctx, server2); + + try (Transport tn = testProtocol.open(uri, client, "server2")) { + tn.setFilterBlobLimit(0); + + thrown.expect(TransportException.class); + thrown.expectMessage("filter requires server to advertise that capability"); + + tn.fetch(NullProgressMonitor.INSTANCE, + Collections.singletonList(new RefSpec(commit.name()))); + } + } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/WalkEncryptionTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/WalkEncryptionTest.java index cb04f83fb5..33e2529731 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/WalkEncryptionTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/WalkEncryptionTest.java @@ -43,7 +43,7 @@ package org.eclipse.jgit.transport; -import static java.nio.charset.StandardCharsets.UTF_8; +import static org.eclipse.jgit.lib.Constants.CHARSET; import static org.eclipse.jgit.transport.WalkEncryptionTest.Util.cryptoCipherListPBE; import static org.eclipse.jgit.transport.WalkEncryptionTest.Util.cryptoCipherListTrans; import static org.eclipse.jgit.transport.WalkEncryptionTest.Util.folderDelete; @@ -360,7 +360,7 @@ public class WalkEncryptionTest { * @throws Exception */ static String textRead(File file) throws Exception { - return new String(Files.readAllBytes(file.toPath()), UTF_8); + return new String(Files.readAllBytes(file.toPath()), CHARSET); } /** @@ -371,7 +371,7 @@ public class WalkEncryptionTest { * @throws Exception */ static void textWrite(File file, String text) throws Exception { - Files.write(file.toPath(), text.getBytes(UTF_8)); + Files.write(file.toPath(), text.getBytes(CHARSET)); } static void verifyFileContent(File fileOne, File fileTwo) @@ -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."); + } } /** @@ -741,7 +738,7 @@ public class WalkEncryptionTest { AmazonS3 s3 = new AmazonS3(props); String file = JGIT_USER + "-" + UUID.randomUUID().toString(); String path = JGIT_REMOTE_DIR + "/" + file; - s3.put(bucket, path, file.getBytes(UTF_8)); + s3.put(bucket, path, file.getBytes(CHARSET)); s3.delete(bucket, path); } @@ -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()); } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/treewalk/filter/NotTreeFilterTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/treewalk/filter/NotTreeFilterTest.java index f7a7fb8a97..c6389fb1ae 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/treewalk/filter/NotTreeFilterTest.java +++ b/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 { @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 diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/RawSubStringPatternTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/RawSubStringPatternTest.java index e8566d2438..a748b52215 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/RawSubStringPatternTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/RawSubStringPatternTest.java @@ -42,7 +42,7 @@ */ package org.eclipse.jgit.util; -import static java.nio.charset.StandardCharsets.UTF_8; +import static org.eclipse.jgit.lib.Constants.CHARSET; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -93,7 +93,7 @@ public class RawSubStringPatternTest extends RepositoryTestCase { } private static RawCharSequence raw(String text) { - byte[] bytes = text.getBytes(UTF_8); + byte[] bytes = text.getBytes(CHARSET); return new RawCharSequence(bytes, 0, bytes.length); } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/TemporaryBufferTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/TemporaryBufferTest.java index d978804d57..e73dab2ce6 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/TemporaryBufferTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/TemporaryBufferTest.java @@ -61,6 +61,7 @@ import org.junit.Test; public class TemporaryBufferTest { @Test public void testEmpty() throws IOException { + @SuppressWarnings("resource") // Buffer is explicitly destroyed in finally block final TemporaryBuffer b = new TemporaryBuffer.LocalFile(null); try { b.close(); @@ -75,6 +76,7 @@ public class TemporaryBufferTest { @Test public void testOneByte() throws IOException { + @SuppressWarnings("resource") // Buffer is explicitly destroyed in finally block final TemporaryBuffer b = new TemporaryBuffer.LocalFile(null); final byte test = (byte) new TestRng(getName()).nextInt(); try { @@ -87,10 +89,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]); @@ -102,6 +102,7 @@ public class TemporaryBufferTest { @Test public void testOneBlock_BulkWrite() throws IOException { + @SuppressWarnings("resource") // Buffer is explicitly destroyed in finally block final TemporaryBuffer b = new TemporaryBuffer.LocalFile(null); final byte[] test = new TestRng(getName()) .nextBytes(TemporaryBuffer.Block.SZ); @@ -118,10 +119,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); @@ -133,6 +132,7 @@ public class TemporaryBufferTest { @Test public void testOneBlockAndHalf_BulkWrite() throws IOException { + @SuppressWarnings("resource") // Buffer is explicitly destroyed in finally block final TemporaryBuffer b = new TemporaryBuffer.LocalFile(null); final byte[] test = new TestRng(getName()) .nextBytes(TemporaryBuffer.Block.SZ * 3 / 2); @@ -149,10 +149,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); @@ -164,6 +162,7 @@ public class TemporaryBufferTest { @Test public void testOneBlockAndHalf_SingleWrite() throws IOException { + @SuppressWarnings("resource") // Buffer is explicitly destroyed in finally block final TemporaryBuffer b = new TemporaryBuffer.LocalFile(null); final byte[] test = new TestRng(getName()) .nextBytes(TemporaryBuffer.Block.SZ * 3 / 2); @@ -178,10 +177,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); @@ -193,6 +190,7 @@ public class TemporaryBufferTest { @Test public void testOneBlockAndHalf_Copy() throws IOException { + @SuppressWarnings("resource") // Buffer is explicitly destroyed in finally block final TemporaryBuffer b = new TemporaryBuffer.LocalFile(null); final byte[] test = new TestRng(getName()) .nextBytes(TemporaryBuffer.Block.SZ * 3 / 2); @@ -208,10 +206,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); @@ -223,6 +219,7 @@ public class TemporaryBufferTest { @Test public void testLarge_SingleWrite() throws IOException { + @SuppressWarnings("resource") // Buffer is explicitly destroyed in finally block final TemporaryBuffer b = new TemporaryBuffer.LocalFile(null); final byte[] test = new TestRng(getName()) .nextBytes(TemporaryBuffer.DEFAULT_IN_CORE_LIMIT * 3); @@ -236,10 +233,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,18 +248,18 @@ 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 public void testInCoreLimit_SwitchOnAppendByte() throws IOException { + @SuppressWarnings("resource") // Buffer is explicitly destroyed in finally block final TemporaryBuffer b = new TemporaryBuffer.LocalFile(null); final byte[] test = new TestRng(getName()) .nextBytes(TemporaryBuffer.DEFAULT_IN_CORE_LIMIT + 1); @@ -279,10 +274,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); @@ -294,6 +287,7 @@ public class TemporaryBufferTest { @Test public void testInCoreLimit_SwitchBeforeAppendByte() throws IOException { + @SuppressWarnings("resource") // Buffer is explicitly destroyed in finally block final TemporaryBuffer b = new TemporaryBuffer.LocalFile(null); final byte[] test = new TestRng(getName()) .nextBytes(TemporaryBuffer.DEFAULT_IN_CORE_LIMIT * 3); @@ -308,10 +302,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); @@ -323,6 +315,7 @@ public class TemporaryBufferTest { @Test public void testInCoreLimit_SwitchOnCopy() throws IOException { + @SuppressWarnings("resource") // Buffer is explicitly destroyed in finally block final TemporaryBuffer b = new TemporaryBuffer.LocalFile(null); final byte[] test = new TestRng(getName()) .nextBytes(TemporaryBuffer.DEFAULT_IN_CORE_LIMIT * 2); @@ -340,10 +333,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); @@ -355,7 +346,7 @@ public class TemporaryBufferTest { @Test public void testDestroyWhileOpen() throws IOException { - @SuppressWarnings("resource" /* java 7 */) + @SuppressWarnings("resource") // Buffer is explicitly destroyed in finally block final TemporaryBuffer b = new TemporaryBuffer.LocalFile(null); try { b.write(new TestRng(getName()) @@ -367,6 +358,7 @@ public class TemporaryBufferTest { @Test public void testRandomWrites() throws IOException { + @SuppressWarnings("resource") // Buffer is explicitly destroyed in finally block final TemporaryBuffer b = new TemporaryBuffer.LocalFile(null); final TestRng rng = new TestRng(getName()); final int max = TemporaryBuffer.DEFAULT_IN_CORE_LIMIT * 2; @@ -399,10 +391,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); diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/io/AutoCRLFOutputStreamTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/io/AutoCRLFOutputStreamTest.java index a72d33cd51..0655827310 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/io/AutoCRLFOutputStreamTest.java +++ b/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) { 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)); } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/io/AutoLFInputStreamTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/io/AutoLFInputStreamTest.java index 38199d8aaf..5058165802 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/io/AutoLFInputStreamTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/io/AutoLFInputStreamTest.java @@ -44,7 +44,7 @@ package org.eclipse.jgit.util.io; -import static java.nio.charset.StandardCharsets.UTF_8; +import static org.eclipse.jgit.lib.Constants.CHARSET; import static org.junit.Assert.assertEquals; import java.io.ByteArrayInputStream; @@ -97,38 +97,41 @@ public class AutoLFInputStreamTest { private static void test(byte[] input, byte[] expected, boolean detectBinary) throws IOException { - final InputStream bis1 = new ByteArrayInputStream(input); - final InputStream cis1 = new AutoLFInputStream(bis1, detectBinary); - int index1 = 0; - for (int b = cis1.read(); b != -1; b = cis1.read()) { - assertEquals(expected[index1], (byte) b); - index1++; - } - - assertEquals(expected.length, index1); - - for (int bufferSize = 1; bufferSize < 10; bufferSize++) { - final byte[] buffer = new byte[bufferSize]; - final InputStream bis2 = new ByteArrayInputStream(input); - final InputStream cis2 = new AutoLFInputStream(bis2, detectBinary); + try (InputStream bis1 = new ByteArrayInputStream(input); + InputStream cis1 = new AutoLFInputStream(bis1, detectBinary)) { + int index1 = 0; + for (int b = cis1.read(); b != -1; b = cis1.read()) { + assertEquals(expected[index1], (byte) b); + index1++; + } - int read = 0; - for (int readNow = cis2.read(buffer, 0, buffer.length); readNow != -1 - && read < expected.length; readNow = cis2.read(buffer, 0, - buffer.length)) { - for (int index2 = 0; index2 < readNow; index2++) { - assertEquals(expected[read + index2], buffer[index2]); + assertEquals(expected.length, index1); + + for (int bufferSize = 1; bufferSize < 10; bufferSize++) { + final byte[] buffer = new byte[bufferSize]; + try (InputStream bis2 = new ByteArrayInputStream(input); + InputStream cis2 = new AutoLFInputStream(bis2, + detectBinary)) { + + int read = 0; + for (int readNow = cis2.read(buffer, 0, + buffer.length); readNow != -1 + && read < expected.length; readNow = cis2 + .read(buffer, 0, buffer.length)) { + for (int index2 = 0; index2 < readNow; index2++) { + assertEquals(expected[read + index2], + buffer[index2]); + } + read += readNow; + } + + assertEquals(expected.length, read); } - read += readNow; } - - assertEquals(expected.length, read); - cis2.close(); } - cis1.close(); } private static byte[] asBytes(String in) { - return in.getBytes(UTF_8); + return in.getBytes(CHARSET); } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/io/UnionInputStreamTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/io/UnionInputStreamTest.java index 6b5ef7ec64..b824fae9fd 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/io/UnionInputStreamTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/io/UnionInputStreamTest.java @@ -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 diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/sha1/SHA1Test.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/sha1/SHA1Test.java index e6045a91bd..3c612e1bdd 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/sha1/SHA1Test.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/sha1/SHA1Test.java @@ -43,7 +43,7 @@ package org.eclipse.jgit.util.sha1; -import static java.nio.charset.StandardCharsets.UTF_8; +import static org.eclipse.jgit.lib.Constants.CHARSET; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -95,15 +95,15 @@ public class SHA1Test { .fromString("a9993e364706816aba3e25717850c26c9cd0d89d"); MessageDigest m = MessageDigest.getInstance("SHA-1"); - m.update(TEST1.getBytes(UTF_8)); + m.update(TEST1.getBytes(CHARSET)); ObjectId m1 = ObjectId.fromRaw(m.digest()); SHA1 s = SHA1.newInstance(); - s.update(TEST1.getBytes(UTF_8)); + s.update(TEST1.getBytes(CHARSET)); ObjectId s1 = ObjectId.fromRaw(s.digest()); s.reset(); - s.update(TEST1.getBytes(UTF_8)); + s.update(TEST1.getBytes(CHARSET)); ObjectId s2 = s.toObjectId(); assertEquals(m1, s1); @@ -117,15 +117,15 @@ public class SHA1Test { .fromString("84983e441c3bd26ebaae4aa1f95129e5e54670f1"); MessageDigest m = MessageDigest.getInstance("SHA-1"); - m.update(TEST2.getBytes(UTF_8)); + m.update(TEST2.getBytes(CHARSET)); ObjectId m1 = ObjectId.fromRaw(m.digest()); SHA1 s = SHA1.newInstance(); - s.update(TEST2.getBytes(UTF_8)); + s.update(TEST2.getBytes(CHARSET)); ObjectId s1 = ObjectId.fromRaw(s.digest()); s.reset(); - s.update(TEST2.getBytes(UTF_8)); + s.update(TEST2.getBytes(CHARSET)); ObjectId s2 = s.toObjectId(); assertEquals(m1, s1); |