类org.eclipse.jgit.transport.Transport源码实例Demo

下面列出了怎么用org.eclipse.jgit.transport.Transport的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: netbeans   文件: TransportCommand.java
protected Transport openTransport (boolean openPush) throws URISyntaxException, NotSupportedException, TransportException {
    URIish uri = getUriWithUsername(openPush);
    // WA for #200693, jgit fails to initialize ftp protocol
    for (TransportProtocol proto : Transport.getTransportProtocols()) {
        if (proto.getSchemes().contains("ftp")) { //NOI18N
            Transport.unregister(proto);
        }
    }
    try {
        Transport transport = Transport.open(getRepository(), uri);
        RemoteConfig config = getRemoteConfig();
        if (config != null) {
            transport.applyConfig(config);
        }
        if (transport.getTimeout() <= 0) {
            transport.setTimeout(45);
        }
        transport.setCredentialsProvider(getCredentialsProvider());
        return transport;
    } catch (IllegalArgumentException ex) {
        throw new TransportException(ex.getLocalizedMessage(), ex);
    }
}
 
源代码2 项目: git-client-plugin   文件: JGitAPIImpl.java
/** {@inheritDoc} */
@Override
@SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE", justification = "Java 11 spotbugs error")
public ObjectId getHeadRev(String remoteRepoUrl, String branchSpec) throws GitException {
    try (Repository repo = openDummyRepository();
         final Transport tn = Transport.open(repo, new URIish(remoteRepoUrl))) {
        final String branchName = extractBranchNameFromBranchSpec(branchSpec);
        String regexBranch = createRefRegexFromGlob(branchName);

        tn.setCredentialsProvider(getProvider());
        try (FetchConnection c = tn.openFetch()) {
            for (final Ref r : c.getRefs()) {
                if (r.getName().matches(regexBranch)) {
                    return r.getPeeledObjectId() != null ? r.getPeeledObjectId() : r.getObjectId();
                }
            }
        }
    } catch (IOException | URISyntaxException | IllegalStateException e) {
        throw new GitException(e);
    }
    return null;
}
 
源代码3 项目: git-client-plugin   文件: JGitAPIImpl.java
@SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE", justification = "Java 11 spotbugs error")
private Set<String> listRemoteBranches(String remote) throws NotSupportedException, TransportException, URISyntaxException {
    Set<String> branches = new HashSet<>();
    try (final Repository repo = getRepository()) {
        StoredConfig config = repo.getConfig();
        try (final Transport tn = Transport.open(repo, new URIish(config.getString("remote",remote,"url")))) {
            tn.setCredentialsProvider(getProvider());
            try (final FetchConnection c = tn.openFetch()) {
                for (final Ref r : c.getRefs()) {
                    if (r.getName().startsWith(R_HEADS))
                        branches.add("refs/remotes/"+remote+"/"+r.getName().substring(R_HEADS.length()));
                }
            }
        }
    }
    return branches;
}
 
源代码4 项目: Jpom   文件: TestSshGit.java
public static void main(String[] args) throws GitAPIException {
    Git.cloneRepository()
            .setURI("[email protected]:jiangzeyin/test.git")
            .setDirectory(new File("D:\\test\\gitssh"))
            .setTransportConfigCallback(new TransportConfigCallback() {
                @Override
                public void configure(Transport transport) {
                    SshTransport sshTransport = (SshTransport) transport;
                    sshTransport.setSshSessionFactory(new JschConfigSessionFactory() {
                        @Override
                        protected void configure(OpenSshConfig.Host hc, Session session) {
                            session.setConfig("StrictHostKeyChecking", "no");
                            session.setPassword("");
                        }

                        @Override
                        protected JSch createDefaultJSch(FS fs) throws JSchException {
                            JSch defaultJSch = super.createDefaultJSch(fs);

                            defaultJSch.addIdentity("C:\\Users\\Colorful\\.ssh\\id_rsa.pub");
                            return defaultJSch;
                        }

                    });
                }
            })
            .call();
}
 
源代码5 项目: netbeans   文件: BranchTest.java
public void testFileProtocolFails () throws Exception {
    try {
        Transport.open(repository, new URIish(workDir.toURI().toURL()));
        fail("Workaround not needed, fix ListRemoteBranchesCommand - Transport.open(String) to Transport.open(URL)");
    } catch (NotSupportedException ex) {
        
    }
}
 
源代码6 项目: netbeans   文件: ProtocolsTestSuite.java
public void testFtpProtocol () throws Exception {
    Transport t = Transport.open(repository, new URIish("ftp://ftphost/abc"));
    try {
        t.openFetch();
        fail("JGit ftp support fixed, fix #200693 workaround");
        // ftp support fixed, wa in TransportCommand.openTransport should be removed 
    } catch (ClassCastException ex) {
        // jgit has a bug that prevents from using ftp protocol
    }
}
 
@Override
public void configure(Transport transport) {
	if (transport instanceof TransportHttp && canHandle(transport.getURI())) {
		addHeaders((TransportHttp) transport,
				credentialsProvider.getAuthorizationHeaders());
	}
}
 
@Override
public void configure(Transport transport) {
	SshSessionFactory.setInstance(new JschConfigSessionFactory() {
		@Override
		protected void configure(OpenSshConfig.Host hc, Session session) {
			session.setConfig("StrictHostKeyChecking",
					FileBasedSshTransportConfigCallback.this.sshUriProperties
							.isStrictHostKeyChecking() ? "yes" : "no");
		}
	});
}
 
@Override
public void configure(Transport transport) {
	if (transport instanceof SshTransport) {
		SshTransport sshTransport = (SshTransport) transport;
		sshTransport.setSshSessionFactory(new PropertyBasedSshSessionFactory(
				new SshUriPropertyProcessor(this.sshUriProperties)
						.getSshKeysByHostname(),
				new JSch()));
	}
}
 
@Test
public void verifyDoesNothingForNonHttpTransports() throws URISyntaxException {
	TransportConfigCallback callback = transportConfigCallbackWith(
			createAuthHeaders());
	Transport transport = mockSshTransport(SSH_GOOGLE_CLOUD_SOURCE_REPO);

	callback.configure(transport);

	verifyOnlyValidInteraction(transport);
}
 
private void verifyOnlyValidInteraction(Transport transport) {
	// Actually, we don't care how often getURI() was invoked, simply "allow"
	// invocation of getURI(), so verifyNoMoreInteractions() won't complain
	// about getURI().
	verify(transport, atMost(10000)).getURI();

	verifyNoMoreInteractions(transport);
}
 
@SuppressWarnings("SameParameterValue")
private Transport mockSshTransport(String uri) throws URISyntaxException {
	Transport transport = Mockito.mock(SshTransport.class);

	when(transport.getURI()).thenReturn(new URIish(uri));

	return transport;
}
 
源代码13 项目: studio   文件: GitContentRepository.java
private boolean isRemoteValid(Git git, String remote, String authenticationType,
                              String remoteUsername, String remotePassword, String remoteToken,
                              String remotePrivateKey)
        throws CryptoException, IOException, ServiceLayerException, GitAPIException {
    LsRemoteCommand lsRemoteCommand = git.lsRemote();
    lsRemoteCommand.setRemote(remote);
    switch (authenticationType) {
        case NONE:
            logger.debug("No authentication");
            break;
        case BASIC:
            logger.debug("Basic authentication");
            lsRemoteCommand.setCredentialsProvider(
                    new UsernamePasswordCredentialsProvider(remoteUsername, remotePassword));
            break;
        case TOKEN:
            logger.debug("Token based authentication");
            lsRemoteCommand.setCredentialsProvider(
                    new UsernamePasswordCredentialsProvider(remoteToken, EMPTY));
            break;
        case PRIVATE_KEY:
            logger.debug("Private key authentication");
            final Path tempKey = Files.createTempFile(UUID.randomUUID().toString(), ".tmp");
            tempKey.toFile().deleteOnExit();
            lsRemoteCommand.setTransportConfigCallback(
                    new TransportConfigCallback() {
                        @Override
                        public void configure(Transport transport) {
                            SshTransport sshTransport = (SshTransport) transport;
                            sshTransport.setSshSessionFactory(getSshSessionFactory(remotePrivateKey, tempKey));
                        }
                    });
            Files.delete(tempKey);
            break;
        default:
            throw new ServiceLayerException("Unsupported authentication type " + authenticationType);
    }
    lsRemoteCommand.call();
    return true;
}
 
源代码14 项目: milkman   文件: JGitUtil.java
@Override
public void configure(Transport transport) {
    SshTransport sshTransport = (SshTransport) transport;
    sshTransport.setSshSessionFactory(SshdSessionFactory.getInstance());
}
 
源代码15 项目: netbeans   文件: PushTest.java
public void testPushRejectNonFastForward () throws Exception {
    String remoteUri = getRemoteRepository().getWorkTree().toURI().toString();
    assertEquals(0, getClient(workDir).listRemoteBranches(remoteUri, NULL_PROGRESS_MONITOR).size());
    File f = new File(workDir, "f");
    add(f);
    String id = getClient(workDir).commit(new File[] { f }, "bbb", null, null, NULL_PROGRESS_MONITOR).getRevision();
    Map<String, GitTransportUpdate> updates = getClient(workDir).push(remoteUri, Arrays.asList(new String[] { "refs/heads/master:refs/heads/master" }), Collections.<String>emptyList(), NULL_PROGRESS_MONITOR).getRemoteRepositoryUpdates();
    Map<String, GitBranch> remoteBranches = getClient(workDir).listRemoteBranches(remoteUri, NULL_PROGRESS_MONITOR);
    assertEquals(1, remoteBranches.size());
    assertEquals(id, remoteBranches.get("master").getId());
    assertEquals(1, updates.size());
    assertUpdate(updates.get("master"), "master", "master", id, null, new URIish(remoteUri).toString(), Type.BRANCH, GitRefUpdateResult.OK);

    // modification
    write(f, "huhu");
    add(f);
    String newid = getClient(workDir).commit(new File[] { f }, "bbb", null, null, NULL_PROGRESS_MONITOR).getRevision();
    updates = getClient(workDir).push(remoteUri, Arrays.asList(new String[] { "refs/heads/master:refs/heads/master" }), Collections.<String>emptyList(), NULL_PROGRESS_MONITOR).getRemoteRepositoryUpdates();
    remoteBranches = getClient(workDir).listRemoteBranches(remoteUri, NULL_PROGRESS_MONITOR);
    assertEquals(1, remoteBranches.size());
    assertEquals(newid, remoteBranches.get("master").getId());
    assertEquals(1, updates.size());
    assertUpdate(updates.get("master"), "master", "master", newid, id, new URIish(remoteUri).toString(), Type.BRANCH, GitRefUpdateResult.OK);
    
    getClient(workDir).createBranch("localbranch", id, NULL_PROGRESS_MONITOR);
    getClient(workDir).checkoutRevision("localbranch", true, NULL_PROGRESS_MONITOR);
    write(f, "huhu2");
    add(f);
    id = getClient(workDir).commit(new File[] { f }, "some change before merge", null, null, NULL_PROGRESS_MONITOR).getRevision();
    updates = getClient(workDir).push(remoteUri, Arrays.asList(new String[] { "+refs/heads/localbranch:refs/heads/master" }), Collections.<String>emptyList(), NULL_PROGRESS_MONITOR).getRemoteRepositoryUpdates();
    remoteBranches = getClient(workDir).listRemoteBranches(remoteUri, NULL_PROGRESS_MONITOR);
    assertEquals(1, remoteBranches.size());
    assertEquals(newid, remoteBranches.get("master").getId());
    assertEquals(1, updates.size());
    assertUpdate(updates.get("master"), "localbranch", "master", id, newid, new URIish(remoteUri).toString(), Type.BRANCH, GitRefUpdateResult.REJECTED_NONFASTFORWARD);
    
    updates = getClient(workDir).push(remoteUri, Arrays.asList(new String[] { "refs/heads/localbranch:refs/heads/master" }), Arrays.asList(new String[] { "+refs/heads/master:refs/remotes/origin/master" }), NULL_PROGRESS_MONITOR).getRemoteRepositoryUpdates();
    remoteBranches = getClient(workDir).listRemoteBranches(remoteUri, NULL_PROGRESS_MONITOR);
    assertEquals(1, remoteBranches.size());
    assertEquals(newid, remoteBranches.get("master").getId());
    assertEquals(1, updates.size());
    assertUpdate(updates.get("master"), "localbranch", "master", id, newid, new URIish(remoteUri).toString(), Type.BRANCH, GitRefUpdateResult.REJECTED_NONFASTFORWARD);
    
    // if starts failing, the WA at GitTransportUpdate.(URIish uri, TrackingRefUpdate update) should be removed
    // this.result = GitRefUpdateResult.valueOf((update.getResult() == null ? RefUpdate.Result.NOT_ATTEMPTED : update.getResult()).name());
    Transport transport = Transport.open(getRepository(getClient(workDir)), new URIish(remoteUri));
    transport.setDryRun(false);
    transport.setPushThin(true);
    PushResult pushResult = transport.push(new DelegatingProgressMonitor(NULL_PROGRESS_MONITOR),
            Transport.findRemoteRefUpdatesFor(getRepository(getClient(workDir)),
            Collections.singletonList(new RefSpec("refs/heads/localbranch:refs/heads/master")),
            Collections.singletonList(new RefSpec("refs/heads/master:refs/remotes/origin/master"))));
    assertEquals(1, pushResult.getTrackingRefUpdates().size());
    for (TrackingRefUpdate update : pushResult.getTrackingRefUpdates()) {
        // null but not NOT_ATTEMPTED, probably a bug
        // remove the WA if it starts failing here
        assertNull(update.getResult());
    }
}
 
源代码16 项目: orion.server   文件: PushJob.java
private IStatus doPush(IProgressMonitor monitor) throws IOException, CoreException, URISyntaxException, GitAPIException {
	ProgressMonitor gitMonitor = new EclipseGitProgressTransformer(monitor);
	// /git/remote/{remote}/{branch}/file/{path}
	File gitDir = GitUtils.getGitDir(path.removeFirstSegments(2));
	Repository db = null;
	JSONObject result = new JSONObject();
	try {
		db = FileRepositoryBuilder.create(gitDir);
		Git git = Git.wrap(db);

		PushCommand pushCommand = git.push();
		pushCommand.setProgressMonitor(gitMonitor);
		pushCommand.setTransportConfigCallback(new TransportConfigCallback() {
			@Override
			public void configure(Transport t) {
				credentials.setUri(t.getURI());
				if (t instanceof TransportHttp && cookie != null) {
					HashMap<String, String> map = new HashMap<String, String>();
					map.put(GitConstants.KEY_COOKIE, cookie.getName() + "=" + cookie.getValue());
					((TransportHttp) t).setAdditionalHeaders(map);
				}
			}
		});
		RemoteConfig remoteConfig = new RemoteConfig(git.getRepository().getConfig(), remote);
		credentials.setUri(remoteConfig.getURIs().get(0));
		pushCommand.setCredentialsProvider(credentials);

		boolean pushToGerrit = branch.startsWith("for/");
		RefSpec spec = new RefSpec(srcRef + ':' + (pushToGerrit ? "refs/" : Constants.R_HEADS) + branch);
		pushCommand.setRemote(remote).setRefSpecs(spec);
		if (tags)
			pushCommand.setPushTags();
		pushCommand.setForce(force);
		Iterable<PushResult> resultIterable = pushCommand.call();
		if (monitor.isCanceled()) {
			return new Status(IStatus.CANCEL, GitActivator.PI_GIT, "Cancelled");
		}
		PushResult pushResult = resultIterable.iterator().next();
		boolean error = false;
		JSONArray updates = new JSONArray();
		result.put(GitConstants.KEY_COMMIT_MESSAGE, pushResult.getMessages());
		result.put(GitConstants.KEY_UPDATES, updates);
		for (final RemoteRefUpdate rru : pushResult.getRemoteUpdates()) {
			if (monitor.isCanceled()) {
				return new Status(IStatus.CANCEL, GitActivator.PI_GIT, "Cancelled");
			}
			final String rm = rru.getRemoteName();
			// check status only for branch given in the URL or tags
			if (branch.equals(Repository.shortenRefName(rm)) || rm.startsWith(Constants.R_TAGS) || rm.startsWith(Constants.R_REFS + "for/")) {
				JSONObject object = new JSONObject();
				RemoteRefUpdate.Status status = rru.getStatus();
				if (status != RemoteRefUpdate.Status.UP_TO_DATE || !rm.startsWith(Constants.R_TAGS)) {
					object.put(GitConstants.KEY_COMMIT_MESSAGE, rru.getMessage());
					object.put(GitConstants.KEY_RESULT, status.name());
					TrackingRefUpdate refUpdate = rru.getTrackingRefUpdate();
					if (refUpdate != null) {
						object.put(GitConstants.KEY_REMOTENAME, Repository.shortenRefName(refUpdate.getLocalName()));
						object.put(GitConstants.KEY_LOCALNAME, Repository.shortenRefName(refUpdate.getRemoteName()));
					} else {
						object.put(GitConstants.KEY_REMOTENAME, Repository.shortenRefName(rru.getSrcRef()));
						object.put(GitConstants.KEY_LOCALNAME, Repository.shortenRefName(rru.getRemoteName()));
					}
					updates.put(object);
				}
				if (status != RemoteRefUpdate.Status.OK && status != RemoteRefUpdate.Status.UP_TO_DATE)
					error = true;
			}
			// TODO: return results for all updated branches once push is available for remote, see bug 352202
		}
		// needs to handle multiple
		result.put("Severity", error ? "Error" : "Ok");
	} catch (JSONException e) {
	} finally {
		if (db != null) {
			db.close();
		}
	}
	return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result);
}
 
源代码17 项目: orion.server   文件: FetchJob.java
private IStatus doFetch(IProgressMonitor monitor) throws IOException, CoreException, URISyntaxException, GitAPIException {
	ProgressMonitor gitMonitor = new EclipseGitProgressTransformer(monitor);
	Repository db = null;
	try {
		db = getRepository();
		Git git = Git.wrap(db);
		FetchCommand fc = git.fetch();
		fc.setProgressMonitor(gitMonitor);

		RemoteConfig remoteConfig = new RemoteConfig(git.getRepository().getConfig(), remote);
		credentials.setUri(remoteConfig.getURIs().get(0));
		if (this.cookie != null) {
			fc.setTransportConfigCallback(new TransportConfigCallback() {
				@Override
				public void configure(Transport t) {
					if (t instanceof TransportHttp && cookie != null) {
						HashMap<String, String> map = new HashMap<String, String>();
						map.put(GitConstants.KEY_COOKIE, cookie.getName() + "=" + cookie.getValue());
						((TransportHttp) t).setAdditionalHeaders(map);
					}
				}
			});
		}
		fc.setCredentialsProvider(credentials);
		fc.setRemote(remote);
		if (branch != null) {
			// refs/heads/{branch}:refs/remotes/{remote}/{branch}
			String remoteBranch = branch;
			if (branch.startsWith("for/")) {
				remoteBranch = branch.substring(4);
			}

			RefSpec spec = new RefSpec(Constants.R_HEADS + remoteBranch + ":" + Constants.R_REMOTES + remote + "/" + branch); //$NON-NLS-1$ //$NON-NLS-2$
			spec = spec.setForceUpdate(force);
			fc.setRefSpecs(spec);
		}
		FetchResult fetchResult = fc.call();
		if (monitor.isCanceled()) {
			return new Status(IStatus.CANCEL, GitActivator.PI_GIT, "Cancelled");
		}
		GitJobUtils.packRefs(db, gitMonitor);
		if (monitor.isCanceled()) {
			return new Status(IStatus.CANCEL, GitActivator.PI_GIT, "Cancelled");
		}
		return handleFetchResult(fetchResult);
	} finally {
		if (db != null) {
			db.close();
		}
	}
}
 
源代码18 项目: orion.server   文件: PullJob.java
private IStatus doPull(IProgressMonitor monitor) throws IOException, GitAPIException, CoreException {
	ProgressMonitor gitMonitor = new EclipseGitProgressTransformer(monitor);
	Repository db = null;
	try {
		db = FileRepositoryBuilder.create(GitUtils.getGitDir(path));
		Git git = Git.wrap(db);
		PullCommand pc = git.pull();
		pc.setProgressMonitor(gitMonitor);
		pc.setCredentialsProvider(credentials);
		pc.setTransportConfigCallback(new TransportConfigCallback() {
			@Override
			public void configure(Transport t) {
				credentials.setUri(t.getURI());
				if (t instanceof TransportHttp && cookie != null) {
					HashMap<String, String> map = new HashMap<String, String>();
					map.put(GitConstants.KEY_COOKIE, cookie.getName() + "=" + cookie.getValue());
					((TransportHttp) t).setAdditionalHeaders(map);
				}
			}
		});
		PullResult pullResult = pc.call();

		if (monitor.isCanceled()) {
			return new Status(IStatus.CANCEL, GitActivator.PI_GIT, "Cancelled");
		}

		// handle result
		if (pullResult.isSuccessful()) {
			return Status.OK_STATUS;
		}
		FetchResult fetchResult = pullResult.getFetchResult();

		IStatus fetchStatus = FetchJob.handleFetchResult(fetchResult);
		if (!fetchStatus.isOK()) {
			return fetchStatus;
		}

		MergeStatus mergeStatus = pullResult.getMergeResult().getMergeStatus();
		if (!mergeStatus.isSuccessful())
			return new Status(IStatus.ERROR, GitActivator.PI_GIT, mergeStatus.name());
	} finally {
		if (db != null) {
			db.close();
		}
	}
	return Status.OK_STATUS;
}
 
源代码19 项目: studio   文件: GitRepositoryHelper.java
public <T extends TransportCommand> T setAuthenticationForCommand(T gitCommand, String authenticationType,
                                                                  String username, String password, String token,
                                                                  String privateKey, Path tempKey, boolean decrypt)
        throws CryptoException, ServiceLayerException {
    String passwordValue = password;
    String tokenValue = token;
    String privateKeyValue = privateKey;
    if (decrypt) {
        if (!StringUtils.isEmpty(password)) {
            passwordValue = encryptor.decrypt(password);
        }
        if (!StringUtils.isEmpty(token)) {
            tokenValue = encryptor.decrypt(token);
        }
        if (!StringUtils.isEmpty(privateKey)) {
            privateKeyValue = encryptor.decrypt(privateKey);
        }
    }
    final String pk = privateKeyValue;
    switch (authenticationType) {
        case RemoteRepository.AuthenticationType.NONE:
            logger.debug("No authentication");
            break;
        case RemoteRepository.AuthenticationType.BASIC:
            logger.debug("Basic authentication");
            UsernamePasswordCredentialsProvider credentialsProviderUP =
                    new UsernamePasswordCredentialsProvider(username, passwordValue);
            gitCommand.setCredentialsProvider(credentialsProviderUP);
            break;
        case RemoteRepository.AuthenticationType.TOKEN:
            logger.debug("Token based authentication");
            UsernamePasswordCredentialsProvider credentialsProvider =
                    new UsernamePasswordCredentialsProvider(tokenValue, StringUtils.EMPTY);
            gitCommand.setCredentialsProvider(credentialsProvider);
            break;
        case RemoteRepository.AuthenticationType.PRIVATE_KEY:
            logger.debug("Private key authentication");
            tempKey.toFile().deleteOnExit();
            gitCommand.setTransportConfigCallback(new TransportConfigCallback() {
                @Override
                public void configure(Transport transport) {
                    SshTransport sshTransport = (SshTransport)transport;
                    sshTransport.setSshSessionFactory(getSshSessionFactory(pk, tempKey));
                }
            });

            break;
        default:
            throw new ServiceLayerException("Unsupported authentication type " + authenticationType);
    }

    return gitCommand;
}