org.eclipse.jgit.transport.Transport Java Examples
The following examples show how to use
org.eclipse.jgit.transport.Transport.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JGitAPIImpl.java From git-client-plugin with MIT License | 6 votes |
@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; }
Example #2
Source File: TransportCommand.java From netbeans with Apache License 2.0 | 6 votes |
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); } }
Example #3
Source File: JGitAPIImpl.java From git-client-plugin with MIT License | 6 votes |
/** {@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; }
Example #4
Source File: GoogleCloudSourceSupport.java From spring-cloud-config with Apache License 2.0 | 5 votes |
@Override public void configure(Transport transport) { if (transport instanceof TransportHttp && canHandle(transport.getURI())) { addHeaders((TransportHttp) transport, credentialsProvider.getAuthorizationHeaders()); } }
Example #5
Source File: GitContentRepository.java From studio with GNU General Public License v3.0 | 5 votes |
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; }
Example #6
Source File: GoogleCloudSourceSupportTests.java From spring-cloud-config with Apache License 2.0 | 5 votes |
@SuppressWarnings("SameParameterValue") private Transport mockSshTransport(String uri) throws URISyntaxException { Transport transport = Mockito.mock(SshTransport.class); when(transport.getURI()).thenReturn(new URIish(uri)); return transport; }
Example #7
Source File: GoogleCloudSourceSupportTests.java From spring-cloud-config with Apache License 2.0 | 5 votes |
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); }
Example #8
Source File: GoogleCloudSourceSupportTests.java From spring-cloud-config with Apache License 2.0 | 5 votes |
@Test public void verifyDoesNothingForNonHttpTransports() throws URISyntaxException { TransportConfigCallback callback = transportConfigCallbackWith( createAuthHeaders()); Transport transport = mockSshTransport(SSH_GOOGLE_CLOUD_SOURCE_REPO); callback.configure(transport); verifyOnlyValidInteraction(transport); }
Example #9
Source File: PropertiesBasedSshTransportConfigCallback.java From spring-cloud-config with Apache License 2.0 | 5 votes |
@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())); } }
Example #10
Source File: FileBasedSshTransportConfigCallback.java From spring-cloud-config with Apache License 2.0 | 5 votes |
@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"); } }); }
Example #11
Source File: TestSshGit.java From Jpom with MIT License | 5 votes |
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(); }
Example #12
Source File: ProtocolsTestSuite.java From netbeans with Apache License 2.0 | 5 votes |
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 } }
Example #13
Source File: BranchTest.java From netbeans with Apache License 2.0 | 5 votes |
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) { } }
Example #14
Source File: PullJob.java From orion.server with Eclipse Public License 1.0 | 4 votes |
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; }
Example #15
Source File: FetchJob.java From orion.server with Eclipse Public License 1.0 | 4 votes |
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(); } } }
Example #16
Source File: PushJob.java From orion.server with Eclipse Public License 1.0 | 4 votes |
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); }
Example #17
Source File: GitRepositoryHelper.java From studio with GNU General Public License v3.0 | 4 votes |
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; }
Example #18
Source File: PushTest.java From netbeans with Apache License 2.0 | 4 votes |
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()); } }
Example #19
Source File: JGitUtil.java From milkman with MIT License | 4 votes |
@Override public void configure(Transport transport) { SshTransport sshTransport = (SshTransport) transport; sshTransport.setSshSessionFactory(SshdSessionFactory.getInstance()); }