Example usage for org.apache.commons.vfs2 FileObject close

List of usage examples for org.apache.commons.vfs2 FileObject close

Introduction

In this page you can find the example usage for org.apache.commons.vfs2 FileObject close.

Prototype

@Override
void close() throws FileSystemException;

Source Link

Document

Closes this file, and its content.

Usage

From source file:fr.cls.atoll.motu.processor.iso19139.ServiceMetadata.java

/**
 * Marshall iso19139./*from  w w  w .j a va  2  s  . c  om*/
 * 
 * @param element the element
 * @param fileObject the file object
 * 
 * @throws MotuMarshallException the motu marshall exception
 * @throws FileSystemException the file system exception
 */
public void marshallIso19139(JAXBElement<?> element, FileObject fileObject)
        throws MotuMarshallException, FileSystemException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("marshallIso19139(JAXBElement<?>, FileObject) - entering");
    }

    marshallIso19139(element, fileObject.getContent().getOutputStream());
    fileObject.close();

    if (LOG.isDebugEnabled()) {
        LOG.debug("marshallIso19139(JAXBElement<?>, FileObject) - exiting");
    }
}

From source file:fr.cls.atoll.motu.processor.iso19139.ServiceMetadata.java

/**
 * Gets the service metadata schema as string.
 * //  ww  w .  j a  va2 s  . c  o  m
 * @param schemaPath the schema path
 * @param localIso19139SchemaPath the local iso19139 schema path
 * @param localIso19139RootSchemaRelPath the local iso19139 root schema rel path
 * 
 * @return the service metadata schema as string
 * 
 * @throws MotuException the motu exception
 * @throws FileSystemException the file system exception
 */
public String[] getServiceMetadataSchemaAsString(String schemaPath, String localIso19139SchemaPath,
        String localIso19139RootSchemaRelPath) throws MotuException, FileSystemException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("getServiceMetadataSchemaAsString(String, String, String) - entering");
    }

    List<String> stringList = new ArrayList<String>();
    String localIso19139RootSchemaPath = String.format("%s%s", localIso19139SchemaPath,
            localIso19139RootSchemaRelPath);

    FileObject dest = Organizer.resolveFile(localIso19139RootSchemaPath);
    boolean hasIso19139asLocalSchema = false;
    if (dest != null) {
        hasIso19139asLocalSchema = dest.exists();
    }

    if (hasIso19139asLocalSchema) {
        dest.close();

    } else {

        URL url = Organizer.findResource(schemaPath);

        FileObject jarFile = Organizer.resolveFile(url.toString());

        // List the children of the Jar file
        // FileObject[] children = null;
        // try {
        // children = jarFile.getChildren();
        // } catch (FileSystemException e) {
        // // TODO Auto-generated catch block
        // e.printStackTrace();
        // }
        // System.out.println("Children of " + jarFile.getName().getURI());
        // for (int i = 0; i < children.length; i++) {
        // System.out.println(children[i].getName().getBaseName());
        // }

        dest = Organizer.resolveFile(localIso19139SchemaPath);
        Organizer.copyFile(jarFile, dest);
    }

    stringList.add(localIso19139RootSchemaPath);
    String[] inS = new String[stringList.size()];
    inS = stringList.toArray(inS);

    if (LOG.isDebugEnabled()) {
        LOG.debug("getServiceMetadataSchemaAsString(String, String, String) - exiting");
    }
    return inS;
}

From source file:maspack.fileutil.FileCacher.java

public File cache(URIx uri, File cacheFile, FileTransferMonitor monitor) throws FileSystemException {

    // For atomic operation, first download to temporary directory
    File tmpCacheFile = new File(cacheFile.getAbsolutePath() + TMP_EXTENSION);
    URIx cacheURI = new URIx(cacheFile.getAbsoluteFile());
    URIx tmpCacheURI = new URIx(tmpCacheFile.getAbsoluteFile());
    FileObject localTempFile = manager.resolveFile(tmpCacheURI.toString(true));
    FileObject localCacheFile = manager.resolveFile(cacheURI.toString(true));

    FileObject remoteFile = null; // will resolve next

    // loop through authenticators until we either succeed or cancel
    boolean cancel = false;
    while (remoteFile == null && cancel == false) {
        remoteFile = resolveRemote(uri);
    }//from w  w  w  .  j  av  a 2 s.c om

    if (remoteFile == null || !remoteFile.exists()) {
        throw new FileSystemException("Cannot find remote file <" + uri.toString() + ">",
                new FileNotFoundException("<" + uri.toString() + ">"));
    }

    // monitor the file transfer progress
    if (monitor != null) {
        monitor.monitor(localTempFile, remoteFile, -1, cacheFile.getName());
        monitor.start();
        monitor.fireStartEvent(localTempFile);
    }

    // transfer content
    try {
        if (remoteFile.isFile()) {
            localTempFile.copyFrom(remoteFile, Selectors.SELECT_SELF);
        } else if (remoteFile.isFolder()) {
            // final FileObject fileSystem = manager.createFileSystem(remoteFile);
            localTempFile.copyFrom(remoteFile, new AllFileSelector());
            // fileSystem.close();
        }

        if (monitor != null) {
            monitor.fireCompleteEvent(localTempFile);
        }
    } catch (Exception e) {
        // try to delete local file
        localTempFile.delete();
        throw new RuntimeException(
                "Failed to complete transfer of " + remoteFile.getURL() + " to " + localTempFile.getURL(), e);
    } finally {
        // close files if we need to
        localTempFile.close();
        remoteFile.close();
        if (monitor != null) {
            monitor.release(localTempFile);
            monitor.stop();
        }

    }

    // now that the copy is complete, do a rename operation
    try {
        if (tmpCacheFile.isDirectory()) {
            SafeFileUtils.moveDirectory(tmpCacheFile, cacheFile);
        } else {
            SafeFileUtils.moveFile(tmpCacheFile, cacheFile);
        }
    } catch (Exception e) {
        localCacheFile.delete(); // delete if possible
        throw new RuntimeException("Failed to atomically move " + "to " + localCacheFile.getURL(), e);
    }

    return cacheFile;

}

From source file:fr.cls.atoll.motu.processor.wps.framework.WPSFactory.java

/**
 * Gets the wPS execute request schema as string.
 * //from w  w w  . ja  va  2 s.c o  m
 * @param schemaPath the schema path
 * @param localWPSSchemaPath the local wps schema path
 * @param localWPSRootSchemaRelPath the local wps root schema rel path
 * 
 * @return the wPS execute request schema as string
 * 
 * @throws MotuException the motu exception
 */
public static String[] getWPSExecuteRequestSchemaAsString(String schemaPath, String localWPSSchemaPath,
        String localWPSRootSchemaRelPath) throws MotuException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("getWPSExecuteRequestSchemaAsString(String, String, String) - entering");
    }

    String[] inS = null;
    try {
        List<String> stringList = new ArrayList<String>();
        String localWPSRootSchemaPath = String.format("%s%s", localWPSSchemaPath, localWPSRootSchemaRelPath);

        FileObject dest = Organizer.resolveFile(localWPSRootSchemaPath);
        boolean hasWPSasLocalSchema = false;
        if (dest != null) {
            hasWPSasLocalSchema = dest.exists();
        }

        if (hasWPSasLocalSchema) {
            dest.close();

        } else {

            URL url = null;
            if (!WPSUtils.isNullOrEmpty(schemaPath)) {
                url = Organizer.findResource(schemaPath);

            } else {
                url = Organizer.findResource(localWPSRootSchemaRelPath);
                String[] str = url.toString().split(localWPSRootSchemaRelPath);
                url = new URL(str[0]);
            }

            FileObject jarFile = Organizer.resolveFile(url.toString());

            // List the children of the Jar file
            // FileObject[] children = null;
            // try {
            // children = jarFile.getChildren();
            // } catch (FileSystemException e) {
            // // TODO Auto-generated catch block
            // e.printStackTrace();
            // }
            // System.out.println("Children of " + jarFile.getName().getURI());
            // for (int i = 0; i < children.length; i++) {
            // System.out.println(children[i].getName().getBaseName());
            // }

            dest = Organizer.resolveFile(localWPSSchemaPath);
            Organizer.copyFile(jarFile, dest);
        }

        stringList.add(localWPSRootSchemaPath);
        inS = new String[stringList.size()];
        inS = stringList.toArray(inS);

    } catch (Exception e) {
        LOG.error("getWPSExecuteRequestSchemaAsString(String, String, String)", e);

        throw new MotuException("ERROR in WPSFactory#getWPSExecuteRequestSchemaAsString", e);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("getWPSExecuteRequestSchemaAsString(String, String, String) - exiting");
    }
    return inS;
}

From source file:maspack.fileutil.FileCacher.java

public boolean copy(URIx from, URIx to, FileTransferMonitor monitor) throws FileSystemException {

    FileObject fromFile = null;
    FileObject toFile = null;//from   w w  w . j av  a2  s.  c  o  m

    // clear authenticators
    setAuthenticator(fsOpts, null);
    setIdentityFactory(fsOpts, null);

    // loop through authenticators until we either succeed or cancel
    boolean cancel = false;
    while (toFile == null && cancel == false) {
        toFile = resolveRemote(to);
    }

    cancel = false;
    while (fromFile == null && cancel == false) {
        fromFile = resolveRemote(from);
    }

    if (fromFile == null || !fromFile.exists()) {
        throw new FileSystemException("Cannot find source file <" + from.toString() + ">",
                new FileNotFoundException("<" + from.toString() + ">"));
    }

    if (toFile == null) {
        throw new FileSystemException("Cannot find destination <" + to.toString() + ">",
                new FileNotFoundException("<" + to.toString() + ">"));
    }

    // monitor the file transfer progress
    if (monitor != null) {
        monitor.monitor(fromFile, toFile, -1, fromFile.getName().getBaseName());
        monitor.start();
        monitor.fireStartEvent(toFile);
    }

    // transfer content
    try {
        if (fromFile.isFile()) {
            toFile.copyFrom(fromFile, Selectors.SELECT_SELF);
        } else if (fromFile.isFolder()) {
            // final FileObject fileSystem = manager.createFileSystem(remoteFile);
            toFile.copyFrom(fromFile, new AllFileSelector());
            // fileSystem.close();
        }

        if (monitor != null) {
            monitor.fireCompleteEvent(toFile);
        }
    } catch (Exception e) {
        throw new FileTransferException(
                "Failed to complete transfer of " + fromFile.getURL() + " to " + toFile.getURL(), e);
    } finally {
        // close files if we need to
        fromFile.close();
        toFile.close();
        if (monitor != null) {
            monitor.release(toFile);
            monitor.stop();
        }
    }

    return true;

}

From source file:com.yenlo.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
 *//*from   ww w  .j av a  2 s.  co  m*/
private void moveOrDeleteAfterProcessing(final PollTableEntry entry, FileObject fileObject) throws AxisFault {

    String moveToDirectoryURI = null;
    try {
        switch (entry.getLastPollState()) {
        case PollTableEntry.SUCCSESSFUL:
            if (entry.getActionAfterProcess() == PollTableEntry.MOVE) {
                moveToDirectoryURI = entry.getMoveAfterProcess();
            }
            break;

        case PollTableEntry.FAILED:
            if (entry.getActionAfterFailure() == PollTableEntry.MOVE) {
                moveToDirectoryURI = entry.getMoveAfterFailure();
            }
            break;

        default:
            return;
        }

        if (moveToDirectoryURI != null) {
            FileObject moveToDirectory = fsManager.resolveFile(moveToDirectoryURI);
            String prefix;
            if (entry.getMoveTimestampFormat() != null) {
                prefix = entry.getMoveTimestampFormat().format(new Date());
            } else {
                prefix = "";
            }
            FileObject dest = moveToDirectory.resolveFile(prefix + fileObject.getName().getBaseName());
            if (log.isDebugEnabled()) {
                log.debug("Moving to file :" + dest.getName().getURI());
            }
            try {
                fileObject.moveTo(dest);
            } catch (FileSystemException e) {
                handleException("Error moving file : " + fileObject + " to " + moveToDirectoryURI, e);
            }
        } else {
            try {
                if (log.isDebugEnabled()) {
                    log.debug("Deleting file :" + fileObject);
                }
                fileObject.close();
                if (!fileObject.delete()) {
                    String msg = "Cannot delete file : " + fileObject;
                    log.error(msg);
                    throw new AxisFault(msg);
                }
            } catch (FileSystemException e) {
                log.error("Error deleting file : " + fileObject, e);
            }
        }

    } catch (FileSystemException e) {
        handleException("Error resolving directory to move after processing : " + moveToDirectoryURI, e);
    }
}

From source file:com.seer.datacruncher.spring.ConnectionsFileDownloadController.java

private String getFileContent(long connId, ConnectionsEntity connectionEntity) {
    String content = "";
    DefaultFileSystemManager fsManager = null;
    FileObject fileObject = null;
    try {//from  www  . j a v a2 s  . c o m

        fsManager = (DefaultFileSystemManager) VFS.getManager();
        int serviceId = connectionEntity.getService();

        String hostName = connectionEntity.getHost();
        String port = connectionEntity.getPort();
        String userName = connectionEntity.getUserName();
        String password = connectionEntity.getPassword();
        String inputDirectory = connectionEntity.getDirectory();
        String fileName = connectionEntity.getFileName();

        log.info("Trying to Server polling at server [" + hostName + ":" + port + "] with user[" + userName
                + "].");

        String url = "";
        if (serviceId == Servers.SAMBA.getDbCode()) {
            if (!fsManager.hasProvider("smb")) {
                fsManager.addProvider("smb", new SmbFileProvider());
            }
            url = "smb://" + userName + ":" + password + "@" + hostName + ":" + port + "/" + inputDirectory
                    + "/" + fileName;
        } else if (serviceId == Servers.HTTP.getDbCode()) {
            if (!fsManager.hasProvider("http")) {
                fsManager.addProvider("http", new HttpFileProvider());
            }
            url = "http://" + hostName + ":" + port + "/" + inputDirectory + "/" + fileName;
        } else if (serviceId == Servers.FTP.getDbCode()) {
            if (!fsManager.hasProvider("ftp")) {
                fsManager.addProvider("ftp", new SmbFileProvider());
            }
            url = "ftp://" + userName + ":" + password + "@" + hostName + ":" + port + "/" + inputDirectory
                    + "/" + fileName;
        }

        fileObject = fsManager.resolveFile(url);

        if (fileObject == null || !fileObject.exists() || fileObject.getType().equals(FileType.IMAGINARY)) {
            return null;
        }

        BufferedReader fileReader = new BufferedReader(
                new InputStreamReader(fileObject.getContent().getInputStream()));
        StringBuilder sb = new StringBuilder();

        String line;
        while ((line = fileReader.readLine()) != null) {
            sb.append(line);
        }

        content = sb.toString();

    } catch (Exception ex) {

    } finally {
        try {
            if (fileObject != null) {
                fileObject.close();
            }
            if (fsManager != null) {
                fsManager.freeUnusedResources();
                fsManager.close();
                fsManager = null;
            }
        } catch (Exception ex) {

        } finally {
            fileObject = null;
            fsManager = null;
        }
    }
    return content;

}

From source file:com.seer.datacruncher.spring.IsSuccessfulConnectionController.java

private String checkServiceRunning(int service, String connID) {

    String success = "true";
    String url = "";
    ConnectionsEntity conn = connectionsDao.find(Long.parseLong(connID));
    DefaultFileSystemManager fsManager = null;
    FileObject fileObject = null;
    String userName = "";
    String password = "";
    String hostName = "";
    String port = "";
    String inputDirectory = "";
    String fileName = "";
    int connType = 1;

    if (conn != null) {
        userName = conn.getUserName();//ww w  .j  a va2  s  .  co  m
        password = conn.getPassword();
        hostName = conn.getHost();
        port = conn.getPort();
        inputDirectory = conn.getDirectory();
        fileName = conn.getFileName();
        connType = conn.getIdConnType();

    }

    if (connType == GenericType.DownloadTypeConn) {
        if (fileName == null || fileName.trim().length() == 0) {
            return "false";
        } else {
            fileName = "/" + fileName;
        }
    } else {
        fileName = "";
    }

    try {
        fsManager = (DefaultFileSystemManager) VFS.getManager();
        if (service == Servers.SAMBA.getDbCode()) {
            if (!fsManager.hasProvider("smb")) {
                fsManager.addProvider("smb", new SmbFileProvider());
            }
            url = "smb://" + userName + ":" + password + "@" + hostName + ":" + port + "/" + inputDirectory
                    + fileName;
        } else if (service == Servers.HTTP.getDbCode()) {
            if (!fsManager.hasProvider("http")) {
                fsManager.addProvider("http", new HttpFileProvider());
            }
            url = "http://" + hostName + ":" + port + "/" + inputDirectory + fileName;
        } else if (service == Servers.FTP.getDbCode()) {
            if (!fsManager.hasProvider("ftp")) {
                fsManager.addProvider("ftp", new FtpFileProvider());
            }
            url = "ftp://" + userName + ":" + password + "@" + hostName + ":" + port + "/" + inputDirectory
                    + fileName;
        }

        fileObject = fsManager.resolveFile(url);

        if (fileObject == null || !fileObject.exists()) {
            success = "false";
        }

        if (connType == GenericType.DownloadTypeConn) {
            if (fileObject.getType().equals(FileType.IMAGINARY)) {
                success = "false";
            }
            byte data[] = new byte[(int) fileObject.getContent().getSize()];
            fileObject.getContent().getInputStream().read(data);
        }

    } catch (Exception ex) {
        success = "false";
    } finally {
        try {
            if (fileObject != null) {
                fileObject.close();
            }
            if (fsManager != null) {
                fsManager.freeUnusedResources();
                fsManager.close();
                fsManager = null;
            }
        } catch (Exception ex) {

        } finally {
            fileObject = null;
            fsManager = null;
        }
    }

    return success;
}

From source file:com.app.server.WarDeployer.java

public Vector<URL> unpack(final FileObject unpackFileObject, final File outputDir,
        StandardFileSystemManager fileSystemManager, ConcurrentHashMap<String, String> jsps)
        throws IOException {
    outputDir.mkdirs();/*from  w  w  w  .j  a va2s.  co m*/
    URLClassLoader webClassLoader;
    Vector<URL> libraries = new Vector<URL>();
    final FileObject packFileObject = fileSystemManager.resolveFile(unpackFileObject.toString());
    try {
        FileObject outputDirFileObject = fileSystemManager.toFileObject(outputDir);
        outputDirFileObject.copyFrom(packFileObject, new AllFileSelector());
        FileObject[] jspFiles = outputDirFileObject.findFiles(new FileSelector() {

            public boolean includeFile(FileSelectInfo arg0) throws Exception {
                return arg0.getFile().getName().getBaseName().toLowerCase().endsWith(".jsp")
                        || arg0.getFile().getName().getBaseName().toLowerCase().endsWith(".jar");
            }

            public boolean traverseDescendents(FileSelectInfo arg0) throws Exception {
                // TODO Auto-generated method stub
                return true;
            }

        });
        String replaceString = "file:///" + outputDir.getAbsolutePath().replace("\\", "/");
        replaceString = replaceString.endsWith("/") ? replaceString : replaceString + "/";
        // System.out.println(replaceString);
        for (FileObject jsplibs : jspFiles) {
            // System.out.println(outputDir.getAbsolutePath());
            // System.out.println(jsp.getName().getFriendlyURI());
            if (jsplibs.getName().getBaseName().endsWith(".jar")) {
                libraries.add(new URL(jsplibs.getName().getFriendlyURI()));
            } else {
                String relJspName = jsplibs.getName().getFriendlyURI().replace(replaceString, "");
                jsps.put(relJspName, relJspName);
            }
            // System.out.println(relJspName);
        }
    } finally {
        packFileObject.close();
    }
    return libraries;
}

From source file:com.yenlo.synapse.transport.vfs.VFSTransportSender.java

/**
 * Send the given message over the VFS transport
 *
 * @param msgCtx the axis2 message context
 * @throws AxisFault on error// w  w w  . j a  v  a2  s.co  m
 */
public void sendMessage(MessageContext msgCtx, String targetAddress, OutTransportInfo outTransportInfo)
        throws AxisFault {

    if (waitForSynchronousResponse(msgCtx)) {
        throw new AxisFault("The VFS transport doesn't support synchronous responses. "
                + "Please use the appropriate (out only) message exchange pattern.");
    }

    VFSOutTransportInfo vfsOutInfo = null;

    if (targetAddress != null) {
        vfsOutInfo = new VFSOutTransportInfo(targetAddress, globalFileLockingFlag);
    } else if (outTransportInfo != null && outTransportInfo instanceof VFSOutTransportInfo) {
        vfsOutInfo = (VFSOutTransportInfo) outTransportInfo;
    }

    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());

                    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 (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);
                        if (!responseFile.exists()) {
                            responseFile.createFile();
                        }
                        populateResponseFile(responseFile, msgCtx, append, true);
                        VFSUtils.releaseLock(fsManager, responseFile);
                    } else {
                        if (!responseFile.exists()) {
                            responseFile.createFile();
                        }
                        populateResponseFile(responseFile, msgCtx, append, false);
                    }

                } 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);
                        populateResponseFile(replyFile, msgCtx, append, true);
                        VFSUtils.releaseLock(fsManager, replyFile);
                    } else {
                        populateResponseFile(replyFile, msgCtx, append, false);
                    }

                } else {
                    handleException("Unsupported reply file type : " + replyFile.getType() + " for file : "
                            + vfsOutInfo.getOutFileURI());
                }
            } else {
                // if file locking is not disabled acquire the lock before uploading the file
                if (vfsOutInfo.isFileLockingEnabled()) {
                    acquireLockForSending(replyFile, vfsOutInfo);
                    replyFile.createFile();
                    populateResponseFile(replyFile, msgCtx, append, true);
                    VFSUtils.releaseLock(fsManager, replyFile);
                } else {
                    replyFile.createFile();
                    populateResponseFile(replyFile, msgCtx, append, false);
                }
            }
        } catch (FileSystemException e) {
            handleException("Error resolving reply file : " + vfsOutInfo.getOutFileURI(), e);
        } finally {
            if (replyFile != null) {
                try {
                    replyFile.close();
                } catch (FileSystemException ignore) {
                }
            }
        }
    } else {
        handleException("Unable to determine out transport information to send message");
    }
}