Example usage for org.dom4j Namespace get

List of usage examples for org.dom4j Namespace get

Introduction

In this page you can find the example usage for org.dom4j Namespace get.

Prototype

public static Namespace get(String uri) 

Source Link

Document

A helper method to return the Namespace instance for no prefix and the URI

Usage

From source file:org.onesocialweb.openfire.handler.activity.IQSubscribeInterceptor.java

License:Apache License

public void interceptPacket(Packet packet, Session session, boolean incoming, boolean processed)
        throws PacketRejectedException {

    // We only care for incoming IQ that have not yet been processed
    if (incoming && !processed && packet instanceof IQ) {

        final IQ iq = (IQ) packet;
        final JID fromJID = iq.getFrom();
        final JID toJID = iq.getTo();

        // Must be iq of type set and sent to remote users
        if (!iq.getType().equals(IQ.Type.set) || server.isLocal(toJID)) {
            return;
        }/*from   ww w  .jav a 2 s . co m*/

        // With a pubsub requests
        Element requestElement = iq.getChildElement();
        if (!requestElement.getNamespace().equals(Namespace.get("http://jabber.org/protocol/pubsub"))) {
            return;
        }

        // With a subscibe or unsubscribe command
        Element commandElement = requestElement.element("subscribe");
        if (commandElement == null) {
            commandElement = requestElement.element("unsubscribe");
            if (commandElement == null) {
                return;
            }
        }

        // Relating to the microblogging node
        Attribute nodeAttribute = commandElement.attribute("node");
        if (!(nodeAttribute != null && nodeAttribute.getValue().equals(PEPActivityHandler.NODE))) {
            return;
        }

        // Then we keep track of the subscribe/unsubscribe request
        if (commandElement.getName().equals("subscribe")) {
            ActivityManager.getInstance().subscribe(fromJID.toBareJID(), toJID.toBareJID());
        } else {
            ActivityManager.getInstance().unsubscribe(fromJID.toBareJID(), toJID.toBareJID());
        }

    }
}

From source file:org.onesocialweb.openfire.handler.relation.IQRelationSetupHandler.java

License:Apache License

@SuppressWarnings({ "deprecation", "unchecked" })
@Override/*from ww w.j  a va2  s . c om*/
public IQ handleIQ(IQ packet) throws UnauthorizedException {
    final JID sender = packet.getFrom();
    final JID recipient = packet.getTo();

    // Process the request inside a try/catch so that unhandled exceptions
    // (oufofbounds etc...) can trigger a server error and we can send a
    // error result packet
    try {

        // A valid request is an IQ of type set, 
        if (!packet.getType().equals(IQ.Type.set)) {
            IQ result = IQ.createResultIQ(packet);
            result.setChildElement(packet.getChildElement().createCopy());
            result.setError(PacketError.Condition.bad_request);
            return result;
        }

        // If a recipient is specified, it must be equal to the sender
        // bareJID
        if (recipient != null && !recipient.toString().equals(sender.toBareJID())) {
            IQ result = IQ.createResultIQ(packet);
            result.setChildElement(packet.getChildElement().createCopy());
            result.setError(PacketError.Condition.not_authorized);
            return result;
        }

        // Only a local user can publish an activity to his stream
        if (!userManager.isRegisteredUser(sender.getNode())) {
            IQ result = IQ.createResultIQ(packet);
            result.setChildElement(packet.getChildElement().createCopy());
            result.setError(PacketError.Condition.not_authorized);
            return result;
        }

        // A valid submit requets must contain one relation item
        Element request = packet.getChildElement();
        Iterator<Element> i_entry = request.elementIterator(
                QName.get(Onesocialweb.RELATION_ELEMENT, Namespace.get(Onesocialweb.NAMESPACE)));
        if (!i_entry.hasNext()) {
            IQ result = IQ.createResultIQ(packet);
            result.setChildElement(packet.getChildElement().createCopy());
            result.setError(PacketError.Condition.bad_request);
            return result;
        }

        // Parse the relation
        RelationDomReader reader = new PersistentRelationDomReader();
        Element e_entry = i_entry.next();
        PersistentRelation relation = (PersistentRelation) reader.readElement(new ElementAdapter(e_entry));
        Log.debug("IQRelationSetup received request: " + relation);

        // Setup the relation (this will also trigger the notification to the user)
        relationManager.setupRelation(sender.toBareJID(), relation);

        // Send a success result
        IQ result = IQ.createResultIQ(packet);
        return result;

    } catch (Exception e) {
        Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
        IQ result = IQ.createResultIQ(packet);
        result.setChildElement(packet.getChildElement().createCopy());
        result.setError(PacketError.Condition.internal_server_error);
        return result;
    }
}

From source file:org.onesocialweb.openfire.handler.relation.IQRelationUpdateHandler.java

License:Apache License

@SuppressWarnings({ "deprecation", "unchecked" })
@Override/*from   w  w w  .  j  a v a  2s  .  c o  m*/
public IQ handleIQ(IQ packet) throws UnauthorizedException {
    final JID sender = packet.getFrom();
    final JID recipient = packet.getTo();

    // Process the request inside a try/catch so that unhandled exceptions
    // (oufofbounds etc...) can trigger a server error and we can send a
    // error result packet
    try {

        // Only a local user can request to update a relation
        if (!userManager.isRegisteredUser(sender.getNode())) {
            IQ result = IQ.createResultIQ(packet);
            result.setChildElement(packet.getChildElement().createCopy());
            result.setError(PacketError.Condition.not_authorized);
            return result;
        }

        // A valid request is an IQ of type set, sent to the bare server
        if ((!packet.getType().equals(IQ.Type.set) || (recipient != null && recipient.getNode() != null))) {
            IQ result = IQ.createResultIQ(packet);
            result.setChildElement(packet.getChildElement().createCopy());
            result.setError(PacketError.Condition.bad_request);
            return result;
        }

        // A valid submit requets must contain one relation item
        Element request = packet.getChildElement();
        Iterator<Element> i_entry = request.elementIterator(
                QName.get(Onesocialweb.RELATION_ELEMENT, Namespace.get(Onesocialweb.NAMESPACE)));
        if (!i_entry.hasNext()) {
            IQ result = IQ.createResultIQ(packet);
            result.setChildElement(packet.getChildElement().createCopy());
            result.setError(PacketError.Condition.bad_request);
            return result;
        }

        // Parse the relation
        RelationDomReader reader = new PersistentRelationDomReader();
        Element e_entry = i_entry.next();
        PersistentRelation relation = (PersistentRelation) reader.readElement(new ElementAdapter(e_entry));
        Log.debug("IQRelationUpdate received request: " + relation);

        // Setup the relation (this will also trigger the notification to the user)
        relationManager.updateRelation(sender.toBareJID(), relation);

        // Send a success result
        IQ result = IQ.createResultIQ(packet);
        return result;

    } catch (Exception e) {
        Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
        IQ result = IQ.createResultIQ(packet);
        result.setChildElement(packet.getChildElement().createCopy());
        result.setError(PacketError.Condition.internal_server_error);
        return result;
    }
}

From source file:org.onosproject.drivers.huawei.util.DocumentConvertUtil.java

License:Apache License

/**
 * Convert To l3vpn Document./*from   w  w  w .j  av  a 2s. co  m*/
 *
 * @param rpcXmlns rpc element attribute xmlns
 * @param datastoreType Netconf Config Datastore Type
 * @param errorOperation error operation
 * @param configXmlns l3vpn element attribute xmlns
 * @param netconfL3vpn NetconfL3vpn
 * @return Document
 */
public static Document convertEditL3vpnDocument(String rpcXmlns, NetconfConfigDatastoreType datastoreType,
        String errorOperation, String configXmlns, NetconfL3vpn netconfL3vpn) {
    Document rpcDoc = convertRpcDocument(rpcXmlns);
    Document editDoc = convertEditConfigDocument(datastoreType, errorOperation);
    Document l3vpnDoc = DocumentHelper.createDocument();
    Element l3vpn = l3vpnDoc.addElement("l3vpn");
    l3vpn.add(Namespace.get(configXmlns));
    l3vpn.addAttribute("content-version", netconfL3vpn.contentVersion());
    l3vpn.addAttribute("format-version", netconfL3vpn.formatVersion());
    Element l3vpncommon = l3vpn.addElement("l3vpncomm");
    Element l3vpnInstances = l3vpncommon.addElement("l3vpnInstances");
    for (NetconfL3vpnInstance netconfL3vpnInstance : netconfL3vpn.l3vpnComm().l3vpninstances()
            .l3vpninstances()) {
        Element l3vpnInstance = l3vpnInstances.addElement("l3vpnInstance");
        l3vpnInstance.addAttribute("operation", netconfL3vpnInstance.operation());
        l3vpnInstance.addElement("vrfName").setText(netconfL3vpnInstance.vrfName());
        Element vpnInstAFs = l3vpnInstance.addElement("vpnInstAFs");
        for (NetconfVpnInstAF netconfVpnInstAF : netconfL3vpnInstance.vpnInstAFs().vpnInstAFs()) {
            Element vpnInstAF = vpnInstAFs.addElement("vpnInstAF");
            vpnInstAF.addElement("afType").setText(netconfVpnInstAF.afType());
            vpnInstAF.addElement("vrfRD").setText(netconfVpnInstAF.vrfRD());
            Element vpnTargets = vpnInstAF.addElement("vpnTargets");
            for (NetconfVpnTarget netconfVpnTarget : netconfVpnInstAF.vpnTargets().vpnTargets()) {
                Element vpnTarget = vpnTargets.addElement("vpnTarget");
                vpnTarget.addElement("vrfRTType").setText(netconfVpnTarget.vrfRTType());
                vpnTarget.addElement("vrfRTValue").setText(netconfVpnTarget.vrfRTValue());
            }
        }
        Element l3vpnIfs = l3vpnInstance.addElement("l3vpnIfs");
        for (NetconfL3vpnIf netconfL3vpnIf : netconfL3vpnInstance.l3vpnIfs().l3vpnIfs()) {
            Element l3vpnIf = l3vpnIfs.addElement("l3vpnIf");
            l3vpnIf.addAttribute("operation", netconfL3vpnIf.operation());
            l3vpnIf.addElement("ifName").setText(netconfL3vpnIf.ifName());
            l3vpnIf.addElement("ipv4Addr").setText(netconfL3vpnIf.ipv4Addr());
            l3vpnIf.addElement("subnetMask").setText(netconfL3vpnIf.subnetMask());
        }
    }
    editDoc.getRootElement().element("config").add(l3vpnDoc.getRootElement());
    rpcDoc.getRootElement().add(editDoc.getRootElement());
    return rpcDoc;
}

From source file:org.onosproject.drivers.huawei.util.DocumentConvertUtil.java

License:Apache License

/**
 * Convert To bgp Document.//from  ww w.java2 s. c  om
 *
 * @param rpcXmlns rpc element attribute xmlns
 * @param datastoreType Netconf Config Datastore Type
 * @param errorOperation error operation
 * @param configXmlns l3vpn element attribute xmlns
 * @param netconfBgp NetconfBgp
 * @return Document
 */
public static Document convertEditBgpDocument(String rpcXmlns, NetconfConfigDatastoreType datastoreType,
        String errorOperation, String configXmlns, NetconfBgp netconfBgp) {
    Document rpcDoc = convertRpcDocument(rpcXmlns);
    Document editDoc = convertEditConfigDocument(datastoreType, errorOperation);
    Document bgpDoc = DocumentHelper.createDocument();
    Element bgp = bgpDoc.addElement("bgp");
    bgp.add(Namespace.get(configXmlns));
    bgp.addAttribute("content-version", netconfBgp.contentVersion());
    bgp.addAttribute("format-version", netconfBgp.formatVersion());
    Element bgpcommon = bgp.addElement("bgpcomm");
    Element bgpVrfs = bgpcommon.addElement("bgpVrfs");
    for (NetconfBgpVrf netconfBgpVrf : netconfBgp.bgpcomm().bgpVrfs().bgpVrfs()) {
        Element bgpVrf = bgpVrfs.addElement("bgpVrf");
        bgpVrf.addAttribute("operation", netconfBgpVrf.operation());
        bgpVrf.addElement("vrfName").setText(netconfBgpVrf.vrfName());
        Element bgpVrfAFs = bgpVrf.addElement("bgpVrfAFs");
        for (NetconfBgpVrfAF netconfBgpVrfAF : netconfBgpVrf.bgpVrfAFs().bgpVrfAFs()) {
            Element bgpVrfAF = bgpVrfAFs.addElement("bgpVrfAF");
            bgpVrfAF.addElement("afType").setText(netconfBgpVrfAF.afType());
            Element importRoutes = bgpVrfAF.addElement("importRoutes");
            for (NetconfImportRoute netconfImportRoute : netconfBgpVrfAF.importRoutes().importRoutes()) {
                Element importRoute = importRoutes.addElement("importRoute");
                importRoute.addAttribute("operation", netconfImportRoute.operation());
                importRoute.addElement("importProtocol").setText(netconfImportRoute.importProtocol());
                importRoute.addElement("importProcessId").setText(netconfImportRoute.importProcessId());
            }
        }
    }
    editDoc.getRootElement().element("config").add(bgpDoc.getRootElement());
    rpcDoc.getRootElement().add(editDoc.getRootElement());
    return rpcDoc;
}

From source file:org.onosproject.drivers.huawei.util.DocumentConvertUtil.java

License:Apache License

/**
 * Convert To Rpc Document.//w  w  w . j  a v  a2  s .  c om
 *
 * @param xmlns xmlns
 * @return Document
 */
public static Document convertRpcDocument(String xmlns) {
    Document doc = DocumentHelper.createDocument();
    Element rpc = doc.addElement("rpc");
    rpc.add(Namespace.get(xmlns));
    return doc;
}

From source file:org.onosproject.yang.serializers.xml.XmlSerializerHandler.java

License:Apache License

/**
 * Returns the new element name by updating tag name and namespace.
 *
 * @param node YDT context node/*www .java 2s.  c o  m*/
 * @return new element name by updating tag name and namespace
 */
Element updateNameAndNamespace(DataNode node, Stack<Element> elementStack) {
    String nameSpace = null;
    String name = null;
    if (node.key() != null && node.key().schemaId() != null) {
        nameSpace = node.key().schemaId().namespace();
        name = node.key().schemaId().name();
    }

    if (elementStack.isEmpty()) {
        Element rootElement = DocumentHelper.createDocument().addElement(name);
        if (nameSpace != null) {
            rootElement.add(Namespace.get(nameSpace));
        }
        return rootElement;
    } else {
        /*
         * If element stack is not empty then root element is already
         * created.
         */
        Element xmlElement = elementStack.peek();
        Element newElement;
        if (nameSpace != null) {
            newElement = xmlElement.addElement(name, nameSpace);
        } else {
            newElement = xmlElement.addElement(name);
        }
        return newElement;
    }
}

From source file:org.onosproject.yms.app.ych.defaultcodecs.xml.DefaultXmlCodec.java

License:Apache License

/**
 * Returns the xml string from YDT.//from   w  w  w.j  a  va 2s .  co m
 *
 * @param ydtBuilder YDT builder
 * @return the xml string from YDT
 */
private String buildXmlForYdt(YdtBuilder ydtBuilder) {

    YdtExtendedBuilder extBuilder = (YdtExtendedBuilder) ydtBuilder;
    YdtExtendedContext rootNode = extBuilder.getRootNode();

    if (rootNode == null) {
        throw new YchException(E_YDT_ROOT_NODE);
    }

    // Creating the root element for xml.
    Element rootElement = DocumentHelper.createDocument().addElement(rootNode.getName());

    // Adding the name space if exist for root name.
    if (rootNode.getNamespace() != null) {
        rootElement.add(Namespace.get(rootNode.getNamespace()));
    }

    if (rootElement.getName().equals("config")) {
        rootElement.add(new Namespace("nc", "urn:ietf:params:xml:ns:netconf:base:1.0"));
    }

    // Adding the attribute if exist
    Map<String, String> tagAttrMap = extBuilder.getRootTagAttributeMap();
    if (tagAttrMap != null && !tagAttrMap.isEmpty()) {
        for (Map.Entry<String, String> attr : tagAttrMap.entrySet()) {
            rootElement.addAttribute(attr.getKey(), attr.getValue());
        }
    }

    XmlCodecYdtListener listener = new XmlCodecYdtListener(XML, rootNode);
    listener.getElementStack().push(rootElement);

    // Walk through YDT and build the xml.
    YdtExtendedWalker extWalker = new DefaultYdtWalker();
    extWalker.walk(listener, rootNode);

    return rootElement.asXML();
}

From source file:org.opencms.webdav.CmsWebdavServlet.java

License:Open Source License

/**
 * Process a LOCK WebDAV request for the specified resource.<p>
 * /*from   w ww. j  av a  2  s.  c o m*/
 * @param req the servlet request we are processing
 * @param resp the servlet response we are creating
 *
 * @throws IOException if an input/output error occurs
 */
@SuppressWarnings("unchecked")
protected void doLock(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    String path = getRelativePath(req);

    // Check if webdav is set to read only
    if (m_readOnly) {

        resp.setStatus(CmsWebdavStatus.SC_FORBIDDEN);

        if (LOG.isDebugEnabled()) {
            LOG.debug(Messages.get().getBundle().key(Messages.LOG_WEBDAV_READ_ONLY_0));
        }

        return;
    }

    // Check if resource is locked
    if (isLocked(req)) {

        resp.setStatus(CmsWebdavStatus.SC_LOCKED);

        if (LOG.isDebugEnabled()) {
            LOG.debug(Messages.get().getBundle().key(Messages.LOG_ITEM_LOCKED_1, path));
        }

        return;
    }

    CmsRepositoryLockInfo lock = new CmsRepositoryLockInfo();

    // Parsing depth header
    String depthStr = req.getHeader(HEADER_DEPTH);
    if (depthStr == null) {
        lock.setDepth(CmsRepositoryLockInfo.DEPTH_INFINITY_VALUE);
    } else {
        if (depthStr.equals("0")) {
            lock.setDepth(0);
        } else {
            lock.setDepth(CmsRepositoryLockInfo.DEPTH_INFINITY_VALUE);
        }
    }

    // Parsing timeout header
    int lockDuration = CmsRepositoryLockInfo.TIMEOUT_INFINITE_VALUE;
    lock.setExpiresAt(System.currentTimeMillis() + (lockDuration * 1000));

    int lockRequestType = LOCK_CREATION;

    Element lockInfoNode = null;

    try {
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(new InputSource(req.getInputStream()));

        // Get the root element of the document
        Element rootElement = document.getRootElement();
        lockInfoNode = rootElement;
    } catch (Exception e) {
        lockRequestType = LOCK_REFRESH;
    }

    if (lockInfoNode != null) {

        // Reading lock information
        Iterator<Element> iter = lockInfoNode.elementIterator();

        Element lockScopeNode = null;
        Element lockTypeNode = null;
        Element lockOwnerNode = null;

        while (iter.hasNext()) {
            Element currentElem = iter.next();
            switch (currentElem.getNodeType()) {
            case Node.TEXT_NODE:
                break;
            case Node.ELEMENT_NODE:
                String nodeName = currentElem.getName();
                if (nodeName.endsWith(TAG_LOCKSCOPE)) {
                    lockScopeNode = currentElem;
                }
                if (nodeName.endsWith(TAG_LOCKTYPE)) {
                    lockTypeNode = currentElem;
                }
                if (nodeName.endsWith(TAG_OWNER)) {
                    lockOwnerNode = currentElem;
                }
                break;
            default:
                break;
            }
        }

        if (lockScopeNode != null) {

            iter = lockScopeNode.elementIterator();
            while (iter.hasNext()) {
                Element currentElem = iter.next();
                switch (currentElem.getNodeType()) {
                case Node.TEXT_NODE:
                    break;
                case Node.ELEMENT_NODE:
                    String tempScope = currentElem.getName();
                    if (tempScope.indexOf(':') != -1) {
                        lock.setScope(tempScope.substring(tempScope.indexOf(':') + 1));
                    } else {
                        lock.setScope(tempScope);
                    }
                    break;
                default:
                    break;
                }
            }

            if (lock.getScope() == null) {

                // Bad request
                resp.setStatus(CmsWebdavStatus.SC_BAD_REQUEST);
            }

        } else {

            // Bad request
            resp.setStatus(CmsWebdavStatus.SC_BAD_REQUEST);
        }

        if (lockTypeNode != null) {

            iter = lockTypeNode.elementIterator();
            while (iter.hasNext()) {
                Element currentElem = iter.next();
                switch (currentElem.getNodeType()) {
                case Node.TEXT_NODE:
                    break;
                case Node.ELEMENT_NODE:
                    String tempType = currentElem.getName();
                    if (tempType.indexOf(':') != -1) {
                        lock.setType(tempType.substring(tempType.indexOf(':') + 1));
                    } else {
                        lock.setType(tempType);
                    }
                    break;
                default:
                    break;
                }
            }

            if (lock.getType() == null) {

                // Bad request
                resp.setStatus(CmsWebdavStatus.SC_BAD_REQUEST);
            }

        } else {

            // Bad request
            resp.setStatus(CmsWebdavStatus.SC_BAD_REQUEST);
        }

        if (lockOwnerNode != null) {

            iter = lockOwnerNode.elementIterator();
            while (iter.hasNext()) {
                Element currentElem = iter.next();
                switch (currentElem.getNodeType()) {
                case Node.TEXT_NODE:
                    lock.setOwner(lock.getOwner() + currentElem.getStringValue());
                    break;
                case Node.ELEMENT_NODE:
                    lock.setOwner(lock.getOwner() + currentElem.getStringValue());
                    break;
                default:
                    break;
                }
            }

            if (lock.getOwner() == null) {

                // Bad request
                resp.setStatus(CmsWebdavStatus.SC_BAD_REQUEST);
            }

        } else {
            lock.setOwner("");
        }

    }

    lock.setPath(path);
    lock.setUsername(m_username);

    if (lockRequestType == LOCK_REFRESH) {

        CmsRepositoryLockInfo currentLock = m_session.getLock(path);
        if (currentLock == null) {
            lockRequestType = LOCK_CREATION;
        }
    }

    if (lockRequestType == LOCK_CREATION) {

        try {

            if (LOG.isDebugEnabled()) {
                LOG.debug(Messages.get().getBundle().key(Messages.LOG_LOCK_ITEM_1, lock.getOwner()));
            }

            boolean result = m_session.lock(path, lock);
            if (result) {

                // Add the Lock-Token header as by RFC 2518 8.10.1
                // - only do this for newly created locks
                resp.addHeader(HEADER_LOCKTOKEN, "<opaquelocktoken:" + generateLockToken(req, lock) + ">");

                if (LOG.isDebugEnabled()) {
                    LOG.debug(Messages.get().getBundle().key(Messages.LOG_LOCK_ITEM_FAILED_0));
                }

            } else {

                resp.setStatus(CmsWebdavStatus.SC_LOCKED);

                if (LOG.isDebugEnabled()) {
                    LOG.debug(Messages.get().getBundle().key(Messages.LOG_LOCK_ITEM_SUCCESS_0));
                }

                return;
            }
        } catch (CmsVfsResourceNotFoundException rnfex) {
            resp.setStatus(CmsWebdavStatus.SC_NOT_FOUND);

            if (LOG.isDebugEnabled()) {
                LOG.debug(Messages.get().getBundle().key(Messages.LOG_ITEM_NOT_FOUND_1, path));
            }

            return;
        } catch (CmsSecurityException sex) {
            resp.setStatus(CmsWebdavStatus.SC_FORBIDDEN);

            if (LOG.isDebugEnabled()) {
                LOG.debug(Messages.get().getBundle().key(Messages.LOG_NO_PERMISSION_0));
            }

            return;
        } catch (CmsException ex) {
            resp.setStatus(CmsWebdavStatus.SC_INTERNAL_SERVER_ERROR);

            if (LOG.isErrorEnabled()) {
                LOG.error(Messages.get().getBundle().key(Messages.LOG_REPOSITORY_ERROR_2, "LOCK", path), ex);
            }

            return;
        }
    }

    // Set the status, then generate the XML response containing
    // the lock information
    Document doc = DocumentHelper.createDocument();
    Element propElem = doc.addElement(new QName(TAG_PROP, Namespace.get(DEFAULT_NAMESPACE)));

    Element lockElem = addElement(propElem, TAG_LOCKDISCOVERY);
    addLockElement(lock, lockElem, generateLockToken(req, lock));

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

    Writer writer = resp.getWriter();
    doc.write(writer);
    writer.close();
}

From source file:org.opencms.webdav.CmsWebdavServlet.java

License:Open Source License

/**
 * Send a multistatus element containing a complete error report to the
 * client.<p>/* w ww  . j a va2s.  c  om*/
 *
 * @param req the servlet request we are processing
 * @param resp the servlet response we are processing
 * @param errors the errors to be displayed
 * 
 * @throws IOException if errors while writing to response occurs
 */
private void sendReport(HttpServletRequest req, HttpServletResponse resp, Map<String, Integer> errors)
        throws IOException {

    resp.setStatus(CmsWebdavStatus.SC_MULTI_STATUS);

    String absoluteUri = req.getRequestURI();
    String relativePath = getRelativePath(req);

    Document doc = DocumentHelper.createDocument();
    Element multiStatusElem = doc.addElement(new QName(TAG_MULTISTATUS, Namespace.get(DEFAULT_NAMESPACE)));

    Iterator<Entry<String, Integer>> it = errors.entrySet().iterator();
    while (it.hasNext()) {
        Entry<String, Integer> e = it.next();
        String errorPath = e.getKey();
        int errorCode = e.getValue().intValue();

        Element responseElem = addElement(multiStatusElem, TAG_RESPONSE);

        String toAppend = errorPath.substring(relativePath.length());
        if (!toAppend.startsWith("/")) {
            toAppend = "/" + toAppend;
        }
        addElement(responseElem, TAG_HREF).addText(absoluteUri + toAppend);
        addElement(responseElem, TAG_STATUS)
                .addText("HTTP/1.1 " + errorCode + " " + CmsWebdavStatus.getStatusText(errorCode));
    }

    Writer writer = resp.getWriter();
    doc.write(writer);
    writer.close();
}