Example usage for org.eclipse.jgit.transport SshSessionFactory setInstance

List of usage examples for org.eclipse.jgit.transport SshSessionFactory setInstance

Introduction

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

Prototype

public static void setInstance(SshSessionFactory newFactory) 

Source Link

Document

Change the JVM-wide factory to a different implementation.

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  . ja v  a2s  .  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:com.gitblit.tests.SshDaemonTest.java

License:Apache License

@Test
public void testCloneCommand() throws Exception {
    if (ticgitFolder.exists()) {
        GitBlitSuite.close(ticgitFolder);
        FileUtils.delete(ticgitFolder, FileUtils.RECURSIVE);
    }/*from  w ww . java  2s.c  o  m*/

    // set clone restriction
    RepositoryModel model = repositories().getRepositoryModel("ticgit.git");
    model.accessRestriction = AccessRestrictionType.CLONE;
    model.authorizationControl = AuthorizationControl.NAMED;
    repositories().updateRepositoryModel(model.name, model, false);

    JschConfigTestSessionFactory sessionFactory = new JschConfigTestSessionFactory(roKeyPair);
    SshSessionFactory.setInstance(sessionFactory);

    CloneCommand clone = Git.cloneRepository();
    clone.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password));
    clone.setURI(MessageFormat.format("{0}/ticgit.git", url));
    clone.setDirectory(ticgitFolder);
    clone.setBare(false);
    clone.setCloneAllBranches(true);
    Git git = clone.call();
    List<RevCommit> commits = JGitUtils.getRevLog(git.getRepository(), 10);
    GitBlitSuite.close(git);
    assertEquals(10, commits.size());

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

From source file:com.google.gerrit.acceptance.git.GitUtil.java

License:Apache License

public static void initSsh(final TestAccount a) {
    final Properties config = new Properties();
    config.put("StrictHostKeyChecking", "no");
    JSch.setConfig(config);// w w  w .j  a v a2 s  .  com

    // register a JschConfigSessionFactory that adds the private key as identity
    // to the JSch instance of JGit so that SSH communication via JGit can
    // succeed
    SshSessionFactory.setInstance(new JschConfigSessionFactory() {
        @Override
        protected void configure(Host hc, Session session) {
            try {
                final JSch jsch = getJSch(hc, FS.DETECTED);
                jsch.addIdentity("KeyPair", a.privateKey(), a.sshKey.getPublicKeyBlob(), null);
            } catch (JSchException e) {
                throw new RuntimeException(e);
            }
        }
    });
}

From source file:com.meltmedia.cadmium.core.git.GitService.java

License:Apache License

public static void setupSsh(String sshDir) {
    if (SshSessionFactory.getInstance() == null || !SshSessionFactory.getInstance().getClass().getName()
            .equals(GithubConfigSessionFactory.class.getName())) {
        log.debug("Setting SSH session factory for ssh dir path {}", sshDir);
        SshSessionFactory.setInstance(new GithubConfigSessionFactory(sshDir));
    }//from w ww  .java 2 s  . co  m
}

From source file:com.meltmedia.cadmium.core.git.GitService.java

License:Apache License

public static void setupLocalSsh(String sshDir, boolean noPrompt) {
    SshSessionFactory.setInstance(new LocalConfigSessionFactory(sshDir, noPrompt));
}

From source file:com.photon.phresco.framework.impl.SCMManagerImpl.java

License:Apache License

void additionalAuthentication(String passPhrase) {
    final String passwordPhrase = passPhrase;
    JschConfigSessionFactory sessionFactory = new JschConfigSessionFactory() {
        @Override/* w ww  . ja  v a 2 s . c o m*/
        protected void configure(OpenSshConfig.Host hc, Session session) {
            CredentialsProvider provider = new CredentialsProvider() {
                @Override
                public boolean isInteractive() {
                    return false;
                }

                @Override
                public boolean supports(CredentialItem... items) {
                    return true;
                }

                @Override
                public boolean get(URIish uri, CredentialItem... items) throws UnsupportedCredentialItem {
                    for (CredentialItem item : items) {
                        if (item instanceof CredentialItem.StringType) {
                            ((CredentialItem.StringType) item).setValue(passwordPhrase);
                        }
                    }
                    return true;
                }
            };
            UserInfo userInfo = new CredentialsProviderUserInfo(session, provider);
            // Unknown host key for ssh
            java.util.Properties config = new java.util.Properties();
            config.put(STRICT_HOST_KEY_CHECKING, NO);
            session.setConfig(config);

            session.setUserInfo(userInfo);
        }
    };

    SshSessionFactory.setInstance(sessionFactory);

    /*
     * Enable clone of https url by trusting those urls
     */
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };

    final String https_proxy = System.getenv(HTTPS_PROXY);
    final String http_proxy = System.getenv(HTTP_PROXY);

    ProxySelector.setDefault(new ProxySelector() {
        final ProxySelector delegate = ProxySelector.getDefault();

        @Override
        public List<Proxy> select(URI uri) {
            // Filter the URIs to be proxied

            if (uri.toString().contains(HTTPS) && StringUtils.isNotEmpty(http_proxy) && http_proxy != null) {
                try {
                    URI httpsUri = new URI(https_proxy);
                    String host = httpsUri.getHost();
                    int port = httpsUri.getPort();
                    return Arrays.asList(new Proxy(Type.HTTP, InetSocketAddress.createUnresolved(host, port)));
                } catch (URISyntaxException e) {
                    if (debugEnabled) {
                        S_LOGGER.debug("Url exception caught in https block of additionalAuthentication()");
                    }
                }
            }

            if (uri.toString().contains(HTTP) && StringUtils.isNotEmpty(http_proxy) && http_proxy != null) {
                try {
                    URI httpUri = new URI(http_proxy);
                    String host = httpUri.getHost();
                    int port = httpUri.getPort();
                    return Arrays.asList(new Proxy(Type.HTTP, InetSocketAddress.createUnresolved(host, port)));
                } catch (URISyntaxException e) {
                    if (debugEnabled) {
                        S_LOGGER.debug("Url exception caught in http block of additionalAuthentication()");
                    }
                }
            }

            // revert to the default behaviour
            return delegate == null ? Arrays.asList(Proxy.NO_PROXY) : delegate.select(uri);
        }

        @Override
        public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
            if (uri == null || sa == null || ioe == null) {
                throw new IllegalArgumentException("Arguments can't be null.");
            }
        }
    });

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance(SSL);
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (GeneralSecurityException e) {
        e.getLocalizedMessage();
    }
}

From source file:com.stormcloud.ide.api.git.GitManager.java

License:Open Source License

@Override
public String cloneRemoteRepository(String uri) throws GitManagerException {

    SshSessionFactory.setInstance(new JschConfigSessionFactory() {

        @Override// w  w  w . j  a va 2s  .com
        protected void configure(Host hc, Session session) {

            try {

                session.setConfig("StrictHostKeyChecking", "no");

                String keyLocation = RemoteUser.get().getSetting(UserSettings.SSH_HOME) + "/"
                        + RemoteUser.get().getUserName();
                String knownHosts = RemoteUser.get().getSetting(UserSettings.SSH_HOME) + "/known_hosts";

                LOG.debug("KeyLoacation " + keyLocation);
                LOG.debug("KnownHosts " + knownHosts);

                JSch jsch = getJSch(hc, FS.DETECTED);
                jsch.addIdentity(keyLocation);
                jsch.setKnownHosts(knownHosts);

            } catch (JSchException e) {
                LOG.error(e);
            }
        }
    });

    CloneCommand cloneCommand = Git.cloneRepository();

    int start = uri.lastIndexOf("/");

    if (start == -1) {
        start = uri.lastIndexOf(":");
    }

    String folder = uri.substring(start + 1, uri.length());

    LOG.info("Cloning : " + uri + " into " + folder);

    cloneCommand
            .setDirectory(new File(RemoteUser.get().getSetting(UserSettings.PROJECT_FOLDER) + "/" + folder));
    cloneCommand.setURI(uri);

    try {

        cloneCommand.call();

    } catch (GitAPIException e) {
        LOG.error(e);
        throw new GitManagerException(e);
    }

    return "0";
}

From source file:es.logongas.openshift.ant.impl.OpenShiftUtil.java

License:Apache License

public void gitCloneApplication(String serverUrl, String userName, String password, String domainName,
        String applicationName, String privateKeyFile, String path) throws GitAPIException {
    IUser user = getUser(serverUrl, userName, password);

    IDomain domain = user.getDomain(domainName);
    IApplication application = domain.getApplicationByName(applicationName);
    String gitURL = application.getGitUrl();

    SshSessionFactory.setInstance(new CustomConfigSessionFactory(privateKeyFile));

    CloneCommand cloneCommand = new CloneCommand();
    cloneCommand.setURI(gitURL);//from   w  w  w  . j a  v  a  2s.  c om
    cloneCommand.setDirectory(new File(path));
    cloneCommand.setTimeout(20);
    cloneCommand.setProgressMonitor(new TextProgressMonitor());
    cloneCommand.call();

}

From source file:es.logongas.openshift.ant.impl.OpenShiftUtil.java

License:Apache License

public void gitPushApplication(String serverUrl, String userName, String password, String domainName,
        String applicationName, String privateKeyFile, String path) throws GitAPIException, IOException {

    SshSessionFactory.setInstance(new CustomConfigSessionFactory(privateKeyFile));

    Git git = Git.open(new File(path));

    PushCommand push = git.push();/*from w  w  w  .ja  v  a 2 s . c o m*/
    push.setProgressMonitor(new TextProgressMonitor());
    LOGGER.info("Finalizado push");
    LOGGER.info("Mostrando resultados");
    Iterable<PushResult> pushResults = push.call();
    for (PushResult pushResult : pushResults) {
        LOGGER.info(pushResult.getMessages());
    }

}

From source file:eu.cloud4soa.cli.roo.addon.commands.GitManager.java

License:Apache License

public void init() throws Exception {
    FileRepositoryBuilder builder;/*from   ww w .j  a  va  2s  .  c  o  m*/

    gitRepository = new FileRepository(localPath + "/" + ".git");
    builder = new FileRepositoryBuilder();
    gitRepository = builder.setGitDir(new File(localPath + "/.git")).readEnvironment().findGitDir().build();
    git = new Git(gitRepository);

    GithubSshSessionFactory factory = new GithubSshSessionFactory();
    factory.setKeyLocation(sshKeyDir);
    factory.setPassphrase(passphrase);
    SshSessionFactory.setInstance(factory);

}