Example usage for javax.swing.text Document getProperty

List of usage examples for javax.swing.text Document getProperty

Introduction

In this page you can find the example usage for javax.swing.text Document getProperty.

Prototype

public Object getProperty(Object key);

Source Link

Document

Gets the properties associated with the document.

Usage

From source file:MyDocumentListener.java

public void updateLog(DocumentEvent e, String action) {
    Document doc = (Document) e.getDocument();
    int changeLength = e.getLength();
    System.out.println(changeLength + " character" + ((changeLength == 1) ? " " : "s ") + action + " "
            + doc.getProperty("name") + "." + newline + "  Text length = " + doc.getLength() + newline);
}

From source file:EditorPaneExample10A.java

public URL[] findLinks(Document doc, String protocol) {
    Vector links = new Vector();
    Vector urlNames = new Vector();
    URL baseURL = (URL) doc.getProperty(Document.StreamDescriptionProperty);

    if (doc instanceof HTMLDocument) {
        HTMLDocument.Iterator iterator = ((HTMLDocument) doc).getIterator(HTML.Tag.A);
        for (; iterator.isValid(); iterator.next()) {
            AttributeSet attrs = iterator.getAttributes();
            Object linkAttr = attrs.getAttribute(HTML.Attribute.HREF);
            if (linkAttr instanceof String) {
                try {
                    URL linkURL = new URL(baseURL, (String) linkAttr);
                    if (protocol == null || protocol.equalsIgnoreCase(linkURL.getProtocol())) {
                        String linkURLName = linkURL.toString();
                        if (urlNames.contains(linkURLName) == false) {
                            urlNames.addElement(linkURLName);
                            links.addElement(linkURL);
                        }//from   ww w.  j a  v a  2 s. c  o m
                    }
                } catch (MalformedURLException e) {
                    // Ignore invalid links
                }
            }
        }
    }

    URL[] urls = new URL[links.size()];
    links.copyInto(urls);
    links.removeAllElements();
    urlNames.removeAllElements();

    return urls;
}

From source file:EditorPaneExample16.java

public TreeNode buildHeadingTree(Document doc) {
    String title = (String) doc.getProperty(Document.TitleProperty);
    if (title == null) {
        title = "[No title]";
    }/*from  ww  w .java  2s . co m*/
    Heading rootHeading = new Heading(title, 0, 0);
    DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(rootHeading);

    DefaultMutableTreeNode lastNode[] = new DefaultMutableTreeNode[7];
    int lastLevel = 0;
    lastNode[lastLevel] = rootNode;

    if (doc instanceof HTMLDocument) {
        Element elem = doc.getDefaultRootElement();
        ElementIterator iterator = new ElementIterator(elem);
        Heading heading;

        while ((heading = getNextHeading(doc, iterator)) != null) {
            // Add the node to the tree
            DefaultMutableTreeNode hNode = new DefaultMutableTreeNode(heading);
            int level = heading.getLevel();

            if (level > lastLevel) {
                for (int i = lastLevel + 1; i < level; i++) {
                    lastNode[i] = null;
                }
                lastNode[lastLevel].add(hNode);
            } else {
                int prevLevel = level - 1;
                while (prevLevel >= 0) {
                    if (lastNode[prevLevel] != null) {
                        break;
                    }
                    lastNode[prevLevel] = null;
                    prevLevel--;
                }
                lastNode[prevLevel].add(hNode);
            }
            lastNode[level] = hNode;
            lastLevel = level;
        }
    }
    return rootNode;
}

From source file:EditorPaneExample16.java

public URL[] findLinks(Document doc, String protocol) {
    Vector links = new Vector();
    Vector urlNames = new Vector();
    URL baseURL = (URL) doc.getProperty(Document.StreamDescriptionProperty);

    if (doc instanceof HTMLDocument) {
        Element elem = doc.getDefaultRootElement();
        ElementIterator iterator = new ElementIterator(elem);

        while ((elem = iterator.next()) != null) {
            AttributeSet attrs = elem.getAttributes();
            Object link = attrs.getAttribute(HTML.Tag.A);
            if (link instanceof AttributeSet) {
                Object linkAttr = ((AttributeSet) link).getAttribute(HTML.Attribute.HREF);
                if (linkAttr instanceof String) {
                    try {
                        URL linkURL = new URL(baseURL, (String) linkAttr);
                        if (protocol == null || protocol.equalsIgnoreCase(linkURL.getProtocol())) {
                            String linkURLName = linkURL.toString();
                            if (urlNames.contains(linkURLName) == false) {
                                urlNames.addElement(linkURLName);
                                links.addElement(linkURL);
                            }//w  w w.  j  ava2 s  .c  o m
                        }
                    } catch (MalformedURLException e) {
                        // Ignore invalid links
                    }
                }
            }
        }
    }

    URL[] urls = new URL[links.size()];
    links.copyInto(urls);
    links.removeAllElements();
    urlNames.removeAllElements();

    return urls;
}

From source file:com.hexidec.ekit.component.RelativeImageView.java

/** Checks to see if the absolute path is availabe thru an application
  * global static variable or thru a system variable. If so, appends
  * the relative path to the absolute path and returns the String.
  *///  w  w w . ja  v a2 s. c o m
private String processSrcPath(String src) {
    String val = src;
    File imageFile = new File(src);
    if (imageFile.isAbsolute()) {
        return src;
    }
    boolean found = false;
    Document doc = getDocument();
    if (doc != null) {
        String pv = (String) doc.getProperty("com.hexidec.ekit.docsource");
        if (pv != null) {
            File f = new File(pv);
            val = (new File(f.getParent(), imageFile.getPath().toString())).toString();
            found = true;
        }
    }
    if (!found) {
        String imagePath = System.getProperty("system.image.path.key");
        if (imagePath != null) {
            val = (new File(imagePath, imageFile.getPath())).toString();
        }
    }
    return val;
}

From source file:org.apache.syncope.ide.netbeans.view.ResourceExplorerTopComponent.java

private void saveContent() {
    try {/*  w  w  w  .j a  v  a2 s. com*/
        JTextComponent ed = EditorRegistry.lastFocusedComponent();
        Document document = ed.getDocument();
        String content = document.getText(0, document.getLength());
        String path = (String) document.getProperty(Document.TitleProperty);
        String[] temp = path.split(File.separator);
        String name = temp[temp.length - 1];
        String templateType = temp[temp.length - 2];
        temp = name.split("\\.");
        String format = temp[1];
        String key = temp[0];

        if (templateType.equals("Mail")) {
            if (format.equals("txt")) {
                mailTemplateManagerService.setFormat(key, MailTemplateFormat.TEXT,
                        IOUtils.toInputStream(content, encodingPattern));
            } else {
                mailTemplateManagerService.setFormat(key, MailTemplateFormat.HTML,
                        IOUtils.toInputStream(content, encodingPattern));
            }
        } else if (format.equals("html")) {
            reportTemplateManagerService.setFormat(key, ReportTemplateFormat.HTML,
                    IOUtils.toInputStream(content, encodingPattern));
        } else if (format.equals("fo")) {
            reportTemplateManagerService.setFormat(key, ReportTemplateFormat.FO,
                    IOUtils.toInputStream(content, encodingPattern));
        } else {
            reportTemplateManagerService.setFormat(key, ReportTemplateFormat.CSV,
                    IOUtils.toInputStream(content, encodingPattern));
        }
    } catch (BadLocationException e) {
        Exceptions.printStackTrace(e);
    }
}

From source file:org.debux.webmotion.netbeans.Utils.java

public static FileObject getFO(Document doc) {
    Object sdp = doc.getProperty(Document.StreamDescriptionProperty);
    if (sdp instanceof FileObject) {
        return (FileObject) sdp;
    }//from   w  ww  .j  a  v  a 2  s . c o m
    if (sdp instanceof DataObject) {
        DataObject dobj = (DataObject) sdp;
        return dobj.getPrimaryFile();
    }
    return null;
}

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

@Action
public void printPreview() {
    WordMLEditor wmlEditor = WordMLEditor.getInstance(WordMLEditor.class);
    JEditorPane editor = wmlEditor.getCurrentEditor();

    WordMLEditorKit kit = (WordMLEditorKit) editor.getEditorKit();
    kit.saveCaretText();//  w w w.j a  v  a 2  s .  c om

    Document doc = editor.getDocument();
    String filePath = (String) doc.getProperty(WordMLDocument.FILE_PATH_PROPERTY);
    DocumentElement elem = (DocumentElement) doc.getDefaultRootElement();
    DocumentML rootML = (DocumentML) elem.getElementML();

    //Do not include the last paragraph when saving or printing.
    //we'll put it back when the job is done.
    elem = (DocumentElement) elem.getElement(elem.getElementCount() - 1);
    ElementML paraML = elem.getElementML();
    ElementML bodyML = paraML.getParent();
    paraML.delete();

    try {
        WordprocessingMLPackage wordMLPackage = rootML.getWordprocessingMLPackage();

        //         XmlPackage worker = new XmlPackage(wordMLPackage);         
        //         org.docx4j.xmlPackage.Package result = worker.get();         
        //         boolean suppressDeclaration = true;
        //         boolean prettyprint = true;         
        //         System.out.println( 
        //               org.docx4j.XmlUtils.
        //                  marshaltoString(result, suppressDeclaration, prettyprint, 
        //                        org.docx4j.jaxb.Context.jcXmlPackage) );

        //Create temporary .pdf file.
        //Remember that filePath is in Commons-VFS format which
        //uses '/' as separator char.
        String tmpName = filePath.substring(filePath.lastIndexOf("/"), filePath.lastIndexOf(Constants.DOT));
        File tmpFile = File.createTempFile(tmpName + ".tmp", ".pdf");
        // Delete the temporary file when program exits.
        tmpFile.deleteOnExit();

        OutputStream os = new java.io.FileOutputStream(tmpFile);

        // Could write to a ByteBuffer and avoid the temp file if:
        // 1. com.sun.pdfview.PDFViewer had an appropriate open method
        // 2. We knew how big to make the buffer
        // java.nio.ByteBuffer buf = java.nio.ByteBuffer.allocate(15000);
        // //15kb
        // OutputStream os = newOutputStream(buf);

        PdfConversion c = new org.docx4j.convert.out.pdf.viaXSLFO.Conversion(wordMLPackage);
        // can change from viaHTML to viaIText or viaXSLFO
        PdfSettings settings = new PdfSettings();
        c.output(os, settings);

        os.close();

        PDFViewer pv = new PDFViewer(true);
        // pv.openFile(buf, "some name"); // requires modified
        // com.sun.pdfview.PDFViewer
        pv.openFile(tmpFile);

    } catch (Exception exc) {
        exc.printStackTrace();
        ResourceMap rm = wmlEditor.getContext().getResourceMap(getClass());
        String title = rm.getString(PRINT_PREVIEW_ACTION_NAME + ".Action.text");
        String message = rm.getString(PRINT_PREVIEW_ACTION_NAME + ".Action.errorMessage") + "\n"
                + VFSUtils.getFriendlyName(filePath);
        wmlEditor.showMessageDialog(title, message, JOptionPane.ERROR_MESSAGE);

    } finally {
        //Remember to put 'paraML' as last paragraph
        bodyML.addChild(paraML);
    }

}

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

/**
 * Saves editor documents to a file.// w ww . jav  a  2 s. c  o  m
 * 
 * Internal frame may have two editors for presenting two different views
 * to user namely editor view and source view. WordMLTextPane is used for 
 * editor view and JEditorPane for source view.
 * The contents of these two editors are synchronized when user switches
 * from one view to the other. Therefore, there will be ONLY ONE editor 
 * that is dirty and has to be saved by this method.
 * 
 * @param iframe
 * @param saveAsFilePath
 * @param callerActionName
 * @return
 */
public boolean save(JInternalFrame iframe, String saveAsFilePath, String callerActionName) {
    boolean success = true;

    if (saveAsFilePath == null) {
        saveAsFilePath = (String) iframe.getClientProperty(WordMLDocument.FILE_PATH_PROPERTY);
    }

    if (log.isDebugEnabled()) {
        log.debug("save(): filePath=" + VFSUtils.getFriendlyName(saveAsFilePath));
    }

    WordMLTextPane editorView = SwingUtil.getWordMLTextPane(iframe);
    JEditorPane sourceView = SwingUtil.getSourceEditor(iframe);

    if (sourceView != null && !((Boolean) sourceView.getClientProperty(Constants.LOCAL_VIEWS_SYNCHRONIZED_FLAG))
            .booleanValue()) {
        //signifies that Source View is not synchronised with Editor View yet.
        //Therefore, it is dirty and has to be saved.
        if (editorView != null && editorView.getWordMLEditorKit().getPlutextClient() != null) {
            //Document has to be saved from editor view 
            //by committing local edits
            success = false;
        } else {
            EditorKit kit = sourceView.getEditorKit();
            Document doc = sourceView.getDocument();
            WordprocessingMLPackage wmlPackage = (WordprocessingMLPackage) doc
                    .getProperty(WordMLDocument.WML_PACKAGE_PROPERTY);

            DocUtil.write(kit, doc, wmlPackage);
            success = save(wmlPackage, saveAsFilePath, callerActionName);

            if (success) {
                if (saveAsFilePath.endsWith(Constants.DOCX_STRING)
                        || saveAsFilePath.endsWith(Constants.FLAT_OPC_STRING)) {
                    doc.putProperty(WordMLDocument.FILE_PATH_PROPERTY, saveAsFilePath);
                    iframe.putClientProperty(WordMLDocument.FILE_PATH_PROPERTY, saveAsFilePath);
                }
            }
        }
        return success;
    }
    sourceView = null;

    if (editorView == null) {
        ;//pass

    } else if (editorView.getWordMLEditorKit().getPlutextClient() != null) {
        if (saveAsFilePath.equals(editorView.getDocument().getProperty(WordMLDocument.FILE_PATH_PROPERTY))) {
            success = commitLocalChanges(editorView, callerActionName);

        } else {
            //TODO: Enable saving Plutext document as a new file.
            WordMLEditor wmlEditor = WordMLEditor.getInstance(WordMLEditor.class);
            ResourceMap rm = wmlEditor.getContext().getResourceMap(getClass());
            String title = rm.getString(callerActionName + ".Action.text");
            StringBuilder message = new StringBuilder();
            message.append("File ");
            message.append(saveAsFilePath);
            message.append(Constants.NEWLINE);
            message.append(rm.getString(callerActionName + ".Action.wrong.fileName.infoMessage"));
            wmlEditor.showMessageDialog(title, message.toString(), JOptionPane.INFORMATION_MESSAGE);

            success = false;
        }
    } else {
        WordMLEditorKit kit = (WordMLEditorKit) editorView.getEditorKit();
        kit.saveCaretText();

        Document doc = editorView.getDocument();
        DocumentElement elem = (DocumentElement) doc.getDefaultRootElement();
        DocumentML rootML = (DocumentML) elem.getElementML();

        //Do not include the last paragraph when saving.
        //After saving we put it back.
        elem = (DocumentElement) elem.getElement(elem.getElementCount() - 1);
        ElementML paraML = elem.getElementML();
        ElementML bodyML = paraML.getParent();
        paraML.delete();

        success = save(rootML.getWordprocessingMLPackage(), saveAsFilePath, callerActionName);

        //Remember to put 'paraML' as last paragraph
        bodyML.addChild(paraML);

        if (success) {
            if (saveAsFilePath.endsWith(Constants.DOCX_STRING)) {
                doc.putProperty(WordMLDocument.FILE_PATH_PROPERTY, saveAsFilePath);
                iframe.putClientProperty(WordMLDocument.FILE_PATH_PROPERTY, saveAsFilePath);
            }
        }
    }

    return success;
}

From source file:org.photovault.swingui.PhotoInfoEditor.java

/**
 DocumentEvent is generated when text field (or to be more exact, its 
 document) is modified.//  www  . ja v a2s  . c o m
 @param ev The DocumentEvent describing the change.
 */
public void insertUpdate(DocumentEvent ev) {
    Document changedDoc = ev.getDocument();
    PhotoInfoFields changedField = (PhotoInfoFields) changedDoc.getProperty(FIELD);
    Set fieldValues = ctrl.getFieldValues(changedField);
    /* Avoid emptying model when the field has multiple values
       in the model.
    */
    Object value = getField(changedField);
    StringBuffer debugMsg = new StringBuffer();
    debugMsg.append("insertUpdate ").append(changedField).append(": ").append(value);
    debugMsg.append("\nOld values: [");
    boolean first = true;
    for (Object oldValue : fieldValues) {
        if (!first)
            debugMsg.append(", ");
        debugMsg.append(oldValue);
        first = false;
    }
    debugMsg.append("]");
    log.debug(debugMsg.toString());

    if ((fieldValues.size() == 1 && !fieldValues.iterator().next().equals(value))
            || (fieldValues.size() != 1 && changedDoc.getLength() > 0)) {
        ctrl.viewChanged(this, changedField, value);
    }
}