Example usage for org.eclipse.jgit.transport SshTransport setSshSessionFactory

List of usage examples for org.eclipse.jgit.transport SshTransport setSshSessionFactory

Introduction

In this page you can find the example usage for org.eclipse.jgit.transport SshTransport setSshSessionFactory.

Prototype

public void setSshSessionFactory(SshSessionFactory factory) 

Source Link

Document

Set SSH session factory instead of the default one for this instance of the transport.

Usage

From source file:GitHelper.java

License:Apache License

public static File cloneRepository(String cloneUrl, String repoPw)
        throws GitAPIException, JSONException, IOException {
    config = ConfigParser.getConfig();//w  w w  .  jav a 2s.  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:bluej.groupwork.git.GitCommand.java

License:Open Source License

/**
 * Prepare a TransportCommand to be executed later.
 * This method checks if the command is using ssh. if it is,
 * then it will disable SSH's fingerprint detection and use
 * username and password authentication.
 * @param command The command to be configured.
 *//*from   w w w  . ja va2 s  . c  o m*/
public void disableFingerprintCheck(TransportCommand command) {
    //check if the command is not null and conects via ssh.
    if (command != null && repository.getReposUrl().startsWith("ssh")) {
        //disable ssh host fingerprint check.
        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);
            }
        };

        command.setTransportConfigCallback((Transport t) -> {
            SshTransport sshTransport = (SshTransport) t;
            sshTransport.setSshSessionFactory(sshSessionFactory);
        });
        command.setCredentialsProvider(getRepository().getCredentialsProvider());
    }
}

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

License:Open Source License

@Override
public TeamworkCommandResult checkConnection(TeamSettings settings) {

    try {//  ww  w.j  a  va  2 s. c  o m
        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: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.");
    }//  ww  w  .  ja va2  s .  co 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:com.mooregreatsoftware.gitprocess.transport.GitTransportConfigCallback.java

License:Apache License

@Override
public void configure(Transport transport) {
    if (transport instanceof SshTransport) {
        SshTransport sshTransport = (SshTransport) transport;
        sshTransport.setSshSessionFactory(new SshAgentJschConfigSessionFactory());
    }/*from ww w  .j a v  a 2  s .co m*/
}

From source file:eu.atos.paas.git.Repository.java

License:Open Source License

private TransportConfigCallback getTransportConfigCallback() {

    if (transportConfigCallback == null) {
        transportConfigCallback = new TransportConfigCallback() {
            @Override//from   ww  w  . j  ava2 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
 *///  w  w w . j a  va  2s.c  o  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   w  ww  .  j  a v  a 2 s .c o m*/
        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
 *///from   www .j  a  va2s  .  co  m
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 a 2  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);
    }
}