Example usage for org.w3c.dom Node PROCESSING_INSTRUCTION_NODE

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

Introduction

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

Prototype

short PROCESSING_INSTRUCTION_NODE

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

Click Source Link

Document

The node is a ProcessingInstruction.

Usage

From source file:DOMWriter.java

private void printInternal(Node node, boolean indentEndMarker) {
    // is there anything to do?
    if (node == null) {
        return;// w w w .ja  va  2 s. c  om
    }

    // JBAS-2117 - Don't skip the DOCUMENT_NODE
    // if (node instanceof Document) node = ((Document)node).getDocumentElement();

    if (wroteXMLDeclaration == false && writeXMLDeclaration == true && canonical == false) {
        out.print("<?xml version='1.0'");
        if (charsetName != null)
            out.print(" encoding='" + charsetName + "'");

        out.print("?>");
        if (prettyprint)
            out.println();

        wroteXMLDeclaration = true;
    }

    int type = node.getNodeType();
    boolean hasChildNodes = node.getChildNodes().getLength() > 0;

    String nodeName = node.getNodeName();
    switch (type) {
    // print document
    case Node.DOCUMENT_NODE: {
        NodeList children = node.getChildNodes();
        for (int iChild = 0; iChild < children.getLength(); iChild++) {
            printInternal(children.item(iChild), false);
        }
        out.flush();
        break;
    }

    // print element with attributes
    case Node.ELEMENT_NODE: {
        Element element = (Element) node;
        if (prettyprint) {
            for (int i = 0; i < prettyIndent; i++) {
                out.print(' ');
            }
            prettyIndent++;
        }

        out.print('<');
        out.print(nodeName);

        Map nsMap = new HashMap();
        String elPrefix = node.getPrefix();
        String elNamespaceURI = node.getNamespaceURI();
        if (elPrefix != null) {
            String nsURI = getNamespaceURI(elPrefix, element, rootNode);
            nsMap.put(elPrefix, nsURI);
        }

        Attr attrs[] = sortAttributes(node.getAttributes());
        for (int i = 0; i < attrs.length; i++) {
            Attr attr = attrs[i];
            String atPrefix = attr.getPrefix();
            String atName = attr.getNodeName();
            String atValue = normalize(attr.getNodeValue(), canonical);

            if (atName.equals("xmlns"))
                currentDefaultNamespace = atValue;

            if (atPrefix != null && !atPrefix.equals("xmlns") && !atPrefix.equals("xml")) {
                String nsURI = getNamespaceURI(atPrefix, element, rootNode);
                nsMap.put(atPrefix, nsURI);
                // xsi:type='ns1:SubType', xsi:type='xsd:string'
                if (atName.equals(atPrefix + ":type") && atValue.indexOf(":") > 0) {
                    // xsi defined on the envelope
                    if (nsURI == null)
                        nsURI = getNamespaceURI(atPrefix, element, null);

                    if ("http://www.w3.org/2001/XMLSchema-instance".equals(nsURI)) {
                        String typePrefix = atValue.substring(0, atValue.indexOf(":"));
                        String typeURI = getNamespaceURI(typePrefix, element, rootNode);
                        nsMap.put(typePrefix, typeURI);
                    }
                }
            }

            out.print(" " + atName + "='" + atValue + "'");
        }

        // Add namespace declaration for prefixes
        // that are defined further up the tree
        if (completeNamespaces) {
            Iterator itPrefix = nsMap.keySet().iterator();
            while (itPrefix.hasNext()) {
                String prefix = (String) itPrefix.next();
                String nsURI = (String) nsMap.get(prefix);
                if (nsURI == null) {
                    nsURI = getNamespaceURI(prefix, element, null);
                    out.print(" xmlns:" + prefix + "='" + nsURI + "'");
                }
            }
        }

        // The SAX ContentHandler will by default not add the namespace declaration
        // <Hello xmlns='http://somens'>World</Hello>
        if (elPrefix == null && elNamespaceURI != null) {
            String defaultNamespace = element.getAttribute("xmlns");
            if (defaultNamespace.length() == 0 && !elNamespaceURI.equals(currentDefaultNamespace)) {
                out.print(" xmlns='" + elNamespaceURI + "'");
                currentDefaultNamespace = elNamespaceURI;
            }
        }

        if (hasChildNodes) {
            out.print('>');
        }

        // Find out if the end marker is indented
        indentEndMarker = isEndMarkerIndented(node);

        if (indentEndMarker) {
            out.print('\n');
        }

        NodeList childNodes = node.getChildNodes();
        int len = childNodes.getLength();
        for (int i = 0; i < len; i++) {
            Node childNode = childNodes.item(i);
            printInternal(childNode, false);
        }
        break;
    }

    // handle entity reference nodes
    case Node.ENTITY_REFERENCE_NODE: {
        if (canonical) {
            NodeList children = node.getChildNodes();
            if (children != null) {
                int len = children.getLength();
                for (int i = 0; i < len; i++) {
                    printInternal(children.item(i), false);
                }
            }
        } else {
            out.print('&');
            out.print(nodeName);
            out.print(';');
        }
        break;
    }

    // print cdata sections
    case Node.CDATA_SECTION_NODE: {
        if (canonical) {
            out.print(normalize(node.getNodeValue(), canonical));
        } else {
            out.print("<![CDATA[");
            out.print(node.getNodeValue());
            out.print("]]&gt;");
        }
        break;
    }

    // print text
    case Node.TEXT_NODE: {
        String text = normalize(node.getNodeValue(), canonical);
        if (text.trim().length() > 0) {
            out.print(text);
        } else if (prettyprint == false && ignoreWhitespace == false) {
            out.print(text);
        }
        break;
    }

    // print processing instruction
    case Node.PROCESSING_INSTRUCTION_NODE: {
        out.print("<?");
        out.print(nodeName);
        String data = node.getNodeValue();
        if (data != null && data.length() > 0) {
            out.print(' ');
            out.print(data);
        }
        out.print("?>");
        break;
    }

    // print comment
    case Node.COMMENT_NODE: {
        for (int i = 0; i < prettyIndent; i++) {
            out.print(' ');
        }

        out.print("<!--");
        String data = node.getNodeValue();
        if (data != null) {
            out.print(data);
        }
        out.print("-->");

        if (prettyprint) {
            out.print('\n');
        }

        break;
    }
    }

    if (type == Node.ELEMENT_NODE) {
        if (prettyprint)
            prettyIndent--;

        if (hasChildNodes == false) {
            out.print("/>");
        } else {
            if (indentEndMarker) {
                for (int i = 0; i < prettyIndent; i++) {
                    out.print(' ');
                }
            }

            out.print("</");
            out.print(nodeName);
            out.print('>');
        }

        if (prettyIndent > 0) {
            out.print('\n');
        }
    }
    out.flush();
}

From source file:DOMWriter.java

private void printInternal(Node node, boolean indentEndMarker) {
    // is there anything to do?
    if (node == null) {
        return;/*from  ww w  .  j  a  v  a  2  s.  co m*/
    }

    // JBAS-2117 - Don't skip the DOCUMENT_NODE
    // if (node instanceof Document) node =
    // ((Document)node).getDocumentElement();

    if (wroteXMLDeclaration == false && writeXMLDeclaration == true && canonical == false) {
        out.print("<?xml version='1.0'");
        if (charsetName != null)
            out.print(" encoding='" + charsetName + "'");

        out.print("?>");
        if (prettyprint)
            out.println();

        wroteXMLDeclaration = true;
    }

    int type = node.getNodeType();
    boolean hasChildNodes = node.getChildNodes().getLength() > 0;

    String nodeName = node.getNodeName();
    switch (type) {
    // print document
    case Node.DOCUMENT_NODE: {
        NodeList children = node.getChildNodes();
        for (int iChild = 0; iChild < children.getLength(); iChild++) {
            printInternal(children.item(iChild), false);
        }
        out.flush();
        break;
    }

    // print element with attributes
    case Node.ELEMENT_NODE: {
        Element element = (Element) node;
        if (prettyprint) {
            for (int i = 0; i < prettyIndent; i++) {
                out.print(' ');
            }
            prettyIndent++;
        }

        out.print('<');
        out.print(nodeName);

        Map nsMap = new HashMap();
        String elPrefix = node.getPrefix();
        String elNamespaceURI = node.getNamespaceURI();
        if (elPrefix != null) {
            String nsURI = getNamespaceURI(elPrefix, element, rootNode);
            nsMap.put(elPrefix, nsURI);
        }

        Attr attrs[] = sortAttributes(node.getAttributes());
        for (int i = 0; i < attrs.length; i++) {
            Attr attr = attrs[i];
            String atPrefix = attr.getPrefix();
            String atName = attr.getNodeName();
            String atValue = normalize(attr.getNodeValue(), canonical);

            if (atName.equals("xmlns"))
                currentDefaultNamespace = atValue;

            if (atPrefix != null && !atPrefix.equals("xmlns") && !atPrefix.equals("xml")) {
                String nsURI = getNamespaceURI(atPrefix, element, rootNode);
                nsMap.put(atPrefix, nsURI);
                // xsi:type='ns1:SubType', xsi:type='xsd:string'
                if (atName.equals(atPrefix + ":type") && atValue.indexOf(":") > 0) {
                    // xsi defined on the envelope
                    if (nsURI == null)
                        nsURI = getNamespaceURI(atPrefix, element, null);

                    if ("http://www.w3.org/2001/XMLSchema-instance".equals(nsURI)) {
                        String typePrefix = atValue.substring(0, atValue.indexOf(":"));
                        String typeURI = getNamespaceURI(typePrefix, element, rootNode);
                        nsMap.put(typePrefix, typeURI);
                    }
                }
            }

            out.print(" " + atName + "='" + atValue + "'");
        }

        // Add namespace declaration for prefixes
        // that are defined further up the tree
        if (completeNamespaces) {
            Iterator itPrefix = nsMap.keySet().iterator();
            while (itPrefix.hasNext()) {
                String prefix = (String) itPrefix.next();
                String nsURI = (String) nsMap.get(prefix);
                if (nsURI == null) {
                    nsURI = getNamespaceURI(prefix, element, null);
                    out.print(" xmlns:" + prefix + "='" + nsURI + "'");
                }
            }
        }

        // The SAX ContentHandler will by default not add the namespace
        // declaration
        // <Hello xmlns='http://somens'>World</Hello>
        if (elPrefix == null && elNamespaceURI != null) {
            String defaultNamespace = element.getAttribute("xmlns");
            if (defaultNamespace.length() == 0 && !elNamespaceURI.equals(currentDefaultNamespace)) {
                out.print(" xmlns='" + elNamespaceURI + "'");
                currentDefaultNamespace = elNamespaceURI;
            }
        }

        if (hasChildNodes) {
            out.print('>');
        }

        // Find out if the end marker is indented
        indentEndMarker = isEndMarkerIndented(node);

        if (indentEndMarker) {
            out.print('\n');
        }

        NodeList childNodes = node.getChildNodes();
        int len = childNodes.getLength();
        for (int i = 0; i < len; i++) {
            Node childNode = childNodes.item(i);
            printInternal(childNode, false);
        }
        break;
    }

    // handle entity reference nodes
    case Node.ENTITY_REFERENCE_NODE: {
        if (canonical) {
            NodeList children = node.getChildNodes();
            if (children != null) {
                int len = children.getLength();
                for (int i = 0; i < len; i++) {
                    printInternal(children.item(i), false);
                }
            }
        } else {
            out.print('&');
            out.print(nodeName);
            out.print(';');
        }
        break;
    }

    // print cdata sections
    case Node.CDATA_SECTION_NODE: {
        if (canonical) {
            out.print(normalize(node.getNodeValue(), canonical));
        } else {
            out.print("<![CDATA[");
            out.print(node.getNodeValue());
            out.print("]]&gt;");
        }
        break;
    }

    // print text
    case Node.TEXT_NODE: {
        String text = normalize(node.getNodeValue(), canonical);
        if (text.trim().length() > 0) {
            out.print(text);
        } else if (prettyprint == false && ignoreWhitespace == false) {
            out.print(text);
        }
        break;
    }

    // print processing instruction
    case Node.PROCESSING_INSTRUCTION_NODE: {
        out.print("<?");
        out.print(nodeName);
        String data = node.getNodeValue();
        if (data != null && data.length() > 0) {
            out.print(' ');
            out.print(data);
        }
        out.print("?>");
        break;
    }

    // print comment
    case Node.COMMENT_NODE: {
        for (int i = 0; i < prettyIndent; i++) {
            out.print(' ');
        }

        out.print("<!--");
        String data = node.getNodeValue();
        if (data != null) {
            out.print(data);
        }
        out.print("-->");

        if (prettyprint) {
            out.print('\n');
        }

        break;
    }
    }

    if (type == Node.ELEMENT_NODE) {
        if (prettyprint)
            prettyIndent--;

        if (hasChildNodes == false) {
            out.print("/>");
        } else {
            if (indentEndMarker) {
                for (int i = 0; i < prettyIndent; i++) {
                    out.print(' ');
                }
            }

            out.print("</");
            out.print(nodeName);
            out.print('>');
        }

        if (prettyIndent > 0) {
            out.print('\n');
        }
    }
    out.flush();
}

From source file:bridge.toolkit.commands.S1000DConverter.java

/**
 * Iterate through the DOM tree/* www . j a  v  a 2  s . com*/
 * 
 * @param node
 * @param output
 * @throws IOException
 */
public static void writeNode(Node node, Writer output) throws IOException {

    int type = node.getNodeType();

    switch (type) {
    case Node.ATTRIBUTE_NODE:
        output.write(' ');
        output.write(node.getNodeName());
        output.write("=\"");
        writeXMLData(node.getNodeValue(), true, output);
        output.write('"');
        break;
    case Node.CDATA_SECTION_NODE:
    case Node.TEXT_NODE:
        writeXMLData(node.getNodeValue(), false, output);
        break;
    case Node.COMMENT_NODE:
        output.write("<!--");
        output.write(((Comment) node).getNodeValue());
        output.write("-->");
        break;
    case Node.DOCUMENT_FRAGMENT_NODE:
        writeNodes(node.getChildNodes(), output);
        break;
    case Node.DOCUMENT_NODE:
        writeNodes(node.getChildNodes(), output);
        break;
    case Node.DOCUMENT_TYPE_NODE:
        break;
    case Node.ELEMENT_NODE: {
        NamedNodeMap atts = node.getAttributes();

        output.write('<');
        output.write(node.getNodeName());
        if (atts != null) {
            int length = atts.getLength();
            for (int i = 0; i < length; i++)
                writeNode(atts.item(i), output);
        }

        if (node.hasChildNodes()) {
            output.write('>');
            writeNodes(node.getChildNodes(), output);
            output.write("</");
            output.write(node.getNodeName());
            output.write('>');
        } else {
            output.write("/>");
        }
        break;
    }
    case Node.ENTITY_NODE:
        break;
    case Node.ENTITY_REFERENCE_NODE:
        writeNodes(node.getChildNodes(), output);
        break;
    case Node.NOTATION_NODE:
        break;
    case Node.PROCESSING_INSTRUCTION_NODE:
        break;
    default:
        throw new Error("Unexpected DOM node type: " + type);
    }
}

From source file:DOMProcessor.java

/** Converts the given DOM node into XML. Recursively converts
  * any child nodes. This version allows the XML version, encoding and stand-alone
  * status to be set./*w  w w.jav  a 2 s.c o  m*/
  * @param node DOM Node to display.
  * @param version XML version, or null if default ('1.0') is to be used.
  * @param encoding XML encoding, or null if encoding is not to be specified.
  * @param standalone XML stand-alone status or null if not to be specified.
  */
private void outputNodeAsXML(Node node, String version, String encoding, Boolean standalone) {
    // Store node name, type and value.
    String name = node.getNodeName(), value = makeFriendly(node.getNodeValue());
    int type = node.getNodeType();

    // Ignore empty nodes (e.g. blank lines etc.)
    if ((value != null) && (value.trim().equals(""))) {
        return;
    }

    switch (type) {
    case Node.DOCUMENT_NODE: // Start of document.
    {
        if (version == null) {
            out.print("<?xml version=\"1.0\" ");
        } else {
            out.print("<?xml version=\"" + version + "\" ");
        }

        if (encoding != null) {
            out.print("encoding=\"" + encoding + "\" ");
        }

        if (standalone != null) {
            if (standalone.booleanValue()) {
                out.print("standalone=\"yes\" ");
            } else {
                out.print("standalone=\"no\" ");
            }
        }

        out.println("?>");

        // Output the document's child nodes.
        NodeList children = node.getChildNodes();

        for (int i = 0; i < children.getLength(); i++) {
            outputNodeAsXML(children.item(i));
        }
        break;
    }

    case Node.ELEMENT_NODE: // Document element with attributes.
    {
        // Output opening element tag.
        indent++;
        indent();
        out.print("<" + name);

        // Output any attributes the element might have.
        NamedNodeMap attributes = node.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node attribute = attributes.item(i);
            out.print(" " + attribute.getNodeName() + "=\"" + attribute.getNodeValue() + "\"");
        }
        out.print(">");

        // Output any child nodes that exist.                    
        NodeList children = node.getChildNodes();

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

        break;
    }

    case Node.CDATA_SECTION_NODE: // Display text.
    case Node.TEXT_NODE: {
        out.print(value);
        break;
    }

    case Node.COMMENT_NODE: // Comment node.
    {
        indent++;
        indent();
        out.print("<!--" + value + "-->");
        indent--;
        break;
    }

    case Node.ENTITY_REFERENCE_NODE: // Entity reference nodes.
    {
        indent++;
        indent();
        out.print("&" + name + ";");
        indent--;
        break;
    }

    case Node.PROCESSING_INSTRUCTION_NODE: // Processing instruction.
    {
        indent++;
        indent();
        out.print("<?" + name);
        if ((value != null) && (value.length() > 0)) {
            out.print(" " + value);
        }
        out.println("?>");
        indent--;
        break;
    }
    }

    // Finally output closing tags for each element.
    if (type == Node.ELEMENT_NODE) {
        out.print("</" + node.getNodeName() + ">");
        indent--;
        if (node.getNextSibling() == null) {
            indent(); // Only throw new line if this is the last sibling.
        }
    }
}

From source file:com.evolveum.midpoint.util.DOMUtil.java

public static boolean isJunk(Node node) {
    if (node.getNodeType() == Node.COMMENT_NODE) {
        return true;
    }//from  www .j  av a2 s.com
    if (node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
        return true;
    }
    if (node.getNodeType() == Node.TEXT_NODE) {
        Text text = (Text) node;
        if (text.getTextContent().matches("^\\s*$")) {
            return true;
        }
        return false;
    }
    return false;
}

From source file:net.sourceforge.pmd.lang.xml.ast.DOMLineNumbers.java

private int determineLocation(Node n, int index) {
    int nextIndex = index;
    if (n.getNodeType() == Node.DOCUMENT_TYPE_NODE) {
        nextIndex = xmlString.indexOf("<!DOCTYPE", nextIndex);
    } else if (n.getNodeType() == Node.COMMENT_NODE) {
        nextIndex = xmlString.indexOf("<!--", nextIndex);
    } else if (n.getNodeType() == Node.ELEMENT_NODE) {
        nextIndex = xmlString.indexOf("<" + n.getNodeName(), nextIndex);
    } else if (n.getNodeType() == Node.CDATA_SECTION_NODE) {
        nextIndex = xmlString.indexOf("<![CDATA[", nextIndex);
    } else if (n.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
        ProcessingInstruction pi = (ProcessingInstruction) n;
        nextIndex = xmlString.indexOf("<?" + pi.getTarget(), nextIndex);
    } else if (n.getNodeType() == Node.TEXT_NODE) {
        String te = unexpandEntities(n, n.getNodeValue());
        int newIndex = xmlString.indexOf(te, nextIndex);
        if (newIndex > 0) {
            nextIndex = newIndex;//from w  w  w .  j av a  2  s  . c  o  m
        }
    } else if (n.getNodeType() == Node.ENTITY_REFERENCE_NODE) {
        nextIndex = xmlString.indexOf("&" + n.getNodeName() + ";", nextIndex);
    }
    setBeginLocation(n, nextIndex);
    if (n.hasChildNodes()) {
        NodeList childs = n.getChildNodes();
        for (int i = 0; i < childs.getLength(); i++) {
            nextIndex = determineLocation(childs.item(i), nextIndex);
        }
    }
    if (n.getNodeType() == Node.ELEMENT_NODE) {
        nextIndex += 2 + n.getNodeName().length() + 1; // </nodename>
    } else if (n.getNodeType() == Node.DOCUMENT_TYPE_NODE) {
        Node nextSibling = n.getNextSibling();
        if (nextSibling.getNodeType() == Node.ELEMENT_NODE) {
            nextIndex = xmlString.indexOf("<" + nextSibling.getNodeName(), nextIndex) - 1;
        } else if (nextSibling.getNodeType() == Node.COMMENT_NODE) {
            nextIndex = xmlString.indexOf("<!--", nextIndex);
        } else {
            nextIndex = xmlString.indexOf(">", nextIndex);
        }
    } else if (n.getNodeType() == Node.COMMENT_NODE) {
        nextIndex += 4 + 3; // <!-- and -->
        nextIndex += n.getNodeValue().length();
    } else if (n.getNodeType() == Node.TEXT_NODE) {
        String te = unexpandEntities(n, n.getNodeValue());
        nextIndex += te.length();
    } else if (n.getNodeType() == Node.CDATA_SECTION_NODE) {
        nextIndex += "<![CDATA[".length() + n.getNodeValue().length() + "]]>".length();
    } else if (n.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
        ProcessingInstruction pi = (ProcessingInstruction) n;
        nextIndex += "<?".length() + pi.getTarget().length() + "?>".length() + pi.getData().length();
    }
    setEndLocation(n, nextIndex - 1);
    return nextIndex;
}

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 ww  .  j av  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.//from  ww  w .  jav a2s . c o 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 .  j av 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;
}