List of usage examples for org.apache.commons.vfs2 FileObject getParent
FileObject getParent() throws FileSystemException;
From source file:org.pentaho.vfs.ui.VfsFileChooserDialog.java
public void updateParentFileCombo(FileObject selectedItem) { try {/*from w w w . j a v a2 s . c om*/ List<FileObject> parentChain = new ArrayList<FileObject>(); // are we a directory? try { if (selectedItem.getType() == FileType.FOLDER && selectedItem.getType().hasChildren()) { // we have real children.... parentChain.add(selectedItem); } } catch (Exception e) { // we are not a folder } FileObject parentFileObject; parentFileObject = selectedItem.getParent(); while (parentFileObject != null) { parentChain.add(parentFileObject); parentFileObject = parentFileObject.getParent(); } File roots[] = File.listRoots(); if (currentPanel != null) { for (int i = 0; i < roots.length; i++) { parentChain.add(currentPanel.resolveFile(roots[i].getAbsolutePath())); } } String items[] = new String[parentChain.size()]; int idx = 0; for (int i = parentChain.size() - 1; i >= 0; i--) { items[idx++] = ((FileObject) parentChain.get(i)).getName().getURI(); } openFileCombo.setItems(items); openFileCombo.select(items.length - 1); } catch (Exception e) { e.printStackTrace(); // then let's not update the GUI } }
From source file:org.renjin.primitives.files.Files.java
@Internal("file.create") @DataParallel/* ww w . j a v a 2 s . c o m*/ public static boolean fileCreate(@Current Context context, @Recycle String fileName, @Recycle(false) boolean showWarnings) throws IOException { try { FileObject file = context.resolveFile(fileName); // VFS will create the parent folder if it doesn't exist, // which the R method is not supposed to do if (!file.getParent().exists()) { throw new IOException("No such file or directory"); } file.getContent().getOutputStream().close(); return true; } catch (Exception e) { if (showWarnings) { Warning.invokeWarning(context, "cannot create file '%s', reason '%s'", fileName, e.getMessage()); } return false; } }
From source file:org.wso2.carbon.connector.FileRead.java
public void connect(MessageContext messageContext) { String fileLocation = (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.FILE_LOCATION); String contentType = (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.CONTENT_TYPE); String filePattern = (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.FILE_PATTERN); FileObject fileObj = null; StandardFileSystemManager manager = null; try {/*from w ww . jav a 2s.c o m*/ manager = FileConnectorUtils.getManager(); fileObj = manager.resolveFile(fileLocation, FileConnectorUtils.init(messageContext)); if (fileObj.exists()) { if (fileObj.getType() == FileType.FOLDER) { FileObject[] children = fileObj.getChildren(); if (children == null || children.length == 0) { log.warn("Empty folder."); handleException("Empty folder.", messageContext); } else if (filePattern != null && !filePattern.trim().equals("")) { boolean bFound = false; for (FileObject child : children) { if (child.getName().getBaseName().matches(filePattern)) { fileObj = child; bFound = true; break; } } if (!bFound) { log.warn("File does not exists for the mentioned pattern."); handleException("File does not exists for the mentioned pattern.", messageContext); } } else { fileObj = children[0]; } } else if (fileObj.getType() != FileType.FILE) { log.warn("File does not exists, or an empty folder."); handleException("File does not exists, or an empty folder.", messageContext); } } else { log.warn("File/Folder does not exists"); handleException("File/Folder does not exists", messageContext); } ResultPayloadCreate.buildFile(fileObj, messageContext, contentType); if (log.isDebugEnabled()) { log.debug("File read completed." + fileLocation); } } catch (Exception e) { handleException(e.getMessage(), messageContext); } finally { try { // Close the File system if it is not already closed by the finally block of // processFile method if (fileObj != null && fileObj.getParent() != null && fileObj.getParent().getFileSystem() != null) { manager.closeFileSystem(fileObj.getParent().getFileSystem()); } } catch (FileSystemException warn) { // ignore the warning, since we handed over the stream close job to // AutoCloseInputStream.. } try { if (fileObj != null) { fileObj.close(); } } catch (Exception e) { // ignore the warning, since we handed over the stream close job to // AutoCloseInputStream.. } } }
From source file:org.wso2.carbon.connector.FileReadConnector.java
/** * Read the file content.//from w ww. ja va2s . co m * * @param messageContext The message context that is generated for processing the read operation. */ private void readFile(MessageContext messageContext) { String source = (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.FILE_LOCATION); String contentType = (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.CONTENT_TYPE); String filePattern = (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.FILE_PATTERN); boolean streaming = false; String enableStreamingParameter = (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.ENABLE_STREAMING); if (StringUtils.isNotEmpty(enableStreamingParameter)) { streaming = Boolean.parseBoolean(enableStreamingParameter); } FileObject fileObjectToRead = null; StandardFileSystemManager manager = FileConnectorUtils.getManager(); try { FileObject rootFileObject = manager.resolveFile(source, FileConnectorUtils.init(messageContext)); if (!rootFileObject.exists()) { log.error("File/Folder does not exists."); } if (FileType.FOLDER.equals(rootFileObject.getType())) { FileObject[] children = rootFileObject.getChildren(); if (children == null || children.length == 0) { log.error("Empty folder."); } else if (StringUtils.isNotEmpty(filePattern)) { for (FileObject child : children) { if (child.getName().getBaseName().matches(filePattern)) { fileObjectToRead = child; break; } } if (fileObjectToRead == null) { log.error("File does not exists for the mentioned pattern."); } } else { fileObjectToRead = children[0]; } } else if (FileType.FILE.equals(rootFileObject.getType())) { fileObjectToRead = rootFileObject; } else { log.error("File does not exists, or an empty folder"); } ResultPayloadCreator.buildFile(fileObjectToRead, messageContext, contentType, streaming); if (log.isDebugEnabled()) { log.debug("File read completed." + source); } } catch (FileSystemException e) { throw new SynapseException("Error while reading a file", e); } finally { try { // Close the File system if it is not already closed by the finally block of processFile method if (fileObjectToRead != null && fileObjectToRead.getParent() != null && fileObjectToRead.getParent().getFileSystem() != null) { manager.closeFileSystem(fileObjectToRead.getParent().getFileSystem()); } if (fileObjectToRead != null) { fileObjectToRead.close(); } } catch (FileSystemException e) { log.error("Error while closing the FileObject", e); } } }
From source file:org.wso2.carbon.inbound.endpoint.protocol.file.FilePollingConsumer.java
/** * //w ww .ja va 2 s .co m * Do the file processing operation for the given set of properties. Do the * checks and pass the control to processFile method * * */ public FileObject poll() { if (fileURI == null || fileURI.trim().equals("")) { log.error("Invalid file url. Check the inbound endpoint configuration. Endpoint Name : " + name + ", File URL : " + VFSUtils.maskURLPassword(fileURI)); return null; } if (log.isDebugEnabled()) { log.debug("Start : Scanning directory or file : " + VFSUtils.maskURLPassword(fileURI)); } if (!initFileCheck()) { // Unable to read from the source location provided. return null; } // If file/folder found proceed to the processing stage try { lastCycle = 0; if (fileObject.exists() && fileObject.isReadable()) { FileObject[] children = null; try { children = fileObject.getChildren(); } catch (FileNotFolderException ignored) { if (log.isDebugEnabled()) { log.debug("No Folder found. Only file found on : " + VFSUtils.maskURLPassword(fileURI)); } } catch (FileSystemException ex) { log.error(ex.getMessage(), ex); } // if this is a file that would translate to a single message if (children == null || children.length == 0) { // Fail record is a one that is processed but was not moved // or deleted due to an error. boolean isFailedRecord = VFSUtils.isFailRecord(fsManager, fileObject); if (!isFailedRecord) { fileHandler(); if (injectHandler == null) { return fileObject; } } else { try { lastCycle = 2; moveOrDeleteAfterProcessing(fileObject); } catch (SynapseException synapseException) { log.error("File object '" + VFSUtils.maskURLPassword(fileObject.getURL().toString()) + "' " + "cloud not be moved after first attempt", synapseException); } if (fileLock) { // TODO: passing null to avoid build break. Fix properly VFSUtils.releaseLock(fsManager, fileObject, fso); } if (log.isDebugEnabled()) { log.debug("File '" + VFSUtils.maskURLPassword(fileObject.getURL().toString()) + "' has been marked as a failed" + " record, it will not process"); } } } else { FileObject fileObject = directoryHandler(children); if (fileObject != null) { return fileObject; } } } else { log.warn("Unable to access or read file or directory : " + VFSUtils.maskURLPassword(fileURI) + "." + " Reason: " + (fileObject.exists() ? (fileObject.isReadable() ? "Unknown reason" : "The file can not be read!") : "The file does not exists!")); return null; } } catch (FileSystemException e) { log.error("Error checking for existence and readability : " + VFSUtils.maskURLPassword(fileURI), e); return null; } catch (Exception e) { log.error("Error while processing the file/folder in URL : " + VFSUtils.maskURLPassword(fileURI), e); return null; } finally { try { if (fsManager != null) { fsManager.closeFileSystem(fileObject.getParent().getFileSystem()); } fileObject.close(); } catch (Exception e) { log.error("Unable to close the file system. " + e.getMessage()); log.error(e); } } if (log.isDebugEnabled()) { log.debug("End : Scanning directory or file : " + VFSUtils.maskURLPassword(fileURI)); } return null; }
From source file:org.wso2.carbon.inbound.endpoint.protocol.file.FilePollingConsumer.java
/** * //from ww w . j av a 2 s . c o m * Acquire distributed lock if required first, then do the file level locking * * @param fsManager * @param fileObject * @return */ private boolean acquireLock(FileSystemManager fsManager, FileObject fileObject) { String strContext = fileObject.getName().getURI(); boolean rtnValue = false; try { if (distributedLock) { if (distributedLockTimeout != null) { if (!ClusteringServiceUtil.setLock(strContext, distributedLockTimeout)) { return false; } } else if (!ClusteringServiceUtil.setLock(strContext)) { return false; } } // When processing a directory list is fetched initially. Therefore // there is still a chance of file processed by another process. // Need to check the source file before processing. try { String parentURI = fileObject.getParent().getName().getURI(); if (parentURI.contains("?")) { String suffix = parentURI.substring(parentURI.indexOf("?")); strContext += suffix; } FileObject sourceFile = fsManager.resolveFile(strContext); if (!sourceFile.exists()) { return false; } } catch (FileSystemException e) { return false; } VFSParamDTO vfsParamDTO = new VFSParamDTO(); vfsParamDTO.setAutoLockRelease(autoLockRelease); vfsParamDTO.setAutoLockReleaseSameNode(autoLockReleaseSameNode); vfsParamDTO.setAutoLockReleaseInterval(autoLockReleaseInterval); rtnValue = VFSUtils.acquireLock(fsManager, fileObject, vfsParamDTO, fso, true); } finally { if (distributedLock) { ClusteringServiceUtil.releaseLock(strContext); } } return rtnValue; }
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;// ww w . j av a 2 s .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.filesystem.connector.server.util.FileTransportUtils.java
/** * Acquire the file level locking.// w w w .j a va 2s . c om * * @param fsManager The file system manager instance * @param fileObject The file object to get the lock from * @param fsOpts The file system options to be used with the file system manager * @return Boolean value whether lock was successful */ public static synchronized boolean acquireLock(FileSystemManager fsManager, FileObject fileObject, FileSystemOptions fsOpts) { String strContext = fileObject.getName().getURI(); // When processing a directory list is fetched initially. Therefore // there is still a chance of file processed by another process. // Need to check the source file before processing. try { String parentURI = fileObject.getParent().getName().getURI(); if (parentURI.contains("?")) { String suffix = parentURI.substring(parentURI.indexOf("?")); strContext += suffix; } FileObject sourceFile = fsManager.resolveFile(strContext, fsOpts); if (!sourceFile.exists()) { return false; } } catch (FileSystemException e) { return false; } FileObject lockObject = null; try { // check whether there is an existing lock for this item, if so it is assumed // to be processed by an another listener (downloading) or a sender (uploading) // lock file is derived by attaching the ".lock" second extension to the file name String fullPath = fileObject.getName().getURI(); int pos = fullPath.indexOf("?"); if (pos != -1) { fullPath = fullPath.substring(0, pos); } lockObject = fsManager.resolveFile(fullPath + ".lock", fsOpts); if (lockObject.exists()) { log.debug("There seems to be an external lock, aborting the processing of the file " + maskURLPassword(fileObject.getName().getURI()) + ". This could possibly be due to some other party already " + "processing this file or the file is still being uploaded"); } else if (processing.contains(fullPath)) { log.debug(maskURLPassword(fileObject.getName().getURI()) + "is already being processed."); } else { //Check the original file existence before the lock file to handle concurrent access scenario FileObject originalFileObject = fsManager.resolveFile(fullPath, fsOpts); if (!originalFileObject.exists()) { return false; } processing.add(fullPath); return true; } } catch (FileSystemException fse) { log.error("Cannot get the lock for the file : " + maskURLPassword(fileObject.getName().getURI()) + " before processing", fse); if (lockObject != null) { try { fsManager.closeFileSystem(lockObject.getParent().getFileSystem()); } catch (FileSystemException e) { log.warn("Unable to close the lockObject parent file system"); } } } return false; }
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;/*from w w w .j av a 2 s . com*/ 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:org.wso2.carbon.transport.remotefilesystem.server.util.FileTransportUtils.java
/** * Acquire the file level locking./*from w w w . j a v a 2 s .com*/ * * @param fsManager The file system manager instance * @param fileObject The file object to get the lock from * @param fsOpts The file system options to be used with the file system manager * @return Boolean value whether lock was successful */ public static synchronized boolean acquireLock(FileSystemManager fsManager, FileObject fileObject, FileSystemOptions fsOpts) { String strContext = fileObject.getName().getURI(); // When processing a directory list is fetched initially. Therefore // there is still a chance of file processed by another process. // Need to check the source file before processing. try { String parentURI = fileObject.getParent().getName().getURI(); if (parentURI.contains("?")) { String suffix = parentURI.substring(parentURI.indexOf("?")); strContext += suffix; } FileObject sourceFile = fsManager.resolveFile(strContext, fsOpts); if (!sourceFile.exists()) { return false; } } catch (FileSystemException e) { return false; } FileObject lockObject = null; try { // check whether there is an existing lock for this item, if so it is assumed // to be processed by an another listener (downloading) or a sender (uploading) // lock file is derived by attaching the ".lock" second extension to the file name String fullPath = fileObject.getName().getURI(); int pos = fullPath.indexOf("?"); if (pos != -1) { fullPath = fullPath.substring(0, pos); } lockObject = fsManager.resolveFile(fullPath + ".lock", fsOpts); if (lockObject.exists()) { if (log.isDebugEnabled()) { log.debug("There seems to be an external lock, aborting the processing of the file " + maskURLPassword(fileObject.getName().getURI()) + ". This could possibly be due to some other party already " + "processing this file or the file is still being uploaded"); } } else if (processing.contains(fullPath)) { if (log.isDebugEnabled()) { log.debug(maskURLPassword(fileObject.getName().getURI()) + "is already being processed."); } } else { //Check the original file existence before the lock file to handle concurrent access scenario FileObject originalFileObject = fsManager.resolveFile(fullPath, fsOpts); if (!originalFileObject.exists()) { return false; } processing.add(fullPath); return true; } } catch (FileSystemException fse) { log.error("Cannot get the lock for the file : " + maskURLPassword(fileObject.getName().getURI()) + " before processing", fse); if (lockObject != null) { try { fsManager.closeFileSystem(lockObject.getParent().getFileSystem()); } catch (FileSystemException e) { log.warn("Unable to close the lockObject parent file system"); } } } return false; }