Example usage for org.eclipse.jgit.api Git cloneRepository

List of usage examples for org.eclipse.jgit.api Git cloneRepository

Introduction

In this page you can find the example usage for org.eclipse.jgit.api Git cloneRepository.

Prototype

public static CloneCommand cloneRepository() 

Source Link

Document

Return a command object to execute a clone command

Usage

From source file:GitHelper.java

License:Apache License

public static File cloneRepository(String cloneUrl, String repoPw)
        throws GitAPIException, JSONException, IOException {
    config = ConfigParser.getConfig();//  ww w .  j a  va2 s. co  m
    File tmpDir = new File("temp_repo");
    String key = null;
    String keyPassPhrase = null;
    if (config.has("privateKey")) {
        key = config.getString("privateKey");
        keyPassPhrase = config.getString("privateKeyPassPhrase");
    }
    // git clone will fail if the directory already exists, even if empty
    if (tmpDir.exists()) {
        FileUtils.deleteDirectory(tmpDir);
    }
    String pw = null;
    if (repoPw != null) {
        pw = repoPw;
    } else if (config.has("gitClonePassword")) {
        pw = config.getString("gitClonePassword");
    }
    final String finalKeyPassPhrase = keyPassPhrase;
    final String finalKey = key;

    SshSessionFactory sessionFactory = new CustomJschConfigSessionFactory();

    // use a private key if provided
    if (finalKey != null) {
        SshSessionFactory.setInstance(sessionFactory);
    }

    // use a password if provided
    if (pw != null) {
        final String finalPw = pw;
        SshSessionFactory.setInstance(new JschConfigSessionFactory() {
            @Override
            protected void configure(OpenSshConfig.Host host, Session session) {
                session.setPassword(finalPw);
            }
        });
    }
    SshSessionFactory.setInstance(sessionFactory);
    Git.cloneRepository().setURI(cloneUrl).setDirectory(tmpDir)
            .setTransportConfigCallback(new TransportConfigCallback() {
                @Override
                public void configure(Transport transport) {
                    SshTransport sshTransport = (SshTransport) transport;
                    sshTransport.setSshSessionFactory(sessionFactory);
                }
            }).call();

    return tmpDir;
}

From source file:actions.DownloadSPDX.java

/**
* Get the files from a given repository on github
* @param slotId The thread where the download is happening
* @param localPath The bigArchive on disk where the files will be placed
* @param location The username/repository identification. We'd
* expect something like triplecheck/reporter
* @return True if everything went ok, false if something went wrong
*//*from ww  w .  j av a  2s  .  co  m*/
public Boolean download(final int slotId, final File localPath, final String location) {
    // we can't have any older files
    files.deleteDir(localPath);
    final String REMOTE_URL = "https://github.com/" + location + ".git";
    try {

        Git.cloneRepository().setURI(REMOTE_URL).setDirectory(localPath).call();

        // now open the created repository
        FileRepositoryBuilder builder = new FileRepositoryBuilder();

        Repository repository = builder.setGitDir(localPath).readEnvironment() // scan environment GIT_* variables
                .findGitDir() // scan up the file system tree
                .build();

        System.out.println(slotId + "-> Downloaded repository: " + repository.getDirectory());

        repository.close();

    } catch (Exception ex) {
        Logger.getLogger(Repositories.class.getName()).log(Level.SEVERE, null, ex);
        // we need to add this event on the exception list
        utils_deprecated.files.addTextToFile(fileExceptionHappened, "\n" + location);
        // delete the files if possible
        files.deleteDir(localPath);
        System.out.println(slotId + " !!!! Failed to download: " + location);
        // clean up the slot
        slots[slotId] = false;
        return false;
    }

    System.out.println(slotId + "-> Downloaded: " + location);
    return true;
}

From source file:am.ik.categolj3.api.git.GitStore.java

License:Apache License

Git getGitDirectory() {
    try {/* ww w.j a  v  a 2 s  . c o m*/
        if (gitProperties.getBaseDir().exists()) {
            if (gitProperties.isInit()) {
                FileSystemUtils.deleteRecursively(gitProperties.getBaseDir());
            } else {
                return Git.open(gitProperties.getBaseDir());
            }
        }
        CloneCommand clone = Git.cloneRepository().setURI(gitProperties.getUri())
                .setDirectory(gitProperties.getBaseDir());
        gitProperties.credentialsProvider().ifPresent(clone::setCredentialsProvider);
        return clone.call();
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } catch (GitAPIException e) {
        throw new IllegalStateException(e);
    }
}

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

License:Open Source License

@Override
public TeamworkCommandResult getResult() {

    try {//from   w  w  w.  j a  v  a  2 s  .com
        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:br.com.ingenieux.mojo.beanstalk.bundle.CodeCommitFastDeployMojo.java

License:Apache License

@Override
protected Git getGitRepo() throws Exception {
    if (stagingDirectory.exists() && new File(stagingDirectory, "HEAD").exists()) {
        Git git = Git.open(stagingDirectory);

        git.fetch().setRemote(getRemoteUrl(null, null)).setProgressMonitor(new TextProgressMonitor())
                .setRefSpecs(new RefSpec("refs/heads/master")).call();
    } else {// w ww  .  j  ava 2 s  .  c o m
        Git.cloneRepository().setURI(getRemoteUrl(null, null)).setProgressMonitor(new TextProgressMonitor())
                .setDirectory(stagingDirectory).setNoCheckout(true).setBare(true).call();
    }

    Repository r = null;

    RepositoryBuilder b = new RepositoryBuilder().setGitDir(stagingDirectory).setWorkTree(sourceDirectory);

    r = b.build();

    final Git git = Git.wrap(r);

    return git;
}

From source file:br.com.raffs.rundeck.plugin.Deployment.java

License:Apache License

/**
 * Execute a step on Node/*ww w.j a va  2  s .  c o  m*/
 */
public void executeStep(final PluginStepContext context, final Map<String, Object> configuration)
        throws StepException {

    // gitlab_repo is a required parameters.
    if (gitlab_repo == null)
        throw new StepException(
                "Configuration failed, missing the gitlab_repo variables on Rundeck Framework properties",
                StepFailureReason.ConfigurationFailure);

    // gitlab_repo is a required parameters.
    if (gitlab_branch == null)
        throw new StepException(
                "Configuration failed, missing the gitlab_branch variables on Rundeck Framework properties",
                StepFailureReason.ConfigurationFailure);

    // gitlab_repo is a required parameters.
    if (gitlab_username == null)
        throw new StepException(
                "Configuration failed, missing the gitlab_username variables on Rundeck Framework properties",
                StepFailureReason.ConfigurationFailure);

    // gitlab_repo is a required parameters.
    if (gitlab_password == null)
        throw new StepException(
                "Configuration failed, missing the gitlab_password variables on Rundeck Framework properties",
                StepFailureReason.ConfigurationFailure);

    // openshift_Server is a required parameters.
    if (openshift_server == null)
        throw new StepException(
                "Configuration failed, missing the openshift_server variables on Rundeck Framework properties",
                StepFailureReason.ConfigurationFailure);

    // openshift_apiversion is a required parameters.
    if (openshift_apiversion == null)
        throw new StepException(
                "Configuration failed, missing the openshift_apiversion variables on Rundeck Framework properties",
                StepFailureReason.ConfigurationFailure);

    // One of the two authentication is need
    if (openshift_username == null && openshift_password == null && openshift_token == null)
        throw new StepException(
                "Configuration failed, missing username/password and token variable which drive the "
                        + "Openshift Authentication on Rundeck framework properties configuration file. ",
                StepFailureReason.ConfigurationFailure);

    // Define the temporary directory.
    String temp_dir = String.format("/tmp/ocdepl-%s", Long.toString(System.nanoTime()));
    String repo_dir = String.format("%s/%s", temp_dir, gitlab_deployment_directory);

    // Trying to Download the Deployment definition
    try {

        // Download the files from the Gitlab, when it's the Service Definition.
        System.out.println("Downloading repository: " + gitlab_repo + " ...");
        Git.cloneRepository().setURI(gitlab_repo).setDirectory(new File(temp_dir)).setBranch(gitlab_branch)
                .setCredentialsProvider(
                        new UsernamePasswordCredentialsProvider(gitlab_username, gitlab_password))
                .call();

        // Looking for the file on the plugins.
        String varsPath = null;
        for (String format : EXTENSION_SUPORTED) {
            String path = String.format("%s/%s/%s.%s", repo_dir, gitlab_variables_dir,
                    gitlab_deployment_environment, format);

            if (new File(path).exists()) {
                varsPath = path;
                break;
            }
        }

        // Looking for the deploymet variable
        String deploymentPath = null;
        for (String format : EXTENSION_SUPORTED) {
            String path = String.format("%s/%s.%s", repo_dir, gitlab_deployment_file, format);

            if (new File(path).exists()) {
                deploymentPath = path;
                break;
            }
        }

        // Proper way to handle errors
        if (deploymentPath == null) {
            String files = "";
            for (String format : EXTENSION_SUPORTED) {
                files = files + String.format("%s/%s.%s,", repo_dir, gitlab_deployment_file, format);
            }

            throw new StepException(
                    String.format("Not able to found any of the file list: %s on %s", files, gitlab_repo),
                    StepFailureReason.ConfigurationFailure);
        }

        // Instance the rundeck vars object mapping
        // allocating the plugin parameters to usage.
        JSONObject rundeckVars = new JSONObject() {
            {
                put("plugin", new JSONObject() {
                    {
                        put("gitlab_repo", gitlab_repo);
                        put("gitlab_branch", gitlab_branch);
                        put("gitlab_username", gitlab_username);
                        put("gitlab_deployment_file", gitlab_deployment_file);
                        put("gitlab_variable_file", gitlab_deployment_environment);

                        put("openshift_server", openshift_server);
                        put("openshift_apiversion", openshift_apiversion);
                        put("openshift_project", openshift_project);
                        put("openshift_service", openshift_service);
                        put("openshift_username", openshift_username);
                    }
                });
            }
        };

        // Read the rundeck job parameters from the JOB Context
        HashMap<String, Map<String, String>> jobContext = (HashMap<String, Map<String, String>>) context
                .getDataContext();

        if (jobContext.get("option") != null) {
            rundeckVars.put("option", jobContext.get("option"));
        }

        // Read the environment variables into map of variables.
        Object vars = null;
        if (varsPath != null) {
            YamlReader varsReader = new YamlReader(new FileReader(varsPath));
            vars = varsReader.read();
        }

        //  Read the Deployment file using template-engine to validate the blocks and dynamic content
        JtwigTemplate template = JtwigTemplate.fileTemplate(new File(deploymentPath));
        JtwigModel model = JtwigModel.newModel().with("vars", vars).with("rundeck", rundeckVars);
        String deploymentFile = template.render(model);

        // Return the Deployment Configuration from the YAML file.
        Map deployment = (Map) new YamlReader(deploymentFile).read();
        JSONObject deployConfig = new JSONObject(deployment);

        // connect to the Openshift client
        System.out.print(String.format("Connecting to Openshift server: %s ...", openshift_server));

        // Define the Openshift
        OpenshiftClient oc = new OpenshiftClient().withProject(openshift_project).withService(openshift_service)
                .withServerUrl(openshift_server).withApiVersion(openshift_apiversion)
                .withTimeout(network_timeout).withToken(openshift_token).withUsername(openshift_username)
                .withPassword(openshift_password)

                .build();

        // Validate the service status
        int serverStatus;
        if ((serverStatus = oc.getServerStatus()) != 200) {
            throw new Exception(
                    String.format("[%d] Receive when trying to return server status", serverStatus));
        } else
            System.out.println("[OK]");

        // Validate whether the project exists.
        if (!oc.checkProject(openshift_project)) {
            throw new Exception(String.format(
                    "Appears that project does not exists, or access ir forbidden, %s", openshift_project));
        }

        // Create the project whether exists
        JSONObject newReleaseResponse;
        if (!oc.checkService(openshift_service)) {
            throw new StepException(
                    String.format("Unable to found the project: %s/%s !", openshift_project, openshift_service),
                    StepFailureReason.ConfigurationFailure);

        } else {

            // Update an already existed Deployment Configuration.
            JSONObject currentDeploy = oc.getDeploymentConfig();
            if (currentDeploy != null) {
                deployConfig.put("metadata", currentDeploy.getJSONObject("metadata"));

                int latestVersion = currentDeploy.getJSONObject("status").getInt("latestVersion");
                deployConfig.getJSONObject("status").put("latestVersion", ++latestVersion);

                if (deployConfig.has("statusCode"))
                    deployConfig.remove("statusCode");
                if (deployConfig.getJSONObject("spec").getJSONObject("template").getJSONObject("metadata")
                        .has("creationTimestamp")) {

                    deployConfig.getJSONObject("spec").getJSONObject("template").getJSONObject("metadata")
                            .remove("creationTimestamp");
                }

                newReleaseResponse = oc.setDeploymentConfig(deployConfig);
            } else {
                throw new Exception("Error on try to get the Deployment Configuration");
            }

        }

        // Watch the deployment
        if (newReleaseResponse.has("status")) {
            if (newReleaseResponse.getJSONObject("status").has("latestVersion")) {
                System.out.println(String.format("Deployment #%d running, this could take some while...",
                        newReleaseResponse.getJSONObject("status").getInt("latestVersion")));
            }
        }

        // Watching the Deployment of the Services.
        int attempts = 0;
        while (oc.notReady()) {
            if (attempts >= network_max_count_attemps) {
                throw new StepException("Openshift deployment took to long to finished. ",
                        StepFailureReason.PluginFailed);
            } else
                Thread.sleep(network_attempts_time_interval * 1000);

            attempts += 1;
        }

        dumpStatus(oc.getDeploymentConfig());
    } catch (Exception ex) {
        throw new StepException(
                "Error on trying automate Openshift Deployment & Provision\nError msg: " + ex.getMessage(),
                StepFailureReason.PluginFailed);
    } finally {

        // House cleaning when need.
        try {
            FileUtils.deleteDir(new File(repo_dir));
        } catch (Exception ex) {
            /* Do NOTHING */ }
    }
}

From source file:br.com.riselabs.cotonet.crawler.RepositoryCrawler.java

License:Open Source License

/**
 * Clones the project's repository of this {@code RepositoryCrawler}
 * instance. The method {@code #getRepository()} returns an object that
 * represents the repository./*from  www .  j  a  v a2 s .  c  o  m*/
 * 
 * @param repositoryURL
 * @return
 * @throws IOException
 * @throws InvalidRemoteException
 * @throws TransportException
 * @throws GitAPIException
 */
public Repository cloneRepository() {
    Git result;
    try {
        Logger.log(log, "[" + getProject().getName() + "] Cloning Start.");
        result = Git.cloneRepository().setURI(project.getUrl() + ".git").setDirectory(repositoryDir).call();
        Logger.log(log, "[" + getProject().getName() + "] Cloning Finished.");
        return result.getRepository();
    } catch (GitAPIException e) {
        Logger.log(log, "[" + getProject().getName() + "] Cloning Failed.");
        Logger.logStackTrace(log, e);
    }
    System.gc();
    return null;
}

From source file:br.edu.ifpb.scm.api.git.Github.java

public Git clone(File directory, String url) throws GitAPIException, IOException {
    try {//from   ww w  .ja v a2s .c o  m
        if (!directory.exists() && !directory.isDirectory()) {
            return Git.cloneRepository().setURI(url).setDirectory(directory).call();
        }
        return this.getRepository(directory);
    } catch (ReferenceException e) {
        throw new IOException("fatal: Not a repository git.");
    }
}

From source file:br.gov.servicos.editor.conteudo.RepositorioGitTest.java

@SneakyThrows
private static void clone(String from, File to) {
    Git.cloneRepository().setURI(from).setDirectory(to).setProgressMonitor(new TextProgressMonitor()).call();
}

From source file:br.gov.servicos.editor.conteudo.RepositorioGitTest.java

@SneakyThrows
private static void cloneBare(String from, File to) {
    Git.cloneRepository().setURI(from).setDirectory(to).setBare(true)
            .setProgressMonitor(new TextProgressMonitor()).call();
}