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

/**
 * Clone given Node into target Document. If targe is null, same Document will be used.
 * If deep is specified, all children below will also be cloned.
 *//*from w w w.  j a va2s. co  m*/
public static Node cloneNode(Node node, Document target, boolean deep) throws DOMException {
    if (target == null || node.getOwnerDocument() == target)
        // same Document
        return node.cloneNode(deep);
    else {
        //DOM level 2 provides this in Document, so once xalan switches to that,
        //we can take out all the below and just call target.importNode(node, deep);
        //For now, we implement based on the javadocs for importNode
        Node newNode;
        int nodeType = node.getNodeType();

        switch (nodeType) {
        case Node.ATTRIBUTE_NODE:
            newNode = target.createAttribute(node.getNodeName());

            break;

        case Node.DOCUMENT_FRAGMENT_NODE:
            newNode = target.createDocumentFragment();

            break;

        case Node.ELEMENT_NODE:

            Element newElement = target.createElement(node.getNodeName());
            NamedNodeMap nodeAttr = node.getAttributes();

            if (nodeAttr != null)
                for (int i = 0; i < nodeAttr.getLength(); i++) {
                    Attr attr = (Attr) nodeAttr.item(i);

                    if (attr.getSpecified()) {
                        Attr newAttr = (Attr) cloneNode(attr, target, true);
                        newElement.setAttributeNode(newAttr);
                    }
                }

            newNode = newElement;

            break;

        case Node.ENTITY_REFERENCE_NODE:
            newNode = target.createEntityReference(node.getNodeName());

            break;

        case Node.PROCESSING_INSTRUCTION_NODE:
            newNode = target.createProcessingInstruction(node.getNodeName(), node.getNodeValue());

            break;

        case Node.TEXT_NODE:
            newNode = target.createTextNode(node.getNodeValue());

            break;

        case Node.CDATA_SECTION_NODE:
            newNode = target.createCDATASection(node.getNodeValue());

            break;

        case Node.COMMENT_NODE:
            newNode = target.createComment(node.getNodeValue());

            break;

        case Node.NOTATION_NODE:
        case Node.ENTITY_NODE:
        case Node.DOCUMENT_TYPE_NODE:
        case Node.DOCUMENT_NODE:
        default:
            throw new IllegalArgumentException("Importing of " + node + " not supported yet");
        }

        if (deep)
            for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling())
                newNode.appendChild(cloneNode(child, target, true));

        return newNode;
    }
}

From source file:Main.java

/**
 * Clone given Node into target Document. If targe is null, same Document will be used.
 * If deep is specified, all children below will also be cloned.
 *//*from   w  ww .  j a  v  a 2  s  .com*/
public final static Node cloneNode(Node node, Document target, boolean deep) throws DOMException {
    if ((target == null) || (node.getOwnerDocument() == target)) {
        // same Document
        return node.cloneNode(deep);
    } else {
        //DOM level 2 provides this in Document, so once xalan switches to that,
        //we can take out all the below and just call target.importNode(node, deep);
        //For now, we implement based on the javadocs for importNode
        Node newNode;
        int nodeType = node.getNodeType();

        switch (nodeType) {
        case Node.ATTRIBUTE_NODE:
            newNode = target.createAttribute(node.getNodeName());

            break;

        case Node.DOCUMENT_FRAGMENT_NODE:
            newNode = target.createDocumentFragment();

            break;

        case Node.ELEMENT_NODE:

            Element newElement = target.createElement(node.getNodeName());
            NamedNodeMap nodeAttr = node.getAttributes();

            if (nodeAttr != null) {
                for (int i = 0; i < nodeAttr.getLength(); i++) {
                    Attr attr = (Attr) nodeAttr.item(i);

                    if (attr.getSpecified()) {
                        Attr newAttr = (Attr) cloneNode(attr, target, true);
                        newElement.setAttributeNode(newAttr);
                    }
                }
            }

            newNode = newElement;

            break;

        case Node.ENTITY_REFERENCE_NODE:
            newNode = target.createEntityReference(node.getNodeName());

            break;

        case Node.PROCESSING_INSTRUCTION_NODE:
            newNode = target.createProcessingInstruction(node.getNodeName(), node.getNodeValue());

            break;

        case Node.TEXT_NODE:
            newNode = target.createTextNode(node.getNodeValue());

            break;

        case Node.CDATA_SECTION_NODE:
            newNode = target.createCDATASection(node.getNodeValue());

            break;

        case Node.COMMENT_NODE:
            newNode = target.createComment(node.getNodeValue());

            break;

        case Node.NOTATION_NODE:
        case Node.ENTITY_NODE:
        case Node.DOCUMENT_TYPE_NODE:
        case Node.DOCUMENT_NODE:
        default:
            throw new IllegalArgumentException("Importing of " + node + " not supported yet");
        }

        if (deep) {
            for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
                newNode.appendChild(cloneNode(child, target, true));
            }
        }

        return newNode;
    }
}

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

/**
 * Append a js definition in loadScript.tagx
 * <p/>//from ww w  .j  av a  2s .co  m
 * This first append a "spring:url" (if not exists) and then add the "link"
 * tag (if not exists)
 * 
 * @param docTagx {@code .tagx} file document
 * @param root XML root node
 * @param varName name of variable to hold js url
 * @param location js location
 * @return document has changed
 */

public boolean addJSToTag(Document docTagx, Element root, String varName, String location) {
    boolean modified = false;

    // add url resolution
    modified = addUrlToTag(docTagx, root, varName, location);

    // Add script
    Element scriptElement = XmlUtils.findFirstElement(String.format("script[@src='${%s}']", varName), root);
    if (scriptElement == null) {
        scriptElement = docTagx.createElement("script");
        scriptElement.setAttribute("src", "${".concat(varName).concat("}"));
        scriptElement.setAttribute("type", "text/javascript");
        scriptElement.appendChild(docTagx.createComment("required for FF3 and Opera"));
        root.appendChild(scriptElement);
        modified = true;
    }
    return modified;
}

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

/**
 * Append a js definition in loadScript.tagx
 * <p/>//w  ww  .j  a  va2 s.c  om
 * This first append a "spring:url" (if not exists) and then add the "link"
 * tag (if not exists)
 * 
 * @param docTagx {@code .tagx} file document
 * @param root XML root node
 * @param varName name of variable to hold js url
 * @param location js location
 * @return document has changed
 */

public boolean updateJSToTag(Document docTagx, Element root, String varName, String location) {
    boolean modified = false;

    // add url resolution
    modified = updateUrlToTag(docTagx, root, varName, location);

    // Add script
    Element scriptElement = XmlUtils.findFirstElement(String.format("script[@src='${%s}']", varName), root);
    if (scriptElement == null) {
        scriptElement = docTagx.createElement("script");
        scriptElement.setAttribute("src", "${".concat(varName).concat("}"));
        scriptElement.setAttribute("type", "text/javascript");
        scriptElement.appendChild(docTagx.createComment("required for FF3 and Opera"));
        root.appendChild(scriptElement);
        modified = true;
    }
    return modified;
}

From source file:cross.applicationContext.ReflectionApplicationContextGenerator.java

/**
 * Creates an xml element using the given document for element creation.
 *
 * @param generator/*from w w w.j ava 2 s .c o  m*/
 * @param document the document use for element creation
 * @param beanDescriptor
 * @return the modified element
 */
public static Element createElement(ReflectionApplicationContextGenerator generator, Document document,
        BeanDescriptor beanDescriptor) {
    Class<?> javaClass = beanDescriptor.clazz;
    System.out.println("Building bean element for " + javaClass.getName());
    //get the name of the class
    String className = javaClass.getSimpleName();

    //get the name of the package
    String packageName = javaClass.getPackage().getName();

    //create <bean /> element
    Element beanElement = document.createElement("bean");
    String classNameLower = toLowerCaseName(className);
    beanElement.setAttribute("id", classNameLower);
    String classAttr = (packageName == null) ? className : packageName + "." + className;
    beanElement.setAttribute("class", classAttr);
    beanElement.setAttribute("scope", beanDescriptor.scope);
    //constructors are not supported
    //get all the class' properties from the public fields and setter methods.

    for (Method method : javaClass.getMethods()) {
        checkMutableProperties(method, javaClass, beanDescriptor.obj, beanDescriptor.properties);
    }
    //sort by name
    Collections.sort(beanDescriptor.properties, new Comparator<ObjectProperty>() {
        @Override
        public int compare(ObjectProperty t, ObjectProperty t1) {
            return t.name.compareTo(t1.name);
        }
    });
    List<String> blackList = Arrays.asList("workflow", "progress", "cvResolver");
    //add all properties as <property /> elements
    for (ObjectProperty p : beanDescriptor.properties) {
        if (!blackList.contains(p.name)) {
            Element propertyElement = document.createElement("property");
            propertyElement.setAttribute("name", p.name);
            Comment propertyCommentElement = document
                    .createComment(AnnotationInspector.getDescriptionFor(javaClass, p.name));
            boolean append = true;
            if (p.type.startsWith("java.lang.")) {
                String shortType = p.type.substring("java.lang.".length());
                if (primitives.contains(shortType) || wrappers.contains(shortType)) {
                    propertyElement.setAttribute("value", p.value);
                }
            } else if (primitives.contains(p.type) || wrappers.contains(p.type)) {
                propertyElement.setAttribute("value", p.value);
            } else if ("Array".equals(p.type) || "List".equals(p.type) || "java.util.List".equals(p.type)) {
                Element listElement = document.createElement("list");
                String genericType = p.genericType;
                propertyElement.appendChild(listElement);
            } else if ("Set".equals(p.type) || "java.util.Set".equals(p.type)) {
                Element listElement = document.createElement("set");
                propertyElement.appendChild(listElement);
            } else if ("Map".equals(p.type) || "java.util.Map".equals(p.type)) {
                Element listElement = document.createElement("map");
                propertyElement.appendChild(listElement);
            } else if ("Properties".equals(p.type) || "java.util.Properties".equals(p.type)) {
                Element listElement = document.createElement("props");
                propertyElement.appendChild(listElement);
            } else {
                try {
                    //                    System.err.println("Skipping ref!");
                    Set<BeanDefinition> beanDefinitions = getImplementationsOf(Class.forName(p.type), "cross",
                            "maltcms", "net.sf.maltcms");
                    BeanDefinition first = null;
                    for (BeanDefinition bd : beanDefinitions) {
                        generator.addBean(bd.getBeanClassName());
                        if (first == null) {
                            first = bd;
                        }
                    }
                    if (first != null) {
                        String simpleName = first.getBeanClassName()
                                .substring(first.getBeanClassName().lastIndexOf(".") + 1);
                        propertyElement.setAttribute("ref",
                                generator.classToElement.get(toLowerCaseName(simpleName)).id);
                    }
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(ReflectionApplicationContextGenerator.class.getName()).log(Level.SEVERE,
                            null, ex);
                }
                append = true;
                //                    try {
                //                        generator.addBean(p.type);
                //                        Class<?> c = Class.forName(p.type);
                //                        List<Object> objects = generator.classToObject.get(c);
                //                        if (objects != null && !objects.isEmpty()) {
                //                            propertyElement.setAttribute("ref", generator.buildBeanElement(objects.get(0)).id);
                //                        } else {
                //                            append = false;
                //                        }
                //                    } catch (ClassNotFoundException ex) {
                //                        Logger.getLogger(ReflectionApplicationContextGenerator.class.getName()).log(Level.SEVERE, null, ex);
                //                    }

            }
            if (append) {
                beanElement.appendChild(propertyCommentElement);
                beanElement.appendChild(propertyElement);
            } else {
                beanElement.appendChild(propertyCommentElement);
                Comment comment = document.createComment("<property name=\"" + p.name + "\" ref=\"\"/>");
                beanElement.appendChild(comment);
            }
        }
    }
    return beanElement;
}

From source file:jef.tools.XMLUtils.java

/**
 * ?//  w  ww  .j a  v  a2s .c  o  m
 * 
 * @param node
 *            
 * @param comment
 *            
 * @return Comment
 */
public static Comment addComment(Node node, String comment) {
    Document doc = null;
    if (node.getNodeType() == Node.DOCUMENT_NODE) {
        doc = (Document) node;
    } else {
        doc = node.getOwnerDocument();
    }
    Comment e = doc.createComment(comment);
    node.appendChild(e);
    return e;
}

From source file:com.twinsoft.convertigo.engine.util.CarUtils.java

private static Document exportProject(Project project, final List<TestCase> selectedTestCases)
        throws EngineException {
    try {//w w w. j av a  2  s . c  o  m
        final Document document = XMLUtils.getDefaultDocumentBuilder().newDocument();
        //            ProcessingInstruction pi = document.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"");
        //            document.appendChild(pi);
        final Element rootElement = document.createElement("convertigo");

        rootElement.setAttribute("version", com.twinsoft.convertigo.engine.Version.fullProductVersion);
        rootElement.setAttribute("engine", com.twinsoft.convertigo.engine.Version.version);
        rootElement.setAttribute("beans", com.twinsoft.convertigo.beans.Version.version);
        String studioVersion = "";
        try {
            Class<?> c = Class.forName("com.twinsoft.convertigo.eclipse.Version");
            studioVersion = (String) c.getDeclaredField("version").get(null);
        } catch (Exception e) {
        } catch (Throwable th) {
        }

        rootElement.setAttribute("studio", studioVersion);
        document.appendChild(rootElement);

        new WalkHelper() {
            protected Element parentElement = rootElement;

            @Override
            protected void walk(DatabaseObject databaseObject) throws Exception {
                Element parentElement = this.parentElement;

                Element element = parentElement;
                element = databaseObject.toXml(document);
                String name = " : " + databaseObject.getName();
                try {
                    name = CachedIntrospector.getBeanInfo(databaseObject.getClass()).getBeanDescriptor()
                            .getDisplayName() + name;
                } catch (IntrospectionException e) {
                    name = databaseObject.getClass().getSimpleName() + name;
                }
                Integer depth = (Integer) document.getUserData("depth");
                if (depth == null) {
                    depth = 0;
                }

                String openpad = StringUtils.repeat("   ", depth);
                String closepad = StringUtils.repeat("   ", depth);
                parentElement.appendChild(document.createTextNode("\n"));
                parentElement.appendChild(
                        document.createComment(StringUtils.rightPad(openpad + "<" + name + ">", 150)));

                if (databaseObject instanceof TestCase && selectedTestCases.size() > 0) {
                    if (selectedTestCases.contains((TestCase) databaseObject)) {
                        parentElement.appendChild(element);
                    }
                } else {
                    parentElement.appendChild(element);
                }

                document.setUserData("depth", depth + 1, null);

                this.parentElement = element;
                super.walk(databaseObject);

                element.appendChild(document.createTextNode("\n"));
                element.appendChild(
                        document.createComment(StringUtils.rightPad(closepad + "</" + name + ">", 150)));
                document.setUserData("depth", depth, null);

                databaseObject.hasChanged = false;
                databaseObject.bNew = false;

                this.parentElement = parentElement;
            }

        }.init(project);

        return document;
    } catch (Exception e) {
        throw new EngineException("Unable to export the project \"" + project.getName() + "\".", e);
    }
}

From source file:conf.Configuration.java

/** 
 * Write out the non-default properties in this configuration to the given
 * {@link Writer}.// w ww . j  a v  a2 s.  c om
 * 
 * @param out the writer to write to.
 */
public synchronized void writeXml(Writer out) throws IOException {
    Properties properties = getProps();
    try {
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        Element conf = doc.createElement("configuration");
        doc.appendChild(conf);
        conf.appendChild(doc.createTextNode("\n"));
        for (Enumeration e = properties.keys(); e.hasMoreElements();) {
            String name = (String) e.nextElement();
            Object object = properties.get(name);
            String value = null;
            if (object instanceof String) {
                value = (String) object;
            } else {
                continue;
            }
            Element propNode = doc.createElement("property");
            conf.appendChild(propNode);

            if (updatingResource != null) {
                Comment commentNode = doc.createComment("Loaded from " + updatingResource.get(name));
                propNode.appendChild(commentNode);
            }
            Element nameNode = doc.createElement("name");
            nameNode.appendChild(doc.createTextNode(name));
            propNode.appendChild(nameNode);

            Element valueNode = doc.createElement("value");
            valueNode.appendChild(doc.createTextNode(value));
            propNode.appendChild(valueNode);

            conf.appendChild(doc.createTextNode("\n"));
        }

        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(out);
        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer transformer = transFactory.newTransformer();
        transformer.transform(source, result);
    } catch (TransformerException te) {
        throw new IOException(te);
    } catch (ParserConfigurationException pe) {
        throw new IOException(pe);
    }
}

From source file:co.cask.cdap.common.conf.Configuration.java

/**
 * Return the XML DOM corresponding to this Configuration.
 *///www. j  av a 2s  . c  om
private synchronized Document asXmlDocument() throws IOException {
    Document doc;
    try {
        doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException pe) {
        throw new IOException(pe);
    }
    Element conf = doc.createElement("configuration");
    doc.appendChild(conf);
    conf.appendChild(doc.createTextNode("\n"));
    handleDeprecation(); //ensure properties is set and deprecation is handled
    for (Enumeration e = properties.keys(); e.hasMoreElements();) {
        String name = (String) e.nextElement();
        Object object = properties.get(name);
        String value = null;
        if (object instanceof String) {
            value = (String) object;
        } else {
            continue;
        }
        Element propNode = doc.createElement("property");
        conf.appendChild(propNode);

        if (updatingResource != null) {
            Comment commentNode = doc.createComment("Loaded from " + updatingResource.get(name));
            propNode.appendChild(commentNode);
        }
        Element nameNode = doc.createElement("name");
        nameNode.appendChild(doc.createTextNode(name));
        propNode.appendChild(nameNode);

        Element valueNode = doc.createElement("value");
        valueNode.appendChild(doc.createTextNode(value));
        propNode.appendChild(valueNode);

        conf.appendChild(doc.createTextNode("\n"));
    }
    return doc;
}