Example usage for org.dom4j Document setXMLEncoding

List of usage examples for org.dom4j Document setXMLEncoding

Introduction

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

Prototype

void setXMLEncoding(String encoding);

Source Link

Document

Sets the encoding of this document as it will appear in the XML declaration part of the document.

Usage

From source file:com.glaf.jbpm.xml.JpdlXmlReader.java

License:Apache License

public void convert(File dir) {
    if (!(dir.exists() || dir.isDirectory())) {
        return;//w w  w .  jav  a 2s . c o  m
    }
    String[] filelist = dir.list();
    for (int i = 0; i < filelist.length; i++) {
        String filename = dir.getAbsolutePath() + "/" + filelist[i];
        java.io.File file = new java.io.File(filename);
        if (file.isDirectory()) {
            this.convert(file);
        } else if (file.isFile() && file.getName().equals("processdefinition.xml")) {
            List<Todo> todoList = null;
            try {
                todoList = this.read(new FileInputStream(file));
            } catch (FileNotFoundException ex) {
                ex.printStackTrace();
            }
            if (todoList != null && todoList.size() > 0) {
                index = index + 100;
                Document doc = DocumentHelper.createDocument();
                doc.setXMLEncoding("GBK");
                Element root = doc.addElement("rows");
                Iterator<Todo> iter = todoList.iterator();
                while (iter.hasNext()) {
                    Todo todo = (Todo) iter.next();
                    Map<String, Object> dataMap = Tools.getDataMap(todo);
                    dataMap.remove("id");
                    dataMap.remove("locked");
                    dataMap.remove("configFlag");
                    dataMap.remove("versionNo");
                    Element row = root.addElement("row");
                    row.addAttribute("id", String.valueOf(index++));
                    Set<Entry<String, Object>> entrySet = dataMap.entrySet();
                    for (Entry<String, Object> entry : entrySet) {
                        String key = entry.getKey();
                        Object value = entry.getValue();
                        if (value != null && !(value instanceof Map<?, ?>) && !(value instanceof Set<?>)
                                && !(value instanceof Collection<?>)) {
                            Element elem = row.addElement("property");
                            elem.addAttribute("name", key);
                            if (key.equals("link") || key.equals("listLink")) {
                                elem.addCDATA(sp + "        " + value.toString());
                            } else {
                                elem.addAttribute("value", value.toString());
                            }
                        }
                    }
                }
                filename = dir.getAbsolutePath() + "/" + "todo.xml";
                Dom4jUtils.savePrettyDoument(doc, filename, "GBK");
                doc = null;
                root = null;
            }
        }
    }
}

From source file:com.gst.mix.service.XBRLBuilder.java

License:Apache License

public String build(final Map<MixTaxonomyData, BigDecimal> map, final Date startDate, final Date endDate,
        final String currency) {
    this.instantScenarioCounter = 1;
    this.durationScenarioCounter = 1;
    this.contextMap = new HashMap<>();
    final Document doc = DocumentHelper.createDocument();
    this.root = doc.addElement("xbrl");

    this.root.addElement("schemaRef").addNamespace("link",
            "http://www.themix.org/sites/default/files/Taxonomy2010/dct/dc-all_2010-08-31.xsd");

    this.startDate = startDate;
    this.endDate = endDate;

    for (final Entry<MixTaxonomyData, BigDecimal> entry : map.entrySet()) {
        final MixTaxonomyData taxonomy = entry.getKey();
        final BigDecimal value = entry.getValue();
        addTaxonomy(this.root, taxonomy, value);

    }//from  w  w w  .j  a v  a 2s  .  com

    addContexts();
    addCurrencyUnit(currency);
    addNumberUnit();

    doc.setXMLEncoding("UTF-8");

    return doc.asXML();
}

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 {/*  w  w w . ja  v a  2 s. c  om*/
            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.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  . ja  v a2  s.  c o  m
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
 *///w  w w  . j a va  2  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.weibo.datasys.crawler.impl.crawlUnit.fetcher.wxcs.WXCSFetcher.java

License:Open Source License

@Override
protected void configPostReq(SeedData seedData, DownRequest req) {
    Document doc = DocumentHelper.createDocument();
    doc.setXMLEncoding("utf-8");
    // //from w w  w.  j  a  v  a 2s  . c o m
    Element root = doc.addElement("root");
    // transactionid
    root.addElement("transactionid").addText("");
    // timestamp
    root.addElement("timestamp").addText(sdf.format(new Date()));
    // msgname
    String msgname = seedData.getExtendField(POST_FIELD_PREFIX + "msgname");
    msgname = StringUtils.nullToEmpty(msgname);
    root.addElement("msgname").addText(msgname);
    // result
    root.addElement("result").addText("");
    // resultdesc
    root.addElement("resultdesc").addText("");
    // body
    Element body = root.addElement("body");
    // dircode ?, root
    String dircode = seedData.getExtendField(POST_FIELD_PREFIX + "dircode");
    dircode = StringUtils.nullToEmpty(dircode);
    body.addElement("dircode").addText(dircode);
    // areacode ???
    String areacode = seedData.getExtendField(POST_FIELD_PREFIX + "areacode");
    areacode = StringUtils.nullToEmpty(areacode);
    body.addElement("areacode").addText(areacode);
    // nodeversion ??
    String nodeversion = seedData.getExtendField(POST_FIELD_PREFIX + "nodeversion");
    nodeversion = StringUtils.nullToEmpty(nodeversion);
    body.addElement("nodeversion").addText(nodeversion);
    // depth ?[0..10]?10
    // ?0?????
    // ?>0????
    String depth = seedData.getExtendField(POST_FIELD_PREFIX + "depth");
    depth = StringUtils.nullToEmpty(depth);
    body.addElement("depth").addText(depth);
    // returenres ???
    // 0
    // 1?
    // ?
    String returenres = seedData.getExtendField(POST_FIELD_PREFIX + "returenres");
    if (StringUtils.isEmptyString(returenres)) {
        returenres = "1";
    }
    body.addElement("returenres").addText(returenres);

    req.setContentType("text/xml");
    req.setPostString(doc.asXML());
}

From source file:de.codecentric.multitool.xml.XmlLibrary.java

License:Apache License

/**
 * Konvertiert einen XML-String in ein XML-Document
 * /*from  w w w  .  j a  v  a  2s  .  co  m*/
 * | ${xmlDoc} = | Get Xml From String | ${xmlString} |
 */
public Document getXmlFromString(String xmlString) {
    try {
        Document result = null;
        SAXReader reader = new SAXReader();
        InputSource source = new InputSource(new StringReader(xmlString));
        source.setEncoding(XML_ENCODING);
        result = reader.read(source);
        if (result.getXMLEncoding() == null)
            result.setXMLEncoding(XML_ENCODING);
        return result;
    } catch (DocumentException e) {
        throw new RuntimeException("Der String " + xmlString + " kann nicht geparst werden" + e);
    }
}

From source file:de.thischwa.pmcms.model.tool.WriteBackup.java

License:LGPL

@Override
public void run() {
    logger.debug("Try to backup [" + site.getUrl() + "].");
    if (monitor != null)
        monitor.beginTask(LabelHolder.get("task.backup.monitor").concat(" ").concat(String.valueOf(pageCount)),
                pageCount * 2 + 1);/* ww w .  j a v  a 2 s. c o m*/

    // Create file infrastructure.
    File dataBaseXml = null;
    try {
        dataBaseXml = File.createTempFile("database", ".xml", Constants.TEMP_DIR.getAbsoluteFile());
    } catch (IOException e1) {
        throw new RuntimeException(
                "Can't create temp file for the database xml file because: " + e1.getMessage(), e1);
    }

    Document dom = DocumentHelper.createDocument();
    dom.setXMLEncoding(Constants.STANDARD_ENCODING);

    Element siteEl = dom.addElement("site").addAttribute("version", IBackupParser.DBXML_2).addAttribute("url",
            site.getUrl());
    siteEl.addElement("title").addCDATA(site.getTitle());

    Element elementTransfer = siteEl.addElement("transfer");
    elementTransfer.addAttribute("host", site.getTransferHost())
            .addAttribute("user", site.getTransferLoginUser())
            .addAttribute("password", site.getTransferLoginPassword())
            .addAttribute("startdir", site.getTransferStartDirectory());

    for (Macro macro : site.getMacros()) {
        Element marcoEl = siteEl.addElement("macro");
        marcoEl.addElement("name").addCDATA(macro.getName());
        marcoEl.addElement("text").addCDATA(macro.getText());
    }

    if (site.getLayoutTemplate() != null) {
        Template template = site.getLayoutTemplate();
        Element templateEl = siteEl.addElement("template");
        init(templateEl, template);
    }
    for (Template template : site.getTemplates()) {
        Element templateEl = siteEl.addElement("template");
        init(templateEl, template);
    }

    if (!CollectionUtils.isEmpty(site.getPages()))
        for (Page page : site.getPages())
            addPageToElement(siteEl, page);

    for (Level level : site.getSublevels())
        addLevelToElement(siteEl, level);

    OutputStream out = null;
    try {
        // It's really important to use the XMLWriter instead of the FileWriter because the FileWriter takes the default
        // encoding of the OS. This my cause some trouble with special chars on some OSs!
        out = new BufferedOutputStream(new FileOutputStream(dataBaseXml));
        OutputFormat outformat = OutputFormat.createPrettyPrint();
        outformat.setEncoding(Constants.STANDARD_ENCODING);
        XMLWriter writer = new XMLWriter(out, outformat);
        writer.write(dom);
        writer.flush();
    } catch (IOException e) {
        throw new FatalException("While exporting the database xml: " + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(out);
    }

    // Generate the zip file, cache and export dir will be ignored.
    File backupZip = new File(InitializationManager.getSitesBackupDir(),
            site.getUrl().concat("_").concat(new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date())
                    .concat(".").concat(Constants.BACKUP_EXTENSION)));
    List<File> filesToIgnore = new ArrayList<File>();
    filesToIgnore.add(PoPathInfo.getSiteImageCacheDirectory(site).getAbsoluteFile());
    filesToIgnore.add(PoPathInfo.getSiteExportDirectory(site).getAbsoluteFile());
    Collection<File> filesToBackup = FileTool.collectFiles(PoPathInfo.getSiteDirectory(site).getAbsoluteFile(),
            filesToIgnore);
    File sitesDir = InitializationManager.getSitesDir();
    Map<File, String> zipEntries = new HashMap<File, String>();
    for (File file : filesToBackup) {
        String entryName = file.getAbsolutePath().substring(sitesDir.getAbsolutePath().length() + 1);
        entryName = StringUtils.replace(entryName, File.separator, "/"); // Slashes are zip conform
        zipEntries.put(file, entryName);
        incProgressValue();
    }
    zipEntries.put(dataBaseXml, "db.xml");
    try {
        if (monitor != null)
            monitor.beginTask(LabelHolder.get("zip.compress").concat(String.valueOf(zipEntries.size())),
                    zipEntries.size());
        Zip.compressFiles(backupZip, zipEntries, monitor);
    } catch (IOException e) {
        throw new FatalException("While generating zip: " + e.getMessage(), e);
    }
    dataBaseXml.delete();
    logger.info("Site backuped successfull to [".concat(backupZip.getAbsolutePath()).concat("]!"));
}

From source file:de.thischwa.pmcms.tool.ChecksumTool.java

License:LGPL

/**
 * Converting a Map with the file checksums to a dom.
 *///from  w ww  . j a va  2 s  . c  o m
public static Document getDomChecksums(final Map<String, String> checksums) {
    Document dom = DocumentHelper.createDocument();
    dom.setXMLEncoding(Constants.STANDARD_ENCODING);
    Element root = dom.addElement("checksums");
    for (String name : checksums.keySet()) {
        Element fileElement = root.addElement("file");
        Element nameElement = fileElement.addElement("name");
        nameElement.addCDATA(name);
        Element hashElement = fileElement.addElement("checksum");
        hashElement.addText(checksums.get(name));
    }
    return dom;
}

From source file:de.thischwa.pmcms.view.renderer.VelocityUtils.java

License:LGPL

/**
 * Replace the img-tag and a-tag with the equivalent velocity macro. Mainly used before saving a field value to the database.
 * /*from   ww w.  j  a va  2s. co  m*/
 * @throws RenderingException
 *             If any exception was thrown while replacing the tags.
 */
@SuppressWarnings("unchecked")
public static String replaceTags(final Site site, final String oldValue) throws RenderingException {
    if (StringUtils.isBlank(oldValue))
        return null;

    // 1. add a root element (to have a proper xml) and replace the ampersand
    String newValue = String.format("<dummytag>\n%s\n</dummytag>",
            StringUtils.replace(oldValue, "&", ampReplacer));
    Map<String, String> replacements = new HashMap<String, String>();

    try {
        Document dom = DocumentHelper.parseText(newValue);
        dom.setXMLEncoding(Constants.STANDARD_ENCODING);

        // 2. Collect the keys, identify the img-tags.
        List<Node> imgs = dom.selectNodes("//img", ".");
        for (Node node : imgs) {
            Element element = (Element) node;
            if (element.attributeValue("src").startsWith("/")) // only internal links have to replaced with a velocity macro
                replacements.put(node.asXML(),
                        generateVelocityImageToolCall(site, element.attributeIterator()));
        }

        // 3. Collect the keys, identify the a-tags
        List<Node> links = dom.selectNodes("//a", ".");
        for (Node node : links) {
            Element element = (Element) node;
            if (element.attributeValue("href").startsWith("/")) // only internal links have to replaced with a velocity macro
                replacements.put(element.asXML(), generateVelocityLinkToolCall(site, element));
        }

        // 4. Replace the tags with the velomacro.
        StringWriter stringWriter = new StringWriter();
        XMLWriter writer = new XMLWriter(stringWriter, sourceFormat);
        writer.write(dom.selectSingleNode("dummytag"));
        writer.close();
        newValue = stringWriter.toString();
        for (String stringToReplace : replacements.keySet())
            newValue = StringUtils.replace(newValue, stringToReplace, replacements.get(stringToReplace));
        newValue = StringUtils.replace(newValue, "<dummytag>", "");
        newValue = StringUtils.replace(newValue, "</dummytag>", "");

    } catch (Exception e) {
        throw new RenderingException("While preprocessing the field value: " + e.getMessage(), e);
    }

    return StringUtils.replace(newValue, ampReplacer, "&");
}