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:ShowProperties.java

public static void main(String[] args) throws FileSystemException {
    if (args.length == 0) {
        System.err.println("Please pass the name of a file as parameter.");
        System.err.println("e.g. java org.apache.commons.vfs2.example.ShowProperties LICENSE.txt");
        return;/*from   www .j ava 2  s .  c om*/
    }
    for (int i = 0; i < args.length; i++) {
        try {
            FileSystemManager mgr = VFS.getManager();
            System.out.println();
            System.out.println("Parsing: " + args[i]);
            FileObject file = mgr.resolveFile(args[i]);
            System.out.println("URL: " + file.getURL());
            System.out.println("getName(): " + file.getName());
            System.out.println("BaseName: " + file.getName().getBaseName());
            System.out.println("Extension: " + file.getName().getExtension());
            System.out.println("Path: " + file.getName().getPath());
            System.out.println("Scheme: " + file.getName().getScheme());
            System.out.println("URI: " + file.getName().getURI());
            System.out.println("Root URI: " + file.getName().getRootURI());
            System.out.println("Parent: " + file.getName().getParent());
            System.out.println("Type: " + file.getType());
            System.out.println("Exists: " + file.exists());
            System.out.println("Readable: " + file.isReadable());
            System.out.println("Writeable: " + file.isWriteable());
            System.out.println("Root path: " + file.getFileSystem().getRoot().getName().getPath());
            if (file.exists()) {
                if (file.getType().equals(FileType.FILE)) {
                    System.out.println("Size: " + file.getContent().getSize() + " bytes");
                } else if (file.getType().equals(FileType.FOLDER) && file.isReadable()) {
                    FileObject[] children = file.getChildren();
                    System.out.println("Directory with " + children.length + " files");
                    for (int iterChildren = 0; iterChildren < children.length; iterChildren++) {
                        System.out.println("#" + iterChildren + ": " + children[iterChildren].getName());
                        if (iterChildren > 5) {
                            break;
                        }
                    }
                }
                System.out.println("Last modified: "
                        + DateFormat.getInstance().format(new Date(file.getContent().getLastModifiedTime())));
            } else {
                System.out.println("The file does not exist");
            }
            file.close();
        } catch (FileSystemException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:ch.descabato.browser.BackupBrowser.java

public static void main2(final String[] args)
        throws InterruptedException, InvocationTargetException, SecurityException, IOException {
    if (args.length > 1)
        throw new IllegalArgumentException(
                "SYNTAX:  java... " + BackupBrowser.class.getName() + " [initialPath]");

    SwingUtilities.invokeAndWait(new Runnable() {

        @Override// www. jav  a 2 s . c  om
        public void run() {
            tryLoadSubstanceLookAndFeel();
            final JFrame f = new JFrame("OtrosVfsBrowser demo");
            f.addWindowListener(finishedListener);
            Container contentPane = f.getContentPane();
            contentPane.setLayout(new BorderLayout());
            DataConfiguration dc = null;
            final PropertiesConfiguration propertiesConfiguration = new PropertiesConfiguration();
            File favoritesFile = new File("favorites.properties");
            propertiesConfiguration.setFile(favoritesFile);
            if (favoritesFile.exists()) {
                try {
                    propertiesConfiguration.load();
                } catch (ConfigurationException e) {
                    e.printStackTrace();
                }
            }
            dc = new DataConfiguration(propertiesConfiguration);
            propertiesConfiguration.setAutoSave(true);
            final VfsBrowser comp = new VfsBrowser(dc, (args.length > 0) ? args[0] : null);
            comp.setSelectionMode(SelectionMode.FILES_ONLY);
            comp.setMultiSelectionEnabled(true);
            comp.setApproveAction(new AbstractAction(Messages.getMessage("demo.showContentButton")) {
                @Override
                public void actionPerformed(ActionEvent e) {
                    FileObject[] selectedFiles = comp.getSelectedFiles();
                    System.out.println("Selected files count=" + selectedFiles.length);
                    for (FileObject selectedFile : selectedFiles) {
                        try {
                            FileSize fileSize = new FileSize(selectedFile.getContent().getSize());
                            System.out.println(selectedFile.getName().getURI() + ": " + fileSize.toString());
                            Desktop.getDesktop()
                                    .open(new File(new URI(selectedFile.getURL().toExternalForm())));
                            //                byte[] bytes = readBytes(selectedFile.getContent().getInputStream(), 150 * 1024l);
                            //                JScrollPane sp = new JScrollPane(new JTextArea(new String(bytes)));
                            //                JDialog d = new JDialog(f);
                            //                d.setTitle("Content of file: " + selectedFile.getName().getFriendlyURI());
                            //                d.getContentPane().add(sp);
                            //                d.setSize(600, 400);
                            //                d.setVisible(true);
                        } catch (Exception e1) {
                            LOGGER.error("Failed to read file", e1);
                            JOptionPane.showMessageDialog(f,
                                    (e1.getMessage() == null) ? e1.toString() : e1.getMessage(), "Error",
                                    JOptionPane.ERROR_MESSAGE);
                        }
                    }
                }
            });

            comp.setCancelAction(new AbstractAction(Messages.getMessage("general.cancelButtonText")) {
                @Override
                public void actionPerformed(ActionEvent e) {
                    f.dispose();
                    try {
                        propertiesConfiguration.save();
                    } catch (ConfigurationException e1) {
                        e1.printStackTrace();
                    }
                    System.exit(0);
                }
            });
            contentPane.add(comp);

            f.pack();
            f.setVisible(true);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        }
    });
    while (!finished)
        Thread.sleep(100);
}

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

public static void getClassList(FileObject jarFile, CopyOnWriteArrayList classList,
        StandardFileSystemManager fsManager) throws FileSystemException {
    // log.info(jarFile);
    FileObject nestedFS = null;//from   w  w  w . ja  va  2s.c  om
    FileObject[] children = null;
    if (jarFile.getURL().toString().trim().endsWith(".jar")) {
        nestedFS = fsManager.createFileSystem(jarFile);
        children = nestedFS.resolveFile("/").getChildren();
    } else if (jarFile.getType() == FileType.FOLDER) {
        children = jarFile.getChildren();
    }
    // log.info();
    // log.info( "Children of " + jarFile.getName().getURI() );
    if (children == null)
        return;
    for (int i = 0; i < children.length; i++) {
        // log.info(children[i].+" "+
        // children[i].getName().getBaseName() );
        if (children[i].getType() == FileType.FILE && children[i].getName().getBaseName().endsWith(".class"))
            classList.add(children[i].toString().substring(children[i].toString().lastIndexOf('!') + 2));
        getClassList(children[i], classList, fsManager);
    }
}

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

public static void getClassList(FileObject jarFile, CopyOnWriteArrayList classList,
        StandardFileSystemManager fsManager) throws FileSystemException {
    // System.out.println(jarFile);
    FileObject nestedFS = null;/*w w w.  j a  v a 2 s .c  om*/
    FileObject[] children = null;
    if (jarFile.getURL().toString().trim().endsWith(".jar")) {
        nestedFS = fsManager.createFileSystem(jarFile);
        children = nestedFS.resolveFile("/").getChildren();
    } else if (jarFile.getType() == FileType.FOLDER) {
        children = jarFile.getChildren();
    }
    // System.out.println();
    // System.out.println( "Children of " + jarFile.getName().getURI() );
    if (children == null)
        return;
    for (int i = 0; i < children.length; i++) {
        // System.out.println(children[i].+" "+
        // children[i].getName().getBaseName() );
        if (children[i].getType() == FileType.FILE && children[i].getName().getBaseName().endsWith(".class"))
            classList.add(children[i].toString().substring(children[i].toString().lastIndexOf('!') + 2));
        getClassList(children[i], classList, fsManager);
    }
}

From source file:binky.reportrunner.engine.utils.impl.FileSystemHandlerImpl.java

public URL getURL(String url) throws IOException {
    FileObject file = fsManager.resolveFile(url);
    return file.getURL();
}

From source file:com.wipro.ats.bdre.filemon.FileMonitor.java

@Override
public void fileCreated(FileChangeEvent fileChangeEvent) throws Exception {
    FileObject obj = fileChangeEvent.getFile();
    LOGGER.debug("File Created " + obj.getURL());
    String dirPath = obj.getParent().getName().getPath();
    LOGGER.debug("Full path " + obj.getName().getPath());

    //Don't process anything with _archive
    if (dirPath.startsWith(monDir + "/" + archiveDirName)) {
        return;//from   www  .  ja  v a 2 s.c  om
    }
    //Don't process directory
    if (obj.getType() == FileType.FOLDER) {
        return;
    }

    String fileName = obj.getName().getPath();

    //Checking if the file name matches with the given pattern
    if (fileName.matches(filePattern)) {
        FileContent fc = obj.getContent();
        LOGGER.debug("Matched File Pattern by " + fileName);
        putEligibleFileInfoInMap(fileName, fc);
    }
}

From source file:com.wipro.ats.bdre.tdimport.FileMonitor.java

@Override
public void fileCreated(FileChangeEvent fileChangeEvent) throws Exception {
    FileObject obj = fileChangeEvent.getFile();
    LOGGER.debug("File Created " + obj.getURL());
    String dirPath = obj.getParent().getName().getPath();
    LOGGER.debug("Full path " + obj.getName().getPath());

    //Don't process anything with _archive
    if (dirPath.startsWith(monDir + "/" + archiveDirName)) {
        return;//from  w  w  w . j a  v  a2  s.  c  o m
    }
    //Don't process directory
    if (obj.getType() == FileType.FOLDER) {
        return;
    }

    String fileName = obj.getName().getPath();

    //Checking if the file name matches with the given pattern
    if (fileName.matches(filePattern)) {
        FileContent fc = obj.getContent();
        LOGGER.debug("Matched File Pattern by " + fileName);
        putEligibleFileInfoInMap(obj.getName().getBaseName(), fc);
    }
}

From source file:architecture.ee.spring.scripting.groovy.GroovyClassLoaderFactory.java

public void afterPropertiesSet() throws Exception {
    if (groovyClassLoader == null) {
        ApplicationProperties setupProperties = AdminHelper.getRepository().getSetupApplicationProperties();

        String sourcePath = setupProperties
                .get(ApplicationConstants.SCRIPTING_GROOVY_SOURCE_LOCATION_PROP_NAME);
        String sourceEncoding = setupProperties
                .get(ApplicationConstants.SCRIPTING_GROOVY_SOURCE_ENCODING_PROP_NAME);
        boolean recompileSource = setupProperties
                .getBooleanProperty(ApplicationConstants.SCRIPTING_GROOVY_SOURCE_RECOMPILE_PROP_NAME, false);
        boolean debug = setupProperties
                .getBooleanProperty(ApplicationConstants.SCRIPTING_GROOVY_DEBUG_PROP_NAME, false);

        if (StringUtils.isEmpty(sourcePath)) {
            sourcePath = AdminHelper.getRepository().getURI("groovy");
        }//w ww.  j  av a  2 s . com
        if (StringUtils.isEmpty(sourceEncoding))
            sourceEncoding = ApplicationConstants.DEFAULT_CHAR_ENCODING;

        CompilerConfiguration config = CompilerConfiguration.DEFAULT;
        config.setSourceEncoding(sourceEncoding);
        config.setRecompileGroovySource(recompileSource);
        config.setDebug(debug);

        GroovyClassLoader groovyClassLoaderToUse = new GroovyClassLoader(ClassUtils.getDefaultClassLoader(),
                config);

        try {
            FileObject fo = VFSUtils.resolveFile(sourcePath);
            groovyClassLoaderToUse.addClasspath(fo.getURL().getFile());

            if (log.isDebugEnabled()) {
                log.debug(fo.getURL());
            }

        } catch (Exception e) {
            if (log.isErrorEnabled())
                log.debug(L10NUtils.format("003031", sourcePath));
        }

        this.groovyClassLoader = groovyClassLoaderToUse;
    }
}

From source file:com.anrisoftware.sscontrol.filesystem.FileSystem.java

private Set<URL> toURLs(Set<FileObject> set) throws FileSystemException {
    Set<URL> urlset = new HashSet<URL>();
    for (FileObject file : set) {
        try {//from  w w w  . j  a v  a 2s.  c o  m
            urlset.add(file.getURL());
        } catch (org.apache.commons.vfs2.FileSystemException e) {
            throw log.getURLError(file, e);
        }
    }
    return urlset;
}

From source file:functionaltests.dataspaces.TestGlobalSpace.java

@Test
public void testGlobalSpace() throws Throwable {

    File in = tmpFolder.newFolder("input_space");
    String inPath = in.getAbsolutePath();

    File out = tmpFolder.newFolder("output_space");
    String outPath = out.getAbsolutePath();

    writeFiles(inFiles, inPath);/*ww w . j a  v  a  2s  .  c  o  m*/

    TaskFlowJob job = new TaskFlowJob();
    job.setName(this.getClass().getSimpleName());
    job.setInputSpace(in.toURI().toURL().toString());
    job.setOutputSpace(out.toURI().toURL().toString());

    JavaTask A = new JavaTask();
    A.setExecutableClassName("org.ow2.proactive.scheduler.examples.EmptyTask");
    A.setName("A");
    for (String[] file : inFiles) {
        A.addInputFiles(file[0], InputAccessMode.TransferFromInputSpace);
        A.addOutputFiles(file[0] + ".glob.A", OutputAccessMode.TransferToGlobalSpace);
    }
    A.setPreScript(new SimpleScript(scriptA, "groovy"));
    A.setForkEnvironment(new ForkEnvironment());
    job.addTask(A);

    JavaTask B = new JavaTask();
    B.setExecutableClassName("org.ow2.proactive.scheduler.examples.EmptyTask");
    B.setName("B");
    B.addDependence(A);
    for (String[] file : inFiles) {
        B.addInputFiles(file[0] + ".glob.A", InputAccessMode.TransferFromGlobalSpace);
        B.addOutputFiles(file[0] + ".out", OutputAccessMode.TransferToOutputSpace);
    }
    B.setPreScript(new SimpleScript(scriptB, "groovy"));
    B.setForkEnvironment(new ForkEnvironment());
    job.addTask(B);

    Scheduler scheduler = schedulerHelper.getSchedulerInterface();
    JobId id = scheduler.submit(job);

    schedulerHelper.waitForEventJobFinished(id);
    assertFalse(schedulerHelper.getJobResult(id).hadException());

    /**
     * check: inFiles > IN > LOCAL A > GLOBAL > LOCAL B > OUT 
     */
    for (String[] inFile : inFiles) {
        File f = new File(outPath + File.separator + inFile[0] + ".out");
        assertTrue("File does not exist: " + f.getAbsolutePath(), f.exists());
        Assert.assertEquals("Original and copied files differ", inFile[1], FileUtils.readFileToString(f));
        f.delete();
        File inf = new File(inPath + File.separator + inFile[0]);
        inf.delete();
    }

    /**
     * check that the file produced is accessible in the global user space via the scheduler API
     */
    String globalURI = scheduler.getGlobalSpaceURIs().get(0);
    assertTrue(globalURI.startsWith("file:"));
    String globalPath = new File(new URI(globalURI)).getAbsolutePath();

    FileSystemManager fsManager = VFSFactory.createDefaultFileSystemManager();
    for (String[] file : inFiles) {
        FileObject outFile = fsManager.resolveFile(globalURI + "/" + file[0] + ".glob.A");
        log("Checking existence of " + outFile.getURL());
        assertTrue(outFile.getURL() + " exists", outFile.exists());

        File outFile2 = new File(globalPath, file[0] + ".glob.A");
        log("Checking existence of " + outFile2);
        assertTrue(outFile2 + " exists", outFile2.exists());
    }
}