List of usage examples for org.springframework.integration.file.remote.session Session write
void write(InputStream inputStream, String destination) throws IOException;
From source file:com.aeg.ims.ftp.SftpTestUtils.java
public static void createTestFiles(RemoteFileTemplate<LsEntry> template, final String... fileNames) { if (template != null) { final ByteArrayInputStream stream = new ByteArrayInputStream("foo".getBytes()); template.execute(new SessionCallback<LsEntry, Void>() { @Override/* w w w . j av a2s . c om*/ public Void doInSession(Session<LsEntry> session) throws IOException { try { session.mkdir("BriansTest"); } catch (Exception e) { assertThat(e.getMessage(), containsString("failed to create")); } for (int i = 0; i < fileNames.length; i++) { stream.reset(); session.write(stream, "Test" + fileNames[i]); } return null; } }); } }
From source file:org.cruk.genologics.api.impl.GenologicsAPIImpl.java
/** * Upload a file to the Genologics file store. This always uses the SFTP protocol. * * @param fileURLResource The URL resource of the file on the local machine. * @param targetFile The GenologicsFile object that holds the reference to the * uploaded file, which was newly created using the API. * * @throws IOException if there is a problem with the transfer. * @throws IllegalStateException if the file store host name or credentials * are not set./*from w w w. jav a 2s.c o m*/ */ protected void uploadViaSFTP(URLInputStreamResource fileURLResource, GenologicsFile targetFile) throws IOException { GenologicsEntity entityAnno = checkEntityAnnotated(GenologicsFile.class); checkFilestoreSet(); Session<LsEntry> session = filestoreSessionFactory.getSession(); try { URI targetURL = targetFile.getContentLocation(); logger.info("Uploading {} over SFTP to {} on {}", fileURLResource.getURL().getPath(), targetURL.getPath(), targetURL.getHost()); String directory = FilenameUtils.getFullPathNoEndSeparator(targetURL.getPath()); if (!session.exists(directory)) { String[] directoryParts = directory.split("/+"); StringBuilder incrementalPath = new StringBuilder(directory.length()); for (int i = 1; i < directoryParts.length; i++) { incrementalPath.append('/').append(directoryParts[i]); String currentPath = incrementalPath.toString(); if (!session.exists(currentPath)) { boolean made = session.mkdir(currentPath); if (!made) { throw new IOException("Could not create file store directory " + directory); } } } } session.write(fileURLResource.getInputStream(), targetURL.getPath()); } finally { session.close(); } // Post the targetFile object back to the server to set the // "publish in lablink" flag and get the LIMS id and URI for the // file object. String filesUrl = getServerApiAddress() + entityAnno.uriSection(); ResponseEntity<GenologicsFile> response = restClient.postForEntity(filesUrl, targetFile, GenologicsFile.class); reflectiveUpdate(targetFile, response.getBody()); }
From source file:org.opentestsystem.authoring.testitembank.service.impl.ExportSetServiceImpl.java
@Async @Override//from w ww . j a v a 2 s . c om 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.authoring.testitembank.service.impl.SftpFileTransferServiceImpl.java
@Override public final void writeFile(final String destinationName, final InputStream inputStream) { Session<ChannelSftp.LsEntry> sftpSession = null; try {//from ww w. j a v a 2 s. c o m sftpSession = this.sftpSessionFactory.getSession(); sftpSession.write(inputStream, destinationName); } catch (final Exception e) { LOGGER.error( "unable to write file to sftp site " + destinationName + " from sftp site:" + e.getMessage()); throw new TestItemBankException("sftp.write.error", new String[] { destinationName }); } finally { try { if (inputStream != null) { inputStream.close(); } if (sftpSession != null) { sftpSession.close(); } } catch (final IOException e) { LOGGER.error("unable to write file " + destinationName + " to sftp site:" + e.getMessage()); throw new TestItemBankException("sftp.write.error", new String[] { destinationName }); } } }
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 va 2s. c o 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 w w . ja va 2 s .c om 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 {/*from ww w . j a va 2 s.co m*/ 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.RemoteFileTemplate.java
private void sendFileToRemoteDirectory(InputStream inputStream, String temporaryRemoteDirectory, String remoteDirectory, String fileName, Session<F> session, FileExistsMode mode) throws IOException { remoteDirectory = this.normalizeDirectoryPath(remoteDirectory); temporaryRemoteDirectory = this.normalizeDirectoryPath(temporaryRemoteDirectory); String remoteFilePath = remoteDirectory + fileName; String tempRemoteFilePath = temporaryRemoteDirectory + fileName; // write remote file first with temporary file extension if enabled String tempFilePath = tempRemoteFilePath + (this.useTemporaryFileName ? this.temporaryFileSuffix : ""); if (this.autoCreateDirectory) { try {//from w w w.ja v a2 s. com RemoteFileUtils.makeDirectories(remoteDirectory, session, this.remoteFileSeparator, this.logger); } catch (IllegalStateException e) { // Revert to old FTP behavior if recursive mkdir fails, for backwards compatibility session.mkdir(remoteDirectory); } } try { boolean rename = this.useTemporaryFileName; if (FileExistsMode.REPLACE.equals(mode)) { session.write(inputStream, tempFilePath); } else if (FileExistsMode.APPEND.equals(mode)) { session.append(inputStream, tempFilePath); } else { if (exists(remoteFilePath)) { if (FileExistsMode.FAIL.equals(mode)) { throw new MessagingException( "The destination file already exists at '" + remoteFilePath + "'."); } else { if (this.logger.isDebugEnabled()) { this.logger.debug("File not transferred to '" + remoteFilePath + "'; already exists."); } } rename = false; } else { session.write(inputStream, tempFilePath); } } // then rename it to its final name if necessary if (rename) { session.rename(tempFilePath, remoteFilePath); } } catch (Exception e) { throw new MessagingException("Failed to write to '" + tempFilePath + "' while uploading the file", e); } finally { inputStream.close(); } }
From source file:org.springframework.integration.sftp.outbound.SftpServerOutboundTests.java
@Test public void testInt3047ConcurrentSharedSession() throws Exception { final Session<?> session1 = this.sessionFactory.getSession(); final Session<?> session2 = this.sessionFactory.getSession(); final PipedInputStream pipe1 = new PipedInputStream(); PipedOutputStream out1 = new PipedOutputStream(pipe1); final PipedInputStream pipe2 = new PipedInputStream(); PipedOutputStream out2 = new PipedOutputStream(pipe2); final CountDownLatch latch1 = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); Executors.newSingleThreadExecutor().execute(() -> { try {//www.j av a 2s . c o m session1.write(pipe1, "foo.txt"); } catch (IOException e) { e.printStackTrace(); } latch1.countDown(); }); Executors.newSingleThreadExecutor().execute(() -> { try { session2.write(pipe2, "bar.txt"); } catch (IOException e) { e.printStackTrace(); } latch2.countDown(); }); out1.write('a'); out2.write('b'); out1.write('c'); out2.write('d'); out1.write('e'); out2.write('f'); out1.close(); out2.close(); assertTrue(latch1.await(10, TimeUnit.SECONDS)); assertTrue(latch2.await(10, TimeUnit.SECONDS)); ByteArrayOutputStream bos1 = new ByteArrayOutputStream(); ByteArrayOutputStream bos2 = new ByteArrayOutputStream(); session1.read("foo.txt", bos1); session2.read("bar.txt", bos2); assertEquals("ace", new String(bos1.toByteArray())); assertEquals("bdf", new String(bos2.toByteArray())); session1.remove("foo.txt"); session2.remove("bar.txt"); session1.close(); session2.close(); }