org.w3c.dom.NodeList

Here are the examples of the java api class org.w3c.dom.NodeList taken from open source projects.

1. SamlModel#getSAMLVersion()

Project: OWASP-WebScarab
Source File: SamlModel.java
View license
public int getSAMLVersion(ConversationID id) {
    Document document = getSAMLDocument(id);
    if (null == document) {
        return 0;
    }
    NodeList saml1ResponseNodeList = document.getElementsByTagNameNS("urn:oasis:names:tc:SAML:1.0:protocol", "Response");
    if (0 != saml1ResponseNodeList.getLength()) {
        return SAML_VERSION_1_1;
    }
    NodeList saml2AuthnRequestNodeList = document.getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:protocol", "AuthnRequest");
    if (0 != saml2AuthnRequestNodeList.getLength()) {
        return SAML_VERSION_2;
    }
    NodeList saml2ResponseNodeList = document.getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:protocol", "Response");
    if (0 != saml2ResponseNodeList.getLength()) {
        return SAML_VERSION_2;
    }
    return 0;
}

2. SamlModel#hasDestinationIndication()

Project: OWASP-WebScarab
Source File: SamlModel.java
View license
public boolean hasDestinationIndication(ConversationID id) {
    Document document = getSAMLDocument(id);
    if (null == document) {
        return false;
    }
    NodeList saml2ResponseNodeList = document.getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:protocol", "Response");
    if (0 != saml2ResponseNodeList.getLength()) {
        return hasDestinationIndicationSaml2Response((Element) saml2ResponseNodeList.item(0));
    }
    NodeList saml2AuthnRequestNodeList = document.getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:protocol", "AuthnRequest");
    if (0 != saml2AuthnRequestNodeList.getLength()) {
        return hasDestinationIndicationSaml2AuthnRequest((Element) saml2AuthnRequestNodeList.item(0));
    }
    NodeList saml1ResponseNodeList = document.getElementsByTagNameNS("urn:oasis:names:tc:SAML:1.0:protocol", "Response");
    if (0 != saml1ResponseNodeList.getLength()) {
        return hasDestinationIndicationSaml1Response((Element) saml1ResponseNodeList.item(0));
    }
    return false;
}

3. SamlTest#testEncryptedXML()

Project: OWASP-WebScarab
Source File: SamlTest.java
View license
@Test
public void testEncryptedXML() throws Exception {
    // setup
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setNamespaceAware(true);
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Document document = builder.parse(SamlTest.class.getResourceAsStream("/test-saml-response-encrypted-attribute.xml"));
    NodeList nodeList = document.getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "EncryptedAttribute");
    assertEquals(1, nodeList.getLength());
    Element encryptedAttributeElement = (Element) nodeList.item(0);
    NodeList encryptedDataNodeList = encryptedAttributeElement.getElementsByTagNameNS("http://www.w3.org/2001/04/xmlenc#", "EncryptedData");
    assertEquals(1, encryptedDataNodeList.getLength());
    Element encryptedDataElement = (Element) encryptedDataNodeList.item(0);
    Init.init();
    XMLCipher xmlCipher = XMLCipher.getInstance(XMLCipher.AES_128);
    String aes128HexStr = "2a1e3d83f475ec3c007f487c5150a5f2";
    byte[] aes128Bytes = Hex.decode(aes128HexStr);
    SecretKeySpec secretKeySpec = new SecretKeySpec(aes128Bytes, "AES");
    xmlCipher.init(XMLCipher.DECRYPT_MODE, secretKeySpec);
    xmlCipher.doFinal(document, encryptedDataElement);
    LOG.debug("decrypted attribute: " + toString(encryptedAttributeElement));
    NodeList attributeNodeList = encryptedAttributeElement.getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "Attribute");
    assertEquals(1, attributeNodeList.getLength());
}

4. XmlAgentConfigurationBuilder#getForbiddenPaths()

View license
private void getForbiddenPaths(Element parent, AgentConfigurationDefaultImpl agentConfiguration) {
    NodeList nodes = parent.getElementsByTagName(EXCLUDED_PREFIXES_TAG);
    Element forbiddenElement = getFirst(nodes);
    if (forbiddenElement == null) {
        return;
    }
    HashSet<String> excludedPrefixes = new HashSet<String>();
    NodeList addClasses = forbiddenElement.getElementsByTagName(FORBIDDEN_PREFIX_TAG);
    if (addClasses == null) {
        return;
    }
    for (int index = 0; index < addClasses.getLength(); ++index) {
        Element classElement = getClassDataElement(addClasses.item(index));
        if (classElement == null) {
            continue;
        }
        excludedPrefixes.add(classElement.getFirstChild().getTextContent());
    }
    agentConfiguration.setExcludedPrefixes(excludedPrefixes);
}

5. XformsQueueProcessor#getPatientIdentifier()

Project: buendia
Source File: XformsQueueProcessor.java
View license
private String getPatientIdentifier(Document doc) {
    NodeList elemList = doc.getDocumentElement().getElementsByTagName("patient");
    if (!(elemList != null && elemList.getLength() > 0))
        return null;
    Element patientNode = (Element) elemList.item(0);
    NodeList children = patientNode.getChildNodes();
    int len = patientNode.getChildNodes().getLength();
    for (int index = 0; index < len; index++) {
        Node child = children.item(index);
        if (child.getNodeType() != Node.ELEMENT_NODE)
            continue;
        if ("patient_identifier".equalsIgnoreCase(((Element) child).getAttribute("openmrs_table")) && "identifier".equalsIgnoreCase(((Element) child).getAttribute("openmrs_attribute")))
            return child.getTextContent();
    }
    return null;
}

6. XMLDocumentHelper#createElementMappingForNodes()

View license
/**
     * Creates the element mapping for the specified nodes and all their child
     * nodes.
     *
     * @param n1 node 1
     * @param n2 node 2
     * @param mapping the mapping to be filled
     */
private static void createElementMappingForNodes(Node n1, Node n2, Map<Node, Node> mapping) {
    mapping.put(n1, n2);
    NodeList childNodes1 = n1.getChildNodes();
    NodeList childNodes2 = n2.getChildNodes();
    int count = Math.min(childNodes1.getLength(), childNodes2.getLength());
    for (int i = 0; i < count; i++) {
        createElementMappingForNodes(childNodes1.item(i), childNodes2.item(i), mapping);
    }
}

7. XPathPropertyArrayItemGetter#get()

View license
public Object get(EventBean eventBean) throws PropertyAccessException {
    Object result = getter.get(eventBean);
    if (!(result instanceof NodeList)) {
        return null;
    }
    NodeList nodeList = (NodeList) result;
    if (nodeList.getLength() <= index) {
        return null;
    }
    return nodeList.item(index);
}

8. TestMixinXml#textExceptions()

Project: etch
Source File: TestMixinXml.java
View license
/** @throws Exception */
@org.junit.Test
public void textExceptions() throws Exception {
    // verify exceptions
    NodeList exceptionsNodeList = document.getElementsByTagName("exceptions");
    assertEquals(exceptionsNodeList.getLength(), 1);
    Node exceptionsNode = exceptionsNodeList.item(0);
    ArrayList<Node> list = new ArrayList<Node>();
    NodeList exceptionsNodeChildren = exceptionsNode.getChildNodes();
    for (int i = 0; i < exceptionsNodeChildren.getLength(); i++) {
        if (exceptionsNodeChildren.item(i).getNodeName() == "exception") {
            list.add(exceptionsNodeChildren.item(i));
        }
    }
    assertEquals(list.size(), 0);
}

9. ExecutionReportTest#shouldHandleMissingRunTimesGraceFully()

Project: fitnesse
Source File: ExecutionReportTest.java
View license
@Test
public void shouldHandleMissingRunTimesGraceFully() throws Exception {
    TestExecutionReport report = new TestExecutionReport(new FitNesseVersion("version"), "rootPath");
    Element element = mock(Element.class);
    NodeList emptyNodeList = mock(NodeList.class);
    when(element.getElementsByTagName("totalRunTimeInMillis")).thenReturn(emptyNodeList);
    when(emptyNodeList.getLength()).thenReturn(0);
    assertThat(report.getTotalRunTimeInMillisOrMinusOneIfNotPresent(element), is(-1L));
    element = mock(Element.class);
    NodeList matchingNodeList = mock(NodeList.class);
    Node elementWithText = mock(Element.class);
    when(element.getElementsByTagName("totalRunTimeInMillis")).thenReturn(matchingNodeList);
    when(matchingNodeList.getLength()).thenReturn(1);
    when(matchingNodeList.item(0)).thenReturn(elementWithText);
    when(elementWithText.getTextContent()).thenReturn("255");
    assertThat(report.getTotalRunTimeInMillisOrMinusOneIfNotPresent(element), is(255L));
}

10. SuiteExecutionReportTest#shouldHandleMissingRunTimesGraceFully()

View license
@Test
public void shouldHandleMissingRunTimesGraceFully() throws Exception {
    Element element = mock(Element.class);
    NodeList emptyNodeList = mock(NodeList.class);
    when(element.getElementsByTagName("runTimeInMillis")).thenReturn(emptyNodeList);
    when(emptyNodeList.getLength()).thenReturn(0);
    assertThat(report1.getRunTimeInMillisOrZeroIfNotPresent(element), is(0L));
    element = mock(Element.class);
    NodeList matchingNodeList = mock(NodeList.class);
    Node elementWithText = mock(Element.class);
    when(element.getElementsByTagName("runTimeInMillis")).thenReturn(matchingNodeList);
    when(matchingNodeList.getLength()).thenReturn(1);
    when(matchingNodeList.item(0)).thenReturn(elementWithText);
    when(elementWithText.getTextContent()).thenReturn("255");
    assertThat(report1.getRunTimeInMillisOrZeroIfNotPresent(element), is(255L));
}

11. DMLConfig#updateYarnMemorySettings()

Project: incubator-systemml
Source File: DMLConfig.java
View license
/**
	 * 
	 * @param amMem
	 * @param mrMem
	 */
public void updateYarnMemorySettings(String amMem, String mrMem) {
    //app master memory
    NodeList list1 = _xmlRoot.getElementsByTagName(YARN_APPMASTERMEM);
    if (list1 != null && list1.getLength() > 0) {
        Element elem = (Element) list1.item(0);
        elem.getFirstChild().setNodeValue(String.valueOf(amMem));
    }
    //mapreduce memory
    NodeList list2 = _xmlRoot.getElementsByTagName(YARN_MAPREDUCEMEM);
    if (list2 != null && list2.getLength() > 0) {
        Element elem = (Element) list2.item(0);
        elem.getFirstChild().setNodeValue(String.valueOf(mrMem));
    }
}

12. EntityChildTest#test()

Project: openjdk
Source File: EntityChildTest.java
View license
@Test
public void test() throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    DocumentBuilder docBuilder = dbf.newDocumentBuilder();
    Document document = docBuilder.parse(new File(XML_DIR + "entitychild.xml"));
    Element root = document.getDocumentElement();
    NodeList n = root.getElementsByTagName("table");
    NodeList nl = n.item(0).getChildNodes();
    assertEquals(n.getLength(), 1);
    assertEquals(nl.getLength(), 3);
}

13. NodeListTest#lastItemTest()

Project: openjdk
Source File: NodeListTest.java
View license
@Test(dataProvider = "xml")
public void lastItemTest(String xmlFileName, String nodeName) throws Exception {
    Document document = createDOM(xmlFileName);
    NodeList nl = document.getElementsByTagName(nodeName);
    int n = nl.getLength();
    Element elem1 = (Element) nl.item(n - 1);
    nl.item(n);
    Element elem3 = (Element) nl.item(n - 1);
    assertEquals(elem3, elem1);
}

14. JaxpIssue43Test#getSchemaSources()

Project: openjdk
Source File: JaxpIssue43Test.java
View license
private Source[] getSchemaSources() throws Exception {
    List<Source> list = new ArrayList<Source>();
    String file = getClass().getResource("hello_literal.wsdl").getFile();
    Source source = new StreamSource(new FileInputStream(file), file);
    Transformer trans = TransformerFactory.newInstance().newTransformer();
    DOMResult result = new DOMResult();
    trans.transform(source, result);
    // Look for <xsd:schema> element in wsdl
    Element e = ((Document) result.getNode()).getDocumentElement();
    NodeList typesList = e.getElementsByTagNameNS("http://schemas.xmlsoap.org/wsdl/", "types");
    NodeList schemaList = ((Element) typesList.item(0)).getElementsByTagNameNS("http://www.w3.org/2001/XMLSchema", "schema");
    Element elem = (Element) schemaList.item(0);
    list.add(new DOMSource(elem, file + "#schema0"));
    return list.toArray(new Source[list.size()]);
}

15. SamlModel#hasDestinationIndicationSaml1Response()

Project: OWASP-WebScarab
Source File: SamlModel.java
View license
private boolean hasDestinationIndicationSaml1Response(Element responseElement) {
    if (null != responseElement.getAttributeNode("Recipient")) {
        return true;
    }
    NodeList assertionNodeList = responseElement.getElementsByTagNameNS("urn:oasis:names:tc:SAML:1.0:assertion", "Assertion");
    if (0 == assertionNodeList.getLength()) {
        return false;
    }
    Element assertionElement = (Element) assertionNodeList.item(0);
    NodeList audienceNodeList = assertionElement.getElementsByTagNameNS("urn:oasis:names:tc:SAML:1.0:assertion", "Audience");
    if (0 != audienceNodeList.getLength()) {
        return true;
    }
    return false;
}

16. XMLModelsParser#getModels()

Project: spaceracer3d
Source File: XMLModelsParser.java
View license
public ArrayList<String> getModels(final String objectName) throws Exception {
    if (filename == null) {
        throw new Exception("No XML file to parse is specified!");
    }
    final ArrayList<String> models = new ArrayList<String>();
    final String expression = "/models/" + objectName;
    final InputSource inputSource = new InputSource(filename);
    final NodeList nodes = (NodeList) xpath.evaluate(expression, inputSource, XPathConstants.NODESET);
    NodeList modelNodes;
    String model = null;
    for (int i = 0; i < nodes.getLength(); i++) {
        modelNodes = nodes.item(i).getChildNodes();
        for (int j = 1; j < modelNodes.getLength(); j += 2) {
            model = modelNodes.item(j).getTextContent();
            if (model != null && model.length() > 0) {
                models.add(model);
            }
        }
    }
    return models;
}

17. XMLUtilTest#testGetTextContext_5()

Project: activemq-artemis
Source File: XMLUtilTest.java
View license
@Test
public void testGetTextContext_5() throws Exception {
    String document = "<blah someattribute=\"somevalue\"><a><b/></a></blah>";
    Element e = XMLUtil.stringToElement(document);
    String s = XMLUtil.getTextContent(e);
    Element subelement = XMLUtil.stringToElement(s);
    Assert.assertEquals("a", subelement.getNodeName());
    NodeList nl = subelement.getChildNodes();
    // try to find <b>
    boolean found = false;
    for (int i = 0; i < nl.getLength(); i++) {
        Node n = nl.item(i);
        if ("b".equals(n.getNodeName())) {
            found = true;
        }
    }
    Assert.assertTrue(found);
}

18. FileJMSConfiguration#parseQueueConfiguration()

View license
/**
    * Parse the Queue Configuration node as a QueueConfiguration object
    *
    * @param node
    * @return jms queue configuration
    * @throws Exception
    */
public static JMSQueueConfiguration parseQueueConfiguration(final Node node) throws Exception {
    Element e = (Element) node;
    NamedNodeMap atts = node.getAttributes();
    String queueName = atts.getNamedItem(NAME_ATTR).getNodeValue();
    String selectorString = null;
    boolean durable = XMLConfigurationUtil.getBoolean(e, "durable", DEFAULT_QUEUE_DURABILITY);
    NodeList children = node.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node child = children.item(i);
        if (QUEUE_SELECTOR_NODE_NAME.equals(children.item(i).getNodeName())) {
            Node selectorNode = children.item(i);
            Node attNode = selectorNode.getAttributes().getNamedItem("string");
            selectorString = attNode.getNodeValue();
        }
    }
    return newQueue(queueName, selectorString, durable);
}

19. FileConfigurationParser#parseSecurity()

View license
/**
    * @param e
    * @param config
    */
private void parseSecurity(final Element e, final Configuration config) {
    NodeList elements = e.getElementsByTagName("security-settings");
    if (elements.getLength() != 0) {
        Element node = (Element) elements.item(0);
        NodeList list = node.getElementsByTagName(SECURITY_ELEMENT_NAME);
        for (int i = 0; i < list.getLength(); i++) {
            Pair<String, Set<Role>> securityItem = parseSecurityRoles(list.item(i));
            config.putSecurityRoles(securityItem.getA(), securityItem.getB());
        }
        list = node.getElementsByTagName(SECURITY_PLUGIN_ELEMENT_NAME);
        for (int i = 0; i < list.getLength(); i++) {
            Pair<SecuritySettingPlugin, Map<String, String>> securityItem = parseSecuritySettingPlugins(list.item(i));
            config.addSecuritySettingPlugin(securityItem.getA().init(securityItem.getB()));
        }
    }
}

20. FileConfigurationParser#parseQueues()

View license
/**
    * @param e
    * @param config
    */
private void parseQueues(final Element e, final Configuration config) {
    NodeList elements = e.getElementsByTagName("queues");
    if (elements.getLength() != 0) {
        Element node = (Element) elements.item(0);
        NodeList list = node.getElementsByTagName("queue");
        for (int i = 0; i < list.getLength(); i++) {
            CoreQueueConfiguration queueConfig = parseQueueConfiguration(list.item(i));
            config.getQueueConfigurations().add(queueConfig);
        }
    }
}

21. FileConfigurationParser#parseAddressSettings()

View license
/**
    * @param e
    * @param config
    */
private void parseAddressSettings(final Element e, final Configuration config) {
    NodeList elements = e.getElementsByTagName("address-settings");
    if (elements.getLength() != 0) {
        Element node = (Element) elements.item(0);
        NodeList list = node.getElementsByTagName("address-setting");
        for (int i = 0; i < list.getLength(); i++) {
            Pair<String, AddressSettings> addressSettings = parseAddressSettings(list.item(i));
            config.getAddressesSettings().put(addressSettings.getA(), addressSettings.getB());
        }
    }
}

22. FileConfigurationParser#parseSecuritySettingPlugins()

View license
private Pair<SecuritySettingPlugin, Map<String, String>> parseSecuritySettingPlugins(Node item) {
    final String clazz = item.getAttributes().getNamedItem("class-name").getNodeValue();
    final Map<String, String> settings = new HashMap<>();
    NodeList children = item.getChildNodes();
    for (int j = 0; j < children.getLength(); j++) {
        Node child = children.item(j);
        final String nodeName = child.getNodeName();
        if (SETTING_ELEMENT_NAME.equalsIgnoreCase(nodeName)) {
            final String settingName = getAttributeValue(child, NAME_ATTR_NAME);
            final String settingValue = getAttributeValue(child, VALUE_ATTR_NAME);
            settings.put(settingName, settingValue);
        }
    }
    SecuritySettingPlugin securitySettingPlugin = AccessController.doPrivileged(new PrivilegedAction<SecuritySettingPlugin>() {

        @Override
        public SecuritySettingPlugin run() {
            return (SecuritySettingPlugin) ClassloadingUtil.newInstanceFromClassLoader(clazz);
        }
    });
    return new Pair<>(securitySettingPlugin, settings);
}

23. FileConfigurationParser#parseResourceLimitSettings()

View license
/**
    * @param node
    * @return
    */
protected ResourceLimitSettings parseResourceLimitSettings(final Node node) {
    ResourceLimitSettings resourceLimitSettings = new ResourceLimitSettings();
    resourceLimitSettings.setMatch(SimpleString.toSimpleString(getAttributeValue(node, "match")));
    NodeList children = node.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        final Node child = children.item(i);
        final String name = child.getNodeName();
        if (MAX_CONNECTIONS_NODE_NAME.equalsIgnoreCase(name)) {
            resourceLimitSettings.setMaxConnections(XMLUtil.parseInt(child));
        } else if (MAX_QUEUES_NODE_NAME.equalsIgnoreCase(name)) {
            resourceLimitSettings.setMaxQueues(XMLUtil.parseInt(child));
        }
    }
    return resourceLimitSettings;
}

24. FileConfigurationParser#parseQueueConfiguration()

View license
protected CoreQueueConfiguration parseQueueConfiguration(final Node node) {
    String name = getAttributeValue(node, "name");
    String address = null;
    String filterString = null;
    boolean durable = true;
    NodeList children = node.getChildNodes();
    for (int j = 0; j < children.getLength(); j++) {
        Node child = children.item(j);
        if (child.getNodeName().equals("address")) {
            address = getTrimmedTextContent(child);
        } else if (child.getNodeName().equals("filter")) {
            filterString = getAttributeValue(child, "string");
        } else if (child.getNodeName().equals("durable")) {
            durable = XMLUtil.parseBoolean(child);
        }
    }
    return new CoreQueueConfiguration().setAddress(address).setName(name).setFilterString(filterString).setDurable(durable);
}

25. XMLConfigurationUtil#getDouble()

View license
public static final Double getDouble(final Element e, final String name, final double def, final Validators.Validator validator) {
    NodeList nl = e.getElementsByTagName(name);
    if (nl.getLength() > 0) {
        double val = XMLUtil.parseDouble(nl.item(0));
        validator.validate(name, val);
        return val;
    } else {
        validator.validate(name, def);
        return def;
    }
}

26. XMLConfigurationUtil#getString()

View license
public static final String getString(final Element e, final String name, final String def, final Validators.Validator validator) {
    NodeList nl = e.getElementsByTagName(name);
    if (nl.getLength() > 0) {
        String val = nl.item(0).getTextContent().trim();
        validator.validate(name, val);
        return val;
    } else {
        validator.validate(name, def);
        return def;
    }
}

27. XMLConfigurationUtil#getLong()

View license
public static final Long getLong(final Element e, final String name, final long def, final Validators.Validator validator) {
    NodeList nl = e.getElementsByTagName(name);
    if (nl.getLength() > 0) {
        long val = XMLUtil.parseLong(nl.item(0));
        validator.validate(name, val);
        return val;
    } else {
        validator.validate(name, def);
        return def;
    }
}

28. XMLConfigurationUtil#getInteger()

View license
public static final Integer getInteger(final Element e, final String name, final int def, final Validators.Validator validator) {
    NodeList nl = e.getElementsByTagName(name);
    if (nl.getLength() > 0) {
        int val = XMLUtil.parseInt(nl.item(0));
        validator.validate(name, val);
        return val;
    } else {
        validator.validate(name, def);
        return def;
    }
}

29. ConfigurationReader#loadConfigurations()

Project: airavata
Source File: ConfigurationReader.java
View license
private void loadConfigurations() throws ParserConfigurationException, IOException, SAXException {
    InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("credential-store/client.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(inputStream);
    doc.getDocumentElement().normalize();
    NodeList nodeList = doc.getElementsByTagName("credential-store");
    readElementValue(nodeList);
}

30. GFacUtils#getElementList()

Project: airavata
Source File: GFacUtils.java
View license
public static List<Element> getElementList(Document doc, String expression) throws XPathExpressionException {
    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath = xPathFactory.newXPath();
    XPathExpression expr = xPath.compile(expression);
    NodeList nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    List<Element> elementList = new ArrayList<Element>();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node item = nodeList.item(i);
        if (item instanceof Element) {
            elementList.add((Element) item);
        }
    }
    return elementList;
}

31. JDBCUserStoreTest#testAuthenticate()

Project: airavata
Source File: JDBCUserStoreTest.java
View license
@Test
public void testAuthenticate() throws Exception {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(this.getClass().getClassLoader().getResourceAsStream("jdbc-authenticator.xml"));
    doc.getDocumentElement().normalize();
    NodeList configurations = doc.getElementsByTagName("specificConfigurations");
    UserStore userStore = new JDBCUserStore();
    userStore.configure(configurations.item(0));
    Assert.assertTrue(userStore.authenticate("amilaj", "secret"));
    Assert.assertFalse(userStore.authenticate("amilaj", "1secret"));
    Assert.assertFalse(userStore.authenticate("lahiru", "1234"));
}

32. LDAPUserStoreTest#testConfigure()

Project: airavata
Source File: LDAPUserStoreTest.java
View license
public void testConfigure() throws Exception {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(this.getClass().getClassLoader().getResourceAsStream("ldap-authenticator.xml"));
    doc.getDocumentElement().normalize();
    NodeList configurations = doc.getElementsByTagName("specificConfigurations");
    UserStore userStore = new LDAPUserStore();
    userStore.configure(configurations.item(0));
    assertTrue(userStore.authenticate("amilaj", "secret"));
}

33. Configuration#readWhiteListFromXml()

Project: AndResGuard
Source File: Configuration.java
View license
private void readWhiteListFromXml(Node node) throws IOException {
    NodeList childNodes = node.getChildNodes();
    if (childNodes.getLength() > 0) {
        for (int j = 0, n = childNodes.getLength(); j < n; j++) {
            Node child = childNodes.item(j);
            if (child.getNodeType() == Node.ELEMENT_NODE) {
                Element check = (Element) child;
                String vaule = check.getAttribute(ATTR_VALUE);
                addWhiteList(vaule);
            }
        }
    }
}

34. Configuration#readCompressFromXml()

Project: AndResGuard
Source File: Configuration.java
View license
private void readCompressFromXml(Node node) throws IOException {
    NodeList childNodes = node.getChildNodes();
    if (childNodes.getLength() > 0) {
        for (int j = 0, n = childNodes.getLength(); j < n; j++) {
            Node child = childNodes.item(j);
            if (child.getNodeType() == Node.ELEMENT_NODE) {
                Element check = (Element) child;
                String value = check.getAttribute(ATTR_VALUE);
                addToCompressPatterns(value);
            }
        }
    }
}

35. Configuration#loadMappingFilesFromXml()

Project: AndResGuard
Source File: Configuration.java
View license
private void loadMappingFilesFromXml(Node node) throws IOException {
    if (mOldMappingFile != null) {
        System.err.println("Mapping file already load from command line, ignore this config");
        return;
    }
    NodeList childNodes = node.getChildNodes();
    if (childNodes.getLength() > 0) {
        for (int j = 0, n = childNodes.getLength(); j < n; j++) {
            Node child = childNodes.item(j);
            if (child.getNodeType() == Node.ELEMENT_NODE) {
                Element check = (Element) child;
                String filePath = check.getAttribute(ATTR_VALUE);
                if (filePath.length() == 0) {
                    throw new IOException(String.format("Invalid config file: Missing required attribute %s\n", ATTR_VALUE));
                }
                readOldMapping(filePath);
            }
        }
    }
}

36. XmlHelper#getOrCreateElement()

Project: android-maven-plugin
Source File: XmlHelper.java
View license
public static Element getOrCreateElement(Document doc, Element manifestElement, String elementName) {
    NodeList nodeList = manifestElement.getElementsByTagName(elementName);
    Element element = null;
    if (nodeList.getLength() == 0) {
        element = doc.createElement(elementName);
        manifestElement.appendChild(element);
    } else {
        element = (Element) nodeList.item(0);
    }
    return element;
}

37. MissionParser#findSingleChildElementByTag()

View license
/**
     * Finds the first occurrence of a child Element of a given tag within a parent's tree.
     * @param parent An Element with child Elements
     * @param tag The Element to find
     * @return The first occurrence of an Element of type tag within the parent's child tree.
     */
private static Element findSingleChildElementByTag(Element parent, String tag) throws MissionParseException {
    Node node = null;
    NodeList nodes = parent.getElementsByTagName(tag);
    for (int i = 0; i < nodes.getLength(); i++) {
        node = nodes.item(i);
        if (isElementNode(node)) {
            break;
        }
        node = null;
    }
    // 'next_moment' attribute signifies that the moment is the last moment in the mission.
    if (!tag.equals(ELEMENT_NEXT_MOMENT) && node == null) {
        throw new MissionParseException(tag + " could not be found.");
    }
    return (Element) node;
}

38. MissionParser#getMissionName()

View license
/**
     * Determines the name of a mission.
     * @param missionStream InputStream to read from.
     * @return A string of the name of the mission. Empty string if a name is not specified.
     * @throws MissionParseException
     */
public static String getMissionName(InputStream missionStream) throws MissionParseException {
    Document doc = getDocumentFromInputStream(missionStream);
    doc.getDocumentElement().normalize();
    NodeList missionNodes = doc.getElementsByTagName(ELEMENT_MISSION);
    String missionName;
    for (int i = 0; i < missionNodes.getLength(); i++) {
        Node missionNode = missionNodes.item(i);
        if (isElementNode(missionNode)) {
            // Gives an empty string if the attribute is missing.
            missionName = ((Element) missionNode).getAttribute(MISSION_ATTRIBUTE_NAME);
            if (missionName.equals("")) {
                throw new MissionParseException("Mission name missing.");
            }
            Utils.logDebug(TAG, "Mission name is " + missionName);
            return missionName;
        }
    }
    // No Element Node for Mission.
    throw new MissionParseException("Mission element could not be found.");
}

39. MissionParser#parseMomentFictionalProgress()

View license
/**
     * Determines the Fictional Progress strings associated with a moment.
     * @param momentElement The moment to parse.
     * @return A list of Fictional Progress strings.
     */
private static ArrayList<String> parseMomentFictionalProgress(Element momentElement) throws MissionParseException {
    ArrayList<String> progress = new ArrayList<>();
    NodeList fictionalProgressNodes = momentElement.getElementsByTagName(ELEMENT_FICTIONAL_PROGRESS);
    for (int i = 0; i < fictionalProgressNodes.getLength(); i++) {
        Node node = fictionalProgressNodes.item(i);
        Element parent = (Element) node.getParentNode();
        if (isElementNode(node) && parent.getTagName().equals(ELEMENT_MOMENT)) {
            String progressString = parseFictionalProgressElement((Element) node);
            progress.add(progressString);
        }
    }
    return progress;
}

40. MissionParser#parseNestedFictionalProgress()

View license
private static ArrayList<String> parseNestedFictionalProgress(Element parent) throws MissionParseException {
    ArrayList<String> progressStrings = new ArrayList<>();
    NodeList nodeList = parent.getElementsByTagName(ELEMENT_FICTIONAL_PROGRESS);
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        if (isElementNode(node)) {
            String progressString = parseFictionalProgressElement((Element) node);
            progressStrings.add(progressString);
        }
    }
    return progressStrings;
}

41. IvyClasspathContainerSerializer#readCpEntries()

View license
private IClasspathEntry[] readCpEntries(Node cpEntries) throws IOException {
    List /* <IClasspathEntry> */
    entries = new ArrayList();
    NodeList children = cpEntries.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node item = children.item(i);
        if (item.getNodeName().equals(CPENTRY)) {
            IClasspathEntry cpEntry = readCpEntry(item);
            if (cpEntry != null) {
                entries.add(cpEntry);
            }
        }
    }
    return (IClasspathEntry[]) entries.toArray(new IClasspathEntry[entries.size()]);
}

42. IvyClasspathContainerSerializer#readAccessRules()

View license
private IAccessRule[] readAccessRules(Node accessRulesNode) throws IOException {
    List /* <IAccessRule> */
    rules = new ArrayList();
    NodeList children = accessRulesNode.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node item = children.item(i);
        if (item.getNodeName().equals(RULE)) {
            IAccessRule rule = readAccessRule(item);
            if (rule != null) {
                rules.add(rule);
            }
        }
    }
    return (IAccessRule[]) rules.toArray(new IAccessRule[rules.size()]);
}

43. IvyClasspathContainerSerializer#readCpAttr()

View license
private IClasspathAttribute[] readCpAttr(Node cpAttrsNode) throws IOException {
    List /* <IClasspathAttribute> */
    attrs = new ArrayList();
    NodeList children = cpAttrsNode.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node item = children.item(i);
        if (item.getNodeName().equals(ATTR)) {
            IClasspathAttribute attr = readAttr(item);
            if (attr != null) {
                attrs.add(attr);
            }
        }
    }
    return (IClasspathAttribute[]) attrs.toArray(new IClasspathAttribute[attrs.size()]);
}

44. PluginManifestParser#parseRequires()

Project: anthelion
Source File: PluginManifestParser.java
View license
/**
   * @param pRootElement
   * @param pDescriptor
   * @throws MalformedURLException
   */
private void parseRequires(Element pRootElement, PluginDescriptor pDescriptor) throws MalformedURLException {
    NodeList nodelist = pRootElement.getElementsByTagName("requires");
    if (nodelist.getLength() > 0) {
        Element requires = (Element) nodelist.item(0);
        NodeList imports = requires.getElementsByTagName("import");
        for (int i = 0; i < imports.getLength(); i++) {
            Element anImport = (Element) imports.item(i);
            String plugin = anImport.getAttribute("plugin");
            if (plugin != null) {
                pDescriptor.addDependency(plugin);
            }
        }
    }
}

45. PluginManifestParser#parseLibraries()

Project: anthelion
Source File: PluginManifestParser.java
View license
/**
   * @param pRootElement
   * @param pDescriptor
   * @throws MalformedURLException
   */
private void parseLibraries(Element pRootElement, PluginDescriptor pDescriptor) throws MalformedURLException {
    NodeList nodelist = pRootElement.getElementsByTagName("runtime");
    if (nodelist.getLength() > 0) {
        Element runtime = (Element) nodelist.item(0);
        NodeList libraries = runtime.getElementsByTagName("library");
        for (int i = 0; i < libraries.getLength(); i++) {
            Element library = (Element) libraries.item(i);
            String libName = library.getAttribute(ATTR_NAME);
            NodeList list = library.getElementsByTagName("export");
            Element exportElement = (Element) list.item(0);
            if (exportElement != null)
                pDescriptor.addExportedLibRelative(libName);
            else
                pDescriptor.addNotExportedLibRelative(libName);
        }
    }
}

46. PluginManifestParser#parseExtensionPoints()

Project: anthelion
Source File: PluginManifestParser.java
View license
/**
   * @param rootElement
   * @param pluginDescriptor
   */
private void parseExtensionPoints(Element pRootElement, PluginDescriptor pPluginDescriptor) {
    NodeList list = pRootElement.getElementsByTagName("extension-point");
    if (list != null) {
        for (int i = 0; i < list.getLength(); i++) {
            Element oneExtensionPoint = (Element) list.item(i);
            String id = oneExtensionPoint.getAttribute(ATTR_ID);
            String name = oneExtensionPoint.getAttribute(ATTR_NAME);
            String schema = oneExtensionPoint.getAttribute("schema");
            ExtensionPoint extensionPoint = new ExtensionPoint(id, name, schema);
            pPluginDescriptor.addExtensionPoint(extensionPoint);
        }
    }
}

47. Subcollection#initialize()

Project: anthelion
Source File: Subcollection.java
View license
/**
   * Initialize Subcollection from dom element
   * 
   * @param collection
   */
public void initialize(Element collection) {
    this.id = DOMUtil.getChildText(collection.getElementsByTagName(TAG_ID).item(0)).trim();
    this.name = DOMUtil.getChildText(collection.getElementsByTagName(TAG_NAME).item(0)).trim();
    this.wlString = DOMUtil.getChildText(collection.getElementsByTagName(TAG_WHITELIST).item(0)).trim();
    parseList(this.whiteList, wlString);
    // Check if there's a blacklist we need to parse
    NodeList nodeList = collection.getElementsByTagName(TAG_BLACKLIST);
    if (nodeList.getLength() > 0) {
        this.blString = DOMUtil.getChildText(nodeList.item(0)).trim();
        parseList(this.blackList, blString);
    }
    // Check if there's a key element or set default name
    nodeList = collection.getElementsByTagName(TAG_KEY);
    if (nodeList.getLength() == 1) {
        this.key = DOMUtil.getChildText(nodeList.item(0)).trim();
    }
}

48. CmNamespaceHandler#parseDefaultProperties()

View license
private Metadata parseDefaultProperties(ParserContext context, MutableBeanMetadata enclosingComponent, Element element) {
    MutableMapMetadata props = context.createMetadata(MutableMapMetadata.class);
    NodeList nl = element.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (node instanceof Element) {
            Element e = (Element) node;
            if (isCmNamespace(e.getNamespaceURI())) {
                if (nodeNameEquals(e, PROPERTY_ELEMENT)) {
                    BeanProperty prop = context.parseElement(BeanProperty.class, enclosingComponent, e);
                    props.addEntry(createValue(context, prop.getName(), String.class.getName()), prop.getValue());
                }
            }
        }
    }
    return props;
}

49. CmNamespaceHandler#parseInterfaceNames()

View license
public List<String> parseInterfaceNames(Element element) {
    List<String> interfaceNames = new ArrayList<String>();
    NodeList nl = element.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (node instanceof Element) {
            Element e = (Element) node;
            if (nodeNameEquals(e, VALUE_ELEMENT)) {
                String v = getTextValue(e).trim();
                if (interfaceNames.contains(v)) {
                    throw new ComponentDefinitionException("The element " + INTERFACES_ELEMENT + " should not contain the same interface twice");
                }
                interfaceNames.add(getTextValue(e));
            } else {
                throw new ComponentDefinitionException("Unsupported element " + e.getNodeName() + " inside an " + INTERFACES_ELEMENT + " element");
            }
        }
    }
    return interfaceNames;
}

50. ExtNamespaceHandler#parseDefaultProperties()

View license
private Metadata parseDefaultProperties(ParserContext context, MutableBeanMetadata enclosingComponent, Element element) {
    MutableMapMetadata props = context.createMetadata(MutableMapMetadata.class);
    NodeList nl = element.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (node instanceof Element) {
            Element e = (Element) node;
            if (isExtNamespace(e.getNamespaceURI())) {
                if (nodeNameEquals(e, PROPERTY_ELEMENT)) {
                    BeanProperty prop = context.parseElement(BeanProperty.class, enclosingComponent, e);
                    props.addEntry(createValue(context, prop.getName(), String.class.getName()), prop.getValue());
                }
            }
        }
    }
    return props;
}

51. GeneratorTest#testGenerateTransactional()

Project: apache-aries
Source File: GeneratorTest.java
View license
@Test
public void testGenerateTransactional() throws Exception {
    Node bean1 = getBeanById("myBean1");
    NodeList txs = (NodeList) xpath.evaluate("transaction", bean1, XPathConstants.NODESET);
    Set<TransactionalDef> defs = new HashSet<TransactionalDef>();
    for (int i = 0; i < txs.getLength(); ++i) {
        Node tx = txs.item(i);
        defs.add(new TransactionalDef(xpath.evaluate("@method", tx), xpath.evaluate("@value", tx)));
    }
    Set<TransactionalDef> expectedDefs = Sets.newHashSet(new TransactionalDef("*", "RequiresNew"), new TransactionalDef("txNotSupported", "NotSupported"), new TransactionalDef("txMandatory", "Mandatory"), new TransactionalDef("txNever", "Never"), new TransactionalDef("txRequired", "Required"), new TransactionalDef("txOverridenWithRequiresNew", "RequiresNew"), new TransactionalDef("txSupports", "Supports"));
    assertEquals(expectedDefs, defs);
}

52. GeneratorTest#testGenerateServiceWith2Interfaces()

Project: apache-aries
Source File: GeneratorTest.java
View license
@Test
public void testGenerateServiceWith2Interfaces() throws Exception {
    Node serviceABImpl = getServiceByRef("serviceABImpl");
    assertEquals("", xpath.evaluate("@interface", serviceABImpl));
    assertEquals("", xpath.evaluate("@auto-export", serviceABImpl));
    NodeList interfaceValues = (NodeList) xpath.evaluate("interfaces/value", serviceABImpl, XPathConstants.NODESET);
    Set<String> interfaceNames = new HashSet<String>();
    for (int i = 0; i < interfaceValues.getLength(); ++i) {
        Node interfaceValue = interfaceValues.item(i);
        interfaceNames.add(interfaceValue.getTextContent());
    }
    assertEquals(Sets.newHashSet(ServiceA.class.getName(), ServiceB.class.getName()), interfaceNames);
}

53. Parser#parseCollection()

Project: apache-aries
Source File: Parser.java
View license
private CollectionMetadata parseCollection(Class collectionType, Element element, ComponentMetadata enclosingComponent) {
    // Parse attributes
    String valueType = element.hasAttribute(VALUE_TYPE_ATTRIBUTE) ? element.getAttribute(VALUE_TYPE_ATTRIBUTE) : null;
    // Parse elements
    List<Metadata> list = new ArrayList<Metadata>();
    NodeList nl = element.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (node instanceof Element) {
            Metadata val = parseValueGroup((Element) node, enclosingComponent, null, true);
            list.add(val);
        }
    }
    return new CollectionMetadataImpl(collectionType, valueType, list);
}

54. Parser#parseProps()

Project: apache-aries
Source File: Parser.java
View license
public PropsMetadata parseProps(Element element) {
    // Parse elements
    List<MapEntry> entries = new ArrayList<MapEntry>();
    NodeList nl = element.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (node instanceof Element) {
            Element e = (Element) node;
            if (isBlueprintNamespace(e.getNamespaceURI()) && nodeNameEquals(e, PROP_ELEMENT)) {
                entries.add(parseProperty(e));
            }
        }
    }
    return new PropsMetadataImpl(entries);
}

55. Parser#parseMap()

Project: apache-aries
Source File: Parser.java
View license
public MapMetadata parseMap(Element element, ComponentMetadata enclosingComponent) {
    // Parse attributes
    String keyType = element.hasAttribute(KEY_TYPE_ATTRIBUTE) ? element.getAttribute(KEY_TYPE_ATTRIBUTE) : null;
    String valueType = element.hasAttribute(VALUE_TYPE_ATTRIBUTE) ? element.getAttribute(VALUE_TYPE_ATTRIBUTE) : null;
    // Parse elements
    List<MapEntry> entries = new ArrayList<MapEntry>();
    NodeList nl = element.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (node instanceof Element) {
            Element e = (Element) node;
            if (nodeNameEquals(e, ENTRY_ELEMENT)) {
                entries.add(parseMapEntry(e, enclosingComponent, null, null));
            }
        }
    }
    return new MapMetadataImpl(keyType, valueType, entries);
}

56. Parser#parseMapKeyEntry()

Project: apache-aries
Source File: Parser.java
View license
private NonNullMetadata parseMapKeyEntry(Element element, ComponentMetadata enclosingComponent, String keyType) {
    NonNullMetadata keyValue = null;
    NodeList nl = element.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (node instanceof Element) {
            Element e = (Element) node;
            if (keyValue != null) {
            // TODO: throw an exception
            }
            keyValue = (NonNullMetadata) parseValueGroup(e, enclosingComponent, keyType, false);
            break;
        }
    }
    if (keyValue == null) {
    // TODO: throw an exception
    }
    return keyValue;
}

57. Parser#parseInterfaceNames()

Project: apache-aries
Source File: Parser.java
View license
public List<String> parseInterfaceNames(Element element) {
    List<String> interfaceNames = new ArrayList<String>();
    NodeList nl = element.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (node instanceof Element) {
            Element e = (Element) node;
            if (nodeNameEquals(e, VALUE_ELEMENT)) {
                String v = getTextValue(e).trim();
                if (interfaceNames.contains(v)) {
                    throw new ComponentDefinitionException("The element " + INTERFACES_ELEMENT + " should not contain the same interface twice");
                }
                interfaceNames.add(getTextValue(e));
            } else {
                throw new ComponentDefinitionException("Unsupported element " + e.getNodeName() + " inside an " + INTERFACES_ELEMENT + " element");
            }
        }
    }
    return interfaceNames;
}

58. Parser#handleCustomElements()

Project: apache-aries
Source File: Parser.java
View license
private ComponentMetadata handleCustomElements(Element element, ComponentMetadata enclosingComponent) {
    NodeList nl = element.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (node instanceof Element) {
            if (!isBlueprintNamespace(node.getNamespaceURI())) {
                enclosingComponent = decorateCustomNode(node, enclosingComponent);
            }
        }
    }
    return enclosingComponent;
}

59. SpringOsgiNamespaceHandler#getTextValue()

View license
public static String getTextValue(Element valueEle) {
    Assert.notNull(valueEle, "Element must not be null");
    StringBuilder sb = new StringBuilder();
    NodeList nl = valueEle.getChildNodes();
    for (int i = 0, l = nl.getLength(); i < l; ++i) {
        Node item = nl.item(i);
        if (item instanceof CharacterData && !(item instanceof Comment) || item instanceof EntityReference) {
            sb.append(item.getNodeValue());
        }
    }
    return sb.toString();
}

60. StramWebServicesTest#verifyAMInfoXML()

Project: apex-core
Source File: StramWebServicesTest.java
View license
void verifyAMInfoXML(String xml, TestAppContext ctx) throws JSONException, Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xml));
    Document dom = db.parse(is);
    NodeList nodes = dom.getElementsByTagName(StramWebServices.PATH_INFO);
    assertEquals("incorrect number of elements", 1, nodes.getLength());
    for (int i = 0; i < nodes.getLength(); i++) {
        Element element = (Element) nodes.item(i);
        verifyAMInfoGeneric(ctx, getXmlString(element, "id"), getXmlString(element, "user"), getXmlString(element, "name"), getXmlLong(element, "startTime"), getXmlLong(element, "elapsedTime"));
    }
}

61. StramWebServicesTest#getXmlString()

Project: apex-core
Source File: StramWebServicesTest.java
View license
public static String getXmlString(Element element, String name) {
    NodeList id = element.getElementsByTagName(name);
    Element line = (Element) id.item(0);
    if (line == null) {
        return null;
    }
    Node first = line.getFirstChild();
    // handle empty <key></key>
    if (first == null) {
        return "";
    }
    String val = first.getNodeValue();
    if (val == null) {
        return "";
    }
    return val;
}

62. AbstractXmlKeyValueCartesianProduct#isTextContainerNode()

View license
private boolean isTextContainerNode(Node n) {
    boolean container = false;
    NodeList childNodes = n.getChildNodes();
    if (childNodes.getLength() == 1) {
        Node firstChild = childNodes.item(0);
        if (firstChild.getNodeType() == Node.TEXT_NODE) {
            container = true;
        }
    }
    return container;
}

63. AndroidManifest#getAndroidComponent()

Project: APKParser
Source File: AndroidManifest.java
View license
private static AndroidComponent getAndroidComponent(Node node, int type) {
    AndroidComponent.Builder builder = AndroidComponent.newAndroidComponent(type);
    NamedNodeMap attributes = node.getAttributes();
    builder.name(XmlUtils.getAttribute(attributes, "android:name"));
    builder.exported(XmlUtils.getBoolAttribute(attributes, "android:exported", false));
    builder.process(XmlUtils.getAttribute(attributes, "android:process"));
    NodeList children = node.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node child = children.item(i);
        String childName = child.getNodeName();
        if (childName.equals("intent-filter")) {
            IntentFilter intentFilter = getIntentFilter(child);
            builder.addIntentFilter(intentFilter);
        }
    }
    return builder.build();
}

64. AndroidManifest#getIntentFilter()

Project: APKParser
Source File: AndroidManifest.java
View license
private static IntentFilter getIntentFilter(Node intentNode) {
    NodeList intentChildren = intentNode.getChildNodes();
    IntentFilter intentFilter = new IntentFilter();
    for (int j = 0; j < intentChildren.getLength(); j++) {
        Node intentChild = intentChildren.item(j);
        String intentChildName = intentChild.getNodeName();
        NamedNodeMap intentChildAttributes = intentChild.getAttributes();
        if (intentChildName.equals("action")) {
            intentFilter.actions.add(XmlUtils.getAttribute(intentChildAttributes, "android:name"));
        } else if (intentChildName.equals("category")) {
            intentFilter.categories.add(XmlUtils.getAttribute(intentChildAttributes, "android:name"));
        } else if (intentChildName.equals("data")) {
            String scheme = XmlUtils.getAttribute(intentChildAttributes, "android:scheme");
            String host = XmlUtils.getAttribute(intentChildAttributes, "android:host");
            String pathPrefix = XmlUtils.getAttribute(intentChildAttributes, "android:pathPrefix");
            String mimeType = XmlUtils.getAttribute(intentChildAttributes, "android:mimeType");
            String type = XmlUtils.getAttribute(intentChildAttributes, "android:type");
            intentFilter.dataList.add(new IntentFilter.IntentData(scheme, mimeType, host, pathPrefix, type));
        }
    }
    return intentFilter;
}

65. XmlAgentConfigurationBuilder#getTopTag()

View license
public Element getTopTag(File configurationFile) throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder;
    dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(configurationFile);
    doc.getDocumentElement().normalize();
    NodeList topTags = doc.getElementsByTagName(MAIN_TAG);
    if (topTags == null || topTags.getLength() == 0) {
        return null;
    }
    Node topNodeTag = topTags.item(0);
    if (topNodeTag.getNodeType() != Node.ELEMENT_NODE) {
        return null;
    }
    Element topElementTag = (Element) topNodeTag;
    return topElementTag;
}

66. PageExtract#extractTextFromPage()

View license
private String extractTextFromPage() {
    NodeList elements = getXmlChildren(page.getSections().get(0).getContent());
    if (elements == null) {
        return "";
    }
    String firstSection = "";
    // First, extract the text of all the <p> tags from the first section
    for (int i = 0; i < elements.getLength(); i++) {
        if (elements.item(i).getNodeName().equalsIgnoreCase("p")) {
            firstSection += elements.item(i).getTextContent() + " ";
        }
    }
    // Strip the unwanted XML
    firstSection = Html.fromHtml(firstSection).toString();
    // Strip the reference texts ([1], [2]...)
    firstSection = firstSection.replaceAll("\\[\\d+\\]", "");
    return firstSection;
}

67. CmNamespaceHandler#parseDefaultProperties()

Project: aries
Source File: CmNamespaceHandler.java
View license
private Metadata parseDefaultProperties(ParserContext context, MutableBeanMetadata enclosingComponent, Element element) {
    MutableMapMetadata props = context.createMetadata(MutableMapMetadata.class);
    NodeList nl = element.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (node instanceof Element) {
            Element e = (Element) node;
            if (isCmNamespace(e.getNamespaceURI())) {
                if (nodeNameEquals(e, PROPERTY_ELEMENT)) {
                    BeanProperty prop = context.parseElement(BeanProperty.class, enclosingComponent, e);
                    props.addEntry(createValue(context, prop.getName(), String.class.getName()), prop.getValue());
                }
            }
        }
    }
    return props;
}

68. CmNamespaceHandler#parseInterfaceNames()

Project: aries
Source File: CmNamespaceHandler.java
View license
public List<String> parseInterfaceNames(Element element) {
    List<String> interfaceNames = new ArrayList<String>();
    NodeList nl = element.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (node instanceof Element) {
            Element e = (Element) node;
            if (nodeNameEquals(e, VALUE_ELEMENT)) {
                String v = getTextValue(e).trim();
                if (interfaceNames.contains(v)) {
                    throw new ComponentDefinitionException("The element " + INTERFACES_ELEMENT + " should not contain the same interface twice");
                }
                interfaceNames.add(getTextValue(e));
            } else {
                throw new ComponentDefinitionException("Unsupported element " + e.getNodeName() + " inside an " + INTERFACES_ELEMENT + " element");
            }
        }
    }
    return interfaceNames;
}

69. ExtNamespaceHandler#parseDefaultProperties()

Project: aries
Source File: ExtNamespaceHandler.java
View license
private Metadata parseDefaultProperties(ParserContext context, MutableBeanMetadata enclosingComponent, Element element) {
    MutableMapMetadata props = context.createMetadata(MutableMapMetadata.class);
    NodeList nl = element.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (node instanceof Element) {
            Element e = (Element) node;
            if (isExtNamespace(e.getNamespaceURI())) {
                if (nodeNameEquals(e, PROPERTY_ELEMENT)) {
                    BeanProperty prop = context.parseElement(BeanProperty.class, enclosingComponent, e);
                    props.addEntry(createValue(context, prop.getName(), String.class.getName()), prop.getValue());
                }
            }
        }
    }
    return props;
}

70. GeneratorTest#testGenerateTransactional()

Project: aries
Source File: GeneratorTest.java
View license
@Test
public void testGenerateTransactional() throws Exception {
    Node bean1 = getBeanById("myBean1");
    NodeList txs = (NodeList) xpath.evaluate("transaction", bean1, XPathConstants.NODESET);
    Set<TransactionalDef> defs = new HashSet<TransactionalDef>();
    for (int i = 0; i < txs.getLength(); ++i) {
        Node tx = txs.item(i);
        defs.add(new TransactionalDef(xpath.evaluate("@method", tx), xpath.evaluate("@value", tx)));
    }
    Set<TransactionalDef> expectedDefs = Sets.newHashSet(new TransactionalDef("*", "RequiresNew"), new TransactionalDef("txNotSupported", "NotSupported"), new TransactionalDef("txMandatory", "Mandatory"), new TransactionalDef("txNever", "Never"), new TransactionalDef("txRequired", "Required"), new TransactionalDef("txOverridenWithRequiresNew", "RequiresNew"), new TransactionalDef("txSupports", "Supports"));
    assertEquals(expectedDefs, defs);
}

71. GeneratorTest#testGenerateServiceWith2Interfaces()

Project: aries
Source File: GeneratorTest.java
View license
@Test
public void testGenerateServiceWith2Interfaces() throws Exception {
    Node serviceABImpl = getServiceByRef("serviceABImpl");
    assertXpathDoesNotExist(serviceABImpl, "@interface");
    assertXpathDoesNotExist(serviceABImpl, "@auto-export");
    NodeList interfaceValues = (NodeList) xpath.evaluate("interfaces/value", serviceABImpl, XPathConstants.NODESET);
    Set<String> interfaceNames = new HashSet<String>();
    for (int i = 0; i < interfaceValues.getLength(); ++i) {
        Node interfaceValue = interfaceValues.item(i);
        interfaceNames.add(interfaceValue.getTextContent());
    }
    assertEquals(Sets.newHashSet(ServiceA.class.getName(), ServiceB.class.getName()), interfaceNames);
}

72. Parser#parseCollection()

Project: aries
Source File: Parser.java
View license
private CollectionMetadata parseCollection(Class collectionType, Element element, ComponentMetadata enclosingComponent) {
    // Parse attributes
    String valueType = element.hasAttribute(VALUE_TYPE_ATTRIBUTE) ? element.getAttribute(VALUE_TYPE_ATTRIBUTE) : null;
    // Parse elements
    List<Metadata> list = new ArrayList<Metadata>();
    NodeList nl = element.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (node instanceof Element) {
            Metadata val = parseValueGroup((Element) node, enclosingComponent, null, true);
            list.add(val);
        }
    }
    return new CollectionMetadataImpl(collectionType, valueType, list);
}

73. Parser#parseProps()

Project: aries
Source File: Parser.java
View license
public PropsMetadata parseProps(Element element) {
    // Parse elements
    List<MapEntry> entries = new ArrayList<MapEntry>();
    NodeList nl = element.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (node instanceof Element) {
            Element e = (Element) node;
            if (isBlueprintNamespace(e.getNamespaceURI()) && nodeNameEquals(e, PROP_ELEMENT)) {
                entries.add(parseProperty(e));
            }
        }
    }
    return new PropsMetadataImpl(entries);
}

74. Parser#parseMap()

Project: aries
Source File: Parser.java
View license
public MapMetadata parseMap(Element element, ComponentMetadata enclosingComponent) {
    // Parse attributes
    String keyType = element.hasAttribute(KEY_TYPE_ATTRIBUTE) ? element.getAttribute(KEY_TYPE_ATTRIBUTE) : null;
    String valueType = element.hasAttribute(VALUE_TYPE_ATTRIBUTE) ? element.getAttribute(VALUE_TYPE_ATTRIBUTE) : null;
    // Parse elements
    List<MapEntry> entries = new ArrayList<MapEntry>();
    NodeList nl = element.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (node instanceof Element) {
            Element e = (Element) node;
            if (nodeNameEquals(e, ENTRY_ELEMENT)) {
                entries.add(parseMapEntry(e, enclosingComponent, null, null));
            }
        }
    }
    return new MapMetadataImpl(keyType, valueType, entries);
}

75. Parser#parseMapKeyEntry()

Project: aries
Source File: Parser.java
View license
private NonNullMetadata parseMapKeyEntry(Element element, ComponentMetadata enclosingComponent, String keyType) {
    NonNullMetadata keyValue = null;
    NodeList nl = element.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (node instanceof Element) {
            Element e = (Element) node;
            if (keyValue != null) {
            // TODO: throw an exception
            }
            keyValue = (NonNullMetadata) parseValueGroup(e, enclosingComponent, keyType, false);
            break;
        }
    }
    if (keyValue == null) {
    // TODO: throw an exception
    }
    return keyValue;
}

76. Parser#parseInterfaceNames()

Project: aries
Source File: Parser.java
View license
public List<String> parseInterfaceNames(Element element) {
    List<String> interfaceNames = new ArrayList<String>();
    NodeList nl = element.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (node instanceof Element) {
            Element e = (Element) node;
            if (nodeNameEquals(e, VALUE_ELEMENT)) {
                String v = getTextValue(e).trim();
                if (interfaceNames.contains(v)) {
                    throw new ComponentDefinitionException("The element " + INTERFACES_ELEMENT + " should not contain the same interface twice");
                }
                interfaceNames.add(getTextValue(e));
            } else {
                throw new ComponentDefinitionException("Unsupported element " + e.getNodeName() + " inside an " + INTERFACES_ELEMENT + " element");
            }
        }
    }
    return interfaceNames;
}

77. Parser#handleCustomElements()

Project: aries
Source File: Parser.java
View license
private ComponentMetadata handleCustomElements(Element element, ComponentMetadata enclosingComponent) {
    NodeList nl = element.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (node instanceof Element) {
            if (!isBlueprintNamespace(node.getNamespaceURI())) {
                enclosingComponent = decorateCustomNode(node, enclosingComponent);
            }
        }
    }
    return enclosingComponent;
}

78. SpringOsgiNamespaceHandler#getTextValue()

View license
public static String getTextValue(Element valueEle) {
    Assert.notNull(valueEle, "Element must not be null");
    StringBuilder sb = new StringBuilder();
    NodeList nl = valueEle.getChildNodes();
    for (int i = 0, l = nl.getLength(); i < l; ++i) {
        Node item = nl.item(i);
        if (item instanceof CharacterData && !(item instanceof Comment) || item instanceof EntityReference) {
            sb.append(item.getNodeValue());
        }
    }
    return sb.toString();
}

79. AssertXPath#assertXPath()

Project: arquillian-core
Source File: AssertXPath.java
View license
/**
    * Assert that the specified XPath Expression resolves to the specified values.
    * <br/><br/>
    * Assertions:<br/>
    * "ExpectedValue count should match found Node count" <br/> 
    * "XPath content should match expected value" <br/>
    * 
    * @param xml The XML to assert against
    * @param expression XPath expression to extract
    * @param expectedValue The Expected values found by expression
    * @throws Exception XML/XPath related parse exceptions
    */
public static void assertXPath(String xml, String expression, Object... expectedValue) throws Exception {
    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes()));
    XPathExpression xPathExpression = XPathFactory.newInstance().newXPath().compile(expression);
    NodeList nodes = (NodeList) xPathExpression.evaluate(doc, XPathConstants.NODESET);
    Assert.assertEquals("ExpectedValue count should match found Node count", expectedValue.length, nodes.getLength());
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        Assert.assertEquals("XPath content should match expected value", String.valueOf(expectedValue[i]), node.getTextContent());
    }
}

80. WebDavCompletionHandlerBase#parse()

View license
private void parse(Document document) {
    Element element = document.getDocumentElement();
    NodeList statusNode = element.getElementsByTagName("status");
    for (int i = 0; i < statusNode.getLength(); i++) {
        Node node = statusNode.item(i);
        String value = node.getFirstChild().getNodeValue();
        int statusCode = Integer.valueOf(value.substring(value.indexOf(" "), value.lastIndexOf(" ")).trim());
        String statusText = value.substring(value.lastIndexOf(" "));
        status = new HttpStatusWrapper(status, statusText, statusCode);
    }
}

81. ExternalResultsXMLParser#parseDerivedFiles()

View license
private void parseDerivedFiles(Element rootElement) {
    // Get the derived file lists.
    NodeList derivedFilesListNodes = rootElement.getElementsByTagName(TagNames.DERIVED_FILES_LIST_ELEM.toString());
    for (int i = 0; i < derivedFilesListNodes.getLength(); ++i) {
        Element derivedFilesListElem = (Element) derivedFilesListNodes.item(i);
        // Get the derived files.
        NodeList derivedFileNodes = derivedFilesListElem.getElementsByTagName(TagNames.DERIVED_FILE_ELEM.toString());
        for (int j = 0; j < derivedFileNodes.getLength(); ++j) {
            Element derivedFileElem = (Element) derivedFileNodes.item(j);
            // Get the local path of the derived file.
            String path = getChildElementContent(derivedFileElem, TagNames.LOCAL_PATH_ELEM.toString(), true);
            if (path.isEmpty()) {
                continue;
            }
            // Get the parent file of the derived file.
            String parentFile = getChildElementContent((Element) derivedFileNodes.item(j), TagNames.PARENT_FILE_ELEM.toString(), true);
            if (parentFile.isEmpty()) {
                continue;
            }
            this.resultsData.addDerivedFile(path, parentFile);
        }
    }
}

82. ExternalResultsXMLParser#parseArtifacts()

View license
private void parseArtifacts(final Element root) {
    // Get the artifact lists.
    NodeList artifactsListNodes = root.getElementsByTagName(TagNames.ARTIFACTS_LIST_ELEM.toString());
    for (int i = 0; i < artifactsListNodes.getLength(); ++i) {
        Element artifactsListElem = (Element) artifactsListNodes.item(i);
        // Get the artifacts.
        NodeList artifactNodes = artifactsListElem.getElementsByTagName(TagNames.ARTIFACT_ELEM.toString());
        for (int j = 0; j < artifactNodes.getLength(); ++j) {
            Element artifactElem = (Element) artifactNodes.item(j);
            // Get the artifact type.
            final String type = getElementAttributeValue(artifactElem, AttributeNames.TYPE_ATTR.toString());
            if (!type.isEmpty()) {
                // Get the source file of the artifact and the attributes,
                // if any.
                final String sourceFilePath = this.getChildElementContent(artifactElem, TagNames.SOURCE_FILE_ELEM.toString(), true);
                if (!sourceFilePath.isEmpty()) {
                    ExternalResults.Artifact artifact = this.resultsData.addArtifact(type, sourceFilePath);
                    parseArtifactAttributes(artifactElem, artifact);
                }
            }
        }
    }
}

83. ExternalResultsXMLParser#parseReports()

View license
private void parseReports(Element root) {
    // Get the report lists.
    NodeList reportsListNodes = root.getElementsByTagName(TagNames.REPORTS_LIST_ELEM.toString());
    for (int i = 0; i < reportsListNodes.getLength(); ++i) {
        Element reportsListElem = (Element) reportsListNodes.item(i);
        // Get the reports.
        NodeList reportNodes = reportsListElem.getElementsByTagName(TagNames.REPORT_ELEM.toString());
        for (int j = 0; j < reportNodes.getLength(); ++j) {
            Element reportElem = (Element) reportNodes.item(j);
            // Get the local path.
            String path = getChildElementContent(reportElem, TagNames.LOCAL_PATH_ELEM.toString(), true);
            if (path.isEmpty()) {
                continue;
            }
            // Get the source module.
            String sourceModule = getChildElementContent(reportElem, TagNames.SOURCE_MODULE_ELEM.toString(), true);
            if (path.isEmpty()) {
                continue;
            }
            // Get the optional report name.
            String reportName = getChildElementContent(reportElem, TagNames.REPORT_NAME_ELEM.toString(), false);
            this.resultsData.addReport(path, sourceModule, reportName);
        }
    }
}

84. ExternalResultsXMLParser#getChildElement()

View license
private Element getChildElement(Element parentElement, String childElementTagName) {
    Element childElem = null;
    NodeList childNodes = parentElement.getElementsByTagName(childElementTagName);
    if (childNodes.getLength() > 0) {
        childElem = (Element) childNodes.item(0);
        if (childNodes.getLength() > 1) {
            String errorMessage = NbBundle.getMessage(this.getClass(), "ExternalResultsXMLParser.getChildElement.errMsg1.text", childElementTagName, parentElement.getTagName(), this.resultsFilePath);
            this.recordError(errorMessage);
        }
    }
    return childElem;
}

85. CustomFileTypesManager#parseSignature()

Project: autopsy
Source File: CustomFileTypesManager.java
View license
/**
     * Gets the signature from a file type XML element.
     *
     * @param fileTypeElem The XML element.
     *
     * @return The signature.
     */
private static Signature parseSignature(Element fileTypeElem) throws IllegalArgumentException, NumberFormatException {
    NodeList signatureElems = fileTypeElem.getElementsByTagName(SIGNATURE_TAG_NAME);
    Element signatureElem = (Element) signatureElems.item(0);
    String sigTypeAttribute = signatureElem.getAttribute(SIGNATURE_TYPE_ATTRIBUTE);
    Signature.Type signatureType = Signature.Type.valueOf(sigTypeAttribute);
    String sigBytesString = getChildElementTextContent(signatureElem, BYTES_TAG_NAME);
    byte[] signatureBytes = DatatypeConverter.parseHexBinary(sigBytesString);
    Element offsetElem = (Element) signatureElem.getElementsByTagName(OFFSET_TAG_NAME).item(0);
    String offsetString = offsetElem.getTextContent();
    long offset = DatatypeConverter.parseLong(offsetString);
    boolean isRelativeToStart;
    String relativeString = offsetElem.getAttribute(RELATIVE_ATTRIBUTE);
    if (null == relativeString || relativeString.equals("")) {
        isRelativeToStart = true;
    } else {
        isRelativeToStart = DatatypeConverter.parseBoolean(relativeString);
    }
    return new Signature(signatureBytes, offset, signatureType, isRelativeToStart);
}

86. RegionMetadataParser#parseRegionElement()

View license
private static Region parseRegionElement(final Element regionElement, final boolean endpointVerification) {
    String name = getChildElementValue(REGION_ID_TAG, regionElement);
    String domain = getChildElementValue(DOMAIN_TAG, regionElement);
    InMemoryRegionImpl regionImpl = new InMemoryRegionImpl(name, domain);
    NodeList endpointNodes = regionElement.getElementsByTagName(ENDPOINT_TAG);
    for (int i = 0; i < endpointNodes.getLength(); i++) {
        addRegionEndpoint(regionImpl, (Element) endpointNodes.item(i), endpointVerification);
    }
    return new Region(regionImpl);
}

87. RegionMetadataParser#getChildElementValue()

View license
private static String getChildElementValue(final String tagName, final Element element) {
    Node tagNode = element.getElementsByTagName(tagName).item(0);
    if (tagNode == null)
        return null;
    NodeList nodes = tagNode.getChildNodes();
    Node node = (Node) nodes.item(0);
    return node.getNodeValue();
}

88. RegionMetadataParser#parseRegionMetadata()

View license
/**
     * Parses the specified input stream and returns a list of the regions
     * declared in it.
     *
     * @param input
     *            The stream containing the region metadata to parse.
     *
     * @return The list of parsed regions.
     */
public List<Region> parseRegionMetadata(InputStream input) {
    Document document;
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = factory.newDocumentBuilder();
        document = documentBuilder.parse(input);
    } catch (Exception e) {
        throw new RuntimeException("Unable to parse region metadata file: " + e.getMessage(), e);
    }
    NodeList regionNodes = document.getElementsByTagName(REGION_TAG);
    List<Region> regions = new ArrayList<Region>();
    for (int i = 0; i < regionNodes.getLength(); i++) {
        Node node = regionNodes.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) node;
            regions.add(parseRegionElement(element));
        }
    }
    return regions;
}

89. RegionMetadataParser#parseRegionElement()

View license
/*
     * Private Interface
     */
private Region parseRegionElement(Element regionElement) {
    String name = getTagValue(REGION_DISPLAY_NAME_TAG, regionElement);
    String id = getTagValue(REGION_SYSTEM_ID_TAG, regionElement);
    String flagIcon = getTagValue(FLAG_ICON_TAG, regionElement);
    Region region = new RegionImpl(name, id, flagIcon);
    NodeList serviceNodes = regionElement.getElementsByTagName(SERVICE_TAG);
    for (int i = 0; i < serviceNodes.getLength(); i++) {
        Node node = serviceNodes.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) node;
            String serviceName = getAttributeValue(element, SERVICE_NAME_ATTRIBUTE);
            String serviceId = getAttributeValue(element, SERVICE_ID_ATTRIBUTE);
            String signer = getAttributeValue(element, SIGNER_ATTRIBUTE);
            String endpoint = element.getTextContent();
            region.getServiceEndpoints().put(serviceName, endpoint);
            region.getServicesByName().put(serviceName, new Service(serviceName, serviceId, endpoint, signer));
        }
    }
    return region;
}

90. WSDDElement#getChildElements()

Project: axis1-java
Source File: WSDDElement.java
View license
public Element[] getChildElements(Element e, String name) {
    NodeList nl = e.getChildNodes();
    Vector els = new Vector();
    for (int i = 0; i < nl.getLength(); i++) {
        Node thisNode = nl.item(i);
        if (!(thisNode instanceof Element))
            continue;
        Element el = (Element) thisNode;
        if (el.getLocalName().equals(name)) {
            els.add(el);
        }
    }
    Element[] elements = new Element[els.size()];
    els.toArray(elements);
    return elements;
}

91. MessageElement#getElementsNS()

Project: axis1-java
Source File: MessageElement.java
View license
/**
     * helper method for recusively getting the element that has namespace URI and localname
     * @param parentElement parent element
     * @param namespace namespace
     * @param localName local name of element
     * @return (potentially empty) list of elements that match the (namespace,localname) tuple
     */
protected NodeList getElementsNS(org.w3c.dom.Element parentElement, String namespace, String localName) {
    NodeList children = parentElement.getChildNodes();
    NodeListImpl matches = new NodeListImpl();
    for (int i = 0; i < children.getLength(); i++) {
        if (children.item(i) instanceof Text) {
            continue;
        }
        Element child = (Element) children.item(i);
        if (namespace.equals(child.getNamespaceURI()) && localName.equals(child.getLocalName())) {
            matches.addNode(child);
        }
        // search the grand-children.
        matches.addNodeList(child.getElementsByTagNameNS(namespace, localName));
    }
    return matches;
}

92. NodeImpl#getPreviousSibling()

Project: axis1-java
Source File: NodeImpl.java
View license
/**
     * The node immediately preceding this node. If there is no such node,
     * this returns <code>null</code>.
     */
public Node getPreviousSibling() {
    SOAPElement parent = getParentElement();
    if (parent == null) {
        return null;
    }
    NodeList nl = parent.getChildNodes();
    int len = nl.getLength();
    int i = 0;
    Node previousSibling = null;
    while (i < len) {
        if (nl.item(i) == this) {
            return previousSibling;
        }
        previousSibling = nl.item(i);
        i++;
    }
    // should be null.
    return previousSibling;
}

93. XMLUtils#findNode()

Project: axis1-java
Source File: XMLUtils.java
View license
/**
     * Find a Node with a given QName
     *
     * @param node parent node
     * @param name QName of the child we need to find
     * @return child node
     */
public static Node findNode(Node node, QName name) {
    if (name.getNamespaceURI().equals(node.getNamespaceURI()) && name.getLocalPart().equals(node.getLocalName()))
        return node;
    NodeList children = node.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node ret = findNode(children.item(i), name);
        if (ret != null)
            return ret;
    }
    return null;
}

94. SchemaUtils#getChildByName()

Project: axis1-java
Source File: SchemaUtils.java
View license
/**
     * Returns named child node.
     *
     * @param parentNode Parent node.
     * @param name Element name of child node to return.
     */
private static Node getChildByName(Node parentNode, String name) throws DOMException {
    if (parentNode == null)
        return null;
    NodeList children = parentNode.getChildNodes();
    if (children != null) {
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            if (child != null) {
                if ((child.getNodeName() != null && (name.equals(child.getNodeName()))) || (child.getLocalName() != null && (name.equals(child.getLocalName())))) {
                    return child;
                }
            }
        }
    }
    return null;
}

95. SchemaUtils#processAllNode()

Project: axis1-java
Source File: SchemaUtils.java
View license
/**
     * Invoked by getContainedElementDeclarations to get the child element types
     * and child element names underneath an all node.
     *
     * @param allNode
     * @param symbolTable
     * @return
     */
private static Vector processAllNode(Node allNode, SymbolTable symbolTable) {
    Vector v = new Vector();
    NodeList children = allNode.getChildNodes();
    for (int j = 0; j < children.getLength(); j++) {
        Node kid = children.item(j);
        if (isXSDNode(kid, "element")) {
            ElementDecl elem = processChildElementNode(kid, symbolTable);
            if (elem != null) {
                v.add(elem);
            }
        }
    }
    return v;
}

96. SymbolTable#getInnerCollectionComponentQName()

Project: axis1-java
Source File: SymbolTable.java
View license
/**
     * Method getInnerCollectionComponentQName
     *
     * @param node
     * @return
     */
private QName getInnerCollectionComponentQName(Node node) {
    if (node == null) {
        return null;
    }
    QName name = SchemaUtils.getCollectionComponentQName(node, new QNameHolder(), new BooleanHolder(), this);
    if (name != null) {
        return name;
    }
    // Dive into the node if necessary
    NodeList children = node.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        name = getInnerCollectionComponentQName(children.item(i));
        if (name != null) {
            return name;
        }
    }
    return null;
}

97. TestDerivatedBeanSerializer#testDerivatedBeanSerialize()

View license
/**
	 * Test the serialization of an simple sequence. The bean contains three
	 * elements (zero, one, two). The excepted result is something like:
	 * <BR>
	 * <PRE>
	 * <SuperBean>
	 *     <zero/>
	 *     <one/>
	 *     <two/>
	 * </SuperBean>
	 * </PRE>
	 */
/*
	public void testSuperBeanSerialize() throws Exception {
		BeanSerializer ser = new BeanSerializer(SuperBean.class, superTypeQName);

		Object object = new SuperBean();
		ser.serialize(superTypeQName,null,object,context);
		
		// Check the result
		String msgString = stringWriter.toString();
		StringReader reader = new StringReader(msgString);
		DOMParser parser = new DOMParser();
		parser.parse(new InputSource(reader));
		Document doc = parser.getDocument();
		
		// We only test the order of the attributes.
		NodeList nodes = doc.getFirstChild().getChildNodes();
		assertEquals("1st Attribute", "zero", nodes.item(0).getLocalName());
		assertEquals("2nd Attribute", "one", nodes.item(1).getLocalName());
		assertEquals("3rd Attribute", "two", nodes.item(2).getLocalName());
	}
    */
/**
	 * Test the serialization of an derivated sequence. The derivated bean contains two elements
	 * (three, four) and the super class has three elements (zero, one, two). The excepted
	 * result is something like: <BR>
	 * <PRE>
	 * <DerivatedBean>
	 *     <zero/>
	 *     <one/>
	 *     <two/>
	 *     <three/>
	 *     <four/>
	 * </DerivatedBean>
	 * </PRE>
	 */
public void testDerivatedBeanSerialize() throws Exception {
    BeanSerializer ser = new BeanSerializer(DerivatedBean.class, inheritedTypeQName);
    Object object = new DerivatedBean();
    ser.serialize(inheritedTypeQName, null, object, context);
    // Check the result
    String msgString = stringWriter.toString();
    StringReader reader = new StringReader(msgString);
    Document doc = XMLUtils.newDocument(new InputSource(reader));
    NodeList nodes = doc.getFirstChild().getChildNodes();
    assertEquals("1st Attribute", "zero", nodes.item(0).getLocalName());
    assertEquals("2nd Attribute", "one", nodes.item(1).getLocalName());
    assertEquals("3rd Attribute", "two", nodes.item(2).getLocalName());
    assertEquals("4th Attribute", "three", nodes.item(3).getLocalName());
    assertEquals("First Attribute", "four", nodes.item(4).getLocalName());
}

98. TestSer#findChildElementByLocalName()

Project: axis1-java
Source File: TestSer.java
View license
private Element findChildElementByLocalName(Element src, String localName) {
    NodeList nl = src.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (node instanceof Element) {
            Element e = (Element) node;
            if (e.getLocalName().equals(localName)) {
                return e;
            }
            // Depth-first search
            e = findChildElementByLocalName(e, localName);
            if (e != null) {
                return e;
            }
        }
    }
    return null;
}

99. TestSOAPFaultException#checkDetailAgainstTestDetail()

View license
/**
     * Checks if the AxisFault contains the expected detail elements
     * 
     * @param axisFault
     */
private void checkDetailAgainstTestDetail(AxisFault axisFault) {
    Element[] details = axisFault.getFaultDetails();
    assertEquals("wrong name for detail element", "MyDetails", details[0].getNodeName());
    assertEquals("wrong node value for detail element", "hossa", ((Text) details[0].getChildNodes().item(0)).getData());
    assertEquals("wrong name for foo element", "foo", details[1].getNodeName());
    boolean found = false;
    NodeList childs = details[1].getChildNodes();
    for (int i = 0; i < childs.getLength(); i++) {
        if ("baz".equals(childs.item(i).getNodeName()))
            found = true;
    }
    assertTrue("subelement baz not found in details", found);
}

100. Service#argAsDOM()

Project: axis1-java
Source File: Service.java
View license
/**
     * Return the target service (should be this!)
     */
public String argAsDOM(Data input) throws Exception {
    // get the first parameter
    Message message = MessageContext.getCurrentContext().getRequestMessage();
    RPCElement body = (RPCElement) message.getSOAPEnvelope().getFirstBody();
    NodeList parms = body.getAsDOM().getChildNodes();
    Node parm1 = null;
    for (int i = 0; i < parms.getLength(); i++) {
        parm1 = parms.item(i);
        if (parm1.getNodeType() == Node.ELEMENT_NODE)
            break;
    }
    // convert it to a DOM and back to a string, and return the result.
    return DOM2Writer.nodeToString(parm1, true);
}