Example usage for org.jsoup.nodes Element before

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

Introduction

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

Prototype

@Override
public Element before(Node node) 

Source Link

Document

Insert the specified node into the DOM before this node (as a preceding sibling).

Usage

From source file:net.slkdev.swagger.confluence.service.impl.XHtmlToConfluenceServiceImpl.java

private static void reformatXHtmlSpacing(final Elements elements) {
    for (final Element element : elements) {
        element.before("<br />");
    }// w w  w . ja v  a  2 s . c  om
}

From source file:com.astamuse.asta4d.render.RenderUtil.java

/**
 * Find out all the snippet in the passed Document and execute them. The Containing embed tag of the passed Document will be exactly
 * mixed in here too. <br>//from   www. j a v a  2 s  .c  om
 * Recursively contained snippets will be executed from outside to inside, thus the inner snippets will not be executed until all of
 * their outer snippets are finished. Also, the dynamically created snippets and embed tags will comply with this rule too.
 * 
 * @param doc
 *            the Document to apply snippets
 * @throws SnippetNotResovlableException
 * @throws SnippetInvokeException
 * @throws TemplateException
 */
public final static void applySnippets(Document doc) throws SnippetNotResovlableException,
        SnippetInvokeException, TemplateException, TemplateNotFoundException {
    if (doc == null) {
        return;
    }

    applyClearAction(doc, false);

    // retrieve ready snippets
    String selector = SelectorUtil.attr(ExtNodeConstants.SNIPPET_NODE_TAG_SELECTOR,
            ExtNodeConstants.SNIPPET_NODE_ATTR_STATUS, ExtNodeConstants.SNIPPET_NODE_ATTR_STATUS_READY);
    List<Element> snippetList = new ArrayList<>(doc.select(selector));
    int readySnippetCount = snippetList.size();
    int blockedSnippetCount = 0;
    for (int i = readySnippetCount - 1; i >= 0; i--) {
        // if parent snippet has not been executed, the current snippet will
        // not be executed too.
        if (isBlockedByParentSnippet(doc, snippetList.get(i))) {
            snippetList.remove(i);
            blockedSnippetCount++;
        }
    }
    readySnippetCount = readySnippetCount - blockedSnippetCount;

    String renderDeclaration;
    Renderer renderer;
    Context context = Context.getCurrentThreadContext();
    Configuration conf = Configuration.getConfiguration();
    final SnippetInvoker invoker = conf.getSnippetInvoker();

    String refId;
    String currentTemplatePath;
    Element renderTarget;
    for (Element element : snippetList) {
        if (!conf.isSkipSnippetExecution()) {
            // for a faked snippet node which is created by template
            // analyzing process, the render target element should be its
            // child.
            if (element.attr(ExtNodeConstants.SNIPPET_NODE_ATTR_TYPE)
                    .equals(ExtNodeConstants.SNIPPET_NODE_ATTR_TYPE_FAKE)) {
                renderTarget = element.children().first();
                // the hosting element of this faked snippet has been removed by outer a snippet
                if (renderTarget == null) {
                    element.attr(ExtNodeConstants.SNIPPET_NODE_ATTR_STATUS,
                            ExtNodeConstants.SNIPPET_NODE_ATTR_STATUS_FINISHED);
                    continue;
                }
            } else {
                renderTarget = element;
            }

            // we have to reset the ref of current snippet at every time to make sure the ref is always unique(duplicated snippet ref
            // could be created by list rendering)
            TemplateUtil.resetSnippetRefs(element);

            context.setCurrentRenderingElement(renderTarget);
            renderDeclaration = element.attr(ExtNodeConstants.SNIPPET_NODE_ATTR_RENDER);

            refId = element.attr(ExtNodeConstants.ATTR_SNIPPET_REF);
            currentTemplatePath = element.attr(ExtNodeConstants.ATTR_TEMPLATE_PATH);

            context.setCurrentRenderingElement(renderTarget);
            context.setData(TRACE_VAR_TEMPLATE_PATH, currentTemplatePath);

            try {
                if (element.hasAttr(ExtNodeConstants.SNIPPET_NODE_ATTR_PARALLEL)) {
                    ConcurrentRenderHelper crHelper = ConcurrentRenderHelper.getInstance(context, doc);
                    final Context newContext = context.clone();
                    final String declaration = renderDeclaration;
                    crHelper.submitWithContext(newContext, declaration, refId, new Callable<Renderer>() {
                        @Override
                        public Renderer call() throws Exception {
                            return invoker.invoke(declaration);
                        }
                    });
                    element.attr(ExtNodeConstants.SNIPPET_NODE_ATTR_STATUS,
                            ExtNodeConstants.SNIPPET_NODE_ATTR_STATUS_WAITING);
                } else {
                    renderer = invoker.invoke(renderDeclaration);
                    applySnippetResultToElement(doc, refId, element, renderTarget, renderer);
                }
            } catch (SnippetNotResovlableException | SnippetInvokeException e) {
                throw e;
            } catch (Exception e) {
                SnippetInvokeException se = new SnippetInvokeException(
                        "Error occured when executing rendering on [" + renderDeclaration + "]:"
                                + e.getMessage(),
                        e);
                throw se;
            }

            context.setData(TRACE_VAR_TEMPLATE_PATH, null);
            context.setCurrentRenderingElement(null);
        } else {// if skip snippet
            element.attr(ExtNodeConstants.SNIPPET_NODE_ATTR_STATUS,
                    ExtNodeConstants.SNIPPET_NODE_ATTR_STATUS_FINISHED);
        }
    }

    // load embed nodes which blocking parents has finished
    List<Element> embedNodeList = doc.select(ExtNodeConstants.EMBED_NODE_TAG_SELECTOR);
    int embedNodeListCount = embedNodeList.size();
    Iterator<Element> embedNodeIterator = embedNodeList.iterator();
    Element embed;
    Element embedContent;
    while (embedNodeIterator.hasNext()) {
        embed = embedNodeIterator.next();
        if (isBlockedByParentSnippet(doc, embed)) {
            embedNodeListCount--;
            continue;
        }
        embedContent = TemplateUtil.getEmbedNodeContent(embed);
        TemplateUtil.mergeBlock(doc, embedContent);
        embed.before(embedContent);
        embed.remove();
    }

    if ((readySnippetCount + embedNodeListCount) > 0) {
        TemplateUtil.regulateElement(null, doc);
        applySnippets(doc);
    } else {
        ConcurrentRenderHelper crHelper = ConcurrentRenderHelper.getInstance(context, doc);
        String delcaration = null;
        if (crHelper.hasUnCompletedTask()) {
            delcaration = null;
            try {
                FutureRendererHolder holder = crHelper.take();
                delcaration = holder.getRenderDeclaration();
                String ref = holder.getSnippetRefId();
                String reSelector = SelectorUtil.attr(ExtNodeConstants.SNIPPET_NODE_TAG_SELECTOR,
                        ExtNodeConstants.ATTR_SNIPPET_REF, ref);
                Element element = doc.select(reSelector).get(0);// must have
                Element target;
                if (element.attr(ExtNodeConstants.SNIPPET_NODE_ATTR_TYPE)
                        .equals(ExtNodeConstants.SNIPPET_NODE_ATTR_TYPE_FAKE)) {
                    target = element.children().first();
                } else {
                    target = element;
                }
                applySnippetResultToElement(doc, ref, element, target, holder.getRenderer());
                applySnippets(doc);
            } catch (InterruptedException | ExecutionException e) {
                throw new SnippetInvokeException("Concurrent snippet invocation failed"
                        + (delcaration == null ? "" : " on [" + delcaration + "]"), e);
            }
        }
    }
}

From source file:net.slkdev.swagger.confluence.service.impl.XHtmlToConfluenceServiceImpl.java

private static String reformatXHtml(final String inputXhtml,
        final Map<String, ConfluenceLink> confluenceLinkMap) {
    final Document document = Jsoup.parse(inputXhtml, "utf-8", Parser.xmlParser());
    document.outputSettings().prettyPrint(false);
    document.outputSettings().escapeMode(xhtml);
    document.outputSettings().charset("UTF-8");

    final Elements linkElements = document.select("a");

    for (final Element linkElement : linkElements) {
        final String originalHref = linkElement.attr("href");
        final ConfluenceLink confluenceLink = confluenceLinkMap.get(originalHref);

        if (confluenceLink == null) {
            LOG.debug("NO LINK MAPPING FOUND TO COVERT LINK: {}", originalHref);
            continue;
        }/* w w w.  j a  v a 2  s. c  o m*/

        final String confluenceLinkMarkup = confluenceLink.getConfluenceLinkMarkup();

        LOG.debug("LINK CONVERSION: {} -> {}", originalHref, confluenceLinkMarkup);

        linkElement.before(confluenceLinkMarkup);

        linkElement.html("");
        linkElement.unwrap();
    }

    reformatXHtmlHeadings(document, "h2");
    reformatXHtmlHeadings(document, "h3");
    reformatXHtmlHeadings(document, "#toctitle");

    final SwaggerConfluenceConfig swaggerConfluenceConfig = SWAGGER_CONFLUENCE_CONFIG.get();

    if (swaggerConfluenceConfig.getPaginationMode() == PaginationMode.SINGLE_PAGE) {
        if (swaggerConfluenceConfig.isIncludeTableOfContentsOnSinglePage()) {
            reformatXHtmlBreakAfterElements(document, "#toc");
        }

        reformatXHtmlBreakAfterElements(document, ".sect1");
    }

    reformatXHtmlSpacing(document.select(".sect2"));
    reformatXHtmlSpacing(document.select(".sect3"));

    return document.html();
}

From source file:by.heap.remark.convert.TextCleaner.java

private void fixLineBreaks(Element el) {
    for (final Element e : el.children()) {
        if (e.tagName().equals("br")) {
            e.before("\n");
            e.remove();//  w  w  w . j  a  va 2  s. co m
        } else {
            fixLineBreaks(e);
        }
    }
}

From source file:com.astamuse.asta4d.render.RenderUtil.java

private final static void apply(Element target, List<Renderer> rendererList, RenderAction renderAction,
        int startIndex, int count) {

    // The renderer list have to be applied recursively because the
    // transformer will always return a new Element clone.

    if (startIndex >= count) {
        return;//from ww  w.j  av a 2 s  . com
    }

    final Renderer currentRenderer = rendererList.get(startIndex);

    RendererType rendererType = currentRenderer.getRendererType();

    switch (rendererType) {
    case GO_THROUGH:
        apply(target, rendererList, renderAction, startIndex + 1, count);
        return;
    /*
    case DEBUG:
    currentRenderer.getTransformerList().get(0).invoke(target);
    apply(target, rendererList, renderAction, startIndex + 1, count);
    return;
    */
    case RENDER_ACTION:
        ((RenderActionRenderer) currentRenderer).getStyle().apply(renderAction);
        apply(target, rendererList, renderAction, startIndex + 1, count);
        return;
    default:
        // do nothing
        break;
    }

    String selector = currentRenderer.getSelector();
    List<Transformer<?>> transformerList = currentRenderer.getTransformerList();

    List<Element> elemList;
    if (PSEUDO_ROOT_SELECTOR.equals(selector)) {
        elemList = new LinkedList<Element>();
        elemList.add(target);
    } else {
        elemList = new ArrayList<>(target.select(selector));
    }

    if (elemList.isEmpty()) {
        if (rendererType == RendererType.ELEMENT_NOT_FOUND_HANDLER) {
            elemList.add(target);
            transformerList.clear();
            transformerList.add(
                    new RendererTransformer(((ElementNotFoundHandler) currentRenderer).alternativeRenderer()));
        } else if (renderAction.isOutputMissingSelectorWarning()) {
            String creationInfo = currentRenderer.getCreationSiteInfo();
            if (creationInfo == null) {
                creationInfo = "";
            } else {
                creationInfo = " at [ " + creationInfo + " ]";
            }
            logger.warn(
                    "There is no element found for selector [{}]{}, if it is deserved, try Renderer#disableMissingSelectorWarning() "
                            + "to disable this message and Renderer#enableMissingSelectorWarning could enable this warning again in "
                            + "your renderer chain",
                    selector, creationInfo);
            apply(target, rendererList, renderAction, startIndex + 1, count);
            return;
        }

    } else {
        if (rendererType == RendererType.ELEMENT_NOT_FOUND_HANDLER) {
            apply(target, rendererList, renderAction, startIndex + 1, count);
            return;
        }
    }

    Element delayedElement = null;
    Element resultNode;
    // TODO we suppose that the element is listed as the order from parent
    // to children, so we reverse it. Perhaps we need a real order process
    // to ensure the wanted order.
    Collections.reverse(elemList);
    boolean renderForRoot;
    for (Element elem : elemList) {
        renderForRoot = PSEUDO_ROOT_SELECTOR.equals(selector)
                || rendererType == RendererType.ELEMENT_NOT_FOUND_HANDLER;
        if (!renderForRoot) {
            // faked group node will be not applied by renderers(only when the current selector is not the pseudo :root)
            if (elem.tagName().equals(ExtNodeConstants.GROUP_NODE_TAG)
                    && ExtNodeConstants.GROUP_NODE_ATTR_TYPE_FAKE
                            .equals(elem.attr(ExtNodeConstants.GROUP_NODE_ATTR_TYPE))) {
                continue;
            }
        }

        if (elem == target) {
            delayedElement = elem;
            continue;
        }
        for (Transformer<?> transformer : transformerList) {
            resultNode = transformer.invoke(elem);
            elem.before(resultNode);
        } // for transformer
        elem.remove();
    } // for element

    // if the root element is one of the process targets, we can not apply
    // the left renderers to original element because it will be replaced by
    // a new element even it is not necessary (that is how Transformer
    // works).
    if (delayedElement == null) {
        apply(target, rendererList, renderAction, startIndex + 1, count);
    } else {
        if (rendererType == RendererType.ELEMENT_NOT_FOUND_HANDLER && delayedElement instanceof Document) {
            delayedElement = delayedElement.child(0);
        }
        for (Transformer<?> transformer : transformerList) {
            resultNode = transformer.invoke(delayedElement);
            delayedElement.before(resultNode);
            apply(resultNode, rendererList, renderAction, startIndex + 1, count);
        } // for transformer
        delayedElement.remove();
    }

}

From source file:ac.simons.oembed.Oembed.java

/**
 * Parses  the given html document into a document and processes 
 * all anchor elements. If a valid anchor is found, it tries to
 * get an oembed response for it's url and than render the result
 * into the document replacing the given anchor.<br>
 * It returns the html representation of the new document.<br>
 * If there's an error or no oembed result for an url, the anchor tag
 * will be left as it was. //  ww w. j a v  a 2 s  .c  o m
 * @param document The document that should be checked for links to transform
 * @return the transformed document
 */
public Document transformDocument(final Document document) {
    boolean changedBaseUri = false;
    if (document.baseUri() == null && this.getBaseUri() != null) {
        document.setBaseUri(this.getBaseUri());
        changedBaseUri = true;
    }
    for (Element a : document.getElementsByTag("a")) {
        final String href = a.absUrl("href");
        try {
            String renderedRespose = null;
            final OembedResponse oembedResponse = this.transformUrl(href);
            // There was no response or an exception happened
            if (oembedResponse == null)
                continue;
            // There is a handler for this response
            else if (this.getHandler().containsKey(oembedResponse.getSource()))
                this.getHandler().get(oembedResponse.getSource()).handle(document, a, oembedResponse);
            // Try to render the response itself and replace the current anchor
            else if ((renderedRespose = oembedResponse.render()) != null) {
                a.before(renderedRespose);
                a.remove();
            }
        } catch (OembedException e) {
            logger.warn(String.format("Skipping '%s': %s", href, e.getMessage()));
        }
    }
    if (changedBaseUri)
        document.setBaseUri(null);
    return document;
}

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 w  w.ja v  a 2s.  c om
    listBuilder.append("</ul>");

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

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

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