Search in sources :

Example 86 with SftpException

use of com.jcraft.jsch.SftpException in project javautils by jiadongpo.

the class SFTPClient method dir.

public String[] dir() throws Exception {
    String[] fileList = null;
    try {
        java.util.Vector<?> v = c.ls(".");
        java.util.Vector<String> o = new java.util.Vector<String>();
        if (v != null) {
            for (int i = 0; i < v.size(); i++) {
                Object obj = v.elementAt(i);
                if (obj != null && obj instanceof com.jcraft.jsch.ChannelSftp.LsEntry) {
                    LsEntry lse = (com.jcraft.jsch.ChannelSftp.LsEntry) obj;
                    if (!lse.getAttrs().isDir())
                        o.add(lse.getFilename());
                }
            }
        }
        if (o.size() > 0) {
            fileList = new String[o.size()];
            o.copyInto(fileList);
        }
    } catch (SftpException e) {
        throw new Exception(e);
    }
    return fileList;
}
Also used : SftpException(com.jcraft.jsch.SftpException) LsEntry(com.jcraft.jsch.ChannelSftp.LsEntry) FileSystemException(org.apache.commons.vfs2.FileSystemException) IOException(java.io.IOException) SftpException(com.jcraft.jsch.SftpException) JSchException(com.jcraft.jsch.JSchException) ChannelSftp(com.jcraft.jsch.ChannelSftp) FileObject(org.apache.commons.vfs2.FileObject) LsEntry(com.jcraft.jsch.ChannelSftp.LsEntry)

Example 87 with SftpException

use of com.jcraft.jsch.SftpException in project cdap by caskdata.

the class SFTPFileSystem method open.

@Override
public FSDataInputStream open(Path f, int bufferSize) throws IOException {
    ChannelSftp channel = connect();
    Path workDir;
    try {
        workDir = new Path(channel.pwd());
    } catch (SftpException e) {
        throw new IOException(e);
    }
    Path absolute = makeAbsolute(workDir, f);
    FileStatus fileStat = getFileStatus(channel, absolute);
    if (fileStat.isDirectory()) {
        disconnect(channel);
        throw new IOException(String.format(E_PATH_DIR, f));
    }
    InputStream is;
    try {
        // the path could be a symbolic link, so get the real path
        absolute = new Path("/", channel.realpath(absolute.toUri().getPath()));
        is = channel.get(absolute.toUri().getPath());
    } catch (SftpException e) {
        throw new IOException(e);
    }
    FSDataInputStream fis = new FSDataInputStream(new SFTPInputStream(is, channel, statistics));
    return fis;
}
Also used : Path(org.apache.hadoop.fs.Path) ChannelSftp(com.jcraft.jsch.ChannelSftp) FileStatus(org.apache.hadoop.fs.FileStatus) FSDataInputStream(org.apache.hadoop.fs.FSDataInputStream) InputStream(java.io.InputStream) SftpException(com.jcraft.jsch.SftpException) FSDataInputStream(org.apache.hadoop.fs.FSDataInputStream) IOException(java.io.IOException)

Example 88 with SftpException

use of com.jcraft.jsch.SftpException 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 89 with SftpException

use of com.jcraft.jsch.SftpException in project litle-sdk-for-java by Vantiv.

the class Communication method receiveLitleRequestResponseFileFromSFTP.

/**
 * Grabs the response file from Litle's sFTP server. This method is blocking! It will continue to poll until the timeout has elapsed
 * or the file has been retrieved!
 * @param requestFile
 * @param responseFile
 * @param configuration
 * @throws IOException
 */
public void receiveLitleRequestResponseFileFromSFTP(File requestFile, File responseFile, Properties configuration) throws IOException {
    String username = configuration.getProperty("sftpUsername");
    String password = configuration.getProperty("sftpPassword");
    String hostname = configuration.getProperty("batchHost");
    java.util.Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking", "no");
    JSch jsch = null;
    Session session = null;
    try {
        jsch = new JSch();
        session = jsch.getSession(username, hostname);
        session.setConfig(config);
        session.setPassword(password);
        session.connect();
    } catch (JSchException e) {
        throw new LitleBatchException("Exception connection to Litle", e);
    }
    Channel channel = null;
    try {
        channel = session.openChannel("sftp");
        channel.connect();
    } catch (JSchException e) {
        throw new LitleBatchException("Exception connection to Litle", e);
    }
    ChannelSftp sftp = (ChannelSftp) channel;
    Long start = System.currentTimeMillis();
    Long timeout = Long.parseLong(configuration.getProperty("sftpTimeout"));
    System.out.println("Retrieving from sFTP...");
    while (System.currentTimeMillis() - start < timeout) {
        try {
            Thread.sleep(45000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        boolean success = true;
        try {
            sftp.get("outbound/" + requestFile.getName() + ".asc", responseFile.getAbsolutePath());
        } catch (SftpException e) {
            success = false;
            System.out.println(e);
        }
        if (success) {
            try {
                sftp.rm("outbound/" + requestFile.getName() + ".asc");
            } catch (SftpException e) {
                throw new LitleBatchException("Exception SFTP operation", e);
            }
            break;
        }
        System.out.print(".");
    }
    boolean printxml = configuration.getProperty("printxml") != null && configuration.getProperty("printxml").equalsIgnoreCase("true");
    if (printxml) {
        BufferedReader reader = new BufferedReader(new FileReader(responseFile));
        String line = "";
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        reader.close();
    }
    channel.disconnect();
    session.disconnect();
}
Also used : JSchException(com.jcraft.jsch.JSchException) Properties(java.util.Properties) Channel(com.jcraft.jsch.Channel) SftpException(com.jcraft.jsch.SftpException) Properties(java.util.Properties) JSch(com.jcraft.jsch.JSch) ChannelSftp(com.jcraft.jsch.ChannelSftp) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) Session(com.jcraft.jsch.Session)

Example 90 with SftpException

use of com.jcraft.jsch.SftpException in project spring-integration by spring-projects.

the class SftpRemoteFileTemplateTests method testINT3412AppendStatRmdir.

@Test
public void testINT3412AppendStatRmdir() {
    SftpRemoteFileTemplate template = new SftpRemoteFileTemplate(sessionFactory);
    DefaultFileNameGenerator fileNameGenerator = new DefaultFileNameGenerator();
    fileNameGenerator.setExpression("'foobar.txt'");
    template.setFileNameGenerator(fileNameGenerator);
    template.setRemoteDirectoryExpression(new LiteralExpression("foo/"));
    template.setUseTemporaryFileName(false);
    template.execute(session -> {
        session.mkdir("foo/");
        return session.mkdir("foo/bar/");
    });
    template.append(new GenericMessage<String>("foo"));
    template.append(new GenericMessage<String>("bar"));
    assertTrue(template.exists("foo/foobar.txt"));
    template.executeWithClient((ClientCallbackWithoutResult<ChannelSftp>) client -> {
        try {
            SftpATTRS file = client.lstat("foo/foobar.txt");
            assertEquals(6, file.getSize());
        } catch (SftpException e) {
            throw new RuntimeException(e);
        }
    });
    template.execute((SessionCallbackWithoutResult<LsEntry>) session -> {
        LsEntry[] files = session.list("foo/");
        assertEquals(4, files.length);
        assertTrue(session.remove("foo/foobar.txt"));
        assertTrue(session.rmdir("foo/bar/"));
        files = session.list("foo/");
        assertEquals(2, files.length);
        List<LsEntry> list = Arrays.asList(files);
        assertThat(list.stream().map(l -> l.getFilename()).collect(Collectors.toList()), containsInAnyOrder(".", ".."));
        assertTrue(session.rmdir("foo/"));
    });
    assertFalse(template.exists("foo"));
}
Also used : DirtiesContext(org.springframework.test.annotation.DirtiesContext) Arrays(java.util.Arrays) SessionFactory(org.springframework.integration.file.remote.session.SessionFactory) RunWith(org.junit.runner.RunWith) LiteralExpression(org.springframework.expression.common.LiteralExpression) Autowired(org.springframework.beans.factory.annotation.Autowired) CachingSessionFactory(org.springframework.integration.file.remote.session.CachingSessionFactory) Assert.assertThat(org.junit.Assert.assertThat) SpringJUnit4ClassRunner(org.springframework.test.context.junit4.SpringJUnit4ClassRunner) DefaultFileNameGenerator(org.springframework.integration.file.DefaultFileNameGenerator) SessionCallbackWithoutResult(org.springframework.integration.file.remote.SessionCallbackWithoutResult) SftpException(com.jcraft.jsch.SftpException) ChannelSftp(com.jcraft.jsch.ChannelSftp) ClientCallbackWithoutResult(org.springframework.integration.file.remote.ClientCallbackWithoutResult) SftpATTRS(com.jcraft.jsch.SftpATTRS) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) LsEntry(com.jcraft.jsch.ChannelSftp.LsEntry) Collectors(java.util.stream.Collectors) Configuration(org.springframework.context.annotation.Configuration) List(java.util.List) SftpTestSupport(org.springframework.integration.sftp.SftpTestSupport) Matchers.containsInAnyOrder(org.hamcrest.Matchers.containsInAnyOrder) Assert.assertFalse(org.junit.Assert.assertFalse) ContextConfiguration(org.springframework.test.context.ContextConfiguration) Bean(org.springframework.context.annotation.Bean) GenericMessage(org.springframework.messaging.support.GenericMessage) Assert.assertEquals(org.junit.Assert.assertEquals) ChannelSftp(com.jcraft.jsch.ChannelSftp) LiteralExpression(org.springframework.expression.common.LiteralExpression) SftpATTRS(com.jcraft.jsch.SftpATTRS) SftpException(com.jcraft.jsch.SftpException) List(java.util.List) LsEntry(com.jcraft.jsch.ChannelSftp.LsEntry) DefaultFileNameGenerator(org.springframework.integration.file.DefaultFileNameGenerator) Test(org.junit.Test)

Aggregations

SftpException (com.jcraft.jsch.SftpException)113 ChannelSftp (com.jcraft.jsch.ChannelSftp)67 IOException (java.io.IOException)49 JSchException (com.jcraft.jsch.JSchException)28 LsEntry (com.jcraft.jsch.ChannelSftp.LsEntry)24 File (java.io.File)24 SftpATTRS (com.jcraft.jsch.SftpATTRS)16 Path (org.apache.hadoop.fs.Path)15 Session (com.jcraft.jsch.Session)13 OutputStream (java.io.OutputStream)11 JSch (com.jcraft.jsch.JSch)10 FileNotFoundException (java.io.FileNotFoundException)10 InputStream (java.io.InputStream)10 Channel (com.jcraft.jsch.Channel)9 GenericFileOperationFailedException (org.apache.camel.component.file.GenericFileOperationFailedException)9 FileStatus (org.apache.hadoop.fs.FileStatus)9 ArrayList (java.util.ArrayList)8 Vector (java.util.Vector)8 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)8 Test (org.junit.Test)8