Example usage for org.jsoup.nodes Element tagName

List of usage examples for org.jsoup.nodes Element tagName

Introduction

In this page you can find the example usage for org.jsoup.nodes Element tagName.

Prototype

public String tagName() 

Source Link

Document

Get the name of the tag for this element.

Usage

From source file:org.asqatasun.rules.rgaa30.Rgaa30Rule100701.java

/**
 * //from  w  w w  . j  a  va2 s.  c o m
 * @param element
 * @param domElement
 * @param elementHandler 
 */
private void treatFocusableElement(Element element, DomElement domElement,
        ElementHandler<Element> elementHandler) {
    if (element == null) {
        return;
    }
    nbOfFocusableElements++;
    if (getFocusableElementExcludedList().contains(element.tagName())) {
        focusableElementExcluded = true;
    } else if (!isOutlineVisible(domElement)) {
        if (StringUtils.equalsIgnoreCase(element.tagName(), BODY_ELEMENT)) {
            nbOfFocusableElements--;
        } else {
            elementHandler.add(element);
        }
    }
}

From source file:org.asqatasun.rules.rgaa30.Rgaa30Rule110102.java

/**
 * This method linked each input on a page to its form in a map.
 *///  w  ww . j  a v a2  s  . c  om
private void putInputElementHandlerIntoTheMap() {
    for (Element el : inputElementHandler.get()) {
        if (!el.hasAttr(TITLE_ATTR) && !el.hasAttr(ARIA_LABEL_ATTR) && !el.hasAttr(ARIA_LABELLEDBY_ATTR)) {
            Element tmpElement = el.parent();
            while (StringUtils.isNotBlank(tmpElement.tagName())) {
                if (tmpElement.tagName().equals(FORM_ELEMENT)) {
                    if (inputFormMap.containsKey(tmpElement)) {
                        inputFormMap.get(tmpElement).add(el);
                    } else {
                        ElementHandler<Element> inputElement = new ElementHandlerImpl();
                        inputElement.add(el);
                        inputFormMap.put(tmpElement, inputElement);
                    }
                    break;
                }
                tmpElement = tmpElement.parent();
            }
        }
    }
}

From source file:org.asqatasun.rules.rgaa30.Rgaa30Rule110102.java

/**
 * This method linked each label which have an input child on a page to its
 * form in a map./*from w w w.  j  a v  a2  s.  c om*/
 */
private void putLabelElementHandlerIntoTheMap() {
    for (Element el : labelElementHandler.get()) {
        Element tmpElement = el.parent();

        while (tmpElement != null && StringUtils.isNotBlank(tmpElement.tagName())) {
            if (tmpElement.tagName().equals(FORM_ELEMENT)) {
                if (labelFormMap.containsKey(tmpElement)) {
                    Elements els = el.select(FORM_ELEMENT_WITH_ID_CSS_LIKE_QUERY);
                    if (!els.isEmpty()) {
                        labelFormMap.get(tmpElement).add(el);
                    }
                } else {
                    Elements els = el.select(FORM_ELEMENT_WITH_ID_CSS_LIKE_QUERY);
                    if (!els.isEmpty()) {
                        ElementHandler<Element> labelElement = new ElementHandlerImpl();
                        labelElement.add(el);
                        labelFormMap.put(tmpElement, labelElement);
                    }
                }
                break;
            }
            tmpElement = tmpElement.parent();
        }
    }
}

From source file:org.asqatasun.rules.rgaa30.Rgaa30Rule110103.java

/**
 * This method linked each input on a page to its form in a map.
 *//*from ww  w . j  av a  2  s .  c  om*/
private void putInputElementHandlerIntoTheMap() {
    for (Element el : inputElementHandler.get()) {
        Element tmpElement = el.parent();
        while (StringUtils.isNotBlank(tmpElement.tagName())) {
            if (tmpElement.tagName().equals(FORM_ELEMENT)) {
                if (inputFormMap.containsKey(tmpElement)) {
                    inputFormMap.get(tmpElement).add(el);
                } else {
                    ElementHandler<Element> inputElement = new ElementHandlerImpl();
                    inputElement.add(el);
                    inputFormMap.put(tmpElement, inputElement);
                }
                break;
            }
            tmpElement = tmpElement.parent();
        }
    }
}

From source file:org.b3log.solo.plugin.list.ListHandler.java

@Override
public void action(final Event<JSONObject> event) throws EventException {
    final JSONObject data = event.getData();
    final JSONObject article = data.optJSONObject(Article.ARTICLE);

    String content = article.optString(Article.ARTICLE_CONTENT);

    final Document doc = Jsoup.parse(content, StringUtils.EMPTY, Parser.htmlParser());
    doc.outputSettings().prettyPrint(false);

    final StringBuilder listBuilder = new StringBuilder();

    listBuilder.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + Latkes.getStaticServePath()
            + "/plugins/list/style.css\" />");

    final Elements hs = doc.select("h1, h2, h3, h4, h5");

    listBuilder.append("<ul class='b3-solo-list'>");
    for (int i = 0; i < hs.size(); i++) {
        final Element element = hs.get(i);
        final String tagName = element.tagName().toLowerCase();
        final String text = element.text();
        final String id = "b3_solo_" + tagName + "_" + i;

        element.before("<span id='" + id + "'></span>");

        listBuilder.append("<li class='b3-solo-list-").append(tagName).append("'><a href='#").append(id)
                .append("'>").append(text).append("</a></li>");
    }//from   w ww  .  ja v  a2 s. co m
    listBuilder.append("</ul>");

    final Element body = doc.getElementsByTag("body").get(0);

    content = listBuilder.toString() + body.html();

    article.put(Article.ARTICLE_CONTENT, content);
}

From source file:org.b3log.symphony.util.Markdowns.java

/**
 * Converts the specified markdown text to HTML.
 *
 * @param markdownText the specified markdown text
 * @return converted HTML, returns an empty string "" if the specified markdown text is "" or {@code null}, returns
 * 'markdownErrorLabel' if exception/*from  w  w  w  .  j ava  2  s. c  o m*/
 */
public static String toHTML(final String markdownText) {
    if (Strings.isEmptyOrNull(markdownText)) {
        return "";
    }

    final String cachedHTML = getHTML(markdownText);
    if (null != cachedHTML) {
        return cachedHTML;
    }

    final ExecutorService pool = Executors.newSingleThreadExecutor();
    final long[] threadId = new long[1];

    final Callable<String> call = () -> {
        threadId[0] = Thread.currentThread().getId();

        String html = LANG_PROPS_SERVICE.get("contentRenderFailedLabel");

        if (MARKED_AVAILABLE) {
            html = toHtmlByMarked(markdownText);
            if (!StringUtils.startsWith(html, "<p>")) {
                html = "<p>" + html + "</p>";
            }
        } else {
            com.vladsch.flexmark.ast.Node document = PARSER.parse(markdownText);
            html = RENDERER.render(document);
            if (!StringUtils.startsWith(html, "<p>")) {
                html = "<p>" + html + "</p>";
            }
        }

        final Document doc = Jsoup.parse(html);
        final List<org.jsoup.nodes.Node> toRemove = new ArrayList<>();
        doc.traverse(new NodeVisitor() {
            @Override
            public void head(final org.jsoup.nodes.Node node, int depth) {
                if (node instanceof org.jsoup.nodes.TextNode) {
                    final org.jsoup.nodes.TextNode textNode = (org.jsoup.nodes.TextNode) node;
                    final org.jsoup.nodes.Node parent = textNode.parent();

                    if (parent instanceof Element) {
                        final Element parentElem = (Element) parent;

                        if (!parentElem.tagName().equals("code")) {
                            String text = textNode.getWholeText();
                            boolean nextIsBr = false;
                            final org.jsoup.nodes.Node nextSibling = textNode.nextSibling();
                            if (nextSibling instanceof Element) {
                                nextIsBr = "br".equalsIgnoreCase(((Element) nextSibling).tagName());
                            }

                            if (null != userQueryService) {
                                try {
                                    final Set<String> userNames = userQueryService.getUserNames(text);
                                    for (final String userName : userNames) {
                                        text = text.replace('@' + userName + (nextIsBr ? "" : " "),
                                                "@<a href='" + Latkes.getServePath() + "/member/" + userName
                                                        + "'>" + userName + "</a> ");
                                    }
                                    text = text.replace("@participants ",
                                            "@<a href='https://hacpai.com/article/1458053458339' class='ft-red'>participants</a> ");
                                } finally {
                                    JdbcRepository.dispose();
                                }
                            }

                            if (text.contains("@<a href=")) {
                                final List<org.jsoup.nodes.Node> nodes = Parser.parseFragment(text, parentElem,
                                        "");
                                final int index = textNode.siblingIndex();

                                parentElem.insertChildren(index, nodes);
                                toRemove.add(node);
                            } else {
                                textNode.text(Pangu.spacingText(text));
                            }
                        }
                    }
                }
            }

            @Override
            public void tail(org.jsoup.nodes.Node node, int depth) {
            }
        });

        toRemove.forEach(node -> node.remove());

        doc.select("pre>code").addClass("hljs");
        doc.select("a").forEach(a -> {
            String src = a.attr("href");
            if (!StringUtils.startsWithIgnoreCase(src, Latkes.getServePath())) {
                try {
                    src = URLEncoder.encode(src, "UTF-8");
                } catch (final Exception e) {
                }
                a.attr("href", Latkes.getServePath() + "/forward?goto=" + src);
                a.attr("target", "_blank");
            }
        });
        doc.outputSettings().prettyPrint(false);

        String ret = doc.select("body").html();
        ret = StringUtils.trim(ret);

        // cache it
        putHTML(markdownText, ret);

        return ret;
    };

    Stopwatchs.start("Md to HTML");
    try {
        final Future<String> future = pool.submit(call);

        return future.get(MD_TIMEOUT, TimeUnit.MILLISECONDS);
    } catch (final TimeoutException e) {
        LOGGER.log(Level.ERROR, "Markdown timeout [md=" + markdownText + "]");
        Callstacks.printCallstack(Level.ERROR, new String[] { "org.b3log" }, null);

        final Set<Thread> threads = Thread.getAllStackTraces().keySet();
        for (final Thread thread : threads) {
            if (thread.getId() == threadId[0]) {
                thread.stop();

                break;
            }
        }
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Markdown failed [md=" + markdownText + "]", e);
    } finally {
        pool.shutdownNow();

        Stopwatchs.end();
    }

    return LANG_PROPS_SERVICE.get("contentRenderFailedLabel");
}

From source file:org.ednovo.gooru.application.util.ResourceImageUtil.java

public Map<String, Object> getResourceMetaData(String url, String resourceTitle, boolean fetchThumbnail) {
    Map<String, Object> metaData = new HashMap<String, Object>();
    ResourceMetadataCo resourceFeeds = null;
    if (url != null && url.contains(VIMEO_VIDEO)) {
        resourceFeeds = getMetaDataFromVimeoVideo(url);
    } else if (url != null && url.contains(YOUTUBE_VIDEO)) {
        resourceFeeds = getYoutubeResourceFeeds(url, null);
    }//from  w  w  w . ja  v  a  2  s. co m
    String description = "";
    String title = "";
    String videoDuration = "";
    Set<String> images = new LinkedHashSet<String>();
    if (resourceFeeds == null || resourceFeeds.getUrlStatus() == 404) {
        Document doc = null;
        try {
            if (url != null && (url.contains("http://") || url.contains("https://"))) {
                doc = Jsoup.connect(url).timeout(6000).get();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (doc != null) {
            title = doc.title();
            Elements meta = doc.getElementsByTag(META);
            if (meta != null) {
                for (Element element : meta) {
                    if (element.attr(NAME) != null && element.attr(NAME).equalsIgnoreCase(DESCRIPTION)) {
                        description = element.attr(CONTENT);
                        break;
                    }
                }
            }
            metaData.put(DESCRIPTION, description);
            if (fetchThumbnail) {
                Elements media = doc.select("[src]");
                if (media != null) {
                    for (Element src : media) {
                        if (src.tagName().equals(IMG)) {
                            images.add(src.attr("abs:src"));
                        }
                        if (images.size() >= SUGGEST_IMAGE_MAX_SIZE) {
                            break;
                        }
                    }
                }
            }
        }
    } else {
        title = resourceFeeds.getTitle();
        description = resourceFeeds.getDescription();
        videoDuration = resourceFeeds.getDuration().toString();
    }
    if (fetchThumbnail) {
        if (resourceFeeds != null && resourceFeeds.getThumbnail() != null) {
            images.add(resourceFeeds.getThumbnail());
        }
        metaData.put(IMAGES, images);
    }
    metaData.put(TITLE, title);
    metaData.put(DESCRIPTION, description);
    metaData.put(DURATION, videoDuration);
    return metaData;
}

From source file:org.opens.tanaguru.rules.accessiweb22.Aw22Rule10071.java

/**
 * /*from  w  w w .  ja v a2  s. c o m*/
 * @param element
 * @param domElement
 * @param elementHandler 
 */
private void treatFocusableElement(Element element, DomElement domElement, ElementHandler elementHandler) {
    if (element == null) {
        return;
    }
    nbOfFocusableElements++;
    if (getFocusableElementExcludedList().contains(element.tagName())) {
        focusableElementExcluded = true;
    } else if (!isOutlineVisible(domElement)) {
        if (!StringUtils.equalsIgnoreCase(element.tagName(), BODY_ELEMENT)) {
            elementHandler.add(element);
        }
    }
}

From source file:org.opens.tanaguru.rules.elementselector.LinkElementSelector.java

/**
 * //from   w  w w .j av  a  2s . c  o m
 * @param linkElement
 * @param linkText
 * @return whether the current link have a context
 */
protected boolean doesLinkHaveContext(Element linkElement, String linkText) {
    // does the current link have a title attribute? 
    if (considerTitleAsContext && linkElement.hasAttr(TITLE_ATTR)
            && !StringUtils.equals(linkElement.attr(TITLE_ATTR), linkText)) {
        return true;
    }
    // does the parent of the current link have some text?
    if (StringUtils.isNotBlank(linkElement.parent().ownText())) {
        return true;
    }
    // does the current element have a previous sibling of heading type?
    if (isOneOfPrecedingSiblingofHeadingType(linkElement)) {
        return true;
    }
    // does one of the parent of the current element have a previous sibling 
    // of heading type or is found in the PARENT_CONTEXT_ELEMENTS list?
    for (Element parent : linkElement.parents()) {
        if (PARENT_CONTEXT_ELEMENTS.contains(parent.tagName())
                || isOneOfPrecedingSiblingofHeadingType(parent)) {
            return true;
        }
    }
    return false;
}

From source file:org.opens.tanaguru.rules.rgaa30.Rgaa30Rule110102.java

/**
 * This method linked each input on a page to its form in a map.
 *//*  w w  w .  j ava  2s  .co  m*/
private void putInputElementHandlerIntoTheMap() {
    for (Element el : inputElementHandler.get()) {
        if (!el.hasAttr(TITLE_ATTR) && !el.hasAttr(ARIA_LABEL_ATTR) && !el.hasAttr(ARIA_LABELLEDBY_ATTR)) {
            Element tmpElement = el.parent();
            while (StringUtils.isNotBlank(tmpElement.tagName())) {
                if (tmpElement.tagName().equals(FORM_TAG)) {
                    if (inputFormMap.containsKey(tmpElement)) {
                        inputFormMap.get(tmpElement).add(el);
                    } else {
                        ElementHandler<Element> inputElement = new ElementHandlerImpl();
                        inputElement.add(el);
                        inputFormMap.put(tmpElement, inputElement);
                    }
                    break;
                }
                tmpElement = tmpElement.parent();
            }
        }
    }
}