List of usage examples for org.apache.commons.vfs2 FileObject copyFrom
void copyFrom(FileObject srcFile, FileSelector selector) throws FileSystemException;
From source file:org.renjin.primitives.files.Files.java
@Internal("file.copy") public static LogicalVector fileCopy(@Current Context context, StringVector fromFiles, String to, boolean overwrite, final boolean recursive) throws FileSystemException { LogicalArrayVector.Builder result = new LogicalArrayVector.Builder(); FileObject toFile = context.resolveFile(to); for (String from : fromFiles) { try {/*from w w w . ja v a 2s. c o m*/ toFile.copyFrom(context.resolveFile(from), new FileSelector() { @Override public boolean traverseDescendents(FileSelectInfo fileInfo) throws Exception { return true; } @Override public boolean includeFile(FileSelectInfo fileInfo) throws Exception { return recursive; } }); result.add(true); } catch (FileSystemException e) { result.add(false); } } return result.build(); }
From source file:org.schedoscope.export.ftp.upload.Uploader.java
/** * A method to copy a file from src (hdfs) to (s)ftp (remote). * * @param inFile The input file to copy. * @param outFile The output file to create. * @throws FileSystemException Is thrown if an error occurs. *//*from ww w . jav a 2s . com*/ public void uploadFile(String inFile, String outFile) throws FileSystemException { FileObject local = fsManager.resolveFile(inFile); FileObject remote = fsManager.resolveFile(outFile, opts); LOG.debug("copy " + local + " to " + remote); remote.copyFrom(local, new AllFileSelector()); }
From source file:org.wso2.carbon.connector.FileCopy.java
/** * Copy files/* w w w .j a v a2s. c o m*/ * * @param source Location of the file * @param destination new file location * @param filePattern pattern of the file * @param messageContext The message context that is generated for processing the file * @param opts FileSystemOptions * @return return a resultStatus */ private boolean copyFile(String source, String destination, String filePattern, MessageContext messageContext, FileSystemOptions opts) { boolean resultStatus = false; StandardFileSystemManager manager = null; try { manager = FileConnectorUtils.getManager(); FileObject souFile = manager.resolveFile(source, opts); FileObject destFile = manager.resolveFile(destination, opts); if (StringUtils.isNotEmpty(filePattern)) { FileObject[] children = souFile.getChildren(); for (FileObject child : children) { if (child.getType() == FileType.FILE) { copy(source, destination, filePattern, opts); } else if (child.getType() == FileType.FOLDER) { String newSource = source + File.separator + child.getName().getBaseName(); copyFile(newSource, destination, filePattern, messageContext, opts); } } resultStatus = true; } else { if (souFile.exists()) { if (souFile.getType() == FileType.FILE) { InputStream fileIn = null; OutputStream fileOut = null; try { String name = souFile.getName().getBaseName(); FileObject outFile = manager.resolveFile(destination + File.separator + name, opts); //TODO make parameter sense fileIn = souFile.getContent().getInputStream(); fileOut = outFile.getContent().getOutputStream(); IOUtils.copyLarge(fileIn, fileOut); resultStatus = true; } catch (FileSystemException e) { log.error("Error while copying a file " + e.getMessage()); } finally { try { if (fileOut != null) { fileOut.close(); } } catch (Exception e) { log.error("Error while closing OutputStream: " + e.getMessage(), e); } try { if (fileIn != null) { fileIn.close(); } } catch (Exception e) { log.error("Error while closing InputStream: " + e.getMessage(), e); } } } else if (souFile.getType() == FileType.FOLDER) { destFile.copyFrom(souFile, Selectors.SELECT_ALL); resultStatus = true; } if (log.isDebugEnabled()) { log.debug("File copying completed from " + source + "to" + destination); } } else { log.error("The File Location does not exist."); resultStatus = false; } } return resultStatus; } catch (IOException e) { handleException("Unable to copy a file/folder", e, messageContext); } finally { if (manager != null) { manager.close(); } } return resultStatus; }
From source file:org.wso2.carbon.connector.FileCopy.java
/** * @param source file location/* ww w.j a v a 2 s . co m*/ * @param destination target file location * @param filePattern pattern of the file * @param opts FileSystemOptions * @throws IOException */ private void copy(String source, String destination, String filePattern, FileSystemOptions opts) throws IOException { StandardFileSystemManager manager = FileConnectorUtils.getManager(); FileObject souFile = manager.resolveFile(source, opts); FileObject[] children = souFile.getChildren(); FilePattenMatcher patternMatcher = new FilePattenMatcher(filePattern); for (FileObject child : children) { try { if (patternMatcher.validate(child.getName().getBaseName())) { String name = child.getName().getBaseName(); FileObject outFile = manager.resolveFile(destination + File.separator + name, opts); outFile.copyFrom(child, Selectors.SELECT_FILES); } } catch (IOException e) { log.error("Error occurred while copying a file. " + e.getMessage(), e); } } manager.close(); }
From source file:org.wso2.carbon.connector.FileCopyConnector.java
/** * Copy the file or folder from source to destination. * * @param messageContext The message context that is generated for processing the file. * @param opts FileSystemOptions. * @return return true, if file/folder is successfully copied. *//*from ww w . j av a2 s. c o m*/ private boolean copyFile(String source, MessageContext messageContext, FileSystemOptions opts) { String destination = (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.NEW_FILE_LOCATION); String filePattern = (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.FILE_PATTERN); String includeParentDir = (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.INCLUDE_PARENT_DIRECTORY); boolean includeParentDirectory = FileConstants.DEFAULT_INCLUDE_PARENT_DIRECTORY; if (StringUtils.isNotEmpty(includeParentDir)) { includeParentDirectory = Boolean.parseBoolean(includeParentDir); } boolean resultStatus = false; StandardFileSystemManager manager = FileConnectorUtils.getManager(); FileObject souFile = null; FileObject destFile = null; try { souFile = manager.resolveFile(source, opts); destFile = manager.resolveFile(destination, opts); if (!souFile.exists()) { log.error("The File Location does not exist."); return false; } if (StringUtils.isNotEmpty(filePattern)) { FileObject[] children = souFile.getChildren(); for (FileObject child : children) { if (FileType.FILE.equals(child.getType())) { copy(child, destination, filePattern, opts, manager); } else if (FileType.FOLDER.equals(child.getType())) { String newSource = source + File.separator + child.getName().getBaseName(); copyFile(newSource, messageContext, opts); } } } else { if (FileType.FILE.equals(souFile.getType())) { String name = souFile.getName().getBaseName(); FileObject outFile = manager.resolveFile(destination + File.separator + name, opts); outFile.copyFrom(souFile, Selectors.SELECT_ALL); } else if (FileType.FOLDER.equals(souFile.getType())) { if (includeParentDirectory) { destFile = manager .resolveFile(destination + File.separator + souFile.getName().getBaseName(), opts); destFile.createFolder(); } destFile.copyFrom(souFile, Selectors.SELECT_ALL); } if (log.isDebugEnabled()) { log.debug("File copying completed from " + source + "to" + destination); } } } catch (FileSystemException e) { throw new SynapseException("Unable to copy a file/folder", e); } finally { manager.close(); } try { souFile.close(); destFile.close(); } catch (FileSystemException e) { log.error("Error while closing the FileObject", e); } return true; }
From source file:org.wso2.carbon.connector.FileCopyConnector.java
/** * copy the file for given pattern.//from w w w . j a va 2s .c om * * @param source The source file object. * @param destination The target file location. * @param filePattern Pattern of the file. * @param opts Configured file system. */ private void copy(FileObject source, String destination, String filePattern, FileSystemOptions opts, StandardFileSystemManager manager) throws FileSystemException { FilePattenMatcher patternMatcher = new FilePattenMatcher(filePattern); if (patternMatcher.validate(source.getName().getBaseName())) { String name = source.getName().getBaseName(); FileObject outFile = manager.resolveFile(destination + File.separator + name, opts); outFile.copyFrom(source, Selectors.SELECT_ALL); } }
From source file:org.wso2.carbon.connector.FileRename.java
/** * Rename the files// w w w . j a v a 2s . co m * * @param fileLocation * @param filename * @param newFileName * @param filebeforepprocess * @return */ private boolean renameFile(String fileLocation, String filename, String newFileName, String filebeforepprocess) throws FileSystemException { boolean resultStatus = false; FileSystemManager manager = VFS.getManager(); if (manager != null) { // Create remote object FileObject remoteFile = manager.resolveFile(fileLocation.toString() + filename.toString(), FTPSiteUtils.createDefaultOptions()); FileObject reNameFile = manager.resolveFile(fileLocation.toString() + newFileName.toString(), FTPSiteUtils.createDefaultOptions()); if (remoteFile.exists()) { if (!filebeforepprocess.equals("")) { FileObject fBeforeProcess = manager.resolveFile(filebeforepprocess + filename); fBeforeProcess.copyFrom(remoteFile, Selectors.SELECT_SELF_AND_CHILDREN); } remoteFile.moveTo(reNameFile); resultStatus = true; if (log.isDebugEnabled()) { log.info("Rename remote file success"); } } } return resultStatus; }
From source file:org.wso2.carbon.transport.file.connector.sender.VFSClientConnector.java
@Override public boolean send(CarbonMessage carbonMessage, CarbonCallback carbonCallback, Map<String, String> map) throws ClientConnectorException { FtpFileSystemConfigBuilder.getInstance().setPassiveMode(opts, true); String fileURI = map.get(Constants.FILE_URI); String action = map.get(Constants.ACTION); FileType fileType;//from w ww. j av a 2s. c o m ByteBuffer byteBuffer; InputStream inputStream = null; OutputStream outputStream = null; try { FileSystemManager fsManager = VFS.getManager(); FileObject path = fsManager.resolveFile(fileURI, opts); fileType = path.getType(); switch (action) { case Constants.CREATE: boolean isFolder = Boolean.parseBoolean(map.getOrDefault("create-folder", "false")); if (path.exists()) { throw new ClientConnectorException("File already exists: " + path.getName().getURI()); } if (isFolder) { path.createFolder(); } else { path.createFile(); } break; case Constants.WRITE: if (!path.exists()) { path.createFile(); path.refresh(); fileType = path.getType(); } if (fileType == FileType.FILE) { if (carbonMessage instanceof BinaryCarbonMessage) { BinaryCarbonMessage binaryCarbonMessage = (BinaryCarbonMessage) carbonMessage; byteBuffer = binaryCarbonMessage.readBytes(); } else { throw new ClientConnectorException("Carbon message received is not a BinaryCarbonMessage"); } byte[] bytes = byteBuffer.array(); if (map.get(Constants.APPEND) != null) { outputStream = path.getContent() .getOutputStream(Boolean.parseBoolean(map.get(Constants.APPEND))); } else { outputStream = path.getContent().getOutputStream(); } outputStream.write(bytes); outputStream.flush(); } break; case Constants.DELETE: if (path.exists()) { int filesDeleted = path.delete(Selectors.SELECT_ALL); if (logger.isDebugEnabled()) { logger.debug(filesDeleted + " files successfully deleted"); } } else { throw new ClientConnectorException( "Failed to delete file: " + path.getName().getURI() + " not found"); } break; case Constants.COPY: if (path.exists()) { String destination = map.get("destination"); FileObject dest = fsManager.resolveFile(destination, opts); dest.copyFrom(path, Selectors.SELECT_ALL); } else { throw new ClientConnectorException( "Failed to copy file: " + path.getName().getURI() + " not found"); } break; case Constants.MOVE: if (path.exists()) { //TODO: Improve this to fix issue #331 String destination = map.get("destination"); FileObject newPath = fsManager.resolveFile(destination, opts); FileObject parent = newPath.getParent(); if (parent != null && !parent.exists()) { parent.createFolder(); } if (!newPath.exists()) { path.moveTo(newPath); } else { throw new ClientConnectorException("The file at " + newPath.getURL().toString() + " already exists or it is a directory"); } } else { throw new ClientConnectorException( "Failed to move file: " + path.getName().getURI() + " not found"); } break; case Constants.READ: if (path.exists()) { //TODO: Do not assume 'path' always refers to a file inputStream = path.getContent().getInputStream(); byte[] bytes = toByteArray(inputStream); BinaryCarbonMessage message = new BinaryCarbonMessage(ByteBuffer.wrap(bytes), true); message.setProperty(org.wso2.carbon.messaging.Constants.DIRECTION, org.wso2.carbon.messaging.Constants.DIRECTION_RESPONSE); carbonMessageProcessor.receive(message, carbonCallback); } else { throw new ClientConnectorException( "Failed to read file: " + path.getName().getURI() + " not found"); } break; case Constants.EXISTS: TextCarbonMessage message = new TextCarbonMessage(Boolean.toString(path.exists())); message.setProperty(org.wso2.carbon.messaging.Constants.DIRECTION, org.wso2.carbon.messaging.Constants.DIRECTION_RESPONSE); carbonMessageProcessor.receive(message, carbonCallback); break; default: return false; } } catch (RuntimeException e) { throw new ClientConnectorException("Runtime Exception occurred : " + e.getMessage(), e); } catch (Exception e) { throw new ClientConnectorException("Exception occurred while processing file: " + e.getMessage(), e); } finally { closeQuietly(inputStream); closeQuietly(outputStream); } return true; }
From source file:org.wso2.carbon.transport.remotefilesystem.client.connector.contractimpl.VFSClientConnectorImpl.java
@Override public void send(RemoteFileSystemMessage message) { FtpFileSystemConfigBuilder.getInstance().setPassiveMode(opts, true); String fileURI = connectorConfig.get(Constants.URI); String action = connectorConfig.get(Constants.ACTION); FileType fileType;/* www. jav a 2 s.c om*/ ByteBuffer byteBuffer; InputStream inputStream = null; OutputStream outputStream = null; FileObject path = null; try { FileSystemManager fsManager = VFS.getManager(); path = fsManager.resolveFile(fileURI, opts); fileType = path.getType(); switch (action) { case Constants.CREATE: boolean isFolder = Boolean .parseBoolean(connectorConfig.getOrDefault(Constants.CREATE_FOLDER, "false")); if (path.exists()) { throw new RemoteFileSystemConnectorException("File already exists: " + path.getName().getURI()); } if (isFolder) { path.createFolder(); } else { path.createFile(); } break; case Constants.WRITE: if (!path.exists()) { path.createFile(); path.refresh(); fileType = path.getType(); } if (fileType == FileType.FILE) { byteBuffer = message.getBytes(); byte[] bytes = byteBuffer.array(); if (connectorConfig.get(Constants.APPEND) != null) { outputStream = path.getContent() .getOutputStream(Boolean.parseBoolean(connectorConfig.get(Constants.APPEND))); } else { outputStream = path.getContent().getOutputStream(); } outputStream.write(bytes); outputStream.flush(); } break; case Constants.DELETE: if (path.exists()) { int filesDeleted = path.delete(Selectors.SELECT_ALL); if (logger.isDebugEnabled()) { logger.debug(filesDeleted + " files successfully deleted"); } } else { throw new RemoteFileSystemConnectorException( "Failed to delete file: " + path.getName().getURI() + " not found"); } break; case Constants.COPY: if (path.exists()) { String destination = connectorConfig.get(Constants.DESTINATION); FileObject dest = fsManager.resolveFile(destination, opts); dest.copyFrom(path, Selectors.SELECT_ALL); } else { throw new RemoteFileSystemConnectorException( "Failed to copy file: " + path.getName().getURI() + " not found"); } break; case Constants.MOVE: if (path.exists()) { //TODO: Improve this to fix issue #331 String destination = connectorConfig.get(Constants.DESTINATION); FileObject newPath = fsManager.resolveFile(destination, opts); FileObject parent = newPath.getParent(); if (parent != null && !parent.exists()) { parent.createFolder(); } if (!newPath.exists()) { path.moveTo(newPath); } else { throw new RemoteFileSystemConnectorException("The file at " + newPath.getURL().toString() + " already exists or it is a directory"); } } else { throw new RemoteFileSystemConnectorException( "Failed to move file: " + path.getName().getURI() + " not found"); } break; case Constants.READ: if (path.exists()) { //TODO: Do not assume 'path' always refers to a file inputStream = path.getContent().getInputStream(); byte[] bytes = toByteArray(inputStream); RemoteFileSystemMessage fileContent = new RemoteFileSystemMessage(ByteBuffer.wrap(bytes)); remoteFileSystemListener.onMessage(fileContent); } else { throw new RemoteFileSystemConnectorException( "Failed to read file: " + path.getName().getURI() + " not found"); } break; case Constants.EXISTS: RemoteFileSystemMessage fileContent = new RemoteFileSystemMessage(Boolean.toString(path.exists())); remoteFileSystemListener.onMessage(fileContent); break; default: break; } remoteFileSystemListener.done(); } catch (RemoteFileSystemConnectorException | IOException e) { remoteFileSystemListener.onError(e); } finally { if (path != null) { try { path.close(); } catch (FileSystemException e) { //Do nothing. } } closeQuietly(inputStream); closeQuietly(outputStream); } }
From source file:sftpexamples.GetMyFiles.java
public boolean startFTP(String propertiesFilename, String fileToDownload) { props = new Properties(); StandardFileSystemManager manager = new StandardFileSystemManager(); try {/*from w ww.j a v a2 s. c o m*/ 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; }