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:com.ewcms.publication.deploy.provider.FtpDeployOperatorTest.java

@Test
public void testGetTargtRoot() throws Exception {
    String hostname = "14.136.146.36";
    String username = "itkaizen.com";
    String password = "kaizenidc";
    String path = "/wwwroot";

    DeployOperatorable operator = new FtpDeployOperator.Builder(hostname, path).setUsername(username)
            .setPassword(password).build();

    FtpDeployOperator ftpOperator = (FtpDeployOperator) operator;

    FileObject target = ftpOperator.getRootFileObject();
    Assert.notNull(target);//from   w w w  .ja  v  a 2  s . c  om
    target.close();
}

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

public static String[] getServiceMetadataSchemaAsString(String schemaPath) throws MotuException {

    List<String> stringList = new ArrayList<String>();
    String localIso19139SchemaPath = "file:///c:/tempVFS/testISO";
    String localIso19139RootSchemaRelPath = "/srv/srv.xsd";
    String localIso19139RootSchemaPath = String.format("%s%s", localIso19139SchemaPath,
            localIso19139RootSchemaRelPath);

    FileObject dest = Organizer.resolveFile(localIso19139RootSchemaPath);
    boolean hasIso19139asLocalSchema = false;
    try {//  www.  ja  va2  s  .  c o m
        if (dest != null) {
            hasIso19139asLocalSchema = dest.exists();
        }
    } catch (FileSystemException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    if (hasIso19139asLocalSchema) {
        try {
            dest.close();
        } catch (FileSystemException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    } else {

        // URL url = Organizer.findResource("schema/iso/srv/srv.xsd");
        // URL url =
        // Organizer.findResource("J:/dev/iso/19139/20070417/schema/src/main/resources/iso/19139/20070417/srv/srv.xsd");
        // URL url = Organizer.findResource("iso/19139/20070417/srv/srv.xsd");
        URL url = Organizer.findResource(schemaPath);
        System.out.println(url);

        // String[] arr = url.toString().split("!");

        // FileObject jarFile = Organizer.resolveFile(arr[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(localIso19139SchemaPath);
        Organizer.deleteDirectory(dest);

        Organizer.copyFile(jarFile, dest);
    }

    // stringList.add(url.toString());
    // stringList.add("J:/dev/iso/19139/20070417/schema/src/main/resources/iso/19139/20070417/srv/srv.xsd");
    stringList.add(localIso19139RootSchemaPath);
    // stringList.add("C:/Documents and Settings/dearith/Mes documents/Atoll/SchemaIso/srv/serviceMetadata.xsd");
    String[] inS = new String[stringList.size()];
    inS = stringList.toArray(inS);
    return inS;
}

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

/**
 * Acquires a file item lock before processing the item, guaranteing that the file is not
 * processed while it is being uploaded and/or the item is not processed by two listeners
 *
 * @param fsManager used to resolve the processing file
 * @param fo representing the processing file item
 * @return boolean true if the lock has been acquired or false if not
 *///  ww  w. j a va  2  s.co  m
public synchronized static boolean acquireLock(FileSystemManager fsManager, FileObject fo) {

    // generate a random lock value to ensure that there are no two parties
    // processing the same file
    Random random = new Random();
    byte[] lockValue = String.valueOf(random.nextLong()).getBytes();

    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 = fo.getName().getURI();
        int pos = fullPath.indexOf("?");
        if (pos != -1) {
            fullPath = fullPath.substring(0, pos);
        }
        FileObject lockObject = fsManager.resolveFile(fullPath + ".lock");
        if (lockObject.exists()) {
            log.debug("There seems to be an external lock, aborting the processing of the file " + fo.getName()
                    + ". This could possibly be due to some other party already "
                    + "processing this file or the file is still being uploaded");
        } else {

            // write a lock file before starting of the processing, to ensure that the
            // item is not processed by any other parties
            lockObject.createFile();
            OutputStream stream = lockObject.getContent().getOutputStream();
            try {
                stream.write(lockValue);
                stream.flush();
                stream.close();
            } catch (IOException e) {
                lockObject.delete();
                log.error("Couldn't create the lock file before processing the file " + fullPath, e);
                return false;
            } finally {
                lockObject.close();
            }

            // check whether the lock is in place and is it me who holds the lock. This is
            // required because it is possible to write the lock file simultaneously by
            // two processing parties. It checks whether the lock file content is the same
            // as the written random lock value.
            // NOTE: this may not be optimal but is sub optimal
            FileObject verifyingLockObject = fsManager.resolveFile(fullPath + ".lock");
            if (verifyingLockObject.exists() && verifyLock(lockValue, verifyingLockObject)) {
                return true;
            }
        }
    } catch (FileSystemException fse) {
        log.error("Cannot get the lock for the file : " + maskURLPassword(fo.getName().getURI())
                + " before processing");
    }
    return false;
}

From source file:mondrian.spi.impl.ApacheVfs2VirtualFileHandler.java

public InputStream readVirtualFile(String url) throws FileSystemException {
    // Treat catalogUrl as an Apache VFS (Virtual File System) URL.
    // VFS handles all of the usual protocols (http:, file:)
    // and then some.
    FileSystemManager fsManager = VFS.getManager();
    if (fsManager == null) {
        throw Util.newError("Cannot get virtual file system manager");
    }/*w  w  w.  j  ava2s . c om*/

    File userDir = new File("").getAbsoluteFile();
    FileObject file = fsManager.resolveFile(userDir, url);
    FileContent fileContent = null;
    try {
        if (!file.isReadable()) {
            throw Util.newError("Virtual file is not readable: " + url);
        }

        fileContent = file.getContent();
    } finally {
        file.close();
    }

    if (fileContent == null) {
        throw Util.newError("Cannot get virtual file content: " + url);
    }

    return fileContent.getInputStream();
}

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

@Override
public void delete(String path) throws PublishException {
    String fullPath = targetFullPath(builder.getPath(), path);
    logger.debug("Delete file's path is {}", path);

    try {// w w  w. j  av a  2s .  com
        FileObject root = getRootFileObject();
        path = path.replace("\\", "/").replace("//", "/");
        if (path.indexOf("/") == 0) {
            path = path.substring(1);
        }
        FileObject target = getTargetFileObject(root, path);

        if (target.exists()) {
            target.delete();
        }
        target.close();
        root.close();
    } catch (FileSystemException e) {
        logger.error("Delete {} file delete is error:{}", fullPath, e);
        throw new PublishException(e);
    }
}

From source file:com.streamsets.pipeline.stage.origin.remote.FTPRemoteDownloadSourceDelegate.java

@Override
String archive(String fromPath) throws IOException {
    if (archiveURI == null) {
        throw new IOException("No archive directory defined - cannot archive");
    }/*from   w  w  w  .  j av a2 s  .c  om*/

    String toPath = archiveURI.toString() + (fromPath.startsWith("/") ? fromPath.substring(1) : fromPath);

    FileObject toFile = VFS.getManager().resolveFile(toPath, archiveOptions);
    toFile.refresh();
    // Create the toPath's parent dir(s) if they don't exist
    toFile.getParent().createFolder();
    getChild(fromPath).moveTo(toFile);
    toFile.close();
    return toPath;
}

From source file:hadoopInstaller.installation.HostInstallation.java

public void run() throws InstallationError {
    log.info("HostInstallation.Started", //$NON-NLS-1$
            host.getHostname());/*from  w ww.  ja v  a2 s . c  o m*/
    Session session = sshConnect();
    // TODO- Detect if the hostname is correctly set in the target host, and
    // promp to fix it. if needed
    FileObject remoteDirectory = sftpConnect();
    try {
        if (installer.doDeploy()) {
            new DeployInstallationFiles(host, session, remoteDirectory, installer).run();
        }
        new UploadConfiguration(installer.getConfigurationFilesToUpload(),
                installer.getConfig().deleteOldConfigurationFiles(), log).run(host, remoteDirectory);
    } finally {
        try {
            remoteDirectory.close();
            log.debug("HostInstallation.SFTP.Disconnect", //$NON-NLS-1$
                    host.getHostname());
        } catch (FileSystemException e) {
            throw new InstallationError(e, "HostInstallation.CouldNotClose", //$NON-NLS-1$
                    remoteDirectory.getName().getURI());
        }
        if (session.isConnected()) {
            session.disconnect();
            log.debug("HostInstallation.SSH.Disconnect", //$NON-NLS-1$
                    host.getHostname());
        }
    }
    log.info("HostInstallation.Ended", //$NON-NLS-1$
            host.getHostname());
}

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

/**
 * Helper method to delete lock file.//from  w w  w.j  a  v  a2s .  c om
 * 
 * @param lockFilePath
 *            Lock file to be deleted
 * @throws FileSystemException
 *             If lock file deletion fails
 */
private void deleteLockFile(String lockFilePath) throws FileSystemException {
    FileObject lockFile = resolveFile(lockFilePath);
    log.debug("Deleting lock file: " + fileObjectNameForDebug(lockFile));
    lockFile.delete();
    lockFile.close();
}

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

/**
 * This method removes the executor services from the executor services
 * map.//w  ww .j a  va 2s. c om
 * 
 * @param jarFile
 * @param classList
 * @throws FileSystemException
 */
public void deleteExecutorServicesEar(URL url) throws FileSystemException {
    try {
        File file = new File(url.toURI());
        String fileName = file.getName();
        synchronized (urlClassLoaderMap) {
            ConcurrentHashMap map = (ConcurrentHashMap) filesMap.get(fileName);
            if (map != null) {
                //log.info("ClassLoader Map=\n\n\n\n"+urlClassLoaderMap);
                Set keysinclassloadermap = map.keySet();
                log.info(keysinclassloadermap.size());
                Iterator classloaders = keysinclassloadermap.iterator();
                while (classloaders.hasNext()) {
                    String classloader = (String) classloaders.next();
                    log.info("ClassLoader=" + classloader);
                    ClassLoader webClassLoader = (ClassLoader) this.urlClassLoaderMap.get(map.get(classloader));
                    this.urlClassLoaderMap.remove(map.get(classloader));
                    ClassLoaderUtil.cleanupJarFileFactory(ClassLoaderUtil.closeClassLoader(webClassLoader));
                    urlClassLoaderMap.remove(map.get(classloader));
                    try {
                        if (webClassLoader instanceof WebClassLoader)
                            ((WebClassLoader) webClassLoader).close();
                        else if (webClassLoader instanceof VFSClassLoader) {
                            FileObject[] fObj = ((VFSClassLoader) webClassLoader).getFileObjects();
                            for (FileObject obj : fObj) {
                                obj.close();
                            }
                        }
                    } catch (Throwable e) {
                        log.error("Error in closing the classLoader", e);
                        // TODO Auto-generated catch block
                        //e.printStackTrace();
                    }
                    /*if (classloader.contains(deployDirectory +"/"+ fileName)) {
                       log.info("removing classloader" + deployDirectory
                      + classloader);
                          File warDir=new File(fileName);
                          if(warDir.exists()){                                    
                      warDeployer.deleteDir(warDir);
                          }
                          //log.info("Before Remove class loader\n\n\n\n"+this.urlClassLoaderMap);                           
                          //log.info("Remove class loader\n\n\n\n"+this.urlClassLoaderMap);
                    }*/
                }
                System.gc();
                classloaders = keysinclassloadermap.iterator();
                while (classloaders.hasNext()) {
                    String classloader = (String) classloaders.next();
                    if (classloader.endsWith(".war")) {
                        mbeanServer.invoke(warObjectName, "removeServlets",
                                new Object[] { (String) map.get(classloader), classloader },
                                new String[] { String.class.getName(), String.class.getName() });
                        File warDir = new File((String) map.get(classloader));
                        if (warDir.exists()) {
                            deleteDir(warDir);
                        }
                    }
                }
                log.info(this.urlClassLoaderMap);
            }
            filesMap.remove(fileName);
        }
    } catch (Exception ex) {
        try {
            log.error("Error in removing the executor services configuration for the file name "
                    + url.toURI().toString(), ex);
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //ex.printStackTrace();
    }
}

From source file:hadoopInstaller.installation.UploadConfiguration.java

private String getLocalFileContents(String fileName) throws InstallationError {
    log.debug("HostInstallation.LoadingLocal", //$NON-NLS-1$
            fileName);//w ww  .  j  a  va 2s .  co  m
    FileObject localFile;
    String localFileContents = new String();
    try {
        localFile = filesToUpload.resolveFile(fileName);
        if (localFile.exists()) {
            localFileContents = IOUtils.toString(localFile.getContent().getInputStream());
        }
    } catch (IOException e) {
        throw new InstallationError(e, "HostInstallation.CouldNotOpen", //$NON-NLS-1$
                fileName);
    }
    try {
        localFile.close();
    } catch (FileSystemException e) {
        log.warn("HostInstallation.CouldNotClose", //$NON-NLS-1$
                localFile.getName().getURI());
    }
    log.debug("HostInstallation.LoadedLocal", //$NON-NLS-1$
            fileName);
    return localFileContents;
}