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

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

Introduction

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

Prototype

URL getURL() throws FileSystemException;

Source Link

Document

Returns a URL representing this file.

Usage

From source file:de.innovationgate.wgpublisher.services.WGACoreServicesImpl.java

public void deleteFSDesignResource(RemoteSession session, String path) throws WGAServiceException {
    if (!isAdminServiceEnabled()) {
        throw new WGAServiceException("Administrative services are disabled");
    }/*from  w w  w . j  a  v a 2 s .  c  om*/

    if (!isAdminSession(session)) {
        throw new WGAServiceException("You need an administrative login to access this service.");
    }

    WGADesignSource source = _core.getDesignManager().getDesignSources()
            .get(WGAConfiguration.UID_DESIGNSOURCE_FILESYSTEM);
    if (source instanceof FileSystemDesignSource) {
        FileSystemDesignSource fsSource = (FileSystemDesignSource) source;
        try {
            fsSource.getDir().refresh();
            FileObject resource = fsSource.getDir().resolveFile(path);

            String basePath = fsSource.getDir().getURL().getPath();
            String resourcePath = resource.getURL().getPath();
            if (!resourcePath.startsWith(basePath)) {
                throw new WGAServiceException(
                        new IllegalArgumentException("Illegal design resource path '" + path + "'."));
            }

            if (resource.exists()) {
                resource.delete(new FileSelector() {

                    public boolean includeFile(FileSelectInfo fileInfo) throws Exception {
                        return true;
                    }

                    public boolean traverseDescendents(FileSelectInfo fileInfo) throws Exception {
                        return true;
                    }

                });
                clearDesignFileCache(fsSource, fsSource.getDir().getName().getRelativeName(resource.getName()));
            }
        } catch (FileSystemException e) {
            throw new WGAServiceException("Deleting FSDesignResource '" + path + "' failed.", e);
        }
    }
}

From source file:de.innovationgate.wgpublisher.services.WGACoreServicesImpl.java

public DataSource retrieveFSDesignResourceContent(RemoteSession session, FSDesignResourceState state)
        throws WGAServiceException {
    if (!isAdminServiceEnabled()) {
        throw new WGAServiceException("Administrative services are disabled");
    }/*from  w ww  .  java  2 s.  c  o  m*/

    if (!isAdminSession(session)) {
        throw new WGAServiceException("You need an administrative login to access this service.");
    }

    WGADesignSource source = _core.getDesignManager().getDesignSources()
            .get(WGAConfiguration.UID_DESIGNSOURCE_FILESYSTEM);
    if (source instanceof FileSystemDesignSource) {
        FileSystemDesignSource fsSource = (FileSystemDesignSource) source;
        try {
            fsSource.getDir().refresh();
            FileObject resource = fsSource.getDir().resolveFile(state.getPath());

            String basePath = fsSource.getDir().getURL().getPath();
            String resourcePath = resource.getURL().getPath();
            if (!resourcePath.startsWith(basePath)) {
                throw new WGAServiceException(new IllegalArgumentException(
                        "Illegal design resource path '" + state.getPath() + "'."));
            }

            if (resource.exists()) {
                if (resource.getType().equals(FileType.FOLDER)) {
                    throw new WGAServiceException(
                            new IllegalArgumentException("Cannot retrieve content of a folder."));
                } else {
                    return new URLDataSource(resource.getURL());
                }
            }
        } catch (FileSystemException e) {
            throw new WGAServiceException(
                    "Retrieving content of FSDesignResource '" + state.getPath() + "' failed.", e);
        }
    }
    return null;
}

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 w  ww.  ja  va2s .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:com.app.server.EARDeployer.java

/**
 * This method configures the executor services from the jar file.
 * //from  w w w .  j ava2  s.com
 * @param jarFile
 * @param classList
 * @throws FileSystemException
 */
public void deployExecutorServicesEar(String earFileName, FileObject earFile) throws FileSystemException {
    try {
        log.info("EARFILE NAMEs=" + earFileName);
        CopyOnWriteArrayList<URL> libs = new CopyOnWriteArrayList<URL>();
        CopyOnWriteArrayList<FileObject> warObjects = new CopyOnWriteArrayList<FileObject>();
        CopyOnWriteArrayList<FileObject> jarObjects = new CopyOnWriteArrayList<FileObject>();
        CopyOnWriteArrayList<FileObject> sarObjects = new CopyOnWriteArrayList<FileObject>();
        CopyOnWriteArrayList<FileObject> rarObjects = new CopyOnWriteArrayList<FileObject>();
        CopyOnWriteArrayList<FileObject> ezbObjects = new CopyOnWriteArrayList<FileObject>();
        WebClassLoader customClassLoaderBaseLib = new WebClassLoader(new URL[] { earFile.getURL() },
                Thread.currentThread().getContextClassLoader());
        final Field factoryField = URL.class.getDeclaredField("factory");
        factoryField.setAccessible(true);
        factoryField.set(null, new RsrcURLStreamHandlerFactory(customClassLoaderBaseLib));
        //URL.setURLStreamHandlerFactory(new RsrcURLStreamHandlerFactory(customClassLoaderBaseLib));
        obtainUrls(earFile, earFile, libs, warObjects, jarObjects, sarObjects, rarObjects, ezbObjects,
                fsManager);
        VFSClassLoader customClassLoader = null;
        for (URL earLib : libs) {
            customClassLoaderBaseLib.addURL(earLib);
        }
        FileObject jarFileObject;
        ConcurrentHashMap classLoaderPath = new ConcurrentHashMap();
        filesMap.put(earFileName, classLoaderPath);
        for (FileObject rarFileObj : rarObjects) {

            //log.info(classLoader);
            //warDeployer.deleteDir(new File(serverConfig.getDeploydirectory()+"/"+fileName.substring(0,fileName.lastIndexOf(".war"))));
            mbeanServer.invoke(rarObjectName, "deploy", new Object[] { rarFileObj },
                    new String[] { FileObject.class.getName() });
            //}
        }
        for (FileObject sarFileObj : sarObjects) {

            //log.info(classLoader);
            //warDeployer.deleteDir(new File(serverConfig.getDeploydirectory()+"/"+fileName.substring(0,fileName.lastIndexOf(".war"))));
            mbeanServer.invoke(sarObjectName, "deploy",
                    new Object[] { sarFileObj, fsManager, customClassLoaderBaseLib },
                    new String[] { FileObject.class.getName(), StandardFileSystemManager.class.getName(),
                            ClassLoader.class.getName() });
            //}
        }

        for (FileObject ezbFileObj : ezbObjects) {

            //log.info(classLoader);
            //warDeployer.deleteDir(new File(serverConfig.getDeploydirectory()+"/"+fileName.substring(0,fileName.lastIndexOf(".war"))));
            mbeanServer.invoke(ezbObjectName, "deploy", new Object[] { ezbFileObj, customClassLoaderBaseLib },
                    new String[] { FileObject.class.getName(), VFSClassLoader.class.getName() });
            //}
        }

        for (FileObject warFileObj : warObjects) {
            //if(warFileObj.getName().getBaseName().endsWith(".war")){
            //logger.info("filePath"+filePath);
            String filePath = serverConfig.getDeploydirectory() + "/" + warFileObj.getName().getBaseName();
            log.info(filePath);
            String fileName = warFileObj.getName().getBaseName();
            String directoryName = fileName.substring(0, fileName.indexOf('.'));

            log.info(customClassLoaderBaseLib);
            //warDeployer.deleteDir(new File(serverConfig.getDeploydirectory()+"/"+fileName.substring(0,fileName.lastIndexOf(".war"))));
            new File(serverConfig.getDeploydirectory() + "/"
                    + fileName.substring(0, fileName.lastIndexOf(".war"))).mkdirs();
            log.info(serverConfig.getDeploydirectory() + "/"
                    + fileName.substring(0, fileName.lastIndexOf(".war")));
            classLoaderPath.put(warFileObj.getName().getBaseName(), serverConfig.getDeploydirectory() + "/"
                    + fileName.substring(0, fileName.lastIndexOf(".war")));
            mbeanServer.invoke(warObjectName, "extractWar",
                    new Object[] { warFileObj, customClassLoaderBaseLib, fsManager },
                    new String[] { FileObject.class.getName(), WebClassLoader.class.getName(),
                            StandardFileSystemManager.class.getName() });
            //}
        }
        //URL.setURLStreamHandlerFactory(new RsrcURLStreamHandlerFactory(null));
        for (FileObject jarFileObj : jarObjects) {

            //log.info(classLoader);
            //warDeployer.deleteDir(new File(serverConfig.getDeploydirectory()+"/"+fileName.substring(0,fileName.lastIndexOf(".war"))));
            mbeanServer.invoke(ejbObjectName, "deploy",
                    new Object[] { new URL(jarFileObj.getURL().toURI().toString()), fsManager,
                            customClassLoaderBaseLib },
                    new String[] { URL.class.getName(), StandardFileSystemManager.class.getName(),
                            ClassLoader.class.getName() });
            //}
        }
        //for (int keyCount = 0; keyCount < keys.size(); keyCount++) {}
        /*for (FileObject fobject : fileObjects) {
           fobject.close();
        }*/
        //log.info("Channel unlocked");
        earsDeployed.add(earFile.getName().getURI());
        earFile.close();
        fsManager.closeFileSystem(earFile.getFileSystem());
        // ClassLoaderUtil.closeClassLoader(customClassLoader);
    } catch (Exception ex) {
        log.error("Error in deploying the ear ", ex);
        //ex.printStackTrace();
    }
}

From source file:com.googlecode.vfsjfilechooser2.plaf.metal.MetalVFSFileChooserUI.java

private void doFileSelectionModeChanged(PropertyChangeEvent e) {
    if (fileNameLabel != null) {
        populateFileNameLabel();//from ww w . j a  va  2  s  .c om
    }

    clearIconCache();

    VFSJFileChooser fc = getFileChooser();
    FileObject currentDirectory = fc.getCurrentDirectoryObject();

    if ((currentDirectory != null) && fc.isDirectorySelectionEnabled() && !fc.isFileSelectionEnabled()
            && fc.getFileSystemView().isFileSystem(currentDirectory)) {
        String url = null;

        try {
            url = currentDirectory.getURL().toExternalForm();
        } catch (FileSystemException e1) {
            e1.printStackTrace();
        }

        setFileName(url);
    } else {
        setFileName(null);
    }
}

From source file:fr.cls.atoll.motu.library.misc.vfs.VFSManager.java

/**
 * Resolve file.//from  w  ww . java2 s.  co  m
 * 
 * @param baseFile the base file
 * @param file the file
 * 
 * @return the file object
 * 
 * @throws MotuException the motu exception
 */
public FileObject resolveFile(FileObject baseFile, final String file) throws MotuException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("resolveFile(FileObject, String) - entering");
    }

    FileObject fileObject = null;
    open();
    if (opts == null) {
        opts = new FileSystemOptions();
    }

    try {

        // setSchemeOpts(baseFile.getName().getScheme());
        setSchemeOpts(baseFile.getURL());

        fileObject = standardFileSystemManager.resolveFile(baseFile, file, opts);

    } catch (FileSystemException e) {
        throw new MotuException(
                String.format("Unable to resolve uri '%s/%s' ", baseFile.getName().toString(), file), e);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("resolveFile(FileObject, String) - exiting");
    }
    return fileObject;

}

From source file:com.googlecode.vfsjfilechooser2.plaf.metal.MetalVFSFileChooserUI.java

private String fileNameString(FileObject fileObject) {
    if (fileObject == null) {
        return null;
    } else {//from  ww  w.j  av  a2 s  . c o m
        VFSJFileChooser fc = getFileChooser();

        if ((fc.isDirectorySelectionEnabled() && !fc.isFileSelectionEnabled())
                || (fc.isDirectorySelectionEnabled() && fc.isFileSelectionEnabled()
                        && fc.getFileSystemView().isFileSystemRoot(fileObject))) {
            String url = null;

            try {
                url = fileObject.getURL().toExternalForm();
            } catch (FileSystemException ex) {
                ex.printStackTrace();
            }

            return url;
        } else {
            return fileObject.getName().getBaseName();
        }
    }
}

From source file:com.googlecode.vfsjfilechooser2.plaf.metal.MetalVFSFileChooserUI.java

private void doDirectoryChanged(PropertyChangeEvent e) {
    VFSJFileChooser fc = getFileChooser();
    AbstractVFSFileSystemView fsv = fc.getFileSystemView();

    clearIconCache();/*from   www.j  av  a2 s  .c om*/

    FileObject currentDirectory = fc.getCurrentDirectoryObject();

    if (currentDirectory != null) {
        directoryComboBoxModel.addItem(currentDirectory);
        directoryComboBox.setSelectedItem(currentDirectory);
        fc.setCurrentDirectoryObject(currentDirectory);

        if (fc.isDirectorySelectionEnabled() && !fc.isFileSelectionEnabled()) {
            if (fsv.isFileSystem(currentDirectory)) {
                String url = null;

                try {
                    url = currentDirectory.getURL().toExternalForm();
                } catch (FileSystemException e1) {
                    e1.printStackTrace();
                }

                setFileName(url);
            } else {
                setFileName(null);
            }
        }
    }
}

From source file:com.google.code.docbook4j.renderer.BaseRenderer.java

public InputStream render() throws Docbook4JException {

    assertNotNull(xmlResource, "Value of the xml source should be not null!");

    FileObject xsltResult = null;
    FileObject xmlSourceFileObject = null;
    FileObject xslSourceFileObject = null;
    FileObject userConfigXmlSourceFileObject = null;

    try {/*from  www . ja va 2  s .c  o  m*/

        xmlSourceFileObject = FileObjectUtils.resolveFile(xmlResource);
        if (xslResource != null) {
            xslSourceFileObject = FileObjectUtils.resolveFile(xslResource);
        } else {
            xslSourceFileObject = getDefaultXslStylesheet();
        }

        if (userConfigXmlResource != null) {
            userConfigXmlSourceFileObject = FileObjectUtils.resolveFile(userConfigXmlResource);
        }

        SAXParserFactory factory = createParserFactory();
        final XMLReader reader = factory.newSAXParser().getXMLReader();

        EntityResolver resolver = new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {

                log.debug("Resolving file {}", systemId);

                FileObject inc = FileObjectUtils.resolveFile(systemId);
                return new InputSource(inc.getContent().getInputStream());
            }
        };

        // prepare xml sax source
        ExpressionEvaluatingXMLReader piReader = new ExpressionEvaluatingXMLReader(reader, vars);
        piReader.setEntityResolver(resolver);

        SAXSource source = new SAXSource(piReader,
                new InputSource(xmlSourceFileObject.getContent().getInputStream()));
        source.setSystemId(xmlSourceFileObject.getURL().toExternalForm());

        // prepare xslt result
        xsltResult = FileObjectUtils.resolveFile("tmp://" + UUID.randomUUID().toString());
        xsltResult.createFile();

        // create transofrmer and do transformation
        final Transformer transformer = createTransformer(xmlSourceFileObject, xslSourceFileObject);
        transformer.transform(source, new StreamResult(xsltResult.getContent().getOutputStream()));

        // do post processing
        FileObject target = postProcess(xmlSourceFileObject, xslSourceFileObject, xsltResult,
                userConfigXmlSourceFileObject);

        FileObjectUtils.closeFileObjectQuietly(xsltResult);
        FileObjectUtils.closeFileObjectQuietly(target);
        return target.getContent().getInputStream();

    } catch (FileSystemException e) {
        throw new Docbook4JException("Error transofrming xml!", e);
    } catch (SAXException e) {
        throw new Docbook4JException("Error transofrming xml!", e);
    } catch (ParserConfigurationException e) {
        throw new Docbook4JException("Error transofrming xml!", e);
    } catch (TransformerException e) {
        throw new Docbook4JException("Error transofrming xml!", e);
    } catch (IOException e) {
        throw new Docbook4JException("Error transofrming xml !", e);
    } finally {
        FileObjectUtils.closeFileObjectQuietly(xmlSourceFileObject);
        FileObjectUtils.closeFileObjectQuietly(xslSourceFileObject);
    }

}

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  ww w.  ja  va  2  s . c o m*/

    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;

}