Example usage for org.eclipse.jgit.transport RemoteSession exec

List of usage examples for org.eclipse.jgit.transport RemoteSession exec

Introduction

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

Prototype

Process exec(String commandName, int timeout) throws IOException;

Source Link

Document

Generate a new remote process to execute the given command.

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  ww  .java2  s .  c  o  m*/
        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;
    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;/*from   w  w  w . j  a  va2  s  .  co  m*/
    }

    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.ReplicationQueue.java

License:Apache License

private void executeRemoteSsh(URIish uri, String cmd, OutputStream errStream) throws IOException {
    RemoteSession ssh = connect(uri);
    Process proc = ssh.exec(cmd, 0);
    proc.getOutputStream().close();/*  w  ww.  j a  v  a 2s. c o  m*/
    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.
    }
    ssh.disconnect();
}

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;
    Process process = null;/*from   w w  w . ja  v a  2  s. c o  m*/
    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 w  w  w.  j  a v a 2 s . co 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

@Override
public String publishLog(BuildbotConfig config, String ticket, String boxId, TaskStatus status,
        InputStream in) {/*  ww  w.java2s. co  m*/
    final String cmd = JENKINS_SSH_COMMAND + " --display " + ticket + "_" + boxId + " --dump-build-number "
            + " --job " + config.getExternalLogViewerJob() + " --result " + (status.isSuccess() ? "0" : "1")
            + " --log -";
    OutputStream errStream = newErrorBufferStream();
    OutputStream outStream = newErrorBufferStream();
    URIish jenkins = null;
    try {
        jenkins = new URIish().setHost(config.getExternalLogViewerHost());
        RemoteSession ssh = connect(jenkins);
        Process proc = ssh.exec(cmd, 0/*timeout*/);
        StreamCopyThread out = new StreamCopyThread(proc.getInputStream(), outStream);
        StreamCopyThread err = new StreamCopyThread(proc.getErrorStream(), errStream);
        StreamCopyThread inp = new StreamCopyThread(in, proc.getOutputStream());
        out.start();
        err.start();
        inp.start();
        try {
            out.flush();
            err.flush();
            inp.flush();
            proc.waitFor();
            proc.exitValue();
            out.halt();
            err.halt();
            inp.halt();
        } catch (InterruptedException interrupted) {
            log.error("process interupted: ", interrupted);
        }
        ssh.disconnect();
    } catch (IOException e) {
        log.error(String.format(
                "Error pushing log to %s:\n" + "  Exception: %s\n" + " Command: %s\n" + "  Output: %s", jenkins,
                e, cmd, errStream), e);
        return null;
    }
    String result = String.format("%s/job/%s/%s", config.getExternalLogViewerUrl(),
            config.getExternalLogViewerJob(), outStream.toString().trim());
    log.debug("log url: {}", result);
    return result;
}

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

License:Mozilla Public License

@Override
public String testChannel(BuildbotConfig config) {
    final String cmd = JENKINS_TEST_CHANNEL;
    StringBuilder builder = new StringBuilder(cmd.length()).append(">ssh ")
            .append(config.getExternalLogViewerHost()).append(" ").append(cmd).append("\n");
    OutputStream errStream = newErrorBufferStream();
    OutputStream outStream = newErrorBufferStream();
    URIish jenkins = null;// w  ww. ja  va  2s.  c o  m
    try {
        jenkins = new URIish().setHost(config.getExternalLogViewerHost());
        RemoteSession ssh = connect(jenkins);
        Process proc = ssh.exec(cmd, 0/*timeout*/);
        StreamCopyThread out = new StreamCopyThread(proc.getInputStream(), outStream);
        StreamCopyThread err = new StreamCopyThread(proc.getErrorStream(), errStream);
        out.start();
        err.start();
        try {
            out.flush();
            err.flush();
            proc.waitFor();
            proc.exitValue();
            out.halt();
            err.halt();
        } catch (InterruptedException interrupted) {
            log.error("process interupted: ", interrupted);
        }
        ssh.disconnect();
        return builder.append("<").append(outStream.toString()).toString();
    } catch (IOException e) {
        log.error(String.format(
                "Error testing log channel\n" + "  Exception: %s\n" + " Command: %s\n" + "  Output: %s",
                jenkins, e, cmd, errStream), e);
        return null;
    }
}

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

License:Apache License

private static ValidationResult isValidRemoteRepository(URIish repoUri) {
    ValidationResult result;/*from w ww. java 2  s.  co  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;
}