Example usage for org.w3c.dom Node CDATA_SECTION_NODE

List of usage examples for org.w3c.dom Node CDATA_SECTION_NODE

Introduction

In this page you can find the example usage for org.w3c.dom Node CDATA_SECTION_NODE.

Prototype

short CDATA_SECTION_NODE

To view the source code for org.w3c.dom Node CDATA_SECTION_NODE.

Click Source Link

Document

The node is a CDATASection.

Usage

From source file:org.adl.parsers.dom.ADLDOMParser.java

/**
 * Traverses the DOM Tree and removes Ignorable Whitespace Text Nodes and
 * Comment Text.  The function also removes extension elements and
 * attributes that are not defined by SCORM.  If extensions are found
 * the function also sets a flag stating that extensions are present in the
 * input XML instance.//from w w w  . j a  v  a 2s.co  m
 *
 * @param iNode The node to be pruned of whitespace and comments<br>
 * @param iXMLFileName The XML file to be pruned
 */
private void pruneTree(Node iNode, String iXMLFileName) {
    String value;

    // is there anything to do?
    if (iNode == null)
        return;

    switch (iNode.getNodeType()) {
    case Node.PROCESSING_INSTRUCTION_NODE: {
        break;
    }
    case Node.DOCUMENT_NODE: {
        pruneTree(((Document) iNode).getDocumentElement(), iXMLFileName);
        break;
    }
    case Node.ELEMENT_NODE: {
        log.debug("Processing Element Node: [" + iNode.getLocalName() + "]");
        log.debug("************************************************");
        log.debug("Processing Element Node: [" + iNode.getLocalName() + "]");

        checkForSchemaLocations(iNode, iXMLFileName);

        // Get the list of attributes of the element
        NamedNodeMap attrList = iNode.getAttributes();

        // Loop over the attributes for this element, remove any attributes
        // that are extensions
        log.debug("Processing " + attrList.getLength() + " attributes");
        for (int i = 0; i < attrList.getLength(); i++) {
            Attr currentAttribute = (Attr) attrList.item(i);

            if (!(DOMTreeUtility.isSCORMAppProfileNode(currentAttribute, iNode))) {
                log.debug("Extension attribute, removing: [" + currentAttribute.getNamespaceURI() + "] "
                        + currentAttribute.getLocalName() + " from the its parent node ["
                        + iNode.getNamespaceURI() + "] " + iNode.getLocalName());

                // Remove the Element Node from the DOM
                attrList.removeNamedItemNS(currentAttribute.getNamespaceURI(), currentAttribute.getLocalName());
                i--;
                mExtensionsFound = true;
            } else {
                log.debug("Valid SCORM attribute, keeping attribute: [" + currentAttribute.getNamespaceURI()
                        + "] " + currentAttribute.getLocalName());
            }
        }

        log.debug("Done processing attributes for node: [" + iNode.getNamespaceURI() + "] "
                + iNode.getLocalName());
        log.debug("************************************************");

        // Done looping over the attributes for this element, now loop over
        // the set of children nodes.

        log.debug("");
        log.debug("************************************************");
        log.debug("Processing direct-descendances for node: [" + iNode.getNamespaceURI() + "] "
                + iNode.getLocalName());

        NodeList children = iNode.getChildNodes();
        if (children != null) {
            // Loop over set of children elements for this element, remove
            // any elements that are extensions
            log.debug("Processing " + children.getLength() + " elements");
            for (int z = 0; z < children.getLength(); z++) {
                Node childNode = children.item(z);

                if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                    log.debug("Processing element: [" + childNode + "]");
                    log.debug("Elements Namespace: [" + childNode.getNamespaceURI() + "]");
                    log.debug("Elements Parent Node: [" + iNode.getLocalName() + "]");
                    log.debug("Parent Nodes Namespace: [" + iNode.getNamespaceURI() + "]");

                    if (!(DOMTreeUtility.isSCORMAppProfileNode(children.item(z),
                            children.item(z).getParentNode()))) {
                        // Before we remove the element see if the elemen
                        // contains any xsi:schemaLocations.  We need
                        // to add them to the list of schema locations for 
                        // parsing
                        checkForSchemaLocations(childNode, iXMLFileName);

                        log.debug("Extension Element Found, removing from DOM Tree ");

                        // Remove the Element Node from the DOM
                        children.item(z).getParentNode().removeChild(children.item(z));
                        z--;
                        mExtensionsFound = true;
                    } else {
                        log.debug("ADL SCORM Element Found, leaving " + "element in DOM Tree");
                        pruneTree(children.item(z), iXMLFileName);
                    }
                } // end if NodeType == ELEMENT_NODE

                if (childNode instanceof TextImpl) {
                    value = children.item(z).getNodeValue().trim();

                    if (((TextImpl) children.item(z)).isIgnorableWhitespace()) {
                        iNode.removeChild(children.item(z));
                        z--;
                    } else if (value.length() == 0) {
                        iNode.removeChild(children.item(z));
                        z--;
                    }
                } else if (children.item(z).getNodeType() == Node.COMMENT_NODE) {
                    iNode.removeChild(children.item(z));
                    z--;
                }
            } // end looping over children nodes
        } // end if there are children

        log.debug("Done processing direct-descendants for node: [" + iNode.getNamespaceURI() + "] "
                + iNode.getLocalName());
        log.debug("**************************************************");

        break;

    }

    // handle entity reference nodes
    case Node.ENTITY_REFERENCE_NODE: {

        NodeList children = iNode.getChildNodes();
        if (children != null) {
            int len = children.getLength();
            for (int i = 0; i < len; i++) {
                pruneTree(children.item(i), iXMLFileName);
            }
        }
        break;
    }

    // text
    case Node.COMMENT_NODE: {
        break;
    }
    case Node.CDATA_SECTION_NODE: {
        break;
    }
    case Node.TEXT_NODE: {
        break;
    }
    default: {
        break;
    }
    }
}

From source file:org.adl.parsers.dom.DOMTreeUtility.java

/**
 * This method gets the text node of an input node.
 *
 * @param iNode The node that contains the desired text node
 *
 * @return Returns the desired value of the node.
 *//*from ww w .  j  av  a  2 s . co  m*/
public static String getNodeValue(Node iNode) {
    // Create a string to hold the results.
    String value = "";

    // Check to make sure node is not null
    if (iNode != null) {
        // Get a list of the children of the input node
        NodeList children = iNode.getChildNodes();

        // Cycle through all children of node to get the text
        if (children != null) {
            int numChildren = children.getLength();
            for (int i = 0; i < numChildren; i++) {
                // make sure we have a text element
                if ((children.item(i).getNodeType() == Node.TEXT_NODE)
                        || (children.item(i).getNodeType() == Node.CDATA_SECTION_NODE)) {
                    value = value + children.item(i).getNodeValue().trim();
                }
            } // end looping over the children nodes
        }
    }

    // Return the value of the node.
    return value;
}

From source file:org.adl.sequencer.ADLSeqUtilities.java

/**
 * Attempts to find the indicated subelement of the current node and
 * extact its value.//from   www  .  j  a  va  2s .c om
 *
 * @param iNode    The DOM node of the target element.
 *
 * @param iElement The requested subelement.
 *
 * @return The value of the requested subelement of target element, or
 *         <code>null</code> if the subelement does not exist.
 */
private static String getElementText(Node iNode, String iElement) {

    if (_Debug) {
        System.out.println("  :: ADLSeqUtilities  --> BEGIN - " + "getElementText");
        System.out.println("  ::-->  " + iElement);
    }

    StringBuilder value = new StringBuilder();
    Node curNode = null;
    NodeList children = null;

    if (iElement != null && iNode != null) {
        children = iNode.getChildNodes();

        // Locate the target subelement
        for (int i = 0; i < children.getLength(); i++) {
            curNode = children.item(i);

            // Check to see if this is an element node.
            if (curNode.getNodeType() == Node.ELEMENT_NODE) {
                if (_Debug) {
                    System.out.println("  ::-->   " + i);
                    System.out.println("  ::-->  <" + curNode.getLocalName() + ">");
                }

                if (curNode.getLocalName().equals(iElement)) {
                    if (_Debug) {
                        System.out.println("  ::--> Found <" + iElement + ">");
                    }

                    break;
                }
            }
        }

        if (curNode != null) {
            String comp = curNode.getLocalName();

            if (comp != null) {
                // Make sure we found the subelement
                if (!comp.equals(iElement)) {
                    curNode = null;
                }
            } else {
                curNode = null;
            }
        }
    } else {
        curNode = iNode;
    }

    if (curNode != null) {
        if (_Debug) {
            System.out.println("  ::--> Looking at children");
        }

        // Extract the element's text value.
        children = curNode.getChildNodes();

        // Cycle through all children of node to get the text
        if (children != null) {
            // There must be a value
            value = new StringBuilder();

            for (int i = 0; i < children.getLength(); i++) {
                curNode = children.item(i);

                // make sure we have a 'text' element
                if ((curNode.getNodeType() == Node.TEXT_NODE)
                        || (curNode.getNodeType() == Node.CDATA_SECTION_NODE)) {
                    value.append(curNode.getNodeValue());
                }
            }
        }
    }

    if (_Debug) {
        System.out.println("  ::-->  " + value);
        System.out.println("  :: ADLSeqUtilities  --> END   - " + "getElementText");
    }

    return value.toString();
}

From source file:org.adl.validator.contentpackage.CPValidator.java

/**
 * This method performs the meat of the application profile checks. The
 * application profiles are described in XML format. Each application
 * profile has its own XML representation. These XML rules are parsed in
 * order to form a document object. The test subject manifest is also
 * available in document format. This method compares the manifest to the
 * rules described in the XML dom. This recursive method is driven by the
 * test subject dom./*from w  w w.  j a  v a 2s. co  m*/
 * 
 * @param iTestSubjectNode
 *            Test Subject DOM
 * @param iPath
 *            Path of the rule to compare to
 * @return - boolean result of the checks performed. True if the check was
 *         conformant, false otherwise.
 */
private boolean compareToRules(Node iTestSubjectNode, String iPath) {
    // is there anything to do?
    if (iTestSubjectNode == null)
        return false;

    mLogger.debug("CPValidator compareToRules");
    mLogger.debug("Node: " + iTestSubjectNode.getLocalName());
    mLogger.debug("Namespace: " + iTestSubjectNode.getNamespaceURI());
    mLogger.debug("Path: " + iPath);

    boolean result = true;
    String msgText = "";

    // Determine which type of DOM Tree Node we are dealing with
    switch (iTestSubjectNode.getNodeType()) {
    case Node.PROCESSING_INSTRUCTION_NODE: {
        // Skip any processing instructions, nothing for us to do
        break;
    }
    case Node.DOCUMENT_NODE: {
        // Found the root document node
        Node rootNode = ((Document) iTestSubjectNode).getDocumentElement();
        String rootNodeName = rootNode.getLocalName();

        mLogger.debug("DOCUMENT_NODE found");
        mLogger.debug("Namespace: " + rootNode.getNamespaceURI());
        mLogger.debug("Node Name: " + rootNodeName);

        mLogger.debug("INFO: Testing element <" + rootNodeName + "> for minimum conformance");
        DetailedLogMessageCollection.getInstance().addMessage(
                new LogMessage(MessageType.INFO, Messages.getString("CPValidator.131", rootNodeName)));

        mLogger.debug("PASSED: Multiplicity for element <" + rootNodeName + "> has been verified");
        DetailedLogMessageCollection.getInstance().addMessage(
                new LogMessage(MessageType.PASSED, Messages.getString("CPValidator.135", rootNodeName)));

        result = compareToRules(rootNode, "") && result;

        break;
    }
    case Node.ELEMENT_NODE: {
        // Found an Element Node
        String parentNodeName = iTestSubjectNode.getLocalName();

        if (parentNodeName.equals("manifest")) {
            // retrieve resources nodes for sco reference validation
            Node resourcesNode = DOMTreeUtility.getNode(iTestSubjectNode, "resources");

            if (resourcesNode != null) {
                // retrieve resource nodes for sco reference validation
                mResourceNodes = DOMTreeUtility.getNodes(resourcesNode, "resource");
                // Must also track resource identifier values for
                // dependency identifierref scope validation

                trackResourceIdentifiers(resourcesNode);
            }
        }

        String dataType = null;
        int multiplicityUsed = -1;
        int minRule = -1;
        int maxRule = -1;
        int spmRule = -1;

        mLogger.debug("Looping through attributes for the input " + "element <" + parentNodeName + ">");

        // Look for the attributes of this element
        NamedNodeMap attrList = iTestSubjectNode.getAttributes();
        int numAttr = attrList.getLength();
        mLogger.debug("There are " + numAttr + " attributes of <" + parentNodeName + "> elememt to test");

        Attr currentAttrNode = null;
        String currentNodeName = "";
        String attributeValue = "";

        // Loop throught attributes
        for (int i = 0; i < numAttr; i++) {
            currentAttrNode = (Attr) attrList.item(i);
            currentNodeName = currentAttrNode.getLocalName();

            mLogger.debug("Processing the [" + currentAttrNode.getNamespaceURI() + "] " + currentNodeName
                    + " attribute of the <" + parentNodeName + "> element.");

            // If the current attribute is persistState then additional
            // checks may be necessary
            if (currentNodeName.equalsIgnoreCase("persistState")) {
                // we must fail. SCORM 3rd Edition Addendum has removed the
                // persistState attribute from the adlcp namespaced schema
                msgText = Messages.getString("CPValidator.274", currentNodeName);
                mLogger.debug("FAILED: " + msgText);
                DetailedLogMessageCollection.getInstance()
                        .addMessage(new LogMessage(MessageType.FAILED, msgText));

                result = false;
            }

            // If the current attribute is scormType then additional
            // checks may be necessary
            if (currentNodeName.equalsIgnoreCase("scormType")) {
                // Application Profile Check: Check to make sure that the
                // adlcp:scormType attribute can only appear on an
                // <imscp:resource> element

                result = checkSCORMTypeReq(currentAttrNode, iTestSubjectNode) && result;

            }

            // If the current attribute is objectivesGlobalToSystem then
            // additional checks may be necessary
            if (currentNodeName.equalsIgnoreCase("objectivesGlobalToSystem")) {
                // Application Profile Check: Check that the
                // adlseq:objectivesGlobalToSystem attribute can only appear
                // on an <imscp:organization> element.
                result = checkObjGlobalToSystemReq(currentAttrNode, iTestSubjectNode) && result;
            }

            // Retrieve the application profile rules only if the the
            // current
            // attribute being processed has SCORM application profile
            // requirements
            mLogger.debug("Additional checks needed for attribute [" + currentNodeName + "].\r\n");

            // Retreive the data type rules
            dataType = mRulesValidator.getRuleValue(parentNodeName, iPath, "datatype", currentNodeName);

            // If the data type rules are for an xml:base, then there is
            // more processing that needs to take place.
            if (dataType.equalsIgnoreCase("xmlbase")) {
                // This is a xml:base data type
                msgText = Messages.getString("CPValidator.164", currentNodeName);
                mLogger.debug("INFO: " + msgText);
                DetailedLogMessageCollection.getInstance()
                        .addMessage(new LogMessage(MessageType.INFO, msgText));

                multiplicityUsed = getMultiplicityUsed(attrList, currentNodeName);

                // We will assume that no attribute can exist more than
                // once (ever). According to W3C. Therefore, min and max
                // rules must exist.

                // Get the min rule and convert to an int
                minRule = Integer
                        .parseInt(mRulesValidator.getRuleValue(parentNodeName, iPath, "min", currentNodeName));

                // Get the max rule and convert to an int
                maxRule = Integer
                        .parseInt(mRulesValidator.getRuleValue(parentNodeName, iPath, "max", currentNodeName));

                if ((minRule != -1) || (maxRule != -1)) {
                    if (multiplicityUsed >= minRule && multiplicityUsed <= maxRule) {
                        msgText = Messages.getString("CPValidator.169", currentNodeName);
                        mLogger.debug("PASSED: " + msgText);
                        DetailedLogMessageCollection.getInstance()
                                .addMessage(new LogMessage(MessageType.PASSED, msgText));
                    } else {
                        msgText = Messages.getString("CPValidator.175", currentNodeName);
                        mLogger.debug("FAILED: " + msgText);
                        DetailedLogMessageCollection.getInstance()
                                .addMessage(new LogMessage(MessageType.FAILED, msgText));

                        result = false;

                    } // mult used >= minRule && mult used <= maxRule
                } // end minRule != -1, maxRule != -1

                // Get the spm rule and convert to an int
                spmRule = Integer
                        .parseInt(mRulesValidator.getRuleValue(parentNodeName, iPath, "spm", currentNodeName));

                attributeValue = currentAttrNode.getValue();

                // Check the attributes for smallest permitted maximum(spm)
                // conformance.

                result = checkSPMConformance(currentNodeName, attributeValue, spmRule, true) && result;

                // Check to make sure slashes are correct
                result = checkForSlashes("xml:base", attributeValue) && result;

                if (parentNodeName.equals("manifest")) {
                    mXMLBase[0][1] = attributeValue;
                    mLogger.debug(" XML:base found in manifest, value is " + attributeValue);
                } else if (parentNodeName.equals("resources")) {
                    mXMLBase[1][1] = attributeValue;
                    mLogger.debug(" XML:base found in resources, value is " + attributeValue);
                } else if (parentNodeName.equals("resource")) {
                    mXMLBase[2][1] = attributeValue;
                    mLogger.debug(" XML:base found in resource, value is " + attributeValue);
                }
            } // end if xml:base
        } // end looping over set of attributes for the element

        // If we are processing an <imscp:manifest> element, then there
        // are special cases application profile checks needed.
        if (parentNodeName.equalsIgnoreCase("manifest")) {
            mLogger.debug("Manifest node, additional check's being done.");
            mLogger.debug("Determining how many times the " + "identifier attribute is present.");

            multiplicityUsed = getMultiplicityUsed(attrList, "identifier");

            if (multiplicityUsed < 1) {
                mLogger.debug("FAILED: Mandatory attribute \"identifier\"" + " could not be found");
                DetailedLogMessageCollection.getInstance().addMessage(new LogMessage(MessageType.FAILED,
                        Messages.getString("CPValidator.198", "identifier")));

                result = false;
            }
        } else if (parentNodeName.equalsIgnoreCase("organizations")
                && (mRulesValidator.getApplicationProfile()).equals("contentaggregation")) {
            // multiple <organization> elements exist, but there is no
            // default attribute.
            // not a conformance check, warning only
            multiplicityUsed = getMultiplicityUsed(attrList, "default");

            if (multiplicityUsed < 1) {
                mLogger.debug("ERROR: Mandatory attribute \"default\" " + "could not be found");
                DetailedLogMessageCollection.getInstance().addMessage(
                        new LogMessage(MessageType.FAILED, Messages.getString("CPValidator.198", "default")));

                result = false;
            }
        } else if (parentNodeName.equalsIgnoreCase("organization")
                && (mRulesValidator.getApplicationProfile()).equals("contentaggregation")) {
            multiplicityUsed = getMultiplicityUsed(attrList, "identifier");
            if (multiplicityUsed < 1) {
                mLogger.debug("FAILED: Mandatory attribute \"identifier\" " + "could not be found");
                DetailedLogMessageCollection.getInstance().addMessage(new LogMessage(MessageType.FAILED,
                        Messages.getString("CPValidator.198", "identifier")));

                result = false;
            }
        } else if (parentNodeName.equalsIgnoreCase("item")
                && (mRulesValidator.getApplicationProfile()).equals("contentaggregation")) {
            multiplicityUsed = getMultiplicityUsed(attrList, "identifier");
            if (multiplicityUsed < 1) {
                mLogger.debug("FAILED: Mandatory attribute \"identifier\" " + "could not be found");
                DetailedLogMessageCollection.getInstance().addMessage(new LogMessage(MessageType.FAILED,
                        Messages.getString("CPValidator.198", "identifier")));

                result = false;
            }

            // need to perform a special check to warn when parameters
            // are present but no identifierref is
            int idrefMult = -1;
            int paramMult = -1;

            idrefMult = getMultiplicityUsed(attrList, "identifierref");
            paramMult = getMultiplicityUsed(attrList, "parameters");

            if ((idrefMult < 1) && !(paramMult < 1)) {
                // we have a parameters but no identifierref - warning
                msgText = Messages.getString("CPValidator.220");

                mLogger.debug("WARNING: " + msgText);

                DetailedLogMessageCollection.getInstance()
                        .addMessage(new LogMessage(MessageType.WARNING, msgText));

            }
            // have to store the idref values in a List for future
            // app profile checking of resource attributes

            if (idrefMult >= 1) {
                String iDREFValue = DOMTreeUtility.getAttributeValue(iTestSubjectNode, "identifierref");

                boolean validIdref = mResourceIdentifierList.contains(iDREFValue);

                if (validIdref) {
                    mValidIdrefs.add(iDREFValue);
                }

                // Whether or not it is true we need to keep track of ALL of
                // the idrefs so we can look for dangling references after
                // the entire list of refs, including those on sub-manifests
                // have been inventoried.
                mAllIdrefsList.add(iDREFValue);

            }

            // Perform a special check to ensure that initialization data
            // only exists on items that reference SCOs
            NodeList childrenOfItem = iTestSubjectNode.getChildNodes();
            if (childrenOfItem != null) {
                Node currentItemChild;
                String currentItemChildName;
                int len = childrenOfItem.getLength();
                for (int k = 0; k < len; k++) {
                    currentItemChild = childrenOfItem.item(k);
                    currentItemChildName = currentItemChild.getLocalName();

                    if (currentItemChildName.equals("timeLimitAction")
                            || currentItemChildName.equals("dataFromLMS")
                            || currentItemChildName.equals("completionThreshold")) {
                        if (idrefMult < 1) {
                            // we have an item that contains initialization
                            // data
                            // and does not reference a resource at all

                            result = false;

                            msgText = Messages.getString("CPValidator.226", currentItemChildName);

                            mLogger.debug("FAILED: " + msgText);
                            DetailedLogMessageCollection.getInstance()
                                    .addMessage(new LogMessage(MessageType.FAILED, msgText));

                        } else {
                            // we must verify that the resource it is
                            // referencing
                            // is a sco

                            String idrefValue = DOMTreeUtility.getAttributeValue(iTestSubjectNode,
                                    "identifierref");

                            result = result && checkForReferenceToSco(idrefValue);

                        }
                    }
                }
            }
        } else if (parentNodeName.equalsIgnoreCase("resource")) {
            checkBucketUniqueness(iTestSubjectNode);
            boolean resourceResult = checkResourceAttributes(iTestSubjectNode, attrList);

            result = result && resourceResult;
        } else if (parentNodeName.equalsIgnoreCase("bucket")) {
            checkBucketAttributes(iTestSubjectNode);
        } else if (parentNodeName.equalsIgnoreCase("size")) {
            checkSizeAttributes(iTestSubjectNode);
        }

        // test the attributes

        for (int j = 0; j < numAttr; j++) {
            currentAttrNode = (Attr) attrList.item(j);
            currentNodeName = currentAttrNode.getLocalName();

            dataType = mRulesValidator.getRuleValue(parentNodeName, iPath, "datatype", currentNodeName);

            // we do not want to test for xml namespaces or extensions

            if (dataType.equalsIgnoreCase("idref") || dataType.equalsIgnoreCase("id")
                    || dataType.equalsIgnoreCase("vocabulary") || dataType.equalsIgnoreCase("text")
                    || dataType.equalsIgnoreCase("uri")) {
                msgText = Messages.getString("CPValidator.164", currentNodeName);
                mLogger.debug("INFO: " + msgText);
                DetailedLogMessageCollection.getInstance()
                        .addMessage(new LogMessage(MessageType.INFO, msgText));

                multiplicityUsed = getMultiplicityUsed(attrList, currentNodeName);

                // We will assume that no attribute can exist more than
                // once (ever). According to W3C. Therefore, min and max
                // rules must exist.

                // get the min rule and convert to an int

                minRule = Integer
                        .parseInt(mRulesValidator.getRuleValue(parentNodeName, iPath, "min", currentNodeName));

                // get the max rule and convert to an int

                maxRule = Integer
                        .parseInt(mRulesValidator.getRuleValue(parentNodeName, iPath, "max", currentNodeName));

                if ((minRule != -1) || (maxRule != -1)) {
                    if (multiplicityUsed >= minRule && multiplicityUsed <= maxRule) {
                        msgText = Messages.getString("CPValidator.169", currentNodeName);
                        mLogger.debug("PASSED: " + msgText);

                        DetailedLogMessageCollection.getInstance()
                                .addMessage(new LogMessage(MessageType.PASSED, msgText));
                    } else {
                        msgText = Messages.getString("CPValidator.175", currentNodeName);
                        mLogger.debug("FAILED: " + msgText);
                        DetailedLogMessageCollection.getInstance()
                                .addMessage(new LogMessage(MessageType.FAILED, msgText));

                        result = false;
                    }
                }

                // get the spm rule and convert to an int
                spmRule = Integer
                        .parseInt(mRulesValidator.getRuleValue(parentNodeName, iPath, "spm", currentNodeName));

                attributeValue = currentAttrNode.getValue();

                if (dataType.equalsIgnoreCase("idref")) {
                    // This is a IDREF data type
                    // check the attributes for smallest permitted maximum
                    // (spm) conformance.

                    result = checkSPMConformance(currentNodeName, attributeValue, spmRule, true) && result;

                    // check the Default Idref to make sure it points to an
                    // valid identifier.

                    if (currentNodeName.equalsIgnoreCase("default")) {
                        boolean foundDefaultIdentifier = false;
                        // check for this identifer in the organization list
                        int numOrganizationIdentifiers = mOrganizationIdentifierList.size();

                        for (int i = 0; i < numOrganizationIdentifiers; i++) {
                            String identifier = (mOrganizationIdentifierList.get(i));

                            if (identifier.equals(attributeValue)) {
                                foundDefaultIdentifier = true;

                                break;
                            }
                        }
                        if (foundDefaultIdentifier) {
                            msgText = Messages.getString("CPValidator.251", currentNodeName);
                            mLogger.debug("PASSED: " + msgText);
                            DetailedLogMessageCollection.getInstance()
                                    .addMessage(new LogMessage(MessageType.PASSED, msgText));
                        } else {
                            msgText = Messages.getString("CPValidator.254", currentNodeName);
                            mLogger.debug("FAILED: " + msgText);
                            DetailedLogMessageCollection.getInstance()
                                    .addMessage(new LogMessage(MessageType.FAILED, msgText));

                            result = false;
                        }
                    }
                    if (currentNodeName.equalsIgnoreCase("identifierref")
                            && parentNodeName.equalsIgnoreCase("dependency")) {
                        mAllIdrefsList.add(currentAttrNode.getValue());
                    }

                } else if (dataType.equalsIgnoreCase("id")) {
                    // This is a id data type
                    // check the attributes for smallest permitted maximum
                    // (spm) conformance.

                    result = checkSPMConformance(currentNodeName, attributeValue, spmRule, true) && result;

                    if (parentNodeName.equals("manifest")) {
                        mManifestID = currentAttrNode.getValue();
                        mLogger.debug("mManifestID is " + mManifestID);
                    }

                    // imsssp id attributes here
                } else if (dataType.equalsIgnoreCase("uri")) {
                    // This is a URI data type
                    // check the attributes for smallest permitted maximum
                    // (spm) conformance. Only perform these checks if
                    // the value is not an empty string

                    String myAttributeValue = currentAttrNode.getValue();
                    if (!myAttributeValue.equals("")) {
                        // check to ensure there are no leading slashes
                        result = checkForSlashes("href", myAttributeValue) && result;

                        // check if the file exists
                        // apply xml:base on href value before href checks
                        if (doesXMLBaseExist()) {
                            mLogger.debug("APPLYING XML BASE");
                            myAttributeValue = applyXMLBase(myAttributeValue);
                        }

                        if (myAttributeValue.indexOf('\\') != -1) {
                            msgText = Messages.getString("CPValidator.265", myAttributeValue);

                            mLogger.debug("FAILED: " + msgText);
                            DetailedLogMessageCollection.getInstance()
                                    .addMessage(new LogMessage(MessageType.FAILED, msgText));

                            result &= false;
                        }

                        // check href spm after it is pre-appended with
                        // xml:base
                        result = checkSPMConformance(currentNodeName, myAttributeValue, spmRule, true)
                                && result;

                        result = checkHref(myAttributeValue) && result;

                    }
                } else if (dataType.equalsIgnoreCase("vocabulary")) {
                    // This is a VOCAB data type
                    // retrieve the vocab rule values and check against the
                    // vocab values that exist within the test subject

                    msgText = "Testing attribute \"" + currentNodeName + "\" for valid vocabulary";
                    mLogger.debug("INFO: " + msgText);

                    List<String> vocabAttribValues = mRulesValidator.getAttribVocabRuleValues(parentNodeName,
                            iPath, currentNodeName);
                    // we are assuming that only 1 vocabulary value may
                    // exist for an attribute

                    result = checkVocabulary(currentNodeName, attributeValue, vocabAttribValues, true)
                            && result;
                } else if (dataType.equalsIgnoreCase("text")) {
                    // This is a TEXT data type
                    // check the attributes for smallest permitted maximum
                    // (spm) conformance.

                    result = checkSPMConformance(currentNodeName, attributeValue, spmRule, true) && result;

                    // test the parameter attribute for valid syntax
                    if (currentNodeName.equalsIgnoreCase("parameters")) {
                        ParameterChecker pc = new ParameterChecker();
                        result = pc.checkParameters(attributeValue) && result;
                    }
                }
            }
        } // done with attributes

        // Test the child Nodes

        NodeList children = iTestSubjectNode.getChildNodes();

        if (children != null) {
            int numChildren = children.getLength();

            // update the path for this child element

            String path;

            if (iPath.equals("")) {
                // the node is a DOCUMENT or a root <manifest>
                path = parentNodeName;
            } else if ((iPath.equals("manifest.manifest")) && (parentNodeName.equals("manifest"))) {
                path = iPath;
            } else if (parentNodeName.equalsIgnoreCase("item")) {
                // the Node is an <imscp:item>
                if (iPath.equals("manifest.organizations.organization.item")) {
                    path = iPath;
                } else {
                    path = iPath + "." + parentNodeName;
                }
            } else {
                path = iPath + "." + parentNodeName;
            }

            // SPECIAL CASE: check for mandatory elements

            if (parentNodeName.equalsIgnoreCase("manifest")) {

                // check for mandatory metadata element at package level
                multiplicityUsed = getMultiplicityUsed(iTestSubjectNode, "metadata");
                if (multiplicityUsed < 1) {
                    msgText = Messages.getString("CPValidator.287", "metadata");
                    mLogger.debug("FAILED: " + msgText);
                    DetailedLogMessageCollection.getInstance()
                            .addMessage(new LogMessage(MessageType.FAILED, msgText));

                    result = false;
                } else
                // check for mandatory children
                {
                    Node caMetadataNode = DOMTreeUtility.getNode(iTestSubjectNode, "metadata");

                    // check for mandatory <imscp:schema> element
                    multiplicityUsed = getMultiplicityUsed(caMetadataNode, "schema");

                    if (multiplicityUsed < 1) {
                        msgText = Messages.getString("CPValidator.287", "schema");
                        mLogger.debug("FAILED: " + msgText);
                        DetailedLogMessageCollection.getInstance()
                                .addMessage(new LogMessage(MessageType.FAILED, msgText));

                        result = false;
                    }

                    // check for mandatory <imscp:schemaversion> element
                    multiplicityUsed = getMultiplicityUsed(caMetadataNode, "schemaversion");

                    if (multiplicityUsed < 1) {
                        msgText = Messages.getString("CPValidator.287", "schemaversion");
                        mLogger.debug("FAILED: " + msgText);
                        DetailedLogMessageCollection.getInstance()
                                .addMessage(new LogMessage(MessageType.FAILED, msgText));

                        result = false;
                    }
                }

                multiplicityUsed = getMultiplicityUsed(iTestSubjectNode, "organizations");
                if (multiplicityUsed < 1) {
                    msgText = Messages.getString("CPValidator.287", "organizations");
                    mLogger.debug("FAILED: " + msgText);
                    DetailedLogMessageCollection.getInstance()
                            .addMessage(new LogMessage(MessageType.FAILED, msgText));

                    result = false;
                }

                multiplicityUsed = getMultiplicityUsed(iTestSubjectNode, "resources");
                if (multiplicityUsed < 1) {
                    msgText = Messages.getString("CPValidator.287", "resources");
                    mLogger.debug("FAILED: " + msgText);
                    DetailedLogMessageCollection.getInstance()
                            .addMessage(new LogMessage(MessageType.FAILED, msgText));

                    result = false;
                }
            } else if (parentNodeName.equalsIgnoreCase("organizations")
                    && (mRulesValidator.getApplicationProfile()).equals("contentaggregation")) {
                multiplicityUsed = getMultiplicityUsed(iTestSubjectNode, "organization");

                if (multiplicityUsed < 1) {
                    msgText = Messages.getString("CPValidator.287", "organization");

                    mLogger.debug("FAILED: " + msgText);
                    DetailedLogMessageCollection.getInstance()
                            .addMessage(new LogMessage(MessageType.FAILED, msgText));

                    result = false;
                }

            }
            // have to check to ensure that empty organizations exist
            // for resource package

            else if (parentNodeName.equalsIgnoreCase("organizations")
                    && (mRulesValidator.getApplicationProfile()).equals("resource")) {
                multiplicityUsed = getMultiplicityUsed(iTestSubjectNode, "organization");
                if (multiplicityUsed > 0) {
                    msgText = Messages.getString("CPValidator.311");
                    mLogger.debug("FAILED: " + msgText);
                    DetailedLogMessageCollection.getInstance()
                            .addMessage(new LogMessage(MessageType.FAILED, msgText));

                    result = false;
                } else {
                    msgText = Messages.getString("CPValidator.312");
                    // we have an empty <orgs> element, display a valid msg
                    mLogger.debug("PASSED: " + msgText);
                    DetailedLogMessageCollection.getInstance()
                            .addMessage(new LogMessage(MessageType.PASSED, msgText));

                }
            } else if (parentNodeName.equalsIgnoreCase("organization")
                    && (mRulesValidator.getApplicationProfile()).equals("contentaggregation")) {
                multiplicityUsed = getMultiplicityUsed(iTestSubjectNode, "title");
                if (multiplicityUsed < 1) {
                    msgText = Messages.getString("CPValidator.287", "title");
                    mLogger.debug("FAILED: " + msgText);
                    DetailedLogMessageCollection.getInstance()
                            .addMessage(new LogMessage(MessageType.FAILED, msgText));

                    result = false;
                }

                multiplicityUsed = getMultiplicityUsed(iTestSubjectNode, "item");
                if (multiplicityUsed < 1) {
                    msgText = Messages.getString("CPValidator.287", "item");
                    mLogger.debug("FAILED: " + msgText);
                    DetailedLogMessageCollection.getInstance()
                            .addMessage(new LogMessage(MessageType.FAILED, msgText));

                    result = false;
                }

                // special checks for item
                result = checkItem(iTestSubjectNode, mManifestInfo) && result;

            }

            for (int z = 0; z < numChildren; z++) {

                Node currentChild = children.item(z);
                String currentChildName = currentChild.getLocalName();

                msgText = "Currentchild is " + currentChildName + " and path is " + path;

                mLogger.debug(msgText);

                if (currentChildName != null) {

                    if (((currentChildName.equals("timeLimitAction"))
                            || (currentChildName.equals("dataFromLMS"))
                            || (currentChildName.equals("completionThreshold"))
                            || (currentChildName.equals("presentation"))) && (!parentNodeName.equals("item"))) {
                        result = false;

                        msgText = Messages.getString("CPValidator.328", currentChildName, "item");

                        mLogger.debug("FAILED: " + msgText);
                        DetailedLogMessageCollection.getInstance()
                                .addMessage(new LogMessage(MessageType.FAILED, msgText));
                    }

                    if (((currentChildName.equals("constrainedChoiceConsiderations"))
                            || (currentChildName.equals("rollupConsiderations")))
                            && (!parentNodeName.equals("sequencing"))) {

                        result = false;

                        msgText = Messages.getString("CPValidator.328", currentChildName, "sequencing");

                        mLogger.debug("FAILED: " + msgText);
                        DetailedLogMessageCollection.getInstance()
                                .addMessage(new LogMessage(MessageType.FAILED, msgText));
                    }

                    // must enforce that the adlcp:location exist
                    // as a child of metadata only - warning for best
                    // practice.

                    if ((currentChildName.equals("location")) && (!parentNodeName.equals("metadata"))) {

                        result = false;

                        msgText = Messages.getString("CPValidator.328", currentChildName, "metadata");

                        mLogger.debug("WARNING: " + msgText);
                        DetailedLogMessageCollection.getInstance()
                                .addMessage(new LogMessage(MessageType.WARNING, msgText));
                    }

                    if ((currentChildName.equals("sequencing")) && (!parentNodeName.equals("item"))
                            && (!parentNodeName.equals("organization"))) {

                        result = false;

                        msgText = Messages.getString("CPValidator.345", currentChildName);

                        mLogger.debug("FAILED: " + msgText);
                        DetailedLogMessageCollection.getInstance()
                                .addMessage(new LogMessage(MessageType.FAILED, msgText));
                    }

                    dataType = mRulesValidator.getRuleValue(currentChildName, path, "datatype");
                    // must enforce that the imsssp:bucket exist
                    // as a child of a resource only.

                    if ((currentChildName.equals("bucket")) && (!parentNodeName.equals("resource"))) {
                        // Check to enforce that bucket is a child of a
                        // resource
                        msgText = "<" + currentChildName + "> can only " + "exist as a child of a <resource>";

                        mLogger.debug("SSP: " + msgText);
                        DetailedLogMessageCollection.getInstance()
                                .addMessage(new LogMessage(MessageType.FAILED, msgText));

                    }

                    // must enforce that the imsssp:size exist
                    // as a child of a bucket only.

                    if ((currentChildName.equals("size")) && (!parentNodeName.equals("bucket"))) {

                        msgText = "<" + currentChildName + "> can only " + "exist as a child of a <bucket>";

                        mLogger.debug("SSP: " + msgText);
                        DetailedLogMessageCollection.getInstance()
                                .addMessage(new LogMessage(MessageType.FAILED, msgText));
                    }

                    // Check the SCORMType of the resource; it must be sco
                    if ((currentChildName.equals("bucket")) && (parentNodeName.equals("resource"))) {
                        // Now check to ensure that the resource type is SCO
                        String typeS = DOMTreeUtility.getAttributeValue(iTestSubjectNode, "scormType");

                        if (!typeS.equalsIgnoreCase("sco")) {
                            // result = false;

                            msgText = "The <" + currentChildName + "> shall"
                                    + " only exist in a resource that is " + " scormType = \"sco\".";

                            mLogger.debug("SSP: " + msgText);
                            DetailedLogMessageCollection.getInstance()
                                    .addMessage(new LogMessage(MessageType.FAILED, msgText));
                        }

                    }

                    // we do not want to test for extensions here

                    if (dataType.equalsIgnoreCase("parent") || dataType.equalsIgnoreCase("vocabulary")
                            || dataType.equalsIgnoreCase("text") || dataType.equalsIgnoreCase("sequencing")
                            || dataType.equalsIgnoreCase("metadata") || dataType.equalsIgnoreCase("decimal")) {
                        // SCORM 3rd edition -- we need to ignore
                        // (sub)manifest
                        // and warn only

                        if (currentChildName.equals("manifest") && path.equals("manifest")) {
                            msgText = Messages.getString("CPValidator.100");
                            mLogger.debug("WARNING: " + msgText);
                            DetailedLogMessageCollection.getInstance()
                                    .addMessage(new LogMessage(MessageType.WARNING, msgText));

                            // Make cleansing call for excess baggage here
                            // pass (sub)manifest node into a new function

                            // retrieve all adlcp:location uri's contained
                            // in the
                            // (sub)manifest
                            List<String> submanifestURIList = mManifestHandler.getLocationMD(currentChild);
                            trackSubManifest(currentChild, submanifestURIList);
                        } else
                        // we are not dealing with (sub)manifest
                        {
                            msgText = Messages.getString("CPValidator.131", currentChildName);

                            mLogger.debug("INFO: " + msgText);
                            DetailedLogMessageCollection.getInstance()
                                    .addMessage(new LogMessage(MessageType.INFO, msgText));

                            multiplicityUsed = getMultiplicityUsed(iTestSubjectNode, currentChildName);

                            // get the min rule and convert to an int

                            minRule = Integer
                                    .parseInt(mRulesValidator.getRuleValue(currentChildName, path, "min"));

                            // get the max rule and convert to an int

                            maxRule = Integer
                                    .parseInt(mRulesValidator.getRuleValue(currentChildName, path, "max"));

                            if ((minRule != -1) && (maxRule != -1)) {
                                if (multiplicityUsed >= minRule && multiplicityUsed <= maxRule) {
                                    msgText = Messages.getString("CPValidator.135", currentChildName);
                                    mLogger.debug("PASSED: " + msgText);
                                    DetailedLogMessageCollection.getInstance()
                                            .addMessage(new LogMessage(MessageType.PASSED, msgText));
                                } else {
                                    msgText = Messages.getString("CPValidator.364", currentChildName);
                                    mLogger.debug("FAILED: " + msgText);
                                    DetailedLogMessageCollection.getInstance()
                                            .addMessage(new LogMessage(MessageType.FAILED, msgText));

                                    result = false;
                                }
                            } else if ((minRule != -1) && (maxRule == -1)) {
                                if (multiplicityUsed >= minRule) {
                                    msgText = Messages.getString("CPValidator.135", currentChildName);
                                    mLogger.debug("PASSED: " + msgText);
                                    DetailedLogMessageCollection.getInstance()
                                            .addMessage(new LogMessage(MessageType.PASSED, msgText));
                                } else {
                                    msgText = Messages.getString("CPValidator.364", currentChildName);
                                    mLogger.debug("FAILED: " + msgText);
                                    DetailedLogMessageCollection.getInstance()
                                            .addMessage(new LogMessage(MessageType.FAILED, msgText));

                                    result = false;
                                }
                            }
                            // test for each particular data type

                            if (dataType.equalsIgnoreCase("parent")) {
                                // need to populate the files that belong to
                                // each resource
                                if (currentChildName.equals("resources")) {
                                    populateResourceTable(currentChild);
                                }

                                // Verify that if the resource href matches
                                // the file href if the resource is local
                                if (currentChildName.equals("resource")) {
                                    result = checkResourceFileHref(currentChild) && result;
                                }

                                // This is a parent element, need to recurse
                                result = compareToRules(currentChild, path) && result;

                            } else if (dataType.equalsIgnoreCase("sequencing")) {
                                // This is a sequencing data type

                                SequenceValidator sequenceValidator = new SequenceValidator();

                                result = sequenceValidator.validate(currentChild) && result;
                            } else if (dataType.equalsIgnoreCase("metadata")) {
                                // This is a metadata data type - no longer
                                // need
                                // to
                                // check for lom and location to coexist
                                // must detect that the metadata exists in
                                // location
                                if (currentChildName.equals("location")) {
                                    String currentLocationValue = mRulesValidator.getTaggedData(currentChild);

                                    // check to ensure there are no leading
                                    // slashes
                                    result = checkForSlashes("location", currentLocationValue) && result;

                                    currentLocationValue = applyXMLBase(currentLocationValue);

                                    result = result && checkHref(currentLocationValue);
                                }
                            } else if (dataType.equalsIgnoreCase("text")) {
                                // This is a text data type
                                // check spm

                                // first must retrieve the value of this
                                // child
                                // element

                                String currentChildValue = mRulesValidator.getTaggedData(currentChild);

                                // get the spm rule and convert to an int

                                spmRule = Integer
                                        .parseInt(mRulesValidator.getRuleValue(currentChildName, path, "spm"));

                                result = checkSPMConformance(currentChildName, currentChildValue, spmRule,
                                        false) && result;
                            } else if (dataType.equalsIgnoreCase("vocabulary")) {
                                // This is a vocabulary data type
                                // more than one vocabulary token may exist

                                msgText = Messages.getString("CPValidator.383", currentChildName);
                                mLogger.debug("INFO: " + msgText);
                                DetailedLogMessageCollection.getInstance()
                                        .addMessage(new LogMessage(MessageType.INFO, msgText));

                                // retrieve the value of this element

                                String currentChildValue = mRulesValidator.getTaggedData(currentChild);

                                List<String> vocabValues = mRulesValidator.getVocabRuleValues(currentChildName,
                                        path);

                                result = checkVocabulary(currentChildName, currentChildValue, vocabValues,
                                        false) && result;

                            } else if (dataType.equalsIgnoreCase("decimal")) {
                                // This is a decimal data type
                                // only adlcp:completionThreshold is of this
                                // type
                                // and currently all checks are enforced by
                                // the schema. No additional checks needed
                                // at
                                // this time.
                                result = true && result;
                            }
                        }
                    } // end ignorning and warning (sub)manifest
                } // end something
            }

        }
        // remove the xml:base value for this particular element

        if (parentNodeName.equals("manifest")) {
            mXMLBase[0][1] = "";
        } else if (parentNodeName.equals("resources")) {
            mXMLBase[1][1] = "";
        } else if (parentNodeName.equals("resource")) {
            mXMLBase[2][1] = "";
        }

        break;
    }

    // handle entity reference nodes
    case Node.ENTITY_REFERENCE_NODE: {
        break;
    }

    // text
    case Node.COMMENT_NODE: {
        break;
    }

    case Node.CDATA_SECTION_NODE: {
        break;
    }

    case Node.TEXT_NODE: {
        break;
    }
    default: {
        // Do nothing - no defined requirements to process any other
        // type of node type
        break;
    }
    }// end switch statement

    mLogger.debug("CPValidator compareToRules()");
    return result;
}

From source file:org.adl.validator.contentpackage.ManifestMap.java

/**
 * This method populates the ManifestMap object by traversing down
 * the document node and storing all information necessary for the validation
 * of (Sub) manifests.  Information stored for each manifest element includes:
 * manifest identifiers,item identifers, item identifierrefs, and
 * resource identifiers/* www .  j a v a 2s. com*/
 *
 * @param iNode the node being checked. All checks will depend on the type of node
 * being evaluated
 * 
 * @return - The boolean describing if the ManifestMap object(s) has been
 * populated properly.
 */
public boolean populateManifestMap(Node iNode) {
    // looks exactly like prunetree as we walk down the tree
    log.debug("populateManifestMap");

    boolean result = true;

    // is there anything to do?
    if (iNode == null) {
        result = false;
        return result;
    }

    int type = iNode.getNodeType();

    switch (type) {
    case Node.PROCESSING_INSTRUCTION_NODE: {
        break;
    }
    case Node.DOCUMENT_NODE: {
        Node rootNode = ((Document) iNode).getDocumentElement();

        result = populateManifestMap(rootNode) && result;

        break;
    }
    case Node.ELEMENT_NODE: {
        String parentNodeName = iNode.getLocalName();

        if (parentNodeName.equalsIgnoreCase("manifest")) {
            // We are dealing with an IMS <manifest> element, get the IMS
            // CP identifier for the <manifest> elememnt
            mManifestId = DOMTreeUtility.getAttributeValue(iNode, "identifier");

            log.debug(
                    "ManifestMap:populateManifestMap, " + "Just stored a Manifest Id value of " + mManifestId);

            // Recurse to populate mItemIdrefs and mItemIds

            // Find the <organization> elements

            Node orgsNode = DOMTreeUtility.getNode(iNode, "organizations");

            if (orgsNode != null) {
                List<Node> orgElems = DOMTreeUtility.getNodes(orgsNode, "organization");

                log.debug("ManifestMap:populateManifestMap, " + "Number of <organization> elements: "
                        + orgElems.size());

                if (!orgElems.isEmpty()) {
                    int orgElemsSize = orgElems.size();
                    for (int i = 0; i < orgElemsSize; i++) {
                        List<Node> itemElems = DOMTreeUtility.getNodes(orgElems.get(i), "item");

                        log.debug("ManifestMap:populateManifestMap, " + "Number of <item> elements: "
                                + itemElems.size());

                        if (!itemElems.isEmpty()) {
                            int itemElemsSize = itemElems.size();
                            for (int j = 0; j < itemElemsSize; j++) {
                                result = populateManifestMap((itemElems.get(j))) && result;
                            }
                        }
                    }
                }
            }

            //recurse to populate mResourceIds

            Node resourcesNode = DOMTreeUtility.getNode(iNode, "resources");

            if (resourcesNode != null) {
                List<Node> resourceElems = DOMTreeUtility.getNodes(resourcesNode, "resource");

                log.debug("ManifestMap:populateManifestMap, " + "Number of <resource> elements: "
                        + resourceElems.size());

                int resourceElemsSize = resourceElems.size();
                for (int k = 0; k < resourceElemsSize; k++) {
                    result = populateManifestMap((resourceElems.get(k))) && result;

                }
            }

            //recurse to populate mManifestMaps

            //find the <manifest> elements (a.k.a sub-manifests)
            List<Node> subManifests = DOMTreeUtility.getNodes(iNode, "manifest");

            log.debug("ManifestMap:populateManifestMap, " + "Number of (Sub) manifest elements: "
                    + subManifests.size());

            if (!subManifests.isEmpty()) {
                mDoSubmanifestExist = true;
                int subManifestSize = subManifests.size();
                for (int l = 0; l < subManifestSize; l++) {
                    ManifestMap manifestMapObject = new ManifestMap();
                    result = manifestMapObject.populateManifestMap(subManifests.get(l)) && result;
                    mManifestMaps.add(manifestMapObject);
                }

            }
        } else if (parentNodeName.equalsIgnoreCase("item")) {
            //store item identifier value
            String itemId = DOMTreeUtility.getAttributeValue(iNode, "identifier");

            mItemIds.add(itemId);

            log.debug("ManifestMap:populateManifestMap, " + "Just stored an Item Id value of " + itemId);

            //store item identifier reference value
            String itemIdref = DOMTreeUtility.getAttributeValue(iNode, "identifierref");

            mItemIdrefs.add(itemIdref);

            log.debug("ManifestMap:populateManifestMap, " + "Just stored an Item Idref value of " + itemIdref);

            //recurse to populate all child item elements
            List<Node> items = DOMTreeUtility.getNodes(iNode, "item");
            if (!items.isEmpty()) {
                int itemsSize = items.size();
                for (int z = 0; z < itemsSize; z++) {
                    result = populateManifestMap(items.get(z)) && result;
                }
            }
        } else if (parentNodeName.equalsIgnoreCase("resource")) {
            //store resource identifier value
            String resourceId = DOMTreeUtility.getAttributeValue(iNode, "identifier");
            // convert to lower so case sensativity does not play a role

            mResourceIds.add(resourceId);

            log.debug("ManifestMap:populateManifestMap, " + "Just stored a Resource Id value of " + resourceId);

            // populate <dependency> element

            List<Node> dependencyElems = DOMTreeUtility.getNodes(iNode, "dependency");

            int dependencyElemsSize = dependencyElems.size();

            for (int w = 0; w < dependencyElemsSize; w++) {
                Node dependencyElem = dependencyElems.get(w);

                //store resource identifier value
                String dependencyIdref = DOMTreeUtility.getAttributeValue(dependencyElem, "identifierref");

                mDependencyIdrefs.add(dependencyIdref);

                log.debug("ManifestMap:populateManifestMap, " + "Just stored a Dependency Idref value of "
                        + mDependencyIdrefs);
            }
        }

        break;
    }
    // handle entity reference nodes
    case Node.ENTITY_REFERENCE_NODE: {
        break;
    }

    // text
    case Node.COMMENT_NODE: {
        break;
    }

    case Node.CDATA_SECTION_NODE: {
        break;
    }

    case Node.TEXT_NODE: {
        break;
    }
    }

    log.debug("populateManifestMap");

    return result;
}

From source file:org.adl.validator.RulesValidator.java

/**
 * Retrieves the text from a text node//from  w  ww . j  av a2s.co  m
 *
 * @param iNode   TEXT_NODE that contains the needed text
 *
 * @return String describing the text contained in the given node
 */
public String getTaggedData(Node iNode) {
    log.debug("getTaggedData()");

    String value = "";
    NodeList kids = iNode.getChildNodes();

    //cycle through all children of node to get the text
    if (kids != null) {
        for (int i = 0; i < kids.getLength(); i++) {
            //make sure this is a "text node"
            if ((kids.item(i).getNodeType() == Node.TEXT_NODE)
                    || (kids.item(i).getNodeType() == Node.CDATA_SECTION_NODE)) {
                value = value + kids.item(i).getNodeValue().trim();
            }
        }
    } else {
        log.debug("%%% no kids for value %%%");

    }
    log.debug("getTaggedData()");

    return value;
}

From source file:org.ajax4jsf.templatecompiler.elements.A4JRendererElementsFactory.java

public TemplateElement getProcessor(final Node nodeElement, final CompilationContext componentBean)
        throws CompilationException {
    TemplateElement returnValue = null;//from  w ww  .  j  av a 2s  .c o m

    short nodeType = nodeElement.getNodeType();
    if (Node.CDATA_SECTION_NODE == nodeType) {
        returnValue = new CDATAElement(nodeElement, componentBean);
    } else if (Node.TEXT_NODE == nodeType) {
        returnValue = new TextElement(nodeElement, componentBean);
    } else if (Node.COMMENT_NODE == nodeType) {
        returnValue = new CommentElement(nodeElement, componentBean);
    } else if (Node.PROCESSING_INSTRUCTION_NODE == nodeType) {
        returnValue = new PIElement(nodeElement, componentBean);
    } else if (Node.ELEMENT_NODE == nodeType) {
        String className = (String) mapClasses.get(nodeElement.getNodeName());

        if (className == null) {
            className = DEFAULT_CLASS_ELEMENT_PROCESSOR;
        }

        if (!className.equals("")) {
            Class class1;
            try {
                log.debug("loading class: " + className);

                class1 = Class.forName(className);
                Object[] objects = new Object[2];
                objects[0] = nodeElement;
                objects[1] = componentBean;

                returnValue = (TemplateElement) class1.getConstructor(paramClasses).newInstance(objects);
            } catch (InstantiationException e) {
                throw new CompilationException("InstantiationException: " + e.getLocalizedMessage(), e);
            } catch (IllegalAccessException e) {
                throw new CompilationException("IllegalAccessException: " + e.getLocalizedMessage(), e);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
                throw new CompilationException("InvocationTargetException: " + e.getMessage(), e);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                throw new CompilationException(" error loading class: " + e.getLocalizedMessage());
            }
        }
    }
    return returnValue;
}

From source file:org.apache.ode.bpel.compiler.v2.xquery10.compiler.XQuery10ExpressionCompilerImpl.java

private void doJaxpCompile(OXQuery10ExpressionBPEL20 out, Expression source) throws CompilationException {
    String xqueryStr;//from   w w  w  .j  ava2 s .c o  m
    Node node = source.getExpression();
    if (node == null) {
        throw new IllegalStateException("XQuery string and xpath node are both null");
    }
    if (node.getNodeType() != Node.TEXT_NODE && node.getNodeType() != Node.ELEMENT_NODE
            && node.getNodeType() != Node.CDATA_SECTION_NODE) {
        throw new CompilationException(__msgs.errUnexpectedNodeTypeForXPath(DOMUtils.domToString(node)));
    }
    xqueryStr = DOMUtils.domToString(node);
    xqueryStr = xqueryStr.trim();
    if (xqueryStr.length() == 0) {
        throw new CompilationException(__msgs.warnXPath20Syntax(DOMUtils.domToString(node), "empty string"));
    }

    try {
        XQDataSource xqds = new SaxonXQDataSource();
        XQConnection xqconn = xqds.getConnection();

        __log.debug("Compiling expression " + xqueryStr);
        Configuration configuration = ((SaxonXQConnection) xqconn).getConfiguration();
        configuration.setAllNodesUntyped(true);
        configuration.setHostLanguage(Configuration.XQUERY);

        XQStaticContext staticContext = xqconn.getStaticContext();
        JaxpFunctionResolver funcResolver = new JaxpFunctionResolver(_compilerContext, out,
                source.getNamespaceContext(), _bpelNS);
        JaxpVariableResolver variableResolver = new JaxpVariableResolver(_compilerContext, out);

        XQueryDeclarations declarations = new XQueryDeclarations();
        NSContext nsContext = source.getNamespaceContext();
        Set<String> prefixes = nsContext.getPrefixes();
        if (!nsContext.getUriSet().contains(Namespaces.ODE_EXTENSION_NS)) {
            nsContext.register("ode", Namespaces.ODE_EXTENSION_NS);
        }
        for (String prefix : prefixes) {
            String uri = nsContext.getNamespaceURI(prefix);
            staticContext.declareNamespace(prefix, uri);
            if ("".equals(prefix)) {
                declarations.declareDefaultElementNamespace(uri);
            } else if ("bpws".equals(prefix)) {
                declarations.declareNamespace("bpws", "java:" + Constants.XQUERY_FUNCTION_HANDLER_COMPILER);
            } else {
                declarations.declareNamespace(prefix, uri);
            }
        }
        declarations.declareVariable(getQName(nsContext, Namespaces.ODE_EXTENSION_NS, "pid"),
                getQName(nsContext, Namespaces.XML_SCHEMA, "integer"));
        Map<URI, Source> schemaDocuments = _compilerContext.getSchemaSources();
        for (URI schemaUri : schemaDocuments.keySet()) {
            Source schemaSource = schemaDocuments.get(schemaUri);
            // Don't add schema sources, since our Saxon library is not schema-aware. 
            // configuration.addSchemaSource(schemaSource);
        }
        configuration.setSchemaValidationMode(Validation.SKIP);
        List<OScope.Variable> variables = _compilerContext.getAccessibleVariables();
        Map<QName, QName> variableTypes = new HashMap<QName, QName>();
        for (String variableName : getVariableNames(xqueryStr)) {
            OScope.Variable variable = getVariable(variables, variableName);
            if (variable == null) {
                continue;
            }
            OVarType type = variable.type;
            QName nameQName = getNameQName(variableName);
            QName typeQName = getTypeQName(variableName, type);
            variableTypes.put(nameQName, typeQName);
            String prefix = typeQName.getPrefix();
            if (prefix == null || "".equals(prefix.trim())) {
                prefix = getPrefixForUri(nsContext, typeQName.getNamespaceURI());
            }
            // don't declare typed variables, as our engine is not schema-aware
            // declarations.declareVariable(variable.name, typeQName);
            declarations.declareVariable(variableName);
        }

        // Add implicit declarations as prolog to the user-defined XQuery
        out.xquery = declarations.toString() + xqueryStr;

        // Check the XQuery for compilation errors 
        xqconn.setStaticContext(staticContext);
        XQPreparedExpression exp = xqconn.prepareExpression(out.xquery);

        // Pre-evaluate variables and functions by executing query  
        node.setUserData(XQuery10BpelFunctions.USER_DATA_KEY_FUNCTION_RESOLVER, funcResolver, null);
        exp.bindItem(XQConstants.CONTEXT_ITEM, xqconn.createItemFromNode(node, xqconn.createNodeType()));
        // Bind external variables to dummy runtime values
        for (QName variable : exp.getAllUnboundExternalVariables()) {
            QName typeQName = variableTypes.get(variable);
            Object value = variableResolver.resolveVariable(variable);
            if (typeQName != null) {
                if (value.getClass().getName().startsWith("java.lang")) {
                    exp.bindAtomicValue(variable, value.toString(),
                            xqconn.createAtomicType(XQItemType.XQBASETYPE_ANYATOMICTYPE));
                } else if (value instanceof Node) {
                    exp.bindNode(variable, (Node) value, xqconn.createNodeType());
                } else if (value instanceof NodeList) {
                    NodeList nodeList = (NodeList) value;
                    ArrayList nodeArray = new ArrayList();
                    for (int i = 0; i < nodeList.getLength(); i++) {
                        nodeArray.add(nodeList.item(i));
                    }
                    XQSequence sequence = xqconn.createSequence(nodeArray.iterator());
                    exp.bindSequence(variable, sequence);
                }
            }
        }
        // evaluate the expression so as to initialize the variables
        try {
            exp.executeQuery();
        } catch (XQException xpee) {
            // swallow errors caused by uninitialized variables 
        }
    } catch (XQException xqe) {
        __log.debug(xqe);
        __log.info("Couldn't validate properly expression " + xqueryStr);
    } catch (WrappedResolverException wre) {
        if (wre._compilationMsg != null)
            throw new CompilationException(wre._compilationMsg, wre);
        if (wre.getCause() instanceof CompilationException)
            throw (CompilationException) wre.getCause();
        throw wre;
    }
}

From source file:org.apache.ode.bpel.elang.xpath20.compiler.XPath20ExpressionCompilerImpl.java

private void doJaxpCompile(OXPath20ExpressionBPEL20 out, Expression source) throws CompilationException {
    String xpathStr;/*from w w w .j a  va2  s  . c o m*/
    Node node = source.getExpression();
    if (node == null) {
        throw new CompilationException(__msgs.errEmptyExpression(source.getURI(),
                new QName(source.getElement().getNamespaceURI(), source.getElement().getNodeName())));
    }
    if (node.getNodeType() != Node.TEXT_NODE && node.getNodeType() != Node.CDATA_SECTION_NODE) {
        throw new CompilationException(__msgs.errUnexpectedNodeTypeForXPath(DOMUtils.domToString(node)));
    }
    xpathStr = node.getNodeValue();
    xpathStr = xpathStr.trim();
    if (xpathStr.length() == 0) {
        throw new CompilationException(__msgs.warnXPath20Syntax(DOMUtils.domToString(node), "empty string"));
    }

    out.xpath = xpathStr;
    try {
        __log.debug("Compiling expression " + xpathStr);
        XPathFactory xpf = new XPathFactoryImpl();
        JaxpFunctionResolver funcResolver = new JaxpFunctionResolver(_compilerContext, out,
                source.getNamespaceContext(), _bpelNS);
        JaxpVariableResolver varResolver = new JaxpVariableResolver(_compilerContext, out);
        XPath xpe = xpf.newXPath();
        xpe.setXPathFunctionResolver(funcResolver);
        xpe.setXPathVariableResolver(varResolver);
        xpe.setNamespaceContext(source.getNamespaceContext());
        XPathExpression expr = xpe.compile(xpathStr);
        // evaluate the expression so as to initialize the variables
        try {
            expr.evaluate(node);
        } catch (XPathExpressionException xpee) {
            // swallow errors caused by uninitialized variable
        }
        for (String varExpr : extractVariableExprs(xpathStr)) {
            expr = xpe.compile(varExpr);
            try {
                expr.evaluate(node);
            } catch (XPathExpressionException xpee) {
                // swallow errors caused by uninitialized variable
            }
        }
        for (String functionExpr : extractFunctionExprs(xpathStr)) {
            expr = xpe.compile(functionExpr);
            try {
                expr.evaluate(node);
            } catch (XPathExpressionException xpee) {
                // swallow errors caused by uninitialized variable
            }
        }
    } catch (XPathExpressionException e) {
        __log.debug(e);
        __log.info("Couldn't validate properly expression " + xpathStr);
    } catch (WrappedResolverException wre) {
        if (wre._compilationMsg != null)
            throw new CompilationException(wre._compilationMsg, wre);
        if (wre.getCause() instanceof CompilationException)
            throw (CompilationException) wre.getCause();
        throw wre;
    }
}

From source file:org.apache.ode.bpel.elang.xquery10.compiler.XQuery10ExpressionCompilerImpl.java

private void doJaxpCompile(OXQuery10ExpressionBPEL20 out, Expression source) throws CompilationException {
    String xqueryStr;/*from w  ww  .j ava2s . c  o m*/
    Node node = source.getExpression();
    if (node == null) {
        throw new CompilationException(__msgs.errEmptyExpression(source.getURI(),
                new QName(source.getElement().getNamespaceURI(), source.getElement().getNodeName())));
    }
    if (node.getNodeType() != Node.TEXT_NODE && node.getNodeType() != Node.ELEMENT_NODE
            && node.getNodeType() != Node.CDATA_SECTION_NODE) {
        throw new CompilationException(__msgs.errUnexpectedNodeTypeForXPath(DOMUtils.domToString(node)));
    }
    xqueryStr = DOMUtils.domToString(node);
    xqueryStr = xqueryStr.trim();
    if (xqueryStr.length() == 0) {
        throw new CompilationException(__msgs.warnXPath20Syntax(DOMUtils.domToString(node), "empty string"));
    }

    try {
        XQDataSource xqds = new SaxonXQDataSource(new Configuration());
        XQConnection xqconn = xqds.getConnection();

        __log.debug("Compiling expression " + xqueryStr);
        Configuration configuration = ((SaxonXQConnection) xqconn).getConfiguration();
        configuration.setAllNodesUntyped(true);
        configuration.setHostLanguage(Configuration.XQUERY);

        XQStaticContext staticContext = xqconn.getStaticContext();
        JaxpFunctionResolver funcResolver = new JaxpFunctionResolver(_compilerContext, out,
                source.getNamespaceContext(), _bpelNS);
        JaxpVariableResolver variableResolver = new JaxpVariableResolver(_compilerContext, out);

        XQueryDeclarations declarations = new XQueryDeclarations();
        NSContext nsContext = source.getNamespaceContext();
        Set<String> prefixes = nsContext.getPrefixes();
        if (!nsContext.getUriSet().contains(Namespaces.ODE_EXTENSION_NS)) {
            nsContext.register("ode", Namespaces.ODE_EXTENSION_NS);
        }
        for (String prefix : prefixes) {
            String uri = nsContext.getNamespaceURI(prefix);
            staticContext.declareNamespace(prefix, uri);
            if ("".equals(prefix)) {
                declarations.declareDefaultElementNamespace(uri);
            } else if ("bpws".equals(prefix)) {
                declarations.declareNamespace("bpws", "java:" + Constants.XQUERY_FUNCTION_HANDLER_COMPILER);
            } else {
                declarations.declareNamespace(prefix, uri);
            }
        }
        declarations.declareVariable(getQName(nsContext, Namespaces.ODE_EXTENSION_NS, "pid"),
                getQName(nsContext, Namespaces.XML_SCHEMA, "integer"));
        //            Map<URI, Source> schemaDocuments = _compilerContext.getSchemaSources();
        //            for (URI schemaUri : schemaDocuments.keySet()) {
        //               Source schemaSource = schemaDocuments.get(schemaUri);
        //               // Don't add schema sources, since our Saxon library is not schema-aware.
        //               // configuration.addSchemaSource(schemaSource);
        //            }
        configuration.setSchemaValidationMode(Validation.SKIP);
        List<OScope.Variable> variables = _compilerContext.getAccessibleVariables();
        Map<QName, QName> variableTypes = new HashMap<QName, QName>();
        for (String variableName : getVariableNames(xqueryStr)) {
            OScope.Variable variable = getVariable(variables, variableName);
            if (variable == null) {
                continue;
            }
            OVarType type = variable.type;
            QName nameQName = getNameQName(variableName);
            QName typeQName = getTypeQName(variableName, type);
            variableTypes.put(nameQName, typeQName);
            String prefix = typeQName.getPrefix();
            if (prefix == null || "".equals(prefix.trim())) {
                prefix = getPrefixForUri(nsContext, typeQName.getNamespaceURI());
            }
            // don't declare typed variables, as our engine is not schema-aware
            // declarations.declareVariable(variable.name, typeQName);
            declarations.declareVariable(variableName);
        }

        // Add implicit declarations as prolog to the user-defined XQuery
        out.xquery = declarations.toString() + xqueryStr;

        // Check the XQuery for compilation errors
        xqconn.setStaticContext(staticContext);
        XQPreparedExpression exp = xqconn.prepareExpression(out.xquery);

        // Pre-evaluate variables and functions by executing query
        node.setUserData(XQuery10BpelFunctions.USER_DATA_KEY_FUNCTION_RESOLVER, funcResolver, null);
        exp.bindItem(XQConstants.CONTEXT_ITEM, xqconn.createItemFromNode(node, xqconn.createNodeType()));
        // Bind external variables to dummy runtime values
        for (QName variable : exp.getAllUnboundExternalVariables()) {
            QName typeQName = variableTypes.get(variable);
            Object value = variableResolver.resolveVariable(variable);
            if (typeQName != null) {
                if (value.getClass().getName().startsWith("java.lang")) {
                    exp.bindAtomicValue(variable, value.toString(),
                            xqconn.createAtomicType(XQItemType.XQBASETYPE_ANYATOMICTYPE));
                } else if (value instanceof Node) {
                    exp.bindNode(variable, (Node) value, xqconn.createNodeType());
                } else if (value instanceof NodeList) {
                    NodeList nodeList = (NodeList) value;
                    ArrayList nodeArray = new ArrayList();
                    for (int i = 0; i < nodeList.getLength(); i++) {
                        nodeArray.add(nodeList.item(i));
                    }
                    XQSequence sequence = xqconn.createSequence(nodeArray.iterator());
                    exp.bindSequence(variable, sequence);
                }
            }
        }
        // evaluate the expression so as to initialize the variables
        try {
            exp.executeQuery();
        } catch (XQException xpee) {
            // swallow errors caused by uninitialized variables
        } finally {
            // reset the expression's user data, in order to avoid
            // serializing the function resolver in the compiled bpel file.
            if (node != null) {
                node.setUserData(XQuery10BpelFunctions.USER_DATA_KEY_FUNCTION_RESOLVER, null, null);
            }
        }
    } catch (XQException xqe) {
        __log.debug(xqe);
        __log.info("Couldn't validate properly expression " + xqueryStr);
        throw new CompilationException(
                __msgs.errXQuery10Syntax(xqueryStr, "Couldn't validate XQuery expression"));
    } catch (WrappedResolverException wre) {
        if (wre._compilationMsg != null)
            throw new CompilationException(wre._compilationMsg, wre);
        if (wre.getCause() instanceof CompilationException)
            throw (CompilationException) wre.getCause();
        throw wre;
    }
}