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:de.innovationgate.wgpublisher.webtml.Root.java

License:Open Source License

private void enableDebug(HttpSession session, Status status) {
    Document doc = DocumentHelper.createDocument();
    Element rootElement = doc.addElement("tmldebugdocument");
    rootElement.addAttribute("url", WGUtils.reduce(getStatus().getRequestURL(), 100));
    rootElement.addAttribute("started", DEBUG_TIMESTAMP_FORMAT.format(new Date()));
    rootElement.addAttribute("traceresults",
            String.valueOf(session.getAttribute(WGACore.ATTRIB_TMLDEBUG_TRACE_RESULTS)));
    rootElement.addAttribute("traceoptions",
            String.valueOf(session.getAttribute(WGACore.ATTRIB_TMLDEBUG_TRACE_OPTIONS)));
    rootElement.addAttribute("ajax", status._ajax ? "true" : "false");
    List<Document> debugDocuments = WGACore.getDebugDocumentsList(session);
    debugDocuments.add(doc);/*w  w w . ja v a2  s . c o m*/
    createDebugNode(rootElement);
    status.iterationDebugNode = status.debugNode.addElement("starttag");
    try {
        getStatus().debugNode.addAttribute("context", getTMLContext().getpath());
    } catch (WGAPIException e) {
        getStatus().debugNode.addAttribute("context", "Unable to retrieve contextpath bc. of exception: "
                + e.getClass().getName() + " message: " + e.getMessage());
    }
}

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 w w w .ja  v a  2 s  .  com
    }

    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);/*  w w w .  j  a va 2s .c  om*/

    // 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.
 *///w  ww . j  av a2s  .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.xaniox.heavyspleef.migration.GameMigrator.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//from ww  w .  j a va2 s.  com
public void migrate(Configuration inputSource, File outputFolder, Object cookie) throws MigrationException {
    if (cookie == null || !(cookie instanceof List<?>)) {
        throw new MigrationException("Cookie must be a game of lists");
    }

    countMigrated = 0;

    List<Game> gameList = (List<Game>) cookie;
    Set<String> gameNames = inputSource.getKeys(false);

    for (String name : gameNames) {
        ConfigurationSection section = inputSource.getConfigurationSection(name);

        File xmlFile = new File(outputFolder, name + FILE_EXTENSION);
        if (xmlFile.exists()) {
            //Rename this game as there is already a file
            xmlFile = new File(outputFolder, name + "_1" + FILE_EXTENSION);
        }

        XMLWriter writer = null;

        try {
            xmlFile.createNewFile();

            GameAccessor accessor = new GameAccessor(heavySpleef);
            Document document = DocumentHelper.createDocument();
            Element rootElement = document.addElement("game");

            Game game = migrateGame(section, rootElement);
            if (game == null) {
                continue;
            }

            accessor.write(game, rootElement);
            gameList.add(game);

            OutputStream out = new FileOutputStream(xmlFile);
            writer = new XMLWriter(out, outputFormat);
            writer.write(document);
            ++countMigrated;
        } catch (IOException e) {
            throw new MigrationException(e);
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                }
            }
        }
    }
}

From source file:de.xaniox.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();//  ww  w  .  ja  v  a  2s  .  c o  m
    }

    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 (File file : gameSchematicFolder.listFiles(FLOOR_SCHEMATIC_FILTER)) {
        String floorName = file.getName().substring(2, file.getName().length() - 6);
        if (game.isFloorPresent(floorName)) {
            continue;
        }

        file.delete();
    }

    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.xaniox.leaderboardextensions.ExtensionXmlHandler.java

License:Open Source License

public void saveExtensions(Set<GameExtension> extensions) throws IOException {
    if (!xmlFile.exists()) {
        xmlFile.createNewFile();//from   w w w . j  ava 2  s  .co m
    }

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

    for (GameExtension extension : extensions) {
        Element extensionElement = rootElement.addElement("extension");
        String name = registry.getExtensionName(extension.getClass());

        extensionElement.addAttribute("name", name);
        context.write(extension, extensionElement);
    }

    XMLWriter xmlWriter = null;

    try (OutputStream out = new FileOutputStream(xmlFile); Writer writer = new OutputStreamWriter(out, UTF8)) {
        xmlWriter = new XMLWriter(writer, format);
        xmlWriter.write(document);
        xmlWriter.flush();
    } finally {
        if (xmlWriter != null) {
            xmlWriter.close();
        }
    }
}

From source file:de.xwic.sandbox.server.installer.XmlExport.java

License:Apache License

/**
 * @param secDump/*from  ww  w .j  ava 2  s.  co m*/
 */
public void exportSecurity(File secDump) throws IOException, ConfigurationException {

    Document doc = DocumentFactory.getInstance().createDocument();
    Element root = doc.addElement(ELM_EXPORT);
    root.addAttribute("type", "security");

    Element info = root.addElement(ELM_EXPORTDDATE);
    info.setText(DateFormat.getDateTimeInstance().format(new Date()));

    Element data = root.addElement(ELM_DATA);

    addAll(IActionDAO.class, data);
    addAll(IActionSetDAO.class, data);
    addAll(IScopeDAO.class, data);
    addAll(IRoleDAO.class, data);
    addAll(IRightDAO.class, data);
    addAll(IUserDAO.class, data);

    OutputFormat prettyFormat = OutputFormat.createPrettyPrint();
    OutputStream out = new FileOutputStream(secDump);
    XMLWriter writer = new XMLWriter(out, prettyFormat);
    writer.write(doc);
    writer.flush();
    out.close();

}

From source file:de.xwic.sandbox.server.installer.XmlExport.java

License:Apache License

/**
 * @param plDump/*from   ww w  .  j  ava2s  .co  m*/
 */
public void exportPicklists(File plDump) throws IOException, ConfigurationException {

    Document doc = DocumentFactory.getInstance().createDocument();
    Element root = doc.addElement(ELM_EXPORT);
    root.addAttribute("type", "picklists");

    Element info = root.addElement(ELM_EXPORTDDATE);
    info.setText(DateFormat.getDateTimeInstance().format(new Date()));

    Element data = root.addElement(ELM_DATA);

    addPicklisten(data);

    OutputFormat prettyFormat = OutputFormat.createPrettyPrint();
    OutputStream out = new FileOutputStream(plDump);
    XMLWriter writer = new XMLWriter(out, prettyFormat);
    writer.write(doc);
    writer.flush();
    out.close();

}

From source file:dk.nsi.stamdata.replication.tools.SchemaGenerator.java

License:Mozilla Public License

private static Element generate(Document doc, String namespace, String entityName) {
    Element root = doc.addElement("xs:schema");

    root.addNamespace("xs", "http://www.w3.org/2001/XMLSchema");
    root.addNamespace("tns", namespace);
    root.addAttribute("targetNamespace", namespace);

    Element element = root.addElement("xs:element");
    element.addAttribute("name", entityName);

    Element complexType = element.addElement("xs:complexType");

    // We use "all" and not "sequence" we cause we cannot tell from the
    // class the order of the elements.
    ///* w  ww .  j  av a 2s .c o m*/
    return complexType.addElement("xs:all");
}