Browse Source

Transport: Implement AutoCloseable

After creating a Transport instance callers should always call
its close() method. Use AutoCloseable to document this idiom
and allow use of try-with-resources.

Change-Id: I0c6ff3e39ebecdd7a028dbcae1856a818937b186
stable-4.3
Shawn Pearce 9 years ago
parent
commit
6b662af76e
  1. 25
      org.eclipse.jgit.http.test/tst/org/eclipse/jgit/http/test/DumbClientDumbServerTest.java
  2. 86
      org.eclipse.jgit.http.test/tst/org/eclipse/jgit/http/test/HttpClientTests.java
  3. 58
      org.eclipse.jgit.http.test/tst/org/eclipse/jgit/http/test/SmartClientSmartServerTest.java
  4. 15
      org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/AtomicPushTest.java
  5. 6
      org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/BundleWriterTest.java
  6. 18
      org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/ReceivePackAdvertiseRefsHookTest.java
  7. 69
      org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/TransportTest.java
  8. 7
      org.eclipse.jgit/src/org/eclipse/jgit/api/FetchCommand.java
  9. 18
      org.eclipse.jgit/src/org/eclipse/jgit/api/LsRemoteCommand.java
  10. 7
      org.eclipse.jgit/src/org/eclipse/jgit/transport/Connection.java
  11. 6
      org.eclipse.jgit/src/org/eclipse/jgit/transport/Transport.java

25
org.eclipse.jgit.http.test/tst/org/eclipse/jgit/http/test/DumbClientDumbServerTest.java

@ -140,8 +140,7 @@ public class DumbClientDumbServerTest extends HttpTestCase {
assertEquals("http", remoteURI.getScheme()); assertEquals("http", remoteURI.getScheme());
Map<String, Ref> map; Map<String, Ref> map;
Transport t = Transport.open(dst, remoteURI); try (Transport t = Transport.open(dst, remoteURI)) {
try {
// I didn't make up these public interface names, I just // I didn't make up these public interface names, I just
// approved them for inclusion into the code base. Sorry. // approved them for inclusion into the code base. Sorry.
// --spearce // --spearce
@ -149,14 +148,9 @@ public class DumbClientDumbServerTest extends HttpTestCase {
assertTrue("isa TransportHttp", t instanceof TransportHttp); assertTrue("isa TransportHttp", t instanceof TransportHttp);
assertTrue("isa HttpTransport", t instanceof HttpTransport); assertTrue("isa HttpTransport", t instanceof HttpTransport);
FetchConnection c = t.openFetch(); try (FetchConnection c = t.openFetch()) {
try {
map = c.getRefsMap(); map = c.getRefsMap();
} finally {
c.close();
} }
} finally {
t.close();
} }
assertNotNull("have map of refs", map); assertNotNull("have map of refs", map);
@ -201,11 +195,8 @@ public class DumbClientDumbServerTest extends HttpTestCase {
Repository dst = createBareRepository(); Repository dst = createBareRepository();
assertFalse(dst.hasObject(A_txt)); assertFalse(dst.hasObject(A_txt));
Transport t = Transport.open(dst, remoteURI); try (Transport t = Transport.open(dst, remoteURI)) {
try {
t.fetch(NullProgressMonitor.INSTANCE, mirror(master)); t.fetch(NullProgressMonitor.INSTANCE, mirror(master));
} finally {
t.close();
} }
assertTrue(dst.hasObject(A_txt)); assertTrue(dst.hasObject(A_txt));
@ -226,11 +217,8 @@ public class DumbClientDumbServerTest extends HttpTestCase {
Repository dst = createBareRepository(); Repository dst = createBareRepository();
assertFalse(dst.hasObject(A_txt)); assertFalse(dst.hasObject(A_txt));
Transport t = Transport.open(dst, remoteURI); try (Transport t = Transport.open(dst, remoteURI)) {
try {
t.fetch(NullProgressMonitor.INSTANCE, mirror(master)); t.fetch(NullProgressMonitor.INSTANCE, mirror(master));
} finally {
t.close();
} }
assertTrue(dst.hasObject(A_txt)); assertTrue(dst.hasObject(A_txt));
@ -265,8 +253,7 @@ public class DumbClientDumbServerTest extends HttpTestCase {
final RevCommit Q = src.commit().create(); final RevCommit Q = src.commit().create();
final Repository db = src.getRepository(); final Repository db = src.getRepository();
Transport t = Transport.open(db, remoteURI); try (Transport t = Transport.open(db, remoteURI)) {
try {
try { try {
t.push(NullProgressMonitor.INSTANCE, push(src, Q)); t.push(NullProgressMonitor.INSTANCE, push(src, Q));
fail("push incorrectly completed against a dumb server"); fail("push incorrectly completed against a dumb server");
@ -274,8 +261,6 @@ public class DumbClientDumbServerTest extends HttpTestCase {
String exp = "remote does not support smart HTTP push"; String exp = "remote does not support smart HTTP push";
assertEquals(exp, nse.getMessage()); assertEquals(exp, nse.getMessage());
} }
} finally {
t.close();
} }
} }
} }

86
org.eclipse.jgit.http.test/tst/org/eclipse/jgit/http/test/HttpClientTests.java

@ -157,8 +157,7 @@ public class HttpClientTests extends HttpTestCase {
public void testRepositoryNotFound_Dumb() throws Exception { public void testRepositoryNotFound_Dumb() throws Exception {
URIish uri = toURIish("/dumb.none/not-found"); URIish uri = toURIish("/dumb.none/not-found");
Repository dst = createBareRepository(); Repository dst = createBareRepository();
Transport t = Transport.open(dst, uri); try (Transport t = Transport.open(dst, uri)) {
try {
try { try {
t.openFetch(); t.openFetch();
fail("connection opened to not found repository"); fail("connection opened to not found repository");
@ -167,8 +166,6 @@ public class HttpClientTests extends HttpTestCase {
+ "/info/refs?service=git-upload-pack not found"; + "/info/refs?service=git-upload-pack not found";
assertEquals(exp, err.getMessage()); assertEquals(exp, err.getMessage());
} }
} finally {
t.close();
} }
} }
@ -176,8 +173,7 @@ public class HttpClientTests extends HttpTestCase {
public void testRepositoryNotFound_Smart() throws Exception { public void testRepositoryNotFound_Smart() throws Exception {
URIish uri = toURIish("/smart.none/not-found"); URIish uri = toURIish("/smart.none/not-found");
Repository dst = createBareRepository(); Repository dst = createBareRepository();
Transport t = Transport.open(dst, uri); try (Transport t = Transport.open(dst, uri)) {
try {
try { try {
t.openFetch(); t.openFetch();
fail("connection opened to not found repository"); fail("connection opened to not found repository");
@ -186,8 +182,6 @@ public class HttpClientTests extends HttpTestCase {
+ "/info/refs?service=git-upload-pack not found"; + "/info/refs?service=git-upload-pack not found";
assertEquals(exp, err.getMessage()); assertEquals(exp, err.getMessage());
} }
} finally {
t.close();
} }
} }
@ -201,16 +195,9 @@ public class HttpClientTests extends HttpTestCase {
Repository dst = createBareRepository(); Repository dst = createBareRepository();
Ref head; Ref head;
Transport t = Transport.open(dst, dumbAuthNoneURI); try (Transport t = Transport.open(dst, dumbAuthNoneURI);
try { FetchConnection c = t.openFetch()) {
FetchConnection c = t.openFetch();
try {
head = c.getRef(Constants.HEAD); head = c.getRef(Constants.HEAD);
} finally {
c.close();
}
} finally {
t.close();
} }
assertNotNull("has " + Constants.HEAD, head); assertNotNull("has " + Constants.HEAD, head);
assertEquals(Q, head.getObjectId()); assertEquals(Q, head.getObjectId());
@ -225,16 +212,9 @@ public class HttpClientTests extends HttpTestCase {
Repository dst = createBareRepository(); Repository dst = createBareRepository();
Ref head; Ref head;
Transport t = Transport.open(dst, dumbAuthNoneURI); try (Transport t = Transport.open(dst, dumbAuthNoneURI);
try { FetchConnection c = t.openFetch()) {
FetchConnection c = t.openFetch();
try {
head = c.getRef(Constants.HEAD); head = c.getRef(Constants.HEAD);
} finally {
c.close();
}
} finally {
t.close();
} }
assertNull("has no " + Constants.HEAD, head); assertNull("has no " + Constants.HEAD, head);
} }
@ -249,16 +229,9 @@ public class HttpClientTests extends HttpTestCase {
Repository dst = createBareRepository(); Repository dst = createBareRepository();
Ref head; Ref head;
Transport t = Transport.open(dst, smartAuthNoneURI); try (Transport t = Transport.open(dst, smartAuthNoneURI);
try { FetchConnection c = t.openFetch()) {
FetchConnection c = t.openFetch();
try {
head = c.getRef(Constants.HEAD); head = c.getRef(Constants.HEAD);
} finally {
c.close();
}
} finally {
t.close();
} }
assertNotNull("has " + Constants.HEAD, head); assertNotNull("has " + Constants.HEAD, head);
assertEquals(Q, head.getObjectId()); assertEquals(Q, head.getObjectId());
@ -268,16 +241,13 @@ public class HttpClientTests extends HttpTestCase {
public void testListRemote_Smart_WithQueryParameters() throws Exception { public void testListRemote_Smart_WithQueryParameters() throws Exception {
URIish myURI = toURIish("/snone/do?r=1&p=test.git"); URIish myURI = toURIish("/snone/do?r=1&p=test.git");
Repository dst = createBareRepository(); Repository dst = createBareRepository();
Transport t = Transport.open(dst, myURI); try (Transport t = Transport.open(dst, myURI)) {
try {
try { try {
t.openFetch(); t.openFetch();
fail("test did not fail to find repository as expected"); fail("test did not fail to find repository as expected");
} catch (NoRemoteRepositoryException err) { } catch (NoRemoteRepositoryException err) {
// expected // expected
} }
} finally {
t.close();
} }
List<AccessEvent> requests = getRequests(); List<AccessEvent> requests = getRequests();
@ -296,8 +266,7 @@ public class HttpClientTests extends HttpTestCase {
@Test @Test
public void testListRemote_Dumb_NeedsAuth() throws Exception { public void testListRemote_Dumb_NeedsAuth() throws Exception {
Repository dst = createBareRepository(); Repository dst = createBareRepository();
Transport t = Transport.open(dst, dumbAuthBasicURI); try (Transport t = Transport.open(dst, dumbAuthBasicURI)) {
try {
try { try {
t.openFetch(); t.openFetch();
fail("connection opened even info/refs needs auth basic"); fail("connection opened even info/refs needs auth basic");
@ -306,23 +275,18 @@ public class HttpClientTests extends HttpTestCase {
+ JGitText.get().noCredentialsProvider; + JGitText.get().noCredentialsProvider;
assertEquals(exp, err.getMessage()); assertEquals(exp, err.getMessage());
} }
} finally {
t.close();
} }
} }
@Test @Test
public void testListRemote_Dumb_Auth() throws Exception { public void testListRemote_Dumb_Auth() throws Exception {
Repository dst = createBareRepository(); Repository dst = createBareRepository();
Transport t = Transport.open(dst, dumbAuthBasicURI); try (Transport t = Transport.open(dst, dumbAuthBasicURI)) {
t.setCredentialsProvider(new UsernamePasswordCredentialsProvider( t.setCredentialsProvider(new UsernamePasswordCredentialsProvider(
AppServer.username, AppServer.password)); AppServer.username, AppServer.password));
try { t.openFetch().close();
t.openFetch();
} finally {
t.close();
} }
t = Transport.open(dst, dumbAuthBasicURI); try (Transport t = Transport.open(dst, dumbAuthBasicURI)) {
t.setCredentialsProvider(new UsernamePasswordCredentialsProvider( t.setCredentialsProvider(new UsernamePasswordCredentialsProvider(
AppServer.username, "")); AppServer.username, ""));
try { try {
@ -332,16 +296,14 @@ public class HttpClientTests extends HttpTestCase {
String exp = dumbAuthBasicURI + ": " String exp = dumbAuthBasicURI + ": "
+ JGitText.get().notAuthorized; + JGitText.get().notAuthorized;
assertEquals(exp, err.getMessage()); assertEquals(exp, err.getMessage());
} finally { }
t.close();
} }
} }
@Test @Test
public void testListRemote_Smart_UploadPackNeedsAuth() throws Exception { public void testListRemote_Smart_UploadPackNeedsAuth() throws Exception {
Repository dst = createBareRepository(); Repository dst = createBareRepository();
Transport t = Transport.open(dst, smartAuthBasicURI); try (Transport t = Transport.open(dst, smartAuthBasicURI)) {
try {
try { try {
t.openFetch(); t.openFetch();
fail("connection opened even though service disabled"); fail("connection opened even though service disabled");
@ -350,8 +312,6 @@ public class HttpClientTests extends HttpTestCase {
+ JGitText.get().noCredentialsProvider; + JGitText.get().noCredentialsProvider;
assertEquals(exp, err.getMessage()); assertEquals(exp, err.getMessage());
} }
} finally {
t.close();
} }
} }
@ -363,8 +323,7 @@ public class HttpClientTests extends HttpTestCase {
cfg.save(); cfg.save();
Repository dst = createBareRepository(); Repository dst = createBareRepository();
Transport t = Transport.open(dst, smartAuthNoneURI); try (Transport t = Transport.open(dst, smartAuthNoneURI)) {
try {
try { try {
t.openFetch(); t.openFetch();
fail("connection opened even though service disabled"); fail("connection opened even though service disabled");
@ -373,24 +332,15 @@ public class HttpClientTests extends HttpTestCase {
+ JGitText.get().serviceNotEnabledNoName; + JGitText.get().serviceNotEnabledNoName;
assertEquals(exp, err.getMessage()); assertEquals(exp, err.getMessage());
} }
} finally {
t.close();
} }
} }
@Test @Test
public void testListRemoteWithoutLocalRepository() throws Exception { public void testListRemoteWithoutLocalRepository() throws Exception {
Transport t = Transport.open(smartAuthNoneURI); try (Transport t = Transport.open(smartAuthNoneURI);
try { FetchConnection c = t.openFetch()) {
FetchConnection c = t.openFetch();
try {
Ref head = c.getRef(Constants.HEAD); Ref head = c.getRef(Constants.HEAD);
assertNotNull(head); assertNotNull(head);
} finally {
c.close();
}
} finally {
t.close();
} }
} }
} }

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

@ -211,8 +211,7 @@ public class SmartClientSmartServerTest extends HttpTestCase {
assertEquals("http", remoteURI.getScheme()); assertEquals("http", remoteURI.getScheme());
Map<String, Ref> map; Map<String, Ref> map;
Transport t = Transport.open(dst, remoteURI); try (Transport t = Transport.open(dst, remoteURI)) {
try {
// I didn't make up these public interface names, I just // I didn't make up these public interface names, I just
// approved them for inclusion into the code base. Sorry. // approved them for inclusion into the code base. Sorry.
// --spearce // --spearce
@ -226,8 +225,6 @@ public class SmartClientSmartServerTest extends HttpTestCase {
} finally { } finally {
c.close(); c.close();
} }
} finally {
t.close();
} }
assertNotNull("have map of refs", map); assertNotNull("have map of refs", map);
@ -257,8 +254,7 @@ public class SmartClientSmartServerTest extends HttpTestCase {
public void testListRemote_BadName() throws IOException, URISyntaxException { public void testListRemote_BadName() throws IOException, URISyntaxException {
Repository dst = createBareRepository(); Repository dst = createBareRepository();
URIish uri = new URIish(this.remoteURI.toString() + ".invalid"); URIish uri = new URIish(this.remoteURI.toString() + ".invalid");
Transport t = Transport.open(dst, uri); try (Transport t = Transport.open(dst, uri)) {
try {
try { try {
t.openFetch(); t.openFetch();
fail("fetch connection opened"); fail("fetch connection opened");
@ -266,8 +262,6 @@ public class SmartClientSmartServerTest extends HttpTestCase {
assertEquals(uri + ": Git repository not found", assertEquals(uri + ": Git repository not found",
notFound.getMessage()); notFound.getMessage());
} }
} finally {
t.close();
} }
List<AccessEvent> requests = getRequests(); List<AccessEvent> requests = getRequests();
@ -288,11 +282,8 @@ public class SmartClientSmartServerTest extends HttpTestCase {
Repository dst = createBareRepository(); Repository dst = createBareRepository();
assertFalse(dst.hasObject(A_txt)); assertFalse(dst.hasObject(A_txt));
Transport t = Transport.open(dst, remoteURI); try (Transport t = Transport.open(dst, remoteURI)) {
try {
t.fetch(NullProgressMonitor.INSTANCE, mirror(master)); t.fetch(NullProgressMonitor.INSTANCE, mirror(master));
} finally {
t.close();
} }
assertTrue(dst.hasObject(A_txt)); assertTrue(dst.hasObject(A_txt));
@ -331,11 +322,8 @@ public class SmartClientSmartServerTest extends HttpTestCase {
// Bootstrap by doing the clone. // Bootstrap by doing the clone.
// //
TestRepository dst = createTestRepository(); TestRepository dst = createTestRepository();
Transport t = Transport.open(dst.getRepository(), remoteURI); try (Transport t = Transport.open(dst.getRepository(), remoteURI)) {
try {
t.fetch(NullProgressMonitor.INSTANCE, mirror(master)); t.fetch(NullProgressMonitor.INSTANCE, mirror(master));
} finally {
t.close();
} }
assertEquals(B, dst.getRepository().exactRef(master).getObjectId()); assertEquals(B, dst.getRepository().exactRef(master).getObjectId());
List<AccessEvent> cloneRequests = getRequests(); List<AccessEvent> cloneRequests = getRequests();
@ -352,11 +340,8 @@ public class SmartClientSmartServerTest extends HttpTestCase {
// Now incrementally update. // Now incrementally update.
// //
t = Transport.open(dst.getRepository(), remoteURI); try (Transport t = Transport.open(dst.getRepository(), remoteURI)) {
try {
t.fetch(NullProgressMonitor.INSTANCE, mirror(master)); t.fetch(NullProgressMonitor.INSTANCE, mirror(master));
} finally {
t.close();
} }
assertEquals(Z, dst.getRepository().exactRef(master).getObjectId()); assertEquals(Z, dst.getRepository().exactRef(master).getObjectId());
@ -394,11 +379,8 @@ public class SmartClientSmartServerTest extends HttpTestCase {
// Bootstrap by doing the clone. // Bootstrap by doing the clone.
// //
TestRepository dst = createTestRepository(); TestRepository dst = createTestRepository();
Transport t = Transport.open(dst.getRepository(), remoteURI); try (Transport t = Transport.open(dst.getRepository(), remoteURI)) {
try {
t.fetch(NullProgressMonitor.INSTANCE, mirror(master)); t.fetch(NullProgressMonitor.INSTANCE, mirror(master));
} finally {
t.close();
} }
assertEquals(B, dst.getRepository().exactRef(master).getObjectId()); assertEquals(B, dst.getRepository().exactRef(master).getObjectId());
List<AccessEvent> cloneRequests = getRequests(); List<AccessEvent> cloneRequests = getRequests();
@ -418,11 +400,8 @@ public class SmartClientSmartServerTest extends HttpTestCase {
// Now incrementally update. // Now incrementally update.
// //
t = Transport.open(dst.getRepository(), remoteURI); try (Transport t = Transport.open(dst.getRepository(), remoteURI)) {
try {
t.fetch(NullProgressMonitor.INSTANCE, mirror(master)); t.fetch(NullProgressMonitor.INSTANCE, mirror(master));
} finally {
t.close();
} }
assertEquals(Z, dst.getRepository().exactRef(master).getObjectId()); assertEquals(Z, dst.getRepository().exactRef(master).getObjectId());
@ -474,8 +453,7 @@ public class SmartClientSmartServerTest extends HttpTestCase {
Repository dst = createBareRepository(); Repository dst = createBareRepository();
assertFalse(dst.hasObject(A_txt)); assertFalse(dst.hasObject(A_txt));
Transport t = Transport.open(dst, brokenURI); try (Transport t = Transport.open(dst, brokenURI)) {
try {
try { try {
t.fetch(NullProgressMonitor.INSTANCE, mirror(master)); t.fetch(NullProgressMonitor.INSTANCE, mirror(master));
fail("fetch completed despite upload-pack being broken"); fail("fetch completed despite upload-pack being broken");
@ -485,8 +463,6 @@ public class SmartClientSmartServerTest extends HttpTestCase {
+ " received Content-Type text/plain; charset=UTF-8"; + " received Content-Type text/plain; charset=UTF-8";
assertEquals(exp, err.getMessage()); assertEquals(exp, err.getMessage());
} }
} finally {
t.close();
} }
List<AccessEvent> requests = getRequests(); List<AccessEvent> requests = getRequests();
@ -517,12 +493,10 @@ public class SmartClientSmartServerTest extends HttpTestCase {
final RevCommit Q = src.commit().add("Q", Q_txt).create(); final RevCommit Q = src.commit().add("Q", Q_txt).create();
final Repository db = src.getRepository(); final Repository db = src.getRepository();
final String dstName = Constants.R_HEADS + "new.branch"; final String dstName = Constants.R_HEADS + "new.branch";
Transport t;
// push anonymous shouldn't be allowed. // push anonymous shouldn't be allowed.
// //
t = Transport.open(db, remoteURI); try (Transport t = Transport.open(db, remoteURI)) {
try {
final String srcExpr = Q.name(); final String srcExpr = Q.name();
final boolean forceUpdate = false; final boolean forceUpdate = false;
final String localName = null; final String localName = null;
@ -538,8 +512,6 @@ public class SmartClientSmartServerTest extends HttpTestCase {
+ JGitText.get().authenticationNotSupported; + JGitText.get().authenticationNotSupported;
assertEquals(exp, e.getMessage()); assertEquals(exp, e.getMessage());
} }
} finally {
t.close();
} }
List<AccessEvent> requests = getRequests(); List<AccessEvent> requests = getRequests();
@ -560,12 +532,10 @@ public class SmartClientSmartServerTest extends HttpTestCase {
final RevCommit Q = src.commit().add("Q", Q_txt).create(); final RevCommit Q = src.commit().add("Q", Q_txt).create();
final Repository db = src.getRepository(); final Repository db = src.getRepository();
final String dstName = Constants.R_HEADS + "new.branch"; final String dstName = Constants.R_HEADS + "new.branch";
Transport t;
enableReceivePack(); enableReceivePack();
t = Transport.open(db, remoteURI); try (Transport t = Transport.open(db, remoteURI)) {
try {
final String srcExpr = Q.name(); final String srcExpr = Q.name();
final boolean forceUpdate = false; final boolean forceUpdate = false;
final String localName = null; final String localName = null;
@ -574,8 +544,6 @@ public class SmartClientSmartServerTest extends HttpTestCase {
RemoteRefUpdate u = new RemoteRefUpdate(src.getRepository(), RemoteRefUpdate u = new RemoteRefUpdate(src.getRepository(),
srcExpr, dstName, forceUpdate, localName, oldId); srcExpr, dstName, forceUpdate, localName, oldId);
t.push(NullProgressMonitor.INSTANCE, Collections.singleton(u)); t.push(NullProgressMonitor.INSTANCE, Collections.singleton(u));
} finally {
t.close();
} }
assertTrue(remoteRepository.hasObject(Q_txt)); assertTrue(remoteRepository.hasObject(Q_txt));
@ -633,7 +601,6 @@ public class SmartClientSmartServerTest extends HttpTestCase {
final RevCommit Q = src.commit().add("Q", Q_bin).create(); final RevCommit Q = src.commit().add("Q", Q_bin).create();
final Repository db = src.getRepository(); final Repository db = src.getRepository();
final String dstName = Constants.R_HEADS + "new.branch"; final String dstName = Constants.R_HEADS + "new.branch";
Transport t;
enableReceivePack(); enableReceivePack();
@ -642,8 +609,7 @@ public class SmartClientSmartServerTest extends HttpTestCase {
cfg.setInt("http", null, "postbuffer", 8 * 1024); cfg.setInt("http", null, "postbuffer", 8 * 1024);
cfg.save(); cfg.save();
t = Transport.open(db, remoteURI); try (Transport t = Transport.open(db, remoteURI)) {
try {
final String srcExpr = Q.name(); final String srcExpr = Q.name();
final boolean forceUpdate = false; final boolean forceUpdate = false;
final String localName = null; final String localName = null;
@ -652,8 +618,6 @@ public class SmartClientSmartServerTest extends HttpTestCase {
RemoteRefUpdate u = new RemoteRefUpdate(src.getRepository(), RemoteRefUpdate u = new RemoteRefUpdate(src.getRepository(),
srcExpr, dstName, forceUpdate, localName, oldId); srcExpr, dstName, forceUpdate, localName, oldId);
t.push(NullProgressMonitor.INSTANCE, Collections.singleton(u)); t.push(NullProgressMonitor.INSTANCE, Collections.singleton(u));
} finally {
t.close();
} }
assertTrue(remoteRepository.hasObject(Q_bin)); assertTrue(remoteRepository.hasObject(Q_bin));

15
org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/AtomicPushTest.java

@ -112,12 +112,9 @@ public class AtomicPushTest {
public void pushNonAtomic() throws Exception { public void pushNonAtomic() throws Exception {
PushResult r; PushResult r;
server.setPerformsAtomicTransactions(false); server.setPerformsAtomicTransactions(false);
Transport tn = testProtocol.open(uri, client, "server"); try (Transport tn = testProtocol.open(uri, client, "server")) {
try {
tn.setPushAtomic(false); tn.setPushAtomic(false);
r = tn.push(NullProgressMonitor.INSTANCE, commands()); r = tn.push(NullProgressMonitor.INSTANCE, commands());
} finally {
tn.close();
} }
RemoteRefUpdate one = r.getRemoteUpdate("refs/heads/one"); RemoteRefUpdate one = r.getRemoteUpdate("refs/heads/one");
@ -131,12 +128,9 @@ public class AtomicPushTest {
@Test @Test
public void pushAtomicClientGivesUpEarly() throws Exception { public void pushAtomicClientGivesUpEarly() throws Exception {
PushResult r; PushResult r;
Transport tn = testProtocol.open(uri, client, "server"); try (Transport tn = testProtocol.open(uri, client, "server")) {
try {
tn.setPushAtomic(true); tn.setPushAtomic(true);
r = tn.push(NullProgressMonitor.INSTANCE, commands()); r = tn.push(NullProgressMonitor.INSTANCE, commands());
} finally {
tn.close();
} }
RemoteRefUpdate one = r.getRemoteUpdate("refs/heads/one"); RemoteRefUpdate one = r.getRemoteUpdate("refs/heads/one");
@ -167,8 +161,7 @@ public class AtomicPushTest {
ObjectId.zeroId())); ObjectId.zeroId()));
server.setPerformsAtomicTransactions(false); server.setPerformsAtomicTransactions(false);
Transport tn = testProtocol.open(uri, client, "server"); try (Transport tn = testProtocol.open(uri, client, "server")) {
try {
tn.setPushAtomic(true); tn.setPushAtomic(true);
tn.push(NullProgressMonitor.INSTANCE, cmds); tn.push(NullProgressMonitor.INSTANCE, cmds);
fail("did not throw TransportException"); fail("did not throw TransportException");
@ -176,8 +169,6 @@ public class AtomicPushTest {
assertEquals( assertEquals(
uri + ": " + JGitText.get().atomicPushNotSupported, uri + ": " + JGitText.get().atomicPushNotSupported,
e.getMessage()); e.getMessage());
} finally {
tn.close();
} }
} }

6
org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/BundleWriterTest.java

@ -166,8 +166,10 @@ public class BundleWriterTest extends SampleDataRepositoryTestCase {
final ByteArrayInputStream in = new ByteArrayInputStream(bundle); final ByteArrayInputStream in = new ByteArrayInputStream(bundle);
final RefSpec rs = new RefSpec("refs/heads/*:refs/heads/*"); final RefSpec rs = new RefSpec("refs/heads/*:refs/heads/*");
final Set<RefSpec> refs = Collections.singleton(rs); final Set<RefSpec> refs = Collections.singleton(rs);
return new TransportBundleStream(newRepo, uri, in).fetch( try (TransportBundleStream transport = new TransportBundleStream(
NullProgressMonitor.INSTANCE, refs); newRepo, uri, in)) {
return transport.fetch(NullProgressMonitor.INSTANCE, refs);
}
} }
private byte[] makeBundle(final String name, private byte[] makeBundle(final String name,

18
org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/ReceivePackAdvertiseRefsHookTest.java

@ -116,12 +116,9 @@ public class ReceivePackAdvertiseRefsHookTest extends LocalDiskRepositoryTestCas
// Clone from dst into src // Clone from dst into src
// //
Transport t = Transport.open(src, uriOf(dst)); try (Transport t = Transport.open(src, uriOf(dst))) {
try {
t.fetch(PM, Collections.singleton(new RefSpec("+refs/*:refs/*"))); t.fetch(PM, Collections.singleton(new RefSpec("+refs/*:refs/*")));
assertEquals(B, src.resolve(R_MASTER)); assertEquals(B, src.resolve(R_MASTER));
} finally {
t.close();
} }
// Now put private stuff into dst. // Now put private stuff into dst.
@ -144,7 +141,8 @@ public class ReceivePackAdvertiseRefsHookTest extends LocalDiskRepositoryTestCas
@Test @Test
public void testFilterHidesPrivate() throws Exception { public void testFilterHidesPrivate() throws Exception {
Map<String, Ref> refs; Map<String, Ref> refs;
TransportLocal t = new TransportLocal(src, uriOf(dst), dst.getDirectory()) { try (TransportLocal t = new TransportLocal(src, uriOf(dst),
dst.getDirectory()) {
@Override @Override
ReceivePack createReceivePack(final Repository db) { ReceivePack createReceivePack(final Repository db) {
db.close(); db.close();
@ -154,16 +152,10 @@ public class ReceivePackAdvertiseRefsHookTest extends LocalDiskRepositoryTestCas
rp.setAdvertiseRefsHook(new HidePrivateHook()); rp.setAdvertiseRefsHook(new HidePrivateHook());
return rp; return rp;
} }
}; }) {
try { try (PushConnection c = t.openPush()) {
PushConnection c = t.openPush();
try {
refs = c.getRefsMap(); refs = c.getRefsMap();
} finally {
c.close();
} }
} finally {
t.close();
} }
assertNotNull(refs); assertNotNull(refs);

69
org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/TransportTest.java

@ -61,13 +61,10 @@ import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.test.resources.SampleDataRepositoryTestCase; import org.eclipse.jgit.test.resources.SampleDataRepositoryTestCase;
import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
public class TransportTest extends SampleDataRepositoryTestCase { public class TransportTest extends SampleDataRepositoryTestCase {
private Transport transport;
private RemoteConfig remoteConfig; private RemoteConfig remoteConfig;
@Override @Override
@ -77,17 +74,6 @@ public class TransportTest extends SampleDataRepositoryTestCase {
final Config config = db.getConfig(); final Config config = db.getConfig();
remoteConfig = new RemoteConfig(config, "test"); remoteConfig = new RemoteConfig(config, "test");
remoteConfig.addURI(new URIish("http://everyones.loves.git/u/2")); remoteConfig.addURI(new URIish("http://everyones.loves.git/u/2"));
transport = null;
}
@Override
@After
public void tearDown() throws Exception {
if (transport != null) {
transport.close();
transport = null;
}
super.tearDown();
} }
/** /**
@ -99,10 +85,11 @@ public class TransportTest extends SampleDataRepositoryTestCase {
@Test @Test
public void testFindRemoteRefUpdatesNoWildcardNoTracking() public void testFindRemoteRefUpdatesNoWildcardNoTracking()
throws IOException { throws IOException {
transport = Transport.open(db, remoteConfig); Collection<RemoteRefUpdate> result;
final Collection<RemoteRefUpdate> result = transport try (Transport transport = Transport.open(db, remoteConfig)) {
.findRemoteRefUpdatesFor(Collections.nCopies(1, new RefSpec( result = transport.findRemoteRefUpdatesFor(Collections.nCopies(1,
"refs/heads/master:refs/heads/x"))); new RefSpec("refs/heads/master:refs/heads/x")));
}
assertEquals(1, result.size()); assertEquals(1, result.size());
final RemoteRefUpdate rru = result.iterator().next(); final RemoteRefUpdate rru = result.iterator().next();
@ -122,10 +109,11 @@ public class TransportTest extends SampleDataRepositoryTestCase {
@Test @Test
public void testFindRemoteRefUpdatesNoWildcardNoDestination() public void testFindRemoteRefUpdatesNoWildcardNoDestination()
throws IOException { throws IOException {
transport = Transport.open(db, remoteConfig); Collection<RemoteRefUpdate> result;
final Collection<RemoteRefUpdate> result = transport try (Transport transport = Transport.open(db, remoteConfig)) {
.findRemoteRefUpdatesFor(Collections.nCopies(1, new RefSpec( result = transport.findRemoteRefUpdatesFor(
"+refs/heads/master"))); Collections.nCopies(1, new RefSpec("+refs/heads/master")));
}
assertEquals(1, result.size()); assertEquals(1, result.size());
final RemoteRefUpdate rru = result.iterator().next(); final RemoteRefUpdate rru = result.iterator().next();
@ -143,10 +131,11 @@ public class TransportTest extends SampleDataRepositoryTestCase {
*/ */
@Test @Test
public void testFindRemoteRefUpdatesWildcardNoTracking() throws IOException { public void testFindRemoteRefUpdatesWildcardNoTracking() throws IOException {
transport = Transport.open(db, remoteConfig); Collection<RemoteRefUpdate> result;
final Collection<RemoteRefUpdate> result = transport try (Transport transport = Transport.open(db, remoteConfig)) {
.findRemoteRefUpdatesFor(Collections.nCopies(1, new RefSpec( result = transport.findRemoteRefUpdatesFor(Collections.nCopies(1,
"+refs/heads/*:refs/heads/test/*"))); new RefSpec("+refs/heads/*:refs/heads/test/*")));
}
assertEquals(12, result.size()); assertEquals(12, result.size());
boolean foundA = false; boolean foundA = false;
@ -171,12 +160,14 @@ public class TransportTest extends SampleDataRepositoryTestCase {
*/ */
@Test @Test
public void testFindRemoteRefUpdatesTwoRefSpecs() throws IOException { public void testFindRemoteRefUpdatesTwoRefSpecs() throws IOException {
transport = Transport.open(db, remoteConfig);
final RefSpec specA = new RefSpec("+refs/heads/a:refs/heads/b"); final RefSpec specA = new RefSpec("+refs/heads/a:refs/heads/b");
final RefSpec specC = new RefSpec("+refs/heads/c:refs/heads/d"); final RefSpec specC = new RefSpec("+refs/heads/c:refs/heads/d");
final Collection<RefSpec> specs = Arrays.asList(specA, specC); final Collection<RefSpec> specs = Arrays.asList(specA, specC);
final Collection<RemoteRefUpdate> result = transport
.findRemoteRefUpdatesFor(specs); Collection<RemoteRefUpdate> result;
try (Transport transport = Transport.open(db, remoteConfig)) {
result = transport.findRemoteRefUpdatesFor(specs);
}
assertEquals(2, result.size()); assertEquals(2, result.size());
boolean foundA = false; boolean foundA = false;
@ -202,10 +193,12 @@ public class TransportTest extends SampleDataRepositoryTestCase {
public void testFindRemoteRefUpdatesTrackingRef() throws IOException { public void testFindRemoteRefUpdatesTrackingRef() throws IOException {
remoteConfig.addFetchRefSpec(new RefSpec( remoteConfig.addFetchRefSpec(new RefSpec(
"refs/heads/*:refs/remotes/test/*")); "refs/heads/*:refs/remotes/test/*"));
transport = Transport.open(db, remoteConfig);
final Collection<RemoteRefUpdate> result = transport Collection<RemoteRefUpdate> result;
.findRemoteRefUpdatesFor(Collections.nCopies(1, new RefSpec( try (Transport transport = Transport.open(db, remoteConfig)) {
"+refs/heads/a:refs/heads/a"))); result = transport.findRemoteRefUpdatesFor(Collections.nCopies(1,
new RefSpec("+refs/heads/a:refs/heads/a")));
}
assertEquals(1, result.size()); assertEquals(1, result.size());
final TrackingRefUpdate tru = result.iterator().next() final TrackingRefUpdate tru = result.iterator().next()
@ -225,20 +218,18 @@ public class TransportTest extends SampleDataRepositoryTestCase {
config.addURI(new URIish("../" + otherDir)); config.addURI(new URIish("../" + otherDir));
// Should not throw NoRemoteRepositoryException // Should not throw NoRemoteRepositoryException
transport = Transport.open(db, config); Transport.open(db, config).close();
} }
@Test @Test
public void testLocalTransportFetchWithoutLocalRepository() public void testLocalTransportFetchWithoutLocalRepository()
throws Exception { throws Exception {
URIish uri = new URIish("file://" + db.getWorkTree().getAbsolutePath()); URIish uri = new URIish("file://" + db.getWorkTree().getAbsolutePath());
transport = Transport.open(uri); try (Transport transport = Transport.open(uri)) {
FetchConnection fetchConnection = transport.openFetch(); try (FetchConnection fetchConnection = transport.openFetch()) {
try {
Ref head = fetchConnection.getRef(Constants.HEAD); Ref head = fetchConnection.getRef(Constants.HEAD);
assertNotNull(head); assertNotNull(head);
} finally { }
fetchConnection.close();
} }
} }

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

@ -116,9 +116,7 @@ public class FetchCommand extends TransportCommand<FetchCommand, FetchResult> {
org.eclipse.jgit.api.errors.TransportException { org.eclipse.jgit.api.errors.TransportException {
checkCallable(); checkCallable();
try { try (Transport transport = Transport.open(repo, remote)) {
Transport transport = Transport.open(repo, remote);
try {
transport.setCheckFetchedObjects(checkFetchedObjects); transport.setCheckFetchedObjects(checkFetchedObjects);
transport.setRemoveDeletedRefs(isRemoveDeletedRefs()); transport.setRemoveDeletedRefs(isRemoveDeletedRefs());
transport.setDryRun(dryRun); transport.setDryRun(dryRun);
@ -129,9 +127,6 @@ public class FetchCommand extends TransportCommand<FetchCommand, FetchResult> {
FetchResult result = transport.fetch(monitor, refSpecs); FetchResult result = transport.fetch(monitor, refSpecs);
return result; return result;
} finally {
transport.close();
}
} catch (NoRemoteRepositoryException e) { } catch (NoRemoteRepositoryException e) {
throw new InvalidRemoteException(MessageFormat.format( throw new InvalidRemoteException(MessageFormat.format(
JGitText.get().invalidRemote, remote), e); JGitText.get().invalidRemote, remote), e);

18
org.eclipse.jgit/src/org/eclipse/jgit/api/LsRemoteCommand.java

@ -182,13 +182,9 @@ public class LsRemoteCommand extends
org.eclipse.jgit.api.errors.TransportException { org.eclipse.jgit.api.errors.TransportException {
checkCallable(); checkCallable();
Transport transport = null; try (Transport transport = repo != null
FetchConnection fc = null; ? Transport.open(repo, remote)
try { : Transport.open(new URIish(remote))) {
if (repo != null)
transport = Transport.open(repo, remote);
else
transport = Transport.open(new URIish(remote));
transport.setOptionUploadPack(uploadPack); transport.setOptionUploadPack(uploadPack);
configure(transport); configure(transport);
Collection<RefSpec> refSpecs = new ArrayList<RefSpec>(1); Collection<RefSpec> refSpecs = new ArrayList<RefSpec>(1);
@ -199,7 +195,7 @@ public class LsRemoteCommand extends
refSpecs.add(new RefSpec("refs/heads/*:refs/remotes/origin/*")); //$NON-NLS-1$ refSpecs.add(new RefSpec("refs/heads/*:refs/remotes/origin/*")); //$NON-NLS-1$
Collection<Ref> refs; Collection<Ref> refs;
Map<String, Ref> refmap = new HashMap<String, Ref>(); Map<String, Ref> refmap = new HashMap<String, Ref>();
fc = transport.openFetch(); try (FetchConnection fc = transport.openFetch()) {
refs = fc.getRefs(); refs = fc.getRefs();
if (refSpecs.isEmpty()) if (refSpecs.isEmpty())
for (Ref r : refs) for (Ref r : refs)
@ -212,6 +208,7 @@ public class LsRemoteCommand extends
break; break;
} }
return refmap; return refmap;
}
} catch (URISyntaxException e) { } catch (URISyntaxException e) {
throw new InvalidRemoteException(MessageFormat.format( throw new InvalidRemoteException(MessageFormat.format(
JGitText.get().invalidRemote, remote)); JGitText.get().invalidRemote, remote));
@ -223,11 +220,6 @@ public class LsRemoteCommand extends
throw new org.eclipse.jgit.api.errors.TransportException( throw new org.eclipse.jgit.api.errors.TransportException(
e.getMessage(), e.getMessage(),
e); e);
} finally {
if (fc != null)
fc.close();
if (transport != null)
transport.close();
} }
} }

7
org.eclipse.jgit/src/org/eclipse/jgit/transport/Connection.java

@ -59,8 +59,7 @@ import org.eclipse.jgit.lib.Ref;
* *
* @see Transport * @see Transport
*/ */
public interface Connection { public interface Connection extends AutoCloseable {
/** /**
* Get the complete map of refs advertised as available for fetching or * Get the complete map of refs advertised as available for fetching or
* pushing. * pushing.
@ -108,6 +107,10 @@ public interface Connection {
* <p> * <p>
* If additional messages were produced by the remote peer, these should * If additional messages were produced by the remote peer, these should
* still be retained in the connection instance for {@link #getMessages()}. * still be retained in the connection instance for {@link #getMessages()}.
* <p>
* {@code AutoClosable.close()} declares that it throws {@link Exception}.
* Implementers shouldn't throw checked exceptions. This override narrows
* the signature to prevent them from doing so.
*/ */
public void close(); public void close();

6
org.eclipse.jgit/src/org/eclipse/jgit/transport/Transport.java

@ -98,7 +98,7 @@ import org.eclipse.jgit.storage.pack.PackConfig;
* Transport instances and the connections they create are not thread-safe. * Transport instances and the connections they create are not thread-safe.
* Callers must ensure a transport is accessed by only one thread at a time. * Callers must ensure a transport is accessed by only one thread at a time.
*/ */
public abstract class Transport { public abstract class Transport implements AutoCloseable {
/** Type of operation a Transport is being opened for. */ /** Type of operation a Transport is being opened for. */
public enum Operation { public enum Operation {
/** Transport is to fetch objects locally. */ /** Transport is to fetch objects locally. */
@ -1353,6 +1353,10 @@ public abstract class Transport {
* must close that network socket, disconnecting the two peers. If the * must close that network socket, disconnecting the two peers. If the
* remote repository is actually local (same system) this method must close * remote repository is actually local (same system) this method must close
* any open file handles used to read the "remote" repository. * any open file handles used to read the "remote" repository.
* <p>
* {@code AutoClosable.close()} declares that it throws {@link Exception}.
* Implementers shouldn't throw checked exceptions. This override narrows
* the signature to prevent them from doing so.
*/ */
public abstract void close(); public abstract void close();
} }

Loading…
Cancel
Save