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

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

Introduction

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

Prototype

public static SshSessionFactory getInstance() 

Source Link

Document

Get the currently configured JVM-wide factory.

Usage

From source file:com.docmd.behavior.GitManager.java

public boolean isValidRemoteRepository(URIish repoUri) {
    boolean result;

    if (repoUri.getScheme().toLowerCase().startsWith("http")) {
        String path = repoUri.getPath();
        String newPath = path.endsWith("/") ? path + INFO_REFS_PATH : path + "/" + INFO_REFS_PATH;
        URIish checkUri = repoUri.setPath(newPath);
        InputStream ins = null;/*from   w  w w .ja  va 2s.c  om*/
        try {
            URLConnection conn = new URL(checkUri.toString()).openConnection();
            //conn.setReadTimeout(5000);
            ins = conn.getInputStream();
            result = true;
        } catch (Exception e) {
            if (e.getMessage().contains("403"))
                result = true;
            else
                result = false;
        } finally {
            try {
                ins.close();
            } catch (Exception e) {
                /* ignore */ }
        }
    } else {
        if (repoUri.getScheme().toLowerCase().startsWith("ssh")) {
            RemoteSession ssh = null;
            Process exec = null;
            try {
                ssh = SshSessionFactory.getInstance().getSession(repoUri, null, FS.detect(), 5000);
                exec = ssh.exec("cd " + repoUri.getPath() + "; git rev-parse --git-dir", 5000);
                Integer exitValue = null;
                do {
                    try {
                        exitValue = exec.exitValue();
                    } catch (Exception e) {
                        try {
                            Thread.sleep(1000);
                        } catch (Exception ee) {
                        }
                    }
                } while (exitValue == null);
                result = exitValue == 0;
            } catch (Exception e) {
                result = false;
            } finally {
                try {
                    exec.destroy();
                } catch (Exception e) {
                    /* ignore */ }
                try {
                    ssh.disconnect();
                } catch (Exception e) {
                    /* ignore */ }
            }
        } else {
            result = true;
        }
    }
    return result;
}

From source file:com.google.gerrit.server.git.PushReplication.java

License:Apache License

private void replicateProject(final URIish replicateURI, final String head) {
    SshSessionFactory sshFactory = SshSessionFactory.getInstance();
    RemoteSession sshSession;/* w w w  . j a v  a  2  s. co  m*/
    String projectPath = QuotedString.BOURNE.quote(replicateURI.getPath());

    if (!usingSSH(replicateURI)) {
        log.warn("Cannot create new project on remote site since the connection " + "method is not SSH: "
                + replicateURI.toString());
        return;
    }

    OutputStream errStream = createErrStream();
    String cmd = "mkdir -p " + projectPath + "&& cd " + projectPath + "&& git init --bare"
            + "&& git symbolic-ref HEAD " + QuotedString.BOURNE.quote(head);

    try {
        sshSession = sshFactory.getSession(replicateURI, null, FS.DETECTED, 0);
        Process proc = sshSession.exec(cmd, 0);
        proc.getOutputStream().close();
        StreamCopyThread out = new StreamCopyThread(proc.getInputStream(), errStream);
        StreamCopyThread err = new StreamCopyThread(proc.getErrorStream(), errStream);
        out.start();
        err.start();
        try {
            proc.waitFor();
            out.halt();
            err.halt();
        } catch (InterruptedException interrupted) {
            // Don't wait, drop out immediately.
        }
        sshSession.disconnect();
    } catch (IOException e) {
        log.error("Communication error when trying to replicate to: " + replicateURI.toString() + "\n"
                + "Error reported: " + e.getMessage() + "\n" + "Error in communication: "
                + errStream.toString());
    }
}

From source file:com.googlesource.gerrit.plugins.replication.ReplicationSshSessionFactoryProvider.java

License:Apache License

@Override
public SshSessionFactory get() {
    return SshSessionFactory.getInstance();
}

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 www. ja v  a2  s .c o  m*/
}

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 {/*from w  w w  .j ava 2 s .c  o m*/
        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:org.eclipse.egit.core.op.ConfigureGerritAfterCloneTask.java

License:Open Source License

private String runSshCommand(URIish sshUri, CredentialsProvider provider, FS fs, String command)
        throws IOException {
    RemoteSession session = null;/*www.j  a v a  2s. co m*/
    Process process = null;
    StreamCopyThread errorThread = null;
    try (MessageWriter stderr = new MessageWriter()) {
        session = SshSessionFactory.getInstance().getSession(sshUri, provider, fs, 1000 * timeout);
        process = session.exec(command, 0);
        errorThread = new StreamCopyThread(process.getErrorStream(), stderr.getRawStream());
        errorThread.start();
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream(), Constants.CHARSET))) {
            return reader.readLine();
        }
    } finally {
        if (errorThread != null) {
            try {
                errorThread.halt();
            } catch (InterruptedException e) {
                // Stop waiting and return anyway.
            } finally {
                errorThread = null;
            }
        }
        if (process != null) {
            process.destroy();
        }
        if (session != null) {
            SshSessionFactory.getInstance().releaseSession(session);
        }
    }
}

From source file:org.jboss.tools.openshift.express.internal.ui.command.TailFilesHandler.java

License:Open Source License

/**
 * Starting the tail process on the remote OpenShift Platform. This method
 * relies on the JGit SSH support (including JSch) to open a connection AND
 * execute a command in a single invocation. The connection establishement
 * requires an SSH key, and the passphrase is prompted to the user if
 * necessary.//from   ww w. j  av a 2  s .  c o  m
         
 * @param sshUrl
 * @param filePattern
 * @param optionsAndFile
 * @param console
 * @return
 * @throws URISyntaxException 
 * @throws IOException 
 */
private TailServerLogWorker startTailProcess(final String sshUrl, final String optionsAndFile,
        final MessageConsole console) throws URISyntaxException, IOException {
    JSch.setLogger(new JschToEclipseLogger());
    final SshSessionFactory sshSessionFactory = SshSessionFactory.getInstance();
    URI uri = new URI(sshUrl);
    uri.getHost();
    final URIish urish = new URIish().setHost(uri.getHost()).setUser(uri.getUserInfo());
    RemoteSession remoteSession = sshSessionFactory.getSession(urish, CredentialsProvider.getDefault(),
            FS.DETECTED, 0);
    final String command = new TailCommandBuilder(optionsAndFile).build();

    Logger.debug("ssh command to execute: " + command);
    Process process = remoteSession.exec(command, 0);
    return new TailServerLogWorker(console, process, remoteSession);
}

From source file:org.libreoffice.ci.gerrit.buildbot.publisher.JenkinsLogPublisher.java

License:Mozilla Public License

private static RemoteSession connect(URIish uri) throws TransportException {
    return SshSessionFactory.getInstance().getSession(uri, null, FS.DETECTED, 0);
}

From source file:org.springframework.cloud.config.server.environment.JGitEnvironmentRepositoryTests.java

License:Apache License

@Test
public void strictHostKeyCheckShouldCheck() throws Exception {
    String uri = "git+ssh://git@somegitserver/somegitrepo";
    SshSessionFactory.setInstance(null);
    JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository(this.environment);
    envRepository.setUri(uri);/*from   w  w w.ja v  a  2  s .c om*/
    envRepository.setBasedir(new File("./mybasedir"));
    assertTrue(envRepository.isStrictHostKeyChecking());
    envRepository.setCloneOnStart(true);
    try {
        // this will throw but we don't care about connecting.
        envRepository.afterPropertiesSet();
    } catch (Exception e) {
        final OpenSshConfig.Host hc = OpenSshConfig.get(FS.detect()).lookup("github.com");
        JschConfigSessionFactory factory = (JschConfigSessionFactory) SshSessionFactory.getInstance();
        // There's no public method that can be used to inspect the ssh configuration, so we'll reflect
        // the configure method to allow us to check that the config property is set as expected.
        Method configure = factory.getClass().getDeclaredMethod("configure", OpenSshConfig.Host.class,
                Session.class);
        configure.setAccessible(true);
        Session session = mock(Session.class);
        ArgumentCaptor<String> keyCaptor = ArgumentCaptor.forClass(String.class);
        ArgumentCaptor<String> valueCaptor = ArgumentCaptor.forClass(String.class);
        configure.invoke(factory, hc, session);
        verify(session).setConfig(keyCaptor.capture(), valueCaptor.capture());
        configure.setAccessible(false);
        assertTrue("yes".equals(valueCaptor.getValue()));
    }
}

From source file:org.z2env.impl.helper.GitTools.java

License:Apache License

private static ValidationResult isValidRemoteRepository(URIish repoUri) {
    ValidationResult result;/*from  ww  w.  j a  v  a2s  .c  o m*/

    if (repoUri.getScheme().toLowerCase().startsWith("http")) {
        String path = repoUri.getPath();
        String newPath = path.endsWith("/") ? path + INFO_REFS_PATH : path + "/" + INFO_REFS_PATH;
        URIish checkUri = repoUri.setPath(newPath);

        InputStream ins = null;
        try {
            URLConnection conn = new URL(checkUri.toString()).openConnection();
            conn.setReadTimeout(NETWORK_TIMEOUT_MSEC);
            ins = conn.getInputStream();
            result = ValidationResult.valid;

        } catch (Exception e) {
            result = ValidationResult.invalid;

        } finally {
            try {
                ins.close();
            } catch (Exception e) {
                /* ignore */ }
        }

    } else if (repoUri.getScheme().toLowerCase().startsWith("ssh")) {

        RemoteSession ssh = null;
        Process exec = null;

        try {
            ssh = SshSessionFactory.getInstance().getSession(repoUri, null, FS.detect(), 5000);
            exec = ssh.exec("cd " + repoUri.getPath() + "; git rev-parse --git-dir", 5000);

            Integer exitValue = null;
            do {
                try {
                    exitValue = exec.exitValue();
                } catch (Exception e) {
                    try {
                        Thread.sleep(1000);
                    } catch (Exception ee) {
                    }
                }
            } while (exitValue == null);

            result = exitValue == 0 ? ValidationResult.valid : ValidationResult.invalid;

        } catch (Exception e) {
            result = ValidationResult.invalid;

        } finally {
            try {
                exec.destroy();
            } catch (Exception e) {
                /* ignore */ }
            try {
                ssh.disconnect();
            } catch (Exception e) {
                /* ignore */ }
        }

    } else {

        // TODO need to implement tests for other schemas
        result = ValidationResult.cannotTell;
    }
    return result;
}