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:edu.lternet.pasta.dml.parser.eml.Eml200Parser.java

/**
 * Processes the attributes in an attribute list. Called by
 * processAttributeList().//from  ww w.j av  a 2s.  c  o  m
 * 
 * @param  xpathapi           the XPath API
 * @param  attributesNodeList a node list
 * @param  attributeList      an AttributeList object
 */
private void processAttributes(CachedXPathAPI xpathapi, NodeList attributesNodeList,
        AttributeList attributeList) throws Exception {
    int attributesNodeListLength = attributesNodeList.getLength();

    // Process each attribute
    for (int i = 0; i < attributesNodeListLength; i++) {
        Node attributeNode = attributesNodeList.item(i);
        NodeList attributeNodeChildren = attributeNode.getChildNodes();
        //NamedNodeMap attAttributes = att.getAttributes();

        String attName = "";
        String attLabel = "";
        String attDefinition = "";
        String attUnit = "";
        String attUnitType = "";
        String attMeasurementScale = "";
        String attPrecision = "";
        Domain domain = null;
        String id = null;
        Vector missingValueCodeVector = new Vector();
        double numberPrecision = 0;
        ArrayList<StorageType> storageTypeArray = new ArrayList<StorageType>();

        // get attribute id
        NamedNodeMap attributeNodeAttributesMap = attributeNode.getAttributes();

        if (attributeNodeAttributesMap != null) {
            Node idNode = attributeNodeAttributesMap.getNamedItem(ID);

            if (idNode != null) {
                id = idNode.getNodeValue();
            }
        }

        elementId++;

        for (int j = 0; j < attributeNodeChildren.getLength(); j++) {
            Node childNode = attributeNodeChildren.item(j);
            String childNodeName = childNode.getNodeName();

            if (childNodeName.equals("attributeName")) {
                attName = childNode.getFirstChild().getNodeValue().trim().replace('.', '_');
            } else if (childNodeName.equals("attributeLabel")) {
                attLabel = childNode.getFirstChild().getNodeValue().trim();
            } else if (childNodeName.equals("attributeDefinition")) {
                attDefinition = childNode.getFirstChild().getNodeValue().trim();
            }
            // Process storageType elements
            else if (childNodeName.equals("storageType")) {
                String storageTypeTextValue = childNode.getFirstChild().getNodeValue().trim();
                NamedNodeMap storageTypeAttributesMap = childNode.getAttributes();
                StorageType storageType;
                String typeSystem = "";
                Node typeSystemNode = null;

                // Determine whether the typeSystem attribute was specified
                if (storageTypeAttributesMap != null) {
                    typeSystemNode = storageTypeAttributesMap.getNamedItem(TYPE_SYSTEM);

                    if (typeSystemNode != null) {
                        typeSystem = typeSystemNode.getNodeValue();
                    }
                }

                // Use the appropriate StorageType constructor depending on 
                // whether the 'typeSystem' attribute was specified
                if (!typeSystem.equals("")) {
                    storageType = new StorageType(storageTypeTextValue, typeSystem);
                } else {
                    storageType = new StorageType(storageTypeTextValue);
                }

                storageTypeArray.add(storageType);
            } else if (childNodeName.equals("measurementScale")) {
                //unit is tricky because it can be custom or standard
                //Vector info = new Vector();
                //int domainType = Domain.DOM_NONE;
                NodeList measurementScaleChildNodes = childNode.getChildNodes();

                for (int k = 0; k < measurementScaleChildNodes.getLength(); k++) {
                    Node measurementScaleChildNode = measurementScaleChildNodes.item(k);
                    String measurementScaleChildNodeName = measurementScaleChildNode.getNodeName();

                    if (measurementScaleChildNodeName.equals("interval")
                            || measurementScaleChildNodeName.equals("ratio")) {
                        String numberType = null;
                        String min = "", max = "";
                        Node standardUnitNode = xpathapi.selectSingleNode(measurementScaleChildNode,
                                "unit/standardUnit");
                        Node customUnitNode = xpathapi.selectSingleNode(measurementScaleChildNode,
                                "unit/customUnit");

                        if (standardUnitNode != null) {
                            attUnit = standardUnitNode.getFirstChild().getNodeValue();
                            attUnitType = Attribute.STANDARDUNIT;
                        } else if (customUnitNode != null) {
                            attUnit = customUnitNode.getFirstChild().getNodeValue();
                            attUnitType = Attribute.CUSTOMUNIT;
                        } else {
                            System.err.println("Unable to determine attribute unit.");
                        }

                        Node precisionNode = xpathapi.selectSingleNode(measurementScaleChildNode, "precision");

                        if (precisionNode != null) {
                            // precision is optional in EML201 so if it is
                            // not provided, the attPrecision will be the
                            // empty string
                            attPrecision = precisionNode.getFirstChild().getNodeValue();
                            numberPrecision = (new Double(attPrecision)).doubleValue();

                        }

                        Node numericDomainNode = xpathapi.selectSingleNode(measurementScaleChildNode,
                                "numericDomain");
                        NodeList numericDomainChildNodes = numericDomainNode.getChildNodes();

                        for (int index = 0; index < numericDomainChildNodes.getLength(); index++) {
                            String numericDomainChildNodeName = numericDomainChildNodes.item(index)
                                    .getNodeName();

                            if (numericDomainChildNodeName.equals("numberType")) {
                                // Got number type
                                numberType = numericDomainChildNodes.item(index).getFirstChild().getNodeValue();

                                if (isDebugging) {
                                    //log.debug("The number type is "+ numberType);
                                }
                            } else if (numericDomainChildNodeName.equals("boundsGroup")) {
                                // Got bounds group
                                NodeList boundsNodeList = xpathapi.selectNodeList(numericDomainNode,
                                        "./bounds");

                                for (i = 0; i < boundsNodeList.getLength(); i++) {
                                    NodeList aNodeList;
                                    Node boundsNode;

                                    //String exclMin = null, exclMax = null;
                                    try {
                                        aNodeList = xpathapi.selectNodeList(boundsNodeList.item(i),
                                                "./minimum");
                                        boundsNode = aNodeList.item(0);
                                        min = boundsNode.getFirstChild().getNodeValue();
                                        /*exclMin = bound.getAttributes()
                                            .getNamedItem("exclusive")
                                            .getNodeValue();*/
                                        aNodeList = xpathapi.selectNodeList(boundsNodeList.item(0),
                                                "./maximum");
                                        boundsNode = aNodeList.item(0);
                                        max = boundsNode.getFirstChild().getNodeValue();
                                        /*exclMax = bound.getAttributes()
                                            .getNamedItem("exclusive")
                                            .getNodeValue();*/
                                    } catch (Exception e) {
                                        //log.debug("Error in handle bound ", e);
                                    }
                                }
                            }
                        }

                        Double minNum = null;
                        Double maxNum = null;

                        if (!min.trim().equals("")) {
                            minNum = new Double(min);
                        }

                        if (!max.trim().equals("")) {
                            maxNum = new Double(max);
                        }

                        NumericDomain numericDomain = new NumericDomain(numberType, minNum, maxNum);
                        numericDomain.setPrecision(numberPrecision);
                        domain = numericDomain;

                    } else if (measurementScaleChildNodeName.equals("nominal")
                            || measurementScaleChildNodeName.equals("ordinal")) {
                        NodeList nonNumericDomainChildNodes = xpathapi
                                .selectSingleNode(measurementScaleChildNode, "nonNumericDomain")
                                .getChildNodes();

                        for (int m = 0; m < nonNumericDomainChildNodes.getLength(); m++) {
                            Node nonNumericDomainChildNode = nonNumericDomainChildNodes.item(m);
                            String nonNumericDomainChildNodeName = nonNumericDomainChildNode.getNodeName();

                            if (nonNumericDomainChildNodeName.equals("textDomain")) {
                                TextDomain textDomain = new TextDomain();
                                NodeList definitionNodeList = xpathapi.selectNodeList(nonNumericDomainChildNode,
                                        "./definition");
                                Node defintionNode = definitionNodeList.item(0);
                                String definition = defintionNode.getFirstChild().getNodeValue();

                                if (isDebugging) {
                                    //log.debug(
                                    // "The definition value is "+definition);
                                }

                                textDomain.setDefinition(definition);
                                NodeList patternNodeList = xpathapi.selectNodeList(nonNumericDomainChildNode,
                                        "./pattern");

                                String[] patternList = new String[patternNodeList.getLength()];

                                for (int l = 0; l < patternNodeList.getLength(); l++) {
                                    patternList[l] = patternNodeList.item(l).getFirstChild().getNodeValue();
                                }

                                if (patternList.length > 0) {
                                    textDomain.setPattern(patternList);
                                }

                                domain = textDomain;

                            } else if (nonNumericDomainChildNodeName.equals("enumeratedDomain")) {
                                EnumeratedDomain enumeratedDomain = new EnumeratedDomain();
                                Vector info = new Vector();

                                NodeList codeDefinitionNodeList = xpathapi
                                        .selectNodeList(nonNumericDomainChildNode, "./codeDefinition");

                                for (int l = 0; l < codeDefinitionNodeList.getLength(); l++) {
                                    info.add(codeDefinitionNodeList.item(l).getFirstChild().getNodeValue());
                                }

                                enumeratedDomain.setInfo(info);
                                domain = enumeratedDomain;
                            }
                        }
                    } else if (measurementScaleChildNodeName.equalsIgnoreCase("datetime")) {
                        DateTimeDomain date = new DateTimeDomain();
                        String formatString = (xpathapi.selectSingleNode(measurementScaleChildNode,
                                "./formatString")).getFirstChild().getNodeValue();

                        if (isDebugging) {
                            //log.debug(
                            //          "The format string in date time is " 
                            //          + formatString);
                        }
                        date.setFormatString(formatString);
                        domain = date;
                    }
                }
            } else if (childNodeName.equals("missingValueCode")) {
                //log.debug("in missingValueCode");
                NodeList missingValueCodeChildNodes = childNode.getChildNodes();

                for (int k = 0; k < missingValueCodeChildNodes.getLength(); k++) {
                    Node missingValueCodeChildNode = missingValueCodeChildNodes.item(k);
                    String missingValueCodeChildNodeName = missingValueCodeChildNode.getNodeName();

                    if (missingValueCodeChildNodeName.equals("code")) {
                        Node missingValueCodeTextNode = missingValueCodeChildNode.getFirstChild();

                        if (missingValueCodeTextNode != null) {
                            String missingValueCode = missingValueCodeTextNode.getNodeValue();

                            if (isDebugging) {
                                //log.debug("the missing code is "+missingCode);
                            }

                            missingValueCodeVector.add(missingValueCode);
                            //hasMissingValue = true;
                        }
                    }
                }
            }
        }

        /******************************************************
         * need to use domain type to replace data type
         ******************************************************/
        /*String resolvedType = null;
        //DataType dataType = domain.getDataType();
        //resolvedType = dataType.getName();
        if(isDebugging) {
          //log.debug("The final type is " + resolvedType);
        }*/

        Attribute attObj = new Attribute(id, attName, attLabel, attDefinition, attUnit, attUnitType,
                attMeasurementScale, domain);

        // Add storageType elements to the Attribute object 
        // if any were parsed in the EML
        for (StorageType storageType : storageTypeArray) {
            attObj.addStorageType(storageType);
        }

        // Add missing value code into attribute
        for (int k = 0; k < missingValueCodeVector.size(); k++) {
            String missingValueCode = (String) missingValueCodeVector.elementAt(k);
            if (isDebugging) {
                //log.debug("the mssing value code " + missingCodeValue + 
                //          " was added to attribute");
            }

            attObj.addMissingValueCode(missingValueCode);
        }

        attributeList.add(attObj);
    }
}

From source file:org.openremote.android.test.console.net.ORConnectionTest.java

/**
 * Test basic get of list of panels from public controller instance -- expects two pre-configured
 * panels to be returned./* w ww .  j  a v  a  2  s.  c o m*/
 *
 * @throws IOException if connection fails for any reason, see checkURLWithHTTPProtocol javadoc
 * @throws ParserConfigurationException if DOM parsing fails on return data
 * @throws SAXException if parsing fails on return data
 */
public void testControllerGETRestPanelXML() throws IOException, ParserConfigurationException, SAXException {
    final String TESTURL = TEST_CONTROLLER_URL + RESTAPI_PANEL_URI;

    HttpResponse response = ORConnection.checkURLWithHTTPProtocol(activity, ORHttpMethod.GET, TESTURL,
            NO_HTTP_AUTH);

    assertHttpResponse(response, TESTURL, HttpURLConnection.HTTP_OK);

    // TODO :
    //   This should be fixed in Controller 2.0 Alpha 12 -- uncomment when online test controller
    //   has been upgraded (currently returns 'text/plain')
    //
    try {
        assertMimeType(response, APPLICATIONXML_MIME_TYPE);

        fail("\n\nIncorrect content-type issue has been fixed, please update this test.\n\n");
    } catch (Throwable t) {
        // TODO: Ignore for now, remove the check once content-type issue has been fixed.
    }

    Document doc = getDOMDocument(response);

    assertOpenRemoteRootElement(doc);

    NodeList list = doc.getElementsByTagName("panel");

    assertTrue(list.getLength() >= 2);

    Map<String, String> panels = new HashMap<String, String>(3);

    for (int panelIndex = 0; panelIndex < list.getLength(); ++panelIndex) {
        Node panel = list.item(panelIndex);
        NamedNodeMap attrs = panel.getAttributes();

        Node id = attrs.getNamedItem("id");
        String idVal = id.getNodeValue();

        Node name = attrs.getNamedItem("name");
        String nameVal = name.getNodeValue();

        panels.put(idVal, nameVal);
    }

    assertNotNull("Expected panel id '1' but that was not found.", panels.get("1"));
    assertNotNull("Expected panel id '5' but that was not found.", panels.get("5"));

    assertTrue("Expected panel id=1 with name 'SimpleName', got " + panels.get("1"),
            panels.get("1").equalsIgnoreCase("SimpleName"));

    assertTrue("Expected panel id=5 with name 'Name With Space', got " + panels.get("5"),
            panels.get("5").equalsIgnoreCase("Name With Spaces"));
}

From source file:net.oddsoftware.android.feedscribe.data.FeedManager.java

private String extractAttribute(Element root, String tagName, String attributeName) {
    StringBuffer buffer = new StringBuffer();
    NodeList nlList = root.getElementsByTagName(tagName);
    if (nlList.getLength() > 0) {
        NamedNodeMap attributes = nlList.item(0).getAttributes();
        Node nValue = attributes.getNamedItem(attributeName);
        if (nValue != null) {
            buffer.append(nValue.getNodeValue());
        }//  w ww.  j  a v  a2  s  .  c o  m
    }
    return buffer.toString();
}

From source file:hoot.services.models.osm.Element.java

protected long parseVersion(final NamedNodeMap xmlAttributes) throws Exception {
    long version = 1;
    //version passed in the request can be ignored if it is a create request
    if (!entityChangeType.equals(EntityChangeType.CREATE)) {
        //if its ever determined that doing this fetch when this method is called in a loop hinders
        //performance (#2951), replace this query with a query outside the loop that checks for the
        //existence of all nodes and validates their versions in a batch query.  The downside to
        //this, however, would be parsing the XML node data more than once.

        Object existingRecord = new SQLQuery(conn, DbUtils.getConfiguration(getMapId())).from(getElementTable())
                .where(getElementIdField().eq(new Long(oldId))).singleResult(getElementTable());

        if (existingRecord == null) {
            throw new Exception(toString() + " to be updated does not exist with ID: " + oldId);
        }/*from   w  ww .ja v  a2 s.  c o m*/
        version = Long.parseLong(xmlAttributes.getNamedItem("version").getNodeValue());
        //the specified version must be validated with what's already in the database on a modify
        final long existingVersion = (Long) MethodUtils.invokeMethod(existingRecord, "getVersion",
                new Object[] {});
        if (version != existingVersion) {
            throw new Exception("Invalid version: " + version + " for " + toString() + " with ID: " + getId()
                    + " and version " + existingVersion + " in changeset with ID: "
                    + MethodUtils.invokeMethod(record, "getChangesetId", new Object[] {}));
        }
        version++;
    } else {
        //TODO: I'm not sure how important it is that this check is strictly enforced here, but I'm
        //doing it for now anyway.
        final long parsedVersion = Long.parseLong(xmlAttributes.getNamedItem("version").getNodeValue());
        if (parsedVersion != 0) {
            throw new Exception("Invalid version: " + version + " for element to be created: " + toString()
                    + " with ID: " + getId() + " and version " + parsedVersion + " in changeset with ID: "
                    + MethodUtils.invokeMethod(record, "getChangesetId", new Object[] {}));
        }
    }
    return version;
}

From source file:org.openremote.android.test.console.net.ORConnectionTest.java

/**
 * Asserts the panel XML definition contains all the necessary elements
 * for the integration tests.//from  w  w w . java 2s.  c  o  m
 *
 * @throws IOException if connection fails for any reason, see checkURLWithHTTPProtocol javadoc
 * @throws ParserConfigurationException if DOM parsing fails on return data
 * @throws SAXException if parsing fails on return data
 */
public void testControllerGETRestFullPanelXML() throws IOException, ParserConfigurationException, SAXException {
    final String TESTURL = TEST_CONTROLLER_URL + RESTAPI_FULLPANEL_URI + "SimpleName";

    HttpResponse response = ORConnection.checkURLWithHTTPProtocol(activity, ORHttpMethod.GET, TESTURL,
            NO_HTTP_AUTH);

    assertHttpResponse(response, TESTURL, HttpURLConnection.HTTP_OK);

    // TODO :
    //   This should be fixed in Controller 2.0 Alpha 12 -- uncomment when online test controller
    //   has been upgraded (currently returns 'text/plain')
    //
    try {
        assertMimeType(response, APPLICATIONXML_MIME_TYPE);

        fail("\n\nIncorrect content-type issue has been fixed, please update this test.\n\n");
    } catch (Throwable t) {
        // TODO: Ignore for now, remove the check once content-type issue has been fixed.
    }

    Document doc = getDOMDocument(response);

    assertOpenRemoteRootElement(doc);

    NodeList list = doc.getElementsByTagName("screens");

    assertTrue("Expected one <screens> element in panel definition.", list.getLength() == 1);

    list = doc.getElementsByTagName("groups");

    assertTrue("Expected one <groups> element in panel definition.", list.getLength() == 1);

    list = doc.getElementsByTagName("group");

    assertTrue("Expected at least one group in the panel definition.", list.getLength() >= 1);

    Set<String> screenReferences = new HashSet<String>(10);

    for (int groupIndex = 0; groupIndex < list.getLength(); ++groupIndex) {
        Node group = list.item(groupIndex);

        if (group.getNodeType() != Node.ELEMENT_NODE)
            continue;

        assertTrue("Expected <group> to have child elements, found none.", group.hasChildNodes());

        NodeList includes = group.getChildNodes();

        assertTrue("Expected at least one included screen in the group.", includes.getLength() >= 1);

        for (int includeIndex = 0; includeIndex < includes.getLength(); ++includeIndex) {
            Node include = includes.item(includeIndex);

            if (include.getNodeType() != Node.ELEMENT_NODE)
                continue;

            NamedNodeMap attrs = include.getAttributes();

            assertNotNull("Expected to find attributes in include", attrs);
            assertNotNull("Expected to find 'ref' attribute in <include>, got null", attrs.getNamedItem("ref"));

            Node ref = attrs.getNamedItem("ref");

            String screenRef = ref.getNodeValue();

            screenReferences.add(screenRef);
        }
    }

    list = doc.getElementsByTagName("screen");

    Set<String> screenIDs = new HashSet<String>(10);

    assertTrue("Expected at least one <screen> in panel definition.", list.getLength() >= 1);

    for (int screenIndex = 0; screenIndex < list.getLength(); ++screenIndex) {
        Node screen = list.item(screenIndex);

        NamedNodeMap attrs = screen.getAttributes();

        assertNotNull("Expected to find 'id' attribute in screen, not null.", attrs.getNamedItem("id"));

        Node id = attrs.getNamedItem("id");

        screenIDs.add(id.getNodeValue());
    }

    for (String ref : screenReferences) {
        assertTrue("Expected to find screen with id: " + ref, screenIDs.contains(ref));
    }

    list = doc.getElementsByTagName("button");

    assertTrue("Expected at least two <button> elements, got " + list.getLength(), list.getLength() >= 2);

    Set<String> buttonIDs = new HashSet<String>(10);

    for (int btnIndex = 0; btnIndex < list.getLength(); ++btnIndex) {
        Node button = list.item(btnIndex);

        NamedNodeMap attrs = button.getAttributes();

        assertNotNull("Expected to find attributes in <button>, got null.", attrs);

        assertNotNull("Expected to find id attribute in <button>.", attrs.getNamedItem("id"));

        Node id = attrs.getNamedItem("id");

        buttonIDs.add(id.getNodeValue());
    }

    assertTrue("Expected to find a button with ID=22", buttonIDs.contains("22"));
    assertTrue("Expected to find a button with ID=24", buttonIDs.contains("24"));

    list = doc.getElementsByTagName("switch");

    assertTrue("Expected at least one <switch> element, got " + list.getLength(), list.getLength() >= 1);

    Set<String> switchIDs = new HashSet<String>(10);
    Set<String> sensorReferences = new HashSet<String>(10);

    for (int switchIndex = 0; switchIndex < list.getLength(); ++switchIndex) {
        Node switchComp = list.item(switchIndex);

        NamedNodeMap attrs = switchComp.getAttributes();

        assertNotNull("Expected to find attributes in <switch>, got null.", attrs);

        assertNotNull("Expected to find id attribute in <switch>.", attrs.getNamedItem("id"));

        Node id = attrs.getNamedItem("id");

        switchIDs.add(id.getNodeValue());

        NodeList links = switchComp.getChildNodes();

        for (int linksIndex = 0; linksIndex < links.getLength(); ++linksIndex) {
            Node link = links.item(linksIndex);

            if (link.getNodeType() != Node.ELEMENT_NODE)
                continue;

            if (!link.getNodeName().equalsIgnoreCase("link"))
                continue;

            NamedNodeMap linkAttrs = link.getAttributes();

            assertNotNull("Expected attributes on <link>, got null.", linkAttrs);

            Node typeAttr = linkAttrs.getNamedItem("type");

            if (typeAttr.getNodeValue().equalsIgnoreCase("sensor")) {
                Node refAttr = linkAttrs.getNamedItem("ref");

                assertNotNull("Expected a 'ref' attribute in 'sensor' link, didn't find it.", refAttr);

                sensorReferences.add(refAttr.getNodeValue());
            }
        }
    }

    assertTrue("Expected to find a switch with ID=28", switchIDs.contains("28"));
    assertTrue("Expected to find sensor link with ID=29", sensorReferences.contains("29"));
}

From source file:net.oddsoftware.android.feedscribe.data.FeedManager.java

private void parseAsAtom(Document doc, Feed feed, FeedStatus feedStatus, ArrayList<FeedItem> feedItems,
        ArrayList<Enclosure> enclosures) {
    // parse all 'item' elements
    NodeList nl = doc.getElementsByTagName("entry");
    for (int i = 0; i < nl.getLength(); i++) {
        FeedItem feedItem = new FeedItem();
        Node node = nl.item(i);//w ww  .jav a  2 s  .  c om
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element eElement = (Element) node;

            feedItem.mTitle = extractValue(eElement, "title");
            feedItem.mGUID = extractValue(eElement, "id");
            feedItem.mCleanDescription = extractValue(eElement, "summary");
            feedItem.mDescription = extractValue(eElement, "content");
            feedItem.mOriginalLink = extractValue(eElement, "feedburner:origLink");

            feedItem.mImageURL = extractAttribute(eElement, "media:thumbnail", "url");

            NodeList authorNodes = eElement.getElementsByTagName("author");
            for (int j = 0; j < authorNodes.getLength(); ++j) {
                if (authorNodes.item(j).getNodeType() == Node.ELEMENT_NODE) {
                    feedItem.mAuthor = extractValue((Element) (authorNodes.item(j)), "name");
                    if (feedItem.mAuthor.length() > 0) {
                        break;
                    }
                }
            }

            Date pubDate = new Date();
            pubDate.setTime(0);

            String pubDateString = extractValue(eElement, "updated");
            try {
                pubDate = parseRFC3339Date(pubDateString);
            } catch (ParseException exc) {
                mLog.e("unable to parse item pubdate:" + pubDateString);
            }
            feedItem.mPubDate = pubDate;

            NodeList linksList = eElement.getElementsByTagName("link");
            if (linksList != null) {
                for (int j = 0; j < linksList.getLength(); ++j) {
                    NamedNodeMap linkAttributes = linksList.item(j).getAttributes();
                    Node relNode = linkAttributes.getNamedItem("rel");
                    if (relNode == null) {
                        continue;
                    }
                    String rel = relNode.getNodeValue();
                    if (rel.equals("alternate") && feedItem.mLink.length() == 0) {
                        feedItem.mLink = extractAttribute(eElement, "link", "href");
                    } else if (rel.equals("enclosure")) {
                        Enclosure enclosure = new Enclosure();

                        Node enclosureURL = linkAttributes.getNamedItem("href");
                        Node enclosureLength = linkAttributes.getNamedItem("length");
                        Node enclosureType = linkAttributes.getNamedItem("type");

                        if (enclosureURL != null) {
                            enclosure.mURL = enclosureURL.getNodeValue();
                        }

                        if (enclosureLength != null) {
                            try {
                                enclosure.mLength = Long.parseLong(enclosureLength.getNodeValue());
                            } catch (NumberFormatException exc) {
                                mLog.e("error parsing enclosure length", exc);
                            }
                        }

                        if (enclosureType != null) {
                            enclosure.mContentType = enclosureType.getNodeValue();
                        }

                        // TODO - find a better way to do this
                        // nuke image enclosures for now
                        if (enclosure.mContentType.startsWith("image/")) {
                            enclosure.mURL = "";
                        }

                        if (enclosure.mURL.length() > 0) {
                            try {
                                URL url = new URL(enclosure.mURL);

                                feedItem.mEnclosureURL = url.toExternalForm();
                                enclosure.mURL = url.toExternalForm();
                                feedItem.mEnclosure = enclosure;

                                enclosures.add(enclosure);
                            } catch (MalformedURLException exc) {
                                mLog.e("error parsing enclosure url", exc);
                            }
                        }
                    }
                }
            }

            if (feedItem.mLink.length() > 0) {
                feedItems.add(feedItem);
            }
        }
    } // proccess all entries

    // parse all 'feed' elements
    nl = doc.getElementsByTagName("feed");
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            // extract ttl
            Element eElement = (Element) node;
            if (feed != null) {
                String title = extractValue(eElement, "title");
                String link = extractAttribute(eElement, "link", "href");
                String description = extractValue(eElement, "subtitle");

                feed.mName = title;
                feed.mLink = link;
                feed.mDescription = description;
                feed.mImageURL = extractValue(eElement, "icon");
            }
        }

        feedStatus.mTTL = 10;
    }
}

From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java

private synchronized boolean hasEqualAttributes(final Node original, final Node patch) {

    NamedNodeMap map1 = original.getAttributes();
    NamedNodeMap map2 = patch.getAttributes();
    int len = map1.getLength();
    if (len != map2.getLength()) {
        return false;
    }/*from www.j a  v  a  2  s .  co m*/

    for (int i = 0; i < len; i++) {
        Node n1 = map1.item(i);
        if (n1.getNodeName() != null) {
            Node n2 = map2.getNamedItem(n1.getNodeName());
            if (n2 == null) {
                return false;
            } else if (!n1.getNodeValue().equals(n2.getNodeValue())) {
                return false;
            }
        }
    }
    return true;
}

From source file:org.keycloak.testsuite.adapter.servlet.SAMLServletAdapterTest.java

@Test
public void testInvalidCredentialsEcpFlow() throws Exception {
    Response authnRequestResponse = ClientBuilder.newClient().target(ecpSPPage.toString()).request()
            .header("Accept", "text/html; application/vnd.paos+xml")
            .header("PAOS", "ver='urn:liberty:paos:2003-08' ;'urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp'")
            .get();// w ww.  jav a 2s .  c o  m

    SOAPMessage authnRequestMessage = MessageFactory.newInstance().createMessage(null,
            new ByteArrayInputStream(authnRequestResponse.readEntity(byte[].class)));
    Iterator<SOAPHeaderElement> it = authnRequestMessage.getSOAPHeader()
            .<SOAPHeaderElement>getChildElements(new QName("urn:liberty:paos:2003-08", "Request"));

    it.next();

    it = authnRequestMessage.getSOAPHeader().<SOAPHeaderElement>getChildElements(
            new QName("urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp", "Request"));
    SOAPHeaderElement ecpRequestHeader = it.next();
    NodeList idpList = ecpRequestHeader.getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:protocol",
            "IDPList");

    Assert.assertThat("No IDPList returned from Service Provider", idpList.getLength(), is(1));

    NodeList idpEntries = idpList.item(0).getChildNodes();

    Assert.assertThat("No IDPEntry returned from Service Provider", idpEntries.getLength(), is(1));

    String singleSignOnService = null;

    for (int i = 0; i < idpEntries.getLength(); i++) {
        Node item = idpEntries.item(i);
        NamedNodeMap attributes = item.getAttributes();
        Node location = attributes.getNamedItem("Loc");

        singleSignOnService = location.getNodeValue();
    }

    Assert.assertThat("Could not obtain SSO Service URL", singleSignOnService, notNullValue());

    Document authenticationRequest = authnRequestMessage.getSOAPBody().getFirstChild().getOwnerDocument();
    String username = "pedroigor";
    String password = "baspassword";
    String pair = username + ":" + password;
    String authHeader = "Basic " + Base64.encodeBytes(pair.getBytes());

    Response authenticationResponse = ClientBuilder.newClient().target(singleSignOnService).request()
            .header(HttpHeaders.AUTHORIZATION, authHeader)
            .post(Entity.entity(DocumentUtil.asString(authenticationRequest), "application/soap+xml"));

    Assert.assertThat(authenticationResponse.getStatus(), is(OK.getStatusCode()));

    SOAPMessage responseMessage = MessageFactory.newInstance().createMessage(null,
            new ByteArrayInputStream(authenticationResponse.readEntity(byte[].class)));
    Node samlResponse = responseMessage.getSOAPBody().getFirstChild();

    Assert.assertThat(samlResponse, notNullValue());

    StatusResponseType responseType = (StatusResponseType) SAMLParser.getInstance().parse(samlResponse);
    StatusCodeType statusCode = responseType.getStatus().getStatusCode();

    Assert.assertThat(statusCode.getStatusCode().getValue().toString(),
            is(not(JBossSAMLURIConstants.STATUS_SUCCESS.get())));
}

From source file:org.keycloak.testsuite.adapter.servlet.SAMLServletAdapterTest.java

@Test
public void testSuccessfulEcpFlow() throws Exception {
    Response authnRequestResponse = ClientBuilder.newClient().target(ecpSPPage.toString()).request()
            .header("Accept", "text/html; application/vnd.paos+xml")
            .header("PAOS", "ver='urn:liberty:paos:2003-08' ;'urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp'")
            .get();//ww w. j  a v a  2s  . co m

    SOAPMessage authnRequestMessage = MessageFactory.newInstance().createMessage(null,
            new ByteArrayInputStream(authnRequestResponse.readEntity(byte[].class)));

    //printDocument(authnRequestMessage.getSOAPPart().getContent(), System.out);

    Iterator<SOAPHeaderElement> it = authnRequestMessage.getSOAPHeader().<SOAPHeaderElement>getChildElements(
            new QName("urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp", "Request"));
    SOAPHeaderElement ecpRequestHeader = it.next();
    NodeList idpList = ecpRequestHeader.getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:protocol",
            "IDPList");

    Assert.assertThat("No IDPList returned from Service Provider", idpList.getLength(), is(1));

    NodeList idpEntries = idpList.item(0).getChildNodes();

    Assert.assertThat("No IDPEntry returned from Service Provider", idpEntries.getLength(), is(1));

    String singleSignOnService = null;

    for (int i = 0; i < idpEntries.getLength(); i++) {
        Node item = idpEntries.item(i);
        NamedNodeMap attributes = item.getAttributes();
        Node location = attributes.getNamedItem("Loc");

        singleSignOnService = location.getNodeValue();
    }

    Assert.assertThat("Could not obtain SSO Service URL", singleSignOnService, notNullValue());

    Document authenticationRequest = authnRequestMessage.getSOAPBody().getFirstChild().getOwnerDocument();
    String username = "pedroigor";
    String password = "password";
    String pair = username + ":" + password;
    String authHeader = "Basic " + Base64.encodeBytes(pair.getBytes());

    Response authenticationResponse = ClientBuilder.newClient().target(singleSignOnService).request()
            .header(HttpHeaders.AUTHORIZATION, authHeader)
            .post(Entity.entity(DocumentUtil.asString(authenticationRequest), "text/xml"));

    Assert.assertThat(authenticationResponse.getStatus(), is(OK.getStatusCode()));

    SOAPMessage responseMessage = MessageFactory.newInstance().createMessage(null,
            new ByteArrayInputStream(authenticationResponse.readEntity(byte[].class)));

    //printDocument(responseMessage.getSOAPPart().getContent(), System.out);

    SOAPHeader responseMessageHeaders = responseMessage.getSOAPHeader();

    NodeList ecpResponse = responseMessageHeaders.getElementsByTagNameNS(
            JBossSAMLURIConstants.ECP_PROFILE.get(), JBossSAMLConstants.RESPONSE__ECP.get());

    Assert.assertThat("No ECP Response", ecpResponse.getLength(), is(1));

    Node samlResponse = responseMessage.getSOAPBody().getFirstChild();

    Assert.assertThat(samlResponse, notNullValue());

    ResponseType responseType = (ResponseType) SAMLParser.getInstance().parse(samlResponse);
    StatusCodeType statusCode = responseType.getStatus().getStatusCode();

    Assert.assertThat(statusCode.getValue().toString(), is(JBossSAMLURIConstants.STATUS_SUCCESS.get()));
    Assert.assertThat(responseType.getDestination(), is(ecpSPPage.toString() + "/"));
    Assert.assertThat(responseType.getSignature(), notNullValue());
    Assert.assertThat(responseType.getAssertions().size(), is(1));

    SOAPMessage samlResponseRequest = MessageFactory.newInstance().createMessage();

    samlResponseRequest.getSOAPBody().addDocument(responseMessage.getSOAPBody().extractContentAsDocument());

    ByteArrayOutputStream os = new ByteArrayOutputStream();

    samlResponseRequest.writeTo(os);

    Response serviceProviderFinalResponse = ClientBuilder.newClient().target(responseType.getDestination())
            .request().post(Entity.entity(os.toByteArray(), "application/vnd.paos+xml"));

    Map<String, NewCookie> cookies = serviceProviderFinalResponse.getCookies();

    Invocation.Builder resourceRequest = ClientBuilder.newClient().target(responseType.getDestination())
            .request();

    for (NewCookie cookie : cookies.values()) {
        resourceRequest.cookie(cookie);
    }

    Response resourceResponse = resourceRequest.get();
    Assert.assertThat(resourceResponse.readEntity(String.class), containsString("pedroigor"));
}

From source file:net.oddsoftware.android.feedscribe.data.FeedManager.java

private void parseAsRss(Document doc, Feed feed, FeedStatus feedStatus, ArrayList<FeedItem> feedItems,
        ArrayList<Enclosure> enclosures) {
    // parse all 'item' elements
    NodeList nl = doc.getElementsByTagName("item");
    for (int i = 0; i < nl.getLength(); i++) {
        FeedItem feedItem = new FeedItem();
        Node node = nl.item(i);/*from w  ww .  ja  v  a  2 s. com*/
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element eElement = (Element) node;

            feedItem.mTitle = extractValue(eElement, "title");
            feedItem.mLink = extractValue(eElement, "link");
            feedItem.mGUID = extractValue(eElement, "guid");
            feedItem.mAuthor = extractValue(eElement, "author");
            feedItem.mDescription = extractValue(eElement, "description");
            feedItem.mOriginalLink = extractValue(eElement, "feedburner:origLink");

            feedItem.mImageURL = extractAttribute(eElement, "media:thumbnail", "url");

            if (feedItem.mAuthor.length() == 0) {
                feedItem.mAuthor = extractValue(eElement, "dc:creator");
            }

            Date pubDate = new Date();
            pubDate.setTime(0);

            String pubDateString = extractValue(eElement, "pubDate");
            try {
                pubDate = parseRFC822Date(pubDateString);
            } catch (ParseException exc) {
                mLog.e("unable to parse item pubdate:" + pubDateString);
            }
            feedItem.mPubDate = pubDate;

            NodeList enclosuresList = eElement.getElementsByTagName("enclosure");
            if (enclosuresList != null && enclosuresList.getLength() > 0) {
                NamedNodeMap enclosureAttributes = enclosuresList.item(0).getAttributes();
                if (enclosureAttributes != null) {
                    Enclosure enclosure = new Enclosure();

                    Node enclosureURL = enclosureAttributes.getNamedItem("url");
                    Node enclosureLength = enclosureAttributes.getNamedItem("length");
                    Node enclosureType = enclosureAttributes.getNamedItem("type");

                    if (enclosureURL != null) {
                        enclosure.mURL = enclosureURL.getNodeValue();
                    }

                    if (enclosureLength != null) {
                        try {
                            enclosure.mLength = Long.parseLong(enclosureLength.getNodeValue());
                        } catch (NumberFormatException exc) {
                            mLog.e("error parsing enclosure length", exc);
                        }
                    }

                    if (enclosureType != null) {
                        enclosure.mContentType = enclosureType.getNodeValue();
                    }

                    String duration = extractValue(eElement, "itunes:duration");
                    if (duration != null && duration.length() > 0) {
                        enclosure.mDuration = Utilities.parseDuration(duration) * 1000;
                    }

                    duration = extractAttribute(eElement, "media:content", "duration");
                    if (duration != null && duration.length() > 0) {
                        enclosure.mDuration = Utilities.parseDuration(duration) * 1000;
                    }

                    duration = extractValue(eElement, "blip:runtime");
                    if (duration != null && duration.length() > 0) {
                        enclosure.mDuration = Utilities.parseDuration(duration) * 1000;
                    }

                    // TODO - find a better way to do this
                    // nuke image enclosures for now
                    if (enclosure.mContentType.startsWith("image/")) {
                        enclosure.mURL = "";
                    }

                    if (enclosure.mURL.length() > 0) {
                        try {
                            URL url = new URL(enclosure.mURL);

                            feedItem.mEnclosureURL = url.toExternalForm();
                            enclosure.mURL = url.toExternalForm();
                            feedItem.mEnclosure = enclosure;

                            enclosures.add(enclosure);
                        } catch (MalformedURLException exc) {
                            mLog.e("error parsing enclosure url", exc);
                        }
                    }
                }
            }

            feedItems.add(feedItem);
        }
    }

    // parse all 'channel' elements
    nl = doc.getElementsByTagName("channel");
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            // extract ttl
            Element eElement = (Element) node;
            String ttlString = extractValue(eElement, "ttl");

            if (ttlString.length() > 0) {
                try {
                    feedStatus.mTTL = Integer.parseInt(ttlString);
                } catch (NumberFormatException exc) {
                    mLog.e("error parsing ttl: " + ttlString, exc);
                }
            }

            if (feed != null) {
                String title = extractValue(eElement, "title");
                String link = extractValue(eElement, "link");
                String description = extractValue(eElement, "description");

                feed.mName = title;
                feed.mLink = link;
                feed.mDescription = description;

                Node imageNode = eElement.getElementsByTagName("image").item(0);
                if (imageNode != null && imageNode.getNodeType() == Node.ELEMENT_NODE) {
                    String imageUrl = extractValue((Element) imageNode, "url");
                    feed.mImageURL = imageUrl;
                }
            }
        }
    }
}