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:erigo.filepump.FilePumpWorker.java

protected void writeToSFTP(String filename, int random_num) {

    String connectionStr = baseConnectionStr + "/" + filename;
    if (debug)//from  w  ww  .j  a v a  2s .co m
        System.err.println(connectionStr);

    try {
        // Create remote file object
        FileObject fo = manager.resolveFile(connectionStr, fileSystemOptions);
        FileContent fc = fo.getContent();
        OutputStream ostream = fc.getOutputStream();
        if (ostream == null) {
            throw new IOException("Error opening output stream to SFTP");
        }
        // Write content to file
        PrintWriter pw = new PrintWriter(ostream);
        pw.format("%06d\n", random_num);
        pw.close();
        // Cleanup
        if (fo != null)
            fo.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:de.innovationgate.wgpublisher.design.fs.AbstractDesignFile.java

protected DesignMetadata readMetaData() throws FileNotFoundException, IOException, InstantiationException,
        IllegalAccessException, WGDesignSyncException {

    FileObject metadataFile = getMetadataFile();

    // If not exists we return a default
    if (!metadataFile.exists()) {
        return createDefaultMetadata();
    }// w w  w. j  a  va  2s.c  o  m

    // If the file exists, but is empty, we put default metadata information into it
    if (metadataFile.getContent().getSize() == 0) {
        createMetadataFile(metadataFile);
    }

    String metaXML;
    Reader reader = createReader(metadataFile);
    try {
        metaXML = WGUtils.readString(reader);
    } finally {
        reader.close();
        metadataFile.close();
    }

    DesignMetadata metaData;
    if (metaXML.trim().equals("")) {
        createMetadataFile(metadataFile);
        metaData = createDefaultMetadata();
    } else {
        DesignMetadataInfo info = (DesignMetadataInfo) DesignSyncManager.getXstream().fromXML(metaXML);
        if (info instanceof TMLMetadataInfo) {
            metaData = new TMLMetadata();
        } else if (info instanceof FCMetadataInfo) {
            metaData = new FCMetadata();
        } else if (info instanceof ScriptMetadataInfo) {
            metaData = new ScriptMetadata();
        } else {
            metaData = new DesignMetadata();
        }
        metaData.setInfo(info);
    }

    return metaData;
}

From source file:maspack.fileutil.FileCacher.java

public InputStream getInputStream(URIx uri) throws FileSystemException {

    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 ww  w  .  j  ava2  s  .c  o m

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

    // open stream content
    InputStream stream = null;
    try {
        stream = remoteFile.getContent().getInputStream();
    } catch (Exception e) {
        remoteFile.close();
        throw new RuntimeException("Failed to open " + remoteFile.getURL(), e);
    } finally {
    }

    return stream;

}

From source file:fi.mystes.synapse.mediator.vfs.VfsFileTransferUtility.java

/**
 * Helper method for file listing./*from w  w  w  .j a va  2s  . c o m*/
 * 
 * @param sourceDirectoryPath
 *            Source directory path to list files from
 * @param filePatternRegex
 *            File pattern regex for file listing
 * @return Array containing file object listed by given file pattern regex
 * @throws FileSystemException
 *             If file listing fails
 */
private FileObject[] listFiles(String sourceDirectoryPath, String filePatternRegex) throws FileSystemException {
    FileObject fromDirectory = resolveFile(sourceDirectoryPath);
    log.debug("Source directory: " + fileObjectNameForDebug(fromDirectory));
    // check that both of the parameters are folders
    isFolder(fromDirectory);

    FileObject[] fileList;
    // if file pattern exists, get files from folder according to that
    if (filePatternRegex != null) {
        log.debug("Applying file pattern " + filePatternRegex);
        FileFilter ff = initFileFilter(filePatternRegex);
        fileList = fromDirectory.findFiles(new FileFilterSelector(ff));
    } else {
        // List all the files in that directory and copy each
        fileList = fromDirectory.getChildren();
    }

    fromDirectory.close();
    log.debug("Found " + fileList.length + " files in source directory");
    return fileList;
}

From source file:com.ewcms.publication.deploy.provider.DeployOperatorBase.java

@Override
public void copy(byte[] content, String targetPath) throws PublishException {

    String targetFullPath = targetFullPath(builder.getPath(), targetPath);
    logger.debug("Server file's path is {}", targetFullPath);

    FileObject root = null;//ww w. j a v a 2s.  c o  m
    FileObject target = null;
    try {
        root = getRootFileObject();
        //target = getTargetFileObject(root, targetFullPath);
        //-------------- Windows? ??----------------------
        targetPath = targetPath.replace("\\", "/").replace("//", "/");
        if (targetPath.indexOf("/") == 0) {
            targetPath = targetPath.substring(1);
        }
        target = getTargetFileObject(root, targetPath);
        //--------------------------------------------------------------
        FileContent fileContent = target.getContent();
        OutputStream stream = fileContent.getOutputStream();
        stream.write(content);
        stream.flush();

        stream.close();
        fileContent.close();
        target.close();
        root.close();
    } catch (FileSystemException e) {
        logger.error("Copy {} is error:{}", targetFullPath, e);
        throw new PublishException(e);
    } catch (IOException e) {
        logger.error("Copy {} is error:{}", targetFullPath, e);
        throw new PublishException(e);
    } finally {
        try {
            if (root != null) {
                root.close();
            }
            if (target != null) {
                target.close();
            }
        } catch (Exception e) {
            logger.error("vfs close is error:{}", e.toString());
        }
    }
}

From source file:maspack.fileutil.FileCacher.java

public OutputStream getOutputStream(URIx uri) throws FileSystemException {

    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 www .  ja v  a 2  s  .  co m*/

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

    // open stream content
    OutputStream stream = null;
    try {
        stream = remoteFile.getContent().getOutputStream();
    } catch (Exception e) {
        throw new RuntimeException("Failed to open " + remoteFile.getURL(), e);
    } finally {
        remoteFile.close();
    }

    return stream;

}

From source file:hadoopInstaller.installation.UploadConfiguration.java

private void modifyEnvShFile(Host host, FileObject configurationDirectory, String fileName)
        throws InstallationError {
    log.debug("HostInstallation.Upload.File.Start", //$NON-NLS-1$
            fileName, host.getHostname());
    FileObject configurationFile;
    try {//from w  ww.  j a  v a2s  .co  m
        configurationFile = configurationDirectory.resolveFile(fileName);
    } catch (FileSystemException e) {
        throw new InstallationError(e, "HostInstallation.CouldNotOpen", //$NON-NLS-1$
                fileName);
    }
    EnvShBuilder builder = new EnvShBuilder(configurationFile);
    String path = host.getInstallationDirectory();
    URI hadoop = URI.create(MessageFormat.format("file://{0}/{1}/", //$NON-NLS-1$
            path, InstallerConstants.HADOOP_DIRECTORY));
    URI java = URI.create(MessageFormat.format("file://{0}/{1}/", //$NON-NLS-1$
            path, InstallerConstants.JAVA_DIRECTORY));
    builder.setCustomConfig(getLocalFileContents(fileName));
    builder.setHadoopPrefix(hadoop.getPath());
    builder.setJavaHome(java.getPath());
    try {
        builder.build();
    } catch (IOException e) {
        throw new InstallationError(e, "HostInstallation.CouldNotWrite", //$NON-NLS-1$
                configurationFile.getName().getURI());
    }
    try {
        configurationFile.close();
    } catch (FileSystemException e) {
        log.warn("HostInstallation.CouldNotClose", //$NON-NLS-1$
                configurationFile.getName().getURI());
    }
    log.debug("HostInstallation.Upload.File.Success", //$NON-NLS-1$
            fileName, host.getHostname());
}

From source file:com.ewcms.publication.deploy.provider.DeployOperatorBase.java

@Override
public void copy(File sourceFile, String targetPath) throws PublishException {
    //TODO ??????
    if (!sourceFile.exists()) {
        logger.debug("Source file path's {} is not exists.", sourceFile.getPath());
        return;/*w  ww . j  a  v  a 2 s. c o m*/
    }

    String targetFullPath = targetFullPath(builder.getPath(), targetPath);
    logger.debug("Server file's path is {}", targetFullPath);
    logger.debug("Source file's path is {}  ", sourceFile.getPath());

    FileObject root = null;
    FileObject target = null;
    try {
        root = getRootFileObject();
        //target = getTargetFileObject(root, targetFullPath);
        //-------------- Windows? ??----------------------
        targetPath = targetPath.replace("\\", "/").replace("//", "/");
        if (targetPath.indexOf("/") == 0) {
            targetPath = targetPath.substring(1);
        }
        target = getTargetFileObject(root, targetPath);
        //--------------------------------------------------------------
        FileContent fileContent = target.getContent();

        OutputStream out = fileContent.getOutputStream();
        InputStream in = new FileInputStream(sourceFile);

        byte[] buffer = new byte[1024 * 8];
        int len = 0;
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
        out.flush();

        in.close();
        out.close();
        fileContent.close();
    } catch (FileSystemException e) {
        logger.error("Copy {} is error:{}", targetFullPath, e);
        throw new PublishException(e);
    } catch (IOException e) {
        logger.error("Copy {} is error:{}", targetFullPath, e);
        throw new PublishException(e);
    } finally {
        try {
            if (root != null) {
                root.close();
            }
            if (target != null) {
                target.close();
            }
        } catch (Exception e) {
            logger.error("vfs close is error:{}", e.toString());
        }
    }
}

From source file:hadoopInstaller.installation.DeployInstallationFiles.java

public void run() throws InstallationError {
    FileObject dependenciesFolder;
    log.debug("DeployInstallationFiles.DeployingStarted", //$NON-NLS-1$
            this.host.getHostname());
    try {// w ww.  j a  v a2  s .  c o  m
        dependenciesFolder = this.installer.getLocalDirectory()
                .resolveFile(InstallerConstants.TGZ_BUNDLES_FOLDER);
    } catch (FileSystemException e) {
        throw new InstallationError(e, "DeployInstallationFiles.CouldNotOpenFile", //$NON-NLS-1$
                InstallerConstants.TGZ_BUNDLES_FOLDER);
    }
    if (this.installer.getConfig().deleteOldFiles()) {
        try {
            /*
             * Current version of commons-vfs can not delete symlinks to a
             * folder because it thinks of them as a folder and then fails
             * to delete them.
             * 
             * Workaround, connect and do rm -rf
             */
            // this.remoteDirectory.delete(new AllFileSelector());
            SshCommandExecutor command = new SshCommandExecutor(this.session);
            command.execute(MessageFormat.format("rm -rf {0}/*", //$NON-NLS-1$
                    this.remoteDirectory.getName().getPath()));
        } catch (ExecutionError e) {
            throw new InstallationError(e, "DeployInstallationFiles.CouldNotDeleteOldFiles", //$NON-NLS-1$
                    this.remoteDirectory.getName().getURI());
        }
        log.info("DeployInstallationFiles.DeletingOldFiles", //$NON-NLS-1$
                this.remoteDirectory.getName().getURI());
    }
    uploadFiles(dependenciesFolder);
    decompressFiles();
    try {
        dependenciesFolder.close();
    } catch (FileSystemException e) {
        log.warn("DeployInstallationFiles.CouldNotCloseFile", //$NON-NLS-1$
                dependenciesFolder.getName().getURI());
    }
    log.debug("DeployInstallationFiles.DeployingFinished", //$NON-NLS-1$
            this.host.getHostname());
}

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

public CopyOnWriteArrayList<String> unpack(final FileObject unpackFileObject, final File outputDir,
        StandardFileSystemManager fileSystemManager) throws IOException {
    outputDir.mkdirs();//from w  w  w .  jav a  2  s  . co m
    URLClassLoader webClassLoader;
    CopyOnWriteArrayList<String> classPath = new CopyOnWriteArrayList<String>();
    final FileObject packFileObject = fileSystemManager
            .resolveFile("jar:" + unpackFileObject.toString() + "!/");
    try {
        FileObject outputDirFileObject = fileSystemManager.toFileObject(outputDir);
        outputDirFileObject.copyFrom(packFileObject, new AllFileSelector());
        FileObject[] libs = outputDirFileObject.findFiles(new FileSelector() {

            public boolean includeFile(FileSelectInfo arg0) throws Exception {
                return 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 lib : libs) {
            // System.out.println(outputDir.getAbsolutePath());
            // System.out.println(jsp.getName().getFriendlyURI());
            classPath.add(lib.getName().getFriendlyURI());
            // System.out.println(relJspName);
        }
    } finally {
        packFileObject.close();
    }
    return classPath;
}