Example usage for org.w3c.dom Node COMMENT_NODE

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

Introduction

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

Prototype

short COMMENT_NODE

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

Click Source Link

Document

The node is a Comment.

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./*  w w w .  j a v a 2  s . c  om*/
 *
 * @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.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.// www.  ja  v  a2  s  .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//w w w .jav a  2  s. co  m
 *
 * @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.ajax4jsf.templatecompiler.elements.A4JRendererElementsFactory.java

public TemplateElement getProcessor(final Node nodeElement, final CompilationContext componentBean)
        throws CompilationException {
    TemplateElement returnValue = null;/*from w  w  w .  j a  v  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.nutch.parse.html.DOMContentUtils.java

private boolean getTextHelper(StringBuffer sb, Node node, boolean abortOnNestedAnchors, int anchorDepth) {
    boolean abort = false;
    NodeWalker walker = new NodeWalker(node);

    while (walker.hasNext()) {

        Node currentNode = walker.nextNode();
        String nodeName = currentNode.getNodeName();
        short nodeType = currentNode.getNodeType();

        if ("script".equalsIgnoreCase(nodeName)) {
            walker.skipChildren();// w w w . j a  v a 2s.c om
        }
        if ("style".equalsIgnoreCase(nodeName)) {
            walker.skipChildren();
        }
        if (abortOnNestedAnchors && "a".equalsIgnoreCase(nodeName)) {
            anchorDepth++;
            if (anchorDepth > 1) {
                abort = true;
                break;
            }
        }
        if (nodeType == Node.COMMENT_NODE) {
            walker.skipChildren();
        }
        if (nodeType == Node.TEXT_NODE) {
            // cleanup and trim the value
            String text = currentNode.getNodeValue();
            String element = currentNode.getParentNode().getNodeName();
            text = text.replaceAll("\\s+", " ");
            text = text.trim();
            if (text.length() > 0) {
                if (sb.length() > 0)
                    sb.append(' ');
                if (StringUtils.isNotBlank(element))
                    //custom code to retain the html tag surrounding this text element 
                    sb.append("<" + element + ">").append(text).append("</" + element + ">");
                else
                    sb.append(text);
            }
        }
    }

    return abort;
}

From source file:org.apache.ode.utils.DOMUtils.java

/**
 * Deep clone, but don't fry, the given node in the context of the given document.
 * For all intents and purposes, the clone is the exact same copy of the node,
 * except that it might have a different owner document.
 *
 * This method is fool-proof, unlike the <code>adoptNode</code> or <code>adoptNode</code> methods,
 * in that it doesn't assume that the given node has a parent or a owner document.
 *
 * @param document/*from  w  ww .  j av a  2 s . c o  m*/
 * @param sourceNode
 * @return a clone of node
 */
public static Node cloneNode(Document document, Node sourceNode) {
    Node clonedNode = null;

    // what is my name?
    QName sourceQName = getNodeQName(sourceNode);
    String nodeName = sourceQName.getLocalPart();
    String namespaceURI = sourceQName.getNamespaceURI();

    // if the node is unqualified, don't assume that it inherits the WS-BPEL target namespace
    if (Namespaces.WSBPEL2_0_FINAL_EXEC.equals(namespaceURI)) {
        namespaceURI = null;
    }

    switch (sourceNode.getNodeType()) {
    case Node.ATTRIBUTE_NODE:
        if (namespaceURI == null) {
            clonedNode = document.createAttribute(nodeName);
        } else {
            String prefix = ((Attr) sourceNode).lookupPrefix(namespaceURI);
            // the prefix for the XML namespace can't be looked up, hence this...
            if (prefix == null && namespaceURI.equals(NS_URI_XMLNS)) {
                prefix = "xmlns";
            }
            // if a prefix exists, qualify the name with it
            if (prefix != null && !"".equals(prefix)) {
                nodeName = prefix + ":" + nodeName;
            }
            // create the appropriate type of attribute
            if (prefix != null) {
                clonedNode = document.createAttributeNS(namespaceURI, nodeName);
            } else {
                clonedNode = document.createAttribute(nodeName);
            }
        }
        break;
    case Node.CDATA_SECTION_NODE:
        clonedNode = document.createCDATASection(((CDATASection) sourceNode).getData());
        break;
    case Node.COMMENT_NODE:
        clonedNode = document.createComment(((Comment) sourceNode).getData());
        break;
    case Node.DOCUMENT_FRAGMENT_NODE:
        clonedNode = document.createDocumentFragment();
        break;
    case Node.DOCUMENT_NODE:
        clonedNode = document;
        break;
    case Node.ELEMENT_NODE:
        // create the appropriate type of element
        if (namespaceURI == null) {
            clonedNode = document.createElement(nodeName);
        } else {
            String prefix = namespaceURI.equals(Namespaces.XMLNS_URI) ? "xmlns"
                    : ((Element) sourceNode).lookupPrefix(namespaceURI);
            if (prefix != null && !"".equals(prefix)) {
                nodeName = prefix + ":" + nodeName;
                clonedNode = document.createElementNS(namespaceURI, nodeName);
            } else {
                clonedNode = document.createElement(nodeName);
            }
        }
        // attributes are not treated as child nodes, so copy them explicitly
        NamedNodeMap attributes = ((Element) sourceNode).getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Attr attributeClone = (Attr) cloneNode(document, attributes.item(i));
            if (attributeClone.getNamespaceURI() == null) {
                ((Element) clonedNode).setAttributeNode(attributeClone);
            } else {
                ((Element) clonedNode).setAttributeNodeNS(attributeClone);
            }
        }
        break;
    case Node.ENTITY_NODE:
        // TODO
        break;
    case Node.ENTITY_REFERENCE_NODE:
        clonedNode = document.createEntityReference(nodeName);
        // TODO
        break;
    case Node.NOTATION_NODE:
        // TODO
        break;
    case Node.PROCESSING_INSTRUCTION_NODE:
        clonedNode = document.createProcessingInstruction(((ProcessingInstruction) sourceNode).getData(),
                nodeName);
        break;
    case Node.TEXT_NODE:
        clonedNode = document.createTextNode(((Text) sourceNode).getData());
        break;
    default:
        break;
    }

    // clone children of element and attribute nodes
    NodeList sourceChildren = sourceNode.getChildNodes();
    if (sourceChildren != null) {
        for (int i = 0; i < sourceChildren.getLength(); i++) {
            Node sourceChild = sourceChildren.item(i);
            Node clonedChild = cloneNode(document, sourceChild);
            clonedNode.appendChild(clonedChild);
            // if the child has a textual value, parse it for any embedded prefixes
            if (clonedChild.getNodeType() == Node.TEXT_NODE
                    || clonedChild.getNodeType() == Node.CDATA_SECTION_NODE) {
                parseEmbeddedPrefixes(sourceNode, clonedNode, clonedChild);
            }
        }
    }
    return clonedNode;
}

From source file:org.apache.shindig.gadgets.parse.AbstractSocialMarkupHtmlParserTest.java

@Test
public void testCommentOrdering() {
    NodeList divElements = document.getElementsByTagName("div");
    assertEquals(1, divElements.getLength());
    NodeList children = divElements.item(0).getChildNodes();
    assertEquals(3, children.getLength());

    // Should be comment/text/comment, not comment/comment/text
    assertEquals(Node.COMMENT_NODE, children.item(0).getNodeType());
    assertEquals(Node.TEXT_NODE, children.item(1).getNodeType());
    assertEquals(Node.COMMENT_NODE, children.item(2).getNodeType());
}

From source file:org.apache.shindig.gadgets.rewrite.ConcatVisitor.java

private Element getSibling(Element root, boolean isPrev) {
    Node cur = root;/*from  w w  w  .j a  v  a 2s  .  c  o m*/
    while ((cur = getNext(cur, isPrev)) != null) {
        // Text nodes are safe to skip, as they won't effect styles or scripts.
        // It is also safe to skip comment nodes except for conditional comments.
        if (cur.getNodeType() == Node.TEXT_NODE
                || (cur.getNodeType() == Node.COMMENT_NODE && !isConditionalComment(cur))) {
            continue;
        }
        break;
    }
    if (cur != null && cur.getNodeType() == Node.ELEMENT_NODE) {
        return (Element) cur;
    }
    return null;
}

From source file:org.automagic.deps.doctor.editor.PomWriterImpl.java

private void clearDummyComment(Node node) {
    NodeList childNodes = node.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node item = childNodes.item(i);
        if (Node.COMMENT_NODE == item.getNodeType()) {
            node.removeChild(item);/*w  w  w .  j a  va2 s .  co m*/
            break;
        }
        if (Node.TEXT_NODE == item.getNodeType()) {
            item.setNodeValue(EMPTY);
        }
    }
}

From source file:org.automagic.deps.doctor.Utils.java

public static Optional<Node> getPluginComment(String parent, Artifact artifact, Document document) {

    Optional<Node> dependencyNode = getDependencyNode(artifact, document, parent);

    if (!dependencyNode.isPresent()) {
        return Optional.absent();
    }//from w ww .  j  a v  a2  s .c  o m

    if (dependencyNode.get().hasChildNodes()) {
        NodeList childNodes = dependencyNode.get().getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            Node node = childNodes.item(i);
            if (Node.COMMENT_NODE == node.getNodeType()
                    && contains(node.getNodeValue(), PomWriter.AUTO_COMMENT)) {
                return Optional.of(node);
            }
        }
    }

    return Optional.absent();
}