Search in sources :

Example 76 with ChannelSftp

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

the class SFTPConnectionPool method getFromPool.

synchronized ChannelSftp getFromPool(ConnectionInfo info) throws IOException {
    Set<ChannelSftp> cons = idleConnections.get(info);
    ChannelSftp channel;
    if (cons != null && cons.size() > 0) {
        Iterator<ChannelSftp> it = cons.iterator();
        if (it.hasNext()) {
            channel = it.next();
            idleConnections.remove(info);
            return channel;
        } else {
            throw new IOException("Connection pool error.");
        }
    }
    return null;
}
Also used : ChannelSftp(com.jcraft.jsch.ChannelSftp) IOException(java.io.IOException)

Example 77 with ChannelSftp

use of com.jcraft.jsch.ChannelSftp 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 78 with ChannelSftp

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

the class SftpOutboundTests method testSharedSession.

@Test
public void testSharedSession() throws Exception {
    JSch jsch = spy(new JSch());
    Constructor<com.jcraft.jsch.Session> ctor = com.jcraft.jsch.Session.class.getDeclaredConstructor(JSch.class, String.class, String.class, int.class);
    ctor.setAccessible(true);
    com.jcraft.jsch.Session jschSession1 = spy(ctor.newInstance(jsch, "foo", "host", 22));
    com.jcraft.jsch.Session jschSession2 = spy(ctor.newInstance(jsch, "foo", "host", 22));
    willAnswer(invocation -> {
        new DirectFieldAccessor(jschSession1).setPropertyValue("isConnected", true);
        return null;
    }).given(jschSession1).connect();
    willAnswer(invocation -> {
        new DirectFieldAccessor(jschSession2).setPropertyValue("isConnected", true);
        return null;
    }).given(jschSession2).connect();
    when(jsch.getSession("foo", "host", 22)).thenReturn(jschSession1, jschSession2);
    final ChannelSftp channel1 = spy(new ChannelSftp());
    doReturn("channel1").when(channel1).toString();
    final ChannelSftp channel2 = spy(new ChannelSftp());
    doReturn("channel2").when(channel2).toString();
    new DirectFieldAccessor(channel1).setPropertyValue("session", jschSession1);
    new DirectFieldAccessor(channel2).setPropertyValue("session", jschSession1);
    // Can't use when(session.open()) with a spy
    final AtomicInteger n = new AtomicInteger();
    doAnswer(invocation -> n.getAndIncrement() == 0 ? channel1 : channel2).when(jschSession1).openChannel("sftp");
    DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory(jsch, true);
    factory.setHost("host");
    factory.setUser("foo");
    factory.setPassword("bar");
    noopConnect(channel1);
    noopConnect(channel2);
    Session<LsEntry> s1 = factory.getSession();
    Session<LsEntry> s2 = factory.getSession();
    assertSame(TestUtils.getPropertyValue(s1, "jschSession"), TestUtils.getPropertyValue(s2, "jschSession"));
    assertSame(channel1, TestUtils.getPropertyValue(s1, "channel"));
    assertSame(channel2, TestUtils.getPropertyValue(s2, "channel"));
}
Also used : JSch(com.jcraft.jsch.JSch) DefaultSftpSessionFactory(org.springframework.integration.sftp.session.DefaultSftpSessionFactory) ChannelSftp(com.jcraft.jsch.ChannelSftp) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) LsEntry(com.jcraft.jsch.ChannelSftp.LsEntry) Session(org.springframework.integration.file.remote.session.Session) SftpSession(org.springframework.integration.sftp.session.SftpSession) Test(org.junit.Test)

Example 79 with ChannelSftp

use of com.jcraft.jsch.ChannelSftp 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)

Example 80 with ChannelSftp

use of com.jcraft.jsch.ChannelSftp in project opentest by mcdcorp.

the class GetFromSftp method run.

@Override
public void run() {
    super.run();
    String sftpHost = this.readStringArgument("sftpHost");
    Integer sftpPort = this.readIntArgument("sftpPort", 22);
    String userName = this.readStringArgument("userName");
    String password = this.readStringArgument("password");
    String sourceDir = this.readStringArgument("sourceDir");
    String sourceFile = this.readStringArgument("sourceFile");
    String destinationDir = this.readStringArgument("destinationDir");
    String destinationFileName = this.readStringArgument("destinationFile", sourceFile);
    Session session = null;
    Channel channel = null;
    ChannelSftp channelSftp = null;
    try {
        JSch jsch = new JSch();
        session = jsch.getSession(userName, sftpHost, sftpPort);
        session.setPassword(password);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        this.log.trace("Connected to SFTP host");
        channel = session.openChannel("sftp");
        channel.connect();
        this.log.trace("The SFTP channel was opened and connected");
        channelSftp = (ChannelSftp) channel;
        channelSftp.cd(sourceDir);
        File destinationFile = new File(destinationDir, destinationFileName);
        FileOutputStream fileOutputStream = new FileOutputStream(destinationFile);
        channelSftp.get(sourceFile, fileOutputStream);
        fileOutputStream.close();
    } catch (Exception ex) {
        throw new RuntimeException("SFTP transfer failed", ex);
    } finally {
        if (channelSftp != null) {
            channelSftp.exit();
        }
        if (channel != null) {
            channel.disconnect();
        }
        if (session != null) {
            session.disconnect();
        }
    }
}
Also used : ChannelSftp(com.jcraft.jsch.ChannelSftp) Channel(com.jcraft.jsch.Channel) FileOutputStream(java.io.FileOutputStream) JSch(com.jcraft.jsch.JSch) Properties(java.util.Properties) File(java.io.File) Session(com.jcraft.jsch.Session)

Aggregations

ChannelSftp (com.jcraft.jsch.ChannelSftp)99 SftpException (com.jcraft.jsch.SftpException)61 IOException (java.io.IOException)36 JSchException (com.jcraft.jsch.JSchException)28 Session (com.jcraft.jsch.Session)25 JSch (com.jcraft.jsch.JSch)20 Channel (com.jcraft.jsch.Channel)17 LsEntry (com.jcraft.jsch.ChannelSftp.LsEntry)17 File (java.io.File)16 Test (org.junit.Test)14 InputStream (java.io.InputStream)12 SftpATTRS (com.jcraft.jsch.SftpATTRS)11 FileNotFoundException (java.io.FileNotFoundException)9 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)8 FileInputStream (java.io.FileInputStream)7 OutputStream (java.io.OutputStream)7 Path (org.apache.hadoop.fs.Path)7 CoreException (org.eclipse.core.runtime.CoreException)7 IStatus (org.eclipse.core.runtime.IStatus)7 Status (org.eclipse.core.runtime.Status)7