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

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

Introduction

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

Prototype

FileName getName();

Source Link

Document

Returns the name of 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  ww w. j  a va2  s  .com*/
    }
    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:net.dempsy.distconfig.apahcevfs.Utils.java

public static int getVersion(final FileObject file) {
    final String base = file.getName().getBaseName();
    return Integer.parseInt(base.substring(versionSuffixPrefixLen, base.length()));
}

From source file:de.innovationgate.wga.common.beans.DesignDefinition.java

/**
 * Loads syncinfo data from a VFS file object. Character data is decoded as UTF-8.
 * @param file The file object/*from   w  ww . j  a  v a2s. c  o m*/
 * @throws IOException
 */
public static DesignDefinition load(FileObject file) throws IOException {
    XStream xStream = createXStreamForFile(file.getName().getBaseName());
    return (DesignDefinition) XStreamUtils.loadUtf8FromFileObject(xStream, file);
}

From source file:com.stratuscom.harvester.Utils.java

public static List<FileObject> findChildrenWithSuffix(FileObject dir, String suffix)
        throws FileSystemException {

    List<FileObject> ret = new ArrayList<FileObject>();

    for (FileObject fo : dir.getChildren()) {
        if (fo.getType() == FileType.FILE && fo.getName().getBaseName().endsWith(suffix)) {
            ret.add(fo);/*from   w  w w . ja  va2s  .  c o m*/
        }
    }
    return ret;
}

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

/**
 * Release a file item lock acquired either by the VFS listener or a sender
 *
 * @param fsManager which is used to resolve the processed file
 * @param fo representing the processed file
 *//*from ww  w  .  ja va  2 s.c o  m*/
public static void releaseLock(FileSystemManager fsManager, FileObject fo) {
    try {
        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()) {
            lockObject.delete();
        }
    } catch (FileSystemException e) {
        log.error("Couldn't release the lock for the file : " + fo.getName() + " after processing");
    }
}

From source file:net.sf.jabb.util.vfs.VfsUtility.java

/**
 * Close the FileObject.//ww  w . j a v a2s .  c  om
 * @param fo the FileObject to be closed. It can be null.
 */
static public void close(FileObject fo) {
    if (fo != null) {
        try {
            fo.close();
        } catch (FileSystemException e) {
            log.debug("Exception when closing FileObject: " + fo.getName(), e);
        }
    }
}

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//from w w  w  . j  a  v  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.googlecode.vfsjfilechooser2.utils.VFSUtils.java

/**
 * Tells whether a file is hidden/*from   www  .j a  va 2 s.c  om*/
 * @param fileObject a file representation
 * @return whether a file is hidden
 */
public static boolean isHiddenFile(FileObject fileObject) {
    try {
        return fileObject.getName().getBaseName().charAt(0) == '.';
    } catch (Exception ex) {
        return false;
    }
}

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
 *///from w  w w  .j  ava2s . c om
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:hadoopInstaller.io.XMLDocumentReader.java

public static Document parse(FileObject xmlDocument, FileObject xsdDocument)
        throws InstallerConfigurationParseError {

    try {/*from  w w  w.  ja v  a  2 s  .c o  m*/
        // Validate against XML Schema
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
                .newSchema(new StreamSource(xsdDocument.getContent().getInputStream()));
        dbf.setValidating(false);
        dbf.setSchema(schema);
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setErrorHandler(new ParseErrorHandler());
        return db.parse(xmlDocument.getContent().getInputStream());
    } catch (ParserConfigurationException | SAXException | IOException e) {
        throw new InstallerConfigurationParseError(e, "XMLDocumentReader.ParseError", xmlDocument.getName()); //$NON-NLS-1$
    }
}