List of usage examples for org.springframework.integration.file.remote.session Session mkdir
boolean mkdir(String directory) 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 .ja v a 2 s.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./* w w w. j a v 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 w w. java 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.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 ww .j ava 2 s.c o m*/ 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.file.remote.RemoteFileUtils.java
/** * Recursively create remote directories. * @param <F> The session type.//w ww .java 2s . c om * @param path The directory path. * @param session The session. * @throws IOException */ public static <F> void makeDirectories(String path, Session<F> session, String remoteFileSeparator, Log logger) throws IOException { if (!session.exists(path)) { int nextSeparatorIndex = path.lastIndexOf(remoteFileSeparator); if (nextSeparatorIndex > -1) { List<String> pathsToCreate = new LinkedList<String>(); while (nextSeparatorIndex > -1) { String pathSegment = path.substring(0, nextSeparatorIndex); if (pathSegment.length() == 0 || session.exists(pathSegment)) { // no more paths to create break; } else { pathsToCreate.add(0, pathSegment); nextSeparatorIndex = pathSegment.lastIndexOf(remoteFileSeparator); } } for (String pathToCreate : pathsToCreate) { if (logger.isDebugEnabled()) { logger.debug("Creating '" + pathToCreate + "'"); } session.mkdir(pathToCreate); } } else { session.mkdir(path); } } }