Example usage for org.w3c.dom Element getNodeName

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

Introduction

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

Prototype

public String getNodeName();

Source Link

Document

The name of this node, depending on its type; see the table above.

Usage

From source file:org.apache.sling.its.servlets.ItsServlet.java

/**
 * Process the child resource. Each child resource needs its own element
 * and append it to the document. After element has been created, the
 * attributes subsequently needs to be processed. However,
 * text-content-node resources do not need its own element. The
 * text-content property needs to be appended to the previous element.
 *
 * @param resource//from  w  w w. ja  v a 2 s.c o  m
 *          the current resource
 * @param element
 *          the current element
 * @param resourceType
 *          the resourceType provided by the root element
 */
private void processChild(final Resource resource, final Element element, final String resourceType) {
    final ValueMap valueMap = resource.adaptTo(ValueMap.class);
    final String prefix = valueMap.get(SlingItsConstants.NODE_PREFIX, String.class);
    final String name = getElementName(resource, prefix);
    final Document doc = element.getOwnerDocument();
    final Element el = doc.createElement(name);
    if (name.equals(SlingItsConstants.TEXT_CONTENT_NODE)) {
        final Text text = doc.createTextNode(valueMap.get(SlingItsConstants.TEXT_CONTENT, StringUtils.EMPTY));
        element.appendChild(text);
    } else if (name.endsWith(SlingItsConstants.ITS_RULES) && this.isHtml
            && !element.getNodeName().equals("script") && StringUtils.isNotBlank(prefix)) {
        final Element scriptElement = doc.createElement("script");
        scriptElement.setAttribute("type", "application/its+xml");
        element.appendChild(scriptElement);
        scriptElement.appendChild(el);
        processAttributes(resource, el);
    } else {
        element.appendChild(el);
        processAttributes(resource, el);
    }

    if (name.endsWith(SlingItsConstants.ITS_RULES) && StringUtils.isNotBlank(prefix)
            && StringUtils.isNotBlank(resourceType)) {
        for (final String globalRulePath : SlingItsConstants.getGlobalRules().values()) {
            final Iterator<Resource> globalRules = resource.getResourceResolver().findResources(
                    "SELECT * FROM [nt:base] as t WHERE ISCHILDNODE([" + globalRulePath + resourceType
                            + "]) AND t.[node-prefix] LIKE '" + prefix + "' ORDER BY name(t) ASC",
                    Query.JCR_SQL2);
            while (globalRules.hasNext()) {
                processChild(globalRules.next(), el, resourceType);
            }
        }
    } else {
        final Iterator<Resource> iter = resource.listChildren();
        while (iter.hasNext()) {
            processChild(iter.next(), el, resourceType);
        }
    }
}

From source file:org.apache.sling.its.servlets.ItsServlet.java

/**
 * Process the properties of the current resource. Every property of the
 * current resource needs to be outputted to the document with the
 * exception of properties with the jcr and sling prefix.
 *
 * To adhere to the w3c id rule, there will be an extra id property that
 * needs to be generated./*from   www .  jav  a  2  s .  co  m*/
 *
 * @param resource
 *          the current resource
 * @param element
 *          the current element
 */
private void processAttributes(final Resource resource, final Element element) {
    final Document doc = element.getOwnerDocument();
    final ValueMap props = resource.adaptTo(ValueMap.class);
    final List<String> namespaces = Arrays
            .asList(props.get(SlingItsConstants.NAMESPACE_DECLARATION, new String[] {}));
    for (final String key : props.keySet()) {
        if (isValidProperty(key)) {
            final String value = (String) props.get(key);
            if (SlingItsConstants.TEXT_CONTENT.equals(key)) {
                element.setTextContent(value);
            } else if (SlingItsConstants.ITS_NOTE.equals(key)
                    && element.getNodeName().endsWith(SlingItsConstants.ITS_LOCNOTE_RULE)) {
                final Element locNoteElement = doc
                        .createElement(props.get(SlingItsConstants.NODE_PREFIX, String.class) + ":locNote");
                locNoteElement.setTextContent(value);
                element.appendChild(locNoteElement);
            } else if (namespaces.contains(key)) {
                element.setAttribute(SlingItsConstants.XMLNS + key, value);
            } else if (this.isHtml && StringUtils.equals(key, SlingItsConstants.XML_PRIMARY_TYPE_PROP)
                    && (!props.keySet().contains(SlingItsConstants.NODE_PREFIX))) {
                element.setAttribute(SlingItsConstants.HTML_PRIMARY_TYPE_PROP, value);
            } else if (this.isHtml && StringUtils.equals(key, JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY)
                    && (!props.keySet().contains(SlingItsConstants.NODE_PREFIX))) {
                element.setAttribute(SlingItsConstants.HTML_RESOURCE_TYPE_PROP, value);
            } else {
                element.setAttribute(key, value);
            }
        }
    }
    if (!resource.getPath().startsWith(SlingItsConstants.ITS_GLOBAL_PATH)
            && !element.getNodeName().endsWith(SlingItsConstants.ITS_RULES) && !props.keySet().contains("id")
            && !props.keySet().contains("xml:id")) {
        element.setAttribute((this.isHtml ? "data-sling-its-id" : "sling-its:id"),
                getUniqueId(resource.getPath()));
    }
}

From source file:org.apache.sling.stanbol.ui.StanbolResourceViewer.java

private void setContent(Node jcrNode, String newContent) throws IOException, RepositoryException {

    try {//from  w  w  w. j ava 2s.  co  m
        Document doc = Utils.getXMLDocument(jcrNode);
        Element docElem = doc.getDocumentElement();
        if (docElem.getNodeName().equalsIgnoreCase("html")) {
            Element newBody = parseBody(newContent);
            Element body = (Element) doc.getElementsByTagName("body").item(0);
            org.w3c.dom.Node importedNewBody = doc.importNode(newBody, true);
            body.getParentNode().replaceChild(importedNewBody, body);
        } else {
            InputSource inputSource = new InputSource(new StringReader(newContent));
            Document newContentDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                    .parse(inputSource);
            docElem = newContentDoc.getDocumentElement();
        }
        DOMSource domSource = new DOMSource(docElem);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        //StringWriter out = new StringWriter();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        StreamResult streamResult = new StreamResult(baos);
        transformer.transform(domSource, streamResult);
        //jcrNode.setProperty("jcr:content/jcr:data", out.toString());
        jcrNode.getProperty("jcr:content/jcr:data").setValue(new String(baos.toByteArray(), "utf-8"));
        jcrNode.save();
    } catch (SAXException e) {
        throw new RuntimeException(e);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    } catch (TransformerConfigurationException e) {
        throw new RuntimeException(e);
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.sysml.conf.DMLConfig.java

/**
 * Get a map of key/value pairs of all configurations w/ the prefix 'mapred'
 * or 'mapreduce'./*from   ww w  .j a  v  a  2s .c om*/
 * 
 * @return map of mapred and mapreduce key/value pairs
 */
public Map<String, String> getCustomMRConfig() {
    HashMap<String, String> ret = new HashMap<String, String>();

    //check for non-existing config xml tree
    if (_xmlRoot == null)
        return ret;

    //get all mapred.* and mapreduce.* tag / value pairs      
    NodeList list = _xmlRoot.getElementsByTagName("*");
    for (int i = 0; list != null && i < list.getLength(); i++) {
        if (list.item(i) instanceof Element && (((Element) list.item(i)).getNodeName().startsWith(PREFIX_MAPRED)
                || ((Element) list.item(i)).getNodeName().startsWith(PREFIX_MAPREDUCE))) {
            Element elem = (Element) list.item(i);
            ret.put(elem.getNodeName(), elem.getFirstChild().getNodeValue());
        }
    }

    return ret;
}

From source file:org.apache.ws.scout.transport.SaajTransport.java

private SOAPMessage createSOAPMessage(Element elem) throws Exception {
    String prefix = "";
    MessageFactory msgFactory = MessageFactory.newInstance();
    SOAPFactory factory = SOAPFactory.newInstance();

    SOAPMessage message = msgFactory.createMessage();
    message.getSOAPHeader().detachNode();
    SOAPPart soapPart = message.getSOAPPart();
    SOAPBody soapBody = soapPart.getEnvelope().getBody();
    //Create the outer body element
    Name bodyName = factory.createName(elem.getNodeName(), prefix, UDDI_V2_NAMESPACE);
    SOAPBodyElement bodyElement = soapBody.addBodyElement(bodyName);
    bodyElement.addNamespaceDeclaration(prefix, UDDI_V2_NAMESPACE);
    appendAttributes(bodyElement, elem.getAttributes(), factory);
    appendElements(bodyElement, elem.getChildNodes(), factory);
    return message;
}

From source file:org.apache.ws.scout.transport.SaajTransport.java

private void appendElements(SOAPElement bodyElement, NodeList nlist, SOAPFactory factory) throws SOAPException {
    String prefix = "";
    int len = nlist != null ? nlist.getLength() : 0;
    for (int i = 0; i < len; i++) {
        Node node = nlist.item(i);
        short nodeType = node != null ? node.getNodeType() : -100;
        if (Node.ELEMENT_NODE == nodeType) {
            Element el = (Element) node;
            Name name = factory.createName(el.getNodeName(), prefix, UDDI_V2_NAMESPACE);
            SOAPElement attachedEl = bodyElement.addChildElement(name);
            appendAttributes(attachedEl, el.getAttributes(), factory);
            appendElements(attachedEl, el.getChildNodes(), factory);
        } else if (nodeType == Node.TEXT_NODE) {
            bodyElement.addTextNode(node.getNodeValue());
        }// w w  w.j av a2  s .  c  om
    }
}

From source file:org.apache.ws.security.util.WSSecurityUtil.java

/**
 * Search through a WSS4J results vector for a single signature covering all
 * these elements./*from   w ww .j a va  2s  .c om*/
 * 
 * NOTE: it is important that the given elements are those that are 
 * referenced using wsu:Id. When the signed element is referenced using a
 * transformation such as XPath filtering the validation is carried out 
 * in signature verification itself.
 * 
 * @param results results (e.g., as stored as WSHandlerConstants.RECV_RESULTS on
 *                an Axis MessageContext)
 * @param elements the elements to check
 * @return the identity of the signer
 * @throws WSSecurityException if no suitable signature could be found or if any element
 *                             didn't have a wsu:Id attribute
 */
public static X509Certificate ensureSignedTogether(Iterator results, Element[] elements)
        throws WSSecurityException {
    log.debug("ensureSignedTogether()");

    if (results == null) {
        throw new IllegalArgumentException("No results vector");
    }
    if (elements == null || elements.length == 0) {
        throw new IllegalArgumentException("No elements to check!");
    }

    // Turn the list of required elements into a list of required wsu:Id
    // strings
    String[] requiredIDs = new String[elements.length];
    for (int i = 0; i < elements.length; i++) {
        Element e = (Element) elements[i];
        if (e == null) {
            throw new IllegalArgumentException("elements[" + i + "] is null!");
        }
        requiredIDs[i] = e.getAttributeNS(WSConstants.WSU_NS, "Id");
        if (requiredIDs[i] == null) {
            throw new WSSecurityException(WSSecurityException.FAILED_CHECK, "requiredElementNoID",
                    new Object[] { e.getNodeName() });
        }
        log.debug("Required element " + e.getNodeName() + " has wsu:Id " + requiredIDs[i]);
    }

    WSSecurityException fault = null;

    // Search through the results for a SIGN result
    while (results.hasNext()) {
        WSHandlerResult result = (WSHandlerResult) results.next();
        Iterator actions = result.getResults().iterator();

        while (actions.hasNext()) {
            WSSecurityEngineResult resultItem = (WSSecurityEngineResult) actions.next();
            int resultAction = ((java.lang.Integer) resultItem.get(WSSecurityEngineResult.TAG_ACTION))
                    .intValue();

            if (resultAction == WSConstants.SIGN) {
                try {
                    checkSignsAllElements(resultItem, requiredIDs);
                    return (X509Certificate) resultItem.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
                } catch (WSSecurityException ex) {
                    // Store the exception but keep going... there may be a
                    // better signature later
                    log.debug("SIGN result does not sign all required elements", ex);
                    fault = ex;
                }
            }
        }
    }

    if (fault != null)
        throw fault;

    throw new WSSecurityException(WSSecurityException.FAILED_CHECK, "noSignResult");
}

From source file:org.apache.xml.security.samples.signature.CreateCollectableSignature.java

/**
 * Method main/*from  w  ww  .ja v a 2 s. c  o m*/
 *
 * @param unused
 * @throws Exception
 */
public static void main(String unused[]) throws Exception {
    //J-
    File signatureFile = new File("collectableSignature.xml");
    String BaseURI = signatureFile.toURL().toString();
    //J+
    javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();

    dbf.setNamespaceAware(true);

    javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
    org.w3c.dom.Document doc = db.newDocument();
    Element rootElement = doc.createElementNS(null, "root");

    doc.appendChild(rootElement);

    /*
    Element signedResourceElement = doc.createElementNS("http://custom/", "custom:signedContent");
    signedResourceElement.setAttributeNS(Constants.NamespaceNS, "xmlns:custom", "http://custom/");
    signedResourceElement.setAttributeNS(null, "Id", "id0");
    */
    Element signedResourceElement = doc.createElementNS(null, "signedContent");

    signedResourceElement.appendChild(doc.createTextNode("Signed Text\n"));
    rootElement.appendChild(signedResourceElement);

    XMLSignature sig = new XMLSignature(doc, BaseURI, XMLSignature.ALGO_ID_MAC_HMAC_SHA1);

    signedResourceElement.appendChild(sig.getElement());

    {
        String rootnamespace = signedResourceElement.getNamespaceURI();
        boolean rootprefixed = (rootnamespace != null) && (rootnamespace.length() > 0);
        String rootlocalname = signedResourceElement.getNodeName();
        Transforms transforms = new Transforms(doc);
        XPathContainer xpath = new XPathContainer(doc);

        xpath.setXPathNamespaceContext("ds", Constants.SignatureSpecNS);

        if (rootprefixed) {
            xpath.setXPathNamespaceContext("root", rootnamespace);
        }

        //J-
        String xpathStr = "\n" + "count(                                                                 "
                + "\n" + " ancestor-or-self::" + (rootprefixed ? "root:" : "") + rootlocalname + "" + "\n"
                + " |                                                                     " + "\n"
                + " here()/ancestor::" + (rootprefixed ? "root:" : "") + rootlocalname + "[1] " + "\n"
                + ") <= count(                                                             " + "\n"
                + " ancestor-or-self::" + (rootprefixed ? "root:" : "") + rootlocalname + "" + "\n"
                + ")                                                                      " + "\n"
                + " and                                                                   " + "\n"
                + "count(                                                                 " + "\n"
                + " ancestor-or-self::ds:Signature                                        " + "\n"
                + " |                                                                     " + "\n"
                + " here()/ancestor::ds:Signature[1]                                      " + "\n"
                + ") > count(                                                             " + "\n"
                + " ancestor-or-self::ds:Signature                                        " + "\n"
                + ")                                                                      " + "\n"

        ;
        //J+
        xpath.setXPath(xpathStr);
        transforms.addTransform(Transforms.TRANSFORM_XPATH, xpath.getElementPlusReturns());
        sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);
    }

    {
        sig.getKeyInfo().add(new KeyName(doc, CreateCollectableSignature.passphrase));
        System.out.println("Start signing");
        sig.sign(sig.createSecretKey(CreateCollectableSignature.passphrase.getBytes()));
        System.out.println("Finished signing");
    }

    FileOutputStream f = new FileOutputStream(signatureFile);

    XMLUtils.outputDOMc14nWithComments(doc, f);
    f.close();
    System.out.println("Wrote signature to " + BaseURI);

    SignedInfo s = sig.getSignedInfo();

    for (int i = 0; i < s.getSignedContentLength(); i++) {
        System.out.println("################ Signed Resource " + i + " ################");
        System.out.println(new String(s.getSignedContentItem(i)));
        System.out.println();
    }
}

From source file:org.apereo.portal.groups.ldap.LDAPGroupStore.java

protected void init(Document config) {
    this.groups = new HashMap();
    this.contexts = new SmartCache(120);
    config.normalize();/*from   w ww .  j a v a  2 s  .c  o m*/
    int refreshminutes = 120;
    Element root = config.getDocumentElement();
    NodeList nl = root.getElementsByTagName("config");
    if (nl.getLength() == 1) {
        Element conf = (Element) nl.item(0);
        Node cc = conf.getFirstChild();
        //NodeList cl= conf.getF.getChildNodes();
        //for(int i=0; i<cl.getLength(); i++){
        while (cc != null) {
            if (cc.getNodeType() == ELEMENT_NODE) {
                Element c = (Element) cc;
                c.normalize();
                Node t = c.getFirstChild();
                if (t != null && t.getNodeType() == Node.TEXT_NODE) {
                    String name = c.getNodeName();
                    String text = ((Text) t).getData();
                    //System.out.println(name+" = "+text);
                    if (name.equals("url")) {
                        url = text;
                    } else if (name.equals("logonid")) {
                        logonid = text;
                    } else if (name.equals("logonpassword")) {
                        logonpassword = text;
                    } else if (name.equals("keyfield")) {
                        keyfield = text;
                    } else if (name.equals("namefield")) {
                        namefield = text;
                    } else if (name.equals("usercontext")) {
                        usercontext = text;
                    } else if (name.equals("refresh-minutes")) {
                        try {
                            refreshminutes = Integer.parseInt(text);
                        } catch (Exception e) {
                        }
                    }
                }
            }
            cc = cc.getNextSibling();
        }
    } else {
        throw new RuntimeException("LDAPGroupStore: config file must contain one config element");
    }

    this.personkeys = new SmartCache(refreshminutes * 60);

    NodeList gl = root.getChildNodes();
    for (int j = 0; j < gl.getLength(); j++) {
        if (gl.item(j).getNodeType() == ELEMENT_NODE) {
            Element g = (Element) gl.item(j);
            if (g.getNodeName().equals("group")) {
                GroupShadow shadow = processXmlGroupRecursive(g);
                groups.put(shadow.key, shadow);
            }
        }
    }

}

From source file:org.apereo.portal.groups.ldap.LDAPGroupStore.java

protected GroupShadow processXmlGroupRecursive(Element groupElem) {
    GroupShadow shadow = new GroupShadow();
    shadow.key = groupElem.getAttribute("key");
    shadow.name = groupElem.getAttribute("name");
    //System.out.println("Loading configuration for group "+shadow.name);
    ArrayList subgroups = new ArrayList();
    NodeList nl = groupElem.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        if (nl.item(i).getNodeType() == ELEMENT_NODE) {
            Element e = (Element) nl.item(i);
            if (e.getNodeName().equals("group")) {
                GroupShadow sub = processXmlGroupRecursive(e);
                subgroups.add(sub);//from   ww  w .j  av  a2 s  .c  o  m
                groups.put(sub.key, sub);
            } else if (e.getNodeName().equals("entity-set")) {
                shadow.entities = new EntitySet(e);
            } else if (e.getNodeName().equals("description")) {
                e.normalize();
                Text t = (Text) e.getFirstChild();
                if (t != null) {
                    shadow.description = t.getData();
                }
            }
        }
    }
    shadow.subgroups = (GroupShadow[]) subgroups.toArray(new GroupShadow[0]);
    return shadow;
}