Search in sources :

Example 1 with SftpProgressMonitor

use of com.jcraft.jsch.SftpProgressMonitor in project fabric8 by jboss-fuse.

the class SshContainerProvider method uploadTo.

protected void uploadTo(Session session, URL url, String path) {
    Channel channel = null;
    try (InputStream is = url.openStream()) {
        channel = session.openChannel("sftp");
        channel.connect();
        ChannelSftp sftpChannel = (ChannelSftp) channel;
        final CountDownLatch uploadLatch = new CountDownLatch(1);
        sftpChannel.put(is, path, new SftpProgressMonitor() {

            @Override
            public void init(int op, String src, String dest, long max) {
            }

            @Override
            public boolean count(long count) {
                try {
                    return is.available() > 0;
                } catch (IOException e) {
                    return false;
                }
            }

            @Override
            public void end() {
                uploadLatch.countDown();
            }
        }, ChannelSftp.OVERWRITE);
        uploadLatch.await(10, TimeUnit.MINUTES);
    } catch (Exception e) {
        LOGGER.warn("Failed to upload. Will attempt downloading distribution via maven.");
    } finally {
        if (channel != null) {
            channel.disconnect();
        }
    }
}
Also used : ChannelSftp(com.jcraft.jsch.ChannelSftp) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Channel(com.jcraft.jsch.Channel) SftpProgressMonitor(com.jcraft.jsch.SftpProgressMonitor) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) FabricException(io.fabric8.api.FabricException) IOException(java.io.IOException)

Example 2 with SftpProgressMonitor

use of com.jcraft.jsch.SftpProgressMonitor in project narchy by automenta.

the class Sftp method run.

public void run() {
    try {
        java.util.Vector cmds = new java.util.Vector();
        byte[] buf = new byte[1024];
        int i;
        String str;
        String lhome = c.lpwd();
        StringBuilder sb = new StringBuilder();
        while (true) {
            // out.print("sftp> ");
            out.write("sftp> ".getBytes());
            cmds.removeAllElements();
            sb.setLength(0);
            loop: while (true) {
                i = in.read(buf, 0, 1024);
                if (i <= 0)
                    break;
                if (i != 1)
                    continue;
                // System.out.println(Integer.toHexString(i)+" "+Integer.toHexString(buf[0]&0xff));
                if (buf[0] == 0x08) {
                    if (sb.length() > 0) {
                        sb.setLength(sb.length() - 1);
                        out.write(del, 0, del.length);
                        out.flush();
                    }
                    continue;
                }
                if (buf[0] == 0x0d) {
                    out.write(lf, 0, lf.length);
                } else if (buf[0] == 0x0a) {
                    out.write(lf, 0, lf.length);
                } else if (buf[0] < 0x20 || (buf[0] & 0x80) != 0) {
                    continue;
                } else {
                    out.write(buf, 0, i);
                }
                out.flush();
                for (int j = 0; j < i; j++) {
                    sb.append((char) buf[j]);
                    if (buf[j] == 0x0d) {
                        System.arraycopy(sb.toString().getBytes(), 0, buf, 0, sb.length());
                        i = sb.length();
                        break loop;
                    }
                    if (buf[j] == 0x0a) {
                        System.arraycopy(sb.toString().getBytes(), 0, buf, 0, sb.length());
                        i = sb.length();
                        break loop;
                    }
                }
            }
            if (i <= 0)
                break;
            i--;
            if (i > 0 && buf[i - 1] == 0x0d)
                i--;
            if (i > 0 && buf[i - 1] == 0x0a)
                i--;
            // str=new String(buf, 0, i);
            // System.out.println("|"+str+"|");
            int s = 0;
            for (int ii = 0; ii < i; ii++) {
                if (buf[ii] == ' ') {
                    if (ii - s > 0) {
                        cmds.addElement(new String(buf, s, ii - s));
                    }
                    while (ii < i) {
                        if (buf[ii] != ' ')
                            break;
                        ii++;
                    }
                    s = ii;
                }
            }
            if (s < i) {
                cmds.addElement(new String(buf, s, i - s));
            }
            if (cmds.isEmpty())
                continue;
            String cmd = (String) cmds.elementAt(0);
            if (cmd.equals("quit")) {
                c.quit();
                break;
            }
            if (cmd.equals("exit")) {
                c.exit();
                break;
            }
            if (cmd.equals("cd") || cmd.equals("lcd")) {
                String path = null;
                if (cmds.size() < 2) {
                    if (cmd.equals("cd"))
                        path = c.getHome();
                    else
                        path = lhome;
                } else {
                    path = (String) cmds.elementAt(1);
                }
                try {
                    if (cmd.equals("cd"))
                        c.cd(path);
                    else
                        c.lcd(path);
                } catch (SftpException e) {
                    // System.out.println(e.getMessage());
                    out.write(e.getMessage().getBytes());
                    out.write(lf);
                    out.flush();
                }
                continue;
            }
            if (cmd.equals("rm") || cmd.equals("rmdir") || cmd.equals("mkdir")) {
                if (cmds.size() < 2)
                    continue;
                String path = (String) cmds.elementAt(1);
                try {
                    switch(cmd) {
                        case "rm":
                            c.rm(path);
                            break;
                        case "rmdir":
                            c.rmdir(path);
                            break;
                        default:
                            c.mkdir(path);
                            break;
                    }
                } catch (SftpException e) {
                    // System.out.println(e.getMessage());
                    out.write(e.getMessage().getBytes());
                    out.write(lf);
                    out.flush();
                }
                continue;
            }
            if (cmd.equals("lmkdir")) {
                if (cmds.size() < 2)
                    continue;
                String path = (String) cmds.elementAt(1);
                File d = new File(c.lpwd(), path);
                if (!d.mkdir()) {
                    // System.out.println(e.getMessage());
                    out.write("failed to make directory".getBytes());
                    out.write(lf);
                    out.flush();
                }
                continue;
            }
            if (cmd.equals("chgrp") || cmd.equals("chown") || cmd.equals("chmod")) {
                if (cmds.size() != 3)
                    continue;
                String path = (String) cmds.elementAt(2);
                int foo = 0;
                if (cmd.equals("chmod")) {
                    byte[] bar = ((String) cmds.elementAt(1)).getBytes();
                    int k;
                    for (int j = 0; j < bar.length; j++) {
                        k = bar[j];
                        if (k < '0' || k > '7') {
                            foo = -1;
                            break;
                        }
                        foo <<= 3;
                        foo |= (k - '0');
                    }
                    if (foo == -1)
                        continue;
                } else {
                    try {
                        foo = Integer.parseInt((String) cmds.elementAt(1));
                    } catch (Exception e) {
                        continue;
                    }
                }
                try {
                    switch(cmd) {
                        case "chgrp":
                            c.chgrp(foo, path);
                            break;
                        case "chown":
                            c.chown(foo, path);
                            break;
                        case "chmod":
                            c.chmod(foo, path);
                            break;
                    }
                } catch (SftpException e) {
                    // System.out.println(e.getMessage());
                    out.write(e.getMessage().getBytes());
                    out.write(lf);
                    out.flush();
                }
                continue;
            }
            if (cmd.equals("pwd") || cmd.equals("lpwd")) {
                str = (cmd.equals("pwd") ? "Remote" : "Local");
                str += " working directory: ";
                if (cmd.equals("pwd"))
                    str += c.pwd();
                else
                    str += c.lpwd();
                // out.print(str+"\n");
                out.write(str.getBytes());
                out.write(lf);
                out.flush();
                continue;
            }
            if (cmd.equals("ls") || cmd.equals("dir")) {
                String path = ".";
                if (cmds.size() == 2)
                    path = (String) cmds.elementAt(1);
                try {
                    java.util.Vector vv = c.ls(path);
                    if (vv != null) {
                        for (int ii = 0; ii < vv.size(); ii++) {
                            // out.print(vv.elementAt(ii)+"\n");
                            // out.write(((String)(vv.elementAt(ii))).getBytes());
                            out.write(vv.elementAt(ii).toString().getBytes());
                            out.write(lf);
                        }
                        out.flush();
                    }
                } catch (SftpException e) {
                    // System.out.println(e.getMessage());
                    out.write(e.getMessage().getBytes());
                    out.write(lf);
                    out.flush();
                }
                continue;
            }
            if (cmd.equals("lls")) {
                String path = c.lpwd();
                if (cmds.size() == 2)
                    path = (String) cmds.elementAt(1);
                try {
                    File d = new File(path);
                    String[] list = d.list();
                    for (int ii = 0; ii < list.length; ii++) {
                        out.write(list[ii].getBytes());
                        out.write(lf);
                    }
                    out.flush();
                } catch (IOException e) {
                    // System.out.println(e.getMessage());
                    out.write(e.getMessage().getBytes());
                    out.write(lf);
                    out.flush();
                }
                continue;
            }
            if (cmd.equals("get") || cmd.equals("put")) {
                if (cmds.size() != 2 && cmds.size() != 3)
                    continue;
                String p1 = (String) cmds.elementAt(1);
                // String p2=p1;
                String p2 = ".";
                if (cmds.size() == 3)
                    p2 = (String) cmds.elementAt(2);
                try {
                    SftpProgressMonitor monitor = new MyProgressMonitor(out);
                    if (cmd.equals("get"))
                        c.get(p1, p2, monitor);
                    else
                        c.put(p1, p2, monitor);
                } catch (SftpException e) {
                    // System.out.println(e.getMessage());
                    out.write(e.getMessage().getBytes());
                    out.write(lf);
                    out.flush();
                }
                continue;
            }
            if (cmd.equals("ln") || cmd.equals("symlink") || cmd.equals("rename")) {
                if (cmds.size() != 3)
                    continue;
                String p1 = (String) cmds.elementAt(1);
                String p2 = (String) cmds.elementAt(2);
                try {
                    if (cmd.equals("rename"))
                        c.rename(p1, p2);
                    else
                        c.symlink(p1, p2);
                } catch (SftpException e) {
                    // System.out.println(e.getMessage());
                    out.write(e.getMessage().getBytes());
                    out.write(lf);
                    out.flush();
                }
                continue;
            }
            if (cmd.equals("stat") || cmd.equals("lstat")) {
                if (cmds.size() != 2)
                    continue;
                String p1 = (String) cmds.elementAt(1);
                SftpATTRS attrs = null;
                try {
                    if (cmd.equals("stat"))
                        attrs = c.stat(p1);
                    else
                        attrs = c.lstat(p1);
                } catch (SftpException e) {
                    // System.out.println(e.getMessage());
                    out.write(e.getMessage().getBytes());
                    out.write(lf);
                    out.flush();
                }
                if (attrs != null) {
                    // out.println(attrs);
                    out.write(attrs.toString().getBytes());
                    out.write(lf);
                    out.flush();
                } else {
                }
                continue;
            }
            if (cmd.equals("version")) {
                // out.print("SFTP protocol version "+c.version()+"\n");
                out.write(("SFTP protocol version " + c.version()).getBytes());
                out.write(lf);
                out.flush();
                continue;
            }
            if (cmd.equals("help") || cmd.equals("help")) {
                // out.print(help+"\n");
                for (int j = 0; j < help.length; j++) {
                    out.write((help[j]).getBytes());
                    out.write(lf);
                }
                out.flush();
                continue;
            }
            // out.print("unimplemented command: "+cmd+"\n");
            out.write(("unimplemented command: " + cmd).getBytes());
            out.write(lf);
            out.flush();
        }
        try {
            in.close();
        } catch (Exception ee) {
        }
        try {
            out.close();
        } catch (Exception ee) {
        }
    } catch (Exception e) {
        System.out.println(e);
    }
}
Also used : SftpException(com.jcraft.jsch.SftpException) SftpATTRS(com.jcraft.jsch.SftpATTRS) IOException(java.io.IOException) SftpException(com.jcraft.jsch.SftpException) IOException(java.io.IOException) SftpProgressMonitor(com.jcraft.jsch.SftpProgressMonitor) File(java.io.File)

Example 3 with SftpProgressMonitor

use of com.jcraft.jsch.SftpProgressMonitor in project ant by apache.

the class ScpFromMessageBySftp method getFile.

private void getFile(final ChannelSftp channel, final ChannelSftp.LsEntry le, File localFile) throws IOException, SftpException {
    final String remoteFile = le.getFilename();
    if (!localFile.exists()) {
        final String path = localFile.getAbsolutePath();
        final int i = path.lastIndexOf(File.pathSeparator);
        if (i != -1) {
            if (path.length() > File.pathSeparator.length()) {
                new File(path.substring(0, i)).mkdirs();
            }
        }
    }
    if (localFile.isDirectory()) {
        localFile = new File(localFile, remoteFile);
    }
    final long startTime = System.currentTimeMillis();
    final long totalLength = le.getAttrs().getSize();
    SftpProgressMonitor monitor = null;
    final boolean trackProgress = getVerbose() && totalLength > HUNDRED_KILOBYTES;
    if (trackProgress) {
        monitor = getProgressMonitor();
    }
    try {
        log("Receiving: " + remoteFile + " : " + le.getAttrs().getSize());
        channel.get(remoteFile, localFile.getAbsolutePath(), monitor);
    } finally {
        final long endTime = System.currentTimeMillis();
        logStats(startTime, endTime, (int) totalLength);
    }
    if (getPreserveLastModified()) {
        FileUtils.getFileUtils().setFileLastModified(localFile, ((long) le.getAttrs().getMTime()) * 1000);
    }
}
Also used : SftpProgressMonitor(com.jcraft.jsch.SftpProgressMonitor) File(java.io.File)

Example 4 with SftpProgressMonitor

use of com.jcraft.jsch.SftpProgressMonitor in project ant by apache.

the class ScpToMessageBySftp method sendFileToRemote.

private void sendFileToRemote(final ChannelSftp channel, final File localFile, String remotePath) throws IOException, SftpException {
    final long filesize = localFile.length();
    if (remotePath == null) {
        remotePath = localFile.getName();
    }
    final long startTime = System.currentTimeMillis();
    final long totalLength = filesize;
    // only track progress for files larger than 100kb in verbose mode
    final boolean trackProgress = getVerbose() && filesize > HUNDRED_KILOBYTES;
    SftpProgressMonitor monitor = null;
    if (trackProgress) {
        monitor = getProgressMonitor();
    }
    try {
        if (this.getVerbose()) {
            log("Sending: " + localFile.getName() + " : " + filesize);
        }
        channel.put(localFile.getAbsolutePath(), remotePath, monitor);
        // set the fileMode on the transferred file. The "remotePath" can potentially be a directory
        // into which the file got transferred, so we can't/shouldn't go ahead and try to change that directory's
        // permissions. Instead we determine the path of the transferred file on remote.
        final String transferredFileRemotePath;
        if (channel.stat(remotePath).isDir()) {
            // Note: It's correct to use "/" as the file separator without worrying about what the remote
            // server's file separator is, since the SFTP spec expects "/" to be considered as file path
            // separator. See section 6.2 "File Names" of the spec, which states:
            // "This protocol represents file names as strings.  File names are
            // assumed to use the slash ('/') character as a directory separator."
            transferredFileRemotePath = remotePath + "/" + localFile.getName();
        } else {
            transferredFileRemotePath = remotePath;
        }
        if (this.getVerbose()) {
            log("Setting file mode '" + Integer.toOctalString(getFileMode()) + "' on remote path " + transferredFileRemotePath);
        }
        channel.chmod(getFileMode(), transferredFileRemotePath);
        if (getPreserveLastModified()) {
            // set the last modified time (seconds since epoch) on the transferred file
            final int lastModifiedTime = (int) (localFile.lastModified() / 1000L);
            if (this.getVerbose()) {
                log("Setting last modified time on remote path " + transferredFileRemotePath + " to " + lastModifiedTime);
            }
            channel.setMtime(transferredFileRemotePath, lastModifiedTime);
        }
    } finally {
        if (this.getVerbose()) {
            final long endTime = System.currentTimeMillis();
            logStats(startTime, endTime, (int) totalLength);
        }
    }
}
Also used : SftpProgressMonitor(com.jcraft.jsch.SftpProgressMonitor)

Aggregations

SftpProgressMonitor (com.jcraft.jsch.SftpProgressMonitor)4 File (java.io.File)2 IOException (java.io.IOException)2 Channel (com.jcraft.jsch.Channel)1 ChannelSftp (com.jcraft.jsch.ChannelSftp)1 SftpATTRS (com.jcraft.jsch.SftpATTRS)1 SftpException (com.jcraft.jsch.SftpException)1 FabricException (io.fabric8.api.FabricException)1 FileInputStream (java.io.FileInputStream)1 InputStream (java.io.InputStream)1 CountDownLatch (java.util.concurrent.CountDownLatch)1