Example usage for org.springframework.integration.file.remote.session Session isOpen

List of usage examples for org.springframework.integration.file.remote.session Session isOpen

Introduction

In this page you can find the example usage for org.springframework.integration.file.remote.session Session isOpen.

Prototype

boolean isOpen();

Source Link

Usage

From source file:org.opentestsystem.authoring.testitembank.service.impl.ExportSetServiceImpl.java

@Async
@Override//w  ww  .ja va  2  s. co m
public void exportFileSet(final ExportSet exportSet) {
    final String targetParentDir = SFTP_TENANT_FOLDER_PREFIX + exportSet.getTenantId() + "/";
    final String targetFilePath = targetParentDir + EXPORT_SET_FILENAME_PREFIX + exportSet.getId() + ".zip";

    if (!CollectionUtils.isEmpty(exportSet.getItems())) {

        // retrieve items from mongo
        final List<ItemHistory> itemHistories = new ArrayList<ItemHistory>();
        final List<ExportItem> invalidItems = new ArrayList<ExportItem>();
        for (final ExportItem item : exportSet.getItems()) {
            final ItemHistory historyItem = itemHistoryRepository.findByTenantIdAndIdentifierAndVersion(
                    exportSet.getTenantId(), item.getIdentifier(), item.getVersion());
            if (historyItem == null) {
                LOGGER.info("Export Failed: Item " + item.getIdentifier() + " (v" + item.getVersion()
                        + ") not found for tenant: " + exportSet.getTenantId());
                invalidItems.add(item);
            } else {
                itemHistories.add(historyItem);
            }
        }

        // validate missing items
        if (!invalidItems.isEmpty()) {
            exportSet.setStatus(ExportStatus.FAILED);
        } else {
            Session<?> sftpSession = null;
            InputStream inputStream = null;
            try {
                // build zip file
                final File exportFile = zipOutputFileBuilderService.createExportFile(exportSet.getId(),
                        itemHistories);

                // get sftp session and create parent directory for the export
                sftpSession = sftpFileTransferService.getSession();
                if (!sftpSession.exists(targetParentDir)) {
                    sftpSession.mkdir(targetParentDir);
                }

                // write file to SFTP site
                inputStream = new FileInputStream(exportFile);
                sftpSession.write(inputStream, targetFilePath);
            } catch (final IOException | JAXBException e) {
                LOGGER.error("unable to export items for set: " + exportSet.getId() + ":", e);
                exportSet.setStatus(ExportStatus.FAILED);
            } catch (final Exception e) {
                exportSet.setStatus(ExportStatus.FAILED);
                exportSet.setExportCompleted(new DateTime());
                saveExportSet(exportSet);
                throw e;
            } finally {
                IOUtils.closeQuietly(inputStream);
                if (sftpSession != null && sftpSession.isOpen()) {
                    sftpSession.close();
                }
            }
        }
    }

    if (!ExportStatus.FAILED.equals(exportSet.getStatus())) {
        exportSet.setStatus(ExportStatus.EXPORT_COMPLETE);
        exportSet.setZipFileName(targetFilePath);
    }
    exportSet.setExportCompleted(new DateTime());
    saveExportSet(exportSet);
}

From source file:org.opentestsystem.delivery.testreg.service.impl.UserChangeEventFileTransferServiceImpl.java

@Override
public final void writeFile(final String fileName, final String fileBody) {
    Session<ChannelSftp.LsEntry> sftpSession = null;
    String destinationPath = (StringUtils.isBlank(sftpDir)) ? fileName : sftpDir + "/" + fileName;
    String humanReadableConnectionInfo = "sftp://" + sftpUser + "@" + sftpHost + ":" + sftpPort + "/"
            + destinationPath;/*from w w w .  j a  v  a  2s  . co  m*/
    try {
        LOGGER.debug("attempting to transfer file: " + humanReadableConnectionInfo);
        sftpSession = defaultSftpSessionFactory.getSession();
        sftpSession.write(new ByteArrayInputStream(fileBody.getBytes("UTF-8")), destinationPath);
        alertBeacon.sendAlert(MnaSeverity.INFO, MnaAlertType.SSO_USER_EXPORT.name(),
                "file transferred: " + humanReadableConnectionInfo);
    } catch (Exception e) {
        String errorMessage = "unable to transfer file: " + humanReadableConnectionInfo;
        LOGGER.error(errorMessage);
        alertBeacon.sendAlert(MnaSeverity.ERROR, MnaAlertType.SSO_USER_EXPORT.name(), errorMessage);
        throw new RuntimeException(e);
    } finally {
        if (sftpSession != null && sftpSession.isOpen()) {
            sftpSession.close();
        }
    }
}

From source file:org.oscarehr.integration.born.BornFtpManager.java

public static void uploadONAREnhancedDataToRepository(String path, String filename) throws Exception {
    String remotePath = OscarProperties.getInstance().getProperty("born_ftps_remote_dir", "");
    DefaultFtpsSessionFactory ftpFactory = (DefaultFtpsSessionFactory) SpringUtils.getBean("ftpClientFactory");
    Session<FTPFile> session = null;
    try {//from  w ww  .java2  s. c  o  m
        session = ftpFactory.getSession();
        if (session.isOpen()) {
            session.write(new FileInputStream(path + File.separator + filename),
                    remotePath + File.separator + filename);
        }
    } finally {
        if (session != null && session.isOpen())
            session.close();
    }
}

From source file:org.oscarehr.integration.born.BornFtpManager.java

public static boolean upload18MEWBVDataToRepository(byte[] xmlFile, String filename) {
    String remotePath = OscarProperties.getInstance().getProperty("born18m_sftp_remote_dir", "");
    DefaultSftpSessionFactory ftpFactory = (DefaultSftpSessionFactory) SpringUtils
            .getBean("ftpClientFactoryBORN18M");
    Session session = null;

    boolean success = false;
    try {//  w w  w . j  av a2 s  . c om
        session = ftpFactory.getSession();
        if (session.isOpen()) {
            session.write(new ByteArrayInputStream(xmlFile), remotePath + File.separator + filename);
            success = true;
        }
    } catch (Exception e) {
        MiscUtils.getLogger().warn("Failed uploading to repository", e);
    } finally {
        if (session != null && session.isOpen())
            session.close();
    }
    return success;
}

From source file:org.springframework.integration.file.remote.session.CachingSessionFactory.java

/**
 * Create a CachingSessionFactory with the specified session limit. By default, if
 * no sessions are available in the cache, and the size limit has been reached,
 * calling threads will block until a session is available.
 * @see #setSessionWaitTimeout(long)/*from w  w w. j  a  v a 2s . c  om*/
 * @see #setPoolSize(int)
 * @param sessionFactory the underlying session factory.
 * @param sessionCacheSize the maximum cache size.
 */
public CachingSessionFactory(SessionFactory<F> sessionFactory, int sessionCacheSize) {
    this.sessionFactory = sessionFactory;
    this.pool = new SimplePool<Session<F>>(sessionCacheSize, new SimplePool.PoolItemCallback<Session<F>>() {
        public Session<F> createForPool() {
            return CachingSessionFactory.this.sessionFactory.getSession();
        }

        public boolean isStale(Session<F> session) {
            return !session.isOpen();
        }

        public void removedFromPool(Session<F> session) {
            session.close();
        }
    });
}

From source file:org.springframework.integration.ftp.outbound.FtpServerOutboundTests.java

@Test
public void testStream() {
    String dir = "ftpSource/";
    this.inboundGetStream.send(new GenericMessage<Object>(dir + " ftpSource1.txt"));
    Message<?> result = this.output.receive(1000);
    assertNotNull(result);//from w  ww.  j  av  a  2  s . c o m
    assertEquals("source1", result.getPayload());
    assertEquals("ftpSource/", result.getHeaders().get(FileHeaders.REMOTE_DIRECTORY));
    assertEquals(" ftpSource1.txt", result.getHeaders().get(FileHeaders.REMOTE_FILE));

    Session<?> session = (Session<?>) result.getHeaders()
            .get(IntegrationMessageHeaderAccessor.CLOSEABLE_RESOURCE);
    // Returned to cache
    assertTrue(session.isOpen());
    // Raw reading is finished
    assertFalse(TestUtils.getPropertyValue(session, "targetSession.readingRaw", AtomicBoolean.class).get());

    // Check that we can use the same session from cache to read another remote InputStream
    this.inboundGetStream.send(new GenericMessage<Object>(dir + "ftpSource2.txt"));
    result = this.output.receive(1000);
    assertNotNull(result);
    assertEquals("source2", result.getPayload());
    assertEquals("ftpSource/", result.getHeaders().get(FileHeaders.REMOTE_DIRECTORY));
    assertEquals("ftpSource2.txt", result.getHeaders().get(FileHeaders.REMOTE_FILE));
    assertSame(TestUtils.getPropertyValue(session, "targetSession"), TestUtils.getPropertyValue(
            result.getHeaders().get(IntegrationMessageHeaderAccessor.CLOSEABLE_RESOURCE), "targetSession"));
}

From source file:org.springframework.integration.ftp.session.SessionFactoryTests.java

@Test
public void testStaleConnection() throws Exception {
    SessionFactory sessionFactory = Mockito.mock(SessionFactory.class);
    Session sessionA = Mockito.mock(Session.class);
    Session sessionB = Mockito.mock(Session.class);
    Mockito.when(sessionA.isOpen()).thenReturn(true);
    Mockito.when(sessionB.isOpen()).thenReturn(false);

    Mockito.when(sessionFactory.getSession()).thenReturn(sessionA);
    Mockito.when(sessionFactory.getSession()).thenReturn(sessionB);

    CachingSessionFactory cachingFactory = new CachingSessionFactory(sessionFactory, 2);

    Session firstSession = cachingFactory.getSession();
    Session secondSession = cachingFactory.getSession();
    secondSession.close();/*from  www.  j a va 2 s  . c  o  m*/
    Session nonStaleSession = cachingFactory.getSession();
    assertEquals(TestUtils.getPropertyValue(firstSession, "targetSession"),
            TestUtils.getPropertyValue(nonStaleSession, "targetSession"));
}