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

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

Introduction

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

Prototype

public FileName getName();

Source Link

Document

Returns the name of this file.

Usage

From source file:org.cfeclipse.cfml.views.explorer.vfs.view.VFSView.java

/**
 * Notifies the application components that a new current directory has been selected
 * // w  w  w  . jav a2  s. com
 * @param dir the directory that was selected, null is ignored
 */
public void notifySelectedDirectory(FileObject dir, String connectionId) throws FileSystemException {
    if (dir == null || connectionId == null)
        return;
    if (getCurrentDirectory() != null && dir.equals(getCurrentDirectory()))
        return;

    setCurrentDirectory(dir);
    setCurrentConnectionId(connectionId);

    //System.err.println("notifySelectedDirectory currentDirectory:" 
    //      + currentDirectory + " notify dir:" + dir );

    // Processing...
    VFSUtil.setUiStateListContents(shell, getCurrentDirectory().getName().toString());

    notifySelectedFiles(null);

    /* Table view:
     * Displays the contents of the selected directory.
     */
    workerUpdate(dir, connectionId, false);

    /* Combo view:
     * Sets the combo box to point to the selected directory.
     */
    final FileObject[] comboRoots = (FileObject[]) combo.getData(COMBODATA_ROOTS);
    int comboEntry = -1;
    if (comboRoots != null) {
        for (int i = 0; i < comboRoots.length; ++i) {
            if (dir.equals(comboRoots[i])) {
                comboEntry = i;
                break;
            }
        }
    }

    if (comboEntry == -1)
        combo.setText(dir.getName().toString());
    else
        combo.select(comboEntry);

    /* Tree view:
     * If not already expanded, recursively expands the parents of the specified
     * directory until it is visible.
     */
    Vector /* of FileObject */ path = new Vector();

    // Build a stack of paths from the root of the tree
    while (dir != null) {
        path.add(dir);
        //dir = dir.getParentFile();

        try {
            dir = dir.getParent();
        } catch (Exception e) {
            System.err.println("notifySelectedDirectory:" + e);
        }
    }

    //System.out.println("notifySelectedDirectory currentDirectory:" 
    //      + currentDirectory + " dir:" + dir + " tree path:" + path);

    // Recursively expand the tree to get to the specified directory
    TreeItem[] items = tree.getItems();
    TreeItem lastItem = null;
    String destConnectionId = null;
    TreeItem item = null;
    // filter by connection first
    for (int k = 0; k < items.length; ++k) {
        item = items[k];
        destConnectionId = (String) item.getData(TREEITEMDATA_CONNECTIONID);
        if (connectionId.equals(connectionId)) {
            items = items[k].getItems();
        }
    }

    for (int i = path.size() - 1; i >= 0; --i) {
        final FileObject pathElement = (FileObject) path.elementAt(i);

        // Search for a particular FileObject in the array of tree items
        // No guarantee that the items are sorted in any recognizable fashion, so we'll
        // just sequential scan.  There shouldn't be more than a few thousand entries.
        item = null;
        for (int k = 0; k < items.length; ++k) {
            item = items[k];
            if (item.isDisposed())
                continue;

            final String fileURI = ((String) item.getData(TREEITEMDATA_URI));
            destConnectionId = (String) item.getData(TREEITEMDATA_CONNECTIONID);

            // Resolving the children will attempt a server connection. This will hang the UI if the server is down
            // Thus perform a comparison by Host/Scheme/Path only
            // Cannot just compare the URI strings cuz FileObject hides the port number

            if (connectionId.equals(destConnectionId) && VFSUtil.compareURIs(fileURI, pathElement.toString()))
                break;
        }

        if (item == null)
            break;
        lastItem = item;

        if (i != 0 && !item.getExpanded()) {
            treeExpandItem(item);
            item.setExpanded(true);
        }
        items = item.getItems();
    }
    if (connectionId.equals(destConnectionId)) {
        tree.setSelection((lastItem != null) ? new TreeItem[] { lastItem } : new TreeItem[0]);
    }

    /* Shell:
     * Sets the title to indicate the selected directory
     */
    VFSUtil.setUiStateIdle(shell, VFSUtil.stripUserTokens(getCurrentDirectory().toString()));
}

From source file:org.cfeclipse.cfml.views.explorer.vfs.view.VFSView.java

/**
 * Handles deferred Refresh notifications (due to Drag & Drop)
 *///from   w w w  . j  av a  2s .  c o m
void handleDeferredRefresh() throws FileSystemException {
    //System.out.println("handleDeferredRefresh");

    if (isDragging || isDropping || !deferredRefreshRequested)
        return;

    deferredRefreshRequested = false;
    FileObject[] files = deferredRefreshFiles;
    deferredRefreshFiles = null;

    shell.setCursor(CFPluginImages.cursors[CFPluginImages.cursorWait]);

    /* Table view:
     * Refreshes information about any files in the list and their children.
     */
    boolean refreshTable = false;

    if (files != null) {
        for (int i = 0; i < files.length; ++i) {
            final FileObject file = files[i];
            if (file.equals(getCurrentDirectory())) {
                refreshTable = true;
                break;
            }

            FileObject parentFile = file.getParent();

            if ((parentFile != null) && (parentFile.equals(getCurrentDirectory()))) {
                refreshTable = true;
                break;
            }
        }
    } else
        refreshTable = true;

    if (refreshTable)
        workerUpdate(getCurrentDirectory(), getCurrentConnectionId(), true);

    /* Combo view:
     * Refreshes the list of roots
     */
    final FileObject[] roots = getRoots(fsManager);

    if (files == null) {
        boolean refreshCombo = false;
        final FileObject[] comboRoots = (FileObject[]) combo.getData(COMBODATA_ROOTS);

        if ((comboRoots != null) && (comboRoots.length == roots.length)) {
            for (int i = 0; i < roots.length; ++i) {
                if (!roots[i].equals(comboRoots[i])) {
                    refreshCombo = true;
                    break;
                }
            }
        } else
            refreshCombo = true;

        if (refreshCombo) {
            combo.removeAll();
            combo.setData(COMBODATA_ROOTS, roots);

            for (int i = 0; i < roots.length; ++i) {
                final FileObject file = roots[i];
                combo.add(file.getName().toString());
            }
        }
    }

    /* Tree view:
     * Refreshes information about any files in the list and their children.
     */
    treeRefresh(roots);

    treeInsertRemoteURIs();

    // Remind everyone where we are in the filesystem
    final FileObject dir = getCurrentDirectory();
    setCurrentDirectory(null);
    final String con = getCurrentConnectionId();
    setCurrentConnectionId(null);
    notifySelectedDirectory(dir, con);

    shell.setCursor(CFPluginImages.cursors[CFPluginImages.cursorDefault]);
}

From source file:org.cfeclipse.cfml.views.explorer.vfs.view.VFSView.java

/**
 * Performs the default action on a set of files.
 * /*from ww  w .j  a  va 2 s. c o m*/
 * @param files the array of files to process
 */
void doDefaultFileAction(FileObject[] files) {
    // only uses the 1st file (for now)
    if (files.length == 0)
        return;
    final FileObject file = files[0];

    if (VFSUtil.isDirectory(file)) {
        try {
            notifySelectedDirectory(file, getCurrentConnectionId());
        } catch (Exception e) {
            debug(e); // "FileViewer.doDefaultFileAction " + 
        }
    } else {
        //final String fileName = file.getAbsolutePath();
        RemoteFileEditorInput input = new RemoteFileEditorInput(file);
        try {
            IEditorDescriptor desc = PlatformUI.getWorkbench().getEditorRegistry()
                    .getDefaultEditor(file.getName().getBaseName());
            IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
            //page.openEditor(input, desc.getId());

            page.openEditor(input, CFMLEditor.ID);

            // wonder how this could work?
            //            IFileStore fileStore;
            //            fileStore = EFS.getFileSystem(file.getName().getScheme()).getStore(file.getURL().toURI());
            //            IDE.openEditorOnFileStore( page, fileStore );
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //         if (! Program.launch(fileName)) {   
        //            MessageBox dialog = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
        //            dialog.setMessage(getResourceString("error.FailedLaunch.message", new Object[] { fileName }));
        //            dialog.setText(shell.getText ());
        //            dialog.open();
        //         }
    }
}

From source file:org.cfeclipse.cfml.views.explorer.vfs.view.VFSView.java

/**
 * Gets filesystem root entries/*from w  w  w . j  a  v  a 2  s  .  c  o  m*/
 * @param fsManager
 * @return an array of Files corresponding to the root directories on the platform,
 *         may be empty but not null
 */
FileObject[] getRoots(FileSystemManager fsManager) throws FileSystemException {
    /*
     * On JDK 1.22 only...
     */
    // return File.listRoots();
    FileObject[] roots = null;
    //      FileObject[] newRequest = null;
    /*
     * On JDK 1.1.7 and beyond...
     * -- PORTABILITY ISSUES HERE --
     */
    if (System.getProperty("os.name").indexOf("Windows") != -1) {
        Vector /* of FileObject */ list = new Vector();
        list.add(fsManager.resolveFile(DRIVE_A));

        for (char i = 'c'; i <= 'z'; ++i) {
            //FileObject drive = new FileObject(i + ":" + FileName.SEPARATOR);
            FileObject drive = fsManager.resolveFile(i + ":" + FileName.SEPARATOR);

            if (VFSUtil.isDirectory(drive) && drive.exists()) {
                list.add(drive);
                if (initial && i == 'c') {
                    setCurrentDirectory(drive);
                    setCurrentConnectionId(drive.getName().toString());
                    initial = false;
                }
            }
        }
        roots = (FileObject[]) list.toArray(new FileObject[list.size()]);
        VFSUtil.sortFiles(roots);

        //return roots;
    } else {
        FileObject root = fsManager.resolveFile(FileName.SEPARATOR);

        if (initial) {
            setCurrentDirectory(root);
            setCurrentConnectionId(root.getName().toString());
            initial = false;
        }
        roots = new FileObject[] { root };
    }

    return roots; //newRequest; 
}

From source file:org.cfeclipse.cfml.views.explorer.vfs.view.VFSView.java

/**
 * Adds a file's detail information to the directory list
 *//*from  w  w w. j  a  va  2 s  .c om*/
private void workerAddFileDetails(final FileObject file, final String connectionId) {
    long date = 0;
    try {
        date = file.getContent().getLastModifiedTime();
    } catch (Exception e) {
    }

    final String nameString = file.getName().getBaseName();
    final String dateString = dateFormat.format(new Date(date));
    final String sizeString;
    final String typeString;
    final Image iconImage;

    // If directory
    if (VFSUtil.isDirectory(file)) {
        typeString = getResourceString("filetype.Folder");
        sizeString = "";
        iconImage = iconCache.get(CFPluginImages.ICON_FOLDER);
    } else {
        long size = 0;
        try {
            size = file.getContent().getSize();
        } catch (Exception e) {
        }

        // It is a file, get size
        sizeString = getResourceString("filesize.KB", new Object[] { new Long((size + 512) / 1024) });

        int dot = nameString.lastIndexOf('.');
        if (dot != -1) {
            String extension = nameString.substring(dot);
            Program program = Program.findProgram(extension);

            // get icon based on extension
            if (program != null) {
                typeString = program.getName();
                iconImage = CFPluginImages.getIconFromProgram(program);
            } else {
                typeString = getResourceString("filetype.Unknown", new Object[] { extension.toUpperCase() });
                iconImage = iconCache.get(CFPluginImages.ICON_FILE);
            }
        } else {
            typeString = getResourceString("filetype.None");
            iconImage = iconCache.get(CFPluginImages.ICON_FILE);
        }
    }

    // Table values: Name, Size, Type, Date
    final String[] strings = new String[] { nameString, sizeString, typeString, dateString };

    display.syncExec(new Runnable() {
        public void run() {
            String attrs = VFSUtil.getFileAttributes(file);

            // guard against the shell being closed before this runs
            if (shell.isDisposed())
                return;
            TableItem tableItem = new TableItem(table, 0);
            tableItem.setText(strings);
            tableItem.setImage(iconImage);
            tableItem.setData(TABLEITEMDATA_FILE, file);
            tableItem.setData(TABLEITEMDATA_CONNECTIONID, connectionId);

            if (attrs.length() > 0)
                tableItem.setData("TIP_TEXT", attrs);
        }
    });
}

From source file:org.codehaus.mojo.unix.core.CopyDirectoryOperation.java

public void perform(FileCollector fileCollector) throws IOException {
    Pattern pattern = this.pattern.isSome() ? Pattern.compile(this.pattern.some()._1()) : null;

    IncludeExcludeFileSelector selector = IncludeExcludeFileSelector.build(from.getName())
            .addStringIncludes(includes).addStringExcludes(excludes).create();

    List<FileObject> files = new ArrayList<FileObject>();
    from.findFiles(selector, true, files);

    for (FileObject f : files) {
        if (f.getName().getBaseName().equals("")) {
            continue;
        }/*from   w  w w  .  j a va 2  s .  c om*/

        String relativeName = from.getName().getRelativeName(f.getName());

        // Transform the path if the pattern is set. The input path will always have a leading slash
        // to make it possible to write more natural expressions.
        // With this one can write "/server-1.0.0/(.*)" => $1
        if (pattern != null) {
            String path = relativePath(relativeName).asAbsolutePath("/");
            relativeName = pattern.matcher(path).replaceAll(this.pattern.some()._2());
        }

        if (f.getType() == FileType.FILE) {
            fileCollector.addFile(f,
                    AssemblyOperationUtil.fromFileObject(to.add(relativeName), f, fileAttributes));
        } else if (f.getType() == FileType.FOLDER) {
            fileCollector.addDirectory(
                    AssemblyOperationUtil.dirFromFileObject(to.add(relativeName), f, directoryAttributes));
        }
    }
}

From source file:org.codehaus.mojo.unix.sysvpkg.prototype.PrototypeFileTest.java

public void testBasic() throws Exception {
    FileSystemManager fsManager = VFS.getManager();

    FileObject root = fsManager.resolveFile(getTestPath("target/prototype-test/assembly"));
    root.createFolder();/*  w  w  w. ja  va  2  s.co  m*/

    PrototypeFile prototypeFile = new PrototypeFile(defaultEntry);

    FileObject bashProfileObject = fsManager.resolveFile(getTestPath("src/test/non-existing/bash_profile"));
    FileObject extractJarObject = fsManager.resolveFile(getTestPath("src/test/non-existing/extract.jar"));
    UnixFsObject.RegularFile extractJar = regularFile(extractJarPath, dateTime, 0, some(fileAttributes));
    UnixFsObject.RegularFile bashProfile = regularFile(bashProfilePath, dateTime, 0, some(fileAttributes));
    UnixFsObject.RegularFile smfManifestXml = regularFile(smfManifestXmlPath, dateTime, 0,
            some(fileAttributes.addTag("class:smf")));

    prototypeFile.addFile(bashProfileObject, bashProfile);
    prototypeFile.addFile(extractJarObject, extractJar);
    prototypeFile.addFile(extractJarObject, smfManifestXml);
    prototypeFile.addDirectory(directory(BASE, dateTime, dirAttributes));
    prototypeFile.addDirectory(directory(specialPath, dateTime, dirAttributes));
    prototypeFile.apply(filter(extractJarPath, fileAttributes.user("funnyuser")));
    prototypeFile.apply(filter(specialPath, dirAttributes.group("funnygroup")));

    LineFile stream = new LineFile();

    prototypeFile.streamTo(stream);

    assertEquals(
            new LineFile()
                    .add("f none /extract.jar=" + extractJarObject.getName().getPath()
                            + " 0644 funnyuser nogroup")
                    .add("d none /opt ? default default").add("d none /opt/jetty ? default default")
                    .add("f none /opt/jetty/.bash_profile="
                            + bashProfileObject.getName().getPath() + " 0644 nouser nogroup")
                    .add("d none /smf ? default default")
                    .add("f smf /smf/manifest.xml=" + extractJarObject.getName().getPath()
                            + " 0644 nouser nogroup")
                    .add("d none /special 0755 nouser funnygroup").toString(),
            stream.toString());
}

From source file:org.codehaus.mojo.unix.util.vfs.IncludeExcludeFileSelector.java

public boolean includeFile(FileSelectInfo fileSelectInfo) throws Exception {
    FileObject fileObject = fileSelectInfo.getFile();
    FileName name = fileObject.getName();

    if (fileType != null && fileObject.getType() != fileType) {
        return false;
    }//from www .j  a v a  2s  . c  o  m

    String relativePath = root.getRelativeName(name);

    return matches(relativePath);
}

From source file:org.codehaus.mojo.unix.util.vfs.IncludeExcludeTest.java

public void testBasic() throws Exception {
    String myProjectPath = new TestUtil(this).getTestPath("src/test/resources/my-project");

    FileSystemManager fsManager = VFS.getManager();
    FileObject myProject = fsManager.resolveFile(myProjectPath);

    assertEquals(FileType.FOLDER, myProject.getType());

    List<FileObject> selection = new ArrayList<FileObject>();
    myProject.findFiles(IncludeExcludeFileSelector.build(myProject.getName())
            .addInclude(new PathExpression("/src/main/unix/files/**")).addInclude(new PathExpression("*.java"))
            .addExclude(new PathExpression("**/huge-file")).filesOnly().
            //            noDefaultExcludes().
            create(), true, selection);/*from  w  w  w.  j  a va 2 s .  co m*/

    System.out.println("Included:");
    for (FileObject fileObject : selection) {
        System.out.println(myProject.getName().getRelativeName(fileObject.getName()));
    }

    assertEquals(2, selection.size());
    assertTrue(selection.contains(myProject.resolveFile("src/main/unix/files/opt/comp/myapp/etc/myapp.conf")));
    assertTrue(selection.contains(myProject.resolveFile("Included.java")));
}

From source file:org.codehaus.mojo.unix.util.vfs.VfsUtil.java

public static File asFile(FileObject fileObject) {
    return new File(fileObject.getName().getPath());
}