Example usage for org.eclipse.jgit.api LsRemoteCommand call

List of usage examples for org.eclipse.jgit.api LsRemoteCommand call

Introduction

In this page you can find the example usage for org.eclipse.jgit.api LsRemoteCommand call.

Prototype

@Override
public Collection<Ref> call()
        throws GitAPIException, InvalidRemoteException, org.eclipse.jgit.api.errors.TransportException 

Source Link

Document

Execute the LsRemote command with all the options and parameters collected by the setter methods (e.g.

Usage

From source file:bluej.groupwork.git.GitProvider.java

License:Open Source License

@Override
public TeamworkCommandResult checkConnection(TeamSettings settings) {

    try {//from  www.jav  a2s.  c om
        String gitUrl = makeGitUrl(settings);

        //perform a lsRemote on the remote git repo.
        LsRemoteCommand lsRemoteCommand = Git.lsRemoteRepository();
        UsernamePasswordCredentialsProvider cp = new UsernamePasswordCredentialsProvider(settings.getUserName(),
                settings.getPassword()); // set a configuration with username and password.
        lsRemoteCommand.setRemote(gitUrl); //configure remote repository address.
        lsRemoteCommand.setCredentialsProvider(cp); //associate the repository to the username and password.
        lsRemoteCommand.setTags(false); //disable refs/tags in reference results
        lsRemoteCommand.setHeads(false); //disable refs/heads in reference results

        //It seems that ssh host fingerprint check is not working properly. 
        //Disable it in a ssh connection.
        if (gitUrl.startsWith("ssh")) {
            SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
                @Override
                protected void configure(OpenSshConfig.Host host, Session sn) {
                    java.util.Properties config = new java.util.Properties();
                    config.put("StrictHostKeyChecking", "no");
                    sn.setConfig(config);
                }

                @Override
                protected JSch createDefaultJSch(FS fs) throws JSchException {
                    return super.createDefaultJSch(fs);
                }
            };

            lsRemoteCommand.setTransportConfigCallback((Transport t) -> {
                SshTransport sshTransport = (SshTransport) t;
                sshTransport.setSshSessionFactory(sshSessionFactory);
            });
        }

        lsRemoteCommand.call(); //executes the lsRemote commnand.
    } catch (GitAPIException ex) {
        return new TeamworkCommandError(ex.getMessage(), ex.getLocalizedMessage());
    } catch (UnsupportedSettingException ex) {
        return new TeamworkCommandUnsupportedSetting(ex.getMessage());
    }
    //if we got here, it means the command was successful.
    return new TeamworkCommandResult();
}

From source file:ch.sourcepond.maven.release.scm.git.GitRepository.java

License:Apache License

public Collection<Ref> allRemoteTags() throws SCMException {
    if (remoteTags == null) {
        final LsRemoteCommand lsRemoteCommand = getGit().lsRemote().setTags(true).setHeads(false);
        if (config.getRemoteUrlOrNull() != null) {
            lsRemoteCommand.setRemote(config.getRemoteUrlOrNull());
        }//w w  w  . ja v  a  2  s  .  c  o  m
        try {
            remoteTags = lsRemoteCommand.call();
        } catch (final GitAPIException e) {
            throw new SCMException(e, "Remote tags could not be listed!");
        }
    }
    return remoteTags;
}

From source file:com.google.gerrit.acceptance.git.RefAdvertisementIT.java

License:Apache License

@Test
public void advertisedReferencesOmitPrivateChangesOfOtherUsers() throws Exception {
    allow(Permission.READ, REGISTERED_USERS, "refs/heads/master");

    TestRepository<?> userTestRepository = cloneProject(project, user);
    try (Git git = userTestRepository.git()) {
        LsRemoteCommand lsRemoteCommand = git.lsRemote();
        String change3RefName = c3.currentPatchSet().getRefName();

        List<String> initialRefNames = lsRemoteCommand.call().stream().map(Ref::getName).collect(toList());
        assertWithMessage("Precondition violated").that(initialRefNames).contains(change3RefName);

        gApi.changes().id(c3.getId().get()).setPrivate(true);

        List<String> refNames = lsRemoteCommand.call().stream().map(Ref::getName).collect(toList());
        assertThat(refNames).doesNotContain(change3RefName);
    }/*from   ww  w .j ava 2  s .c  o  m*/
}

From source file:com.google.gerrit.acceptance.git.RefAdvertisementIT.java

License:Apache License

@Test
public void advertisedReferencesIncludePrivateChangesWhenAllRefsMayBeRead() throws Exception {
    allow(Permission.READ, REGISTERED_USERS, "refs/*");

    TestRepository<?> userTestRepository = cloneProject(project, user);
    try (Git git = userTestRepository.git()) {
        LsRemoteCommand lsRemoteCommand = git.lsRemote();
        String change3RefName = c3.currentPatchSet().getRefName();

        List<String> initialRefNames = lsRemoteCommand.call().stream().map(Ref::getName).collect(toList());
        assertWithMessage("Precondition violated").that(initialRefNames).contains(change3RefName);

        gApi.changes().id(c3.getId().get()).setPrivate(true);

        List<String> refNames = lsRemoteCommand.call().stream().map(Ref::getName).collect(toList());
        assertThat(refNames).contains(change3RefName);
    }/*from   ww  w . jav a  2s  . c  o m*/
}

From source file:de.egore911.versioning.util.vcs.GitProvider.java

License:Open Source License

@Override
public boolean tagExistsImpl(String tagName) {
    InMemoryRepository repo = initRepository();

    // Ask for the remote tags
    LsRemoteCommand command = new LsRemoteCommand(repo);
    command.setTags(true);//from  w w w. j  a  v a2 s  .  co  m
    try {
        Collection<Ref> tags = command.call();
        for (Ref tag : tags) {
            // Tag found, all is fine
            if (tag.getName().equals("refs/tags/" + tagName)) {
                return true;
            }
        }
        // Tag not found
        return false;
    } catch (GitAPIException e) {
        log.error(e.getMessage(), e);
        return false;
    }
}

From source file:de.egore911.versioning.util.vcs.GitProvider.java

License:Open Source License

@Override
protected List<Tag> getTagsImpl() {
    InMemoryRepository repo = initRepository();
    List<Tag> result = new ArrayList<>();

    // Ask for the remote tags
    LsRemoteCommand command = new LsRemoteCommand(repo);
    command.setTags(true);// w  w  w.  j  a v  a  2  s.c o m
    try {
        Collection<Ref> tags = command.call();
        result.addAll(tags.stream().map(tag -> new Tag(null, tag.getName().replace("refs/tags/", "")))
                .collect(Collectors.toList()));
        return result;
    } catch (GitAPIException e) {
        log.error(e.getMessage(), e);
        return Collections.emptyList();
    }
}

From source file:fr.treeptik.cloudunit.utils.GitUtils.java

License:Open Source License

/**
 * List all GIT Tags of an application with an index
 * After this index is use to choose on which tag user want to restre his application
 * with resetOnChosenGitTag() method//from   w  w w. j  av a  2 s .co  m
 *
 * @param application
 * @param dockerManagerAddress
 * @param containerGitAddress
 * @return
 * @throws GitAPIException
 * @throws IOException
 */
public static List<String> listGitTagsOfApplication(Application application, String dockerManagerAddress,
        String containerGitAddress) throws GitAPIException, IOException {

    List<String> listTagsName = new ArrayList<>();

    User user = application.getUser();
    String sshPort = application.getServers().get(0).getSshPort();
    String password = user.getPassword();
    String userNameGit = user.getLogin();
    String dockerManagerIP = dockerManagerAddress.substring(0, dockerManagerAddress.length() - 5);
    String remoteRepository = "ssh://" + userNameGit + "@" + dockerManagerIP + ":" + sshPort
            + containerGitAddress;

    Path myTempDirPath = Files.createTempDirectory(Paths.get("/tmp"), null);
    File gitworkDir = myTempDirPath.toFile();

    InitCommand initCommand = Git.init();
    initCommand.setDirectory(gitworkDir);
    initCommand.call();
    FileRepository gitRepo = new FileRepository(gitworkDir);
    LsRemoteCommand lsRemoteCommand = new LsRemoteCommand(gitRepo);

    CredentialsProvider credentialsProvider = configCredentialsForGit(userNameGit, password);

    lsRemoteCommand.setCredentialsProvider(credentialsProvider);
    lsRemoteCommand.setRemote(remoteRepository);
    lsRemoteCommand.setTags(true);
    Collection<Ref> collectionRefs = lsRemoteCommand.call();
    List<Ref> listRefs = new ArrayList<>(collectionRefs);

    for (Ref ref : listRefs) {
        listTagsName.add(ref.getName());
    }
    Collections.sort(listTagsName);
    FilesUtils.deleteDirectory(gitworkDir);

    return listTagsName;

}

From source file:org.eclipse.che.git.impl.jgit.JGitConnection.java

License:Open Source License

@Override
public List<RemoteReference> lsRemote(LsRemoteRequest request) throws UnauthorizedException, GitException {
    String remoteUrl = request.getRemoteUrl();
    LsRemoteCommand lsRemoteCommand = getGit().lsRemote().setRemote(remoteUrl);
    Collection<Ref> refs;
    try {//  w  ww . ja v  a2s  .co  m
        refs = lsRemoteCommand.call();
    } catch (GitAPIException exception) {
        if (exception.getMessage().contains(ERROR_AUTHENTICATION_REQUIRED)) {
            throw new UnauthorizedException(String.format(ERROR_AUTHENTICATION_FAILED, remoteUrl));
        } else {
            throw new GitException(exception.getMessage(), exception);
        }
    }

    return refs.stream().map(ref -> newDto(RemoteReference.class).withCommitId(ref.getObjectId().name())
            .withReferenceName(ref.getName())).collect(Collectors.toList());
}

From source file:org.flowerplatform.web.git.GitService.java

License:Open Source License

@RemoteInvocation
public List<Object> getBranches(ServiceInvocationContext context, String repositoryUrl) {
    tlCommand.set((InvokeServiceMethodServerCommand) context.getCommand());
    Repository db = null;//w ww  .j  ava 2 s .  co  m
    try {
        URIish uri = new URIish(repositoryUrl.trim());
        db = new FileRepository(new File("/tmp"));

        Git git = new Git(db);
        LsRemoteCommand rc = git.lsRemote();
        rc.setRemote(uri.toString()).setTimeout(30);

        Collection<Ref> remoteRefs = rc.call();
        List<GitRef> branches = new ArrayList<GitRef>();

        Ref idHEAD = null;
        for (Ref r : remoteRefs) {
            if (r.getName().equals(Constants.HEAD)) {
                idHEAD = r;
            }
        }
        Ref head = null;
        boolean headIsMaster = false;
        String masterBranchRef = Constants.R_HEADS + Constants.MASTER;
        for (Ref r : remoteRefs) {
            String n = r.getName();
            if (!n.startsWith(Constants.R_HEADS))
                continue;
            branches.add(new GitRef(n, Repository.shortenRefName(n)));
            if (idHEAD == null || headIsMaster)
                continue;
            if (r.getObjectId().equals(idHEAD.getObjectId())) {
                headIsMaster = masterBranchRef.equals(r.getName());
                if (head == null || headIsMaster)
                    head = r;
            }
        }
        Collections.sort(branches, new Comparator<GitRef>() {
            public int compare(GitRef r1, GitRef r2) {
                return r1.getShortName().compareTo(r2.getShortName());
            }
        });
        if (idHEAD != null && head == null) {
            head = idHEAD;
            branches.add(0, new GitRef(idHEAD.getName(), Repository.shortenRefName(idHEAD.getName())));
        }

        GitRef headRef = head != null ? new GitRef(head.getName(), Repository.shortenRefName(head.getName()))
                : null;
        return Arrays.asList(new Object[] { branches, headRef });
    } catch (JGitInternalException | GitAPIException e) {
        context.getCommunicationChannel()
                .appendOrSendCommand(
                        new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                                GitPlugin.getInstance().getMessage("git.cloneWizard.branch.cannotListBranches")
                                        + "\n" + e.getCause().getMessage(),
                                DisplaySimpleMessageClientCommand.ICON_ERROR));
    } catch (IOException e) {
        context.getCommunicationChannel().appendOrSendCommand(
                new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                        GitPlugin.getInstance().getMessage("git.cloneWizard.branch.cannotCreateTempRepo"),
                        DisplaySimpleMessageClientCommand.ICON_ERROR));
    } catch (URISyntaxException e) {
        context.getCommunicationChannel().appendOrSendCommand(
                new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                        e.getReason(), DisplaySimpleMessageClientCommand.ICON_ERROR));
    } catch (Exception e) {
        if (GitPlugin.getInstance().getUtils().isAuthentificationException(e)) {
            openLoginWindow();
            return null;
        }
        logger.debug(CommonPlugin.getInstance().getMessage("error"), e);
    } finally {
        if (db != null) {
            db.close();
        }
    }
    return null;
}

From source file:org.gitective.core.RepositoryUtils.java

License:Open Source License

/**
 * List remote references and return all remote references that are missing
 * locally or have a different remote object id than the local reference.
 *
 * @param repository/*  w w  w .ja  va2  s .co  m*/
 * @param remote
 * @return non-null but possibly collection of {@link RefDiff}
 */
public static Collection<RefDiff> diffRemoteRefs(final Repository repository, final String remote) {
    if (repository == null)
        throw new IllegalArgumentException(Assert.formatNotNull("Repository"));
    if (remote == null)
        throw new IllegalArgumentException(Assert.formatNotNull("Remote"));
    if (remote.length() == 0)
        throw new IllegalArgumentException(Assert.formatNotEmpty("Remote"));

    final LsRemoteCommand lsRemote = new LsRemoteCommand(repository);
    lsRemote.setRemote(remote);
    try {
        final Collection<Ref> remoteRefs = lsRemote.call();
        final List<RefDiff> diffs = new ArrayList<RefDiff>();
        if (hasRemote(repository, remote)) {
            final String refPrefix = R_REMOTES + remote + "/";
            for (Ref remoteRef : remoteRefs) {
                String name = remoteRef.getName();
                if (name.startsWith(R_HEADS))
                    name = refPrefix + name.substring(R_HEADS.length());
                else if (!name.startsWith(R_TAGS))
                    name = refPrefix + name;
                final Ref localRef = repository.getRef(name);
                if (localRef == null || !remoteRef.getObjectId().equals(localRef.getObjectId()))
                    diffs.add(new RefDiff(localRef, remoteRef));
            }
        } else
            for (Ref remoteRef : remoteRefs) {
                final Ref localRef = repository.getRef(remoteRef.getName());
                if (localRef == null || !remoteRef.getObjectId().equals(localRef.getObjectId()))
                    diffs.add(new RefDiff(localRef, remoteRef));
            }
        return diffs;
    } catch (Exception e) {
        throw new GitException(e, repository);
    }
}