Example usage for org.dom4j Document setRootElement

List of usage examples for org.dom4j Document setRootElement

Introduction

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

Prototype

void setRootElement(Element rootElement);

Source Link

Document

Sets the root element for this document

Usage

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

License:Open Source License

@Override
public void setValue(Object value) {
    if (value == null)
        value = "";//null??
    if ((node instanceof org.dom4j.CharacterData || node instanceof Attribute || node instanceof DocumentType
            || node instanceof Entity || node instanceof ProcessingInstruction)) {
        String string = (String) TypeUtils.convert(value, String.class);
        if (string != null && !string.equals("")) {
            ((Node) node).setText(string);
        } else {//from  www .  j a va  2 s  . co m
            ((Node) node).getParent().remove((Node) node);
        }
    } else if (node instanceof Document) {
        Document theOriginalDoc = (Document) node;
        Element theOrigialRoot = theOriginalDoc.getRootElement();

        if (value instanceof Document) {//?document

            Document valueDoc = (Document) value;
            Element valueRoot = valueDoc.getRootElement();

            if (theOrigialRoot == null || valueRoot == null
                    || theOrigialRoot.getQName().equals(valueRoot.getQName())) {

                theOriginalDoc.clearContent();

                List content = valueDoc.content();
                if (content != null) {
                    for (int i = 0; i < content.size(); i++) {
                        Node dom4jNode = (Node) content.get(i);
                        Node newDom4jNode = (Node) dom4jNode.clone();
                        theOriginalDoc.add(newDom4jNode);
                    }
                }
            } else {
                throw new RuntimeException(
                        "Can NOT assign " + valueRoot.getQName() + " to " + theOrigialRoot.getQName());

            }

        } else if (value instanceof Element) {
            Element valueElem = (Element) value;
            if (valueElem.getQName().equals(theOrigialRoot.getQName())) {
                theOriginalDoc.clearContent();
                Element newValueElem = (Element) valueElem.clone();
                theOriginalDoc.setRootElement(newValueElem);
            } else {
                throw new RuntimeException(
                        "Can NOT assign " + valueElem.getQName() + " to " + theOrigialRoot.getQName());
            }
        } else {
            throw new RuntimeException("Can NOT assign " + value + " to " + theOrigialRoot.getQName());

        }
        //         else if (value instanceof Comment){
        //            Comment cmmt = (Comment)((Comment)value).clone();
        //            theOriginalDoc.add(cmmt);
        //            
        //         }else if (value instanceof ProcessingInstruction){
        //            ProcessingInstruction instru = (ProcessingInstruction)((ProcessingInstruction)value).clone();
        //            theOriginalDoc.add(instru);
        //         }

    } else if (node instanceof Element) {
        Element originalElem = ((Element) node);

        if (value != null && value instanceof Element) {
            Element valueElm = (Element) value;
            if (originalElem.getQName().equals(valueElm.getQName())) {
                originalElem.clearContent();
                List content = valueElm.content();
                if (content != null) {
                    for (int i = 0; i < content.size(); i++) {
                        Node dom4jNode = (Node) content.get(i);
                        Node newDom4jNode = (Node) dom4jNode.clone();
                        originalElem.add(newDom4jNode);
                    }
                }
            } else {
                throw new RuntimeException(
                        "Can NOT assign " + valueElm.getQName() + " to " + originalElem.getQName());
            }

        } else if (value != null && value instanceof Text) {
            originalElem.clearContent();
            Text txt = (Text) ((Text) value).clone();
            originalElem.add(txt);
        } else if (value != null && value instanceof CDATA) {
            originalElem.clearContent();
            CDATA cdata = (CDATA) ((CDATA) value).clone();
            originalElem.add(cdata);
        } else if (value != null && value instanceof java.util.Date) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateStr = format.format((java.util.Date) value);
            originalElem.clearContent();
            originalElem.addText(dateStr);
        } else {
            String string = (String) TypeUtils.convert(value, String.class);
            originalElem.clearContent();
            originalElem.addText(string);
        }

    }

}

From source file:org.forzaframework.util.XmlUtils.java

License:Apache License

public static void buildEmptyListDocument(Document doc) {
    Element root = doc.addElement("items");
    root.addAttribute("success", "true");
    doc.setRootElement(root);
    root.addElement("totalCount").addText("0");
}

From source file:org.forzaframework.util.XmlUtils.java

License:Apache License

public static void buildDocument(Document doc, List<? extends BaseEntity> list, Integer totalCount) {
    Element root = doc.addElement("items");
    root.addAttribute("success", "true");
    doc.setRootElement(root);

    for (BaseEntity object : list) {
        root.add(object.toXml());//from  w ww  .  ja v a  2s . c  o  m
    }
    root.addElement("totalCount").addText(String.valueOf(totalCount));
}

From source file:org.forzaframework.util.XmlUtils.java

License:Apache License

public static Document buildDocument(Document doc, List list, Integer size, String[] elements)
        throws Exception {
    Element root = doc.addElement("items");
    root.addAttribute("success", "true");
    doc.setRootElement(root);

    for (Object bean : list) {
        Element item = root.addElement("item");
        buildElement(item, bean, elements);
    }//from   w  ww  .  ja v a  2 s  .c  o m
    root.addElement("totalCount").addText(String.valueOf(size));

    return doc;
}

From source file:org.forzaframework.util.XmlUtils.java

License:Apache License

public static Document buildDocument(Document doc, List list, Integer size, Map<String, String> elements,
        Map<String, String> emptyElement) throws Exception {
    Element root = doc.addElement("items");
    root.addAttribute("success", "true");
    doc.setRootElement(root);

    if (emptyElement != null) {
        Element item = root.addElement("item");
        for (Map.Entry<String, String> e : emptyElement.entrySet()) {
            item.addElement(e.getKey()).addText(e.getValue());
        }/*from  w  w  w .java 2 s.  co m*/
    }

    for (Object bean : list) {
        Element item = root.addElement("item");
        buildElement(item, bean, elements);
    }
    root.addElement("totalCount").addText(String.valueOf(size));

    return doc;
}

From source file:org.forzaframework.util.XmlUtils.java

License:Apache License

public static Document buildDocumentFromMap(List<Map> list) {
    Document doc = DocumentHelper.createDocument();
    doc.setXMLEncoding("ISO-8859-1");

    Element root = doc.addElement("items");
    root.addAttribute("success", "true");
    doc.setRootElement(root);

    for (Map map : list) {
        Element el = DocumentHelper.createElement("item");
        for (Iterator it = map.entrySet().iterator(); it.hasNext();) {
            Map.Entry entry = (Map.Entry) it.next();
            if (entry.getKey().toString().equals("$type$"))
                continue;

            el.addElement(entry.getKey().toString())
                    .addText(entry.getValue() == null ? "" : entry.getValue().toString());
        }/*from  w  ww . j  av a  2s .  c o m*/
        root.add(el);
    }

    return doc;
}

From source file:org.forzaframework.web.servlet.view.ListXmlView.java

License:Apache License

protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    Document doc = DocumentHelper.createDocument();

    String query = request.getParameter("query");
    String id = request.getParameter("id");

    if (StringUtils.isNotBlank(id)) {
        SystemEntity entity = getSystemEntity(request, model);
        BaseEntity object = (BaseEntity) entityManager.get(entity.getType(), Long.valueOf(id));
        Element element = object.toXml();
        Element root = doc.addElement("response");
        root.addAttribute("success", "true");
        root.add(element);//from  w  w w  .ja v a2 s  .co  m
        doc.setRootElement(root);

    } else if (request.getParameter("id") != null) {
        XmlUtils.buildEmptyListDocument(doc);
    } else {
        List<? extends BaseEntity> list;
        if (request.getParameter("e").equals("entity") || request.getParameter("e").equals("externalSystem")) {
            if (request.getParameter("e").equals("entity")) {
                list = systemConfiguration.getSystemEntities();
            } else {
                list = systemConfiguration.getExternalSystems();
            }
        } else {
            SystemEntity entity = getSystemEntity(request, model);
            org.hibernate.Criteria crit = entityManager.getHibernateSession().createCriteria(entity.getType());
            if (entity.findAttribute("name") != null && query != null) {
                crit.add(org.hibernate.criterion.Restrictions.like("name", "%" + query + "%").ignoreCase());
            }
            if (StringUtils.isNotBlank(request.getParameter("orderBy"))) {
                crit.addOrder(Order.asc(request.getParameter("orderBy")));
            }
            list = crit.list();
        }
        if (StringUtils.isNotBlank(request.getParameter("sort"))) {
            Collections.sort(list,
                    new AlphanumBeanComparator(request.getParameter("sort"), request.getParameter("dir")));
        }
        List<? extends BaseEntity> objects = CollectionUtils.paginate(list, request.getParameterMap(), false);

        XmlUtils.buildDocument(doc, objects, list.size());
    }

    response.setContentType("text/xml");

    response.getWriter().write(doc.asXML());

}

From source file:org.hibernate.console.ConfigurationXMLFactory.java

License:Open Source License

public Document createXML() {
    Document res = DocumentFactory.getInstance().createDocument();
    Element root = createRoot();/*from   w w  w  .j  a  v  a 2s  . c o m*/
    res.setRootElement(root);
    return res;
}

From source file:org.jboss.mx.metadata.JBossXMBean10.java

License:Open Source License

/**
 * Convert org.dom4j.Element->org.w3c.dom.Element
 *///w  ww  .  j  a v  a 2 s  .c o  m
private org.w3c.dom.Element toW3CElement(org.dom4j.Element d4element) throws org.dom4j.DocumentException {
    // prepare
    org.dom4j.Document d4doc = org.dom4j.DocumentFactory.getInstance().createDocument();
    org.dom4j.io.DOMWriter d4Writer = new org.dom4j.io.DOMWriter();
    // copy
    d4doc.setRootElement(d4element.createCopy());
    // convert
    org.w3c.dom.Document doc = d4Writer.write(d4doc);
    // return root Element - should I copy again?
    return doc.getDocumentElement();
}

From source file:org.nuxeo.ecm.webapp.liveedit.LiveEditBootstrapHelper.java

License:Apache License

/**
 * Creates the bootstrap file. It is called from the browser's addon. The URL composition tells the case and what to
 * create. The structure is depicted in the NXP-1881. Rux NXP-1959: add new tag on root level describing the action:
 * actionEdit, actionNew or actionFromTemplate.
 *
 * @return the bootstrap file content//  www.  j a  va  2s.  c o  m
 */
public void getBootstrap() throws IOException {
    String currentRepoID = documentManager.getRepositoryName();

    CoreSession session = documentManager;
    CoreSession templateSession = documentManager;
    try {
        if (repoID != null && !currentRepoID.equals(repoID)) {
            session = CoreInstance.openCoreSession(repoID);
        }

        if (templateRepoID != null && !currentRepoID.equals(templateRepoID)) {
            templateSession = CoreInstance.openCoreSession(templateRepoID);
        }

        DocumentModel doc = null;
        DocumentModel templateDoc = null;
        String filename = null;
        if (ACTION_EDIT_DOCUMENT.equals(action)) {
            // fetch the document to edit to get its mimetype and document
            // type
            doc = session.getDocument(new IdRef(docRef));
            docType = doc.getType();
            Blob blob = null;
            if (blobPropertyName != null) {
                blob = (Blob) doc.getPropertyValue(blobPropertyName);
                if (blob == null) {
                    throw new NuxeoException(
                            String.format("could not find blob to edit with property '%s'", blobPropertyName));
                }
            } else {
                blob = (Blob) doc.getProperty(schema, blobField);
                if (blob == null) {
                    throw new NuxeoException(String.format(
                            "could not find blob to edit with schema '%s' and field '%s'", schema, blobField));
                }
            }
            mimetype = blob.getMimeType();
            if (filenamePropertyName != null) {
                filename = (String) doc.getPropertyValue(filenamePropertyName);
            } else {
                filename = (String) doc.getProperty(schema, filenameField);
            }
        } else if (ACTION_CREATE_DOCUMENT.equals(action)) {
            // creating a new document all parameters are read from the
            // request parameters
        } else if (ACTION_CREATE_DOCUMENT_FROM_TEMPLATE.equals(action)) {
            // fetch the template blob to get its mimetype
            templateDoc = templateSession.getDocument(new IdRef(templateDocRef));
            Blob blob = (Blob) templateDoc.getProperty(templateSchema, templateBlobField);
            if (blob == null) {
                throw new NuxeoException(
                        String.format("could not find template blob with schema '%s' and field '%s'",
                                templateSchema, templateBlobField));
            }
            mimetype = blob.getMimeType();
            // leave docType from the request query parameter
        } else {
            throw new NuxeoException(String.format(
                    "action '%s' is not a valid LiveEdit action: should be one of '%s', '%s' or '%s'", action,
                    ACTION_CREATE_DOCUMENT, ACTION_CREATE_DOCUMENT_FROM_TEMPLATE, ACTION_EDIT_DOCUMENT));
        }

        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();

        Element root = DocumentFactory.getInstance().createElement(liveEditTag);
        root.addNamespace("", XML_LE_NAMESPACE);
        // RUX NXP-1959: action id
        Element actionInfo = root.addElement(actionSelectorTag);
        actionInfo.setText(action);

        // Document related informations
        Element docInfo = root.addElement(documentTag);
        addTextElement(docInfo, docRefTag, docRef);
        Element docPathT = docInfo.addElement(docPathTag);
        Element docTitleT = docInfo.addElement(docTitleTag);
        if (doc != null) {
            docPathT.setText(doc.getPathAsString());
            docTitleT.setText(doc.getTitle());
        }
        addTextElement(docInfo, docRepositoryTag, repoID);

        addTextElement(docInfo, docSchemaNameTag, schema);
        addTextElement(docInfo, docFieldNameTag, blobField);
        addTextElement(docInfo, docBlobFieldNameTag, blobField);
        Element docFieldPathT = docInfo.addElement(docfieldPathTag);
        Element docBlobFieldPathT = docInfo.addElement(docBlobFieldPathTag);
        if (blobPropertyName != null) {
            // FIXME AT: NXP-2306: send blobPropertyName correctly (?)
            docFieldPathT.setText(blobPropertyName);
            docBlobFieldPathT.setText(blobPropertyName);
        } else {
            if (schema != null && blobField != null) {
                docFieldPathT.setText(schema + ':' + blobField);
                docBlobFieldPathT.setText(schema + ':' + blobField);
            }
        }
        addTextElement(docInfo, docFilenameFieldNameTag, filenameField);
        Element docFilenameFieldPathT = docInfo.addElement(docFilenameFieldPathTag);
        if (filenamePropertyName != null) {
            docFilenameFieldPathT.setText(filenamePropertyName);
        } else {
            if (schema != null && blobField != null) {
                docFilenameFieldPathT.setText(schema + ':' + filenameField);
            }
        }

        addTextElement(docInfo, docfileNameTag, filename);
        addTextElement(docInfo, docTypeTag, docType);
        addTextElement(docInfo, docMimetypeTag, mimetype);
        addTextElement(docInfo, docFileExtensionTag, getFileExtension(mimetype));

        Element docFileAuthorizedExtensions = docInfo.addElement(docFileAuthorizedExtensionsTag);
        List<String> authorizedExtensions = getFileExtensions(mimetype);
        if (authorizedExtensions != null) {
            for (String extension : authorizedExtensions) {
                addTextElement(docFileAuthorizedExtensions, docFileAuthorizedExtensionTag, extension);
            }
        }

        Element docIsVersionT = docInfo.addElement(docIsVersionTag);
        Element docIsLockedT = docInfo.addElement(docIsLockedTag);
        if (ACTION_EDIT_DOCUMENT.equals(action)) {
            docIsVersionT.setText(Boolean.toString(doc.isVersion()));
            docIsLockedT.setText(Boolean.toString(doc.isLocked()));
        }

        // template information for ACTION_CREATE_DOCUMENT_FROM_TEMPLATE

        Element templateDocInfo = root.addElement(templateDocumentTag);
        addTextElement(templateDocInfo, docRefTag, templateDocRef);
        docPathT = templateDocInfo.addElement(docPathTag);
        docTitleT = templateDocInfo.addElement(docTitleTag);
        if (templateDoc != null) {
            docPathT.setText(templateDoc.getPathAsString());
            docTitleT.setText(templateDoc.getTitle());
        }
        addTextElement(templateDocInfo, docRepositoryTag, templateRepoID);
        addTextElement(templateDocInfo, docSchemaNameTag, templateSchema);
        addTextElement(templateDocInfo, docFieldNameTag, templateBlobField);
        addTextElement(templateDocInfo, docBlobFieldNameTag, templateBlobField);
        docFieldPathT = templateDocInfo.addElement(docfieldPathTag);
        docBlobFieldPathT = templateDocInfo.addElement(docBlobFieldPathTag);
        if (templateSchema != null && templateBlobField != null) {
            docFieldPathT.setText(templateSchema + ":" + templateBlobField);
            docBlobFieldPathT.setText(templateSchema + ":" + templateBlobField);
        }
        addTextElement(templateDocInfo, docMimetypeTag, mimetype);
        addTextElement(templateDocInfo, docFileExtensionTag, getFileExtension(mimetype));

        Element templateFileAuthorizedExtensions = templateDocInfo.addElement(docFileAuthorizedExtensionsTag);
        if (authorizedExtensions != null) {
            for (String extension : authorizedExtensions) {
                addTextElement(templateFileAuthorizedExtensions, docFileAuthorizedExtensionTag, extension);
            }
        }

        // Browser request related informations
        Element requestInfo = root.addElement(requestInfoTag);
        Cookie[] cookies = request.getCookies();
        Element cookiesT = requestInfo.addElement(requestCookiesTag);
        for (Cookie cookie : cookies) {
            Element cookieT = cookiesT.addElement(requestCookieTag);
            cookieT.addAttribute("name", cookie.getName());
            cookieT.setText(cookie.getValue());
        }
        Element headersT = requestInfo.addElement(requestHeadersTag);
        Enumeration hEnum = request.getHeaderNames();
        while (hEnum.hasMoreElements()) {
            String hName = (String) hEnum.nextElement();
            if (!hName.equalsIgnoreCase("cookie")) {
                Element headerT = headersT.addElement(requestHeaderTag);
                headerT.addAttribute("name", hName);
                headerT.setText(request.getHeader(hName));
            }
        }
        addTextElement(requestInfo, requestBaseURLTag, BaseURL.getBaseURL(request));

        // User related informations
        String username = context.getExternalContext().getUserPrincipal().getName();
        Element userInfo = root.addElement(userInfoTag);
        addTextElement(userInfo, userNameTag, username);
        addTextElement(userInfo, userPasswordTag, "");
        addTextElement(userInfo, userTokenTag, "");
        addTextElement(userInfo, userLocaleTag, context.getViewRoot().getLocale().toString());
        // Rux NXP-1882: the wsdl locations
        String baseUrl = BaseURL.getBaseURL(request);
        Element wsdlLocations = root.addElement(wsdlLocationsTag);
        Element wsdlAccessWST = wsdlLocations.addElement(wsdlAccessWebServiceTag);
        wsdlAccessWST.setText(baseUrl + "webservices/nuxeoAccess?wsdl");
        Element wsdlEEWST = wsdlLocations.addElement(wsdlLEWebServiceTag);
        wsdlEEWST.setText(baseUrl + "webservices/nuxeoLEWS?wsdl");

        // Server related informations
        Element serverInfo = root.addElement(serverInfoTag);
        Element serverVersionT = serverInfo.addElement(serverVersionTag);
        serverVersionT.setText("5.1"); // TODO: use a buildtime generated
        // version tag instead

        // Client related informations
        Element editId = root.addElement(editIdTag);
        editId.setText(getEditId(doc, session, username));

        // serialize bootstrap XML document in the response
        Document xmlDoc = DocumentFactory.getInstance().createDocument();
        xmlDoc.setRootElement(root);
        response.setContentType("text/xml; charset=UTF-8");

        // use a formatter to make it easier to debug live edit client
        // implementations
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        XMLWriter writer = new XMLWriter(response.getOutputStream(), format);
        writer.write(xmlDoc);

        response.flushBuffer();
        context.responseComplete();
    } finally {
        if (session != null && session != documentManager) {
            session.close();
        }
        if (templateSession != null && templateSession != documentManager) {
            templateSession.close();
        }
    }
}