Example usage for org.dom4j Document addElement

List of usage examples for org.dom4j Document addElement

Introduction

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

Prototype

Element addElement(String name);

Source Link

Document

Adds a new Element node with the given name to this branch and returns a reference to the new node.

Usage

From source file:org.axonframework.migration.eventstore.LegacyAxonEventUpcaster.java

License:Apache License

@SuppressWarnings({ "unchecked" })
@Override//from ww  w .ja va 2  s.co  m
public IntermediateRepresentation upcast(IntermediateRepresentation event) {
    Element rootNode = ((Document) event.getContents()).getRootElement();
    if (rootNode.attribute("eventRevision") == null) {
        rootNode.addAttribute("eventRevision", "0");
        Element metaData = rootNode.addElement("metaData").addElement("values");
        Iterator<Element> children = rootNode.elementIterator();
        while (children.hasNext()) {
            Element childNode = children.next();
            String childName = childNode.getName();
            if ("eventIdentifier".equals(childName)) {
                addMetaDataEntry(metaData, "_identifier", childNode.getTextTrim(), "uuid");
                rootNode.remove(childNode);
            } else if ("timestamp".equals(childName)) {
                addMetaDataEntry(metaData, "_timestamp", childNode.getTextTrim(), "localDateTime");
                rootNode.remove(childNode);
            }
        }
    }
    Document document = new DefaultDocument();
    Element newRoot = document.addElement("domain-event");
    Element payload = newRoot.addElement("payload");
    String objectType = rootNode.getName().replaceAll("\\_\\-", "\\$");
    payload.addAttribute("class", objectType);
    Set<String> forbiddenPayloadElements = new HashSet<String>(
            Arrays.asList("metaData", "aggregateIdentifier", "sequenceNumber", "timestamp"));
    for (Object node : rootNode.elements()) {
        Element element = (Element) node;
        if (!forbiddenPayloadElements.contains(element.getName())) {
            payload.add(element.createCopy());
        } else {
            newRoot.add(element.createCopy());
        }
    }
    newRoot.addElement("timestamp").addText(extractMetaDataValue(newRoot, "_timestamp"));
    newRoot.addElement("eventIdentifier").addText(extractMetaDataValue(newRoot, "_identifier"));
    String eventRevision = rootNode.attribute("eventRevision").getValue();
    payload.addAttribute("eventRevision", eventRevision);
    return new Dom4jRepresentation(document, DomainEventMessage.class.getName(),
            Integer.parseInt(eventRevision));
}

From source file:org.beangle.emsapp.security.action.MenuAction.java

License:Open Source License

public void exportXML() {
    Document doc = DocumentHelper.createDocument();
    Element root = doc.addElement("root");
    List<Menu> menus = (List<Menu>) entityDao.search(getQueryBuilder().limit(null));
    for (Menu m : menus) {
        Element em = root.addElement("menu");
        em.addAttribute("id", m.getId().toString());
        em.addAttribute("code", m.getCode());
        em.addAttribute("name", m.getName());
        em.addAttribute("title", m.getTitle());
        em.addAttribute("entry", m.getEntry());
        em.addAttribute("remark", m.getRemark());
        em.addAttribute("profileId", m.getProfile().getId().toString());
        if (m.getParent() != null) {
            em.addAttribute("parentId", m.getParent().getId().toString());
        }/*  ww w.j a  v a2s  . co m*/
        for (Resource res : m.getResources()) {
            Element eres = em.addElement("resource");
            eres.addAttribute("id", res.getId().toString());
            eres.addAttribute("name", res.getName());
            eres.addAttribute("title", res.getTitle());
            eres.addAttribute("remark", res.getRemark());
            eres.addAttribute("scope", res.getScope() + "");
            for (Category c : res.getCategories()) {
                Element ec = eres.addElement("category");
                ec.addAttribute("id", c.getId().toString());
            }
        }
    }

    try {
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setHeader("Content-Disposition", "attachment;filename=menu.xml");
        response.setContentType("application/x-msdownload");
        OutputFormat of = new OutputFormat();
        of.setIndent(true);
        of.setNewlines(true);
        XMLWriter writer = new XMLWriter(getResponse().getOutputStream(), of);
        writer.write(doc);
        writer.close();
    } catch (UnsupportedEncodingException e) {
        logger.error("exportXML error", e);
    } catch (IOException e) {
        logger.error("exportXML error", e);
    }
}

From source file:org.bigmouth.nvwa.pay.service.prepay.wx.WxPrepayInsideRequest.java

License:Apache License

public String toXML() {
    Document doc = DocumentHelper.createDocument();
    Element xml = doc.addElement("xml");
    if (StringUtils.isNotBlank(getAppId()))
        xml.addElement("appid").setText(getAppId());
    if (StringUtils.isNotBlank(getMchId()))
        xml.addElement("mch_id").setText(getMchId());
    if (StringUtils.isNotBlank(getDeviceInfo()))
        xml.addElement("device_info").setText(getDeviceInfo());
    if (StringUtils.isNotBlank(getNonceStr()))
        xml.addElement("nonce_str").setText(getNonceStr());
    if (StringUtils.isNotBlank(getSign()))
        xml.addElement("sign").setText(getSign());
    if (StringUtils.isNotBlank(getBody()))
        xml.addElement("body").setText(getBody());
    if (StringUtils.isNotBlank(getDetail()))
        xml.addElement("detail").setText(getDetail());
    if (StringUtils.isNotBlank(getAttach()))
        xml.addElement("attach").setText(getAttach());
    if (StringUtils.isNotBlank(getOutTradeNo()))
        xml.addElement("out_trade_no").setText(getOutTradeNo());
    if (null != getFeeType())
        xml.addElement("fee_type").setText(getFeeType());
    xml.addElement("total_fee").setText(String.valueOf(getTotalFee()));
    if (StringUtils.isNotBlank(getSpbillIp()))
        xml.addElement("spbill_create_ip").setText(getSpbillIp());
    if (StringUtils.isNotBlank(getTimeStart()))
        xml.addElement("time_start").setText(getTimeStart());
    if (StringUtils.isNotBlank(getTimeExpire()))
        xml.addElement("time_expire").setText(getTimeExpire());
    if (StringUtils.isNotBlank(getGoodsTag()))
        xml.addElement("goods_tag").setText(getGoodsTag());
    if (StringUtils.isNotBlank(getNotifyUrl()))
        xml.addElement("notify_url").setText(getNotifyUrl());
    if (null != getTradeType())
        xml.addElement("trade_type").setText(getTradeType());
    if (StringUtils.isNotBlank(getProductId()))
        xml.addElement("product_id").setText(getProductId());
    if (StringUtils.isNotBlank(getLimitPay()))
        xml.addElement("limit_pay").setText(getLimitPay());
    if (StringUtils.isNotBlank(getOpenId()))
        xml.addElement("openid").setText(getOpenId());
    return doc.asXML();
}

From source file:org.bigmouth.nvwa.utils.xml.Dom4jEncoder.java

License:Apache License

/**
 * ???XML<br>//w  w  w  .ja v a  2s  . com
 * ?{@linkplain org.bigmouth.nvwa.utils.Argument}??
 * 
 * <pre>
 * e.g.
 * 
 * List&lt;Object&gt; list = new ArrayList&lt;Object&gt;();
 * 
 * Object obj1 = new Object();
 * obj1.setName("Allen");
 * obj1.setOld(18);
 * obj1.setHomeAddr("Hangzhou");
 * obj1.setCellphon_no("10086");
 * 
 * Object obj2 = new Object();
 * obj2.setName("Lulu");
 * obj2.setOld(16);
 * obj2.setHomeAddr("Hangzhou");
 * obj2.setCellphon_no("10086-1");
 * 
 * list.add(obj1);
 * list.add(obj2);
 * 
 * String xml = Dom4jEncoder.encode(list, "/class", "student");
 * System.out.println(xml);
 * 
 * -------------------------
 * | XML Result:
 * -------------------------
 * 
 * &lt;class&gt;
 *  &lt;student&gt;
 *      &lt;name&gt;Allen&lt;/Name&gt;
 *      &lt;old&gt;18&lt;/old&gt;
 *      &lt;home_addr&gt;Hangzhou&lt;/home_addr&gt;
 *      &lt;cellphone__no&gt;10086&lt;/cellphone__no&gt;
 *  &lt;/student&gt;
 *  &lt;student&gt;
 *      &lt;name&gt;Lulu&lt;/Name&gt;
 *      &lt;old&gt;16&lt;/old&gt;
 *      &lt;home_addr&gt;Hangzhou&lt;/home_addr&gt;
 *      &lt;cellphone__no&gt;10086-1&lt;/cellphone__no&gt;
 *  &lt;/student&gt;
 * &lt;/class&gt;
 * 
 * </pre>
 * 
 * @param <T> 
 * @param objs ???
 * @param xpath 
 * @param itemNodeName ??
 * @return
 * @see org.bigmouth.nvwa.utils.Argument
 */
public static <T> String encode(List<T> objs, String xpath, String itemNodeName) {
    if (CollectionUtils.isEmpty(objs))
        return null;
    if (StringUtils.isBlank(xpath) || StringUtils.equals(xpath, "/")) {
        throw new IllegalArgumentException("xpath cannot be blank or '/'!");
    }
    Document doc = DocumentHelper.createDocument();
    Element root = null;
    if (StringUtils.split(xpath, "/").length > 2) {
        root = DocumentHelper.makeElement(doc, xpath);
    } else {
        xpath = StringUtils.removeStart(xpath, "/");
        root = doc.addElement(xpath);
    }

    for (Object obj : objs) {
        addElement(itemNodeName, root, obj);
    }

    return doc.asXML();
}

From source file:org.cipango.littleims.scscf.charging.CDF.java

License:Apache License

public String start(SipServletRequest event, int role) {
    log.debug("Start Session CDR");
    Document document = DocumentHelper.createDocument();
    Element root = document.addElement("ims-cdr");
    root.addElement("sip-method").setText(event.getMethod());
    root.addElement("role-of-node").setText(String.valueOf(role));
    root.addElement("session-id").setText(event.getCallId());
    root.addElement("calling-party-address").setText(event.getFrom().getURI().toString());
    root.addElement("called-party-address").setText(event.getTo().getURI().toString());
    root.addElement("serviceDeliveryStartTimeStamp").setText(getDate());

    String cdrID = idGenerator.newRandomID();
    cdrs.put(cdrID, document);/*from  w ww. j a va2  s .  com*/
    return cdrID;
}

From source file:org.cipango.littleims.scscf.charging.CDF.java

License:Apache License

public void event(SipServletRequest event, int role) {
    log.debug("Generate Event CDR");
    Document document = DocumentHelper.createDocument();
    Element root = document.addElement("ims-cdr");
    root.addElement("sip-method").setText(event.getMethod());
    root.addElement("role-of-node").setText(String.valueOf(role));
    root.addElement("session-id").setText(event.getCallId());
    root.addElement("calling-party-address").setText(event.getFrom().getURI().toString());
    root.addElement("called-party-address").setText(event.getTo().getURI().toString());

    try {//from   ww  w.j ava2 s.co m
        File cdr = new File(_chargingDirectory, idGenerator.newRandomID() + ".xml");
        FileOutputStream cdrOut = new FileOutputStream(cdr);
        synchronized (xmlWriter) {
            xmlWriter.setOutputStream(cdrOut);
            xmlWriter.write(document);
            xmlWriter.flush();
        }
        cdrOut.close();
    } catch (IOException e) {
        log.error("Error while writing CDR", e);
    }
}

From source file:org.codehaus.aspectwerkz.metadata.AttributeC.java

License:Open Source License

/**
 * Creates a DOM documents out of the definition.
 *
 * @param definition the AspectWerkz definition
 * @param uuid the UUID for the definition
 * @return the DOM document/*from   ww  w .j ava 2  s.com*/
 */
public static Document createDocument(final AspectWerkzDefinitionImpl definition, final String uuid) {
    if (definition == null)
        throw new IllegalArgumentException("definition can not be null");

    Document document = DocumentHelper.createDocument();
    document.addDocType("aspectwerkz", "-//AspectWerkz//DTD//EN",
            "http://aspectwerkz.codehaus.org/dtd/aspectwerkz.dtd");

    Element root = document.addElement("aspectwerkz");
    Element system = root.addElement("system");
    system.addAttribute("id", uuid);

    handleIntroductionDefinitions(system, definition);
    handleAdviceDefinitions(system, definition);
    handleAspectDefinitions(system, definition);

    return document;
}

From source file:org.codehaus.cargo.container.weblogic.WebLogic9xStandaloneLocalConfiguration.java

License:Apache License

/**
 * Create a blank datasource file with correct namespace.
 * /*w w  w  . java  2  s. com*/
 * @param path where to create the base file.
 */
protected void createBlankDataSourceFile(String path) {
    Document document = DocumentHelper.createDocument();
    Element dataSource = document.addElement("jdbc-data-source");
    document.setRootElement(dataSource);
    dataSource.addNamespace("", "http://www.bea.com/ns/weblogic/90");
    xmlTool.saveXml(document, path);
}

From source file:org.codehaus.modello.plugin.jaxrs.JaxRSMappingModelloGenerator.java

License:Apache License

private void generateJaxRS(File webXml, Model model) throws IOException, ModelloException {
    OutputStreamWriter fileWriter = new OutputStreamWriter(new FileOutputStream(webXml), "UTF-8");

    org.dom4j.io.XMLWriter writer = null;

    namespace = DocumentHelper.createNamespace("", "http://java.sun.com/xml/ns/j2ee");
    Document document = DocumentHelper.createDocument();
    Element root = document.addElement("web-app");
    root.addNamespace("", "http://java.sun.com/xml/ns/j2ee");
    root.addAttribute("version", "2.4");
    root.addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
    root.addAttribute("xsi:schemaLocation",
            "http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd");
    Element displayName = addElement(root, "display-name", model.getName());
    // add the declaration for the Jersey servlet
    Element servlet = addElement(root, "servlet");
    addElement(servlet, "servlet-name", JERSEY_SERVLET_NAME);
    addElement(servlet, "servlet-class", "com.sun.jersey.spi.container.servlet.ServletContainer");
    Element pkgsParam = addElement(servlet, "init-param");
    addElement(pkgsParam, "param-name", "com.sun.jersey.config.property.packages");
    addElement(servlet, "load-on-startup", "1");

    Set<String> pkgs = new HashSet<String>();

    // Processed classes to be mapped here
    for (Iterator it = model.getClasses(getGeneratedVersion()).iterator(); it.hasNext();) {
        ModelClass modelClass = (ModelClass) it.next();

        JaxRSClassLevelMetadata metadata = (JaxRSClassLevelMetadata) modelClass
                .getMetadata(JaxRSClassLevelMetadata.ID);

        // only generate servlet-mappings for classes which have a jaxrs.urls parameter
        if (!isEmpty(metadata.getUrls())) {
            String packageName = modelClass.getPackageName(isPackageWithVersion(), getGeneratedVersion());
            if (!pkgs.contains(packageName)) {
                pkgs.add(packageName);/*from www.j av a 2  s. c  o  m*/
            }

            String[] urls = metadata.getUrls().split(",");
            for (String url : urls) {
                Element mapping = addElement(root, "servlet-mapping");
                addElement(mapping, "servlet-name", JERSEY_SERVLET_NAME);
                addElement(mapping, "url-pattern", url);
            }
        }

    }

    String pkgsString = "";
    for (String s : pkgs) {
        if (!"".equals(pkgsString))
            pkgsString += ",";
        pkgsString += s;
    }
    addElement(pkgsParam, "param-value", pkgsString);

    OutputFormat format = OutputFormat.createPrettyPrint();
    writer = new XMLWriter(fileWriter, format);
    writer.write(document);
    writer.close();
}

From source file:org.codehaus.modello.plugin.jpa.JpaOrmMappingModelloGenerator.java

License:Apache License

private void generateOrm(File orm, Model model) throws IOException, ModelloException {
    OutputStreamWriter fileWriter = new OutputStreamWriter(new FileOutputStream(orm), "UTF-8");

    org.dom4j.io.XMLWriter writer = null;

    JpaModelMetadata modelMetadata = (JpaModelMetadata) model.getMetadata(JpaModelMetadata.ID);

    String jpaVersion = modelMetadata.getVersion();

    String jpaUnit = modelMetadata.getUnit();

    Document document = DocumentHelper.createDocument();

    Element root = null;/*from   w  ww .j  a v a  2s.c  om*/

    if (JpaMetadataPlugin.JPA_VERSION_1.equals(jpaVersion) || (jpaVersion == null)) {
        namespace = DocumentHelper.createNamespace("", "http://java.sun.com/xml/ns/persistence/orm");
        root = document.addElement("entity-mappings");
        root.addNamespace("", "http://java.sun.com/xml/ns/persistence/orm");
        root.addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        root.addAttribute("xsi:schemaLocation",
                "http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_1_0.xsd");
        root.addAttribute("version", "1.0");
    } else if (JpaMetadataPlugin.JPA_VERSION_2.equals(jpaVersion)) {
        namespace = DocumentHelper.createNamespace("", "http://java.sun.com/xml/ns/persistence");
        root = document.addElement("persistence");
        root.addNamespace("", "http://java.sun.com/xml/ns/persistence");
        root.addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        root.addAttribute("version", "2.0");
        root.addAttribute("xsi:schemaLocation",
                "http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd");
        Element persistenceUnit = addElement(root, "persistence-unit");
        persistenceUnit.addAttribute("name", jpaUnit);
        addElement(persistenceUnit, "provider", "org.apache.openjpa.persistence.PersistenceProviderImpl");
    }

    // Processed classes to be mapped here
    for (Iterator it = model.getClasses(getGeneratedVersion()).iterator(); it.hasNext();) {
        ModelClass modelClass = (ModelClass) it.next();

        String packageName = modelClass.getPackageName(isPackageWithVersion(), getGeneratedVersion());

        JpaClassLevelMetadata metadata = (JpaClassLevelMetadata) modelClass
                .getMetadata(JpaClassLevelMetadata.ID);

        List processorMetadataList = metadata.getProcessorMetadata();
        for (Iterator it2 = processorMetadataList.iterator(); it2.hasNext();) {
            ProcessorMetadata procMetadata = (ProcessorMetadata) it2.next();
            try {
                ((ClassMetadataProcessorMetadata) procMetadata).setModelClass(modelClass);

                ((ClassMetadataProcessorMetadata) procMetadata).setPackageName(modelClass.getPackageName());

                MetadataProcessor metadataProcessor = processorFactory.createMetadataProcessor(procMetadata);

                // set up Processor Context.
                MetadataProcessorContext processorContext = new MetadataProcessorContext();
                processorContext.setDocument(document);
                processorContext.setModel(model);

                boolean valid = metadataProcessor.validate(processorContext, procMetadata);

                if (valid)
                    metadataProcessor.process(processorContext, procMetadata);
                else
                    throw new ModelloException(
                            "Processor Metadata validate failed for '" + procMetadata.getKey() + "' in class "
                                    + modelClass.getPackageName() + '.' + modelClass.getName());
            } catch (MetadataProcessorInstantiationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (MetadataProcessorException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    if (JpaMetadataPlugin.JPA_VERSION_2.equals(jpaVersion)) {

        Element persistenceUnit = root.element("persistence-unit");
        addElement(persistenceUnit, "validation-mode", "NONE");
        File propsFile = new File("src/main/resources/" + jpaUnit + ".properties");
        if (propsFile.exists()) {
            Element properties = addElement(persistenceUnit, "properties");
            Properties persistenceProviderProps = new Properties();
            persistenceProviderProps.load(new FileInputStream(propsFile));
            Iterator it = persistenceProviderProps.keySet().iterator();
            while (it.hasNext()) {
                String k = it.next().toString();
                String v = persistenceProviderProps.getProperty(k);
                Element property = addElement(properties, "property");
                property.addAttribute("name", k);
                property.addAttribute("value", v);
            }
        }
    }

    OutputFormat format = OutputFormat.createPrettyPrint();
    writer = new XMLWriter(fileWriter, format);
    writer.write(document);
    writer.close();
}