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.docx4all.swing.text.WordMLEditorKit.java

/**
 * Creates a WordMLDocument from the given .docx file
 * /*w  ww . ja  v a2 s  . com*/
 * @param f  The file to read from
 * @exception IOException on any I/O error
 */
public WordMLDocument read(FileObject f) throws IOException {
    if (log.isDebugEnabled()) {
        log.debug("read(): File = " + VFSUtils.getFriendlyName(f.getName().getURI()));
    }

    //Default WordMLDocument has to be created prior to 
    //unmarshalling docx4j Document so that StyleDefinitionsPart's
    //liveStyles property will be populated correctly.
    //See: StyleDefinitionsPart.unmarshall(java.io.InputStream)
    WordMLDocument doc = (WordMLDocument) createDefaultDocument();
    List<ElementSpec> specs = DocUtil.getElementSpecs(ElementMLFactory.createDocumentML(f));
    doc.createElementStructure(specs);

    if (log.isDebugEnabled()) {
        DocUtil.displayStructure(specs);
        DocUtil.displayStructure(doc);
    }

    return doc;
}

From source file:org.docx4all.ui.main.WordMLApplet.java

private void openLocalFile(WordMLEditor editor, String urlParam) {
    ResourceMap rm = editor.getContext().getResourceMap(WordMLEditor.class);

    String localFileUrl = urlParam;
    if (System.getProperty("os.name").toLowerCase().startsWith("windows")) {
        if (urlParam.startsWith("file:///")) {
            ;//pass
        } else {/*from   ww  w.j  av  a 2  s.c o m*/
            localFileUrl = "file:///" + urlParam.substring(7);
        }
    }

    String errMsg = null;
    try {
        FileObject fo = VFSUtils.getFileSystemManager().resolveFile(urlParam);
        if (fo.exists()) {
            Preferences prefs = Preferences.userNodeForPackage(FileMenu.class);
            localFileUrl = fo.getName().getURI();
            prefs.put(Constants.LAST_OPENED_FILE, localFileUrl);
            prefs.put(Constants.LAST_OPENED_LOCAL_FILE, localFileUrl);
            PreferenceUtil.flush(prefs);
            log.info("\n\n Opening " + urlParam);
            editor.createInternalFrame(fo);
        } else {
            errMsg = rm.getString("Application.applet.initialisation.file.not.found.message", urlParam);
        }
    } catch (FileSystemException exc) {
        exc.printStackTrace();
        errMsg = rm.getString("Application.applet.initialisation.file.io.error.message", urlParam);
    }

    if (errMsg != null) {
        String title = rm.getString("Application.applet.initialisation.Action.text");
        editor.showMessageDialog(title, errMsg, JOptionPane.ERROR_MESSAGE);
    }
}

From source file:org.docx4all.ui.main.WordMLEditor.java

public void createInternalFrame(FileObject f) {
    if (f == null) {
        return;/*from w  w  w  . ja va2  s.  c  o m*/
    }

    log.info(VFSUtils.getFriendlyName(f.getName().getURI()));

    JInternalFrame iframe = _iframeMap.get(f.getName().getURI());
    if (iframe != null) {
        iframe.setVisible(true);

    } else {
        iframe = new JInternalFrame(f.getName().getBaseName(), true, true, true, true);
        iframe.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
        iframe.addInternalFrameListener(_internalFrameListener);
        iframe.addInternalFrameListener(_toolbarStates);
        iframe.addPropertyChangeListener(WindowMenu.getInstance());

        if (iframe.getUI() instanceof BasicInternalFrameUI) {
            BasicInternalFrameUI ui = (BasicInternalFrameUI) iframe.getUI();
            javax.swing.JComponent northPane = ui.getNorthPane();
            if (northPane == null) {
                // Happens on Mac OSX: Google for "osx java getNorthPane"
                // Fix is from it.businesslogic.ireport.gui.JMDIFrame
                javax.swing.plaf.basic.BasicInternalFrameUI aUI = new javax.swing.plaf.basic.BasicInternalFrameUI(
                        iframe);
                iframe.setUI(aUI);

                // Try again
                ui = (BasicInternalFrameUI) iframe.getUI();
                northPane = ((javax.swing.plaf.basic.BasicInternalFrameUI) ui).getNorthPane();
            }
            northPane.addMouseMotionListener(_titleBarMouseListener);
        }

        JEditorPane editorView = createEditorView(f);
        JPanel panel = FxScriptUIHelper.getInstance().createEditorPanel(editorView);

        iframe.getContentPane().add(panel);
        iframe.pack();
        _desktop.add(iframe);

        editorView.requestFocusInWindow();
        editorView.select(0, 0);

        String filePath = f.getName().getURI();
        iframe.putClientProperty(WordMLDocument.FILE_PATH_PROPERTY, filePath);
        _iframeMap.put(filePath, iframe);

        iframe.show();
    }

    try {
        iframe.setSelected(true);
        iframe.setIcon(false);
        iframe.setMaximum(true);
    } catch (PropertyVetoException exc) {
        // do nothing
    }
}

From source file:org.docx4all.ui.main.WordMLEditor.java

public void updateInternalFrame(FileObject oldFile, FileObject newFile) {
    if (oldFile.equals(newFile)) {
        return;//from   w  w  w  .j a  v a2s . co  m
    }

    String fileUri = oldFile.getName().getURI();
    JInternalFrame iframe = _iframeMap.remove(fileUri);
    if (iframe != null) {
        fileUri = newFile.getName().getURI();
        iframe.putClientProperty(WordMLDocument.FILE_PATH_PROPERTY, fileUri);
        iframe.setTitle(newFile.getName().getBaseName());
    }
}

From source file:org.docx4all.ui.main.WordMLEditor.java

private JEditorPane createEditorView(FileObject f) {
    String fileUri = f.getName().getURI();

    WordMLTextPane editorView = new WordMLTextPane();
    editorView.addFocusListener(_toolbarStates);
    editorView.addCaretListener(_toolbarStates);
    editorView.setTransferHandler(new TransferHandler());

    WordMLEditorKit editorKit = (WordMLEditorKit) editorView.getEditorKit();
    editorKit.addInputAttributeListener(_toolbarStates);

    WordMLDocument doc = null;//w  w w  .  j ava 2 s.  com

    try {
        if (f.exists()) {
            doc = editorKit.read(f);
        }
    } catch (Exception exc) {
        exc.printStackTrace();

        ResourceMap rm = getContext().getResourceMap();
        String title = rm.getString(Constants.INIT_EDITOR_VIEW_IO_ERROR_DIALOG_TITLE);
        StringBuffer msg = new StringBuffer();
        msg.append(rm.getString(Constants.INIT_EDITOR_VIEW_IO_ERROR_MESSAGE));
        msg.append(Constants.NEWLINE);
        msg.append(VFSUtils.getFriendlyName(fileUri));
        showMessageDialog(title, msg.toString(), JOptionPane.ERROR_MESSAGE);
        doc = null;
    }

    if (doc == null) {
        doc = (WordMLDocument) editorKit.createDefaultDocument();
    }

    doc.putProperty(WordMLDocument.FILE_PATH_PROPERTY, fileUri);
    doc.addDocumentListener(_toolbarStates);
    doc.setDocumentFilter(new WordMLDocumentFilter());
    editorView.setDocument(doc);
    editorView.putClientProperty(Constants.LOCAL_VIEWS_SYNCHRONIZED_FLAG, Boolean.TRUE);

    if (DocUtil.isSharedDocument(doc)) {
        editorKit.initPlutextClient(editorView);
    }

    return editorView;
}

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

@Action
public void openFile(ActionEvent actionEvent) {
    Preferences prefs = Preferences.userNodeForPackage(getClass());
    WordMLEditor editor = WordMLEditor.getInstance(WordMLEditor.class);
    ResourceMap rm = editor.getContext().getResourceMap(WordMLEditor.class);

    String lastFileUri = prefs.get(Constants.LAST_OPENED_FILE, Constants.EMPTY_STRING);
    FileObject dir = null;// w  w  w  . j a  v a  2 s. co m
    if (lastFileUri.length() > 0) {
        try {
            dir = VFSUtils.getFileSystemManager().resolveFile(lastFileUri).getParent();
        } catch (FileSystemException exc) {
            dir = null;
        }
    }

    VFSJFileChooser chooser = createFileChooser(rm, dir, Constants.DOCX_STRING);

    RETURN_TYPE returnVal = chooser.showOpenDialog((Component) actionEvent.getSource());

    if (returnVal == RETURN_TYPE.APPROVE) {
        FileObject file = getSelectedFile(chooser, Constants.DOCX_STRING);
        if (file != null) {
            lastFileUri = file.getName().getURI();

            prefs.put(Constants.LAST_OPENED_FILE, lastFileUri);
            if (file.getName().getScheme().equals(("file"))) {
                prefs.put(Constants.LAST_OPENED_LOCAL_FILE, lastFileUri);
            }
            PreferenceUtil.flush(prefs);
            log.info("\n\n Opening " + VFSUtils.getFriendlyName(lastFileUri));
            editor.createInternalFrame(file);
        }
    }
}

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 {/*  ww  w  . j ava  2  s  .co  m*/

            //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

/**
 * If user types in a filename JFileChooser does not append the file extension
 * displayed by its FileFilter to it.//from   ww  w. ja  v  a  2 s.  c om
 * This method appends desiredFileType parameter as file extension
 * if JFileChooser's selected file does not have it.
 * 
 * @param chooser JFileChooser instance
 * @param desiredFileType File extension
 * @return a File whose extension is desiredFileType.
 */
public FileObject getSelectedFile(VFSJFileChooser chooser, String desiredFileType) {
    FileObject theFile = chooser.getSelectedFile();

    StringBuffer uri = new StringBuffer(theFile.getName().getURI());
    if (desiredFileType.equalsIgnoreCase(theFile.getName().getExtension())) {
        //user may type in the file extension in the JFileChooser dialog.
        //Therefore worth checking file extension case insensitively
        //          int dot = uri.lastIndexOf(Constants.DOT);
        //          uri = new StringBuffer(uri.substring(0, dot));

        // Do nothing

    } else if (Constants.DOCX_STRING.equals(desiredFileType) // also allow .xml
            && Constants.FLAT_OPC_STRING.equalsIgnoreCase(theFile.getName().getExtension())) {

        // Do nothing

    } else {
        uri.append(Constants.DOT);
        uri.append(desiredFileType);
    }
    try {
        theFile = VFSUtils.getFileSystemManager().resolveFile(uri.toString());
    } catch (FileSystemException exc) {
        exc.printStackTrace();
        theFile = null;
    }

    return theFile;
}

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  ww w. ja v  a2 s . com*/
    }

    file.createFile();
}

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

private boolean createInFileSystem(FileObject fo, WordprocessingMLPackage source) throws FileSystemException {
    boolean success = false;

    WordprocessingMLPackage newPack = createNewEmptyPackage(source);
    if (newPack != null) {
        String targetPath = fo.getName().getURI();
        FileMenu.getInstance().createInFileSystem(fo);
        success = FileMenu.getInstance().save(newPack, targetPath, OPEN_LINKED_DOCUMENT_ACTION_NAME);
        if (!success) {
            fo.delete();/*from  w w w  .j ava2 s.c om*/
        }
    }

    return success;
}