List of usage examples for org.apache.commons.vfs2.impl StandardFileSystemManager close
public void close()
From source file:org.wso2.carbon.connector.FileListZipConnector.java
/** * List all the files inside zip file.// w w w . j a v a2s.co m * * @param messageContext The message context that is generated for processing the file. */ private void listAllFiles(MessageContext messageContext) throws FileSystemException { String source = (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.FILE_LOCATION); StandardFileSystemManager manager = FileConnectorUtils.getManager(); FileObject remoteFile = manager.resolveFile(source, FileConnectorUtils.init(messageContext)); if (!remoteFile.exists()) { log.error("Zip file location does not exist."); } // open the zip file InputStream input = remoteFile.getContent().getInputStream(); ZipInputStream zip = new ZipInputStream(input); OMFactory factory = OMAbstractFactory.getOMFactory(); OMNamespace ns = factory.createOMNamespace(FileConstants.FILECON, FileConstants.NAMESPACE); OMElement result = factory.createOMElement(FileConstants.RESULT, ns); ZipEntry zipEntry; try { while ((zipEntry = zip.getNextEntry()) != null && !zipEntry.isDirectory()) { // add the entries String outputResult = zipEntry.getName(); OMElement messageElement = factory.createOMElement(FileConstants.FILE, ns); messageElement.setText(outputResult); result.addChild(messageElement); } } catch (IOException e) { throw new SynapseException("Error while reading the next ZIP file entry", e); } finally { try { zip.close(); } catch (IOException e) { log.error("Error while closing ZipInputStream"); } try { remoteFile.close(); } catch (FileSystemException e) { log.error("Error while closing the FileObject", e); } // close the StandardFileSystemManager manager.close(); } ResultPayloadCreator.preparePayload(messageContext, result); if (log.isDebugEnabled()) { log.debug("The envelop body with the read files path is " + messageContext.getEnvelope().getBody().toString()); } }
From source file:org.wso2.carbon.connector.FileMove.java
/** * Move the files/*from ww w. ja va 2 s .com*/ * * @param source Location of the file * @param destination Destination of the file * @return return a resultStatus */ private boolean moveFile(String source, String destination, MessageContext messageContext) { boolean resultStatus = false; StandardFileSystemManager manager = null; try { manager = FileConnectorUtils.getManager(); // Create remote object FileObject remoteFile = manager.resolveFile(source, FileConnectorUtils.init(messageContext)); if (remoteFile.exists()) { FileObject file = manager.resolveFile(destination, FileConnectorUtils.init(messageContext)); if (!file.exists()) { file.createFolder(); } if (remoteFile.getType() == FileType.FOLDER) { remoteFile.moveTo(file); } else if (remoteFile.getType() == FileType.FILE) { FileObject newFile = manager.resolveFile( destination + File.separator + remoteFile.getName().getBaseName(), FileConnectorUtils.init(messageContext)); remoteFile.moveTo(newFile); } resultStatus = true; if (log.isDebugEnabled()) { log.debug("File move completed from " + source + " to " + destination); } } else { log.error("The file/folder location does not exist."); resultStatus = false; } } catch (IOException e) { handleException("Unable to move a file/folder.", e, messageContext); } finally { if (manager != null) { manager.close(); } } return resultStatus; }
From source file:org.wso2.carbon.connector.FileMoveConnector.java
/** * Move the file/folder from source to destination directory. * * @param messageContext The message context that is generated for processing the move operation. * @return true, if the file/folder is successfully moved. *///from w w w . j a v a2 s.co m private boolean move(MessageContext messageContext) throws FileSystemException { String source = (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.FILE_LOCATION); String destination = (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.NEW_FILE_LOCATION); String filePattern = (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.FILE_PATTERN); String includeParentDirectory = (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.INCLUDE_PARENT_DIRECTORY); boolean includeParentDirectoryParameter = FileConstants.DEFAULT_INCLUDE_PARENT_DIRECTORY; if (StringUtils.isNotEmpty(includeParentDirectory)) { includeParentDirectoryParameter = Boolean.parseBoolean(includeParentDirectory); } StandardFileSystemManager manager = FileConnectorUtils.getManager(); FileSystemOptions opts = FileConnectorUtils.init(messageContext); // Create remote object FileObject remoteFile = manager.resolveFile(source, opts); try { if (!remoteFile.exists()) { log.error("The file/folder location does not exist."); return false; } if (FileType.FILE.equals(remoteFile.getType())) { moveFile(destination, remoteFile, manager, opts); } else { moveFolder(source, destination, filePattern, includeParentDirectoryParameter, manager, opts); } if (log.isDebugEnabled()) { log.debug("File move completed from " + source + " to " + destination); } } catch (FileSystemException e) { throw new SynapseException("Unable to move a file/folder.", e); } finally { // close the StandardFileSystemManager manager.close(); try { remoteFile.close(); } catch (FileSystemException e) { log.error("Error while closing the FileObject", e); } } return true; }
From source file:org.wso2.carbon.connector.FileSearch.java
/** * Generate the file search/* w ww . j a v a 2 s . c o m*/ * * @param source Location fo the file * @param filePattern Pattern of the file * @param recursiveSearch check whether recursively search or not * @param messageContext The message context that is processed by a handler in the handle method */ private void search(String source, String filePattern, String recursiveSearch, MessageContext messageContext) { ResultPayloadCreate resultPayload = new ResultPayloadCreate(); StandardFileSystemManager manager = null; if (StringUtils.isEmpty(filePattern)) { log.error("FilePattern should not be null"); } else { try { manager = FileConnectorUtils.getManager(); FileSystemOptions opt = FileConnectorUtils.init(messageContext); FileObject remoteFile = manager.resolveFile(source, opt); if (remoteFile.exists()) { FileObject[] children = remoteFile.getChildren(); OMFactory factory = OMAbstractFactory.getOMFactory(); String outputResult; OMNamespace ns = factory.createOMNamespace(FileConstants.FILECON, FileConstants.NAMESPACE); OMElement result = factory.createOMElement(FileConstants.RESULT, ns); resultPayload.preparePayload(messageContext, result); FilePattenMatcher fpm = new FilePattenMatcher(filePattern); recursiveSearch = recursiveSearch.trim(); for (FileObject child : children) { try { if (child.getType() == FileType.FILE && fpm.validate(child.getName().getBaseName().toLowerCase())) { outputResult = child.getName().getPath(); OMElement messageElement = factory.createOMElement(FileConstants.FILE, ns); messageElement.setText(outputResult); result.addChild(messageElement); } else if (child.getType() == FileType.FOLDER && "true".equals(recursiveSearch)) { searchSubFolders(child, filePattern, messageContext, factory, result, ns); } } catch (IOException e) { handleException("Unable to search a file.", e, messageContext); } finally { try { if (child != null) { child.close(); } } catch (IOException e) { log.error("Error while closing Directory: " + e.getMessage(), e); } } } messageContext.getEnvelope().getBody().addChild(result); } else { log.error("File location does not exist."); } } catch (IOException e) { handleException("Unable to search a file.", e, messageContext); } finally { if (manager != null) { manager.close(); } } } }
From source file:org.wso2.carbon.connector.FileSearchConnector.java
/** * List the all files of given pattern.//from w w w. j a v a 2 s . c om * * @param messageContext The message context that is generated for processing the file. */ private void searchFile(MessageContext messageContext) { String source = (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.FILE_LOCATION); String filePattern = (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.FILE_PATTERN); boolean enableRecursiveSearch = false; String recursiveSearchParameter = (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.RECURSIVE_SEARCH); if (StringUtils.isNotEmpty(recursiveSearchParameter)) { enableRecursiveSearch = Boolean.parseBoolean(recursiveSearchParameter); } StandardFileSystemManager manager = FileConnectorUtils.getManager(); if (StringUtils.isEmpty(filePattern)) { throw new SynapseException("FilePattern should not be null"); } try { FileSystemOptions opt = FileConnectorUtils.init(messageContext); FileObject remoteFile = manager.resolveFile(source, opt); if (!remoteFile.exists()) { throw new SynapseException("File location does not exist"); } FileObject[] children = remoteFile.getChildren(); OMFactory factory = OMAbstractFactory.getOMFactory(); OMNamespace ns = factory.createOMNamespace(FileConstants.FILECON, FileConstants.NAMESPACE); OMElement result = factory.createOMElement(FileConstants.RESULT, ns); ResultPayloadCreator.preparePayload(messageContext, result); FilePattenMatcher fpm = new FilePattenMatcher(filePattern); for (FileObject child : children) { try { if (FileType.FILE.equals(child.getType()) && fpm.validate(child.getName().getBaseName())) { String outputResult = child.getName().getPath(); OMElement messageElement = factory.createOMElement(FileConstants.FILE, ns); messageElement.setText(outputResult); result.addChild(messageElement); } else if (FileType.FOLDER.equals(child.getType()) && enableRecursiveSearch) { searchSubFolders(child, filePattern, factory, result, ns); } } catch (FileSystemException e) { throw new SynapseException("Unable to search a file.", e); } finally { try { if (child != null) { child.close(); } } catch (IOException e) { log.error("Error while closing Directory: " + e.getMessage(), e); } } } messageContext.getEnvelope().getBody().addChild(result); } catch (FileSystemException e) { throw new SynapseException("Unable to search a file for a given pattern.", e); } finally { manager.close(); } }
From source file:org.wso2.carbon.connector.FileSend.java
/** * Send the file to the target directory. * * @param address Location for send the file. * @param append If the response should be appended to the response file or not. * @return return true, if file is sent successfully. *//*w w w . jav a 2 s. c o m*/ private boolean sendResponseFile(String address, MessageContext messageContext, boolean append) { boolean resultStatus = false; FileObject fileObj; StandardFileSystemManager manager = null; CountingOutputStream os = null; if (log.isDebugEnabled()) { log.debug("File sending started to" + address); } try { manager = FileConnectorUtils.getManager(); org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) .getAxis2MessageContext(); fileObj = manager.resolveFile(address, FileConnectorUtils.init(messageContext)); if (fileObj.getType() == FileType.FOLDER) { address = address.concat(FileConstants.DEFAULT_RESPONSE_FILE); fileObj = manager.resolveFile(address, FileConnectorUtils.init(messageContext)); } // Get the message formatter. MessageFormatter messageFormatter = getMessageFormatter(axis2MessageContext); OMOutputFormat format = BaseUtils.getOMOutputFormat(axis2MessageContext); // Creating output stream and give the content to that. os = new CountingOutputStream(fileObj.getContent().getOutputStream(append)); if (format != null && os != null && messageContext != null) { messageFormatter.writeTo(axis2MessageContext, format, os, true); resultStatus = true; if (log.isDebugEnabled()) { log.debug("File send completed to " + address); } } else { log.error("Can not send the file to specific address"); } } catch (IOException e) { handleException("Unable to send a file/folder.", e, messageContext); } finally { try { os.close(); } catch (IOException e) { log.warn("Can not close the output stream"); } if (manager != null) { manager.close(); } } return resultStatus; }
From source file:org.wso2.carbon.connector.FileSendConnector.java
/** * Send the file to the target directory. * * @param messageContext The message context that is used in file send mediation flow. * @return return true, if file is sent successfully. * @throws FileSystemException On error parsing the file name and getting file type. *///from w w w . j a v a2s .c om private boolean sendResponseFile(MessageContext messageContext) throws FileSystemException { boolean append = false; String destination = (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.NEW_FILE_LOCATION); String strAppend = (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.APPEND); if (StringUtils.isNotEmpty(strAppend)) { append = Boolean.parseBoolean(strAppend); } StandardFileSystemManager manager = FileConnectorUtils.getManager(); FileObject fileObjectToSend = null; FileObject fileObj = manager.resolveFile(destination, FileConnectorUtils.init(messageContext)); CountingOutputStream outputStream = null; if (log.isDebugEnabled()) { log.debug("File sending started to " + destination); } try { org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) .getAxis2MessageContext(); if (FileType.FOLDER.equals(fileObj.getType())) { String destDir = destination.concat(FileConstants.DEFAULT_RESPONSE_FILE); fileObjectToSend = manager.resolveFile(destDir, FileConnectorUtils.init(messageContext)); } else if (FileType.FILE.equals(fileObj.getType())) { fileObjectToSend = fileObj; } // Get the message formatter. MessageFormatter messageFormatter = getMessageFormatter(axis2MessageContext); OMOutputFormat format = BaseUtils.getOMOutputFormat(axis2MessageContext); // Creating output stream and give the content to that. outputStream = new CountingOutputStream(fileObjectToSend.getContent().getOutputStream(append)); messageFormatter.writeTo(axis2MessageContext, format, outputStream, true); if (log.isDebugEnabled()) { log.debug("File send completed to " + destination); } } catch (AxisFault e) { throw new SynapseException("Error while writing the message context", e); } finally { try { fileObjectToSend.close(); } catch (FileSystemException e) { log.error("Error while closing FileObject", e); } try { if (outputStream != null) { outputStream.close(); } } catch (IOException e) { log.warn("Can not close the output stream"); } manager.close(); } return true; }
From source file:org.wso2.carbon.connector.FileUnzipConnector.java
/** * Decompress the compressed file into the given directory. * * @param messageContext The message context that is generated for processing unzip operation. * @return true, if zip file successfully extracts and false, if not. * @throws FileSystemException On error parsing the file name, determining if the file exists and creating the * folder.//from w w w . j ava 2 s. co m */ private boolean unzip(MessageContext messageContext) throws FileSystemException { String source = (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.FILE_LOCATION); String destination = (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.NEW_FILE_LOCATION); StandardFileSystemManager manager = FileConnectorUtils.getManager(); FileSystemOptions opts = FileConnectorUtils.init(messageContext); FileObject remoteFile = manager.resolveFile(source, opts); FileObject remoteDesFile = manager.resolveFile(destination, opts); if (!remoteFile.exists()) { log.error("File does not exist."); return false; } if (!remoteDesFile.exists()) { //create a folder remoteDesFile.createFolder(); } //open the zip file ZipInputStream zipIn = new ZipInputStream(remoteFile.getContent().getInputStream()); try { ZipEntry entry = zipIn.getNextEntry(); // iterates over entries in the zip file while (entry != null) { String filePath = destination + File.separator + entry.getName(); // create remote object FileObject remoteFilePath = manager.resolveFile(filePath, opts); if (log.isDebugEnabled()) { log.debug("The created path is " + remoteFilePath.toString()); } try { if (!entry.isDirectory()) { // if the entry is a file, extracts it extractFile(zipIn, remoteFilePath); } else { // if the entry is a directory, make the directory remoteFilePath.createFolder(); } } finally { try { zipIn.closeEntry(); entry = zipIn.getNextEntry(); } catch (IOException e) { log.error("Error while closing the ZipInputStream", e); } } } } catch (IOException e) { throw new SynapseException("Error while reading the next ZIP file entry", e); } finally { // close the zip file try { zipIn.close(); } catch (IOException e) { log.error("Error while closing the ZipInputStream", e); } // close the StandardFileSystemManager manager.close(); try { remoteFile.close(); remoteDesFile.close(); } catch (FileSystemException e) { log.error("Error while closing the FileObject", e); } } if (log.isDebugEnabled()) { log.debug("File extracted to" + destination); } return true; }
From source file:sftpexamples.GetMyFiles.java
public boolean startFTP(String propertiesFilename, String fileToDownload) { props = new Properties(); StandardFileSystemManager manager = new StandardFileSystemManager(); try {/*from w ww . ja v a 2 s . c om*/ props.load(new FileInputStream(System.getProperty("user.home") + propertiesFilename)); String serverAddress = props.getProperty("serverAddress").trim(); String userId = props.getProperty("userId").trim(); String password = props.getProperty("password").trim(); String remoteDirectory = props.getProperty("remoteDirectory").trim(); String localDirectory = props.getProperty("localDirectory").trim(); //Initializes the file manager manager.init(); //Setup our SFTP configuration FileSystemOptions opts = new FileSystemOptions(); SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no"); SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true); SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000); //Create the SFTP URI using the host name, userid, password, remote path and file name //String sftpUri = "sftp://" + userId + ":" + password + "@" + serverAddress // + "/" + remoteDirectory + fileToDownload; String sftpUri = "sftp://" + userId + ":" + password + "@" + serverAddress + "/" + fileToDownload; // Create local file object String filepath = localDirectory + fileToDownload; File file = new File(filepath); FileObject localFile = manager.resolveFile(file.getAbsolutePath()); // Create remote file object FileObject remoteFile = manager.resolveFile(sftpUri, opts); // Copy local file to sftp server localFile.copyFrom(remoteFile, Selectors.SELECT_SELF); System.out.println("File download successful"); } catch (Exception ex) { ex.printStackTrace(); return false; } finally { manager.close(); } return true; }
From source file:sftpexamples.SendMyFiles.java
public boolean startFTP(String propertiesFilename, String fileToFTP) { props = new Properties(); StandardFileSystemManager manager = new StandardFileSystemManager(); try {// w w w .j ava 2s. c om props.load(new FileInputStream(System.getProperty("user.home") + propertiesFilename)); //props.setProperty("serverAddress", "127.0.0.1"); String serverAddress = props.getProperty("serverAddress").trim(); String userId = props.getProperty("userId").trim(); String password = props.getProperty("password").trim(); String remoteDirectory = props.getProperty("remoteDirectory").trim(); String localDirectory = props.getProperty("localDirectory").trim(); System.out.println("properties are fetched:serverAddress=" + serverAddress); System.out.println("userId=" + userId); System.out.println("password=" + password); System.out.println("remoteDirectory=" + remoteDirectory); System.out.println("localDirectory=" + localDirectory); //check if the file exists String filepath = localDirectory + fileToFTP; System.out.println("filepath:" + filepath); File file = new File(filepath); if (!file.exists()) { throw new RuntimeException("Error. Local file not found"); } //Initializes the file manager manager.init(); //Setup our SFTP configuration FileSystemOptions opts = new FileSystemOptions(); SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no"); SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true); SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000); //Create the SFTP URI using the host name, userid, password, remote path and file name String sftpUri = "sftp://" + userId + ":" + password + "@" + serverAddress + "/" + fileToFTP; System.out.println("uri: " + sftpUri); // Create local file object FileObject localFile = manager.resolveFile(file.getAbsolutePath()); // Create remote file object FileObject remoteFile = manager.resolveFile(sftpUri, opts); // Copy local file to sftp server remoteFile.copyFrom(localFile, Selectors.SELECT_SELF); System.out.println("File upload successful"); } catch (Exception ex) { ex.printStackTrace(); return false; } finally { manager.close(); } return true; }