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

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

Introduction

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

Prototype

public FileObject getParent() throws FileSystemException;

Source Link

Document

Returns the folder that contains 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
 * //  ww w. jav a2 s  .  c  o m
 * @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)
 *//*ww  w .j av a2s .  com*/
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.codehaus.mojo.unix.core.FsFileCollector.java

private Callable packageFile(final FileObject from, final UnixFsObject.RegularFile to) {
    return new Callable() {
        public Object call() throws Exception {
            FileObject toFile = root.resolveFile(to.path.string);

            toFile.getParent().createFolder();
            toFile.copyFrom(from, Selectors.SELECT_SELF);
            toFile.getContent().setLastModifiedTime(to.lastModified.toDateTime().toDate().getTime());
            return Unit.unit();
        }// w  w  w.j a  v  a2 s.  c  o  m
    };
}

From source file:org.codehaus.mojo.unix.maven.sysvpkg.PkgUnixPackage.java

public FileObject fromFile(final FileObject fromFile, UnixFsObject.RegularFile file)
        throws FileSystemException {
    // If it is a file on the local file system, just point the entry in the prototype file to it
    if (fromFile.getFileSystem() instanceof LocalFileSystem) {
        return fromFile;
    }//from  ww w  .  java 2  s  . com

    // Creates a file under the working directory that should match the destination path
    final FileObject tmpFile = workingDirectory.resolveFile(file.path.string);

    operations = operations.cons(new Callable() {
        public Object call() throws Exception {
            OutputStream outputStream = null;
            try {
                tmpFile.getParent().createFolder();
                tmpFile.copyFrom(fromFile, Selectors.SELECT_ALL);
                tmpFile.getContent().setLastModifiedTime(fromFile.getContent().getLastModifiedTime());
            } finally {
                IOUtil.close(outputStream);
            }

            return Unit.unit();
        }
    });

    return tmpFile;
}

From source file:org.docx4all.ui.menu.FileMenu.java

private RETURN_TYPE saveAsFile(String callerActionName, ActionEvent actionEvent, String fileType) {
    Preferences prefs = Preferences.userNodeForPackage(getClass());
    WordMLEditor editor = WordMLEditor.getInstance(WordMLEditor.class);
    ResourceMap rm = editor.getContext().getResourceMap(getClass());

    JInternalFrame iframe = editor.getCurrentInternalFrame();
    String oldFilePath = (String) iframe.getClientProperty(WordMLDocument.FILE_PATH_PROPERTY);

    VFSJFileChooser chooser = createFileChooser(rm, callerActionName, iframe, fileType);

    RETURN_TYPE returnVal = chooser.showSaveDialog((Component) actionEvent.getSource());
    if (returnVal == RETURN_TYPE.APPROVE) {
        FileObject selectedFile = getSelectedFile(chooser, fileType);

        boolean error = false;
        boolean newlyCreatedFile = false;

        if (selectedFile == null) {

            // Should never happen, whether the file exists or not

        } else {//from  w w w  .jav a2  s .  c om

            //Check selectedFile's existence and ask user confirmation when needed.
            try {
                boolean selectedFileExists = selectedFile.exists();
                if (!selectedFileExists) {
                    FileObject parent = selectedFile.getParent();
                    String uri = UriParser.decode(parent.getName().getURI());

                    if (System.getProperty("os.name").toUpperCase().indexOf("WINDOWS") > -1
                            && parent.getName().getScheme().startsWith("file") && !parent.isWriteable()
                            && (uri.indexOf("/Documents") > -1 || uri.indexOf("/My Documents") > -1)) {
                        //TODO: Check whether we still need this workaround.
                        //See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4939819
                        //Re: File.canWrite() returns false for the "My Documents" directory (win)
                        String localpath = org.docx4j.utils.VFSUtils.getLocalFilePath(parent);
                        File f = new File(localpath);
                        f.setWritable(true, true);
                    }

                    selectedFile.createFile();
                    newlyCreatedFile = true;

                } else if (!selectedFile.getName().getURI().equalsIgnoreCase(oldFilePath)) {
                    String title = rm.getString(callerActionName + ".Action.text");
                    String message = VFSUtils.getFriendlyName(selectedFile.getName().getURI()) + "\n"
                            + rm.getString(callerActionName + ".Action.confirmMessage");
                    int answer = editor.showConfirmDialog(title, message, JOptionPane.YES_NO_OPTION,
                            JOptionPane.QUESTION_MESSAGE);
                    if (answer != JOptionPane.YES_OPTION) {
                        selectedFile = null;
                    }
                } // if (!selectedFileExists)

            } catch (FileSystemException exc) {
                exc.printStackTrace();//ignore
                log.error("Couldn't create new file or assure file existence. File = "
                        + selectedFile.getName().getURI());
                selectedFile = null;
                error = true;
            }
        }

        //Check whether there has been an error, cancellation by user
        //or may proceed to saving file.
        if (selectedFile != null) {
            //Proceed to saving file
            String selectedPath = selectedFile.getName().getURI();
            if (log.isDebugEnabled()) {
                log.debug("saveAsFile(): selectedFile = " + VFSUtils.getFriendlyName(selectedPath));
            }

            prefs.put(Constants.LAST_OPENED_FILE, selectedPath);
            if (selectedFile.getName().getScheme().equals("file")) {
                prefs.put(Constants.LAST_OPENED_LOCAL_FILE, selectedPath);
            }
            PreferenceUtil.flush(prefs);

            boolean success = false;
            if (EXPORT_AS_NON_SHARED_DOC_ACTION_NAME.equals(callerActionName)) {
                log.info("saveAsFile(): Exporting as non shared document to "
                        + VFSUtils.getFriendlyName(selectedPath));
                success = export(iframe, selectedPath, callerActionName);
                if (success) {
                    prefs.put(Constants.LAST_OPENED_FILE, selectedPath);
                    if (selectedPath.startsWith("file:")) {
                        prefs.put(Constants.LAST_OPENED_LOCAL_FILE, selectedPath);
                    }
                    PreferenceUtil.flush(prefs);
                    log.info("saveAsFile(): Opening " + VFSUtils.getFriendlyName(selectedPath));
                    editor.createInternalFrame(selectedFile);
                }
            } else {
                success = save(iframe, selectedPath, callerActionName);
                if (success) {
                    if (Constants.DOCX_STRING.equals(fileType) || Constants.FLAT_OPC_STRING.equals(fileType)) {
                        //If saving as .docx then update the document dirty flag 
                        //of toolbar states as well as internal frame title.
                        editor.getToolbarStates().setDocumentDirty(iframe, false);
                        editor.getToolbarStates().setLocalEditsEnabled(iframe, false);
                        FileObject file = null;
                        try {
                            file = VFSUtils.getFileSystemManager().resolveFile(oldFilePath);
                            editor.updateInternalFrame(file, selectedFile);
                        } catch (FileSystemException exc) {
                            ;//ignore
                        }
                    } else {
                        //Because document dirty flag is not cleared
                        //and internal frame title is not changed,
                        //we present a success message.
                        String title = rm.getString(callerActionName + ".Action.text");
                        String message = VFSUtils.getFriendlyName(selectedPath) + "\n"
                                + rm.getString(callerActionName + ".Action.successMessage");
                        editor.showMessageDialog(title, message, JOptionPane.INFORMATION_MESSAGE);
                    }
                }
            }

            if (!success && newlyCreatedFile) {
                try {
                    selectedFile.delete();
                } catch (FileSystemException exc) {
                    log.error("saveAsFile(): Saving failure and cannot remove the newly created file = "
                            + selectedPath);
                    exc.printStackTrace();
                }
            }
        } else if (error) {
            log.error("saveAsFile(): selectedFile = NULL");
            String title = rm.getString(callerActionName + ".Action.text");
            String message = rm.getString(callerActionName + ".Action.errorMessage");
            editor.showMessageDialog(title, message, JOptionPane.ERROR_MESSAGE);
        }

    } //if (returnVal == JFileChooser.APPROVE_OPTION)

    return returnVal;
}

From source file:org.docx4all.ui.menu.FileMenu.java

private VFSJFileChooser createFileChooser(ResourceMap resourceMap, String callerActionName,
        JInternalFrame iframe, String filteredFileExtension) {

    String filePath = null;/*  w  w w. j a  va2  s.  c o  m*/
    if (EXPORT_AS_SHARED_DOC_ACTION_NAME.equals(callerActionName)) {
        Preferences prefs = Preferences.userNodeForPackage(getClass());
        filePath = prefs.get(Constants.LAST_OPENED_FILE, Constants.EMPTY_STRING);
    } else {
        filePath = (String) iframe.getClientProperty(WordMLDocument.FILE_PATH_PROPERTY);
    }

    FileObject file = null;
    FileObject dir = null;
    try {
        file = VFSUtils.getFileSystemManager().resolveFile(filePath);
        dir = file.getParent();
    } catch (FileSystemException exc) {
        ;//ignore
    }

    return createFileChooser(resourceMap, dir, filteredFileExtension);
}

From source file:org.docx4all.ui.menu.FileMenu.java

public void createInFileSystem(FileObject file) throws FileSystemException {
    FileObject parent = file.getParent();
    String uri = UriParser.decode(parent.getName().getURI());

    if (System.getProperty("os.name").toUpperCase().indexOf("WINDOWS") > -1
            && parent.getName().getScheme().startsWith("file") && !parent.isWriteable()
            && (uri.indexOf("/Documents") > -1 || uri.indexOf("/My Documents") > -1)) {
        //TODO: Check whether we still need this workaround.
        //See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4939819
        //Re: File.canWrite() returns false for the "My Documents" directory (win)
        String localpath = org.docx4j.utils.VFSUtils.getLocalFilePath(parent);
        File f = new File(localpath);
        f.setWritable(true, true);/*from  w  w w .  j ava  2 s.c  o m*/
    }

    file.createFile();
}

From source file:org.docx4all.xml.HyperlinkML.java

public final static String encodeTarget(HyperlinkML ml, FileObject sourceFile, boolean inFriendlyFormat) {
    String target = ml.getTarget();
    if (target == null) {
        return null;
    }//from   ww w  .  ja  v a 2  s.  c  o  m

    target = target.replace('\\', '/');
    int idx = target.indexOf("://");
    if (idx > 0) {
        //if protocol is specified, directly construct 
        //target by decoding it
        try {
            target = URLDecoder.decode(target, "UTF-8");
        } catch (UnsupportedEncodingException exc) {
            //should not happen
        }

        if (inFriendlyFormat) {
            //target should already be in friendly format.
        } else if (sourceFile != null) {
            String sourcePath = sourceFile.getName().getURI();
            if (sourcePath.startsWith("file://") || target.startsWith("file://")) {
                //either sourcePath or target is local.
                //No need for user credentials
            } else {
                VFSURIParser parser = new VFSURIParser(sourcePath, false);
                String username = parser.getUsername();
                String password = parser.getPassword();

                StringBuilder sb = new StringBuilder();
                sb.append(target.substring(0, idx + 3));
                sb.append(username);
                sb.append(":");
                sb.append(password);
                sb.append("@");
                sb.append(target.substring(idx + 3));
            }
        }
    } else if (sourceFile != null) {
        //protocol is NOT specified in target.
        //Construct target by appending target to 
        //sourceFile directory.
        String base = null;
        try {
            base = sourceFile.getParent().getName().getURI();
        } catch (FileSystemException exc) {
            ;//ignore
        }
        if (base != null) {
            if (inFriendlyFormat) {
                base = VFSUtils.getFriendlyName(base, false);
            }

            StringBuilder sb = new StringBuilder();
            sb.append(base.replace('\\', '/'));
            if (!base.endsWith("/")) {
                sb.append("/");
            }
            if (target.startsWith("/")) {
                target = target.substring(1);
            }
            sb.append(target);
            target = sb.toString();
        }
    }

    return target;
}

From source file:org.efaps.webdav4vfs.handler.AbstractCopyMoveBaseHandler.java

/**
 * Handle a COPY or MOVE request.//w w w .  j a  v  a 2s  . c  o  m
 *
 * @param _request      HTTP servlet request
 * @param _response     HTTP servlet response
 * @throws IOException if there is an error executing this request
 */
@Override
public void service(final HttpServletRequest _request, final HttpServletResponse _response) throws IOException {
    boolean overwrite = getOverwrite(_request);
    FileObject object = VFSBackend.resolveFile(_request.getPathInfo());
    FileObject targetObject = getDestination(_request);

    try {
        final LockManager lockManager = LockManager.getInstance();
        LockManager.EvaluationResult evaluation = lockManager.evaluateCondition(targetObject, getIf(_request));
        if (!evaluation.result) {
            _response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        }
        if ("MOVE".equals(_request.getMethod())) {
            evaluation = lockManager.evaluateCondition(object, getIf(_request));
            if (!evaluation.result) {
                _response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                return;
            }
        }
    } catch (LockException e) {
        _response.sendError(SC_LOCKED);
        return;
    } catch (ParseException e) {
        _response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    if (null == targetObject) {
        _response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    if (object.equals(targetObject)) {
        _response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    if (targetObject.exists()) {
        if (!overwrite) {
            _response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        }
        _response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    } else {
        FileObject targetParent = targetObject.getParent();
        if (!targetParent.exists() || !FileType.FOLDER.equals(targetParent.getType())) {
            _response.sendError(HttpServletResponse.SC_CONFLICT);
        }
        _response.setStatus(HttpServletResponse.SC_CREATED);
    }

    // delegate the actual execution to a sub class
    this.copyOrMove(object, targetObject, getDepth(_request));
}

From source file:org.efaps.webdav4vfs.handler.MkColHandler.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    BufferedReader bufferedReader = request.getReader();
    String line = bufferedReader.readLine();
    if (line != null) {
        response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
        return;/*from  w  w w  .j  a  va 2 s  .co  m*/
    }

    FileObject object = VFSBackend.resolveFile(request.getPathInfo());

    try {
        if (!LockManager.getInstance().evaluateCondition(object, getIf(request)).result) {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        }
    } catch (LockException e) {
        response.sendError(SC_LOCKED);
        return;
    } catch (ParseException e) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    if (object.exists()) {
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    }

    if (!object.getParent().exists() || !FileType.FOLDER.equals(object.getParent().getType())) {
        response.sendError(HttpServletResponse.SC_CONFLICT);
        return;
    }

    try {
        object.createFolder();
        response.setStatus(HttpServletResponse.SC_CREATED);
    } catch (FileSystemException e) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    }
}