List of usage examples for org.springframework.integration.file.remote.session Session close
@Override
void close();
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.// ww w . ja v a 2 s .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.cruk.genologics.api.impl.GenologicsAPIImpl.java
@Override public void deleteAndRemoveFile(Linkable<GenologicsFile> file) throws IOException { if (file == null) { throw new IllegalArgumentException("file cannot be null"); }/*from w ww . j ava2s. c o m*/ GenologicsFile realFile; if (file instanceof GenologicsFile) { realFile = (GenologicsFile) file; if (realFile.getContentLocation() == null) { // Don't know where the actual file is, so fetch to get the full info. realFile = retrieve(file.getUri(), GenologicsFile.class); } } else { realFile = retrieve(file.getUri(), GenologicsFile.class); } URL targetURL = new URL(null, realFile.getContentLocation().toString(), NullURLStreamHandler.INSTANCE); if ("sftp".equalsIgnoreCase(targetURL.getProtocol())) { logger.info("Deleting file {} from file store on {}", targetURL.getPath(), targetURL.getHost()); checkFilestoreSet(); Session<LsEntry> session = filestoreSessionFactory.getSession(); try { session.remove(targetURL.getPath()); } catch (NestedIOException e) { // Don't want things to fail if the file doesn't exist on the file store, // just a warning. This handling code deals with this. try { if (e.getCause() != null) { throw e.getCause(); } else { // There is an error in line 71 of SftpSession, where instead of the // SftpException being the cause, its own message is appended to the // detail message for the outer exception with a +. // Bug raised with Spring Integrations as issue INT-3954. if ("Failed to remove file: 2: No such file".equals(e.getMessage())) { throw new SftpException(2, e.getMessage()); } throw e; } } catch (SftpException se) { // See if it's just a "file not found". if (se.id == 2) { logger.warn("File {} does not exist on {}", targetURL.getPath(), targetURL.getHost()); } else { throw e; } } catch (Throwable t) { throw e; } } finally { session.close(); } } else { logger.debug("File {} is not in the file store, so just removing its record.", targetURL.getPath()); } delete(realFile); }
From source file:org.opentestsystem.authoring.testitembank.service.impl.ExportSetServiceImpl.java
@Async @Override/*from ww w .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.authoring.testitembank.service.impl.SftpFileTransferServiceImpl.java
@Override public final File getFile(final String importSetId, final String fileName) { File file = null;// w ww . j av a 2 s. c o m FileOutputStream fileOutputStream = null; Session<ChannelSftp.LsEntry> sftpSession = null; String path = this.tempFileDirectory; if (StringUtils.isEmpty(path)) { String userDir = System.getProperty("user.dir"); LOGGER.info("The property 'tib.file.pathname' is not populated, defaulting to :" + userDir); path = userDir; } try { sftpSession = this.sftpSessionFactory.getSession(); final String[] pathPortions = fileName.split("/"); final String justFileName = pathPortions[pathPortions.length - 1]; LOGGER.debug("TIB temp dir is: " + path + " file name: " + justFileName); path = path + "/importSet_" + importSetId; new File(path).mkdirs(); file = new File(path, justFileName); fileOutputStream = new FileOutputStream(file); sftpSession.read(fileName, fileOutputStream); } catch (final Exception e) { LOGGER.error("unable to get file " + fileName + " from sftp site:" + e.getMessage(), e); throw new TestItemBankException("sftp.read.error", new String[] { fileName }); } finally { try { if (fileOutputStream != null) { fileOutputStream.close(); } if (sftpSession != null) { sftpSession.close(); } } catch (final IOException e) { LOGGER.error("unable to get file " + fileName + " from sftp site:" + e.getMessage(), e); throw new TestItemBankException("sftp.read.error", new String[] { fileName }); } } return file; }
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 {/* www.ja 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.authoring.testitembank.service.impl.SftpFileTransferServiceImpl.java
@Override public final int cleanDirectory(final String baseDirectory, final int maxAge) { int remainingFileCount = 0; Session<ChannelSftp.LsEntry> sftpSession = null; try {/* www . j a v a2 s.c o m*/ sftpSession = this.sftpSessionFactory.getSession(); remainingFileCount = cleanDirectory(baseDirectory, maxAge, sftpSession); } finally { if (sftpSession != null) { sftpSession.close(); } } return remainingFileCount; }
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 ww . java 2 s . 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 ww w . j a v a2s.co 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 {/*from w ww . j av a2 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
@SuppressWarnings("rawtypes") @Override//w w w . j av a2s . c o m public <T> T execute(SessionCallback<F, T> callback) { Session<F> session = null; try { session = this.sessionFactory.getSession(); Assert.notNull(session, "failed to acquire a Session"); return callback.doInSession(session); } catch (Exception e) { if (session instanceof CachingSessionFactory<?>.CachedSession) { ((CachingSessionFactory.CachedSession) session).dirty(); } if (e instanceof MessagingException) { throw (MessagingException) e; } throw new MessagingException("Failed to execute on session", e); } finally { if (session != null) { try { session.close(); } catch (Exception ignored) { if (this.logger.isDebugEnabled()) { this.logger.debug("failed to close Session", ignored); } } } } }