Example usage for org.dom4j DocumentHelper createDocument

List of usage examples for org.dom4j DocumentHelper createDocument

Introduction

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

Prototype

public static Document createDocument() 

Source Link

Usage

From source file:com.taobao.datax.engine.tools.JobConfGenDriver.java

License:Open Source License

private static int genXmlFile(String filename, ClassNode reader, ClassNode writer) throws IOException {

    Document document = DocumentHelper.createDocument();
    Element jobsElement = document.addElement("jobs");
    Element jobElement = jobsElement.addElement("job");
    String id = reader.getName() + "_to_" + writer.getName() + "_job";
    jobElement.addAttribute("id", id);

    /**//from   ww w .  j  a  v  a 2  s  .c o m
     * ?readerxml
     */
    Element readerElement = jobElement.addElement("reader");
    Element plugin_Element = readerElement.addElement("plugin");
    plugin_Element.setText(reader.getName());

    ClassNode readerNode = reader;
    Element tempElement = null;

    List<ClassMember> members = readerNode.getAllMembers();
    for (ClassMember member : members) {
        StringBuilder command = new StringBuilder("\n");

        Set<String> set = member.getAllKeys();
        String value = "";
        for (String key : set) {
            value = member.getAttr("default");
            command.append(key).append(":").append(member.getAttr(key)).append("\n");
        }
        readerElement.addComment(command.toString());

        String keyName = member.getName();
        keyName = keyName.substring(1, keyName.length() - 1);
        tempElement = readerElement.addElement("param");
        tempElement.addAttribute("key", keyName);

        if (value == null || "".equals(value)) {
            value = "?";
        }
        tempElement.addAttribute("value", value);
    }

    /**
     * ?writerxml
     */
    Element writerElement = jobElement.addElement("writer");
    plugin_Element = writerElement.addElement("plugin");
    plugin_Element.setText(writer.getName());

    members = writer.getAllMembers();
    for (ClassMember member : members) {
        StringBuilder command = new StringBuilder("\n");
        Set<String> set = member.getAllKeys();

        String value = "";
        for (String key : set) {
            value = member.getAttr("default");
            command.append(key).append(":").append(member.getAttr(key)).append("\n");
        }
        writerElement.addComment(command.toString());

        String keyName = member.getName();
        keyName = keyName.substring(1, keyName.length() - 1);
        tempElement = writerElement.addElement("param");
        tempElement.addAttribute("key", keyName);

        if (value == null || "".equals(value)) {
            value = "?";
        }
        tempElement.addAttribute("value", value);
    }

    try {
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        XMLWriter writerOfXML = new XMLWriter(new FileWriter(new File(filename)), format);
        writerOfXML.write(document);
        writerOfXML.close();
    } catch (Exception ex) {
        throw new IOException(ex.getCause());
    }

    return 0;
}

From source file:com.tedi.engine.XMLOutput.java

License:Open Source License

public String process(Vector structureV, Vector dataV) {
    doc = DocumentHelper.createDocument();
    Element root = null;//from  w w  w  . jav a 2s .  co m
    String suppress = null;
    String result = "";

    if (logger.isDebugEnabled()) {
        logger.debug("Processing XML output.");
    }

    if (structureV != null && structureV.size() > 0 && structureV != null) {
        try {
            // main loop for creating the XML document
            for (int i = 0; i < structureV.size(); i++) {
                String value = (String) dataV.elementAt(i);
                Vector fieldV = (Vector) structureV.elementAt(i);
                String path = (String) fieldV.elementAt(0);
                String endpoint = (String) fieldV.elementAt(1);
                String datatype = (String) fieldV.elementAt(4);
                // deal with suppression criteria
                // --------------------------------------------------------------
                if (suppress != null) {
                    if (path.indexOf(suppress) > -1)
                        continue;
                    else
                        suppress = null;
                }
                // if printing of this part of the tree was supressed, skip
                // ahead
                if (value.equals(TEDI_SUPRESS)) {
                    if (suppress == null)
                        suppress = path;
                    continue;
                }
                // ---------------------------------------------------------------------------------------------
                Vector currentRowVector = (Vector) structureV.elementAt(i);
                // Only non-calc fields make it to output
                if (!currentRowVector.elementAt(4).toString().equals(CALC)) {
                    StringTokenizer st = new StringTokenizer(path, "/");
                    int count = st.countTokens();
                    // factor out the root
                    String firstToken = st.nextToken();
                    count--;
                    // Set root if required
                    if (root == null) {
                        this.setSystemID(firstToken);
                        root = DocumentHelper.createElement(firstToken);
                        doc.setRootElement(root);
                        if (count == 0 && endpoint.length() == 0)
                            continue;
                    } else if (endpoint.length() == 0)
                        count--;
                    // Handle error condition of no root
                    if (root == null) {
                        execResults.addMessage(ExecutionResults.M_ERROR, ExecutionResults.J2EE_TARGET_ERR,
                                "Mapping defintion error locating root element declaration.");
                        execResults.setReturnCode(ExecutionResults.RESULT_ERROR);
                        break;
                    }
                    if (endpoint.length() > 0) {
                        if (mapFile.isSuppressAttribIfEmpty() && value.length() == 0)
                            continue;
                        else if (mapFile.isSuppressAttribIfHasOnlyWhitespace() && value.trim().length() == 0)
                            continue;
                    }
                    // this is the main loop for a path
                    Element elem = root;
                    for (int j = 0; j < count; j++) {
                        String item = st.nextToken();
                        List childList = elem.elements(item);
                        if (childList.size() > 0) {
                            elem = (Element) childList.get(childList.size() - 1);
                        } else {
                            elem = elem.addElement(item);
                        }
                    }
                    if (endpoint.length() == 0) {
                        elem = elem.addElement(st.nextToken());
                        if (datatype.equals(TEXT_CDATA))
                            elem.addCDATA(value);
                        else if (!datatype.equals(NOT_MAPPABLE))
                            elem.addText(value);
                    } else {
                        elem.addAttribute(endpoint, value);
                    }
                }
            } // end for() main loop

            // "isSuppressDocType" indicator re-used to suppress NS prefixes
            if (!isSuppressDocType) {
                addNSPrefixesToDocument();
            }

            result = cleanDocument(doc);
        } catch (Exception e) {
            execResults.addMessage(ExecutionResults.M_ERROR, ExecutionResults.J2EE_TARGET_ERR,
                    "Error creating XML document: " + e.getMessage());
            execResults.setReturnCode(ExecutionResults.RESULT_ERROR);
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Processing of XML output completed.");
    }
    return result;
}

From source file:com.thinkberg.moxo.dav.LockHandler.java

License:Apache License

private void sendLockAcquiredResponse(HttpServletResponse response, Lock lock) throws IOException {
    response.setContentType("text/xml");
    response.setCharacterEncoding("UTF-8");
    response.setHeader(HEADER_LOCK_TOKEN, "<" + lock.getToken() + ">");

    Document propDoc = DocumentHelper.createDocument();
    Element propEl = propDoc.addElement(TAG_PROP, "DAV:");
    Element lockdiscoveryEl = propEl.addElement(TAG_LOCKDISCOVERY);

    lock.serializeToXml(lockdiscoveryEl);

    XMLWriter xmlWriter = new XMLWriter(response.getWriter());
    xmlWriter.write(propDoc);/* w w w .  j a  v a  2s.  com*/
    log(propDoc);
}

From source file:com.thinkberg.moxo.dav.PropFindHandler.java

License:Apache License

private Document getMultiStatusRespons(FileObject object, List<String> requestedProperties, URL baseUrl,
        int depth, boolean ignoreValues) throws FileSystemException {
    Document propDoc = DocumentHelper.createDocument();
    propDoc.setXMLEncoding("UTF-8");

    Element multiStatus = propDoc.addElement(TAG_MULTISTATUS, "DAV:");
    FileObject[] children = object.findFiles(new DepthFileSelector(depth));
    for (FileObject child : children) {
        Element responseEl = multiStatus.addElement(TAG_RESPONSE);
        try {//from  w w w .  j  a va  2s.c  o  m
            URL url = new URL(baseUrl, URLEncoder.encode(child.getName().getPath(), "UTF-8"));
            log("!! " + url);
            responseEl.addElement(TAG_HREF).addText(url.toExternalForm());
        } catch (Exception e) {
            e.printStackTrace();
        }
        DavResource resource = DavResourceFactory.getInstance().getDavResource(child);
        resource.setIgnoreValues(ignoreValues);
        resource.serializeToXml(responseEl, requestedProperties);
    }
    return propDoc;
}

From source file:com.thinkberg.moxo.dav.PropPatchHandler.java

License:Apache License

public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    FileObject object = getResourceManager().getFileObject(request.getPathInfo());

    try {/*from   w ww. java 2 s  . co  m*/
        LockManager.getInstance().checkCondition(object, getIf(request));
    } catch (LockException e) {
        if (e.getLocks() != null) {
            response.sendError(SC_LOCKED);
        } else {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        }
        return;
    }

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

        response.setContentType("text/xml");
        response.setCharacterEncoding("UTF-8");
        response.setStatus(SC_MULTI_STATUS);

        if (object.exists()) {
            Document resultDoc = DocumentHelper.createDocument();
            Element multiStatusResponse = resultDoc.addElement("multistatus", "DAV:");
            Element responseEl = multiStatusResponse.addElement("response");
            try {
                URL url = new URL(getBaseUrl(request), URLEncoder.encode(object.getName().getPath(), "UTF-8"));
                log("!! " + url);
                responseEl.addElement("href").addText(url.toExternalForm());
            } catch (Exception e) {
                e.printStackTrace();
            }

            Element propstatEl = responseEl.addElement("propstat");
            Element propEl = propstatEl.addElement("prop");

            Element propertyUpdateEl = propDoc.getRootElement();
            for (Object elObject : propertyUpdateEl.elements()) {
                Element el = (Element) elObject;
                if ("set".equals(el.getName())) {
                    for (Object propObject : el.elements()) {
                        setProperty(propEl, object, (Element) propObject);
                    }
                } else if ("remove".equals(el.getName())) {
                    for (Object propObject : el.elements()) {
                        removeProperty(propEl, object, (Element) propObject);
                    }
                }
            }
            propstatEl.addElement("status").addText(DavResource.STATUS_403);

            //        log(resultDoc);

            // write the actual response
            XMLWriter writer = new XMLWriter(response.getWriter(), OutputFormat.createCompactFormat());
            writer.write(resultDoc);
            writer.flush();
            writer.close();
        } else {
            log("!! " + object.getName().getPath() + " NOT FOUND");
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    } catch (DocumentException e) {
        log("!! inavlid request: " + e.getMessage());
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:com.thinkberg.webdav.LockHandler.java

License:Apache License

private void sendLockAcquiredResponse(HttpServletResponse response, Lock lock) throws IOException {
    if (!lock.getObject().exists()) {
        response.setStatus(SC_CREATED);// w w w .  j av a 2s. c o m
    }
    response.setContentType("text/xml");
    response.setCharacterEncoding("UTF-8");
    response.setHeader(HEADER_LOCK_TOKEN, "<" + lock.getToken() + ">");

    Document propDoc = DocumentHelper.createDocument();
    Element propEl = propDoc.addElement(TAG_PROP, "DAV:");
    Element lockdiscoveryEl = propEl.addElement(TAG_LOCKDISCOVERY);

    lock.serializeToXml(lockdiscoveryEl);

    XMLWriter xmlWriter = new XMLWriter(response.getWriter());
    xmlWriter.write(propDoc);

    logXml(propDoc);
}

From source file:com.thinkberg.webdav.PropFindHandler.java

License:Apache License

/**
 * Create a multistatus response by requesting all properties and writing a response for each
 * the found and the non-found properties
 *
 * @param object  the context object the propfind request applies to
 * @param propEl  the &lt;prop&gt; element containing the actual properties
 * @param baseUrl the base url of this server
 * @param depth   a depth argument for how deep the find will go
 * @return an XML document that is the response
 * @throws FileSystemException if there was an error executing the propfind request
 *//*  w  w  w . j  a  v a2 s  . com*/
private Document getMultiStatusResponse(FileObject object, Element propEl, URL baseUrl, int depth)
        throws FileSystemException {
    Document propDoc = DocumentHelper.createDocument();
    propDoc.setXMLEncoding("UTF-8");

    Element multiStatus = propDoc.addElement(TAG_MULTISTATUS, NAMESPACE_DAV);
    FileObject[] children = object.findFiles(new DepthFileSelector(depth));
    for (FileObject child : children) {
        Element responseEl = multiStatus.addElement(TAG_RESPONSE);
        try {
            URL url = new URL(baseUrl, URLEncoder.encode(child.getName().getPath(), "UTF-8"));
            responseEl.addElement(TAG_HREF).addText(url.toExternalForm());
        } catch (Exception e) {
            LOG.error("can't set href in response", e);
        }
        DavResource resource = DavResourceFactory.getInstance().getDavResource(child);
        resource.getPropertyValues(responseEl, propEl);
    }
    return propDoc;
}

From source file:com.thinkberg.webdav.PropPatchHandler.java

License:Apache License

/**
 * Get a multistatus response for each of the property set/remove requests.
 *
 * @param object              the context object the property requests apply to
 * @param requestedProperties the properties that should be set or removed
 * @param baseUrl             the base url of this server
 * @return an XML document that is the response
 * @throws FileSystemException if there is an error setting or removing a property
 *///from  w  w  w  . j a  va2 s.  c  om
private Document getMultiStatusResponse(FileObject object, List<Element> requestedProperties, URL baseUrl)
        throws FileSystemException {
    Document propDoc = DocumentHelper.createDocument();
    propDoc.setXMLEncoding("UTF-8");

    Element multiStatus = propDoc.addElement(TAG_MULTISTATUS, NAMESPACE_DAV);
    Element responseEl = multiStatus.addElement(TAG_RESPONSE);
    try {
        URL url = new URL(baseUrl, URLEncoder.encode(object.getName().getPath(), "UTF-8"));
        responseEl.addElement(TAG_HREF).addText(url.toExternalForm());
    } catch (Exception e) {
        LOG.error("can't set HREF tag in response", e);
    }
    DavResource resource = DavResourceFactory.getInstance().getDavResource(object);
    resource.setPropertyValues(responseEl, requestedProperties);
    return propDoc;
}

From source file:com.tmount.util.FileUtils.java

License:Open Source License

 /**
 * ?/*from w  ww.java  2  s . c o  m*/
 * @param fileName ??
 */
private static void initFile(String fileName){
      
   Document document = DocumentHelper.createDocument();
   Element root = document.addElement("auth");
   Element billdata = root.addElement("balance");
   billdata.setText("100");
   OutputFormat format = OutputFormat.createPrettyPrint();
   format.setEncoding("GBK");
   XMLWriter writer;
   try {
      writer = new XMLWriter(new FileWriter(new File(
            fileName)), format);
      writer.write(document); // 
      writer.close();
   } catch (IOException e) {
      log.info(" *** IOException *** ",e);
   }
      
}

From source file:com.uletian.ultcrm.business.service.CustomerInfoSyncService.java

public void notifycationDataChange(Customer customer) {
    StringWriter writer = new StringWriter();
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding("UTF-8");
    Document doc = DocumentHelper.createDocument();

    Namespace namespace = new Namespace("ns0", "http://crm/91jpfw.cn");
    Element root = doc.addElement(new QName("customer", namespace));
    root.addElement(new QName("action")).addText(action.BINDING_TEL.toString());
    root.addElement(new QName("sourceSys")).addText("ULTCRM");
    root.addElement(new QName("ultcrmid")).addText(customer.getId().toString());
    root.addElement(new QName("crmid")).addText(customer.getSyncid() == null ? "" : customer.getSyncid());
    String name = null;//w  w w. ja  va 2  s.  c o  m
    if (customer.getName() == null || "".equals(customer.getName())) {
        name = customer.getNickname();
    } else {
        name = customer.getName();
    }
    root.addElement(new QName("name")).addText(name);
    root.addElement(new QName("sexy")).addText(customer.getSex() == null ? "" : customer.getSex());
    root.addElement(new QName("telephone")).addText(customer.getPhone() == null ? "" : customer.getPhone());
    root.addElement(new QName("country")).addText(customer.getCountry() == null ? "" : customer.getCountry());
    root.addElement(new QName("province"))
            .addText(customer.getProvince() == null ? "" : customer.getProvince());
    root.addElement(new QName("city")).addText(customer.getCity() == null ? "" : customer.getCity());
    root.addElement(new QName("address")).addText(customer.getAddress() == null ? "" : customer.getAddress());
    root.addElement(new QName("postcode"))
            .addText(customer.getPostcode() == null ? "" : customer.getPostcode());
    Element techsElement = root.addElement(new QName("techs"));
    List<Tech> techs = customer.getTechs();
    if (techs != null && techs.size() > 0) {
        for (int i = 0; i < techs.size(); i++) {
            Tech tech = techs.get(i);
            Element techElement = techsElement.addElement("tech");

            techElement.addElement(new QName("crmtechid"))
                    .addText(tech.getCrmTechId() == null ? "" : tech.getCrmTechId());
            techElement.addElement(new QName("code")).addText(tech.getTechModel().getCode());
            techElement.addElement(new QName("techlevelno"))
                    .addText(tech.getTechlevelno() == null ? "" : tech.getTechlevelno());
            techElement.addElement(new QName("techerno"))
                    .addText(tech.getTecherno() == null ? "" : tech.getTecherno());
            techElement.addElement(new QName("techname"))
                    .addText(tech.getTechname() == null ? "" : tech.getTechname());
            techElement.addElement(new QName("coursetime"))
                    .addText(tech.getCoursetime() == null ? "" : tech.getCoursetime());
            String trainExpireDate = "";
            if (tech.getTrainExpireDate() != null) {
                trainExpireDate = sdf.format(tech.getTrainExpireDate());
            }
            techElement.addElement(new QName("trainExpireDate")).addText(trainExpireDate);
            techElement.addElement(new QName("trainCompany"))
                    .addText(tech.getTrainCompany() == null ? "" : tech.getTrainCompany());
            techElement.addElement(new QName("courseCode"))
                    .addText(tech.getCourseCode() == null ? "" : tech.getCourseCode());
            techElement.addElement(new QName("techColor"))
                    .addText(tech.getColor() == null ? "" : tech.getColor());
            String registerDate = "";
            if (tech.getRegisterDate() != null) {
                registerDate = sdf.format(tech.getRegisterDate());
            }
            techElement.addElement(new QName("registerDate")).addText(registerDate);
            techElement.addElement(new QName("courseLicense"))
                    .addText(tech.getCourseLicense() == null ? "" : tech.getCourseLicense());
            String checkExpireDate = "";
            if (tech.getCheckExpireDate() != null) {
                checkExpireDate = sdf.format(tech.getCheckExpireDate());
            }
            techElement.addElement(new QName("checkExpireDate")).addText(checkExpireDate);
            techElement.addElement(new QName("memberLevel"))
                    .addText(tech.getMemberLevel() == null ? "" : tech.getMemberLevel());

            // ? by xiecheng 2015-11-19
            techElement.addElement(new QName("nextMaintCoursetime"))
                    .addText(StringUtils.isNoneBlank(tech.getNextMaintCoursetime())
                            ? tech.getNextMaintCoursetime()
                            : "");

            String nextMaintDate = "";
            if (tech.getNextMaintDate() != null) {
                nextMaintDate = sdf.format(tech.getNextMaintDate());
            }
            techElement.addElement(new QName("nextMaintDate")).addText(nextMaintDate);

            String lastConsumeDate = "";
            if (tech.getLastConsumeDate() != null) {
                lastConsumeDate = sdf.format(tech.getLastConsumeDate());
            }
            techElement.addElement(new QName("lastConsumeDate")).addText(lastConsumeDate);

        }
    }
    XMLWriter xmlwriter = new XMLWriter(writer, format);
    try {
        xmlwriter.write(doc);
    } catch (IOException e) {
    }
    customerInfoMessageService.sendMessage(writer.toString());

}