Example usage for org.w3c.dom Element setTextContent

List of usage examples for org.w3c.dom Element setTextContent

Introduction

In this page you can find the example usage for org.w3c.dom Element setTextContent.

Prototype

public void setTextContent(String textContent) throws DOMException;

Source Link

Document

This attribute returns the text content of this node and its descendants.

Usage

From source file:org.gvnix.addon.gva.security.providers.aplusu.AplusuSecurityProvider.java

/**
 * Set session-timeout with value given as parameter
 * //w w  w  .  java 2  s  .  c om
 * @param sessionTimeout
 */
private void updateSessionTimeout(Integer sessionTimeout) {
    Validate.notNull(sessionTimeout, "Session timeout must not be null");

    String webXmlPath = pathResolver.getIdentifier(LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""),
            "WEB-INF/web.xml");

    Document webXmlDoc;
    MutableFile mutableFile;
    try {
        if (fileManager.exists(webXmlPath)) {
            // File exists, update file
            mutableFile = fileManager.updateFile(webXmlPath);
            webXmlDoc = XmlUtils.getDocumentBuilder().parse(mutableFile.getInputStream());
        } else {
            throw new IllegalStateException("Could not acquire ".concat(webXmlPath));
        }
        Element root = webXmlDoc.getDocumentElement();
        Element sessionTimeoutElement = XmlUtils.findFirstElement("/web-app/session-config/session-timeout",
                root);
        sessionTimeoutElement.setTextContent(String.valueOf(sessionTimeout));
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    // Write file
    XmlUtils.writeXml(mutableFile.getOutputStream(), webXmlDoc);

}

From source file:org.gvnix.flex.FlexOperationsImpl.java

private void fixBrokenFlexDependency() {
    String pomPath = getPathResolver().getIdentifier(LogicalPath.getInstance(Path.ROOT, ""), "pom.xml");

    Document pomDoc;/*from w ww . j  a  v a 2  s .  c  o m*/
    try {
        pomDoc = XmlUtils.getDocumentBuilder().parse(this.fileManager.getInputStream(pomPath));
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    Element typeElement = XmlUtils.findFirstElement(
            "/project/dependencies/dependency[artifactId='flex-framework']/type", pomDoc.getDocumentElement());
    Validate.notNull(typeElement, "Could not find the flex-framework dependency type.");
    typeElement.setTextContent("pom");

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    XmlUtils.writeXml(XmlUtils.createIndentingTransformer(), byteArrayOutputStream, pomDoc);
    String pomContent = byteArrayOutputStream.toString();

    try {
        this.fileManager.createOrUpdateTextFileIfRequired(pomPath, pomContent, false);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.gvnix.flex.FlexOperationsImpl.java

private void fixBrokenFlexPlugin() {
    String pomPath = getPathResolver().getIdentifier(LogicalPath.getInstance(Path.ROOT, ""), "pom.xml");

    Document pomDoc;/*  ww w.  java2 s .  c o m*/
    try {
        pomDoc = XmlUtils.getDocumentBuilder().parse(this.fileManager.getInputStream(pomPath));
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    Element pluginDependencyElement = XmlUtils.findFirstElement(
            "/project/build/plugins/plugin[artifactId='flexmojos-maven-plugin']/dependencies/dependency",
            pomDoc.getDocumentElement());
    Validate.notNull(pluginDependencyElement,
            "Could not find the flexmojos-maven-plugin's dependency element.");
    Element newTypeNode = pomDoc.createElement("type");
    newTypeNode.setTextContent("pom");
    pluginDependencyElement.appendChild(newTypeNode);

    Element pluginExecutionElement = XmlUtils.findFirstElement(
            "/project/build/plugins/plugin[artifactId='flexmojos-maven-plugin']/executions/execution",
            pomDoc.getDocumentElement());
    InputStream templateInputStream = FileUtils.getInputStream(getClass(), "pluginsFix.xml");
    Document configurationTemplate;
    try {
        configurationTemplate = XmlUtils.getDocumentBuilder().parse(templateInputStream);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
    Element configurationElement = XmlUtils.findFirstElement("/configuration",
            configurationTemplate.getDocumentElement());
    Validate.notNull(configurationElement, "flexmojos-maven-plugin configuration did not parse as expected.");

    pluginExecutionElement.appendChild(pomDoc.importNode(configurationElement, true));

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    XmlUtils.writeXml(XmlUtils.createIndentingTransformer(), byteArrayOutputStream, pomDoc);
    String pomContent = byteArrayOutputStream.toString();

    try {
        this.fileManager.createOrUpdateTextFileIfRequired(pomPath, pomContent, false);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.gvnix.flex.ui.FlexUIMetadataProvider.java

private void updateScaffoldIfNecessary(String scaffoldAppFileId, FlexScaffoldMetadata flexScaffoldMetadata) {
    MutableFile scaffoldMutableFile = null;

    Document scaffoldDoc;//from w  ww  .  j a  v a2s .  com
    try {
        scaffoldMutableFile = getFileManager().updateFile(scaffoldAppFileId);
        scaffoldDoc = XmlUtils.getDocumentBuilder().parse(scaffoldMutableFile.getInputStream());
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    String entityName = flexScaffoldMetadata.getEntity().getSimpleTypeName();

    if (XmlUtils.findFirstElement(
            "/Application/Declarations/ArrayList[@id='entities' and String='" + entityName + "']",
            scaffoldDoc.getDocumentElement()) != null) {
        return;
    }

    Element entitiesElement = XmlUtils.findFirstElement("/Application/Declarations/ArrayList[@id='entities']",
            scaffoldDoc.getDocumentElement());
    Validate.notNull(entitiesElement, "Could not find the entities element in the main scaffold mxml.");
    Element entityElement = scaffoldDoc.createElement("fx:String");
    entityElement.setTextContent(entityName);
    entitiesElement.appendChild(entityElement);

    // Build a string representation of the MXML and write it to disk
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    XmlUtils.writeXml(XmlUtils.createIndentingTransformer(), byteArrayOutputStream, scaffoldDoc);
    String mxmlContent = byteArrayOutputStream.toString();

    InputStream inputStream = null;
    OutputStream outputStream = null;
    try {
        inputStream = IOUtils.toInputStream(mxmlContent);
        outputStream = scaffoldMutableFile.getOutputStream();
        IOUtils.copy(inputStream, outputStream);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    } finally {
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(outputStream);
    }
}

From source file:org.gvnix.flex.ui.FlexUIMetadataProvider.java

private void updateCompilerConfigIfNecessary(String flexConfigFileId, String entityPresentationPackage,
        FlexScaffoldMetadata flexScaffoldMetadata) {
    MutableFile flexConfigMutableFile = null;

    Document flexConfigDoc;/*ww  w. ja  va 2  s .c  o m*/
    try {
        flexConfigMutableFile = getFileManager().updateFile(flexConfigFileId);
        flexConfigDoc = XmlUtils.getDocumentBuilder().parse(flexConfigMutableFile.getInputStream());
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    String viewName = entityPresentationPackage + "." + flexScaffoldMetadata.getEntity().getSimpleTypeName()
            + "View";

    if (XmlUtils.findFirstElement("/flex-config/includes[symbol='" + viewName + "']",
            flexConfigDoc.getDocumentElement()) != null) {
        return;
    }

    Element includesElement = XmlUtils.findFirstElement("/flex-config/includes",
            flexConfigDoc.getDocumentElement());
    Validate.notNull(includesElement, "Could not find the includes element in the flex compiler config.");

    Element entityElement = flexConfigDoc.createElement("symbol");
    entityElement.setTextContent(viewName);
    includesElement.appendChild(entityElement);

    // Build a string representation of the MXML and write it to disk
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    XmlUtils.writeXml(XmlUtils.createIndentingTransformer(), byteArrayOutputStream, flexConfigDoc);
    String mxmlContent = byteArrayOutputStream.toString();

    InputStream inputStream = null;
    OutputStream outputStream = null;
    try {
        inputStream = IOUtils.toInputStream(mxmlContent);
        outputStream = flexConfigMutableFile.getOutputStream();
        IOUtils.copy(inputStream, outputStream);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    } finally {
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(outputStream);
    }
}

From source file:org.gvnix.flex.ui.MxmlRoundTripUtils.java

/**
 * Compares and updates script blocks in the MXML document if necessary.
 * Assumes that there is only a single script block.
 * //  w w  w. j  a v  a2s. c om
 * @param original
 * @param proposed
 * @param originalDocumentAdjusted
 * @return the new document if changes are necessary, null if no changes are
 *         necessary
 */
private static boolean updateScriptBlock(Element original, Element proposed, boolean originalDocumentAdjusted) {
    Element originalScriptBlock = XmlUtils.findFirstElementByName("fx:Script", original);
    Element proposedScriptBlock = XmlUtils.findFirstElementByName("fx:Script", proposed);
    if (originalScriptBlock != null && proposedScriptBlock != null) {
        if (originalScriptBlock.getTextContent() != null
                && !originalScriptBlock.getTextContent().equals(proposedScriptBlock.getTextContent())) {
            originalScriptBlock.setTextContent(proposedScriptBlock.getTextContent());
            originalDocumentAdjusted = true;
        } else if (originalScriptBlock.getChildNodes().getLength() > 0
                && proposedScriptBlock.getChildNodes().getLength() > 0) {
            CDATASection originalCDATA = null;
            CDATASection proposedCDATA = null;
            for (int i = 0; i < originalScriptBlock.getChildNodes().getLength(); i++) {
                if (originalScriptBlock.getChildNodes().item(i).getNodeType() == Node.CDATA_SECTION_NODE) {
                    originalCDATA = (CDATASection) originalScriptBlock.getChildNodes().item(i);
                    break;
                }
            }
            for (int i = 0; i < proposedScriptBlock.getChildNodes().getLength(); i++) {
                if (proposedScriptBlock.getChildNodes().item(i).getNodeType() == Node.CDATA_SECTION_NODE) {
                    proposedCDATA = (CDATASection) proposedScriptBlock.getChildNodes().item(i);
                    break;
                }
            }

            if (originalCDATA == null || proposedCDATA == null) {
                return originalDocumentAdjusted;
            }

            if (originalCDATA.getData() != null && !originalCDATA.getData().equals(proposedCDATA.getData())) {
                originalCDATA.setData(proposedCDATA.getData());
                originalDocumentAdjusted = true;
            }
        }
    }
    return originalDocumentAdjusted;
}

From source file:org.gvnix.web.screen.roo.addon.SeleniumServicesImpl.java

/**
 * Install central Selenium configuration if not already and reference a new
 * test./*  w  w  w.j  av a  2s. c  om*/
 * 
 * @param testPath New test path
 * @param name Test name
 * @param serverURL Application base URL
 */
protected void manageTestSuite(String testPath, String name, String serverURL) {

    String relativePath = "selenium/test-suite.xhtml";
    String seleniumPath = projectOperations.getPathResolver()
            .getIdentifier(LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""), relativePath);

    Document suite;
    try {

        if (fileManager.exists(seleniumPath)) {

            suite = XmlUtils.readXml(fileManager.getInputStream(seleniumPath));

        } else {

            InputStream templateInputStream = FileUtils.getInputStream(SeleniumOperationsImpl.class,
                    "selenium-test-suite-template.xhtml");
            Validate.notNull(templateInputStream, "Could not acquire selenium test suite template");
            suite = XmlUtils.readXml(templateInputStream);
        }
    } catch (Exception e) {

        throw new IllegalStateException(e);
    }

    ProjectMetadata projectMetadata = projectOperations
            .getProjectMetadata(projectOperations.getFocusedModuleName());
    Validate.notNull(projectMetadata, "Unable to obtain project metadata");

    Element root = (Element) suite.getLastChild();

    XmlUtils.findRequiredElement("/html/head/title", root).setTextContent("Test suite for "
            + projectOperations.getProjectName(projectOperations.getFocusedModuleName()) + "project");

    Element tr = suite.createElement("tr");
    Element td = suite.createElement("td");
    tr.appendChild(td);
    Element a = suite.createElement("a");
    a.setAttribute("href",
            serverURL + projectOperations.getProjectName(projectOperations.getFocusedModuleName())
                    + "/resources/" + testPath);
    a.setTextContent(name);
    td.appendChild(a);

    XmlUtils.findRequiredElement("/html/body/table", root).appendChild(tr);

    fileManager.createOrUpdateTextFileIfRequired(seleniumPath, XmlUtils.nodeToString(suite), false);

    menuOperations.addMenuItem(new JavaSymbolName("SeleniumTests"), new JavaSymbolName("Test"), "Test",
            "selenium_menu_test_suite", "/resources/" + relativePath, "si_",
            LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""));
}

From source file:org.jboss.pressgang.ccms.contentspec.builder.DocBookBuilder.java

/**
 * Builds the Book.xml file of a Docbook from the resource files for a specific content specification.
 *
 * @param buildData/*  w ww. j  ava 2s  . c  o m*/
 * @throws BuildProcessingException
 */
protected void buildBookBase(final BuildData buildData) throws BuildProcessingException {
    final ContentSpec contentSpec = buildData.getContentSpec();

    // Get the template from the server
    final String bookXmlTemplate;
    if (contentSpec.getBookType() == BookType.ARTICLE || contentSpec.getBookType() == BookType.ARTICLE_DRAFT) {
        bookXmlTemplate = stringConstantProvider
                .getStringConstant(buildData.getServerEntities().getArticleStringConstantId()).getValue();
    } else {
        bookXmlTemplate = stringConstantProvider
                .getStringConstant(buildData.getServerEntities().getBookStringConstantId()).getValue();
    }

    // Setup the basic book.xml
    String basicBook = bookXmlTemplate.replaceAll(BuilderConstants.ESCAPED_TITLE_REGEX,
            buildData.getEscapedBookTitle());
    basicBook = basicBook.replaceAll(BuilderConstants.PRODUCT_REGEX,
            DocBookBuildUtilities.getKeyValueNodeText(buildData, contentSpec.getProductNode()));
    basicBook = basicBook.replaceAll(BuilderConstants.VERSION_REGEX,
            DocBookBuildUtilities.getKeyValueNodeText(buildData, contentSpec.getVersionNode()));
    basicBook = basicBook.replaceAll(BuilderConstants.DRAFT_REGEX,
            buildData.getBuildOptions().getDraft() ? "status=\"draft\"" : "");

    if (contentSpec.getUseDefaultPreface()) {
        // Add the preface to the book.xml
        basicBook = basicBook.replaceAll(BuilderConstants.PREFACE_REGEX,
                "<xi:include href=\"Preface.xml\" xmlns:xi=\"http://www.w3.org/2001/XInclude\" />");
    }

    // Remove the Injection sequence as we'll add the revision history and xiinclude element later
    basicBook = basicBook.replaceAll(BuilderConstants.XIINCLUDES_INJECTION_STRING, "");
    basicBook = basicBook.replaceAll(BuilderConstants.REV_HISTORY_REGEX, "");

    // Create the Book.xml DOM Document
    Document bookBase = null;
    try {
        // Find and Remove the Doctype first
        final String doctype = XMLUtilities.findDocumentType(basicBook);

        bookBase = XMLUtilities
                .convertStringToDocument(doctype == null ? basicBook : basicBook.replace(doctype, ""));
    } catch (Exception e) {
        throw new BuildProcessingException(e);
    }

    boolean flattenStructure = buildData.getBuildOptions().isServerBuild()
            || buildData.getBuildOptions().getFlatten();
    final List<org.jboss.pressgang.ccms.contentspec.Node> levelData = contentSpec.getBaseLevel()
            .getChildNodes();

    // Loop through and create each chapter and the topics inside those chapters
    log.info("\tBuilding Level and Topic XML Files");

    for (final org.jboss.pressgang.ccms.contentspec.Node node : levelData) {
        // Check if the app should be shutdown
        if (isShuttingDown.get()) {
            return;
        }

        if (node instanceof Level) {
            final Level level = (Level) node;

            if (level instanceof InitialContent && (level.hasSpecTopics() || level.hasCommonContents())) {
                addLevelsInitialContent(buildData, (InitialContent) level, bookBase,
                        bookBase.getDocumentElement(), false);
            } else if (level.hasSpecTopics() || level.hasCommonContents()) {
                // If the book is an article than just include it directly and don't create a new file
                if (contentSpec.getBookType() == BookType.ARTICLE
                        || contentSpec.getBookType() == BookType.ARTICLE_DRAFT) {
                    // Create the section and its title
                    final Element sectionNode = bookBase.createElement("section");
                    setUpRootElement(buildData, level, bookBase, sectionNode);

                    createContainerXML(buildData, level, bookBase, sectionNode, buildData.getBookTopicsFolder(),
                            flattenStructure);

                    bookBase.getDocumentElement().appendChild(sectionNode);
                } else {
                    final Element xiInclude = createRootContainerXML(buildData, bookBase, level,
                            flattenStructure);
                    if (xiInclude != null) {
                        bookBase.getDocumentElement().appendChild(xiInclude);
                    }
                }
            } else if (buildData.getBuildOptions().isAllowEmptySections()) {
                final Element para = bookBase.createElement("para");
                para.setTextContent("No Content");
                bookBase.getDocumentElement().appendChild(para);
            }
        } else if (node instanceof SpecTopic) {
            final SpecTopic specTopic = (SpecTopic) node;
            final Node topicNode = createTopicDOMNode(specTopic, bookBase, flattenStructure,
                    buildData.getBookTopicsFolder());

            // Add the node to the Book
            if (topicNode != null) {
                bookBase.getDocumentElement().appendChild(topicNode);
            }
        } else if (node instanceof CommonContent) {
            final Node xiInclude = XMLUtilities.createXIInclude(bookBase,
                    "Common_Content/" + ((CommonContent) node).getFixedTitle());
            bookBase.getDocumentElement().appendChild(xiInclude);
        }
    }

    // Insert the editor link for the content spec if it's a translation
    if (buildData.getBuildOptions().getInsertEditorLinks() && buildData.isTranslationBuild()) {
        final String translateLinkChapter = buildTranslateCSChapter(buildData);
        buildData.getOutputFiles().put(buildData.getBookLocaleFolder() + "Translate.xml",
                StringUtilities.getStringBytes(StringUtilities
                        .cleanTextForXML(translateLinkChapter == null ? "" : translateLinkChapter)));

        // Create and append the XI Include element
        final Element translateXMLNode = XMLUtilities.createXIInclude(bookBase, "Translate.xml");
        bookBase.getDocumentElement().appendChild(translateXMLNode);
    }

    // Add any compiler errors
    if (!buildData.getBuildOptions().getSuppressErrorsPage()
            && buildData.getErrorDatabase().hasItems(buildData.getBuildLocale())) {
        final String compilerOutput = buildErrorChapter(buildData);
        buildData.getOutputFiles().put(buildData.getBookLocaleFolder() + "Errors.xml", StringUtilities
                .getStringBytes(StringUtilities.cleanTextForXML(compilerOutput == null ? "" : compilerOutput)));

        // Create and append the XI Include element
        final Element translateXMLNode = XMLUtilities.createXIInclude(bookBase, "Errors.xml");
        bookBase.getDocumentElement().appendChild(translateXMLNode);
    }

    // Add the report chapter
    if (buildData.getBuildOptions().getShowReportPage()) {
        final String compilerOutput = buildReportChapter(buildData);
        buildData.getOutputFiles().put(buildData.getBookLocaleFolder() + "Report.xml", StringUtilities
                .getStringBytes(StringUtilities.cleanTextForXML(compilerOutput == null ? "" : compilerOutput)));

        // Create and append the XI Include element
        final Element translateXMLNode = XMLUtilities.createXIInclude(bookBase, "Report.xml");
        bookBase.getDocumentElement().appendChild(translateXMLNode);
    }

    // Build the content specification page
    if (!buildData.getBuildOptions().getSuppressContentSpecPage()) {
        final String contentSpecPage = DocBookUtilities.buildAppendix(DocBookUtilities.wrapInPara(
                "<programlisting>" + XMLUtilities.wrapStringInCDATA(contentSpec.toString(INCLUDE_CHECKSUMS))
                        + "</programlisting>"),
                "Build Content Specification");
        addToZip(buildData.getBookLocaleFolder() + "Build_Content_Specification.xml",
                DocBookBuildUtilities.addDocBookPreamble(buildData.getDocBookVersion(), contentSpecPage,
                        "appendix", buildData.getEntityFileName()),
                buildData);

        // Create and append the XI Include element
        final Element translateXMLNode = XMLUtilities.createXIInclude(bookBase,
                "Build_Content_Specification.xml");
        bookBase.getDocumentElement().appendChild(translateXMLNode);
    }

    // Add the revision history to the book.xml
    final Element revisionHistoryXMLNode = XMLUtilities.createXIInclude(bookBase, "Revision_History.xml");
    bookBase.getDocumentElement().appendChild(revisionHistoryXMLNode);

    // Add the index node if required
    if (contentSpec.getIncludeIndex()) {
        final Element indexNode = bookBase.createElement("index");
        bookBase.getDocumentElement().appendChild(indexNode);
    }

    // Change the DOM Document into a string so it can be added to the ZIP
    final String rootElementName = contentSpec.getBookType().toString().toLowerCase().replace("-draft", "");
    final String book = DocBookBuildUtilities.convertDocumentToDocBookFormattedString(
            buildData.getDocBookVersion(), bookBase, rootElementName, buildData.getEntityFileName(),
            getXMLFormatProperties());
    addToZip(buildData.getBookLocaleFolder() + buildData.getRootBookFileName() + ".xml", book, buildData);
}

From source file:org.jboss.pressgang.ccms.contentspec.builder.DocBookBuilder.java

/**
 * Builds the Preface.xml file for the book.
 *
 * @param buildData/*from  w  w  w . ja  v  a 2  s . c o m*/
 * @throws BuildProcessingException
 */
protected void buildBookPreface(final BuildData buildData) throws BuildProcessingException {
    final ContentSpec contentSpec = buildData.getContentSpec();

    // Check that should actually use the preface
    if (contentSpec.getUseDefaultPreface()) {
        final Map<String, String> overrides = buildData.getBuildOptions().getOverrides();
        final Map<String, byte[]> overrideFiles = buildData.getOverrideFiles();

        final Document prefaceDoc;
        try {
            prefaceDoc = XMLUtilities.convertStringToDocument("<preface></preface>");
        } catch (Exception e) {
            throw new BuildProcessingException(e);
        }

        // Add the title
        final String prefaceTitleTranslation = buildData.getConstants().getString("PREFACE");
        final Element titleEle = prefaceDoc.createElement("title");
        titleEle.setTextContent(prefaceTitleTranslation);
        prefaceDoc.getDocumentElement().appendChild(titleEle);

        // Add the Conventions.xml
        final Element conventions = XMLUtilities.createXIInclude(prefaceDoc, "Common_Content/Conventions.xml");
        prefaceDoc.getDocumentElement().appendChild(conventions);

        // Add the Feedback.xml
        if (overrides.containsKey(CSConstants.FEEDBACK_OVERRIDE)
                && overrideFiles.containsKey(CSConstants.FEEDBACK_OVERRIDE)
                || contentSpec.getFeedback() != null) {
            final Element xinclude = XMLUtilities.createXIInclude(prefaceDoc, "Feedback.xml");
            prefaceDoc.getDocumentElement().appendChild(xinclude);
        } else {
            final Element xinclude = XMLUtilities.createXIInclude(prefaceDoc, "Common_Content/Feedback.xml");
            prefaceDoc.getDocumentElement().appendChild(xinclude);
        }

        final String prefaceXml = DocBookBuildUtilities.convertDocumentToDocBookFormattedString(
                buildData.getDocBookVersion(), prefaceDoc, "preface", buildData.getEntityFileName(),
                getXMLFormatProperties());
        addToZip(buildData.getBookLocaleFolder() + PREFACE_FILE_NAME, prefaceXml, buildData);
    }
}

From source file:org.jboss.pressgang.ccms.contentspec.builder.DocBookBuilder.java

/**
 * Sets up an elements title, info and id based on the passed level.
 *
 * @param buildData Information and data structures for the build.
 * @param level     The level to build the root element is being built for.
 * @param doc       The document object the content is being added to.
 * @param ele//from www.  jav a  2s .  c  om
 */
protected void setUpRootElement(final BuildData buildData, final Level level, final Document doc, Element ele) {
    final Element titleNode = doc.createElement("title");
    if (buildData.isTranslationBuild() && !isNullOrEmpty(level.getTranslatedTitle())) {
        titleNode.setTextContent(DocBookUtilities.escapeForXML(level.getTranslatedTitle()));
    } else {
        titleNode.setTextContent(DocBookUtilities.escapeForXML(level.getTitle()));
    }

    // Add the info if the container has one
    final Element infoElement;
    if (level.getInfoTopic() != null) {
        final InfoTopic infoTopic = level.getInfoTopic();
        final Node info = doc.importNode(infoTopic.getXMLDocument().getDocumentElement(), true);

        // Generate the info node
        final String elementInfoName;
        if (buildData.getDocBookVersion() == DocBookVersion.DOCBOOK_50) {
            elementInfoName = "info";
        } else {
            elementInfoName = ele.getNodeName() + "info";
        }
        infoElement = doc.createElement(elementInfoName);

        // Move the contents of the info to the chapter/level
        final NodeList infoChildren = info.getChildNodes();
        while (infoChildren.getLength() > 0) {
            infoElement.appendChild(infoChildren.item(0));
        }
    } else {
        infoElement = null;
    }

    if (buildData.getDocBookVersion() == DocBookVersion.DOCBOOK_50) {
        ele.appendChild(titleNode);
        if (infoElement != null) {
            ele.appendChild(infoElement);
        }
    } else {
        if (infoElement != null) {
            ele.appendChild(infoElement);
        }
        ele.appendChild(titleNode);
    }

    DocBookBuildUtilities.setDOMElementId(buildData.getDocBookVersion(), ele,
            level.getUniqueLinkId(buildData.isUseFixedUrls()));
}