Example usage for org.dom4j QName QName

List of usage examples for org.dom4j QName QName

Introduction

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

Prototype

public QName(String name, Namespace namespace) 

Source Link

Usage

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

License:Open Source License

/**
 * Adds an xml element to the given parent and sets the appropriate namespace and 
 * prefix.<p>//from  w  ww.  j a  v  a2 s .  c o  m
 * 
 * @param parent the parent node to add the element
 * @param name the name of the new element
 * 
 * @return the created element with the given name which was added to the given parent
 */
public static Element addElement(Element parent, String name) {

    return parent.addElement(new QName(name, Namespace.get("D", DEFAULT_NAMESPACE)));
}

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

License:Open Source License

/**
 * Process a LOCK WebDAV request for the specified resource.<p>
 * //from  www . j  av  a2s.  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

/**
 * Process a PROPFIND WebDAV request for the specified resource.<p>
 * //ww w .j  a va  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
 */
protected void doPropfind(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    String path = getRelativePath(req);

    if (!m_listings) {

        // Get allowed methods
        StringBuffer methodsAllowed = determineMethodsAllowed(getRelativePath(req));

        resp.addHeader(HEADER_ALLOW, methodsAllowed.toString());
        resp.setStatus(CmsWebdavStatus.SC_METHOD_NOT_ALLOWED);
        return;
    }

    // Properties which are to be displayed.
    List<String> properties = new Vector<String>();

    // Propfind depth
    int depth = CmsRepositoryLockInfo.DEPTH_INFINITY_VALUE;

    // Propfind type
    int type = FIND_ALL_PROP;

    String depthStr = req.getHeader(HEADER_DEPTH);

    if (depthStr == null) {
        depth = CmsRepositoryLockInfo.DEPTH_INFINITY_VALUE;
    } else {
        if (depthStr.equals("0")) {
            depth = 0;
        } else if (depthStr.equals("1")) {
            depth = 1;
        } else if (depthStr.equalsIgnoreCase(DEPTH_INFINITY)) {
            depth = CmsRepositoryLockInfo.DEPTH_INFINITY_VALUE;
        }
    }

    Element propNode = null;

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

        // Get the root element of the document
        Element rootElement = document.getRootElement();
        @SuppressWarnings("unchecked")
        Iterator<Element> iter = rootElement.elementIterator();

        while (iter.hasNext()) {
            Element currentElem = iter.next();
            switch (currentElem.getNodeType()) {
            case Node.TEXT_NODE:
                break;
            case Node.ELEMENT_NODE:
                if (currentElem.getName().endsWith("prop")) {
                    type = FIND_BY_PROPERTY;
                    propNode = currentElem;
                }
                if (currentElem.getName().endsWith("propname")) {
                    type = FIND_PROPERTY_NAMES;
                }
                if (currentElem.getName().endsWith("allprop")) {
                    type = FIND_ALL_PROP;
                }
                break;
            default:
                break;
            }
        }
    } catch (Exception e) {
        // Most likely there was no content : we use the defaults.
    }

    if (propNode != null) {
        if (type == FIND_BY_PROPERTY) {
            @SuppressWarnings("unchecked")
            Iterator<Element> iter = propNode.elementIterator();
            while (iter.hasNext()) {
                Element currentElem = iter.next();
                switch (currentElem.getNodeType()) {
                case Node.TEXT_NODE:
                    break;
                case Node.ELEMENT_NODE:
                    String nodeName = currentElem.getName();
                    String propertyName = null;
                    if (nodeName.indexOf(':') != -1) {
                        propertyName = nodeName.substring(nodeName.indexOf(':') + 1);
                    } else {
                        propertyName = nodeName;
                    }
                    // href is a live property which is handled differently
                    properties.add(propertyName);
                    break;
                default:
                    break;
                }
            }
        }
    }

    boolean exists = m_session.exists(path);
    if (!exists) {

        resp.setStatus(CmsWebdavStatus.SC_NOT_FOUND);

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

        return;
    }

    I_CmsRepositoryItem item = null;
    try {
        item = m_session.getItem(path);
    } catch (CmsException e) {
        resp.setStatus(CmsWebdavStatus.SC_NOT_FOUND);
        return;
    }

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

    // Create multistatus object
    Document doc = DocumentHelper.createDocument();
    Element multiStatusElem = doc.addElement(new QName(TAG_MULTISTATUS, Namespace.get("D", DEFAULT_NAMESPACE)));

    if (depth == 0) {
        parseProperties(req, multiStatusElem, item, type, properties);
    } else {
        // The stack always contains the object of the current level
        Stack<I_CmsRepositoryItem> stack = new Stack<I_CmsRepositoryItem>();
        stack.push(item);

        // Stack of the objects one level below
        Stack<I_CmsRepositoryItem> stackBelow = new Stack<I_CmsRepositoryItem>();

        while ((!stack.isEmpty()) && (depth >= 0)) {

            I_CmsRepositoryItem currentItem = stack.pop();
            parseProperties(req, multiStatusElem, currentItem, type, properties);

            if ((currentItem.isCollection()) && (depth > 0)) {

                try {
                    List<I_CmsRepositoryItem> list = m_session.list(currentItem.getName());
                    Iterator<I_CmsRepositoryItem> iter = list.iterator();
                    while (iter.hasNext()) {
                        I_CmsRepositoryItem element = iter.next();
                        stackBelow.push(element);
                    }

                } catch (CmsException e) {

                    resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

                    if (LOG.isErrorEnabled()) {
                        LOG.error(Messages.get().getBundle().key(Messages.LOG_LIST_ITEMS_ERROR_1,
                                currentItem.getName()), e);
                    }

                    return;
                }
            }

            if (stack.isEmpty()) {
                depth--;
                stack = stackBelow;
                stackBelow = new Stack<I_CmsRepositoryItem>();
            }
        }
    }

    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  w w  .  j av  a 2  s.  com
 *
 * @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();
}

From source file:org.openflexo.docxparser.DocxQName.java

License:Open Source License

public static QName getQName(OpenXmlTag openXmlTag) {
    return new QName(openXmlTag.getTagName(), DocxXmlUtil.getNamespace(openXmlTag));
}

From source file:org.openxml4j.opc.internal.marshallers.ZipPartMarshaller.java

License:Apache License

/**
 * Save relationships into the part.//from  ww w  . ja v a2 s.c  om
 * 
 * @param rels
 *            The relationships collection to marshall.
 * @param relPartURI
 *            Part name of the relationship part to marshall.
 * @param zos
 *            Zip output stream in which to save the XML content of the
 *            relationships serialization.
 */
public static boolean marshallRelationshipPart(PackageRelationshipCollection rels, PackagePartName relPartName,
        ZipOutputStream zos) {
    // Building xml
    Document xmlOutDoc = DocumentHelper.createDocument();
    // make something like <Relationships
    // xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
    Namespace dfNs = Namespace.get("", PackageNamespaces.RELATIONSHIPS);
    Element root = xmlOutDoc.addElement(new QName(PackageRelationship.RELATIONSHIPS_TAG_NAME, dfNs));

    // <Relationship
    // TargetMode="External"
    // Id="rIdx"
    // Target="http://www.custom.com/images/pic1.jpg"
    // Type="http://www.custom.com/external-resource"/>

    URI sourcePartURI = PackagingURIHelper.getSourcePartUriFromRelationshipPartUri(relPartName.getURI());

    for (PackageRelationship rel : rels) {
        // L'lment de la relation
        Element relElem = root.addElement(PackageRelationship.RELATIONSHIP_TAG_NAME);

        // L'attribut ID
        relElem.addAttribute(PackageRelationship.ID_ATTRIBUTE_NAME, rel.getId());

        // L'attribut Type
        relElem.addAttribute(PackageRelationship.TYPE_ATTRIBUTE_NAME, rel.getRelationshipType());

        // L'attribut Target
        String targetValue;
        URI uri = rel.getTargetURI();
        if (rel.getTargetMode() == TargetMode.EXTERNAL) {
            // Save the target as-is - we don't need to validate it,
            //  alter it etc
            try {
                targetValue = URLEncoder.encode(uri.toString(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                targetValue = uri.toString();
            }

            // add TargetMode attribut (as it is external link external)
            relElem.addAttribute(PackageRelationship.TARGET_MODE_ATTRIBUTE_NAME, "External");
        } else {
            targetValue = PackagingURIHelper.relativizeURI(sourcePartURI, rel.getTargetURI()).getPath();
        }
        relElem.addAttribute(PackageRelationship.TARGET_ATTRIBUTE_NAME, targetValue);
    }

    xmlOutDoc.normalize();

    // String schemaFilename = Configuration.getPathForXmlSchema()+
    // File.separator + "opc-relationships.xsd";

    // Save part in zip
    ZipEntry ctEntry = new ZipEntry(
            ZipHelper.getZipURIFromOPCName(relPartName.getURI().toASCIIString()).getPath());
    try {
        // Cration de l'entre dans le fichier ZIP
        zos.putNextEntry(ctEntry);
        if (!StreamHelper.saveXmlInStream(xmlOutDoc, zos)) {
            return false;
        }
        zos.closeEntry();
    } catch (IOException e) {
        logger.error("Cannot create zip entry " + relPartName, e);
        return false;
    }
    return true; // success
}

From source file:org.openxml4j.opc.internal.unmarshallers.PackagePropertiesUnmarshaller.java

License:Apache License

private String loadCategory(Document xmlDoc) {
    Element el = xmlDoc.getRootElement().element(new QName(KEYWORD_CATEGORY, namespaceCP));
    if (el != null)
        return el.getStringValue();
    else//from  ww  w .  j  a  va  2s. c  o  m
        return null;
}

From source file:org.openxml4j.opc.internal.unmarshallers.PackagePropertiesUnmarshaller.java

License:Apache License

private String loadContentStatus(Document xmlDoc) {
    Element el = xmlDoc.getRootElement().element(new QName(KEYWORD_CONTENT_STATUS, namespaceCP));
    if (el != null)
        return el.getStringValue();
    else//w  w w  . j ava 2  s.  com
        return null;
}

From source file:org.openxml4j.opc.internal.unmarshallers.PackagePropertiesUnmarshaller.java

License:Apache License

private String loadContentType(Document xmlDoc) {
    Element el = xmlDoc.getRootElement().element(new QName(KEYWORD_CONTENT_TYPE, namespaceCP));
    if (el != null)
        return el.getStringValue();
    else/*from   w  w  w.  j  a  v  a 2  s .  c  o m*/
        return null;
}

From source file:org.openxml4j.opc.internal.unmarshallers.PackagePropertiesUnmarshaller.java

License:Apache License

private String loadCreated(Document xmlDoc) {
    Element el = xmlDoc.getRootElement().element(new QName(KEYWORD_CREATED, namespaceDcTerms));
    if (el != null)
        return el.getStringValue();
    else//w  w w.j  a  v a2  s .  c o m
        return null;
}