Example usage for org.eclipse.jgit.transport JschConfigSessionFactory JschConfigSessionFactory

List of usage examples for org.eclipse.jgit.transport JschConfigSessionFactory JschConfigSessionFactory

Introduction

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

Prototype

JschConfigSessionFactory

Source Link

Usage

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

License:Apache License

private void setupCredentials(CloneCommand command) {
    command.setTransportConfigCallback(new TransportConfigCallback() {
        @Override/*from  w  w w .  j  a  v a2 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.openshift.agent.SshSessionFactoryUtils.java

License:Apache License

public static <T> T useOpenShiftSessionFactory(Callable<T> callable) throws Exception {
    SshSessionFactory oldFactory = SshSessionFactory.getInstance();
    try {//w ww .  java2s.  com
        SshSessionFactory.setInstance(new JschConfigSessionFactory() {
            @Override
            protected void configure(OpenSshConfig.Host hc, Session session) {
                session.setConfig("StrictHostKeyChecking", "no");
            }
        });

        return callable.call();
    } finally {
        SshSessionFactory.setInstance(oldFactory);
    }
}

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 ww  .j  av 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");
    }/*from  w w  w  . j a  va 2  s .  c  om*/

    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.gobblin.service.modules.core.GitMonitoringService.java

License:Apache License

private SshSessionFactory getSshSessionFactory() {
    JschConfigSessionFactory sessionFactory = new JschConfigSessionFactory() {
        @Override/*  ww w  .  jav  a  2s.co  m*/
        protected void configure(OpenSshConfig.Host hc, Session session) {
            if (!GitMonitoringService.this.strictHostKeyCheckingEnabled) {
                session.setConfig("StrictHostKeyChecking", "no");
            }
        }

        @Override
        protected JSch createDefaultJSch(FS fs) throws JSchException {
            if (GitMonitoringService.this.isJschLoggerEnabled) {
                JSch.setLogger(new JschLogger());
            }
            JSch defaultJSch = super.createDefaultJSch(fs);
            defaultJSch.getIdentityRepository().removeAll();
            if (GitMonitoringService.this.privateKeyPath != null) {
                defaultJSch.addIdentity(GitMonitoringService.this.privateKeyPath,
                        GitMonitoringService.this.passphrase);
            } else {
                defaultJSch.addIdentity("gaas-git", GitMonitoringService.this.privateKey, null,
                        GitMonitoringService.this.passphrase.getBytes(Charset.forName("UTF-8")));
            }
            if (!Strings.isNullOrEmpty(GitMonitoringService.this.knownHosts)) {
                defaultJSch.setKnownHosts(new ByteArrayInputStream(
                        GitMonitoringService.this.knownHosts.getBytes(Charset.forName("UTF-8"))));
            } else if (!Strings.isNullOrEmpty(GitMonitoringService.this.knownHostsFile)) {
                defaultJSch.setKnownHosts(GitMonitoringService.this.knownHostsFile);
            }
            return defaultJSch;
        }
    };
    return sessionFactory;
}

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

License:Apache License

/**
 * Clones a Git repository//from   ww  w .jav  a2s.  c om
 * @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.craftercms.commons.git.auth.SshRsaKeyPairAuthConfigurator.java

License:Open Source License

@Override
protected SshSessionFactory createSessionFactory() {
    return new JschConfigSessionFactory() {

        @Override//from w  w w  .j  a  v a2 s.co m
        protected JSch createDefaultJSch(FS fs) throws JSchException {
            JSch defaultJSch = super.createDefaultJSch(fs);

            if (StringUtils.isNotEmpty(privateKeyPath)) {
                if (StringUtils.isNotEmpty(passphrase)) {
                    defaultJSch.addIdentity(privateKeyPath, passphrase);
                } else {
                    defaultJSch.addIdentity(privateKeyPath);
                }
            }

            return defaultJSch;
        }

        @Override
        protected void configure(OpenSshConfig.Host host, Session session) {
            setHostKeyType(host, session);
        }

    };
}

From source file:org.craftercms.commons.git.auth.SshUsernamePasswordAuthConfigurator.java

License:Open Source License

@Override
protected SshSessionFactory createSessionFactory() {
    return new JschConfigSessionFactory() {

        @Override// w w w .j  a  va 2 s.  c o m
        protected void configure(OpenSshConfig.Host hc, Session session) {
            session.setPassword(password);

            setHostKeyType(hc, session);
        }

    };
}

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

License:Open Source License

/**
 * Execute remote jgit command./*from w w  w .  ja v a 2  s . c  o  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.jabylon.team.git.GitTeamProvider.java

License:Open Source License

private TransportConfigCallback createTransportConfigCallback(Project project) {

    Preferences node = PreferencesUtil.scopeFor(project);
    //        String username = node.get(GitConstants.KEY_USERNAME, "");
    final String password = node.get(GitConstants.KEY_PASSWORD, "");
    String privateKey = node.get(GitConstants.KEY_PRIVATE_KEY, null);
    File tempFile = null;/*from w w  w  .  j  a  v  a 2s  .c  o  m*/
    if (privateKey != null) {
        try {
            // store it somewhere temporary
            File tempDir = new File(new File(ServerConstants.WORKING_DIR), "temp");
            tempDir.mkdirs();
            tempFile = File.createTempFile("temp", ".key", tempDir);
            Files.copy(new ByteArrayInputStream(privateKey.getBytes("UTF-8")), tempFile.toPath(),
                    StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            LOGGER.error("Could not store private key to " + tempFile.getAbsolutePath(), e);
        }

    }
    final File keyFile = tempFile;
    final SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {

        AtomicInteger sessionCounter = new AtomicInteger();

        @Override
        protected void configure(Host host, Session session) {

            // do nothing
        }

        protected JSch createDefaultJSch(FS fs) throws JSchException {
            JSch defaultJSch = super.createDefaultJSch(fs);
            if (keyFile != null)
                defaultJSch.addIdentity(keyFile.getAbsolutePath(), password);
            return defaultJSch;
        }

        @Override
        protected Session createSession(Host hc, String user, String host, int port, FS fs)
                throws JSchException {
            sessionCounter.getAndIncrement();
            return super.createSession(hc, user, host, port, fs);
        }

        @Override
        public void releaseSession(RemoteSession session) {
            if (sessionCounter.decrementAndGet() == 0) {
                LOGGER.debug("Connection closing, deleting keyfile");
                keyFile.delete();
            }
            super.releaseSession(session);
        }

    };
    return new TransportConfigCallback() {

        @Override
        public void configure(Transport transport) {
            SshTransport sshTransport = (SshTransport) transport;
            sshTransport.setSshSessionFactory(sshSessionFactory);
        }
    };
}