List of usage examples for org.apache.commons.vfs2 FileObject close
@Override void close() throws FileSystemException;
From source file:org.apache.synapse.transport.vfs.VFSTransportListener.java
/** * Take specified action to either move or delete the processed file, depending on the outcome * @param entry the PollTableEntry for the file that has been processed * @param fileObject the FileObject representing the file to be moved or deleted */// w ww. j ava 2 s.c o m private void moveOrDeleteAfterProcessing(final PollTableEntry entry, FileObject fileObject, FileSystemOptions fso) throws AxisFault { String moveToDirectoryURI = null; try { switch (entry.getLastPollState()) { case PollTableEntry.SUCCSESSFUL: if (entry.getActionAfterProcess() == PollTableEntry.MOVE) { moveToDirectoryURI = entry.getMoveAfterProcess(); //Postfix the date given timestamp format String strSubfoldertimestamp = entry.getSubfolderTimestamp(); if (strSubfoldertimestamp != null) { try { SimpleDateFormat sdf = new SimpleDateFormat(strSubfoldertimestamp); String strDateformat = sdf.format(new Date()); int iIndex = moveToDirectoryURI.indexOf("?"); if (iIndex > -1) { moveToDirectoryURI = moveToDirectoryURI.substring(0, iIndex) + strDateformat + moveToDirectoryURI.substring(iIndex, moveToDirectoryURI.length()); } else { moveToDirectoryURI += strDateformat; } } catch (Exception e) { log.warn("Error generating subfolder name with date", e); } } } break; case PollTableEntry.FAILED: if (entry.getActionAfterFailure() == PollTableEntry.MOVE) { moveToDirectoryURI = entry.getMoveAfterFailure(); } break; default: return; } if (moveToDirectoryURI != null) { FileObject moveToDirectory = fsManager.resolveFile(moveToDirectoryURI, fso); String prefix; if (entry.getMoveTimestampFormat() != null) { prefix = entry.getMoveTimestampFormat().format(new Date()); } else { prefix = ""; } //Forcefully create the folder(s) if does not exists if (entry.isForceCreateFolder() && !moveToDirectory.exists()) { moveToDirectory.createFolder(); } FileObject dest = moveToDirectory.resolveFile(prefix + fileObject.getName().getBaseName()); if (log.isDebugEnabled()) { log.debug("Moving to file :" + VFSUtils.maskURLPassword(dest.getName().getURI())); } try { fileObject.moveTo(dest); } catch (FileSystemException e) { handleException("Error moving file : " + VFSUtils.maskURLPassword(fileObject.toString()) + " to " + VFSUtils.maskURLPassword(moveToDirectoryURI), e); } finally { try { fileObject.close(); } catch (FileSystemException ignore) { } } } else { try { if (log.isDebugEnabled()) { log.debug("Deleting file :" + VFSUtils.maskURLPassword(fileObject.toString())); } fileObject.close(); if (!fileObject.delete()) { String msg = "Cannot delete file : " + VFSUtils.maskURLPassword(fileObject.toString()); log.error(msg); throw new AxisFault(msg); } } catch (FileSystemException e) { log.error("Error deleting file : " + VFSUtils.maskURLPassword(fileObject.toString()), e); } } } catch (FileSystemException e) { handleException("Error resolving directory to move after processing : " + VFSUtils.maskURLPassword(moveToDirectoryURI), e); } }
From source file:org.apache.synapse.transport.vfs.VFSTransportListener.java
/** * Process a single file through Axis2// w w w .ja v a 2s .c o m * @param entry the PollTableEntry for the file (or its parent directory or archive) * @param file the file that contains the actual message pumped into Axis2 * @throws AxisFault on error */ private void processFile(PollTableEntry entry, FileObject file) throws AxisFault { try { FileContent content = file.getContent(); String fileName = file.getName().getBaseName(); String filePath = file.getName().getPath(); String fileURI = file.getName().getURI(); metrics.incrementBytesReceived(content.getSize()); Map<String, Object> transportHeaders = new HashMap<String, Object>(); transportHeaders.put(VFSConstants.FILE_PATH, filePath); transportHeaders.put(VFSConstants.FILE_NAME, fileName); transportHeaders.put(VFSConstants.FILE_URI, fileURI); try { transportHeaders.put(VFSConstants.FILE_LENGTH, content.getSize()); transportHeaders.put(VFSConstants.LAST_MODIFIED, content.getLastModifiedTime()); } catch (FileSystemException ignore) { } MessageContext msgContext = entry.createMessageContext(); String contentType = entry.getContentType(); if (BaseUtils.isBlank(contentType)) { if (file.getName().getExtension().toLowerCase().endsWith(".xml")) { contentType = "text/xml"; } else if (file.getName().getExtension().toLowerCase().endsWith(".txt")) { contentType = "text/plain"; } } else { // Extract the charset encoding from the configured content type and // set the CHARACTER_SET_ENCODING property as e.g. SOAPBuilder relies on this. String charSetEnc = null; try { if (contentType != null) { charSetEnc = new ContentType(contentType).getParameter("charset"); } } catch (ParseException ex) { // ignore } msgContext.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc); } // if the content type was not found, but the service defined it.. use it if (contentType == null) { if (entry.getContentType() != null) { contentType = entry.getContentType(); } else if (VFSUtils.getProperty(content, BaseConstants.CONTENT_TYPE) != null) { contentType = VFSUtils.getProperty(content, BaseConstants.CONTENT_TYPE); } } // does the service specify a default reply file URI ? String replyFileURI = entry.getReplyFileURI(); if (replyFileURI != null) { msgContext.setProperty(Constants.OUT_TRANSPORT_INFO, new VFSOutTransportInfo(replyFileURI, entry.isFileLockingEnabled())); } // Determine the message builder to use Builder builder; if (contentType == null) { log.debug("No content type specified. Using SOAP builder."); builder = new SOAPBuilder(); } else { int index = contentType.indexOf(';'); String type = index > 0 ? contentType.substring(0, index) : contentType; builder = BuilderUtil.getBuilderFromSelector(type, msgContext); if (builder == null) { if (log.isDebugEnabled()) { log.debug("No message builder found for type '" + type + "'. Falling back to SOAP."); } builder = new SOAPBuilder(); } } // set the message payload to the message context InputStream in; ManagedDataSource dataSource; if (builder instanceof DataSourceMessageBuilder && entry.isStreaming()) { in = null; dataSource = ManagedDataSourceFactory.create(new FileObjectDataSource(file, contentType)); } else { in = new AutoCloseInputStream(content.getInputStream()); dataSource = null; } try { OMElement documentElement; if (in != null) { documentElement = builder.processDocument(in, contentType, msgContext); } else { documentElement = ((DataSourceMessageBuilder) builder).processDocument(dataSource, contentType, msgContext); } msgContext.setEnvelope(TransportUtils.createSOAPEnvelope(documentElement)); handleIncomingMessage(msgContext, transportHeaders, null, //* SOAP Action - not applicable *// contentType); } finally { if (dataSource != null) { dataSource.destroy(); } } if (log.isDebugEnabled()) { log.debug("Processed file : " + VFSUtils.maskURLPassword(file.toString()) + " of Content-type : " + contentType); } } catch (FileSystemException e) { handleException( "Error reading file content or attributes : " + VFSUtils.maskURLPassword(file.toString()), e); } finally { try { if (file != null) { file.close(); } } catch (FileSystemException warn) { // ignore the warning, since we handed over the stream close job to // AutocloseInputstream.. } } }
From source file:org.apache.synapse.transport.vfs.VFSTransportSender.java
private void writeFile(MessageContext msgCtx, VFSOutTransportInfo vfsOutInfo) throws AxisFault { FileSystemOptions fso = null;//from w w w .j av a 2 s . com try { fso = VFSUtils.attachFileSystemOptions(vfsOutInfo.getOutFileSystemOptionsMap(), fsManager); } catch (Exception e) { log.error("Error while attaching VFS file system properties. " + e.getMessage()); } if (vfsOutInfo != null) { FileObject replyFile = null; try { boolean wasError = true; int retryCount = 0; int maxRetryCount = vfsOutInfo.getMaxRetryCount(); long reconnectionTimeout = vfsOutInfo.getReconnectTimeout(); boolean append = vfsOutInfo.isAppend(); while (wasError) { try { retryCount++; replyFile = fsManager.resolveFile(vfsOutInfo.getOutFileURI(), fso); if (replyFile == null) { log.error("replyFile is null"); throw new FileSystemException("replyFile is null"); } wasError = false; } catch (FileSystemException e) { log.error("cannot resolve replyFile", e); if (maxRetryCount <= retryCount) { handleException("cannot resolve replyFile repeatedly: " + e.getMessage(), e); } } if (wasError) { try { Thread.sleep(reconnectionTimeout); } catch (InterruptedException e2) { e2.printStackTrace(); } } } //If the reply folder does not exists create the folder structure if (vfsOutInfo.isForceCreateFolder()) { String strPath = vfsOutInfo.getOutFileURI(); int iIndex = strPath.indexOf("?"); if (iIndex > -1) { strPath = strPath.substring(0, iIndex); } //Need to add a slash otherwise vfs consider this as a file if (!strPath.endsWith("/") || !strPath.endsWith("\\")) { strPath += "/"; } FileObject replyFolder = fsManager.resolveFile(strPath, fso); if (!replyFolder.exists()) { replyFile.createFolder(); } } if (replyFile.exists()) { if (replyFile.getType() == FileType.FOLDER) { // we need to write a file containing the message to this folder FileObject responseFile = fsManager.resolveFile(replyFile, VFSUtils.getFileName(msgCtx, vfsOutInfo)); // if file locking is not disabled acquire the lock // before uploading the file if (vfsOutInfo.isFileLockingEnabled()) { acquireLockForSending(responseFile, vfsOutInfo, fso); if (!responseFile.exists()) { responseFile.createFile(); } populateResponseFile(responseFile, msgCtx, append, true, fso); VFSUtils.releaseLock(fsManager, responseFile, fso); } else { if (!responseFile.exists()) { responseFile.createFile(); } populateResponseFile(responseFile, msgCtx, append, false, fso); } } else if (replyFile.getType() == FileType.FILE) { // if file locking is not disabled acquire the lock // before uploading the file if (vfsOutInfo.isFileLockingEnabled()) { acquireLockForSending(replyFile, vfsOutInfo, fso); populateResponseFile(replyFile, msgCtx, append, true, fso); VFSUtils.releaseLock(fsManager, replyFile, fso); } else { populateResponseFile(replyFile, msgCtx, append, false, fso); } } else { handleException("Unsupported reply file type : " + replyFile.getType() + " for file : " + VFSUtils.maskURLPassword(vfsOutInfo.getOutFileURI())); } } else { // if file locking is not disabled acquire the lock before uploading the file if (vfsOutInfo.isFileLockingEnabled()) { acquireLockForSending(replyFile, vfsOutInfo, fso); replyFile.createFile(); populateResponseFile(replyFile, msgCtx, append, true, fso); VFSUtils.releaseLock(fsManager, replyFile, fso); } else { replyFile.createFile(); populateResponseFile(replyFile, msgCtx, append, false, fso); } } } catch (FileSystemException e) { handleException( "Error resolving reply file : " + VFSUtils.maskURLPassword(vfsOutInfo.getOutFileURI()), e); } finally { if (replyFile != null) { try {/* if (fsManager != null && replyFile.getParent() != null && replyFile.getParent().getFileSystem() != null) { fsManager.closeFileSystem(replyFile.getParent().getFileSystem()); }*/ replyFile.close(); } catch (FileSystemException ignore) { } } } } else { handleException("Unable to determine out transport information to send message"); } }
From source file:org.efaps.db.store.VFSStoreResource.java
/** * The method writes the context (from the input stream) to a temporary file * (same file URL, but with extension {@link #EXTENSION_TEMP}). * * @param _in input stream defined the content of the file * @param _size length of the content (or negative meaning that the length * is not known; then the content gets the length of readable * bytes from the input stream) * @param _fileName name of the file/*from ww w .j a v a 2s. com*/ * @return size of the created temporary file object * @throws EFapsException on error */ @Override public long write(final InputStream _in, final long _size, final String _fileName) throws EFapsException { try { long size = _size; final FileObject tmpFile = this.manager.resolveFile(this.manager.getBaseFile(), this.storeFileName + VFSStoreResource.EXTENSION_TEMP); if (!tmpFile.exists()) { tmpFile.createFile(); } final FileContent content = tmpFile.getContent(); OutputStream out = content.getOutputStream(false); if (getCompress().equals(Compress.GZIP)) { out = new GZIPOutputStream(out); } else if (getCompress().equals(Compress.ZIP)) { out = new ZipOutputStream(out); } // if size is unkown! if (_size < 0) { int length = 1; size = 0; while (length > 0) { length = _in.read(this.buffer); if (length > 0) { out.write(this.buffer, 0, length); size += length; } } } else { Long length = _size; while (length > 0) { final int readLength = length.intValue() < this.buffer.length ? length.intValue() : this.buffer.length; _in.read(this.buffer, 0, readLength); out.write(this.buffer, 0, readLength); length -= readLength; } } if (getCompress().equals(Compress.GZIP) || getCompress().equals(Compress.ZIP)) { out.close(); } tmpFile.close(); setFileInfo(_fileName, size); return size; } catch (final IOException e) { VFSStoreResource.LOG.error("write of content failed", e); throw new EFapsException(VFSStoreResource.class, "write.IOException", e); } }
From source file:org.efaps.db.store.VFSStoreResource.java
/** * The method is called from the transaction manager if the complete * transaction is completed.<br/>//from w ww .ja va 2 s . co m * A file in the virtual file system is committed with the algorithms: * <ol> * <li>any existing backup fill will be moved to an older backup file. The * maximum number of backups can be defined by setting the property * {@link #PROPERTY_NUMBER_BACKUP}. Default is one. To disable the * property must be set to 0.</li> * <li>the current file is moved to the backup file (or deleted if property * {@link #PROPERTY_NUMBER_BACKUP} is 0)</li> * <li>the new file is moved to the original name</li> * </ol> * * @param _xid global transaction identifier (not used, because each * file with the file id gets a new VFS store resource * instance) * @param _onePhase <i>true</i> if it is a one phase commitment transaction * (not used) * @throws XAException if any exception occurs (catch on * {@link java.lang.Throwable}) */ @Override public void commit(final Xid _xid, final boolean _onePhase) throws XAException { if (VFSStoreResource.LOG.isDebugEnabled()) { VFSStoreResource.LOG.debug("transaction commit"); } if (getStoreEvent() == VFSStoreResource.StoreEvent.WRITE) { try { final FileObject tmpFile = this.manager.resolveFile(this.manager.getBaseFile(), this.storeFileName + VFSStoreResource.EXTENSION_TEMP); final FileObject currentFile = this.manager.resolveFile(this.manager.getBaseFile(), this.storeFileName + VFSStoreResource.EXTENSION_NORMAL); final FileObject bakFile = this.manager.resolveFile(this.manager.getBaseFile(), this.storeFileName + VFSStoreResource.EXTENSION_BACKUP); if (bakFile.exists() && (this.numberBackup > 0)) { backup(bakFile, 0); } if (currentFile.exists()) { if (this.numberBackup > 0) { currentFile.moveTo(bakFile); } else { currentFile.delete(); } } tmpFile.moveTo(currentFile); tmpFile.close(); currentFile.close(); bakFile.close(); } catch (final FileSystemException e) { VFSStoreResource.LOG .error("transaction commit fails for " + _xid + " (one phase = " + _onePhase + ")", e); final XAException xa = new XAException(XAException.XA_RBCOMMFAIL); xa.initCause(e); throw xa; } } else if (getStoreEvent() == VFSStoreResource.StoreEvent.DELETE) { try { final FileObject curFile = this.manager.resolveFile(this.manager.getBaseFile(), this.storeFileName + VFSStoreResource.EXTENSION_NORMAL); final FileObject bakFile = this.manager.resolveFile(this.manager.getBaseFile(), this.storeFileName + VFSStoreResource.EXTENSION_BACKUP); if (bakFile.exists()) { bakFile.delete(); } if (curFile.exists()) { curFile.moveTo(bakFile); } bakFile.close(); curFile.close(); } catch (final FileSystemException e) { VFSStoreResource.LOG .error("transaction commit fails for " + _xid + " (one phase = " + _onePhase + ")", e); final XAException xa = new XAException(XAException.XA_RBCOMMFAIL); xa.initCause(e); throw xa; } } }
From source file:org.geoserver.backuprestore.utils.BackupUtils.java
/** * Extracts the archive file {@code archiveFile} to {@code targetFolder}; both shall previously exist. * * @param archiveFile//from w ww . ja v a 2s.c om * @param targetFolder * @throws IOException */ public static void extractTo(Resource archiveFile, Resource targetFolder) throws IOException { FileSystemManager manager = VFS.getManager(); String sourceURI = resolveArchiveURI(archiveFile); FileObject source = manager.resolveFile(sourceURI); if (manager.canCreateFileSystem(source)) { source = manager.createFileSystem(source); } FileObject target = manager .createVirtualFileSystem(manager.resolveFile(targetFolder.dir().getAbsolutePath())); FileSelector selector = new AllFileSelector() { @Override public boolean includeFile(FileSelectInfo fileInfo) { LOGGER.fine("Uncompressing " + fileInfo.getFile().getName().getFriendlyURI()); return true; } }; target.copyFrom(source, selector); source.close(); target.close(); manager.closeFileSystem(source.getFileSystem()); }
From source file:org.geoserver.backuprestore.utils.BackupUtils.java
/** * Compress {@code sourceFolder} to the archive file {@code archiveFile}; both shall previously exist. * // ww w. j a v a 2 s. c om * @param sourceFolder * @param archiveFile * @throws IOException */ public static void compressTo(Resource sourceFolder, Resource archiveFile) throws IOException { // See https://commons.apache.org/proper/commons-vfs/filesystems.html // for the supported filesystems FileSystemManager manager = VFS.getManager(); FileObject sourceDir = manager .createVirtualFileSystem(manager.resolveFile(sourceFolder.dir().getAbsolutePath())); try { if ("zip".equalsIgnoreCase(FileUtils.getExtension(archiveFile.path()))) { // apache VFS does not support ZIP as writable FileSystem OutputStream fos = archiveFile.out(); // Create access to zip. ZipOutputStream zos = new ZipOutputStream(fos); // add entry/-ies. for (FileObject sourceFile : sourceDir.getChildren()) { writeEntry(zos, sourceFile, null); } // Close streams zos.flush(); zos.close(); fos.close(); } else { // Create access to archive. FileObject zipFile = manager.resolveFile(resolveArchiveURI(archiveFile)); zipFile.createFile(); ZipOutputStream zos = new ZipOutputStream(zipFile.getContent().getOutputStream()); // add entry/-ies. for (FileObject sourceFile : sourceDir.getChildren()) { writeEntry(zos, sourceFile, null); } // Close streams zos.flush(); zos.close(); zipFile.close(); manager.closeFileSystem(zipFile.getFileSystem()); } } finally { manager.closeFileSystem(sourceDir.getFileSystem()); } }
From source file:org.geoserver.importer.RemoteData.java
public ImportData resolve(Importer importer) throws IOException { // prepare the target Directory target = Directory.createNew(importer.getUploadRoot()); FileSystemManager manager = null;//from ww w. j ava 2s . c o m FileObject fo = null; try { manager = VFS.getManager(); if (username != null) { StaticUserAuthenticator auth = new StaticUserAuthenticator(domain, username, password); FileSystemOptions opts = new FileSystemOptions(); DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth); fo = manager.resolveFile(location, opts); } else { fo = manager.resolveFile(location); } target.accept(fo); } finally { if (fo != null) { FileSystem fs = fo.getFileSystem(); fo.close(); manager.closeFileSystem(fs); } } return target; }
From source file:org.horiam.ResourceManager.model.TestObjectToXmlToObject.java
@AfterClass public static void stop() throws FileSystemException { for (FileObject file : xmls.values()) file.close(); }
From source file:org.jahia.modules.external.vfs.VFSDataSource.java
@Override public void move(String oldPath, String newPath) throws RepositoryException { if (oldPath.equals(newPath)) { return;// w w w . ja v a 2 s . c o m } try { FileObject origin = getFile(oldPath); if (origin.isContentOpen()) { origin.close(); } FileObject destination = getFile(newPath); if (destination.exists() && destination.isContentOpen()) { destination.close(); } origin.moveTo(destination); } catch (FileSystemException e) { throw new RepositoryException(oldPath, e); } }