Example usage for org.eclipse.jgit.api TransportConfigCallback TransportConfigCallback

List of usage examples for org.eclipse.jgit.api TransportConfigCallback TransportConfigCallback

Introduction

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

Prototype

TransportConfigCallback

Source Link

Usage

From source file:GitHelper.java

License:Apache License

public static File cloneRepository(String cloneUrl, String repoPw)
        throws GitAPIException, JSONException, IOException {
    config = ConfigParser.getConfig();//from w w  w.  j  a  v  a  2  s. c o  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: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 ww  .  j ava2 s .c o m*/

    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:eu.atos.paas.git.Repository.java

License:Open Source License

private TransportConfigCallback getTransportConfigCallback() {

    if (transportConfigCallback == null) {
        transportConfigCallback = new TransportConfigCallback() {
            @Override//from w  w w . ja  v  a  2 s  .co m
            public void configure(Transport transport) {
                SshTransport sshTransport = (SshTransport) transport;
                sshTransport.setSshSessionFactory(getSshSessionFactory());
            }
        };
    }
    return transportConfigCallback;
}

From source file:io.fabric8.collector.git.GitHelpers.java

License:Apache License

/**
 * Configures the transport of the command to deal with things like SSH
 *///from   ww w  . jav a  2 s .  co  m
public static <C extends GitCommand> void configureCommand(TransportCommand<C, ?> command,
        CredentialsProvider credentialsProvider, final File sshPrivateKey, final File sshPublicKey) {
    if (sshPrivateKey != null) {
        final CredentialsProvider provider = credentialsProvider;
        command.setTransportConfigCallback(new TransportConfigCallback() {
            @Override
            public void configure(Transport transport) {
                if (transport instanceof SshTransport) {
                    SshTransport sshTransport = (SshTransport) transport;
                    SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
                        @Override
                        protected void configure(OpenSshConfig.Host host, Session session) {
                            session.setConfig("StrictHostKeyChecking", "no");
                            UserInfo userInfo = new CredentialsProviderUserInfo(session, provider);
                            session.setUserInfo(userInfo);
                        }

                        @Override
                        protected JSch createDefaultJSch(FS fs) throws JSchException {
                            JSch jsch = super.createDefaultJSch(fs);
                            jsch.removeAllIdentity();
                            String absolutePath = sshPrivateKey.getAbsolutePath();
                            if (LOG.isDebugEnabled()) {
                                LOG.debug("Adding identity privateKey: " + sshPrivateKey + " publicKey: "
                                        + sshPublicKey);
                            }
                            if (sshPublicKey != null) {
                                jsch.addIdentity(absolutePath, sshPublicKey.getAbsolutePath(), null);
                            } else {
                                jsch.addIdentity(absolutePath);
                            }
                            return jsch;
                        }
                    };
                    sshTransport.setSshSessionFactory(sshSessionFactory);
                }
            }
        });
    }
}

From source file:io.fabric8.maven.HelmMojo.java

License:Apache License

private void setupCredentials(CloneCommand command) {
    command.setTransportConfigCallback(new TransportConfigCallback() {
        @Override//from  ww w .  j av a 2  s.c  om
        public void configure(Transport transport) {
            SshTransport sshTransport = (SshTransport) transport;
            sshTransport.setSshSessionFactory(new JschConfigSessionFactory() {
                @Override
                protected void configure(OpenSshConfig.Host host, Session session) {
                }

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

                    // If private key path is set, use this
                    if (!Strings.isNullOrBlank(privateKeyPath)) {
                        getLog().debug("helm: Using SSH private key from " + privateKeyPath);
                        jsch.removeAllIdentity();
                        if (!Strings.isNullOrBlank(privateKeyPassphrase)) {
                            jsch.addIdentity(privateKeyPath, privateKeyPassphrase);
                        } else {
                            jsch.addIdentity(privateKeyPath);
                        }
                    } else {
                        try {
                            // Try using an ssh-agent first
                            ConnectorFactory cf = ConnectorFactory.getDefault();
                            Connector con = cf.createConnector();
                            IdentityRepository irepo = new RemoteIdentityRepository(con);
                            jsch.setIdentityRepository(irepo);
                            getLog().debug("helm: Using ssh-agent");
                        } catch (AgentProxyException e) {
                            // No special handling
                            getLog().debug("helm: No ssh-agent available");
                        }
                    }
                    return jsch;
                }
            });
        }
    });
}

From source file:io.fabric8.project.support.GitUtils.java

License:Apache License

/**
 * Configures the transport of the command to deal with things like SSH
 *//*  w  w w.j  a  v  a  2  s.  c  om*/
public static <C extends GitCommand> void configureCommand(TransportCommand<C, ?> command,
        CredentialsProvider credentialsProvider, final File sshPrivateKey, final File sshPublicKey) {
    LOG.info("Using " + credentialsProvider);
    if (sshPrivateKey != null) {
        final CredentialsProvider provider = credentialsProvider;
        command.setTransportConfigCallback(new TransportConfigCallback() {
            @Override
            public void configure(Transport transport) {
                if (transport instanceof SshTransport) {
                    SshTransport sshTransport = (SshTransport) transport;
                    SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
                        @Override
                        protected void configure(OpenSshConfig.Host host, Session session) {
                            session.setConfig("StrictHostKeyChecking", "no");
                            UserInfo userInfo = new CredentialsProviderUserInfo(session, provider);
                            session.setUserInfo(userInfo);
                        }

                        @Override
                        protected JSch createDefaultJSch(FS fs) throws JSchException {
                            JSch jsch = super.createDefaultJSch(fs);
                            jsch.removeAllIdentity();
                            String absolutePath = sshPrivateKey.getAbsolutePath();
                            if (LOG.isDebugEnabled()) {
                                LOG.debug("Adding identity privateKey: " + sshPrivateKey + " publicKey: "
                                        + sshPublicKey);
                            }
                            if (sshPublicKey != null) {
                                jsch.addIdentity(absolutePath, sshPublicKey.getAbsolutePath(), null);
                            } else {
                                jsch.addIdentity(absolutePath);
                            }
                            return jsch;
                        }
                    };
                    sshTransport.setSshSessionFactory(sshSessionFactory);
                }
            }
        });
    }
}

From source file:io.vertx.config.git.GitConfigStore.java

License:Apache License

public GitConfigStore(Vertx vertx, JsonObject configuration) {
    this.vertx = vertx;

    String path = Objects.requireNonNull(configuration.getString("path"),
            "The `path` configuration is required.");
    this.path = new File(path);
    if (this.path.isFile()) {
        throw new IllegalArgumentException("The `path` must not be a file");
    }//w w w.  j  av  a2  s . c  o  m

    JsonArray filesets = Objects.requireNonNull(configuration.getJsonArray("filesets"),
            "The `filesets` element is required.");

    for (Object o : filesets) {
        JsonObject json = (JsonObject) o;
        FileSet set = new FileSet(vertx, this.path, json);
        this.filesets.add(set);
    }

    // Git repository
    url = Objects.requireNonNull(configuration.getString("url"),
            "The `url` configuration (Git repository location) is required.");
    branch = configuration.getString("branch", "master");
    remote = configuration.getString("remote", "origin");

    if (Objects.nonNull(configuration.getString("user"))
            && Objects.nonNull(configuration.getString("password"))) {
        credentialProvider = new UsernamePasswordCredentialsProvider(configuration.getString("user"),
                configuration.getString("password"));
    } else {
        credentialProvider = null;
    }
    if (Objects.nonNull(configuration.getString("idRsaKeyPath"))) {
        SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
            @Override
            protected void configure(OpenSshConfig.Host host, Session session) {
            }

            @Override
            protected JSch createDefaultJSch(FS fs) throws JSchException {
                JSch defaultJSch = super.createDefaultJSch(fs);
                defaultJSch.setConfig("StrictHostKeyChecking", "no");
                defaultJSch.addIdentity(configuration.getString("idRsaKeyPath"));
                return defaultJSch;
            }
        };
        transportConfigCallback = new TransportConfigCallback() {
            @Override
            public void configure(Transport transport) {
                SshTransport sshTransport = (SshTransport) transport;
                sshTransport.setSshSessionFactory(sshSessionFactory);
            }
        };
    } else {
        transportConfigCallback = null;
    }

    try {
        git = initializeGit();
    } catch (Exception e) {
        throw new VertxException("Unable to initialize the Git repository", e);
    }
}

From source file:org.apache.oozie.action.hadoop.GitOperations.java

License:Apache License

/**
 * Clones a Git repository//from w w w . j a  va  2s  .c  o m
 * @param outputDir location in which to clone the Git repository
 * @throws GitOperationsException if the Git clone fails
 */
private void cloneRepo(final File outputDir) throws GitOperationsException {
    final SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
        @Override
        protected void configure(final OpenSshConfig.Host host, final Session session) {
            // nop
        }

        @Override
        protected JSch createDefaultJSch(final FS fs) throws JSchException {
            JSch.setConfig("StrictHostKeyChecking", "no");
            final JSch defaultJSch = super.createDefaultJSch(fs);

            if (credentialFile != null) {
                defaultJSch.addIdentity(credentialFile.toString());
            }

            return defaultJSch;
        }
    };

    final CloneCommand cloneCommand = Git.cloneRepository();
    cloneCommand.setURI(srcURL.toString());

    if (srcURL.getScheme().toLowerCase().equals("ssh")) {
        cloneCommand.setTransportConfigCallback(new TransportConfigCallback() {
            @Override
            public void configure(final Transport transport) {
                final SshTransport sshTransport = (SshTransport) transport;
                sshTransport.setSshSessionFactory(sshSessionFactory);
            }
        });
    }

    cloneCommand.setDirectory(outputDir);
    // set our branch identifier
    if (branch != null) {
        cloneCommand.setBranchesToClone(Arrays.asList("refs/heads/" + branch));
    }

    try {
        cloneCommand.call();
    } catch (final GitAPIException e) {
        throw new GitOperationsException("Unable to clone Git repo: ", e);
    }
}

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

License:Open Source License

/**
 * Execute remote jgit command./*from  w ww.  jav a  2s .  co m*/
 *
 * @param remoteUrl
 *         remote url
 * @param command
 *         command to execute
 * @return executed command
 * @throws GitException
 * @throws GitAPIException
 * @throws UnauthorizedException
 */
private Object executeRemoteCommand(String remoteUrl, TransportCommand command)
        throws GitException, GitAPIException, UnauthorizedException {
    String sshKeyDirectoryPath = "";
    try {
        if (GitUrlUtils.isSSH(remoteUrl)) {
            File keyDirectory = Files.createTempDir();
            sshKeyDirectoryPath = keyDirectory.getPath();
            File sshKey = writePrivateKeyFile(remoteUrl, keyDirectory);

            SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
                @Override
                protected void configure(OpenSshConfig.Host host, Session session) {
                    session.setConfig("StrictHostKeyChecking", "no");
                }

                @Override
                protected JSch getJSch(final OpenSshConfig.Host hc, FS fs) throws JSchException {
                    JSch jsch = super.getJSch(hc, fs);
                    jsch.removeAllIdentity();
                    jsch.addIdentity(sshKey.getAbsolutePath());
                    return jsch;
                }
            };
            command.setTransportConfigCallback(new TransportConfigCallback() {
                @Override
                public void configure(Transport transport) {
                    SshTransport sshTransport = (SshTransport) transport;
                    sshTransport.setSshSessionFactory(sshSessionFactory);
                }
            });
        } else {
            UserCredential credentials = credentialsLoader.getUserCredential(remoteUrl);
            if (credentials != null) {
                command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(
                        credentials.getUserName(), credentials.getPassword()));
            }
        }
        return command.call();
    } catch (GitException | TransportException exception) {
        if ("Unable get private ssh key".equals(exception.getMessage())
                || exception.getMessage().contains(ERROR_AUTHENTICATION_REQUIRED)) {
            throw new UnauthorizedException(exception.getMessage());
        } else {
            throw exception;
        }
    } finally {
        if (!sshKeyDirectoryPath.isEmpty()) {
            try {
                FileUtils.delete(new File(sshKeyDirectoryPath), FileUtils.RECURSIVE);
            } catch (IOException exception) {
                throw new GitException("Can't remove SSH key directory", exception);
            }
        }
    }
}

From source file:org.eclipse.orion.server.git.jobs.PullJob.java

License:Open Source License

private IStatus doPull() throws IOException, GitAPIException, CoreException {
    Repository db = new FileRepository(GitUtils.getGitDir(path));

    Git git = new Git(db);
    PullCommand pc = git.pull();//from w  w  w.j  ava 2 s.  co m
    pc.setCredentialsProvider(credentials);
    pc.setTransportConfigCallback(new TransportConfigCallback() {
        @Override
        public void configure(Transport t) {
            credentials.setUri(t.getURI());
        }
    });
    PullResult pullResult = pc.call();

    // handle result
    if (pullResult.isSuccessful()) {
        return Status.OK_STATUS;
    } else {

        FetchResult fetchResult = pullResult.getFetchResult();

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

        MergeStatus mergeStatus = pullResult.getMergeResult().getMergeStatus();
        if (mergeStatus.isSuccessful()) {
            return Status.OK_STATUS;
        } else {
            return new Status(IStatus.ERROR, GitActivator.PI_GIT, mergeStatus.name());
        }
    }
}