Example usage for org.jsoup.nodes Element nodeName

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

Introduction

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

Prototype

@Override
    public String nodeName() 

Source Link

Usage

From source file:org.asqatasun.processing.ProcessRemarkServiceImpl.java

/**
 * /*  w  w  w . j a va  2 s .  c om*/
 * @param node
 * @return
 */
private int searchElementLineNumber(Element element) {
    int nodeIndex = getElementIndex(element);
    int lineNumber = 0;
    boolean found = false;
    boolean isWithinComment = false;
    Iterator<Map.Entry<Integer, String>> iter = rawSourceCodeWithLine.entrySet().iterator();
    String codeLine;
    while (iter.hasNext() && !found) {
        Map.Entry<Integer, String> entry = iter.next();
        int myLineNumber = entry.getKey();
        int index = 0;
        while (index != -1) {
            codeLine = entry.getValue().toLowerCase();
            int characterPositionOri = index;
            index = codeLine.indexOf("<" + element.nodeName() + ">", index);
            if (index == -1) {
                index = codeLine.indexOf("<" + element.nodeName() + " ", characterPositionOri);
            }
            int startCommentIndex = codeLine.indexOf(START_COMMENT_OCCURENCE, characterPositionOri);
            int endCommentIndex = codeLine.indexOf(END_COMMENT_OCCURENCE, characterPositionOri);
            if (index != -1) { // if an occurence of the tag is found
                if (!isWithinComment && !(startCommentIndex != -1 && index > startCommentIndex)
                        && !(endCommentIndex != -1 && index < endCommentIndex)) { // if a comment is not currently opened or a comment is found on the current line and the occurence is not within
                    if (nodeIndex == 0) {
                        found = true;
                        lineNumber = myLineNumber;
                        break;
                    }
                    nodeIndex--;
                }
                index += element.nodeName().length();
            }
            // if a "start comment" occurence is found on the line,
            // the boolean isWithinComment is set to true. Thus, while a
            // "end comment" is not found, all the occurences of the
            // wanted node will be ignored
            if (!isWithinComment && startCommentIndex != -1 && endCommentIndex == -1) {
                isWithinComment = true;
            } else if (isWithinComment && endCommentIndex != -1 && startCommentIndex < endCommentIndex) {
                isWithinComment = false;
            }
        }
    }
    return lineNumber;
}

From source file:org.asqatasun.processing.ProcessRemarkServiceImpl.java

@Override
public SourceCodeRemark createSourceCodeRemark(TestSolution processResult, Element element,
        String messageCode) {/*from  w  w  w  . j a  v a2  s  .  co m*/

    SourceCodeRemark remark = processRemarkDataService.getSourceCodeRemark(element.nodeName(), processResult,
            messageCode, searchElementLineNumber(element));

    remark.setSnippet(getSnippetFromElement(element));
    for (String attr : evidenceElementList) {
        EvidenceElement evidenceElementSup;
        if (StringUtils.equalsIgnoreCase(attr, "text")) {
            evidenceElementSup = getEvidenceElement(attr, element.text());
        } else {
            evidenceElementSup = getEvidenceElement(attr, element.attr(attr));
        }
        remark.addElement(evidenceElementSup);
    }
    return remark;
}

From source file:org.asqatasun.rules.elementselector.CaptchaElementSelector.java

/**
 * This methods parses all the elements retrieved from the scope and extracts
 * the ones where the occurrence "captcha" is found among the attribute values
 *
 * @param selectionHandler/*w w w  .  j  av  a 2 s  .c  om*/
 */
public void extractCaptchaElements(ElementHandler<Element> selectionHandler) {
    if (selectionHandler.isEmpty()) {
        return;
    }
    Set<Element> captchaElements = new HashSet<>();
    for (Element el : selectionHandler.get()) {
        if (parseAttributeToExtractCaptcha(el)) {
            captchaElements.add(el);
        } else {
            for (Element sel : getSiblingsAndParents(el)) {
                if (!el.nodeName().equalsIgnoreCase(sel.nodeName()) && parseAttributeToExtractCaptcha(sel)) {
                    captchaElements.add(el);
                    break;
                }
            }
        }
    }
    selectionHandler.clean();
    for (Element el : captchaElements) {
        selectionHandler.add(el);
    }
}

From source file:org.asqatasun.rules.elementselector.CaptchaElementSelector.java

/**
 *
 * @param element/*from w  ww .jav a  2s . co  m*/
 * @return wheter either one attribute of the current element, either its
 * text, either one attribute of one of its parent or the text of one of
 * its parents contains the "captcha" keyword
 */
private boolean parseAttributeToExtractCaptcha(Element element) {
    if (element.nodeName().equalsIgnoreCase(HTML_ELEMENT)
            || element.nodeName().equalsIgnoreCase(BODY_ELEMENT)) {
        return false;
    }
    if (StringUtils.containsIgnoreCase(element.ownText(), CAPTCHA_KEY)) {
        return true;
    } else {
        for (Attribute attr : element.attributes()) {
            if (StringUtils.containsIgnoreCase(attr.getValue(), CAPTCHA_KEY)) {
                return true;
            }
        }
    }
    return false;
}

From source file:org.opens.tanaguru.contentadapter.css.CSSJsoupPhlocContentAdapterImpl.java

/**
 * Retrieve css content and adapt it for each inline resource
 *//*from   ww  w  .  j av  a  2  s.  c o m*/
private void adaptInlineCSS() {
    Set<Long> relatedCssIdSet = new HashSet<Long>();

    for (Element el : inlineCssElements) {
        String attributeValue = el.attr("style");
        if (StringUtils.isNotBlank(attributeValue)) {
            Resource cssResource = new CSSResourceImpl(el.nodeName() + "{" + attributeValue + "}", 0,
                    new InlineRsrc());
            StylesheetContent cssContent = getStylesheetFromInlineResource(cssResource.getResource());
            adaptContent(cssContent, cssResource, getCurrentResourcePath(el.baseUri()), null);
            relatedCssIdSet.add(getContentDataService().saveOrUpdate(cssContent).getId());
        }
    }
    getContentDataService().saveContentRelationShip(getSSP(), relatedCssIdSet);
}

From source file:org.opens.tanaguru.processing.ProcessRemarkServiceImpl.java

@Override
public void addSourceCodeRemarkOnElement(TestSolution processResult, Element element, String messageCode,
        Collection<EvidenceElement> evidenceElementList) {
    SourceCodeRemark remark = sourceCodeRemarkFactory.create();
    remark.setIssue(processResult);//from w w  w  . jav  a 2s  .c o m
    remark.setMessageCode(messageCode);
    if (element != null) {
        remark.setLineNumber(searchElementLineNumber(element));
        remark.setTarget(element.nodeName());
        remark.setSnippet(getSnippetFromElement(element));
    } else {
        remark.setLineNumber(-1);
    }
    if (CollectionUtils.isNotEmpty(evidenceElementList)) {
        for (EvidenceElement ee : evidenceElementList) {
            remark.addElement(ee);
            ee.setProcessRemark(remark);
        }
    }
    remarkSet.add(remark);
}

From source file:org.opens.tanaguru.processing.ProcessRemarkServiceImpl.java

@Override
public SourceCodeRemark createSourceCodeRemark(TestSolution processResult, Element element,
        String messageCode) {//  ww w  .j a v a2 s .  c om
    SourceCodeRemark remark = sourceCodeRemarkFactory.create();
    remark.setIssue(processResult);
    remark.setMessageCode(messageCode);
    remark.setLineNumber(searchElementLineNumber(element));
    remark.setTarget(element.nodeName());
    remark.setSnippet(getSnippetFromElement(element));
    for (String attr : evidenceElementList) {
        EvidenceElement evidenceElementSup;
        if (StringUtils.equalsIgnoreCase(attr, "text")) {
            evidenceElementSup = getEvidenceElement(attr, element.text());
        } else {
            evidenceElementSup = getEvidenceElement(attr, element.attr(attr));
        }
        remark.addElement(evidenceElementSup);
    }
    return remark;
}

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

/**
 * This methods parses all the elements retrieved from the scope and extracts
 * the ones where the occurrence "captcha" is found among the attribute values
 *
 * @param selectionHandler/*from   www  .ja v  a 2  s. c  o  m*/
 */
public void extractCaptchaElements(ElementHandler<Element> selectionHandler) {
    if (selectionHandler.isEmpty()) {
        return;
    }
    Set<Element> captchaElements = new HashSet<Element>();
    for (Element el : selectionHandler.get()) {
        if (parseAttributeToExtractCaptcha(el)) {
            captchaElements.add(el);
        } else {
            for (Element sel : getSiblingsAndParents(el)) {
                if (!el.nodeName().equalsIgnoreCase(sel.nodeName()) && parseAttributeToExtractCaptcha(sel)) {
                    captchaElements.add(el);
                    break;
                }
            }
        }
    }
    selectionHandler.clean();
    for (Element el : captchaElements) {
        selectionHandler.add(el);
    }
}

From source file:org.xwiki.validator.HTML5DutchWebGuidelinesValidator.java

/**
 * Do not skip any levels in the hierarchy of headings in the markup.
 *//*from   www .  j a v  a2 s  .  com*/
public void validateRpd3s3() {
    List<String> headings = Arrays.asList("//h1", "h2", "h3", "h4", "h5", "h6");

    int previousLevel = 1;
    for (Element element : getElements(headings)) {
        int currentLevel = Integer.parseInt(element.nodeName().substring(1));

        // Verify that we haven't jumped from h1 to h3.
        assertTrue(Type.ERROR, "rpd3s3.headings", currentLevel <= previousLevel + 1);
        previousLevel = currentLevel;
    }
}

From source file:synapticloop.documentr.generator.Generator.java

/**
 * Render the table of contents.  This will also render links to the headers, 
 * and back to top links - if the options are enabled.  The first thing that 
 * we do is to remove any of the code fence blocks, we then convert the 
 * markdown to HTML to extract the headers to generate the table of context.
 * Then we go through the actual markdown and add in the links (if 
 * applicable), finally we put in the table of contents and re-insert the 
 * code fence blocks./*  ww  w .  j  ava 2  s . c om*/
 * 
 * @param rendered The previously rendered string
 * 
 * @return the rendered content, with the table of contents inserted
 */
private String renderTableOfContents(String rendered) {

    // the first thing we are going to do is to remove code fences...
    String renderedClean = removeCodeFenceBlocks(rendered);

    int numHeader = 0;

    // here we are going to render the markdown to HTML and then get all of the
    // header items to build the table of contents.
    StringBuilder headerStringBuilder = new StringBuilder("\n\n");

    PegDownProcessor pegDownProcessor = new PegDownProcessor();

    String markdownToHtml = pegDownProcessor.markdownToHtml(renderedClean);

    numHeader = 0;
    Document document = Jsoup.parse(markdownToHtml);
    Elements headings = document.select("h1, h2, h3, h4, h5, h6");
    for (Element heading : headings) {
        int valueOf = Integer.parseInt(heading.nodeName().substring(1));
        if (valueOf <= tocLevel) {
            if (hasTocLinks) {
                headerStringBuilder.append(SPACING_LOOKUP.get(valueOf) + "[" + heading.text()
                        + "](#documentr_heading_" + numHeader + ")\n");
            } else {
                headerStringBuilder.append(SPACING_LOOKUP.get(valueOf) + heading.text() + "\n");
            }
        }
        numHeader++;
    }

    headerStringBuilder.append("\n\n");

    // Now we have the header all set up

    numHeader = 0;
    // go through and parse the markdown, get all of the headers 
    char[] charArray = renderedClean.toCharArray();
    RootNode rootNode = pegDownProcessor.parseMarkdown(charArray);
    List<Node> children = rootNode.getChildren();

    for (Node node : children) {
        if (node instanceof HeaderNode) {
            HeaderNode headerNode = (HeaderNode) node;
            int level = headerNode.getLevel();
            if (level <= tocLevel) {
                HEADER_LOOKUP.put(new StartEndBean(headerNode.getStartIndex(), headerNode.getEndIndex()),
                        numHeader);
            }
            numHeader++;
        }
    }

    if (hasTocLinks) {
        Iterator<StartEndBean> iterator = HEADER_LOOKUP.keySet().iterator();
        int start = 0;
        StringBuilder renderedStringBuilder = new StringBuilder();

        while (iterator.hasNext()) {
            StartEndBean startEndBean = (StartEndBean) iterator.next();
            int headerStart = startEndBean.getStart();
            int headerEnd = startEndBean.getEnd();
            Integer headerNum = HEADER_LOOKUP.get(startEndBean);
            renderedStringBuilder.append(Arrays.copyOfRange(charArray, start, headerStart));
            renderedStringBuilder.append("\n\n<a name=\"documentr_heading_" + headerNum + "\"></a>\n\n");

            if (hasTocBackToTop) {
                renderedStringBuilder.append(Arrays.copyOfRange(charArray, headerStart, headerEnd - 1));
                renderedStringBuilder.append(tocBackToTop);
                start = headerEnd - 1;
            } else {
                start = headerStart;
            }
        }

        renderedStringBuilder.append(Arrays.copyOfRange(charArray, start, charArray.length));
        renderedClean = renderedStringBuilder.toString();
    }

    renderedClean = renderedClean.replace(DOCUMENTR_TABLE_OF_CONTENTS, headerStringBuilder.toString());

    // last but not least, we need to put back in the code fences
    Iterator<Integer> codeFenceBlocksIterator = codeFenceBlocks.keySet().iterator();
    while (codeFenceBlocksIterator.hasNext()) {
        Integer integer = (Integer) codeFenceBlocksIterator.next();
        renderedClean = renderedClean.replace(
                String.format("%s%d%s", DOCUMENTR_CODE_FENCE_PREFIX, integer, DOCUMENTR_DELIMETER),
                codeFenceBlocks.get(integer).toString());
    }

    return renderedClean;
}