Example usage for org.w3c.dom NamedNodeMap getNamedItem

List of usage examples for org.w3c.dom NamedNodeMap getNamedItem

Introduction

In this page you can find the example usage for org.w3c.dom NamedNodeMap getNamedItem.

Prototype

public Node getNamedItem(String name);

Source Link

Document

Retrieves a node specified by name.

Usage

From source file:org.apache.jackrabbit.core.query.lucene.IndexingConfigurationImpl.java

/**
 * Creates property configurations defined in the <code>config</code>.
 *
 * @param config the fulltext indexing configuration.
 * @param propConfigs will be filled with exact <code>Name</code> to
 *                    <code>PropertyConfig</code> mappings.
 * @param namePatterns will be filled with <code>NamePattern</code>s.
 * @throws IllegalNameException   if the node type name contains illegal
 *                                characters.
 * @throws NamespaceException if the node type contains an unknown
 *                                prefix.
 *///from w ww . j  a va  2  s .  co  m
private void createPropertyConfigs(Node config, Map propConfigs, List namePatterns)
        throws IllegalNameException, NamespaceException {
    NodeList childNodes = config.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node n = childNodes.item(i);
        if (n.getNodeName().equals("property")) {
            NamedNodeMap attributes = n.getAttributes();
            // get boost value
            float boost = 1.0f;
            Node boostAttr = attributes.getNamedItem("boost");
            if (boostAttr != null) {
                try {
                    boost = Float.parseFloat(boostAttr.getNodeValue());
                } catch (NumberFormatException e) {
                    // use default
                }
            }

            // get nodeScopeIndex flag
            boolean nodeScopeIndex = true;
            Node nsIndex = attributes.getNamedItem("nodeScopeIndex");
            if (nsIndex != null) {
                nodeScopeIndex = Boolean.valueOf(nsIndex.getNodeValue()).booleanValue();
            }

            // get isRegexp flag
            boolean isRegexp = false;
            Node regexp = attributes.getNamedItem("isRegexp");
            if (regexp != null) {
                isRegexp = Boolean.valueOf(regexp.getNodeValue()).booleanValue();
            }

            // get useInExcerpt flag
            boolean useInExcerpt = true;
            Node excerpt = attributes.getNamedItem("useInExcerpt");
            if (excerpt != null) {
                useInExcerpt = Boolean.valueOf(excerpt.getNodeValue()).booleanValue();
            }

            PropertyConfig pc = new PropertyConfig(boost, nodeScopeIndex, useInExcerpt);

            if (isRegexp) {
                namePatterns.add(new NamePattern(getTextContent(n), pc, resolver));
            } else {
                Name propName = resolver.getQName(getTextContent(n));
                propConfigs.put(propName, pc);
            }
        }
    }
}

From source file:org.apache.jackrabbit.core.query.lucene.IndexingConfigurationImpl.java

/**
 * Creates property configurations defined in the <code>config</code>.
 *
 * @param config the fulltext indexing configuration.
 * @param propConfigs will be filled with exact <code>Name</code> to
 *                    <code>PropertyConfig</code> mappings.
 * @param namePatterns will be filled with <code>NamePattern</code>s.
 * @throws IllegalNameException   if the node type name contains illegal
 *                                characters.
 * @throws NamespaceException if the node type contains an unknown
 *                                prefix.
 *//*from w  ww.ja  va 2 s  . co  m*/
private void createPropertyConfigs(Node config, Map propConfigs, List namePatterns)
        throws IllegalNameException, NamespaceException {
    NodeList childNodes = config.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node n = childNodes.item(i);
        if (n.getNodeName().equals("property")) {
            NamedNodeMap attributes = n.getAttributes();
            // get boost value
            float boost = 1.0f;
            Node boostAttr = attributes.getNamedItem("boost");
            if (boostAttr != null) {
                try {
                    boost = Float.parseFloat(boostAttr.getNodeValue());
                } catch (NumberFormatException e) {
                    // use default
                }
            }

            // get nodeScopeIndex flag
            boolean nodeScopeIndex = true;
            Node nsIndex = attributes.getNamedItem("nodeScopeIndex");
            if (nsIndex != null) {
                nodeScopeIndex = Boolean.valueOf(nsIndex.getNodeValue()).booleanValue();
            }

            // get isRegexp flag
            boolean isRegexp = false;
            Node regexp = attributes.getNamedItem("isRegexp");
            if (regexp != null) {
                isRegexp = Boolean.valueOf(regexp.getNodeValue()).booleanValue();
            }

            PropertyConfig pc = new PropertyConfig(boost, nodeScopeIndex);

            if (isRegexp) {
                namePatterns.add(new NamePattern(getTextContent(n), pc, resolver));
            } else {
                Name propName = resolver.getQName(getTextContent(n));
                propConfigs.put(propName, pc);
            }
        }
    }
}

From source file:org.apache.jackrabbit.core.query.lucene.IndexingConfigurationImpl.java

/**
 * Creates property configurations defined in the <code>config</code>.
 *
 * @param config the fulltext indexing configuration.
 * @return the property configurations defined in the <code>config</code>.
 * @throws IllegalNameException   if the node type name contains illegal
 *                                characters.
 * @throws NamespaceException if the node type contains an unknown
 *                                prefix.
 *///w  w w  .  j a  va2s.c om
private Map getPropertyConfigs(Node config) throws IllegalNameException, NamespaceException {
    Map configs = new HashMap();
    NodeList childNodes = config.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node n = childNodes.item(i);
        if (n.getNodeName().equals("property")) {
            NamedNodeMap attributes = n.getAttributes();
            // get boost value
            float boost = 1.0f;
            Node boostAttr = attributes.getNamedItem("boost");
            if (boostAttr != null) {
                try {
                    boost = Float.parseFloat(boostAttr.getNodeValue());
                } catch (NumberFormatException e) {
                    // use default
                }
            }

            // get nodeScopeIndex flag
            boolean nodeScopeIndex = true;
            Node nsIndex = attributes.getNamedItem("nodeScopeIndex");
            if (nsIndex != null) {
                nodeScopeIndex = Boolean.valueOf(nsIndex.getNodeValue()).booleanValue();
            }

            // get property name
            Name propName = resolver.getQName(getTextContent(n));

            configs.put(propName, new PropertyConfig(boost, nodeScopeIndex));
        }
    }
    return configs;
}

From source file:org.apache.jmeter.protocol.http.parser.JTidyHTMLParser.java

private String getValue(NamedNodeMap attrs, String attname) {
    String v = null;//w  w w.j  av a  2 s  .  co m
    Node n = attrs.getNamedItem(attname);
    if (n != null) {
        v = n.getNodeValue();
    }
    return v;
}

From source file:org.apache.nutch.parse.html.DOMContentUtils.java

/**
 * This method finds all anchors below the supplied DOM
 * <code>node</code>, and creates appropriate {@link Outlink}
 * records for each (relative to the supplied <code>base</code>
 * URL), and adds them to the <code>outlinks</code> {@link
 * ArrayList}.//ww w .jav  a  2  s  .co m
 *
 * <p>
 *
 * Links without inner structure (tags, text, etc) are discarded, as
 * are links which contain only single nested links and empty text
 * nodes (this is a common DOM-fixup artifact, at least with
 * nekohtml).
 */
public void getOutlinks(URL base, ArrayList<Outlink> outlinks, Node node) {

    NodeWalker walker = new NodeWalker(node);
    while (walker.hasNext()) {

        Node currentNode = walker.nextNode();
        String nodeName = currentNode.getNodeName();
        short nodeType = currentNode.getNodeType();
        NodeList children = currentNode.getChildNodes();
        int childLen = (children != null) ? children.getLength() : 0;

        if (nodeType == Node.ELEMENT_NODE) {

            nodeName = nodeName.toLowerCase();
            LinkParams params = (LinkParams) linkParams.get(nodeName);
            if (params != null) {
                if (!shouldThrowAwayLink(currentNode, children, childLen, params)) {

                    StringBuffer linkText = new StringBuffer();
                    getText(linkText, currentNode, true);
                    if (linkText.toString().trim().length() == 0) {
                        // try harder - use img alt if present
                        NodeWalker subWalker = new NodeWalker(currentNode);
                        while (subWalker.hasNext()) {
                            Node subNode = subWalker.nextNode();
                            if (subNode.getNodeType() == Node.ELEMENT_NODE) {
                                if (subNode.getNodeName().toLowerCase().equals("img")) {
                                    NamedNodeMap subAttrs = subNode.getAttributes();
                                    Node alt = subAttrs.getNamedItem("alt");
                                    if (alt != null) {
                                        String altTxt = alt.getTextContent();
                                        if (altTxt != null && altTxt.trim().length() > 0) {
                                            if (linkText.length() > 0)
                                                linkText.append(' ');
                                            linkText.append(altTxt);
                                        }
                                    }
                                } else {
                                    // ignore other types of elements

                                }
                            } else if (subNode.getNodeType() == Node.TEXT_NODE) {
                                String txt = subNode.getTextContent();
                                if (txt != null && txt.length() > 0) {
                                    if (linkText.length() > 0)
                                        linkText.append(' ');
                                    linkText.append(txt);
                                }
                            }
                        }
                    }

                    NamedNodeMap attrs = currentNode.getAttributes();
                    String target = null;
                    boolean noFollow = false;
                    boolean post = false;
                    for (int i = 0; i < attrs.getLength(); i++) {
                        Node attr = attrs.item(i);
                        String attrName = attr.getNodeName();
                        if (params.attrName.equalsIgnoreCase(attrName)) {
                            target = attr.getNodeValue();
                        } else if ("rel".equalsIgnoreCase(attrName)
                                && "nofollow".equalsIgnoreCase(attr.getNodeValue())) {
                            noFollow = true;
                        } else if ("method".equalsIgnoreCase(attrName)
                                && "post".equalsIgnoreCase(attr.getNodeValue())) {
                            post = true;
                        }
                    }
                    if (target != null && !noFollow && !post)
                        try {

                            URL url = URLUtil.resolveURL(base, target);
                            outlinks.add(new Outlink(url.toString(), linkText.toString().trim()));
                        } catch (MalformedURLException e) {
                            // don't care
                        }
                }
                // this should not have any children, skip them
                if (params.childLen == 0)
                    continue;
            }
        }
    }
}

From source file:org.apache.openaz.xacml.std.json.JSONResponse.java

/**
 * Read characters from the given <code>InputStream</code> and parse them into an XACML
 * {@link org.apache.openaz.xacml.api.Request} object.
 *
 * @param is//from   ww  w  . j  a v  a 2  s . c  o m
 * @return
 * @throws JSONStructureException
 */
public static Response load(InputStream is) throws JSONStructureException {

    // TODO - ASSUME that order of members within an object does not matter (Different from XML, in JSON
    // everything is handled as Maps so order does not matter)

    // ensure shorthand map is set up
    if (shorthandMap == null) {
        initShorthandMap();
    }

    // ensure that we have an instance of the DataTypeFactory for generating AttributeValues by DataType
    if (dataTypeFactory == null) {
        try {
            dataTypeFactory = DataTypeFactory.newInstance();
            if (dataTypeFactory == null) {
                throw new NullPointerException("No DataTypeFactory found");
            }
        } catch (FactoryException e) {
            throw new JSONStructureException("Unable to find DataTypeFactory, e=" + e);
        }
    }

    // create a new Response object to be filled in
    StdMutableResponse stdMutableResponse = null;

    String json = null;
    ObjectMapper mapper = null;
    try {

        // read the inputStream into a buffer (trick found online scans entire input looking for
        // end-of-file)
        java.util.Scanner scanner = new java.util.Scanner(is);
        scanner.useDelimiter("\\A");
        json = scanner.hasNext() ? scanner.next() : "";
        scanner.close();

        mapper = new ObjectMapper().setVisibility(PropertyAccessor.FIELD, Visibility.ANY);

        // TODO - ASSUME that any duplicated component is a bad thing (probably indicating an error in the
        // incoming JSON)
        mapper.configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, true);

        Map<?, ?> root = mapper.readValue(json, Map.class);

        //
        // Does the Response exist?
        //
        List<?> resultList = (List<?>) root.remove("Response");
        if (resultList == null) {
            throw new JSONStructureException("No \"Response\" property found.");
        }

        checkUnknown("Top-level message", root);

        stdMutableResponse = new StdMutableResponse();

        // handle each Result object
        for (int resultIndex = 0; resultIndex < resultList.size(); resultIndex++) {
            // each item should be a Map<?,?> containing a Result, otherwise it is an error
            Object resultObj = resultList.get(resultIndex);
            if (resultObj == null || !(resultObj instanceof Map)) {
                throw new JSONStructureException(
                        "Response contains null Result or list instead of Result object");
            }

            StdMutableResult stdMutableResult = new StdMutableResult();

            Map<?, ?> resultMap = (Map<?, ?>) resultObj;

            // Must have a Decision
            Object decisionObject = resultMap.remove("Decision");
            if (decisionObject == null) {
                throw new JSONStructureException("Result must have Decision");
            }
            Decision decision = Decision.get(decisionObject.toString());
            if (decision == null) {
                throw new JSONStructureException(
                        "Unknown value for Decision: '" + decisionObject.toString() + "'");
            }
            stdMutableResult.setDecision(decision);

            // may have Status
            Object statusObject = resultMap.remove("Status");
            if (statusObject != null) {
                if (!(statusObject instanceof Map)) {
                    throw new JSONStructureException(
                            "Status must be an object, not type '" + statusObject.getClass().getName() + "'");
                }
                StdMutableStatus stdMutableStatus = new StdMutableStatus();
                Map<?, ?> statusMap = (Map<?, ?>) statusObject;

                // optional message
                Object messageObject = statusMap.remove("StatusMessage");
                if (messageObject != null) {
                    stdMutableStatus.setStatusMessage(messageObject.toString());
                }

                // optional detail
                Object detailObject = statusMap.remove("StatusDetail");
                if (detailObject != null) {
                    StdMutableStatusDetail statusDetail = new StdMutableStatusDetail();
                    // TODO - PROBLEM: The JSON spec says only that the status Detail is raw XML rather
                    // than a JSON object. Therefore we cannot discriminate what is inside the string we
                    // just got.
                    // TODO Fortunately there is only one thing it can be: a MissingAttributeDetail.
                    // TODO Unfortunately the MissingAttributeDetail contains multiple optional elements
                    // including 0 or more values, which makes it non-trivial to parse the XML
                    // representation.
                    // TODO Unfortunately the JSON spec does not say how the XML is formatted
                    // (with/without whitespace, etc).

                    //
                    // First of all, the String is possible escaped.
                    //
                    // The meaning of "escaped" is defined in section 4.2.3.1 in the JSON spec
                    //
                    String unescapedContent = detailObject.toString().replace("\\\"", "\"");
                    unescapedContent = unescapedContent.replace("\\\\", "\\");

                    // need to add a root element so that the MissingAttributeDetail elements are findable
                    unescapedContent = "<ROOT>" + unescapedContent + "</ROOT>";

                    // logger.info("Escaped content: \n" + unescapedContent);
                    Document doc = null;
                    try (InputStream bis = new ByteArrayInputStream(unescapedContent.getBytes("UTF-8"))) {
                        doc = DOMUtil.loadDocument(bis);
                    } catch (Exception ex) {
                        throw new JSONStructureException(
                                "Unable to parse Content '" + detailObject.toString() + "'");
                    }

                    // ASSUME that this can only be an array of MissingAttributeDetail. Example:
                    // <MissingAttributeDetail
                    // Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource"
                    // AttributeId="urn:att:xacml:resource:application:motsid"
                    // DataType="http://www.w3.org/2001/XMLSchema#integer">
                    // <AttributeValue
                    // DataType="http://www.w3.org/2001/XMLSchema#integer">56</AttributeValue>
                    // </MissingAttributeDetail>"
                    Element docElement = doc.getDocumentElement();
                    NodeList missingAttributeDetailList = docElement
                            .getElementsByTagName("MissingAttributeDetail");
                    for (int madNodeIndex = 0; madNodeIndex < missingAttributeDetailList
                            .getLength(); madNodeIndex++) {
                        Node madNode = missingAttributeDetailList.item(madNodeIndex);
                        StdMutableMissingAttributeDetail mutableMAD = new StdMutableMissingAttributeDetail();

                        NamedNodeMap attributeMap = madNode.getAttributes();
                        Node attributeNode = attributeMap.getNamedItem("AttributeId");
                        if (attributeNode == null) {
                            throw new JSONStructureException("MissingAttributeDetail missing AttributeId");
                        }
                        mutableMAD.setAttributeId(new IdentifierImpl(attributeNode.getNodeValue()));
                        Node categoryNode = attributeMap.getNamedItem("Category");
                        if (categoryNode == null) {
                            throw new JSONStructureException("MissingAttributeDetail missing Category");
                        }
                        mutableMAD.setCategory(new IdentifierImpl(categoryNode.getNodeValue()));
                        Node dataTypeNode = attributeMap.getNamedItem("DataType");
                        if (dataTypeNode == null) {
                            throw new JSONStructureException("MissingAttributeDetail missing DataType");
                        }
                        mutableMAD.setDataTypeId(new IdentifierImpl(dataTypeNode.getNodeValue()));
                        Node issuerNode = attributeMap.getNamedItem("Issuer");
                        if (issuerNode != null) {
                            mutableMAD.setIssuer(issuerNode.getNodeValue());
                        }

                        // get any value elements
                        NodeList childNodeList = madNode.getChildNodes();
                        for (int childIndex = 0; childIndex < childNodeList.getLength(); childIndex++) {
                            Node childNode = childNodeList.item(childIndex);
                            if (!childNode.getNodeName().equals("AttributeValue")) {
                                continue;
                            }
                            Node childDataTypeNode = childNode.getAttributes().getNamedItem("DataType");
                            if (childDataTypeNode == null) {
                                throw new JSONStructureException(
                                        "MissingAttributeDetail contains AttributeValue '"
                                                + childNode.getNodeValue() + "' with no DataType");
                            }
                            String dataType = childDataTypeNode.getNodeValue();
                            // this probably is not a shorthand, but look it up anyway. The full Ids are
                            // in the table too.
                            Identifier valueDataTypeId = shorthandMap.get(dataType);
                            if (valueDataTypeId == null) {
                                throw new JSONStructureException(
                                        "MissingAttibuteDetail contains AttributeValue with unknown DataType="
                                                + dataType);
                            }
                            // if Id is known then it is reasonable to do the following without checking
                            DataType<?> valueDataType = dataTypeFactory.getDataType(valueDataTypeId);
                            AttributeValue<?> attributeValue;
                            try {
                                // for some reason the value may be the value of a child of this node
                                // rather than the value of this node itself.
                                Node valueNode = childNode;
                                if (valueNode.hasChildNodes()) {
                                    valueNode = valueNode.getFirstChild();
                                }
                                attributeValue = valueDataType.createAttributeValue(valueNode.getNodeValue());
                            } catch (Exception ex) {
                                throw new JSONStructureException(
                                        "Unable to create AttributeValue from MissingAttributeDetail AttributeValue '"
                                                + childNode.getNodeValue() + "', error was: "
                                                + ex.getMessage());
                            }
                            mutableMAD.addAttributeValue(attributeValue);
                        }

                        statusDetail.addMissingAttributeDetail(mutableMAD);
                    }

                    stdMutableStatus.setStatusDetail(statusDetail);
                }

                // optional StatusCode which may contain recursive child StatusCode
                Object statusCodeObject = statusMap.remove("StatusCode");
                if (statusCodeObject != null) {
                    if (!(statusCodeObject instanceof Map)) {
                        throw new JSONStructureException("StatusCode must be object");
                    }
                    StatusCode statusCode = parseStatusCode((Map<?, ?>) statusCodeObject);
                    stdMutableStatus.setStatusCode(statusCode);
                }

                checkUnknown("Status", statusMap);

                stdMutableResult.setStatus(stdMutableStatus);
            }

            // may have Obligations
            Object obligationsObject = resultMap.remove("Obligations");
            if (obligationsObject != null) {
                parseObligationsOrAdvice(obligationsObject, stdMutableResult, true);
            }

            // may have Advice
            Object adviceObject = resultMap.remove("AssociatedAdvice");
            if (adviceObject != null) {
                parseObligationsOrAdvice(adviceObject, stdMutableResult, false);
            }

            // may have Category (a.k.a Attributes)
            // TODO - POSSIBLE NAME CHANGE - XML core calls this "Attributes", but name in JSON standard
            // is questionable.
            // TODO The variables here are named "Attributes" because that is the internal name in our
            // objects (based on the Core spec).
            Object attributesObject = resultMap.remove("Category");
            if (attributesObject != null) {
                if (!(attributesObject instanceof List)) {
                    throw new JSONStructureException("Category must be list");
                }
                List<?> attributesList = (List<?>) attributesObject;

                for (Object categoryObject : attributesList) {
                    if (categoryObject == null || !(categoryObject instanceof Map)) {
                        throw new JSONStructureException("Category array item must be object");
                    }
                    Map<?, ?> categoryMap = (Map<?, ?>) categoryObject;
                    StdMutableAttributeCategory stdMutableAttributeCategory = new StdMutableAttributeCategory();

                    // mandatory CategoryId
                    Object categoryIdObject = categoryMap.remove("CategoryId");
                    if (categoryIdObject == null) {
                        throw new JSONStructureException("Category array item must contain CategoryId");
                    }
                    Identifier categoryId = new IdentifierImpl(categoryIdObject.toString());

                    stdMutableAttributeCategory.setCategory(categoryId);

                    // optional Attributes
                    Object attributeListObject = categoryMap.remove("Attribute");
                    if (attributeListObject != null) {
                        if (!(attributeListObject instanceof List)) {
                            throw new JSONStructureException("Category memeber Attribute must be list");
                        }
                        List<?> attributeList = (List<?>) attributeListObject;
                        // get each attribute and add to category
                        for (Object attributeMapObject : attributeList) {
                            if (attributeMapObject == null || !(attributeMapObject instanceof Map)) {
                                throw new JSONStructureException(
                                        "Category member Attribute list item must be object");
                            }
                            Map<?, ?> attributeMap = (Map<?, ?>) attributeMapObject;

                            StdMutableAttribute stdMutableAttribute = new StdMutableAttribute();

                            // optional IncludeInResult
                            // TODO - Odd situation!!: We are reading a string representing a Result which
                            // includes Attributes.
                            // TODO In this case, what does it mean if "IncludeInResult=false"?
                            // TODO The Attribute is obviously included in this Result because it is in
                            // the file/string we are reading.
                            // TODO Our choice: Always include the Attribute. If the IncludeInResult is
                            // included in the input, set it's value in the object as directed.
                            // TODO This may cause mismatches between a Result read in and a new text
                            // generated from the internal Result object.
                            Object includeInResultObject = attributeMap.remove("IncludeInResult");
                            // the fact that the attribute is in the input means this should be true
                            stdMutableAttribute.setIncludeInResults(true);
                            if (includeInResultObject != null) {
                                // need to check the value in the input
                                try {
                                    boolean include = DataTypes.DT_BOOLEAN.convert(includeInResultObject)
                                            .booleanValue();
                                    // set the value in the object exactly as directed, whether it makes
                                    // sense or not
                                    stdMutableAttribute.setIncludeInResults(include);
                                } catch (DataTypeException e) {
                                    throw new JSONStructureException(
                                            "Category member Attribute list item has IncludeInResult value '"
                                                    + includeInResultObject.toString()
                                                    + "' which is not boolean");
                                }
                            }

                            // category is not part of Attribute in spec - it is used internally to link
                            // attribute to Category
                            stdMutableAttribute.setCategory(categoryId);

                            // mandatory Id
                            Object aaIdObject = attributeMap.remove("AttributeId");
                            if (aaIdObject == null) {
                                throw new JSONStructureException(
                                        "Category member Attribute list item missing AttributeId");
                            }
                            stdMutableAttribute.setAttributeId(new IdentifierImpl(aaIdObject.toString()));

                            // get the optional DataType so we know what to do with the mandatory value
                            Object dataTypeObject = attributeMap.remove("DataType");
                            Identifier dataTypeId = null;
                            if (dataTypeObject != null) {
                                dataTypeId = shorthandMap.get(dataTypeObject.toString());
                                // if there was a DataType given it must be a real one
                                if (dataTypeId == null) {
                                    throw new JSONStructureException(
                                            "Category member Attribute list item has unknown DataType='"
                                                    + dataTypeObject.toString() + "'");
                                }
                            } else {
                                // if DataType not given, use String
                                dataTypeId = DataTypes.DT_STRING.getId();
                            }

                            // mandatory Value
                            Object valueObject = attributeMap.remove("Value");
                            if (valueObject == null) {
                                throw new JSONStructureException(
                                        "Category member Attribute list item missing Value");
                            }
                            AttributeValue<?> attributeValue = null;
                            try {
                                DataType<?> dataType = new StdDataTypeFactory().getDataType(dataTypeId);
                                if (dataType == DataTypes.DT_XPATHEXPRESSION) {
                                    // XPAthExpressions are complex data types that need special
                                    // translation from the JSON form to the internal form
                                    attributeValue = convertMapToXPathExpression(valueObject);

                                } else {
                                    // everything other than XPathExpressions are simple values that the
                                    // DataTypes know how to handle
                                    attributeValue = dataType.createAttributeValue(valueObject);
                                }
                            } catch (DataTypeException e) {
                                throw new JSONStructureException("Category member Attribute list item Value='"
                                        + valueObject.toString() + "' not of type '" + dataTypeId + "'");
                            }
                            stdMutableAttribute.addValue(attributeValue);

                            // optional Issuer
                            Object issuerObject = attributeMap.remove("Issuer");
                            if (issuerObject != null) {
                                stdMutableAttribute.setIssuer(issuerObject.toString());
                            }

                            checkUnknown("Category Attribute list item", attributeMap);
                            stdMutableAttributeCategory.add(stdMutableAttribute);
                        }
                    }

                    checkUnknown("Category", categoryMap);

                    // if none of the attributes are returned, do not return the category either
                    if (stdMutableAttributeCategory.getAttributes().size() > 0) {
                        stdMutableResult.addAttributeCategory(stdMutableAttributeCategory);
                    }
                }
            }

            // may have PolicyIdentifierList
            Object policyIdObject = resultMap.remove("PolicyIdentifier");
            if (policyIdObject != null) {
                if (!(policyIdObject instanceof Map)) {
                    throw new JSONStructureException("PolicyIdentifier must be object");
                }
                Map<?, ?> policyIdMap = (Map<?, ?>) policyIdObject;

                // optional PolicyIdReference list
                Object policyIdReferenceObject = policyIdMap.remove("PolicyIdReference");
                if (policyIdReferenceObject != null) {
                    parseIdReferences(policyIdReferenceObject, stdMutableResult, false);
                }

                // optional PolicySetIdReferenceList
                Object policySetIdReferenceObject = policyIdMap.remove("PolicySetIdReference");
                if (policySetIdReferenceObject != null) {
                    parseIdReferences(policySetIdReferenceObject, stdMutableResult, true);
                }

                checkUnknown("PolicyIdentifier", policyIdMap);

            }

            checkUnknown("Result", resultMap);

            // add this result to the Response
            stdMutableResponse.add(stdMutableResult);

        }

        return stdMutableResponse;

    } catch (JsonParseException e) {
        throw new JSONStructureException("Unable to parse JSON '" + json + "', exception: " + e, e);
    } catch (JsonMappingException e) {
        throw new JSONStructureException("Unable to map JSON '" + json + "', exception: " + e, e);
    } catch (IOException e) {
        throw new JSONStructureException("Unable to read JSON input, exception: " + e, e);
    }

    // all done
    // return new StdRequest(stdMutableRequest);

    // throw new JSONStructureException("JSONResponse load string and load from file not implemented");
}

From source file:org.apache.openaz.xacml.util.ObjUtil.java

/**
 * Recursively compare these two nodes and then compare their children.
 *
 * @param node1//from  w w  w  . j a  va 2  s  . c o  m
 * @param node2
 * @return
 */
private static boolean compareXML(Node node1, Node node2) {
    // compare the nodes
    if (!equalsAllowNull(node1.getNodeName(), node2.getNodeName())
            || !equalsAllowNull(node1.getNodeValue(), node2.getNodeValue())
            || node1.getNodeType() != node2.getNodeType()) {
        // these two nodes to not match their basic information
        logger.info("Node1 '" + node1.getNodeName() + "' type: " + node1.getNodeType() + "  != Node2 '"
                + node2.getNodeName() + "' type: " + node2.getNodeType());
        return false;
    }

    // compare the attributes of the two nodes
    NamedNodeMap node1Attributes = node1.getAttributes();
    NamedNodeMap node2Attributes = node2.getAttributes();

    // null attributes == attributes with length 0
    if (node1Attributes == null) {
        if (node2Attributes != null && node2Attributes.getLength() > 0) {
            logger.info("Node1 '" + node1.getNodeName() + "' attrs null != Node2 '" + node2.getNodeName()
                    + "' attrs non-null");
            return false;
        }
    } else {
        // node1 Attributes is not null
        if (node2Attributes == null || node2Attributes.getLength() != node1Attributes.getLength()) {
            logger.info("Node1 '" + node1.getNodeName() + "' attrs non-null  != Node2 '" + node2.getNodeName()
                    + "' attrs null or length not same");
            return false;
        }

        // both attrs exist and are same length
        // check that all of list 1 is in list 2
        // no need to check attr from node2 exist in node 1 because the lists are the same length,
        // and since all attrs from node 1 exist in node 2 there cannot be any extra in node2
        for (int i = 0; i < node1Attributes.getLength(); i++) {
            if (node2Attributes.getNamedItem(node1Attributes.item(i).getNodeName()) == null) {
                // attribute in node 1 does not exist in node 2
                logger.info(
                        "Node1 '" + node1.getNodeName() + "' attr: '" + node1Attributes.item(i).getNodeName()
                                + "'  != Node2 '" + node2.getNodeName() + "' (missing attr)");
                return false;
            }
        }
    }

    // compare the children of the nodes
    NodeList children1 = node1.getChildNodes();
    NodeList children2 = node2.getChildNodes();

    if (children1.getLength() != children2.getLength()) {
        // they cannot be the same because the length is different
        logger.info("Node1 '" + node1.getNodeName() + "' children: " + children1.getLength() + " != Node2 '"
                + node2.getNodeName() + "' children: " + children2.getLength());
        return false;
    }

    // children are supposed to be in the same order
    for (int index1 = 0; index1 < children1.getLength(); index1++) {
        if (!compareXML(children1.item(index1), children2.item(index1))) {
            logger.info("Node1 '" + node1.getNodeName() + "' != Node2 '" + node2.getNodeName() + "'");
            return false;
        }
    }

    return true;
}

From source file:org.apache.openjpa.jdbc.sql.SQLErrorCodeReader.java

public List<String> getDictionaries(InputStream in) {
    List<String> result = new ArrayList<String>();
    DocumentBuilder builder = XMLFactory.getDOMParser(false, false);
    try {/*  w w  w.ja v a2s  . com*/
        Document doc = builder.parse(in);
        Element root = doc.getDocumentElement();
        NodeList nodes = root.getElementsByTagName("dictionary");
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            NamedNodeMap attrs = node.getAttributes();
            Node dictionary = attrs.getNamedItem("class");
            if (dictionary != null) {
                result.add(dictionary.getNodeValue());
            }
        }
    } catch (Throwable e) {
        if (log.isWarnEnabled()) {
            log.error(_loc.get("error-code-parse-error"));
        }
    } finally {
        try {
            in.close();
        } catch (IOException e) {
            // ignore
        }
    }
    return result;
}

From source file:org.apache.openjpa.jdbc.sql.SQLErrorCodeReader.java

/**
  * Parses given stream of XML content for error codes of the given database
  * dictionary name. Populates the given dictionary with the error codes.
 * //from  w ww.  j  a v  a 2  s. co  m
 */
public void parse(InputStream in, String dictName, DBDictionary dict) {
    if (in == null || dict == null)
        return;
    log = dict.conf.getLog(JDBCConfiguration.LOG_JDBC);
    DocumentBuilder builder = XMLFactory.getDOMParser(false, false);
    try {
        Document doc = builder.parse(in);
        Element root = doc.getDocumentElement();
        NodeList nodes = root.getElementsByTagName("dictionary");
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            NamedNodeMap attrs = node.getAttributes();
            Node dictionary = attrs.getNamedItem("class");
            if (dictionary != null && dictionary.getNodeValue().equals(dictName)) {
                readErrorCodes(node, dict);
            }
        }
    } catch (Throwable e) {
        if (log.isWarnEnabled()) {
            log.error(_loc.get("error-code-parse-error"));
        }
    } finally {
        try {
            in.close();
        } catch (IOException e) {
            // ignore
        }
    }
}

From source file:org.apache.poi.poifs.crypt.EncryptionHeader.java

public EncryptionHeader(String descriptor) throws IOException {
    NamedNodeMap keyData;
    try {//from   ww  w.ja v a2  s  .  c  o m
        ByteArrayInputStream is;
        is = new ByteArrayInputStream(descriptor.getBytes());
        keyData = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is)
                .getElementsByTagName("keyData").item(0).getAttributes();
    } catch (Exception e) {
        throw new EncryptedDocumentException("Unable to parse keyData");
    }

    keySize = Integer.parseInt(keyData.getNamedItem("keyBits").getNodeValue());
    flags = 0;
    sizeExtra = 0;
    cspName = null;

    int blockSize = Integer.parseInt(keyData.getNamedItem("blockSize").getNodeValue());
    String cipher = keyData.getNamedItem("cipherAlgorithm").getNodeValue();

    if ("AES".equals(cipher)) {
        providerType = PROVIDER_AES;
        if (blockSize == 16)
            algorithm = ALGORITHM_AES_128;
        else if (blockSize == 24)
            algorithm = ALGORITHM_AES_192;
        else if (blockSize == 32)
            algorithm = ALGORITHM_AES_256;
        else
            throw new EncryptedDocumentException("Unsupported key length");
    } else {
        throw new EncryptedDocumentException("Unsupported cipher");
    }

    String chaining = keyData.getNamedItem("cipherChaining").getNodeValue();

    if ("ChainingModeCBC".equals(chaining))
        cipherMode = MODE_CBC;
    else if ("ChainingModeCFB".equals(chaining))
        cipherMode = MODE_CFB;
    else
        throw new EncryptedDocumentException("Unsupported chaining mode");

    String hashAlg = keyData.getNamedItem("hashAlgorithm").getNodeValue();
    int hashSize = Integer.parseInt(keyData.getNamedItem("hashSize").getNodeValue());

    if ("SHA1".equals(hashAlg) && hashSize == 20)
        hashAlgorithm = HASH_SHA1;
    else
        throw new EncryptedDocumentException("Unsupported hash algorithm");

    String salt = keyData.getNamedItem("saltValue").getNodeValue();
    int saltLength = Integer.parseInt(keyData.getNamedItem("saltSize").getNodeValue());
    keySalt = Base64.decodeBase64(salt.getBytes());
    if (keySalt.length != saltLength)
        throw new EncryptedDocumentException("Invalid salt length");
}