Example usage for org.dom4j.io OutputFormat createPrettyPrint

List of usage examples for org.dom4j.io OutputFormat createPrettyPrint

Introduction

In this page you can find the example usage for org.dom4j.io OutputFormat createPrettyPrint.

Prototype

public static OutputFormat createPrettyPrint() 

Source Link

Document

A static helper method to create the default pretty printing format.

Usage

From source file:DAO.LocationDAO.java

public boolean addNewLocation(String webAppPath, String location) {
    try {/*from   w  ww  . j a va  2  s . c o m*/
        SAXReader reader = new SAXReader();
        Document document = reader.read(webAppPath + "/xml/Locations.xml");
        Element root = document.getRootElement();
        int max = 0;
        for (Iterator i = root.elementIterator("Location"); i.hasNext();) {
            Element elt = (Element) i.next();
            int cur = Integer.parseInt(elt.element("LocationId").getText());
            if (cur > max) {
                max = cur;
            }
        }

        Integer newLocationId = max + 1;
        Element newLocation = root.addElement("Location");
        newLocation.addElement("LocationId").setText(newLocationId.toString());
        newLocation.addElement("Name").setText(location);
        root.appendAttributes(newLocation);
        try {
            FileOutputStream fos = new FileOutputStream(webAppPath + "/xml/Locations.xml");
            OutputFormat format = OutputFormat.createPrettyPrint();
            XMLWriter xmlwriter = new XMLWriter(fos, format);
            xmlwriter.write(document);
            System.out.println("dead");
            xmlwriter.close();
        } catch (Exception ex) {
            System.out.println("Failed!");
            ex.printStackTrace();
        }
        //Node node = document.selectSingleNode("/Locations/Location[not(../Location/LocationId > LocationId)]");
        //String id = node.valueOf("LocationId");
        //System.out.println(id);
        return true;
    } catch (DocumentException ex) {
        System.out.println("Add New Location Failed!");
        Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }
}

From source file:datasource.XMLTools.java

License:Open Source License

public static long writeToXML(Document doc, String Filename) {
    long errorcode = 0;

    try {//from   ww w  .  j a v  a  2  s .c  o m
        OutputFormat outformat = OutputFormat.createPrettyPrint();
        outformat.setEncoding("UTF-8");
        FileOutputStream out = new FileOutputStream(Filename);
        XMLWriter writer = new XMLWriter(out, outformat);
        writer.write(doc);
        writer.flush();
    } catch (Exception x) {
        System.out.println(x.getMessage());
        errorcode = x.hashCode();
    }
    return errorcode;
}

From source file:de.ailis.wlandsuite.game.blocks.GameBlock.java

License:Open Source License

/**
 * Writes the block to a stream as XML/*from w  w w. j  a  va  2s  .co  m*/
 *
 * @param stream
 *            The output stream
 * @throws IOException
 *             When file operation fails.
 */

public void writeXml(final OutputStream stream) throws IOException {
    XMLWriter writer;
    Document document;
    OutputFormat format;

    format = OutputFormat.createPrettyPrint();
    format.setTrimText(false);

    writer = new XMLWriter(stream, format);
    try {
        final Element rootElement = toXml();
        document = DocumentHelper.createDocument(rootElement);
        writer.write(document);
    } finally {
        writer.close();
    }
}

From source file:de.ailis.xadrian.utils.XmlUtils.java

License:Open Source License

/**
 * Writes the specified document to the specified file.
 *
 * @param document/*from w w  w  . j a va2s  .co  m*/
 *            The document to write
 * @param file
 *            The file to write to
 * @throws IOException
 *             If file could not be written
 */
public static void write(final Document document, final File file) throws IOException {
    final OutputFormat format = OutputFormat.createPrettyPrint();
    final XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"), format);
    try {
        writer.write(document);
    } finally {
        writer.close();
    }
}

From source file:de.awtools.xml.TransformerUtils.java

License:Open Source License

/**
 * Schreibt ein dom4j Dokument in eine Datei.
 *
 * @param document Ein dom4j Dokument./*  ww w.  ja v  a 2  s.  co  m*/
 * @param file Die zu schreibende Datei.
 * @param encoding Das Encoding.
 * @throws UnhandledException Da ging was schief.
 */
public static void toFile(final Document document, final File file, final String encoding)
        throws UnhandledException {

    XMLWriter writer = null;
    try {
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding(encoding);
        writer = new XMLWriter(new FileWriter(file), format);
        writer.write(document);
    } catch (IOException ex) {
        log.debug("Fehler: ", ex);
        throw new UnhandledException(ex);
    } finally {
        XMLUtils.close(writer);
    }
}

From source file:de.innovationgate.utils.WGUtils.java

License:Apache License

/**
 * Creates a directory link file pointing to a target path
 * @param parentDir The directory to contain the link file
 * @param target The target path that the directory link should point to
 * @throws IOException/*from   www.  j  av a  2  s  . c  o  m*/
 */
public static void createDirLink(File parentDir, String target) throws IOException {
    File link = new File(parentDir, DIRLINK_FILE);
    Document doc = DocumentFactory.getInstance().createDocument();
    Element dirlink = doc.addElement("dirlink");
    Element path = dirlink.addElement("path");
    path.addAttribute("location", target);
    XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint());
    writer.setOutputStream(new FileOutputStream(link));
    writer.write(doc);
    writer.close();
}

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

License:Open Source License

/**
 * writes the current configuration to file
 * @throws IOException/*from  w  w  w  .j a v  a 2  s .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.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 ww  w .j  a va 2 s.  co m
    outputFormat.setNewlines(true);

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

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 ww  .j av  a2s  . 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.view.renderer.ExportRenderer.java

License:LGPL

/**
 * Start the export of the static html pages.
 * //from  w w w.  j  a v a  2 s. c o m
 * @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();
    }
}