Example usage for org.dom4j.io XMLWriter write

List of usage examples for org.dom4j.io XMLWriter write

Introduction

In this page you can find the example usage for org.dom4j.io XMLWriter write.

Prototype

public void write(Object object) throws IOException 

Source Link

Document

Writes the given object which should be a String, a Node or a List of Nodes.

Usage

From source file:de.innovationgate.wgpublisher.lucene.LuceneIndexConfiguration.java

License:Open Source License

/**
 * writes the current configuration to file
 * @throws IOException//w w  w.j  av a 2s . c  o m
 */
private void writeConfigDoc() throws IOException {
    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter(new FileWriter(_configFile), format);
    writer.write(_configDoc);
    writer.flush();
    writer.close();
}

From source file:de.innovationgate.wgpublisher.WebTMLDebugger.java

License:Open Source License

/**
 * @param request/*  w  w w  .j av  a2 s  .  co  m*/
 * @param response
 * @param session
 * @throws HttpErrorException
 * @throws IOException
 */
private void sendDebugDoc(HttpServletRequest request, HttpServletResponse response, HttpSession session)
        throws HttpErrorException, IOException {
    String urlStr = request.getParameter("url");
    String indexStr = request.getParameter("index");

    if (urlStr != null) {
        urlStr = _dispatcher.getCore().getURLEncoder().decode(urlStr);
        List<Document> debugDocuments = WGACore.getDebugDocumentsList(session);
        Document debugDoc;
        for (int idx = 0; idx < debugDocuments.size(); idx++) {
            debugDoc = (Document) debugDocuments.get(idx);
            if (debugDoc.getRootElement().attributeValue("url", "").equals(urlStr)) {
                indexStr = String.valueOf(idx);
                break;
            }
        }
    }

    if (indexStr != null) {
        int index = Integer.valueOf(indexStr).intValue();
        List<Document> debugDocuments = WGACore.getDebugDocumentsList(session);
        if (index == -1) {
            index = debugDocuments.size() - 1;
        }
        if (index >= debugDocuments.size()) {
            throw new HttpErrorException(HttpServletResponse.SC_BAD_REQUEST,
                    "Index out of range: " + index + " where maximum index is " + (debugDocuments.size() - 1),
                    null);
        } else {
            Document doc = (Document) debugDocuments.get(index);
            response.setContentType("text/xml");
            XMLWriter writer = new XMLWriter(response.getWriter());
            writer.write(doc);
        }
    } else {
        throw new HttpErrorException(HttpServletResponse.SC_BAD_REQUEST,
                "You must include either parameter index or url to address the debug document to show", null);
    }
}

From source file:de.innovationgate.wgpublisher.WGACore.java

License:Open Source License

public String updateConfigDocument(Document newConfig) throws UnsupportedEncodingException,
        FileNotFoundException, IOException, ParserConfigurationException, DocumentException {
    String newTimestamp = WGACore.DATEFORMAT_GMT.format(new Date());
    newConfig.getRootElement().addAttribute("timestamp", newTimestamp);

    OutputFormat outputFormat = OutputFormat.createPrettyPrint();
    outputFormat.setTrimText(true);//from w  w  w.  jav a  2s  .c  om
    outputFormat.setNewlines(true);

    XMLWriter writer = new XMLWriter(new FileOutputStream(getConfigFile()), outputFormat);
    writer.write(newConfig);
    writer.close();
    return newTimestamp;
}

From source file:de.matzefratze123.heavyspleef.persistence.handler.CachingReadWriteHandler.java

License:Open Source License

@Override
public void saveGame(Game game) throws IOException {
    File gameFile = new File(xmlFolder, game.getName() + ".xml");
    if (!gameFile.exists()) {
        gameFile.createNewFile();//from  ww  w  . j  ava  2 s  .c  om
    }

    Document document = DocumentHelper.createDocument();
    Element rootElement = document.addElement("game");

    xmlContext.write(game, rootElement);

    File gameSchematicFolder = new File(schematicFolder, game.getName());
    if (!gameSchematicFolder.exists()) {
        gameSchematicFolder.mkdir();
    }

    XMLWriter writer = null;

    try {
        FileOutputStream out = new FileOutputStream(gameFile);

        writer = new XMLWriter(out, xmlOutputFormat);
        writer.write(document);
    } finally {
        if (writer != null) {
            writer.close();
        }
    }

    for (Floor floor : game.getFloors()) {
        File floorFile = new File(gameSchematicFolder, getFloorFileName(floor));
        if (!floorFile.exists()) {
            floorFile.createNewFile();
        }

        schematicContext.write(floorFile, floor);
    }
}

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);/*from   w w  w. j a v a 2 s  .  com*/

    // 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.view.renderer.ExportRenderer.java

License:LGPL

/**
 * Start the export of the static html pages.
 * /*from w  ww .ja  va2s .  c om*/
 * @throws RuntimeException if an exception is happened during rendering.
 */
@Override
public void run() {
    logger.debug("Entered run.");
    File siteDir = PoPathInfo.getSiteDirectory(this.site);
    if (monitor != null)
        monitor.beginTask(
                String.format("%s: %d", LabelHolder.get("task.export.monitor"), this.renderableObjects.size()),
                this.renderableObjects.size()); //$NON-NLS-1$

    if (CollectionUtils.isEmpty(site.getPages()))
        renderRedirector();

    try {
        FileUtils.cleanDirectory(exportDir);

        // build the directory structure for the renderables
        for (IRenderable ro : renderableObjects) {
            File dir = PathTool.getExportFile(ro, poExtension).getParentFile();
            if (!dir.exists())
                dir.mkdirs();
        }

        // loop through the renderable objects
        renderRenderables();

        if (!exportController.isError() && !isInterruptByUser) {
            logger.debug("Static export successfull!");

            // extra files to copy
            Set<File> filesToCopy = renderData.getFilesToCopy();
            for (File srcFile : filesToCopy) {
                String exportPathPart = srcFile.getAbsolutePath()
                        .substring(siteDir.getAbsolutePath().length() + 1);
                File destFile = new File(exportDir, exportPathPart);
                if (srcFile.isFile())
                    FileUtils.copyFile(srcFile, destFile);
            }
            logger.debug("Extra files successful copied!");

            // generate hashes
            Collection<File> exportedFiles = FileTool.collectFiles(exportDir);
            if (monitor != null) {
                monitor.done();
                monitor.beginTask("Calculate checksums", exportedFiles.size());
            }
            Document dom = ChecksumTool
                    .getDomChecksums(ChecksumTool.get(exportedFiles, exportDir.getAbsolutePath(), monitor));
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            OutputFormat outformat = OutputFormat.createPrettyPrint();
            outformat.setEncoding(Constants.STANDARD_ENCODING);
            XMLWriter writer = new XMLWriter(out, outformat);
            writer.write(dom);
            writer.flush();
            String formatedDomString = out.toString();
            InputStream in = new ByteArrayInputStream(formatedDomString.getBytes());
            Map<InputStream, String> toCompress = new HashMap<InputStream, String>();
            toCompress.put(in, checksumFilename);
            File zipFile = new File(PoPathInfo.getSiteExportDirectory(site),
                    FilenameUtils.getBaseName(checksumFilename) + ".zip");
            Zip.compress(zipFile, toCompress);
            zipFile = null;
        } else
            FileUtils.cleanDirectory(exportDir);
    } catch (Exception e) {
        logger.error("Error while export: " + e.getMessage(), e);
        throw new FatalException("Error while export " + this.site.getUrl() + e.getMessage(), e);
    } finally {
        if (monitor != null)
            monitor.done();
    }
}

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.
 * // www . j  ava  2s.c  om
 * @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, "&");
}

From source file:de.tud.kom.p2psim.impl.network.gnp.topology.HostMap.java

License:Open Source License

/**
 * saves host postion location, GNP position, groups, GNP Space, PingER
 * Lookup table in an xml file used within the simulation
 * //from w w  w .j a va  2s . c  om
 * @param file
 */
public void exportToXml(File file) {
    log.debug("Export Hosts to an XML File");
    try {
        OutputFormat format = OutputFormat.createPrettyPrint();
        OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
        XMLWriter writer = new XMLWriter(out, format);
        writer.write(getDocument());
        writer.close();
    } catch (IOException e) {
        System.out.println(e);
    }
}

From source file:de.tud.kom.p2psim.impl.vis.util.Config.java

License:Open Source License

/**
 * Schreibt die bestehende XML-Struktur in die Config-Datei
 *//*from  w w  w  .ja  v  a2s .  c om*/
public static void writeXMLFile() {

    if (config != null) { // Schreibe Datei nur, wenn XML-Baum im Speicher
        // vorhanden
        try {
            OutputFormat format = OutputFormat.createPrettyPrint();
            XMLWriter writer = new XMLWriter(new FileWriter(configFile), format);
            writer.write(Config.config);
            writer.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:de.tudarmstadt.ukp.dkpro.lab.uima.engine.uimaas.AsDeploymentDescription.java

License:Apache License

public void toXML(OutputStream aOutput) throws IOException {
    Element root = createElement(E_ROOT);
    if (getName() != null) {
        root.addElement(E_NAME).setText(getName());
    }/*  ww  w  . j  a v a  2 s .  c  om*/
    if (getDescription() != null) {
        root.addElement(E_DESCRIPTION).setText(getDescription());
    }
    if (getVendor() != null) {
        root.addElement(E_VENDOR).setText(getVendor());
    }
    if (getVersion() != null) {
        root.addElement(E_VERSION).setText(getVersion());
    }

    Element deployment = root.addElement(E_DEPLOYMENT).addAttribute(A_PROTOCOL, getProtocol())
            .addAttribute(A_PROVIDER, getProvider());

    Element service = deployment.addElement(E_SERVICE);
    service.addElement(E_INPUT_QUEUE).addAttribute(A_ENDPOINT, getEndpoint())
            .addAttribute(A_BROKER_URL, getBrokerUrl()).addAttribute(A_PREFETCH, getPrefetch());
    service.addElement(E_TOP_DESCRIPTOR).addElement(E_IMPORT).addAttribute(A_LOCATION,
            getTopDescriptorFile().getAbsolutePath());

    OutputFormat outformat = OutputFormat.createPrettyPrint();
    outformat.setEncoding("UTF-8");
    XMLWriter writer = new XMLWriter(aOutput, outformat);
    writer.write(createDocument(root));
    writer.flush();
}