Example usage for org.dom4j Node getName

List of usage examples for org.dom4j Node getName

Introduction

In this page you can find the example usage for org.dom4j Node getName.

Prototype

String getName();

Source Link

Document

getName returns the name of this node.

Usage

From source file:org.danann.cernunnos.xml.AppendNodeTask.java

License:Apache License

@SuppressWarnings("unchecked")
public void perform(TaskRequest req, TaskResponse res) {

    // Figure out where to put the content...
    Branch p = null;/*ww  w  . ja v a2s .  c o m*/
    int index;
    if (sibling != null) {
        Node sib = (Node) sibling.evaluate(req, res);
        p = sib.getParent();
        index = p.indexOf(sib) + 1;
    } else {
        // Work from the PARENT...
        p = (Branch) parent.evaluate(req, res);
        index = p.content().size();
    }

    // Figure out what content to add...
    List list = null;
    if (content != null && content.size() > 0) {
        list = content;
    } else {
        list = new LinkedList();
        list.add(node.evaluate(req, res));
    }

    // Evaluate phrases & add...
    for (Object o : list) {

        Node n = (Node) ((Node) o).clone();
        NodeProcessor.evaluatePhrases(n, grammar, req, res);

        // If the parent is an element, check if we should
        // carry the parent namespace over to the child...
        if ((Boolean) apply_namespace.evaluate(req, res) && p.getNodeType() == Node.ELEMENT_NODE
                && !((Element) p).getNamespace().equals(Namespace.NO_NAMESPACE)) {
            // We know the parent is an Element w/ a namespace,
            // is the child (also) an Element w/ none?
            if (n.getNodeType() == Node.ELEMENT_NODE
                    && ((Element) n).getNamespace().equals(Namespace.NO_NAMESPACE)) {
                // Yes -- we need to port the namespace forward...
                Namespace nsp = ((Element) p).getNamespace();
                if (log.isTraceEnabled()) {
                    StringBuffer msg = new StringBuffer();
                    msg.append("Adding the following namespace to <").append(n.getName()).append(">:  ")
                            .append(nsp);
                    log.trace(msg.toString());
                }
                NodeProcessor.applyNamespace(nsp, (Element) n);
            }
        }

        // Although they *are* nodes, attributes are not technically
        // content, and therefore they must have special treatment...
        if (p.getNodeType() == Node.ELEMENT_NODE && n.getNodeType() == Node.ATTRIBUTE_NODE) {
            // Add attributes by calling addAttribute on the Element contract...
            ((Element) p).add((Attribute) n);
        } else {
            // Add everything else as 'content'...
            p.content().add(index++, n);
        }

    }

}

From source file:org.danann.cernunnos.xml.PrependNodeTask.java

License:Apache License

@SuppressWarnings("unchecked")
public void perform(TaskRequest req, TaskResponse res) {

    // Figure out where to put the content...
    Branch p = null;//  ww w. ja  v  a 2s  .com
    int index;
    if (sibling != null) {
        Node sib = (Node) sibling.evaluate(req, res);
        p = sib.getParent();
        index = p.indexOf(sib);
    } else {
        // Work from the PARENT...
        p = (Branch) parent.evaluate(req, res);
        index = 0;
    }

    // Figure out what content to add...
    List list = null;
    if (content != null && content.size() > 0) {
        list = content;
    } else {
        list = new LinkedList();
        list.add(node.evaluate(req, res));
    }

    // Evaluate phrases & add...
    for (Object o : list) {

        Node n = (Node) ((Node) o).clone();
        NodeProcessor.evaluatePhrases(n, grammar, req, res);

        // If the parent is an element, check if we should
        // carry the parent namespace over to the child...
        if ((Boolean) apply_namespace.evaluate(req, res) && p.getNodeType() == Node.ELEMENT_NODE
                && !((Element) p).getNamespace().equals(Namespace.NO_NAMESPACE)) {
            // We know the parent is an Element w/ a namespace,
            // is the child (also) an Element w/ none?
            if (n.getNodeType() == Node.ELEMENT_NODE
                    && ((Element) n).getNamespace().equals(Namespace.NO_NAMESPACE)) {
                // Yes -- we need to port the namespace forward...
                Namespace nsp = ((Element) p).getNamespace();
                if (log.isTraceEnabled()) {
                    StringBuffer msg = new StringBuffer();
                    msg.append("Adding the following namespace to <").append(n.getName()).append(">:  ")
                            .append(nsp);
                    log.trace(msg.toString());
                }
                NodeProcessor.applyNamespace(nsp, (Element) n);
            }
        }

        // Although they *are* nodes, attributes are not technically
        // content, and therefore they must have special treatment...
        if (p.getNodeType() == Node.ELEMENT_NODE && n.getNodeType() == Node.ATTRIBUTE_NODE) {
            // Add attributes by calling addAttribute on the Element contract...
            ((Element) p).add((Attribute) n);
        } else {
            // Add everything else as 'content'...
            p.content().add(index++, n);
        }

    }

}

From source file:org.dommons.dom.dom4j.XDom4jNode.java

License:Open Source License

/**
 * ??//w  w w  . ja  v a2 s.c  o  m
 * @param parent 
 * @param name ???
 * @return 
 */
private static Element element(Branch parent, String name) {
    for (Iterator<Node> it = parent.nodeIterator(); it.hasNext();) {
        Node node = it.next();
        if (node.getNodeType() == Node.ELEMENT_NODE && name.equals(node.getName()))
            return (Element) node;
    }
    return null;
}

From source file:org.dommons.dom.dom4j.XDom4jNode.java

License:Open Source License

public List<XElement> elements(String... names) {
    Branch ele = element(names, 0, -1);/*from   w w w.  j  a  v  a2 s.  com*/
    List<XElement> list = new ArrayList();
    if (ele != null) {
        for (Iterator<Node> it = ele.nodeIterator(); it.hasNext();) {
            Node node = it.next();
            if (node.getNodeType() == Node.ELEMENT_NODE && names[names.length - 1].equals(node.getName()))
                list.add(new XDom4jElement((Element) node));
        }
    }
    return list;
}

From source file:org.efaps.webdav4vfs.handler.LockHandler.java

License:Apache License

@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    FileObject object = VFSBackend.resolveFile(request.getPathInfo());

    try {//from   w  ww.j  a v a2  s . c o  m
        final LockManager manager = LockManager.getInstance();
        final LockManager.EvaluationResult evaluation = manager.evaluateCondition(object, getIf(request));
        if (!evaluation.result) {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        } else {
            if (!evaluation.locks.isEmpty()) {
                LOG.debug(String.format("discovered locks: %s", evaluation.locks));
                sendLockAcquiredResponse(response, evaluation.locks.get(0));
                return;
            }
        }
    } catch (LockConflictException e) {
        List<Lock> locks = e.getLocks();
        for (Lock lock : locks) {
            if (Lock.EXCLUSIVE.equals(lock.getType())) {
                response.sendError(SC_LOCKED);
                return;
            }
        }
    } catch (ParseException e) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    try {
        SAXReader saxReader = new SAXReader();
        Document lockInfo = saxReader.read(request.getInputStream());
        //log(lockInfo);

        Element rootEl = lockInfo.getRootElement();
        String lockScope = null, lockType = null;
        Object owner = null;
        Iterator<?> elIt = rootEl.elementIterator();
        while (elIt.hasNext()) {
            Element el = (Element) elIt.next();
            if (TAG_LOCKSCOPE.equals(el.getName())) {
                lockScope = el.selectSingleNode("*").getName();
            } else if (TAG_LOCKTYPE.equals(el.getName())) {
                lockType = el.selectSingleNode("*").getName();
            } else if (TAG_OWNER.equals(el.getName())) {
                // TODO correctly handle owner
                Node subEl = el.selectSingleNode("*");
                if (subEl != null && TAG_HREF.equals(subEl.getName())) {
                    owner = new URL(el.selectSingleNode("*").getText());
                } else {
                    owner = el.getText();
                }
            }
        }

        LOG.debug("LOCK(" + lockType + ", " + lockScope + ", " + owner + ")");

        Lock requestedLock = new Lock(object, lockType, lockScope, owner, getDepth(request),
                getTimeout(request));
        try {
            LockManager.getInstance().acquireLock(requestedLock);
            sendLockAcquiredResponse(response, requestedLock);
        } catch (LockConflictException e) {
            response.sendError(SC_LOCKED);
        } catch (IllegalArgumentException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        }
    } catch (DocumentException e) {
        e.printStackTrace();
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:org.esupportail.lecture.domain.model.ChannelConfig.java

/**
 * Check syntax file that cannot be checked by DTD.
 * @param xmlFileChecked//w w w .j  a v a 2 s.  co m
 * @return xmlFileLoading
 */
@SuppressWarnings("unchecked")
private synchronized static Document checkConfigFile(Document xmlFileChecked) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("checkXmlFile()");
    }
    // Merge categoryProfilesUrl and check number of contexts + categories
    Document xmlFileLoading = xmlFileChecked;
    Element channelConfig = xmlFileLoading.getRootElement();
    List<Element> contexts = channelConfig.selectNodes("context");
    nbContexts = contexts.size();
    if (nbContexts == 0) {
        LOG.warn("No context declared in channel config (esup-lecture.xml)");
    }

    // 1. merge categoryProfilesUrls and refCategoryProfile
    for (Element context : contexts) {
        List<Node> nodes = context.selectNodes("categoryProfilesUrl|refCategoryProfile");
        for (Node node : nodes) {
            //Is a refCategoryProfile ?
            if (node.getName().equals("refCategoryProfile")) {
                //remove from context (from its current place in original XML file)
                context.remove(node);
                //add to context (at the end of new constructed context: With merged refCategoryProfile from categoryProfilesUrl)
                context.add(node);
            } else {
                String categoryProfilesUrlPath = node.valueOf("@url");
                //URL url = ChannelConfig.class.getResource(categoryProfilesUrlPath);
                String idPrefix = node.valueOf("@idPrefix");
                if ((categoryProfilesUrlPath == null) || (categoryProfilesUrlPath == "")) {
                    String errorMsg = "URL of : categoryProfilesUrl with prefix " + idPrefix
                            + " is null or empty.";
                    LOG.warn(errorMsg);
                } else {
                    Document categoryProfilesFile = getFreshConfigFile(categoryProfilesUrlPath);
                    if (categoryProfilesFile == null) {
                        String errorMsg = "Impossible to load categoryProfilesUrl " + categoryProfilesUrlPath;
                        LOG.warn(errorMsg);
                    } else {
                        // merge one categoryProfilesUrl
                        // add categoryProfile
                        Element rootCategoryProfilesFile = categoryProfilesFile.getRootElement();
                        // replace ids with IdPrefix + "-" + id
                        List<Element> categoryProfiles = rootCategoryProfilesFile.elements();
                        for (Element categoryProfile : categoryProfiles) {
                            String categoryProfileId = idPrefix + "-" + categoryProfile.valueOf("@id");
                            //String categoryProfileName = categoryProfile.valueOf("@name");
                            categoryProfile.addAttribute("id", categoryProfileId);
                            Element categoryProfileAdded = categoryProfile.createCopy();
                            channelConfig.add(categoryProfileAdded);
                            // delete node categoryProfilesUrl ?
                            // add refCategoryProfile
                            context.addElement("refCategoryProfile").addAttribute("refId", categoryProfileId);
                        }
                    }
                }
                //remove now unneeded categoryProfilesUrl
                context.remove(node);
            }
        }
    }
    List<Node> categoryProfiles = channelConfig.selectNodes("categoryProfile");
    nbProfiles = categoryProfiles.size();
    if (nbProfiles == 0) {
        LOG.warn("checkXmlConfig :: No managed category profile declared in channel config");
    }
    return xmlFileLoading;

}

From source file:org.firesoa.common.jxpath.model.dom4j.Dom4JNodePointer.java

License:Open Source License

public static String getLocalName(Node node) {
    return node.getName();
}

From source file:org.jboss.as.quickstart.xml.DOM4JXMLParser.java

License:Apache License

@Override
public List<Book> parseInternal(InputStream is) throws Exception {

    Document document = this.dom4jReader.read(is);

    List<Book> catalog = new ArrayList<Book>();
    Element root = document.getRootElement();
    if (!root.getQName().getName().equals("catalog")) {
        throw new RuntimeException("Wrong element: " + root.getQName());
    }//from w ww  .  j  av  a 2 s  .c  o  m

    Iterator children = root.elementIterator();
    while (children.hasNext()) {
        Node n = (Node) children.next();
        String childName = n.getName();
        if (childName == null)
            continue;

        if (childName.equals("book")) {
            Book b = parseBook((Element) n);
            catalog.add(b);
        }
    }

    return catalog;

}

From source file:org.jboss.as.quickstart.xml.DOM4JXMLParser.java

License:Apache License

private Book parseBook(Element n) {
    Book b = new Book();
    Iterator children = n.elementIterator();
    /*/*from   w w  w  . j a  v a2s  . c  o m*/
     * parse book element, we have to once more iterate over children.
     */
    while (children.hasNext()) {
        Node child = (Node) children.next();
        String childName = child.getName();
        // empty/text nodes dont have name
        if (childName == null)
            continue;

        if (childName.equals("author")) {
            Element childElement = (Element) child;

            String textVal = childElement.getTextTrim();
            b.setAuthor(textVal);
        } else if (childName.equals("title")) {
            Element childElement = (Element) child;

            String textVal = childElement.getTextTrim();
            b.setTitle(textVal);
        } else if (childName.equals("genre")) {
            Element childElement = (Element) child;

            String textVal = childElement.getTextTrim();
            b.setGenre(textVal);
        } else if (childName.equals("price")) {
            Element childElement = (Element) child;

            String textVal = childElement.getTextTrim();
            b.setPrice(Float.parseFloat(textVal));
        } else if (childName.equals("publish_date")) {
            Element childElement = (Element) child;

            String textVal = childElement.getTextTrim();
            Date d;
            try {

                d = DATE_FORMATTER.parse(textVal);
                b.setPublishDate(d);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }

        } else if (childName.equals("description")) {
            Element childElement = (Element) child;
            String textVal = childElement.getTextTrim();
            b.setDescription(textVal);
        }

    }

    return b;
}

From source file:org.jboss.jaxr.servlet.SAAJServlet.java

License:LGPL

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    SOAPMessage msg = null;/*from   ww w  . ja  v  a2s .  c o m*/
    SOAPMessage soapResponse = null;
    try {
        MessageFactory factory = MessageFactory.newInstance();
        MimeHeaders headers = new MimeHeaders();
        Enumeration names = request.getHeaderNames();
        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            Enumeration values = request.getHeaders(name);
            while (values.hasMoreElements()) {
                String value = (String) values.nextElement();
                headers.addHeader(name, value);
            }
        }

        InputStream is = request.getInputStream();
        ByteArrayOutputStream copy = new ByteArrayOutputStream(is.available());
        byte[] tmp = new byte[1024];
        int length;
        while ((length = is.read(tmp)) > 0) {
            copy.write(tmp, 0, length);
        }
        copy.close();
        byte[] msgBytes = copy.toByteArray();
        msg = factory.createMessage(headers, new ByteArrayInputStream(msgBytes));

        /* Firstly we put save the attached repository items in a map. Later
         we will remove the attachments.
         */
        HashMap idToRepositoryItemMap = new HashMap();

        //Now get any repository items that may be attached
        Iterator apIter = msg.getAttachments();
        while (apIter.hasNext()) {
            AttachmentPart ap = (AttachmentPart) apIter.next();
            //Get the DSIG and content for the attachment
            RepositoryItem ri = processAttachment(ap);
            idToRepositoryItemMap.put(ri.getId(), ri);
        }

        /*
        Due to the suspected bugs in JAXM, we have to call writeTo method of the
        input message that has been received to write the content
        to a ByteArrayOutputStream and re-instantiate another SOAPMessage
        to make the XML signature properly verified.
         */

        /*
        If we do not remove the attachment, the SOAPMessage.writeTo() mehtod
        will output a MIME-encoded form of the message, not pure SOAP part.
         */
        if (msg.countAttachments() > 0) {
            msg.removeAllAttachments();
            if (msg.saveRequired()) {
                msg.saveChanges();
            }
        }

        copy = new ByteArrayOutputStream(copy.size());
        msg.writeTo(copy);
        copy.close();
        msgBytes = copy.toByteArray();
        msg = Utility.getInstance().createSOAPMessageFromSOAPStream(new ByteArrayInputStream(msgBytes));

        // Get the header signature (if any) from the SOAPHeader
        XMLSignature headerSignature = SecurityUtil.getInstance().verifySOAPMessage(msg);

        //System.err.println("Getting ebXML Registry request");

        SAXReader xmlReader = new SAXReader();
        Document xmlDoc = xmlReader.read(new ByteArrayInputStream(msgBytes));
        List soapBody = xmlDoc.selectNodes("//soap-env:Body/*");
        if (soapBody.size() != 1) {
            throw new RegistryException("InvalidRequest: must have one child element");
        }

        Node requestNode = (Node) soapBody.get(0);
        String requestRootElement = requestNode.getName();

        /*
        SOAPPart sp = msg.getSOAPPart();
        SOAPEnvelope se = sp.getEnvelope(); //<-------------------------------
        SOAPBody sb = se.getBody();
        SOAPElement requestElement = null;
        Iterator iter = sb.getChildElements();
        String requestRootElement = null;
        int i = 0;
        while (iter.hasNext())
        {
           Object obj = iter.next();
           if (!(obj instanceof SOAPElement))
           {
              continue;
           }
                
           if (i++ == 0)
           {
              requestElement = (SOAPElement) obj;
              Name name = requestElement.getElementName();
              requestRootElement = name.getLocalName();
           }
           else
           {
              throw new RegistryException("InvalidRequest: Cannot have more than one child element");
           }
        }
        */
        Object requestObj = getRequestObject(requestRootElement, requestNode);
        Request ebxmlRequest = new Request(headerSignature, requestObj, idToRepositoryItemMap);

        Response ebxmlResponse = ebxmlRequest.process();
        soapResponse = createResponseSOAPMessage(ebxmlResponse);
        if (ebxmlRequest.getMessage() instanceof GetContentRequest
                && ebxmlResponse.getMessage().getStatus().getType() == StatusType.SUCCESS_TYPE) {
            ObjectRefListItem[] items = ((GetContentRequest) ebxmlRequest.getMessage()).getObjectRefList()
                    .getObjectRefListItem();
            for (int j = 0; j < items.length; j++) {
                String id = items[j].getObjectRef().getId();
                if (id.startsWith("urn:uuid:")) {
                    id = id.substring(9);
                }

                RepositoryItem repositoryItem = RepositoryManagerFactory.getInstance().getRepositoryManager()
                        .getRepositoryItem(id);

                DataHandler contentDataHandler = repositoryItem.getDataHandler();

                String xmlsigStr = repositoryItem.signatureToString();

                MimeMultipart mp = new MimeMultipart();

                // Payload signature
                MimeBodyPart bp1 = new MimeBodyPart();
                // Can't set
                bp1.setHeader("Content-Type", "text/xml; charset=UTF-8");
                // Can't set
                bp1.addHeader("Content-Transfer-Encoding", "8bit");
                bp1.setHeader("Content-ID", "payload1");
                bp1.setContent(xmlsigStr, "text/plain");
                mp.addBodyPart(bp1);

                // Repository item
                MimeBodyPart bp2 = new MimeBodyPart();
                bp2.setDataHandler(contentDataHandler);
                bp2.setHeader("Content-Type", contentDataHandler.getContentType());
                bp2.setHeader("Content-ID", "payload2");
                mp.addBodyPart(bp2);

                AttachmentPart ap = soapResponse.createAttachmentPart(mp, "multipart/related");
                // Can't add type=text/xml; start="urn:uuid:1234567" ??
                ap.setContentType(ap.getContentType() + "; type=text/xml; start=\"urn:uuid:" + id + "\"");
                // Not in spec??
                ap.setContentId("urn:uuid:" + id);

                ContentType contentTypeMP = new ContentType(mp.getContentType());

                String boundary = contentTypeMP.getParameter("boundary");
                ContentType contentType = new ContentType("multipart/related");
                contentType.setParameter("boundary", boundary);
                ap.setContentType(contentType.toString());
                soapResponse.addAttachmentPart(ap);
            }
        }

        soapResponse.saveChanges();
    } catch (RegistryException e) {
        log.error("Caught exception: " + e.getMessage(), e);
        soapResponse = createResponseSOAPMessage(e);
    } catch (SOAPException e) {
        log.error("Caught exception: " + e.getMessage(), e);
        soapResponse = createResponseSOAPMessage(e);
    } catch (MessagingException e) {
        log.error("Caught exception: " + e.getMessage(), e);
        soapResponse = createResponseSOAPMessage(e);
    } catch (Exception e) {
        log.error("Caught exception: " + e.getMessage(), e);
        soapResponse = createResponseSOAPMessage(e);
    } catch (Throwable t) {
        log.error("Caught exception: " + t.getMessage(), t);
        soapResponse = createResponseSOAPMessage(t);
    }

    try {
        // Need to saveChanges 'cos we're going to use the
        // MimeHeaders to set HTTP response information. These
        // MimeHeaders are generated as part of the save.
        if (soapResponse.saveRequired()) {
            soapResponse.saveChanges();
        }

        response.setStatus(HttpServletResponse.SC_OK);

        putHeaders(soapResponse.getMimeHeaders(), response);

        OutputStream os = response.getOutputStream();
        soapResponse.writeTo(os);
        os.flush();
    } catch (Throwable t) {
        throw new ServletException("Failed to write SOAP response", t);
    }
}