Example usage for org.w3c.dom Element getElementsByTagNameNS

List of usage examples for org.w3c.dom Element getElementsByTagNameNS

Introduction

In this page you can find the example usage for org.w3c.dom Element getElementsByTagNameNS.

Prototype

public NodeList getElementsByTagNameNS(String namespaceURI, String localName) throws DOMException;

Source Link

Document

Returns a NodeList of all the descendant Elements with a given local name and namespace URI in document order.

Usage

From source file:org.pengyou.client.lib.properties.AclProperty.java

/**
 * Parse an ace./*from   ww  w  . ja v a2s.  com*/
 */
protected Ace parseAce(Element element) {

    String principal = null;
    Element child = DOMUtils.getFirstElement(element, "DAV:", "principal");
    if (child == null) {
        System.err.println("Error: mandatory element <principal> is missing !");
        System.err.println("element: " + element);
        return null;
    }

    Element href = DOMUtils.getFirstElement(child, "DAV:", "href");
    if (href != null) {
        principal = DOMUtils.getTextValue(href);
        try {
            principal = URIUtil.decode(principal);
        } catch (URIException e) {
            System.err.println("Warning: decoding href element failed!");
            System.err.println("reason: " + e.getReason());
        }
    }

    String[] types = { "all", "authenticated", "unauthenticated", "property", "self" };
    for (int i = 0; i < types.length && principal == null; i++) {
        Element type = DOMUtils.getFirstElement(child, "DAV:", types[i]);
        if (type != null) {
            principal = types[i];
        }
    }

    if (principal == null) {
        System.err.println("Error: unknown type of principal");
        System.err.println("element: " + element);
        return null;
    }

    Ace ace = new Ace(principal);

    child = DOMUtils.getFirstElement(element, "DAV:", "grant");
    if (child == null) {
        child = DOMUtils.getFirstElement(element, "DAV:", "deny");
        ace.setNegative(true);
    }
    if (child != null) {
        NodeList privilegeElements = child.getElementsByTagNameNS("DAV:", "privilege");
        for (int i = 0; i < privilegeElements.getLength(); i++) {
            Element privilegeElement = (Element) privilegeElements.item(i);
            NodeList privileges = privilegeElement.getElementsByTagName("*");
            for (int j = 0; j < privileges.getLength(); j++) {
                Element privilege = (Element) privileges.item(j);
                ace.addPrivilege(parsePrivilege(privilege));
            }
        }
    }

    child = DOMUtils.getFirstElement(element, "DAV:", "inherited");
    if (child != null) {
        href = DOMUtils.getFirstElement(child, "DAV:", "href");
        String shref = null;
        if (href != null) {
            shref = DOMUtils.getTextValue(href);
            if (!shref.equals(response.getHref())) {
                ace.setInherited(true);
                ace.setInheritedFrom(shref);
            }
        } else {
            System.err.println("Error: mandatory element <href> is missing !");
            return null;
        }
    }

    child = DOMUtils.getFirstElement(element, "DAV:", "protected");
    if (child != null) {
        ace.setProtected(true);
    }

    return ace;

}

From source file:org.sakaiproject.dav.DavServlet.java

/**
 * PROPPATCH Method.//from w  w  w  .  j  a v  a2s  .  c  om
 */
@SuppressWarnings("deprecation")
protected void doProppatch(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    // Check that the resource is not locked
    if (isLocked(req)) {
        resp.sendError(SakaidavStatus.SC_LOCKED);
    }

    // we can't actually do this, but MS requires us to. Say we did.
    // I'm trying to be as close to valid here, so I generate an OK
    // for all the properties they tried to set. This is really hairy because
    // it gets into name spaces. But if we ever try to implement this for real,
    // we'll have to do this. So might as well start now.
    //    During testing I found by mistake that it's actually OK to send
    // an empty multistatus return, so I don't actually  need all of this stuff.
    //    The big problem is that the properties are typically not in the dav namespace
    // we build a hash table of namespaces, with the prefix we're going to use
    // since D: is used for dav, we start with E:, actually D+1

    DocumentBuilder documentBuilder = null;
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
        factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);

        documentBuilder = factory.newDocumentBuilder();
    } catch (Exception e) {
        resp.sendError(SakaidavStatus.SC_METHOD_FAILURE);
        return;
    }

    int contentLength = req.getContentLength();

    // a list of the properties with the new prefix
    List<String> props = new ArrayList<String>();
    // hash of namespace, prefix
    Hashtable<String, String> spaces = new Hashtable<String, String>();

    // read the xml document
    if (contentLength > MAX_XML_STREAM_LENGTH) {
        resp.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
        return;
    } else if (contentLength > 0) {

        byte[] byteContent = new byte[contentLength];
        InputStream inputStream = req.getInputStream();

        int lenRead = 0;

        try {
            while (lenRead < contentLength) {
                int read = inputStream.read(byteContent, lenRead, contentLength - lenRead);
                if (read <= 0)
                    break;
                lenRead += read;
            }
        } catch (Exception ignore) {
        }

        // Parse the input XML to see what they really want
        if (lenRead > 0)
            try {
                // if we got here, "is" is the xml document
                InputStream is = new ByteArrayInputStream(byteContent, 0, lenRead);
                Document document = documentBuilder.parse(new InputSource(is));

                // Get the root element of the document
                Element rootElement = document.getDocumentElement();
                // find all the property nodes
                NodeList childList = rootElement.getElementsByTagNameNS("DAV:", "prop");

                int nextChar = 1;

                for (int i = 0; i < childList.getLength(); i++) {

                    // this should be a prop node
                    Node currentNode = childList.item(i);
                    // this should be the actual property
                    NodeList names = currentNode.getChildNodes();
                    // this should be the name
                    for (int j = 0; j < names.getLength(); j++) {
                        String namespace = names.item(j).getNamespaceURI();
                        String prefix = spaces.get(namespace);
                        // see if we know about this namespace. If not add it and
                        // generate a prefix
                        if (prefix == null) {
                            prefix = "" + Character.toChars('D' + nextChar)[0];
                            spaces.put(namespace, prefix);
                        }
                        props.add(prefix + ":" + names.item(j).getLocalName());
                    }
                }
            } catch (Exception ignore) {
            }
    }

    resp.setStatus(SakaidavStatus.SC_MULTI_STATUS);
    resp.setContentType("text/xml; charset=UTF-8");

    Writer writer = resp.getWriter();

    writer.write("<D:multistatus xmlns:D=\"DAV:\"");
    // dump all the name spaces and their prefix
    for (String namespace : spaces.keySet())
        writer.write(" xmlns:" + spaces.get(namespace) + "=\"" + namespace + "\"");
    writer.write("><D:response><D:href>" + javax.servlet.http.HttpUtils.getRequestURL(req) + "</D:href>");
    // now output properties, claiming we did it
    for (String pname : props) {
        writer.write("<D:propstat><D:prop><" + pname
                + "/></D:prop><D:status>HTTP/1.1 201 OK</D:status></D:propstat>");
    }
    writer.write("</D:response></D:multistatus>");
    writer.close();

}

From source file:org.soa4all.dashboard.gwt.module.wsmolite.server.WsmoLiteDataServiceImpl.java

public String getSAWSDLService(String restURL) throws Exception {
    Document parsed = getContentAsXML(restURL);
    Element root = parsed.getDocumentElement();
    ServiceDataProcessor.markElementsWithIDs(root);
    ServiceDataProcessor.buildLabels(root);

    ServiceDataProcessor.encodeWSDL11AnnOnOperations(root);

    NodeList schemas = root.getElementsByTagNameNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "schema");

    for (int i = 0; i < schemas.getLength(); i++) {
        ServiceDataProcessor.simplifyTree((Element) schemas.item(i));
    }//from  w w w  . j  ava  2s. c  om
    return getXMLString(parsed);
}

From source file:org.socraticgrid.workbench.security.wso2.SamlConsumer.java

private String getResult(XMLObject responseObject) {
    // Retrieve results by converting the response to DOM
    Element ele = responseObject.getDOM();
    NodeList statusNodeList = ele.getElementsByTagName("samlp:StatusCode");
    Node statusNode = statusNodeList.item(0);
    NamedNodeMap statusAttr = statusNode.getAttributes();
    Node valueAtt = statusAttr.item(0);
    String statusValue = valueAtt.getNodeValue();
    String[] word = statusValue.split(":");
    String result = word[word.length - 1];

    NodeList nameIDNodeList = ele.getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "NameID");
    Node nameIDNode = nameIDNodeList.item(0);
    String nameID = nameIDNode.getFirstChild().getNodeValue();

    result = nameID + ":" + result;
    return result;
}

From source file:org.socraticgrid.xmlCommon.XmlUtility.java

public static Element getSingleChildElement(Element element, String namespaceURI, String localName) {
    Element childElement = null;/*  www  . j a  v a2  s .  co  m*/
    if ((element != null)
            && (NullChecker.isNotNullish(namespaceURI) && (NullChecker.isNotNullish(localName)))) {
        NodeList result = element.getElementsByTagNameNS(namespaceURI, localName);
        if ((result != null) && (result.getLength() >= 1)) {
            childElement = (Element) result.item(0);
        }
    }
    return childElement;
}

From source file:org.springmodules.validation.bean.conf.loader.xml.DefaultXmlBeanValidationConfigurationLoader.java

/**
 * Creates and builds a bean validation configuration based for the given class, based on the given &lt;class&gt;
 * element./*from   w w  w  .j  a v  a 2 s  . c o m*/
 *
 * @param element The &lt;class&gt; element.
 * @return The created bean validation configuration.
 */
public BeanValidationConfiguration handleClassDefinition(Class clazz, Element element) {

    DefaultBeanValidationConfiguration configuration = new DefaultBeanValidationConfiguration();

    NodeList nodes = element.getElementsByTagNameNS(DEFAULT_NAMESPACE_URL, VALIDATOR_TAG);
    for (int i = 0; i < nodes.getLength(); i++) {
        Element validatorDefinition = (Element) nodes.item(i);
        handleValidatorDefinition(validatorDefinition, clazz, configuration);
    }

    nodes = element.getElementsByTagNameNS(DEFAULT_NAMESPACE_URL, GLOBAL_TAG);
    for (int i = 0; i < nodes.getLength(); i++) {
        Element globalDefinition = (Element) nodes.item(i);
        handleGlobalDefinition(globalDefinition, clazz, configuration);
    }

    nodes = element.getElementsByTagNameNS(DEFAULT_NAMESPACE_URL, PROPERTY_TAG);
    for (int i = 0; i < nodes.getLength(); i++) {
        Element propertyDefinition = (Element) nodes.item(i);
        handlePropertyDefinition(propertyDefinition, clazz, configuration);
    }

    return configuration;
}

From source file:org.warlock.itk.distributionenvelope.Payload.java

/**
 * Retrieves the certificate used for an enveloping signature.
 * @param signature//from w w  w  . j a v  a2 s . c  o m
 * @return
 * @throws Exception 
 */
private X509Certificate getCertificate(Element signature) throws Exception {
    NodeList nl = signature.getElementsByTagNameNS(CfHNamespaceContext.DSNAMESPACE, "X509Certificate");
    if (nl.getLength() == 0) {
        throw new Exception("Cannot find certificate in signature");
    }
    Element x509cert = (Element) nl.item(0);
    StringBuilder sb = new StringBuilder("-----BEGIN CERTIFICATE-----\n");
    String encodedKey = x509cert.getTextContent();
    sb.append(encodedKey);
    if (encodedKey.charAt(encodedKey.length() - 1) != '\n') {
        sb.append("\n");
    }
    sb.append("-----END CERTIFICATE-----");
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate x = (X509Certificate) cf
            .generateCertificate(new ByteArrayInputStream(sb.toString().getBytes()));
    return x;
}

From source file:org.warlock.itk.distributionenvelope.Payload.java

/**
 * Extracts the content of an "Object" element element of the enveloping 
 * signature - see the W3 XML Encryption specification.
 * @param signature/*  ww w  .  ja va2  s .c  om*/
 * @return
 * @throws Exception 
 */
private byte[] getSignatureObject(Element signature) throws Exception {
    //        NodeList nl = signature.getElementsByTagNameNS(CfHNamespaceContext.DSNAMESPACE, "Object");
    //        if (nl.getLength() == 0) {
    //            throw new Exception("Error retrieving object from signature");
    //        }
    //        String object = ((Element)nl.item(0)).getTextContent();
    //        return object.getBytes();
    NodeList nl = signature.getElementsByTagNameNS(CfHNamespaceContext.DSNAMESPACE, "Object");
    if (nl.getLength() == 0) {
        throw new Exception("Error retrieving object from signature");
    }
    StringWriter outfile = new StringWriter();
    StreamResult sr = new StreamResult(outfile);
    Transformer tx = TransformerFactory.newInstance().newTransformer();
    String out;
    Node n = (Node) nl.item(0);
    NodeList subnl = n.getChildNodes();
    Node subn = (Node) subnl.item(0);
    if (subn.hasChildNodes()) {
        tx.transform(new DOMSource((Node) subnl.item(0)), sr);
        out = outfile.toString();
        if (out.indexOf("<?xml ") == 0) {
            out = out.substring(out.indexOf("?>") + "?>".length());
        }
    } else {
        out = n.getTextContent();
    }

    return out.getBytes();
}

From source file:org.wso2.carbon.apimgt.migration.client._200Specific.ResourceModifier200.java

private static void updateInSequence(Element resourceElement, Document doc) {
    // Find the inSequence
    Element inSequenceElement = (Element) resourceElement
            .getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_INSEQUENCE).item(0);

    // Find the property element in the inSequence
    NodeList filters = inSequenceElement.getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_FILTER);

    for (int j = 0; j < filters.getLength(); ++j) {
        Element filterElement = (Element) filters.item(j);
        if (Constants.SYNAPSE_API_VALUE_AM_KEY_TYPE
                .equals(filterElement.getAttribute(Constants.SYNAPSE_API_ATTRIBUTE_SOURCE))) {
            // Only one <then> element can exist in filter mediator
            Element thenElement = (Element) filterElement
                    .getElementsByTagNameNS(Constants.SYNAPSE_API_XMLNS, Constants.SYNAPSE_API_ELEMENT_THEN)
                    .item(0);/* w w  w . ja v  a  2 s  . c o m*/
            NodeList properties = thenElement.getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_PROPERTY);
            for (int i = 0; i < properties.getLength(); ++i) {
                Element propertyElement = (Element) properties.item(i);
                if (propertyElement.hasAttribute(Constants.SYNAPSE_API_ATTRIBUTE_NAME)) {
                    if (Constants.SYNAPSE_API_VALUE_BACKEND_REQUEST_TIME
                            .equals(propertyElement.getAttribute(Constants.SYNAPSE_API_ATTRIBUTE_NAME))) {
                        thenElement.removeChild(propertyElement);
                        break;
                    }
                }
            }

            //removing bam mediator
            //for production url
            NodeList thenFilterElement = thenElement.getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_FILTER);
            if (thenFilterElement != null && thenFilterElement.getLength() > 0) {
                for (int i = 0; i < thenFilterElement.getLength(); ++i) {
                    Element filterNode = (Element) thenFilterElement.item(i);
                    if (filterNode.getAttribute(Constants.SYNAPSE_API_ATTRIBUTE_SOURCE)
                            .contains(Constants.SYNAPSE_IS_STAT_ENABLED_PROPERTY_NAME)) {
                        thenElement.removeChild(filterNode);
                    }
                }
            }
            //for sandbox url
            Element elseElement = (Element) filterElement
                    .getElementsByTagNameNS(Constants.SYNAPSE_API_XMLNS, "else").item(0);
            NodeList elseFilterElement = elseElement.getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_FILTER);
            if (elseFilterElement != null && elseFilterElement.getLength() > 0) {
                for (int i = 0; i < elseFilterElement.getLength(); ++i) {
                    Element filterNode = (Element) elseFilterElement.item(i);
                    if (filterNode.getAttribute(Constants.SYNAPSE_API_ATTRIBUTE_SOURCE)
                            .contains(Constants.SYNAPSE_IS_STAT_ENABLED_PROPERTY_NAME)) {
                        elseElement.removeChild(filterNode);
                    }
                }
            }

            //adding endpoint_address property, only for production
            Element sendElement = (Element) thenElement
                    .getElementsByTagNameNS(Constants.SYNAPSE_API_XMLNS, Constants.SYNAPSE_API_ELEMENT_SEND)
                    .item(0);
            Element endpointElement = (Element) sendElement
                    .getElementsByTagNameNS(Constants.SYNAPSE_API_XMLNS, Constants.SYNAPSE_ENDPOINT_XML_ELEMENT)
                    .item(0);

            if (endpointElement != null) {
                NodeList failOverElements = endpointElement
                        .getElementsByTagName(Constants.SYNAPSE_FAIL_OVER_XML_ELEMENT);
                NodeList loadBalanceElements = endpointElement
                        .getElementsByTagName(Constants.SYNAPSE_LOAD_BALANCE_XML_ELEMENT);
                if (failOverElements.getLength() > 0) {
                    Element failOverElement = (Element) failOverElements.item(0);
                    NodeList endpointElements = failOverElement
                            .getElementsByTagName(Constants.SYNAPSE_ENDPOINT_XML_ELEMENT);
                    for (int i = 0; i < endpointElements.getLength(); i++) {
                        addingAddressPropertyToEndpoint((Element) endpointElements.item(i), doc);
                    }
                } else if (loadBalanceElements.getLength() > 0) {
                    Element loadBalanceElement = (Element) loadBalanceElements.item(0);
                    NodeList endpointElements = loadBalanceElement
                            .getElementsByTagName(Constants.SYNAPSE_ENDPOINT_XML_ELEMENT);
                    for (int i = 0; i < endpointElements.getLength(); i++) {
                        addingAddressPropertyToEndpoint((Element) endpointElements.item(i), doc);
                    }
                } else {
                    addingAddressPropertyToEndpoint(endpointElement, doc);
                }
            }
        }
    }

    boolean isExistProp = false;
    NodeList properties = inSequenceElement.getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_PROPERTY);
    for (int i = 0; i < properties.getLength(); ++i) {
        Element propertyElement = (Element) properties.item(i);
        if (propertyElement.hasAttribute(Constants.SYNAPSE_API_ATTRIBUTE_NAME)) {
            if (Constants.SYNAPSE_API_VALUE_BACKEND_REQUEST_TIME
                    .equals(propertyElement.getAttribute(Constants.SYNAPSE_API_ATTRIBUTE_NAME))) {
                isExistProp = true;
                log.info("Property '" + Constants.SYNAPSE_API_VALUE_BACKEND_REQUEST_TIME + "' already exist");
                break;
            }
        }
    }

    if (!isExistProp) {
        Element propertyElement = doc.createElementNS(Constants.SYNAPSE_API_XMLNS,
                Constants.SYNAPSE_API_ELEMENT_PROPERTY);
        propertyElement.setAttribute(Constants.SYNAPSE_API_ATTRIBUTE_EXPRESSION,
                Constants.SYNAPSE_API_VALUE_EXPRESSION);
        propertyElement.setAttribute(Constants.SYNAPSE_API_ATTRIBUTE_NAME,
                Constants.SYNAPSE_API_VALUE_BACKEND_REQUEST_TIME);
        if (filters.getLength() > 0) {
            inSequenceElement.insertBefore(propertyElement, filters.item(0));
        } else {
            inSequenceElement.appendChild(propertyElement);
        }
    }
}

From source file:org.wso2.carbon.bpel.b4p.extension.PeopleActivity.java

/**
 * Determine what the standard element is and process it
 *
 * @param peopleActivityElement/*www.ja v a  2 s . com*/
 * @throws FaultException
 */
private void processStandardElement(Element peopleActivityElement) throws FaultException {
    try {
        String elementType = extractStandardElementType(peopleActivityElement);

        if (elementType.equals(BPEL4PeopleConstants.PEOPLE_ACTIVITY_REMOTE_TASK)) {
            Node node = peopleActivityElement.getElementsByTagNameNS(BPEL4PeopleConstants.B4P_NAMESPACE,
                    BPEL4PeopleConstants.PEOPLE_ACTIVITY_REMOTE_TASK).item(0);
            if (node == null) {
                throw new FaultException(BPEL4PeopleConstants.B4P_FAULT, "Namespace for element:" + elementType
                        + " is not " + BPEL4PeopleConstants.B4P_NAMESPACE);
            }
            parseRemoteTask(node);
        } else if (elementType.equals(BPEL4PeopleConstants.PEOPLE_ACTIVITY_REMOTE_NOTIFICATION)) {
            Node node = peopleActivityElement.getElementsByTagNameNS(BPEL4PeopleConstants.B4P_NAMESPACE,
                    BPEL4PeopleConstants.PEOPLE_ACTIVITY_REMOTE_NOTIFICATION).item(0);
            if (node == null) {
                throw new FaultException(BPEL4PeopleConstants.B4P_FAULT, "Namespace for element:" + elementType
                        + " is not " + BPEL4PeopleConstants.B4P_NAMESPACE);
            }
            parseRemoteNotification(node);
        } else if (elementType.equals(BPEL4PeopleConstants.PEOPLE_ACTIVITY_LOCAL_NOTIFICATION)) {
            Node node = peopleActivityElement.getElementsByTagNameNS(BPEL4PeopleConstants.B4P_NAMESPACE,
                    BPEL4PeopleConstants.PEOPLE_ACTIVITY_LOCAL_NOTIFICATION).item(0);

            if (node == null) {
                throw new FaultException(BPEL4PeopleConstants.B4P_FAULT, "Namespace for element:" + elementType
                        + " is not " + BPEL4PeopleConstants.B4P_NAMESPACE);
            }
            parseLocalNotification(node);
        } else if (elementType.equals(BPEL4PeopleConstants.PEOPLE_ACTIVITY_LOCAL_TASK)) {
            Node node = peopleActivityElement.getElementsByTagNameNS(BPEL4PeopleConstants.B4P_NAMESPACE,
                    BPEL4PeopleConstants.PEOPLE_ACTIVITY_LOCAL_TASK).item(0);

            if (node == null) {
                throw new FaultException(BPEL4PeopleConstants.B4P_FAULT, "Namespace for element:" + elementType
                        + " is not " + BPEL4PeopleConstants.B4P_NAMESPACE);
            }
            parseLocalTask(node);
        }
    } catch (FaultException fex) {
        throw fex;
    }
}