Example usage for org.w3c.dom Document createComment

List of usage examples for org.w3c.dom Document createComment

Introduction

In this page you can find the example usage for org.w3c.dom Document createComment.

Prototype

public Comment createComment(String data);

Source Link

Document

Creates a Comment node given the specified string.

Usage

From source file:Main.java

public static void copyInto(Node src, Node dest) throws DOMException {

    Document factory = dest.getOwnerDocument();

    //Node start = src;
    Node parent = null;/* w w  w.j  av  a2s.  c o m*/
    Node place = src;

    // traverse source tree
    while (place != null) {

        // copy this node
        Node node = null;
        int type = place.getNodeType();
        switch (type) {
        case Node.CDATA_SECTION_NODE: {
            node = factory.createCDATASection(place.getNodeValue());
            break;
        }
        case Node.COMMENT_NODE: {
            node = factory.createComment(place.getNodeValue());
            break;
        }
        case Node.ELEMENT_NODE: {
            Element element = factory.createElement(place.getNodeName());
            node = element;
            NamedNodeMap attrs = place.getAttributes();
            int attrCount = attrs.getLength();
            for (int i = 0; i < attrCount; i++) {
                Attr attr = (Attr) attrs.item(i);
                String attrName = attr.getNodeName();
                String attrValue = attr.getNodeValue();
                element.setAttribute(attrName, attrValue);
            }
            break;
        }
        case Node.ENTITY_REFERENCE_NODE: {
            node = factory.createEntityReference(place.getNodeName());
            break;
        }
        case Node.PROCESSING_INSTRUCTION_NODE: {
            node = factory.createProcessingInstruction(place.getNodeName(), place.getNodeValue());
            break;
        }
        case Node.TEXT_NODE: {
            node = factory.createTextNode(place.getNodeValue());
            break;
        }
        default: {
            throw new IllegalArgumentException(
                    "can't copy node type, " + type + " (" + place.getNodeName() + ')');
        }
        }
        dest.appendChild(node);

        // iterate over children
        if (place.hasChildNodes()) {
            parent = place;
            place = place.getFirstChild();
            dest = node;
        } else if (parent == null) {
            place = null;
        } else {
            // advance
            place = place.getNextSibling();
            while (place == null && parent != null) {
                place = parent.getNextSibling();
                parent = parent.getParentNode();
                dest = dest.getParentNode();
            }
        }

    }

}

From source file:Main.java

/**
 * Copies the source tree into the specified place in a destination
 * tree. The source node and its children are appended as children
 * of the destination node./*from   w  w w . ja v a 2 s. co m*/
 * <p>
 * <em>Note:</em> This is an iterative implementation.
 */
public static void copyInto(Node src, Node dest) throws DOMException {

    // get node factory
    Document factory = dest.getOwnerDocument();
    boolean domimpl = factory instanceof DocumentImpl;

    // placement variables
    Node start = src;
    Node parent = src;
    Node place = src;

    // traverse source tree
    while (place != null) {

        // copy this node
        Node node = null;
        int type = place.getNodeType();
        switch (type) {
        case Node.CDATA_SECTION_NODE: {
            node = factory.createCDATASection(place.getNodeValue());
            break;
        }
        case Node.COMMENT_NODE: {
            node = factory.createComment(place.getNodeValue());
            break;
        }
        case Node.ELEMENT_NODE: {
            Element element = factory.createElement(place.getNodeName());
            node = element;
            NamedNodeMap attrs = place.getAttributes();
            int attrCount = attrs.getLength();
            for (int i = 0; i < attrCount; i++) {
                Attr attr = (Attr) attrs.item(i);
                String attrName = attr.getNodeName();
                String attrValue = attr.getNodeValue();
                element.setAttribute(attrName, attrValue);
                if (domimpl && !attr.getSpecified()) {
                    ((AttrImpl) element.getAttributeNode(attrName)).setSpecified(false);
                }
            }
            break;
        }
        case Node.ENTITY_REFERENCE_NODE: {
            node = factory.createEntityReference(place.getNodeName());
            break;
        }
        case Node.PROCESSING_INSTRUCTION_NODE: {
            node = factory.createProcessingInstruction(place.getNodeName(), place.getNodeValue());
            break;
        }
        case Node.TEXT_NODE: {
            node = factory.createTextNode(place.getNodeValue());
            break;
        }
        default: {
            throw new IllegalArgumentException(
                    "can't copy node type, " + type + " (" + node.getNodeName() + ')');
        }
        }
        dest.appendChild(node);

        // iterate over children
        if (place.hasChildNodes()) {
            parent = place;
            place = place.getFirstChild();
            dest = node;
        }

        // advance
        else {
            place = place.getNextSibling();
            while (place == null && parent != start) {
                place = parent.getNextSibling();
                parent = parent.getParentNode();
                dest = dest.getParentNode();
            }
        }

    }

}

From source file:cross.applicationContext.ReflectionApplicationContextGenerator.java

/**
 * Creates a stub application context xml file for the given classes. The
 * default bean scope is 'prototype'.//from  w  ww  .  j a v a  2 s  .c  o  m
 *
 * @param outputFile the output file for the generated xml file
 * @param springVersion the spring version to use for validation
 * @param defaultScope the default scope
 * @param classes the classes to generate stubs for
 */
public static void createContextXml(File outputFile, String springVersion, String defaultScope,
        String... classes) {
    //generate the application context XML
    ReflectionApplicationContextGenerator generator = new ReflectionApplicationContextGenerator(springVersion,
            defaultScope);
    for (String className : classes) {
        try {
            Collection<?> serviceImplementations = Lookup.getDefault().lookupAll(Class.forName(className));
            if (serviceImplementations.isEmpty()) {
                //standard bean, add it
                try {
                    generator.addBean(className);
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(ReflectionApplicationContextGenerator.class.getName()).log(Level.SEVERE,
                            null, ex);
                }
            } else {//service provider implementation
                for (Object obj : serviceImplementations) {
                    try {
                        generator.addBean(obj.getClass().getCanonicalName());
                    } catch (ClassNotFoundException ex) {
                        Logger.getLogger(ReflectionApplicationContextGenerator.class.getName())
                                .log(Level.SEVERE, null, ex);
                    }
                }
            }
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ReflectionApplicationContextGenerator.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
    Document document = generator.getDocument();
    Element element = document.getDocumentElement();
    Comment comment = document.createComment(
            "In order to use this template in a runnable pipeline, please include it from another application context xml file.");
    element.getParentNode().insertBefore(comment, element);
    writeToFile(document, outputFile);
}

From source file:com.moviejukebox.model.JukeboxStatistics.java

/**
 * Write the statistics to a file/*from  w  w w  .jav  a  2  s  .com*/
 *
 * @param jukebox
 * @param library
 * @param mediaLibraryPaths
 */
public static void writeFile(Jukebox jukebox, Library library, Collection<MediaLibraryPath> mediaLibraryPaths) {
    File jbStats = new File(jukebox.getJukeboxRootLocationDetailsFile(), XML_FILENAME);
    FileTools.addJukeboxFile(jbStats.getName());

    Document docJbStats;
    Element eRoot, eStats, eTimes;

    try {
        LOG.debug("Creating JukeboxStatistics file: {}", jbStats.getAbsolutePath());
        if (jbStats.exists() && !jbStats.delete()) {
            LOG.error("Failed to delete {}. Please make sure it's not read only", jbStats.getName());
            return;
        }
    } catch (Exception ex) {
        LOG.error("Failed to create/delete {}. Please make sure it's not read only", jbStats.getName());
        return;
    }

    try {
        // Start with a blank document
        docJbStats = DOMHelper.createDocument();
        String tempString = (new DateTime(System.currentTimeMillis()))
                .toString(DateTimeTools.getDateFormatLongString());
        docJbStats.appendChild(docJbStats.createComment("This file was created on: " + tempString));

        //create the root element and add it to the document
        eRoot = docJbStats.createElement("root");
        docJbStats.appendChild(eRoot);

        // Create the statistics node
        eStats = docJbStats.createElement("statistics");
        eRoot.appendChild(eStats);

        for (Map.Entry<JukeboxStatistic, Integer> entry : STATISTICS.entrySet()) {
            DOMHelper.appendChild(docJbStats, eStats, entry.getKey().toString().toLowerCase(),
                    entry.getValue().toString());
        }
        DOMHelper.appendChild(docJbStats, eStats, "libraries", Integer.toString(mediaLibraryPaths.size()));

        // Create the time node
        eTimes = docJbStats.createElement("times");
        eRoot.appendChild(eTimes);

        DateTime dt;
        for (Map.Entry<JukeboxTimes, Long> entry : TIMES.entrySet()) {
            if (entry.getValue() > 0) {
                dt = new DateTime(entry.getValue());
                DOMHelper.appendChild(docJbStats, eTimes, entry.getKey().toString().toLowerCase(),
                        dt.toString(DateTimeTools.getDateFormatLongString()));
            }
        }
        DOMHelper.appendChild(docJbStats, eTimes, "processing", getProcessingTime());

        DOMHelper.writeDocumentToFile(docJbStats, jbStats.getAbsolutePath());
    } catch (ParserConfigurationException | DOMException ex) {
        LOG.error("Error creating {} file: {}", jbStats.getName(), ex.getMessage());
        LOG.error(SystemTools.getStackTrace(ex));
    }

}

From source file:ConfigFiles.java

public static void saveXML(boolean blank, String filename) {
    boolean saved = true;
    try {//from w ww.  ja v a 2s .c  o m
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.newDocument();
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        DOMSource source = new DOMSource(document);
        Comment simpleComment = document.createComment(
                "\n Master config file for TSC.\n \n Logs" + " Path: Where CE and PE write their getLogs()."
                        + " Reports Path: Where all reports are saved.\n "
                        + "Test Suite Config: All info about the current " + "Test Suite (Test Plan).\n");
        document.appendChild(simpleComment);
        Element root = document.createElement("Root");
        document.appendChild(root);
        Element rootElement = document.createElement("FileType");
        root.appendChild(rootElement);
        rootElement.appendChild(document.createTextNode("config"));
        try {
            addTag("CentralEnginePort", tceport.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("CentralEnginePort", "", root, blank, document);
        }
        //             try{addTag("ResourceAllocatorPort",traPort.getText(),root,blank,document);}
        //             catch(Exception e){addTag("ResourceAllocatorPort","",root,blank,document);}
        //             try{addTag("HttpServerPort",thttpPort.getText(),root,blank,document);}
        //             catch(Exception e){addTag("HttpServerPort","",root,blank,document);}
        try {
            addTag("TestCaseSourcePath", ttcpath.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("TestCaseSourcePath", "", root, blank, document);
        }
        try {
            addTag("LibsPath", libpath.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("LibsPath", "", root, blank, document);
        }
        try {
            addTag("UsersPath", tUsers.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("UsersPath", "", root, blank, document);
        }
        try {
            addTag("PredefinedSuitesPath", tSuites.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("PredefinedSuitesPath", "", root, blank, document);
        }

        try {
            addTag("ArchiveLogsPath", tsecondarylog.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("ArchiveLogsPath", "", root, blank, document);
        }
        try {
            addTag("ArchiveLogsPathActive", logsenabled.isSelected() + "", root, blank, document);
        } catch (Exception e) {
            addTag("ArchiveLogsPath", "", root, blank, document);
        }

        try {
            addTag("LogsPath", tlog.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("LogsPath", "", root, blank, document);
        }
        rootElement = document.createElement("LogFiles");
        root.appendChild(rootElement);
        try {
            addTag("logRunning", trunning.getText(), rootElement, blank, document);
        } catch (Exception e) {
            addTag("logRunning", "", rootElement, blank, document);
        }
        try {
            addTag("logDebug", tdebug.getText(), rootElement, blank, document);
        } catch (Exception e) {
            addTag("logDebug", "", rootElement, blank, document);
        }
        try {
            addTag("logSummary", tsummary.getText(), rootElement, blank, document);
        } catch (Exception e) {
            addTag("logSummary", "", rootElement, blank, document);
        }
        try {
            addTag("logTest", tinfo.getText(), rootElement, blank, document);
        } catch (Exception e) {
            addTag("logTest", "", rootElement, blank, document);
        }
        try {
            addTag("logCli", tcli.getText(), rootElement, blank, document);
        } catch (Exception e) {
            addTag("logCli", "", rootElement, blank, document);
        }
        try {
            addTag("DbConfigFile", tdbfile.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("DbConfigFile", "", root, blank, document);
        }
        try {
            addTag("EpNames", tepid.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("EpNames", "", root, blank, document);
        }
        try {
            addTag("EmailConfigFile", temailfile.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("EmailConfigFile", "", root, blank, document);
        }
        try {
            addTag("GlobalParams", tglobalsfile.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("GlobalParams", "", root, blank, document);
        }
        try {
            addTag("TestConfigPath", testconfigpath.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("TestConfigPath", "", root, blank, document);
        }
        String temp;
        if (blank)
            temp = "fwmconfig";
        else
            temp = filename;
        File file = new File(RunnerRepository.temp + RunnerRepository.getBar() + "Twister"
                + RunnerRepository.getBar() + temp + ".xml");
        Result result = new StreamResult(file);
        transformer.transform(source, result);
        System.out.println("Saving to: " + RunnerRepository.USERHOME + "/twister/config/");
        FileInputStream in = new FileInputStream(file);
        RunnerRepository.uploadRemoteFile(RunnerRepository.USERHOME + "/twister/config/", in, file.getName());
    } catch (ParserConfigurationException e) {
        System.out
                .println("DocumentBuilder cannot be created which" + " satisfies the configuration requested");
        saved = false;
    } catch (TransformerConfigurationException e) {
        System.out.println("Could not create transformer");
        saved = false;
    } catch (Exception e) {
        e.printStackTrace();
        saved = false;
    }
    if (saved) {
        CustomDialog.showInfo(JOptionPane.INFORMATION_MESSAGE, RunnerRepository.window, "Successful",
                "File successfully saved");
    } else {
        CustomDialog.showInfo(JOptionPane.WARNING_MESSAGE, RunnerRepository.window.mainpanel.p4.getConfig(),
                "Warning", "File could not be saved ");
    }
}

From source file:io.wcm.devops.conga.generator.plugins.fileheader.XmlFileHeader.java

@Override
public Void apply(FileContext file, FileHeaderContext context) {
    try {/*w  ww . j  a  va  2 s.  c  o m*/
        Document doc = documentBuilder.parse(file.getFile());

        // build XML comment and add it at first position
        Comment comment = doc.createComment("\n" + StringUtils.join(context.getCommentLines(), "\n") + "\n");
        doc.insertBefore(comment, doc.getChildNodes().item(0));

        // write file
        file.getFile().delete();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(file.getFile());
        transformer.transform(source, result);
    } catch (SAXException | IOException | TransformerException ex) {
        throw new GeneratorException("Unable to add file header to " + FileUtil.getCanonicalPath(file), ex);
    }
    return null;
}

From source file:com.twinsoft.convertigo.engine.requesters.InternalRequester.java

protected Object addStatisticsAsText(String stats, Object result) throws UnsupportedEncodingException {
    if (result != null) {
        if (stats == null)
            stats = context.statistics.printStatistics();
        if (result instanceof Document) {
            Document document = (Document) result;
            Comment comment = document.createComment("\n" + stats);
            document.appendChild(comment);
        } else if (result instanceof byte[]) {
            String encodingCharSet = "UTF-8";
            if (context.requestedObject != null)
                encodingCharSet = context.requestedObject.getEncodingCharSet();
            String sResult = new String((byte[]) result, encodingCharSet);
            sResult += "<!--\n" + stats + "\n-->";
            result = sResult.getBytes(encodingCharSet);
        }//from  w  ww. j a  v  a 2  s .  co m
    }
    return result;
}

From source file:com.datatorrent.stram.client.DTConfiguration.java

public void writeToFile(File file, Scope scope, String comment) throws IOException {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    Date date = new Date();
    Document doc;
    try {//from   w  ww  . jav a2s  . com
        doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException ex) {
        throw new RuntimeException(ex);
    }
    Element rootElement = doc.createElement("configuration");
    rootElement.appendChild(
            doc.createComment(" WARNING: Do not edit this file. Your changes will be overwritten. "));
    rootElement.appendChild(doc.createComment(" Written by dtgateway on " + sdf.format(date)));
    rootElement.appendChild(doc.createComment(" " + comment + " "));
    doc.appendChild(rootElement);
    for (Map.Entry<String, ValueEntry> entry : map.entrySet()) {
        ValueEntry valueEntry = entry.getValue();
        if (scope == null || valueEntry.scope == scope) {
            Element property = doc.createElement("property");
            rootElement.appendChild(property);
            Element name = doc.createElement("name");
            name.appendChild(doc.createTextNode(entry.getKey()));
            property.appendChild(name);
            Element value = doc.createElement("value");
            value.appendChild(doc.createTextNode(valueEntry.value));
            property.appendChild(value);
            if (valueEntry.description != null) {
                Element description = doc.createElement("description");
                description.appendChild(doc.createTextNode(valueEntry.description));
                property.appendChild(description);
            }
            if (valueEntry.isFinal) {
                Element isFinal = doc.createElement("final");
                isFinal.appendChild(doc.createTextNode("true"));
                property.appendChild(isFinal);
            }
        }
    }
    rootElement.appendChild(
            doc.createComment(" WARNING: Do not edit this file. Your changes will be overwritten. "));

    // write the content into xml file
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(file);
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.transform(source, result);
    } catch (TransformerConfigurationException ex) {
        throw new RuntimeException(ex);
    } catch (TransformerException ex) {
        throw new IOException(ex);
    }
}

From source file:uk.co.markfrimston.tasktree.TaskTree.java

protected void makeConfigEl(Document doc, Node parent, String name, String description, Object value) {
    parent.appendChild(doc.createTextNode("\n\t"));
    parent.appendChild(doc.createComment(description));
    parent.appendChild(doc.createTextNode("\n\t"));
    Element elParam = doc.createElement(name);
    if (value != null) {
        elParam.appendChild(doc.createTextNode(String.valueOf(value)));
    }/*from   www .j  ava  2  s  .  c  o  m*/
    parent.appendChild(elParam);
    parent.appendChild(doc.createTextNode("\n"));
}

From source file:org.gvnix.support.WebProjectUtilsImpl.java

/**
 * Add variable to contain request Locale in string format.
 * <p/>/*from ww  w . j a v  a  2 s  .c  o  m*/
 * 
 * <pre>
 * {@code
 * <c:set var="VAR_NAME">
 *   <!-- Get the user local from the page context (it was set by
 *        Spring MVC's locale resolver) -->
 *   <c:set var="jqlocale">${pageContext.response.locale}</c:set>
 *   <c:if test="${fn:length(jqlocale) eq 2}">
 *     <c:out value="${jqlocale}" />
 *   </c:if>
 *   <c:if test="${fn:length(jqlocale) gt 2}">
 *     <c:out value="${fn:substringBefore(jqlocale, '_')}" default="en" />
 *   </c:if>
 *   <c:if test="${fn:length(jqlocale) lt 2}">
 *     <c:out value="en" />
 *   </c:if>
 * </c:set>
 * }
 * </pre>
 * 
 * @param docTagx {@code .tagx} file document
 * @param root XML root node
 * @param varName name of variable to create, see {@code VAR_NAME} in
 *        example above
 */
public boolean addLocaleVarToTag(Document docTagx, Element root, String varName) {

    // Add locale var
    Element varElement = XmlUtils.findFirstElement(String.format("c:set[@var='${%s}']", varName), root);
    if (varElement == null) {
        varElement = docTagx.createElement("c:set");
        varElement.setAttribute("var", varName);
        varElement.appendChild(docTagx.createComment(
                " Get the user local from the page context (it was set by Spring MVC's locale resolver) "));

        Element pElement = docTagx.createElement("c:set");
        pElement.setAttribute("var", "jqlocale");
        pElement.appendChild(docTagx.createTextNode("${pageContext.response.locale}"));
        varElement.appendChild(pElement);

        Element ifElement = docTagx.createElement("c:if");
        ifElement.setAttribute("test", "${fn:length(jqlocale) eq 2}");

        Element outElement = docTagx.createElement("c:out");
        outElement.setAttribute(VALUE, "${jqlocale}");
        ifElement.appendChild(outElement);
        varElement.appendChild(ifElement);

        ifElement = docTagx.createElement("c:if");
        ifElement.setAttribute("test", "${fn:length(jqlocale) gt 2}");

        outElement = docTagx.createElement("c:out");
        outElement.setAttribute(VALUE, "${fn:substringBefore(jqlocale, '_')}");
        outElement.setAttribute("default", "en");
        ifElement.appendChild(outElement);
        varElement.appendChild(ifElement);

        ifElement = docTagx.createElement("c:if");
        ifElement.setAttribute("test", "${fn:length(jqlocale) lt 2}");

        outElement = docTagx.createElement("c:out");
        outElement.setAttribute(VALUE, "en");
        ifElement.appendChild(outElement);
        varElement.appendChild(ifElement);

        root.appendChild(varElement);

        return true;
    }
    return false;
}