Example usage for javax.swing.text Element getElement

List of usage examples for javax.swing.text Element getElement

Introduction

In this page you can find the example usage for javax.swing.text Element getElement.

Prototype

public Element getElement(int index);

Source Link

Document

Fetches the child element at the given index.

Usage

From source file:net.java.sip.communicator.impl.gui.main.chat.ChatConversationPanel.java

/**
 *
 * @param element/* w ww  .  jav  a 2 s .  com*/
 * @param attrName
 * @param matchStrings
 * @return
 */
private Element findFirstElement(Element element, HTML.Attribute attrName, String[] matchStrings) {
    String attr = (String) element.getAttributes().getAttribute(attrName);

    if (attr != null)
        for (String matchString : matchStrings)
            if (attr.startsWith(matchString))
                return element;

    Element resultElement = null;

    // Count how many messages we have in the document.
    for (int i = 0; i < element.getElementCount(); i++) {
        resultElement = findFirstElement(element.getElement(i), attrName, matchStrings);
        if (resultElement != null)
            return resultElement;
    }

    return null;
}

From source file:net.sf.jasperreports.engine.util.JEditorPaneHtmlMarkupProcessor.java

@Override
public String convert(String srcText) {
    JEditorPane editorPane = new JEditorPane("text/html", srcText);
    editorPane.setEditable(false);/*from  w ww.  j av  a2  s. c  o m*/

    List<Element> elements = new ArrayList<Element>();

    Document document = editorPane.getDocument();

    Element root = document.getDefaultRootElement();
    if (root != null) {
        addElements(elements, root);
    }

    int startOffset = 0;
    int endOffset = 0;
    int crtOffset = 0;
    String chunk = null;
    JRPrintHyperlink hyperlink = null;
    Element element = null;
    Element parent = null;
    boolean bodyOccurred = false;
    int[] orderedListIndex = new int[elements.size()];
    String whitespace = "    ";
    String[] whitespaces = new String[elements.size()];
    for (int i = 0; i < elements.size(); i++) {
        whitespaces[i] = "";
    }

    StringBuilder text = new StringBuilder();
    List<JRStyledText.Run> styleRuns = new ArrayList<>();

    for (int i = 0; i < elements.size(); i++) {
        if (bodyOccurred && chunk != null) {
            text.append(chunk);
            Map<Attribute, Object> styleAttributes = getAttributes(element.getAttributes());
            if (hyperlink != null) {
                styleAttributes.put(JRTextAttribute.HYPERLINK, hyperlink);
                hyperlink = null;
            }
            if (!styleAttributes.isEmpty()) {
                styleRuns.add(
                        new JRStyledText.Run(styleAttributes, startOffset + crtOffset, endOffset + crtOffset));
            }
        }

        chunk = null;
        element = elements.get(i);
        parent = element.getParentElement();
        startOffset = element.getStartOffset();
        endOffset = element.getEndOffset();
        AttributeSet attrs = element.getAttributes();

        Object elementName = attrs.getAttribute(AbstractDocument.ElementNameAttribute);
        Object object = (elementName != null) ? null : attrs.getAttribute(StyleConstants.NameAttribute);
        if (object instanceof HTML.Tag) {

            HTML.Tag htmlTag = (HTML.Tag) object;
            if (htmlTag == Tag.BODY) {
                bodyOccurred = true;
                crtOffset = -startOffset;
            } else if (htmlTag == Tag.BR) {
                chunk = "\n";
            } else if (htmlTag == Tag.OL) {
                orderedListIndex[i] = 0;
                String parentName = parent.getName().toLowerCase();
                whitespaces[i] = whitespaces[elements.indexOf(parent)] + whitespace;
                if (parentName.equals("li")) {
                    chunk = "";
                } else {
                    chunk = "\n";
                    ++crtOffset;
                }
            } else if (htmlTag == Tag.UL) {
                whitespaces[i] = whitespaces[elements.indexOf(parent)] + whitespace;

                String parentName = parent.getName().toLowerCase();
                if (parentName.equals("li")) {
                    chunk = "";
                } else {
                    chunk = "\n";
                    ++crtOffset;
                }

            } else if (htmlTag == Tag.LI) {

                whitespaces[i] = whitespaces[elements.indexOf(parent)];
                if (element.getElement(0) != null && (element.getElement(0).getName().toLowerCase().equals("ol")
                        || element.getElement(0).getName().toLowerCase().equals("ul"))) {
                    chunk = "";
                } else if (parent.getName().equals("ol")) {
                    int index = elements.indexOf(parent);
                    Object type = parent.getAttributes().getAttribute(HTML.Attribute.TYPE);
                    Object startObject = parent.getAttributes().getAttribute(HTML.Attribute.START);
                    int start = startObject == null ? 0
                            : Math.max(0, Integer.valueOf(startObject.toString()) - 1);
                    String suffix = "";

                    ++orderedListIndex[index];

                    if (type != null) {
                        switch (((String) type).charAt(0)) {
                        case 'A':
                            suffix = getOLBulletChars(orderedListIndex[index] + start, true);
                            break;
                        case 'a':
                            suffix = getOLBulletChars(orderedListIndex[index] + start, false);
                            break;
                        case 'I':
                            suffix = JRStringUtil.getRomanNumeral(orderedListIndex[index] + start, true);
                            break;
                        case 'i':
                            suffix = JRStringUtil.getRomanNumeral(orderedListIndex[index] + start, false);
                            break;
                        case '1':
                        default:
                            suffix = String.valueOf(orderedListIndex[index] + start);
                            break;
                        }
                    } else {
                        suffix += orderedListIndex[index] + start;
                    }
                    chunk = whitespaces[index] + suffix + DEFAULT_BULLET_SEPARATOR + "  ";

                } else {
                    chunk = whitespaces[elements.indexOf(parent)] + DEFAULT_BULLET_CHARACTER + "  ";
                }
                crtOffset += chunk.length();
            } else if (element instanceof LeafElement) {
                if (element instanceof RunElement) {
                    RunElement runElement = (RunElement) element;
                    AttributeSet attrSet = (AttributeSet) runElement.getAttribute(Tag.A);
                    if (attrSet != null) {
                        hyperlink = new JRBasePrintHyperlink();
                        hyperlink.setHyperlinkType(HyperlinkTypeEnum.REFERENCE);
                        hyperlink.setHyperlinkReference((String) attrSet.getAttribute(HTML.Attribute.HREF));
                        hyperlink.setLinkTarget((String) attrSet.getAttribute(HTML.Attribute.TARGET));
                    }
                }
                try {
                    chunk = document.getText(startOffset, endOffset - startOffset);
                } catch (BadLocationException e) {
                    if (log.isDebugEnabled()) {
                        log.debug("Error converting markup.", e);
                    }
                }
            }
        }
    }

    if (chunk != null) {
        if (!"\n".equals(chunk)) {
            text.append(chunk);
            Map<Attribute, Object> styleAttributes = getAttributes(element.getAttributes());
            if (hyperlink != null) {
                styleAttributes.put(JRTextAttribute.HYPERLINK, hyperlink);
                hyperlink = null;
            }
            if (!styleAttributes.isEmpty()) {
                styleRuns.add(
                        new JRStyledText.Run(styleAttributes, startOffset + crtOffset, endOffset + crtOffset));
            }
        } else {
            //final newline, not appending
            //check if there's any style run that would have covered it, that can happen if there's a <li> tag with style
            int length = text.length();
            for (ListIterator<JRStyledText.Run> it = styleRuns.listIterator(); it.hasNext();) {
                JRStyledText.Run run = it.next();
                //only looking at runs that end at the position where the newline should have been
                //we don't want to hide bugs in which runs that span after the text length are created
                if (run.endIndex == length + 1) {
                    if (run.startIndex < run.endIndex - 1) {
                        it.set(new JRStyledText.Run(run.attributes, run.startIndex, run.endIndex - 1));
                    } else {
                        it.remove();
                    }
                }
            }
        }
    }

    JRStyledText styledText = new JRStyledText(null, text.toString());
    for (JRStyledText.Run run : styleRuns) {
        styledText.addRun(run);
    }
    styledText.setGlobalAttributes(new HashMap<Attribute, Object>());

    return JRStyledTextParser.getInstance().write(styledText);
}

From source file:com.hexidec.ekit.EkitCore.java

/**
 * Traverses nodes for the describing method
 *///from w  ww .j  a  v a2 s .c  om
private void traverseElement(Element element, StringBuilder sb) {
    indent += indentStep;
    for (int i = 0; i < element.getElementCount(); i++) {
        for (int j = 0; j < indent; j++) {
            sb.append(" ");
        }
        sb.append(element.getElement(i));
        traverseElement(element.getElement(i), sb);
    }
    indent -= indentStep;
}

From source file:com.hexidec.ekit.EkitCore.java

public void removeEmptyLists() {
    javax.swing.text.ElementIterator ei = new javax.swing.text.ElementIterator(htmlDoc);
    Element ele;
    while ((ele = ei.next()) != null) {
        if (ele.getName().equals("ul") || ele.getName().equals("ol")) {
            int listChildren = 0;
            for (int i = 0; i < ele.getElementCount(); i++) {
                if (ele.getElement(i).getName().equals("li")) {
                    listChildren++;//from   www .j  a v a2  s.co  m
                }
            }
            if (listChildren <= 0) {
                htmlUtilities.removeTag(ele, true);
            }
        }
    }
    refreshOnUpdate();
}

From source file:com.hexidec.ekit.EkitCore.java

private void moveCaretOnTable(Element tdElement, boolean up, boolean selecting) {

    int caretPos = jtpMain.getCaretPosition();

    Element rowElement = tdElement.getParentElement();
    Element tableElement = rowElement.getParentElement();

    int rowIndex = DocumentUtil.getIndexInParent(rowElement);
    if (up) {/*from  w  w w. j a v  a2s.c o m*/
        if (rowIndex == 0) {
            moveCaret(Math.max(tableElement.getStartOffset() - 1, 0), selecting);
        } else {
            rowElement = tableElement.getElement(rowIndex - 1);
            int posInCell = caretPos - tdElement.getStartOffset();
            int colIndex = DocumentUtil.getIndexInParent(tdElement);
            tdElement = rowElement.getElement(colIndex);
            moveCaret(
                    tdElement.getStartOffset()
                            + Math.min(posInCell, tdElement.getEndOffset() - tdElement.getStartOffset() - 1),
                    selecting);
        }
    } else { // down
        if (rowIndex >= tableElement.getElementCount() - 1) {
            moveCaret(Math.min(tableElement.getEndOffset(), htmlDoc.getLength() - 1), selecting);
        } else {
            rowElement = tableElement.getElement(rowIndex + 1);
            int posInCell = caretPos - tdElement.getStartOffset();
            int colIndex = DocumentUtil.getIndexInParent(tdElement);
            tdElement = rowElement.getElement(colIndex);
            moveCaret(
                    tdElement.getStartOffset()
                            + Math.min(posInCell, tdElement.getEndOffset() - tdElement.getStartOffset() - 1),
                    selecting);
        }
    }

}

From source file:net.team2xh.crt.gui.editor.EditorTextPane.java

/**
 * Returns the first character offset of the given line number.
 *
 * @param line Line number.//w  w  w  .  j ava  2s .  c  om
 * @return First character offset of that line.
 * @throws BadLocationException
 */
public int getLineStartOffset(int line) throws BadLocationException {
    Element map = doc.getDefaultRootElement();
    if (line < 0) {
        throw new BadLocationException("Negative line", -1);
    } else if (line >= map.getElementCount()) {
        throw new BadLocationException("No such line", doc.getLength() + 1);
    } else {
        Element lineElem = map.getElement(line);
        return lineElem.getStartOffset();
    }
}

From source file:net.team2xh.crt.gui.editor.EditorTextPane.java

/**
 * Returns the last character offset of the given line number.
 *
 * @param line Line number./*from   w w  w.j  a v  a  2 s  . co  m*/
 * @return Last character offset of that line.
 * @throws BadLocationException
 */
public int getLineEndOffset(int line) throws BadLocationException {
    Element map = doc.getDefaultRootElement();
    if (line < 0) {
        throw new BadLocationException("Negative line", -1);
    } else if (line >= map.getElementCount()) {
        throw new BadLocationException("No such line", doc.getLength() + 1);
    } else {
        Element lineElem = map.getElement(line);
        return lineElem.getEndOffset();
    }
}

From source file:org.alder.fotobuchconvert.scribus.RtfToScribusConverter.java

void output(XmlBuilder xml, DefaultStyledDocument doc, ScribusWriter scribus) {
    log.debug("Starting conversion of RTF data");
    if (log.isTraceEnabled())
        doc.dump(System.err);/*from   ww w.  j ava 2  s .c o  m*/

    try {
        Element section = doc.getDefaultRootElement();
        log.trace(section);
        assert section.getName().equals("section");

        final int nj = section.getElementCount();
        for (int j = 0; j < nj; j++) {
            Element paragraph = section.getElement(j);
            log.trace(paragraph);
            assert section.getName().equals("paragraph");

            // boolean firstInPara = true;
            AttributeSet attr = paragraph.getAttributes();
            Integer alignment = (Integer) attr.getAttribute(StyleConstants.Alignment);

            boolean elementsInThisLine = false;
            final int ni = paragraph.getElementCount();
            for (int i = 0; i < ni; i++) {
                Element content = paragraph.getElement(i);
                assert section.getName().equals("content");

                int start = content.getStartOffset();
                int end = content.getEndOffset();

                attr = content.getAttributes();
                Boolean italic = (Boolean) attr.getAttribute(StyleConstants.Italic);
                Boolean bold = (Boolean) attr.getAttribute(StyleConstants.Bold);
                Boolean underline = (Boolean) attr.getAttribute(StyleConstants.Underline);
                String family = (String) attr.getAttribute(StyleConstants.Family);
                Integer fontSize = (Integer) attr.getAttribute(StyleConstants.Size);
                Color color = (Color) attr.getAttribute(StyleConstants.ColorConstants.Foreground);

                String text = doc.getText(start, end - start);

                // if (firstInPara && text.trim().isEmpty() && family ==
                // null
                // && fontSize == null)
                // continue;
                // else
                // firstInPara = false;
                if (i == ni - 1 && text.trim().isEmpty() && text.length() < 3)
                    continue;
                elementsInThisLine = true;

                while (text.endsWith("\n") || text.endsWith("\r"))
                    text = text.substring(0, text.length() - 1);

                log.debug(italic + " " + bold + " " + underline + " " + family + " " + fontSize + " " + color
                        + "\t\"" + text + "\"");

                XmlBuilder el = xml.add(C.EL_ITEXT).set(C.CH, text);

                if (bold == Boolean.TRUE && italic == Boolean.TRUE)
                    el.set(C.FONT, family + " Bold Italic");
                else if (bold == Boolean.TRUE)
                    el.set(C.FONT, family + " Bold");
                else if (italic == Boolean.TRUE)
                    el.set(C.FONT, family + " Italic");
                else
                    el.set(C.FONT, family + " Regular");

                if (fontSize != null)
                    el.set(C.FONTSIZE, fontSize);

                if (color != null && color.equals(Color.BLACK) && scribus != null) {
                    String colname = scribus.colorManager.getColorName(color);
                    el.set(C.FCOLOR, colname);
                }
            }

            if (!elementsInThisLine && j == nj - 1)
                break; // don't convert last line if empty

            XmlBuilder el = xml.add(C.EL_PARA);
            if (alignment != null)
                switch (alignment) {
                case StyleConstants.ALIGN_LEFT:
                    el.set(C.ALIGN, 0);
                    break;
                case StyleConstants.ALIGN_CENTER:
                    el.set(C.ALIGN, 1);
                    break;
                case StyleConstants.ALIGN_RIGHT:
                    el.set(C.ALIGN, 2);
                    break;
                case StyleConstants.ALIGN_JUSTIFIED:
                    el.set(C.ALIGN, 3);
                    break;
                }
        }
    } catch (BadLocationException e) {
        throw new RuntimeException("This error should not occour", e);
    }

}

From source file:org.deegree.tools.metadata.InspireValidator.java

/**
 * parse INSPIRE metadata validator response and print out result onto the console
 * //from  w w w .  j av  a2s. c om
 * @param response
 * @throws IOException
 * @throws IllegalStateException
 */
private void parseServiceResponse(HttpResponse response) throws Exception {
    String s = FileUtils.readTextFile(((BasicHttpResponse) response).getEntity().getContent()).toString();
    if (response.getStatusLine().getStatusCode() != 200) {
        outputWriter.println(s);
        outputWriter.println();
        return;
    }
    s = "<html><head></head><body>" + s + "</body></html>";
    BufferedReader br = new BufferedReader(new StringReader(s));

    HTMLEditorKit htmlKit = new HTMLEditorKit();
    HTMLDocument htmlDoc = (HTMLDocument) htmlKit.createDefaultDocument();
    HTMLEditorKit.Parser parser = new ParserDelegator();
    HTMLEditorKit.ParserCallback callback = htmlDoc.getReader(0);
    parser.parse(br, callback, true);

    // Parse
    ElementIterator iterator = new ElementIterator(htmlDoc);
    Element element;
    while ((element = iterator.next()) != null) {
        AttributeSet attributes = element.getAttributes();
        Object name = attributes.getAttribute(StyleConstants.NameAttribute);
        if ((name instanceof HTML.Tag) && ((name == HTML.Tag.IMPLIED))) {
            // Build up content text as it may be within multiple elements
            StringBuffer text = new StringBuffer();
            int count = element.getElementCount();
            for (int i = 0; i < count; i++) {
                Element child = element.getElement(i);
                AttributeSet childAttributes = child.getAttributes();
                if (childAttributes.getAttribute(StyleConstants.NameAttribute) == HTML.Tag.CONTENT) {
                    int startOffset = child.getStartOffset();
                    int endOffset = child.getEndOffset();
                    int length = endOffset - startOffset;
                    text.append(htmlDoc.getText(startOffset, length));
                }
            }
            outputWriter.println(text.toString());
        }
    }
    outputWriter.println("---------------------------------------------------------------------");
    outputWriter.println();
}

From source file:org.domainmath.gui.MainFrame.java

public void gotoLine(String goto_file, int lineRequested) {
    if (fileTab.getSelectedIndex() >= 0) {
        int indexOf = MainFrame.fileNameList.indexOf(goto_file);
        RTextScrollPane t = (RTextScrollPane) fileTab.getComponentAt(indexOf);
        RSyntaxTextArea selectedArea = (RSyntaxTextArea) t.getTextArea();
        try {//from w  w  w. j  a v a2s  . com
            Element element = selectedArea.getDocument().getDefaultRootElement();

            int rowCount = element.getElementCount();
            if (lineRequested > rowCount || lineRequested < 0) {

                setVisible(false);
                return;
            }
            Element row = null;
            int firstCharacter = 0;
            int rowNumber = 0;
            for (int i = 0; i < lineRequested; ++i) {
                firstCharacter = getFirstCharacter(row);
                rowNumber = element.getElementIndex(firstCharacter);
                row = element.getElement(rowNumber);
            }
            int lastColumnInRow = row.getEndOffset();
            selectedArea.select(firstCharacter, lastColumnInRow - 1);

        } catch (Exception e) {

        }
    }
}