Example usage for org.eclipse.jgit.api CloneCommand setURI

List of usage examples for org.eclipse.jgit.api CloneCommand setURI

Introduction

In this page you can find the example usage for org.eclipse.jgit.api CloneCommand setURI.

Prototype

public CloneCommand setURI(String uri) 

Source Link

Document

Set the URI to clone from

Usage

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

License:Open Source License

@Override
public TeamworkCommandResult getResult() {

    try {/*from   ww w . j ava 2 s  .co m*/
        String reposUrl = getRepository().getReposUrl();
        CloneCommand cloneCommand = Git.cloneRepository();
        disableFingerprintCheck(cloneCommand);
        cloneCommand.setDirectory(clonePath);
        cloneCommand.setURI(reposUrl);
        StoredConfig repoConfig = cloneCommand.call().getRepository().getConfig(); //save the repo
        repoConfig.setString("user", null, "name", getRepository().getYourName()); //register the user name
        repoConfig.setString("user", null, "email", getRepository().getYourEmail()); //register the user email
        repoConfig.save();

        if (!isCancelled()) {
            return new TeamworkCommandResult();
        }

        return new TeamworkCommandAborted();
    } catch (GitAPIException | IOException ex) {
        return new TeamworkCommandError(ex.getMessage(), ex.getLocalizedMessage());
    }
}

From source file:com.denimgroup.threadfix.service.repository.GitServiceImpl.java

License:Mozilla Public License

private Git clone(Application application, File dirLocation) {
    Git git = null;/*from   w ww.j  a v a  2s . c o m*/
    try {
        CloneCommand clone = Git.cloneRepository();

        clone.setURI(application.getRepositoryUrl()).setDirectory(dirLocation)
                .setCredentialsProvider(getApplicationCredentials(application));

        if (application.getRepositoryBranch() != null && !application.getRepositoryBranch().isEmpty()) {
            clone.setBranch(application.getRepositoryBranch());
        }

        // clone git repo
        git = clone.call();

        // checkout specific revision
        if (application.getRepositoryRevision() != null && !application.getRepositoryRevision().isEmpty()) {
            git.checkout().setCreateBranch(true).setStartPoint(application.getRepositoryRevision())
                    .setName(application.getRepositoryRevision()).call();
        }

    } catch (WrongRepositoryStateException e) {
        log.error(EXCEPTION_MESSAGE, e);
    } catch (InvalidConfigurationException e) {
        log.error(EXCEPTION_MESSAGE, e);
    } catch (DetachedHeadException e) {
        log.error(EXCEPTION_MESSAGE, e);
    } catch (InvalidRemoteException e) {
        log.error(EXCEPTION_MESSAGE, e);
    } catch (CanceledException e) {
        log.error(EXCEPTION_MESSAGE, e);
    } catch (RefNotFoundException e) {
        log.error(EXCEPTION_MESSAGE, e);
    } catch (NoHeadException e) {
        log.error(EXCEPTION_MESSAGE, e);
    } catch (RefAlreadyExistsException e) {
        log.error(EXCEPTION_MESSAGE, e);
    } catch (CheckoutConflictException e) {
        log.error(EXCEPTION_MESSAGE, e);
    } catch (InvalidRefNameException e) {
        log.error(EXCEPTION_MESSAGE, e);
    } catch (TransportException e) {
        log.error(EXCEPTION_MESSAGE, e);
    } catch (GitAPIException e) {
        log.error(EXCEPTION_MESSAGE, e);
    }

    return git;
}

From source file:com.ejwa.gitdepmavenplugin.DownloaderMojo.java

License:Open Source License

private Git clone(Pom pom, GitDependency dependency) throws MojoExecutionException {
    final CloneCommand c = new CloneCommand();
    final String location = dependency.getLocation();

    c.setURI(location);
    c.setCloneAllBranches(true);// ww w.j a  va2 s. c  o  m
    c.setProgressMonitor(new TextProgressMonitor());

    final GitDependencyHandler dependencyHandler = new GitDependencyHandler(dependency);
    final String version = dependencyHandler.getDependencyVersion(pom);
    final String tempDirectory = Directory.getTempDirectoryString(location, version);

    c.setDirectory(new File(tempDirectory));
    return c.call();
}

From source file:com.ejwa.mavengitdepplugin.DownloaderMojo.java

License:Open Source License

private Git clone(POM pom, GitDependency dependency) {
    final CloneCommand c = new CloneCommand();

    c.setURI(dependency.getLocation());
    c.setCloneAllBranches(true);//from ww  w  . ja v a  2s . c o  m
    c.setProgressMonitor(new TextProgressMonitor());

    final GitDependencyHandler dependencyHandler = new GitDependencyHandler(dependency);
    final String version = dependencyHandler.getDependencyVersion(pom);
    final String tempDirectory = Directory.getTempDirectoryString(dependency.getLocation(), version);
    c.setDirectory(new File(tempDirectory));

    return c.call();
}

From source file:com.fanniemae.ezpie.common.GitOperations.java

License:Open Source License

public String cloneHTTP(String repo_url, String destination, String userID, String password, String branch)
        throws InvalidRemoteException, TransportException, GitAPIException, URISyntaxException {

    _repositoryHost = getHost(repo_url);
    setupProxy();/*  w  ww.j ava2s . c o  m*/

    File localDir = new File(destination);
    CloneCommand cloneCommand = Git.cloneRepository();
    cloneCommand.setURI(repo_url);
    cloneCommand.setDirectory(localDir);

    if (StringUtilities.isNotNullOrEmpty(branch))
        cloneCommand.setBranch(branch);

    if (StringUtilities.isNotNullOrEmpty(userID))
        cloneCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userID, password));

    try (Writer writer = new StringWriter()) {
        TextProgressMonitor tpm = new TextProgressMonitor(writer);
        cloneCommand.setProgressMonitor(tpm);
        try (Git result = cloneCommand.call()) {
        }
        clearProxyAuthenticatorCache();
        writer.flush();
        return writer.toString();
    } catch (IOException e) {
        throw new PieException("Error while trying to clone the git repository. " + e.getMessage(), e);
    }
}

From source file:com.fanniemae.ezpie.common.GitOperations.java

License:Open Source License

public String cloneSSH(String repo_url, String destination, String privateKey, String password, String branch) {
    if (_useProxy) {
        throw new PieException(
                "Network proxies do not support SSH, please use an http url to clone this repository.");
    }/*from   w  w w.  j ava  2 s .c om*/

    final SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
        @Override
        protected void configure(Host host, Session session) {
            // This still checks existing host keys and will disable "unsafe"
            // authentication mechanisms if the host key doesn't match.
            session.setConfig("StrictHostKeyChecking", "no");
        }

        @Override
        protected JSch createDefaultJSch(FS fs) throws JSchException {
            JSch defaultJSch = super.createDefaultJSch(fs);
            defaultJSch.addIdentity(privateKey, password);
            return defaultJSch;
        }
    };

    CloneCommand cloneCommand = Git.cloneRepository();
    cloneCommand.setURI(repo_url);
    File dir = new File(destination);
    cloneCommand.setDirectory(dir);

    if (StringUtilities.isNotNullOrEmpty(branch))
        cloneCommand.setBranch(branch);

    cloneCommand.setTransportConfigCallback(new TransportConfigCallback() {
        public void configure(Transport transport) {
            SshTransport sshTransport = (SshTransport) transport;
            sshTransport.setSshSessionFactory(sshSessionFactory);
        }
    });

    try (Writer writer = new StringWriter()) {
        TextProgressMonitor tpm = new TextProgressMonitor(writer);
        cloneCommand.setProgressMonitor(tpm);
        try (Git result = cloneCommand.call()) {
        }
        writer.flush();
        return writer.toString();
    } catch (IOException | GitAPIException e) {
        throw new PieException("Error while trying to clone the git repository. " + e.getMessage(), e);
    }
}

From source file:com.gitblit.manager.GitblitManager.java

License:Apache License

/**
 * Creates a personal fork of the specified repository. The clone is view
 * restricted by default and the owner of the source repository is given
 * access to the clone.//from  ww w  .  ja v a 2 s  .  c  o  m
 *
 * @param repository
 * @param user
 * @return the repository model of the fork, if successful
 * @throws GitBlitException
 */
@Override
public RepositoryModel fork(RepositoryModel repository, UserModel user) throws GitBlitException {
    String cloneName = MessageFormat.format("{0}/{1}.git", user.getPersonalPath(),
            StringUtils.stripDotGit(StringUtils.getLastPathElement(repository.name)));
    String fromUrl = MessageFormat.format("file://{0}/{1}",
            repositoryManager.getRepositoriesFolder().getAbsolutePath(), repository.name);

    // clone the repository
    try {
        Repository canonical = getRepository(repository.name);
        File folder = new File(repositoryManager.getRepositoriesFolder(), cloneName);
        CloneCommand clone = new CloneCommand();
        clone.setBare(true);

        // fetch branches with exclusions
        Collection<Ref> branches = canonical.getRefDatabase().getRefs(Constants.R_HEADS).values();
        List<String> branchesToClone = new ArrayList<String>();
        for (Ref branch : branches) {
            String name = branch.getName();
            if (name.startsWith(Constants.R_TICKET)) {
                // exclude ticket branches
                continue;
            }
            branchesToClone.add(name);
        }
        clone.setBranchesToClone(branchesToClone);
        clone.setURI(fromUrl);
        clone.setDirectory(folder);
        Git git = clone.call();

        // fetch tags
        FetchCommand fetch = git.fetch();
        fetch.setRefSpecs(new RefSpec("+refs/tags/*:refs/tags/*"));
        fetch.call();

        git.getRepository().close();
    } catch (Exception e) {
        throw new GitBlitException(e);
    }

    // create a Gitblit repository model for the clone
    RepositoryModel cloneModel = repository.cloneAs(cloneName);
    // owner has REWIND/RW+ permissions
    cloneModel.addOwner(user.username);

    // ensure initial access restriction of the fork
    // is not lower than the source repository  (issue-495/ticket-167)
    if (repository.accessRestriction.exceeds(cloneModel.accessRestriction)) {
        cloneModel.accessRestriction = repository.accessRestriction;
    }

    repositoryManager.updateRepositoryModel(cloneName, cloneModel, false);

    // add the owner of the source repository to the clone's access list
    if (!ArrayUtils.isEmpty(repository.owners)) {
        for (String owner : repository.owners) {
            UserModel originOwner = userManager.getUserModel(owner);
            if (originOwner != null && !originOwner.canClone(cloneModel)) {
                // origin owner can't yet clone fork, grant explicit clone access
                originOwner.setRepositoryPermission(cloneName, AccessPermission.CLONE);
                reviseUser(originOwner.username, originOwner);
            }
        }
    }

    // grant origin's user list clone permission to fork
    List<String> users = repositoryManager.getRepositoryUsers(repository);
    List<UserModel> cloneUsers = new ArrayList<UserModel>();
    for (String name : users) {
        if (!name.equalsIgnoreCase(user.username)) {
            UserModel cloneUser = userManager.getUserModel(name);
            if (cloneUser.canClone(repository) && !cloneUser.canClone(cloneModel)) {
                // origin user can't yet clone fork, grant explicit clone access
                cloneUser.setRepositoryPermission(cloneName, AccessPermission.CLONE);
            }
            cloneUsers.add(cloneUser);
        }
    }
    userManager.updateUserModels(cloneUsers);

    // grant origin's team list clone permission to fork
    List<String> teams = repositoryManager.getRepositoryTeams(repository);
    List<TeamModel> cloneTeams = new ArrayList<TeamModel>();
    for (String name : teams) {
        TeamModel cloneTeam = userManager.getTeamModel(name);
        if (cloneTeam.canClone(repository) && !cloneTeam.canClone(cloneModel)) {
            // origin team can't yet clone fork, grant explicit clone access
            cloneTeam.setRepositoryPermission(cloneName, AccessPermission.CLONE);
        }
        cloneTeams.add(cloneTeam);
    }
    userManager.updateTeamModels(cloneTeams);

    // add this clone to the cached model
    repositoryManager.addToCachedRepositoryList(cloneModel);

    if (pluginManager != null) {
        for (RepositoryLifeCycleListener listener : pluginManager
                .getExtensions(RepositoryLifeCycleListener.class)) {
            try {
                listener.onFork(repository, cloneModel);
            } catch (Throwable t) {
                logger.error(String.format("failed to call plugin onFork %s", repository.name), t);
            }
        }
    }
    return cloneModel;
}

From source file:com.gitblit.servlet.GitServletTest.java

License:Apache License

@Test
public void testClone() throws Exception {
    GitBlitSuite.close(ticgitFolder);/*from w  ww .  j a  va  2  s . c  o  m*/
    if (ticgitFolder.exists()) {
        FileUtils.delete(ticgitFolder, FileUtils.RECURSIVE | FileUtils.RETRY);
    }

    CloneCommand clone = Git.cloneRepository();
    clone.setURI(MessageFormat.format("{0}/ticgit.git", url));
    clone.setDirectory(ticgitFolder);
    clone.setBare(false);
    clone.setCloneAllBranches(true);
    clone.setCredentialsProvider(new UsernamePasswordCredentialsProvider(account, password));
    GitBlitSuite.close(clone.call());
    assertTrue(true);
}

From source file:com.gitblit.servlet.GitServletTest.java

License:Apache License

@Test
public void testBogusLoginClone() throws Exception {
    // restrict repository access
    RepositoryModel model = repositories().getRepositoryModel("ticgit.git");
    model.accessRestriction = AccessRestrictionType.CLONE;
    repositories().updateRepositoryModel(model.name, model, false);

    // delete any existing working folder
    boolean cloned = false;
    try {/*  w w  w .  j  a  va2 s.  c  o m*/
        CloneCommand clone = Git.cloneRepository();
        clone.setURI(MessageFormat.format("{0}/ticgit.git", url));
        clone.setDirectory(ticgit2Folder);
        clone.setBare(false);
        clone.setCloneAllBranches(true);
        clone.setCredentialsProvider(new UsernamePasswordCredentialsProvider("bogus", "bogus"));
        GitBlitSuite.close(clone.call());
        cloned = true;
    } catch (Exception e) {
        // swallow the exception which we expect
    }

    // restore anonymous repository access
    model.accessRestriction = AccessRestrictionType.NONE;
    repositories().updateRepositoryModel(model.name, model, false);

    assertFalse("Bogus login cloned a repository?!", cloned);
}

From source file:com.gitblit.servlet.GitServletTest.java

License:Apache License

@Test
public void testUnauthorizedLoginClone() throws Exception {
    // restrict repository access
    RepositoryModel model = repositories().getRepositoryModel("ticgit.git");
    model.accessRestriction = AccessRestrictionType.CLONE;
    model.authorizationControl = AuthorizationControl.NAMED;
    UserModel user = new UserModel("james");
    user.password = "james";
    gitblit().addUser(user);//from w  w w  .java  2s  .c om
    repositories().updateRepositoryModel(model.name, model, false);

    FileUtils.delete(ticgit2Folder, FileUtils.RECURSIVE);

    // delete any existing working folder
    boolean cloned = false;
    try {
        CloneCommand clone = Git.cloneRepository();
        clone.setURI(MessageFormat.format("{0}/ticgit.git", url));
        clone.setDirectory(ticgit2Folder);
        clone.setBare(false);
        clone.setCloneAllBranches(true);
        clone.setCredentialsProvider(new UsernamePasswordCredentialsProvider(user.username, user.password));
        GitBlitSuite.close(clone.call());
        cloned = true;
    } catch (Exception e) {
        // swallow the exception which we expect
    }

    assertFalse("Unauthorized login cloned a repository?!", cloned);

    FileUtils.delete(ticgit2Folder, FileUtils.RECURSIVE);

    // switch to authenticated
    model.authorizationControl = AuthorizationControl.AUTHENTICATED;
    repositories().updateRepositoryModel(model.name, model, false);

    // try clone again
    cloned = false;
    CloneCommand clone = Git.cloneRepository();
    clone.setURI(MessageFormat.format("{0}/ticgit.git", url));
    clone.setDirectory(ticgit2Folder);
    clone.setBare(false);
    clone.setCloneAllBranches(true);
    clone.setCredentialsProvider(new UsernamePasswordCredentialsProvider(user.username, user.password));
    GitBlitSuite.close(clone.call());
    cloned = true;

    assertTrue("Authenticated login could not clone!", cloned);

    FileUtils.delete(ticgit2Folder, FileUtils.RECURSIVE);

    // restore anonymous repository access
    model.accessRestriction = AccessRestrictionType.NONE;
    model.authorizationControl = AuthorizationControl.NAMED;
    repositories().updateRepositoryModel(model.name, model, false);

    delete(user);
}