Example usage for org.w3c.dom Element getAttributeNode

List of usage examples for org.w3c.dom Element getAttributeNode

Introduction

In this page you can find the example usage for org.w3c.dom Element getAttributeNode.

Prototype

public Attr getAttributeNode(String name);

Source Link

Document

Retrieves an attribute node by name.

Usage

From source file:org.dita.dost.module.BranchFilterModule.java

/** Modify and filter topics for branches. These files use an existing file name. */
private void filterTopics(final Element topicref, final List<FilterUtils> filters) {
    final List<FilterUtils> fs = combineFilterUtils(topicref, filters);

    final String href = topicref.getAttribute(ATTRIBUTE_NAME_HREF);
    final Attr skipFilter = topicref.getAttributeNode(SKIP_FILTER);
    final URI srcAbsUri = job.tempDirURI.resolve(map.resolve(href));
    if (!fs.isEmpty() && skipFilter == null && !filtered.contains(srcAbsUri) && !href.isEmpty()
            && !ATTR_SCOPE_VALUE_EXTERNAL.equals(topicref.getAttribute(ATTRIBUTE_NAME_SCOPE))
            && !ATTR_PROCESSING_ROLE_VALUE_RESOURCE_ONLY
                    .equals(topicref.getAttribute(ATTRIBUTE_NAME_PROCESSING_ROLE))
            && isDitaFormat(topicref.getAttributeNode(ATTRIBUTE_NAME_FORMAT))) {
        final ProfilingFilter writer = new ProfilingFilter();
        writer.setLogger(logger);//  w w w.j a  v  a 2s  . c  o m
        writer.setJob(job);
        writer.setFilterUtils(fs);
        writer.setCurrentFile(srcAbsUri);
        final List<XMLFilter> pipe = singletonList(writer);

        logger.info("Filtering " + srcAbsUri);
        try {
            xmlUtils.transform(srcAbsUri, pipe);
        } catch (final DITAOTException e) {
            logger.error("Failed to filter " + srcAbsUri + ": " + e.getMessage(), e);
        }
        filtered.add(srcAbsUri);
    }
    if (skipFilter != null) {
        topicref.removeAttributeNode(skipFilter);
    }

    for (final Element child : getChildElements(topicref, MAP_TOPICREF)) {
        if (DITAVAREF_D_DITAVALREF.matches(child)) {
            continue;
        }
        filterTopics(child, fs);
    }
}

From source file:org.dita.dost.reader.ChunkMapReader.java

private void processTopicref(final Element topicref) {
    final String xtrfValue = getValue(topicref, ATTRIBUTE_NAME_XTRF);
    if (xtrfValue != null && xtrfValue.contains(ATTR_XTRF_VALUE_GENERATED)) {
        return;/*from   ww w. j  a  v  a  2s. co  m*/
    }

    final Collection<String> chunkValue = split(getValue(topicref, ATTRIBUTE_NAME_CHUNK));

    if (topicref.getAttributeNode(ATTRIBUTE_NAME_HREF) == null && chunkValue.contains(CHUNK_TO_CONTENT)) {
        generateStumpTopic(topicref);
    }

    final URI hrefValue = toURI(getValue(topicref, ATTRIBUTE_NAME_HREF));
    final URI copytoValue = toURI(getValue(topicref, ATTRIBUTE_NAME_COPY_TO));
    final String scopeValue = getCascadeValue(topicref, ATTRIBUTE_NAME_SCOPE);
    final String chunkByToken = getChunkByToken(chunkValue, "by-", defaultChunkByToken);

    if (ATTR_SCOPE_VALUE_EXTERNAL.equals(scopeValue)
            || (hrefValue != null && !resolve(fileDir, hrefValue.toString()).exists())
            || (chunkValue.isEmpty() && hrefValue == null)) {
        processChildTopicref(topicref);
    } else if (chunkValue.contains(CHUNK_TO_CONTENT)
            && (hrefValue != null || copytoValue != null || topicref.hasChildNodes())) {
        if (chunkValue.contains(CHUNK_BY_TOPIC)) {
            logger.warn(MessageUtils.getInstance().getMessage("DOTJ064W").setLocation(topicref).toString());
        }
        processChunk(topicref, false);
    } else if (chunkValue.contains(CHUNK_TO_NAVIGATION) && supportToNavigation) {
        processChildTopicref(topicref);
        processNavitation(topicref);
    } else if (chunkByToken.equals(CHUNK_BY_TOPIC)) {
        processChunk(topicref, true);
        processChildTopicref(topicref);
    } else { // chunkByToken.equals(CHUNK_BY_DOCUMENT)
        String currentPath = null;
        if (copytoValue != null) {
            currentPath = resolve(fileDir, copytoValue).getPath();
        } else if (hrefValue != null) {
            currentPath = resolve(fileDir, hrefValue).getPath();
        }
        if (currentPath != null) {
            if (changeTable.containsKey(currentPath)) {
                changeTable.remove(currentPath);
            }
            final String processingRole = getCascadeValue(topicref, ATTRIBUTE_NAME_PROCESSING_ROLE);
            if (!ATTR_PROCESSING_ROLE_VALUE_RESOURCE_ONLY.equals(processingRole)) {
                changeTable.put(currentPath, currentPath);
            }
        }
        processChildTopicref(topicref);
    }
}

From source file:org.dita.dost.reader.ChunkMapReader.java

public static String getValue(final Element elem, final String attrName) {
    final Attr attr = elem.getAttributeNode(attrName);
    if (attr != null && !attr.getValue().isEmpty()) {
        return attr.getValue();
    }// w  ww.ja  v  a 2 s .c  o m
    return null;
}

From source file:org.dita.dost.reader.ChunkMapReader.java

public static String getCascadeValue(final Element elem, final String attrName) {
    Element current = elem;
    while (current != null) {
        final Attr attr = current.getAttributeNode(attrName);
        if (attr != null) {
            return attr.getValue();
        }/*  w w  w.  j  av  a 2s .  c  o m*/
        final Node parent = current.getParentNode();
        if (parent != null && parent.getNodeType() == Node.ELEMENT_NODE) {
            current = (Element) parent;
        } else {
            break;
        }
    }
    return null;
}

From source file:org.dita.dost.writer.ConrefPushParser.java

/**
 * /*from ww  w.  j a  va  2 s. c  om*/
 * @param targetClassAttribute targetClassAttribute
 * @param content string
 * @return string
 */
private DocumentFragment replaceElementName(final DitaClass targetClassAttribute,
        final DocumentFragment content) {
    try {
        if (content.hasChildNodes()) {
            final NodeList nodeList = content.getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {
                final Node node = nodeList.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    final Element elem = (Element) node;
                    final DitaClass clazz = DitaClass.getInstance(elem);
                    // get type of the target element
                    final String type = targetClassAttribute.toString()
                            .substring(1, targetClassAttribute.toString().indexOf("/")).trim();
                    if (!clazz.equals(targetClassAttribute) && targetClassAttribute.matches(clazz)) {
                        // Specializing the pushing content is not handled here
                        // but we can catch such a situation to emit a warning by comparing the class values.
                        final String targetElementName = targetClassAttribute.toString()
                                .substring(targetClassAttribute.toString().indexOf("/") + 1).trim();
                        if (elem.getAttributeNode(ATTRIBUTE_NAME_CONREF) != null) {
                            hasConref = true;
                        }
                        if (elem.getAttributeNode(ATTRIBUTE_NAME_KEYREF) != null) {
                            hasKeyref = true;
                        }
                        elem.getOwnerDocument().renameNode(elem, elem.getNamespaceURI(), targetElementName);
                        // process the child nodes of the current node
                        final NodeList nList = elem.getChildNodes();
                        for (int j = 0; j < nList.getLength(); j++) {
                            final Node subNode = nList.item(j);
                            if (subNode.getNodeType() == Node.ELEMENT_NODE) {
                                //replace the subElement Name
                                replaceSubElementName(type, (Element) subNode);
                            }
                        }
                    } else {
                        replaceSubElementName(STRING_BLANK, elem);
                    }
                }
            }
        }
    } catch (final Exception e) {
        e.printStackTrace();
    }
    return content;
}

From source file:org.dita.dost.writer.ConrefPushParser.java

/**
 * /*from w  w w .j ava2 s  . c  o  m*/
 * @param type pushtype
 * @param elem element
 * @return string
 */
private void replaceSubElementName(final String type, final Element elem) {
    final DitaClass classValue = DitaClass.getInstance(elem);
    if (elem.getAttributeNode(ATTRIBUTE_NAME_CONREF) != null) {
        hasConref = true;
    }
    if (elem.getAttributeNode(ATTRIBUTE_NAME_KEYREF) != null) {
        hasKeyref = true;
    }
    String generalizedElemName = elem.getNodeName();
    if (classValue != null) {
        if (classValue.toString().contains(type) && !type.equals(STRING_BLANK)) {
            generalizedElemName = classValue.toString()
                    .substring(classValue.toString().indexOf("/") + 1,
                            classValue.toString().indexOf(STRING_BLANK, classValue.toString().indexOf("/")))
                    .trim();
        }
    }
    elem.getOwnerDocument().renameNode(elem, elem.getNamespaceURI(), generalizedElemName);
    final NodeList nodeList = elem.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        final Node node = nodeList.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            replaceSubElementName(type, (Element) node);
        }
    }
}

From source file:org.ebayopensource.turmeric.eclipse.typelibrary.ui.wst.WTPCopyUtil.java

private static void updatePrefixes(Element element, Map<String, String> prefixMap) {
    NamedNodeMap namedNodeMap = element.getAttributes();
    for (int i = 0; i < namedNodeMap.getLength(); i++) {
        String attrValue = namedNodeMap.item(i).getNodeValue();
        String attrName = namedNodeMap.item(i).getNodeName();
        for (String str : prefixMap.keySet()) {
            if (StringUtils.isNotEmpty(attrValue) && attrValue.trim().startsWith(str + ":")) {
                String trimmedAttrValue = attrValue.trim();
                String newAttrValue = trimmedAttrValue;
                if (trimmedAttrValue.startsWith(str + ":xs:")) {
                    newAttrValue = StringUtils.replaceOnce(trimmedAttrValue, str + ":xs:", "xs:");
                } else if (StringUtils.countMatches(trimmedAttrValue, ":") == 2) {
                    //already contains a prefix
                    trimmedAttrValue = StringUtils.substringAfter(trimmedAttrValue, ":");
                    String oldPrefix = StringUtils.substringBefore(trimmedAttrValue, ":");
                    newAttrValue = StringUtils.replaceOnce(trimmedAttrValue, oldPrefix + ":",
                            prefixMap.get(oldPrefix) + ":");
                } else {
                    newAttrValue = StringUtils.replaceOnce(trimmedAttrValue, str + ":",
                            prefixMap.get(str) + ":");
                }//from w  w w  . jav a 2s .  co m
                element.getAttributeNode(attrName).setValue(newAttrValue);
            }
        }
    }
    NodeList children = element.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node child = children.item(i);
        if (child instanceof Element)
            updatePrefixes((Element) child, prefixMap);
    }
}

From source file:org.eclipse.skalli.core.persistence.XStreamPersistenceTest.java

@Test
public void testSetLastModiefiedAttribute() throws SAXException, IOException, ParserConfigurationException {
    XStreamPersistence xp = new TestXStreamPersistence();
    Element element = XMLUtils.documentFromString("<dummy></dummy>").getDocumentElement();
    xp.setLastModifiedAttribute(element);
    Attr lastMod = element.getAttributeNode("lastModified");
    assertIsXsdDateTime(lastMod.getTextContent());
}

From source file:org.etudes.mneme.impl.ImportQtiServiceImpl.java

/**
 * Process the item if it is recognized as a Respondous Essay question.
 * /*w  w w  .  jav a 2 s .  c o  m*/
 * @param item
 *        The QTI item from the QTI file DOM.
 * @param pool
 *        The pool to add the question to.
 * @param pointsAverage
 *        A running average to contribute the question's point value to for the pool.
 */
protected boolean processRespondousEssay(Element item, Pool pool) throws AssessmentPermissionException {
    try {
        // the attributes of a survey question
        String presentation = null;
        String feedback = null;
        String externalId = null;

        externalId = StringUtil.trimToNull(item.getAttribute("ident"));

        // presentation text
        // Respondous is using the format - presentation/material/mattext
        XPath presentationTextPath = new DOMXPath("presentation/material/mattext");
        List presentationMaterialTexts = presentationTextPath.selectNodes(item);
        StringBuilder presentationTextBuilder = new StringBuilder();
        for (Object presentationMaterialText : presentationMaterialTexts) {
            Element presentationTextElement = (Element) presentationMaterialText;
            XPath matTextPath = new DOMXPath(".");
            String matText = StringUtil.trimToNull(matTextPath.stringValueOf(presentationTextElement));

            if (matText != null)
                presentationTextBuilder.append(matText);
        }
        presentation = presentationTextBuilder.toString();

        if (presentation == null) {
            // QTI format - presentation/flow/material/mattext
            presentationTextPath = new DOMXPath("presentation/flow/material/mattext");
            presentation = StringUtil.trimToNull(presentationTextPath.stringValueOf(item));
        }

        if (presentation == null)
            return false;

        // reponse_str/response_fib
        XPath renderFibPath = new DOMXPath("presentation/response_str/render_fib");
        Element responseFib = (Element) renderFibPath.selectSingleNode(item);

        if (responseFib == null)
            return false;

        Attr promptAttr = responseFib.getAttributeNode("prompt");
        Attr rowsAttr = responseFib.getAttributeNode("rows");
        Attr columnsAttr = responseFib.getAttributeNode("columns");

        if (promptAttr == null || rowsAttr == null || columnsAttr == null)
            return false;

        if (!"Box".equalsIgnoreCase(promptAttr.getValue().trim()))
            return false;

        // create the question
        Question question = this.questionService.newQuestion(pool, "mneme:Essay");
        EssayQuestionImpl e = (EssayQuestionImpl) (question.getTypeSpecificQuestion());

        String clean = HtmlHelper.cleanAndAssureAnchorTarget(presentation, true);

        question.getPresentation().setText(clean);

        // type
        e.setSubmissionType(EssayQuestionImpl.SubmissionType.inline);

        XPath itemfeedbackPath = new DOMXPath("itemfeedback/material/mattext");
        feedback = StringUtil.trimToNull(itemfeedbackPath.stringValueOf(item));

        // add feedback
        if (StringUtil.trimToNull(feedback) != null) {
            question.setFeedback(HtmlHelper.cleanAndAssureAnchorTarget(feedback, true));
        }

        // save
        question.getTypeSpecificQuestion().consolidate("");
        this.questionService.saveQuestion(question);

        return true;
    } catch (JaxenException e) {
        return false;
    }
}

From source file:org.etudes.mneme.impl.ImportQtiServiceImpl.java

/**
 * Process this item if it is recognized as a Respondous Fill in the blank.
 * //from w ww .j a va  2  s  .c o m
 * @param item
 *        The QTI item from the QTI file DOM.
 * @param pool
 *        The pool to add the question to.
 * @param pointsAverage
 *        A running average to contribute the question's point value to for the pool.
 * @return true if successfully recognized and processed, false if not.
 */
protected boolean processRespondousFillIn(Element item, Pool pool, Average pointsAverage)
        throws AssessmentPermissionException {
    // the attributes of a Fill In the Blank question
    boolean caseSensitive = false;
    boolean mutuallyExclusive = false;
    String presentation = null;
    float points = 0.0f;
    String feedback = null;
    boolean isResponseTextual = false;

    String externalId = null;
    List<String> answers = new ArrayList<String>();

    try {
        // identifier
        externalId = StringUtil.trimToNull(item.getAttribute("ident"));

        // presentation text
        // Respondous is using the format - presentation/material/mattext
        XPath presentationTextPath = new DOMXPath("presentation/material/mattext");
        List presentationMaterialTexts = presentationTextPath.selectNodes(item);
        StringBuilder presentationTextBuilder = new StringBuilder();
        for (Object presentationMaterialText : presentationMaterialTexts) {
            Element presentationTextElement = (Element) presentationMaterialText;
            XPath matTextPath = new DOMXPath(".");
            String matText = StringUtil.trimToNull(matTextPath.stringValueOf(presentationTextElement));

            if (matText != null)
                presentationTextBuilder.append(matText);
        }
        presentation = presentationTextBuilder.toString();

        if (presentation == null) {
            // QTI format - presentation/flow/material/mattext
            presentationTextPath = new DOMXPath("presentation/flow/material/mattext");
            presentation = StringUtil.trimToNull(presentationTextPath.stringValueOf(item));
        }

        if (presentation == null)
            return false;

        // reponse_str/response_fib
        XPath renderFibPath = new DOMXPath("presentation/response_str/render_fib");
        Element responseFib = (Element) renderFibPath.selectSingleNode(item);

        if (responseFib == null)
            return false;

        Attr promptAttr = responseFib.getAttributeNode("prompt");
        Attr rowsAttr = responseFib.getAttributeNode("rows");
        Attr columnsAttr = responseFib.getAttributeNode("columns");

        if (promptAttr == null || rowsAttr != null || columnsAttr != null)
            return false;

        if (!"Box".equalsIgnoreCase(promptAttr.getValue().trim()))
            return false;

        // score declaration - decvar
        XPath scoreDecVarPath = new DOMXPath("resprocessing/outcomes/decvar");
        Element scoreDecVarElement = (Element) scoreDecVarPath.selectSingleNode(item);

        if (scoreDecVarElement == null)
            return false;

        String vartype = StringUtil.trimToNull(scoreDecVarElement.getAttribute("vartype"));

        if ((vartype != null) && !("Integer".equalsIgnoreCase(vartype) || "Decimal".equalsIgnoreCase(vartype)))
            return false;

        String maxValue = StringUtil.trimToNull(scoreDecVarElement.getAttribute("maxvalue"));
        String minValue = StringUtil.trimToNull(scoreDecVarElement.getAttribute("minvalue"));

        try {
            points = Float.valueOf(maxValue);
        } catch (NumberFormatException e) {
            points = Float.valueOf("1.0");
        }

        // correct answer
        XPath respConditionPath = new DOMXPath("resprocessing/respcondition");
        List responses = respConditionPath.selectNodes(item);

        if (responses == null || responses.size() == 0)
            return false;

        for (Object oResponse : responses) {
            Element responseElement = (Element) oResponse;

            XPath responsePath = new DOMXPath("conditionvar/varequal");
            String responseText = StringUtil.trimToNull(responsePath.stringValueOf(responseElement));

            if (responseText != null) {
                // score
                XPath setVarPath = new DOMXPath("setvar");
                Element setVarElement = (Element) setVarPath.selectSingleNode(responseElement);

                if (setVarElement == null)
                    continue;

                if ("Add".equalsIgnoreCase(setVarElement.getAttribute("action"))) {
                    String pointsValue = StringUtil.trimToNull(setVarElement.getTextContent());

                    if (pointsValue == null)
                        pointsValue = "1.0";

                    answers.add(responseText.trim());

                    // feedback optional and can be Response, Solution, Hint
                    XPath displayFeedbackPath = new DOMXPath("displayfeedback");
                    Element displayFeedbackElement = (Element) displayFeedbackPath
                            .selectSingleNode(responseElement);

                    if (displayFeedbackElement == null)
                        continue;

                    String feedbackType = StringUtil
                            .trimToNull(displayFeedbackElement.getAttribute("feedbacktype"));

                    if (feedbackType == null || "Response".equalsIgnoreCase(feedbackType)) {
                        String linkRefId = StringUtil
                                .trimToNull(displayFeedbackElement.getAttribute("linkrefid"));

                        if (linkRefId == null)
                            continue;

                        XPath itemfeedbackPath = new DOMXPath(".//itemfeedback[@ident='" + linkRefId + "']");
                        Element feedbackElement = (Element) itemfeedbackPath.selectSingleNode(item);

                        if (feedbackElement == null)
                            continue;

                        XPath feedbackTextPath = new DOMXPath("material/mattext");
                        String feedbackText = StringUtil
                                .trimToNull(feedbackTextPath.stringValueOf(feedbackElement));

                        feedback = feedbackText;
                    }
                }
            }
        }

        if (answers.size() == 0)
            return false;

        // create the question
        Question question = this.questionService.newQuestion(pool, "mneme:FillBlanks");
        FillBlanksQuestionImpl f = (FillBlanksQuestionImpl) (question.getTypeSpecificQuestion());

        // case sensitive
        f.setCaseSensitive(Boolean.FALSE.toString());

        // mutually exclusive
        f.setAnyOrder(Boolean.FALSE.toString());

        StringBuffer buildAnswers = new StringBuffer();
        buildAnswers.append("{");
        for (String answer : answers) {
            if (!isResponseTextual) {
                try {
                    Float.parseFloat(answer);
                } catch (NumberFormatException e) {
                    isResponseTextual = true;
                }
            }
            buildAnswers.append(answer);
            buildAnswers.append("|");
        }
        buildAnswers.replace(buildAnswers.length() - 1, buildAnswers.length(), "}");
        String questionText = presentation.concat(buildAnswers.toString());

        String clean = HtmlHelper.cleanAndAssureAnchorTarget(questionText, true);

        f.setText(clean);

        // text or numeric
        f.setResponseTextual(Boolean.toString(isResponseTextual));

        // add feedback
        if (StringUtil.trimToNull(feedback) != null) {
            question.setFeedback(HtmlHelper.cleanAndAssureAnchorTarget(feedback, true));
        }

        // save
        question.getTypeSpecificQuestion().consolidate("");
        this.questionService.saveQuestion(question);

        // add to the points average
        pointsAverage.add(points);

        return true;
    } catch (JaxenException e) {
        return false;
    }
}