Example usage for org.apache.commons.vfs FileSystemManager resolveFile

List of usage examples for org.apache.commons.vfs FileSystemManager resolveFile

Introduction

In this page you can find the example usage for org.apache.commons.vfs FileSystemManager resolveFile.

Prototype

public FileObject resolveFile(String name) throws FileSystemException;

Source Link

Document

Locates a file by name.

Usage

From source file:org.eclim.plugin.jdt.util.JavaUtils.java

/**
 * Attempts to locate the IClassFile for the supplied file path from the
 * specified project's classpath./*  w ww  . j  av  a 2  s  . c om*/
 *
 * @param project The project to find the class file in.
 * @param path Absolute path or url (jar:, zip:) to a .java source file.
 * @return The IClassFile.
 */
public static IClassFile findClassFile(IJavaProject project, String path) throws Exception {
    if (path.startsWith("/") || path.toLowerCase().startsWith("jar:")
            || path.toLowerCase().startsWith("zip:")) {
        FileSystemManager fsManager = VFS.getManager();
        FileObject file = fsManager.resolveFile(path);
        if (file.exists()) {
            BufferedReader in = null;
            try {
                in = new BufferedReader(new InputStreamReader(file.getContent().getInputStream()));
                String pack = null;
                String line = null;
                while ((line = in.readLine()) != null) {
                    Matcher matcher = PACKAGE_LINE.matcher(line);
                    if (matcher.matches()) {
                        pack = matcher.group(1);
                        break;
                    }
                }
                if (pack != null) {
                    String name = pack + '.' + FileUtils.getFileName(file.getName().getPath());
                    IType type = project.findType(name);
                    if (type != null) {
                        return type.getClassFile();
                    }
                }
            } finally {
                IOUtils.closeQuietly(in);
            }
        }
    }
    return null;
}

From source file:org.eclim.util.file.FileOffsets.java

/**
 * Reads the supplied file and compiles a list of offsets.
 *
 * @param filename The file to compile a list of offsets for.
 * @return The FileOffsets instance./*from  w ww. j  a va2s . c  o  m*/
 */
public static FileOffsets compile(String filename) {
    try {
        FileSystemManager fsManager = VFS.getManager();
        FileObject file = fsManager.resolveFile(filename);

        // disable caching (the cache seems to become invalid at some point
        // causing vfs errors).
        //fsManager.getFilesCache().clear(file.getFileSystem());

        if (!file.exists()) {
            throw new IllegalArgumentException(Services.getMessage("file.not.found", filename));
        }
        return compile(file.getContent().getInputStream());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.eclim.util.file.FileUtils.java

/**
 * Converts the supplied byte offset in the specified file to the
 * corresponding char offset for that file using the supplied file encoding.
 *
 * @param filename The absolute path to the file.
 * @param byteOffset The byte offset to be converted.
 * @param encoding The encoding of the file.  If null, defaults to utf-8.
 *
 * @return The char offset./*from w ww.j  a va  2s  .  co m*/
 */
public static int byteOffsetToCharOffset(String filename, int byteOffset, String encoding) throws Exception {
    FileSystemManager fsManager = VFS.getManager();
    FileObject file = fsManager.resolveFile(filename);

    return byteOffsetToCharOffset(file.getContent().getInputStream(), byteOffset, encoding);
}

From source file:org.efaps.webdav4vfs.test.AbstractDavTestCase.java

@BeforeMethod()
public void setUp() throws Exception {
    FileSystemManager fsm = VFS.getManager();
    FileObject fsRoot = fsm.createVirtualFileSystem(fsm.resolveFile("ram:/"));
    this.aFile = fsRoot.resolveFile("/file.txt");
    this.aFile.delete();
    this.aFile.createFile();
    this.aDirectory = fsRoot.resolveFile("/folder");
    this.aDirectory.delete();
    this.aDirectory.createFolder();
}

From source file:org.geoserver.importer.VFSWorker.java

/**
 * //from   w  ww  .  j av  a  2  s .  c om
 * @param archiveFile
 * @param filter
 * 
 * @return
 */
public List<String> listFiles(final File archiveFile, final FilenameFilter filter) {
    FileSystemManager fsManager;
    try {
        fsManager = VFS.getManager();
        String absolutePath = resolveArchiveURI(archiveFile);
        FileObject resolvedFile = fsManager.resolveFile(absolutePath);

        FileSelector fileSelector = new FileSelector() {
            /**
             * @see org.apache.commons.vfs.FileSelector#traverseDescendents(org.apache.commons.vfs.FileSelectInfo)
             */
            public boolean traverseDescendents(FileSelectInfo folderInfo) throws Exception {
                return true;
            }

            /**
             * @see org.apache.commons.vfs.FileSelector#includeFile(org.apache.commons.vfs.FileSelectInfo)
             */
            public boolean includeFile(FileSelectInfo fileInfo) throws Exception {
                File folder = archiveFile.getParentFile();
                String name = fileInfo.getFile().getName().getFriendlyURI();
                return filter.accept(folder, name);
            }
        };

        FileObject fileSystem;
        if (fsManager.canCreateFileSystem(resolvedFile)) {
            fileSystem = fsManager.createFileSystem(resolvedFile);
        } else {
            fileSystem = resolvedFile;
        }
        LOGGER.fine("Listing spatial data files archived in " + archiveFile.getName());
        FileObject[] containedFiles = fileSystem.findFiles(fileSelector);
        List<String> names = new ArrayList<String>(containedFiles.length);
        for (FileObject fo : containedFiles) {
            // path relative to its filesystem (ie, to the archive file)
            String pathDecoded = fo.getName().getPathDecoded();
            names.add(pathDecoded);
        }
        LOGGER.fine("Found " + names.size() + " spatial data files in " + archiveFile.getName() + ": " + names);
        return names;
    } catch (FileSystemException e) {
        e.printStackTrace();
    } finally {
        // fsManager.closeFileSystem(fileSystem.getFileSystem());
    }
    return Collections.emptyList();
}

From source file:org.geoserver.importer.VFSWorker.java

/**
 * Extracts the archive file {@code archiveFile} to {@code targetFolder}; both shall previously
 * exist./*from   w  ww.ja v  a  2 s  .c  o  m*/
 */
public void extractTo(File archiveFile, File targetFolder) throws IOException {

    FileSystemManager manager = VFS.getManager();
    String sourceURI = resolveArchiveURI(archiveFile);
    // String targetURI = resolveArchiveURI(targetFolder);
    FileObject source = manager.resolveFile(sourceURI);
    if (manager.canCreateFileSystem(source)) {
        source = manager.createFileSystem(source);
    }
    FileObject target = manager.createVirtualFileSystem(manager.resolveFile(targetFolder.getAbsolutePath()));

    FileSelector selector = new AllFileSelector() {
        @Override
        public boolean includeFile(FileSelectInfo fileInfo) {
            LOGGER.fine("Uncompressing " + fileInfo.getFile().getName().getFriendlyURI());
            return true;
        }
    };
    target.copyFrom(source, selector);
}

From source file:org.innobuilt.fincayra.FincayraApplication.java

public void watch(String fileName) {
    if (this.getReloadRootScope()) {

        LOGGER.info("Adding file to root scope watch: {}", fileName);
        try {/*from   ww  w  . ja  v  a  2s.  c o m*/
            FileSystemManager fsManager = VFS.getManager();
            FileObject listendir = fsManager.resolveFile(fileName);

            DefaultFileMonitor fm = new DefaultFileMonitor(new FincayraFileListener());
            fm.setRecursive(true);
            fm.addFile(listendir);
            fm.start();
        } catch (FileSystemException e) {
            LOGGER.error("Unable to watch directory: {}", fileName);
        }
    }
}

From source file:org.jahia.configuration.configurators.JahiaGlobalConfigurator.java

private void updateConfigurationFiles(String sourceWebAppPath, String webappPath, Properties dbProps,
        JahiaConfigInterface jahiaConfigInterface) throws Exception {
    getLogger().info("Configuring file using source " + sourceWebAppPath + " to target " + webappPath);

    FileSystemManager fsManager = VFS.getManager();

    new JackrabbitConfigurator(dbProps, jahiaConfigInterface, getLogger()).updateConfiguration(
            new VFSConfigFile(fsManager,
                    sourceWebAppPath + "/WEB-INF/etc/repository/jackrabbit/repository.xml"),
            webappPath + "/WEB-INF/etc/repository/jackrabbit/repository.xml");
    new TomcatContextXmlConfigurator(dbProps, jahiaConfigInterface).updateConfiguration(
            new VFSConfigFile(fsManager, sourceWebAppPath + "/META-INF/context.xml"),
            webappPath + "/META-INF/context.xml");

    String rootUserTemplate = sourceWebAppPath + "/WEB-INF/etc/repository/template-root-user.xml";
    FileObject rootUserTemplateFile = fsManager.resolveFile(rootUserTemplate);
    if (rootUserTemplateFile.exists()) {
        if (Boolean.valueOf(jahiaConfigInterface.getProcessingServer())) {
            new RootUserConfigurator(dbProps, jahiaConfigInterface,
                    encryptPassword(jahiaConfigInterface.getJahiaRootPassword())).updateConfiguration(
                            new VFSConfigFile(fsManager, rootUserTemplate),
                            webappPath + "/WEB-INF/etc/repository/root-user.xml");
        }// www  .ja  v  a  2s  .  c o m
    } else {
        new RootUserConfigurator(dbProps, jahiaConfigInterface,
                encryptPassword(jahiaConfigInterface.getJahiaRootPassword())).updateConfiguration(
                        new VFSConfigFile(fsManager, sourceWebAppPath + "/WEB-INF/etc/repository/root.xml"),
                        webappPath + "/WEB-INF/etc/repository/root.xml");
    }

    String mailServerTemplate = sourceWebAppPath + "/WEB-INF/etc/repository/template-root-mail-server.xml";
    if (fsManager.resolveFile(mailServerTemplate).exists()
            && Boolean.valueOf(jahiaConfigInterface.getProcessingServer())) {
        new MailServerConfigurator(dbProps, jahiaConfigInterface).updateConfiguration(
                new VFSConfigFile(fsManager, mailServerTemplate),
                webappPath + "/WEB-INF/etc/repository/root-mail-server.xml");
    }
    if ("jboss".equalsIgnoreCase(jahiaConfigInterface.getTargetServerType())) {
        updateForJBoss(dbProps, jahiaConfigInterface, fsManager);
    }

    String targetConfigPath = webappPath + "/WEB-INF/etc/config";
    String jahiaPropertiesFileName = "jahia.properties";
    String jahiaNodePropertiesFileName = "jahia.node.properties";
    if (externalizedConfigTempPath != null) {
        targetConfigPath = externalizedConfigTempPath;
        if (!StringUtils.isBlank(jahiaConfigInterface.getExternalizedConfigClassifier())) {
            jahiaPropertiesFileName = "jahia." + jahiaConfigInterface.getExternalizedConfigClassifier()
                    + ".properties";
            jahiaNodePropertiesFileName = "jahia.node." + jahiaConfigInterface.getExternalizedConfigClassifier()
                    + ".properties";
        }
    }

    ConfigFile jahiaPropertiesConfigFile = readJahiaProperties(sourceWebAppPath, fsManager);

    new JahiaPropertiesConfigurator(dbProps, jahiaConfigInterface)
            .updateConfiguration(jahiaPropertiesConfigFile, targetConfigPath + "/" + jahiaPropertiesFileName);

    try {
        ConfigFile jahiaNodePropertiesConfigFile = readJahiaNodeProperties(sourceWebAppPath, fsManager);
        if (jahiaNodePropertiesConfigFile != null) {
            new JahiaNodePropertiesConfigurator(logger, jahiaConfigInterface).updateConfiguration(
                    jahiaNodePropertiesConfigFile, targetConfigPath + "/" + jahiaNodePropertiesFileName);
        }
    } catch (FileSystemException fse) {
        // in the case we cannot access the file, it means we should not do the advanced configuration, which is expected for community edition.
    }

    // create empty Spring config file for custom configuration
    InputStream is = getClass().getResourceAsStream("/applicationcontext-custom.xml");
    FileOutputStream os = new FileOutputStream(new File(targetConfigPath, "applicationcontext-custom.xml"));
    try {
        IOUtils.copy(is, os);
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }

    String ldapTargetFile = new File(getDataDir(), "modules").getAbsolutePath();
    new LDAPConfigurator(dbProps, jahiaConfigInterface)
            .updateConfiguration(new VFSConfigFile(fsManager, sourceWebAppPath), ldapTargetFile);

    String jeeApplicationLocation = jahiaConfigInterface.getJeeApplicationLocation();
    boolean jeeLocationSpecified = !StringUtils.isEmpty(jeeApplicationLocation);
    if (jeeLocationSpecified || getDeployer().isEarDeployment()) {
        if (!jeeLocationSpecified) {
            jeeApplicationLocation = getDeployer().getDeploymentFilePath("digitalfactory", "ear")
                    .getAbsolutePath();
        }
        String jeeApplicationModuleList = jahiaConfigInterface.getJeeApplicationModuleList();
        if (StringUtils.isEmpty(jeeApplicationModuleList)) {
            jeeApplicationModuleList = "ROOT".equals(jahiaConfigInterface.getWebAppDirName())
                    ? "jahia-war:web:jahia.war:"
                    : ("jahia-war:web:jahia.war:" + jahiaConfigInterface.getWebAppDirName());
        }
        new ApplicationXmlConfigurator(jahiaConfigInterface, jeeApplicationModuleList).updateConfiguration(
                new VFSConfigFile(fsManager, jeeApplicationLocation + "/META-INF/application.xml"),
                jeeApplicationLocation + "/META-INF/application.xml");
    }
}

From source file:org.jahia.configuration.configurators.JahiaGlobalConfigurator.java

private ConfigFile readJahiaNodeProperties(String sourceWebAppPath, FileSystemManager fsManager)
        throws FileSystemException {
    URL jarUrl = null;//from ww w  .j  ava2s .c o  m
    FileObject jahiaEEImplFileObject = findVFSFile(sourceWebAppPath + "/WEB-INF/lib",
            "jahia\\-ee\\-impl.*\\.jar");
    if (jahiaEEImplFileObject != null) {
        jarUrl = jahiaEEImplFileObject.getURL();
    } else {
        jarUrl = this.getClass().getClassLoader().getResource("jahia-default-config.jar");
    }
    if (jarUrl != null) {
        return new VFSConfigFile(fsManager.resolveFile("jar:" + jarUrl.toExternalForm()),
                "org/jahia/defaults/config/properties/jahia.node.properties");
    }
    return null;
}

From source file:org.jahia.configuration.configurators.JahiaGlobalConfigurator.java

private ConfigFile readJahiaProperties(String sourceWebAppPath, FileSystemManager fsManager)
        throws IOException {
    ConfigFile cfg = null;//w  w  w  .  j a  v a2  s .  c  o m

    // Locate the Jar file
    FileObject jahiaImplFileObject = findVFSFile(sourceWebAppPath + "/WEB-INF/lib", "jahia\\-impl\\-.*\\.jar");
    URL jahiaDefaultConfigJARURL = this.getClass().getClassLoader().getResource("jahia-default-config.jar");
    if (jahiaImplFileObject != null) {
        jahiaDefaultConfigJARURL = jahiaImplFileObject.getURL();
    }
    VFSConfigFile jahiaPropertiesConfigFile = null;
    VFSConfigFile jahiaAdvancedPropertiesConfigFile = null;

    try {
        jahiaPropertiesConfigFile = new VFSConfigFile(
                fsManager.resolveFile("jar:" + jahiaDefaultConfigJARURL.toExternalForm()),
                "org/jahia/defaults/config/properties/jahia.properties");
        cfg = jahiaPropertiesConfigFile;

        FileObject jahiaEEImplFileObject = findVFSFile(sourceWebAppPath + "/WEB-INF/lib",
                "jahia\\-ee\\-impl.*\\.jar");
        if (jahiaEEImplFileObject != null) {
            jahiaDefaultConfigJARURL = jahiaEEImplFileObject.getURL();
        }
        try {
            jahiaAdvancedPropertiesConfigFile = new VFSConfigFile(
                    fsManager.resolveFile("jar:" + jahiaDefaultConfigJARURL.toExternalForm()),
                    "org/jahia/defaults/config/properties/jahia.advanced.properties");
            if (jahiaAdvancedPropertiesConfigFile != null) {
                InputStream is1 = jahiaPropertiesConfigFile.getInputStream();
                InputStream is2 = jahiaAdvancedPropertiesConfigFile.getInputStream();
                try {
                    final String content = IOUtils.toString(is1) + "\n" + IOUtils.toString(is2);
                    cfg = new ConfigFile() {
                        @Override
                        public URI getURI() throws IOException, URISyntaxException {
                            return null;
                        }

                        @Override
                        public InputStream getInputStream() throws IOException {
                            return IOUtils.toInputStream(content);
                        }
                    };
                } finally {
                    IOUtils.closeQuietly(is1);
                    IOUtils.closeQuietly(is2);
                }
            }
        } catch (FileSystemException fse) {
            // in the case we cannot access the file, it means we should not do the advanced configuration, which is expected for
            // Jahia "core".
        }
    } finally {
        if (jahiaPropertiesConfigFile != null) {
            jahiaPropertiesConfigFile.close();
        }
        if (jahiaAdvancedPropertiesConfigFile != null) {
            jahiaAdvancedPropertiesConfigFile.close();
        }
    }

    return cfg;
}