Example usage for javax.swing.text Document putProperty

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

Introduction

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

Prototype

public void putProperty(Object key, Object value);

Source Link

Document

Associates a property with the document.

Usage

From source file:HTML.java

/**
 * Utility method to convert HTML to text.
 * @param html The string containing HTML.
 * @return a String containing the derived text .
 *//* w ww  . ja v  a 2s  .co  m*/
public static final String html2text(String html) {
    EditorKit kit = new HTMLEditorKit();
    Document doc = kit.createDefaultDocument();
    doc.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
    try {
        Reader reader = new StringReader(html);
        kit.read(reader, doc, 0);
        return doc.getText(0, doc.getLength());
    } catch (Exception e) {

        return "";
    }
}

From source file:de.codesourcery.jasm16.utils.ASTInspector.java

private void openFile(final File file) throws IOException {

    FileInputStream in = new FileInputStream(file);
    final String source;
    try {/*from   ww w.j a v  a  2s . c  o m*/
        source = Misc.readSource(in);
    } finally {
        in.close();
    }

    disableDocumentListener();
    final Document doc = editorPane.getDocument();
    doc.putProperty(Document.StreamDescriptionProperty, null);

    editorPane.setText(source);

    final IResource resource = new AbstractResource(ResourceType.UNKNOWN) {

        @Override
        public String readText(ITextRegion range) throws IOException {
            return range.apply(getSourceFromEditor());
        }

        private String getSourceFromEditor() throws IOException {
            try {
                return editorPane.getDocument().getText(0, editorPane.getDocument().getLength());
            } catch (BadLocationException e) {
                throw new IOException("Internal error", e);
            }
        }

        @Override
        public long getAvailableBytes() throws IOException {
            return editorPane.getDocument().getLength();
        }

        @Override
        public OutputStream createOutputStream(boolean append) throws IOException {
            throw new UnsupportedOperationException("Not implemented");
        }

        @Override
        public InputStream createInputStream() throws IOException {
            return new ByteArrayInputStream(getSourceFromEditor().getBytes());
        }

        @Override
        public String getIdentifier() {
            return file.getAbsolutePath();
        }
    };

    this.file = file;
    this.currentUnit = CompilationUnit.createInstance(file.getAbsolutePath(), resource);

    enableDocumentListener();

    frame.setTitle(Compiler.VERSION + "    /    " + file.getName());
    compile();
}

From source file:de.codesourcery.jasm16.ide.ui.views.SourceCodeView.java

protected final void openResource(final IAssemblyProject project, final IResource sourceFile, int caretPosition,
        boolean compileSource) throws IOException {
    if (project == null) {
        throw new IllegalArgumentException("project must not be NULL");
    }/* w w  w .  ja  v  a2s  .  co m*/
    if (sourceFile == null) {
        throw new IllegalArgumentException("sourceFile must not be NULL");
    }

    // read source first so we don't discard internal state
    // and end up with an IOException later on...
    final String source = Misc.readSource(sourceFile);
    this.initialHashCode = Misc.calcHash(source);

    this.project = project;
    if (sourceFile instanceof InMemorySourceResource) {
        this.sourceInMemory = (InMemorySourceResource) sourceFile;
        this.persistentResource = sourceInMemory.getPersistentResource();
    } else {
        this.sourceInMemory = new InMemorySourceResource(sourceFile, editorPane) {

            @Override
            public String toString() {
                return "SourceCodeView[ " + persistentResource + " ]";
            }
        };
        this.persistentResource = sourceFile;
    }
    clearHighlight();

    try {
        disableDocumentListener();
        try {
            final Document doc = editorPane.getDocument();
            doc.putProperty(Document.StreamDescriptionProperty, null);

            disableNavigationHistoryUpdates();
            System.out.println("Text length: " + (source == null ? 0 : source.length()));

            try {
                editorPane.setText(source);
            } finally {
                enableNavigationHistoryUpdates();
            }

            try {
                editorPane.setCaretPosition(caretPosition);
            } catch (IllegalArgumentException e) {
                LOG.error("openResource(): Invalid caret position " + caretPosition + " in resource "
                        + sourceFile);
            }

            if (panel != null) {
                ICompilationUnit existing = null;
                if (!compileSource) {
                    existing = project.getProjectBuilder().getCompilationUnit(sourceFile);
                }
                validateSourceCode(existing);
            }
        } finally {
            enableDocumentListener();
        }
    } finally {
        enableNavigationHistoryUpdates();
    }

    editorPane.requestFocus();
    updateTitle();
}

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

private JEditorPane createSourceView(WordMLTextPane editorView) {
    //Create the Source View
    JEditorPane sourceView = new JEditorPane();

    MutableAttributeSet attrs = new SimpleAttributeSet();
    StyleConstants.setFontFamily(attrs, FontManager.getInstance().getSourceViewFontFamilyName());
    StyleConstants.setFontSize(attrs, FontManager.getInstance().getSourceViewFontSize());

    // TODO - only do this if the font is available.
    Font font = new Font("Arial Unicode MS", Font.PLAIN, 12);

    System.out.println(font.getFamily());
    System.out.println(font.getFontName());
    System.out.println(font.getPSName());

    sourceView.setFont(font);/*from   w  w  w .j a  v  a 2  s .c om*/
    //sourceView.setFont(FontManager.getInstance().getFontInAction(attrs));

    sourceView.setContentType("text/xml; charset=UTF-16");

    // Instantiate a XMLEditorKit with wrapping enabled.
    XMLEditorKit kit = new XMLEditorKit(true);
    // Set the wrapping style.
    kit.setWrapStyleWord(true);

    sourceView.setEditorKit(kit);

    WordMLDocument editorViewDoc = (WordMLDocument) editorView.getDocument();

    try {
        editorViewDoc.readLock();

        editorView.getWordMLEditorKit().saveCaretText();

        DocumentElement elem = (DocumentElement) editorViewDoc.getDefaultRootElement();
        WordprocessingMLPackage wmlPackage = ((DocumentML) elem.getElementML()).getWordprocessingMLPackage();
        String filePath = (String) editorView.getDocument().getProperty(WordMLDocument.FILE_PATH_PROPERTY);

        //Do not include the last paragraph which is an extra paragraph.
        elem = (DocumentElement) elem.getElement(elem.getElementCount() - 1);
        ElementML paraML = elem.getElementML();
        ElementML bodyML = paraML.getParent();
        paraML.delete();

        Document doc = DocUtil.read(sourceView, wmlPackage);
        doc.putProperty(WordMLDocument.FILE_PATH_PROPERTY, filePath);
        doc.putProperty(WordMLDocument.WML_PACKAGE_PROPERTY, wmlPackage);
        doc.addDocumentListener(getToolbarStates());

        //Below are the properties used by bounce.jar library
        //See http://www.edankert.com/bounce/xmleditorkit.html
        doc.putProperty(PlainDocument.tabSizeAttribute, new Integer(4));
        doc.putProperty(XMLDocument.AUTO_INDENTATION_ATTRIBUTE, Boolean.TRUE);
        doc.putProperty(XMLDocument.TAG_COMPLETION_ATTRIBUTE, Boolean.TRUE);

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

    } finally {
        editorViewDoc.readUnlock();
    }

    kit.setStyle(XMLStyleConstants.ATTRIBUTE_NAME, new Color(255, 0, 0), Font.PLAIN);

    sourceView.addFocusListener(getToolbarStates());
    //sourceView.setDocument(doc);
    sourceView.putClientProperty(Constants.LOCAL_VIEWS_SYNCHRONIZED_FLAG, Boolean.TRUE);

    return sourceView;
}

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

/**
 * Saves editor documents to a file.//  w  ww.  j av a 2 s  .co 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.python.pydev.core.docutils.StringUtils.java

/**
 * Given some html, extracts its text./*w  ww. jav  a 2s .c  o  m*/
 */
public static String extractTextFromHTML(String html) {
    try {
        EditorKit kit = new HTMLEditorKit();
        Document doc = kit.createDefaultDocument();

        // The Document class does not yet handle charset's properly.
        doc.putProperty("IgnoreCharsetDirective", Boolean.TRUE);

        // Create a reader on the HTML content.
        Reader rd = new StringReader(html);

        // Parse the HTML.
        kit.read(rd, doc, 0);

        //  The HTML text is now stored in the document
        return doc.getText(0, doc.getLength());
    } catch (Exception e) {
    }
    return "";
}