Example usage for org.w3c.dom Document appendChild

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

Introduction

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

Prototype

public Node appendChild(Node newChild) throws DOMException;

Source Link

Document

Adds the node newChild to the end of the list of children of this node.

Usage

From source file:com.mirth.connect.server.mule.transformers.ResultMapToXML.java

public Object doTransform(Object source) throws TransformerException {
    if (source instanceof Map) {
        Map data = (Map) source;

        try {//from w w  w  . j  a  v  a 2 s.  c  om
            Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
            Element root = document.createElement("result");
            document.appendChild(root);

            for (Iterator iter = data.keySet().iterator(); iter.hasNext();) {
                String key = (String) iter.next();
                Element child = document.createElement(key);
                String value = new String();
                Object objectValue = data.get(key);
                if (objectValue != null) {
                    if (objectValue instanceof byte[]) {
                        value = new String((byte[]) objectValue);
                    } else if (objectValue instanceof java.sql.Clob) {
                        // convert it to a string
                        java.sql.Clob clobValue = (java.sql.Clob) objectValue;
                        Reader reader = clobValue.getCharacterStream();
                        if (reader == null) {
                            value = "";
                        }
                        StringBuffer sb = new StringBuffer();
                        try {
                            char[] charbuf = new char[(int) clobValue.length()];
                            for (int i = reader.read(charbuf); i > 0; i = reader.read(charbuf)) {
                                sb.append(charbuf, 0, i);
                            }
                        } catch (IOException e) {
                            logger.error("Error reading clob value.\n" + ExceptionUtils.getStackTrace(e));

                        }
                        value = sb.toString();
                    } else if (objectValue instanceof java.sql.Blob) {
                        try {
                            java.sql.Blob blobValue = (java.sql.Blob) objectValue;
                            value = new String(blobValue.getBytes(1, (int) blobValue.length()));
                        } catch (Exception ex) {
                            logger.error("Error reading blob value.\n" + ExceptionUtils.getStackTrace(ex));
                        }
                    } else {
                        value = objectValue.toString();
                    }

                }
                child.appendChild(document.createTextNode(value));
                root.appendChild(child);
            }

            DocumentSerializer docSerializer = new DocumentSerializer();
            return docSerializer.toXML(document);
        } catch (Exception e) {
            throw new TransformerException(
                    org.mule.config.i18n.Message.createStaticMessage("Failed to parse result map"), this);
        }
    } else if (source instanceof String) {
        return source.toString();
    } else {
        throw new TransformerException(
                org.mule.config.i18n.Message.createStaticMessage("Unregistered result type"), this);
    }
}

From source file:com.bluexml.xforms.actions.GetAction.java

/**
 * Gets the instance for forms that do not require calling the controller because of how simple
 * their instance is. The controller acts as a bridge to the mapping; when there's no
 * information to extract from the mapping, a better option is to serve the instance here.
 * // w  w  w.  j  a v a 2s .c o m
 * @param dataType
 * @param formType
 * @return the instance
 */
private Document getInstanceListOrSelector(String dataType, FormTypeEnum formType) {
    DocumentBuilder docBuilder = null;
    try {
        docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        if (logger.isErrorEnabled()) {
            logger.error("Failed to obtain a document builder", e);
        }
        return null;
    }
    Document instance = docBuilder.newDocument();
    Element rootElement = instance.createElement(dataType);
    instance.appendChild(rootElement);
    if (formType == FormTypeEnum.SELECTOR) {
        // the data type in the combo box
        Element sideData = instance.createElement(MsgId.INT_INSTANCE_SIDE_DATATYPE.getText());
        sideData.setTextContent(dataType);
        rootElement.appendChild(sideData);
        return instance;
    } else if (formType == FormTypeEnum.LIST) {
        // the id of the object whose Edit button was clicked
        Element editedid = instance.createElement(MsgId.INT_INSTANCE_SIDEEDIT.getText());
        rootElement.appendChild(editedid);
        return instance;
    }

    return null; // we never reach here
}

From source file:de.betterform.connector.ant.AntSubmissionHandler.java

public Map submit(Submission submission, Node instance) throws XFormsException {
    LOGGER.debug("AntSubmissionHandler.submit()");
    ByteArrayOutputStream stream = new ByteArrayOutputStream();

    if (submission.getMethod().equals("get")) {
        try {/*from w w w. j  ava2s. com*/
            String uri = getURI();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ByteArrayOutputStream errorStream = new ByteArrayOutputStream();

            String buildFilePath = (new URI(uri)).getSchemeSpecificPart()
                    .substring((new URI(uri)).getSchemeSpecificPart().indexOf(':') + 1);
            if (!"".equals(buildFilePath)) {
                File buildFile = new File(buildFilePath);
                String target = null;
                if (uri.contains("#")) {
                    //got Traget from uri
                    target = uri.substring(uri.indexOf('#') + 1);
                } else if (((Document) instance).getElementsByTagName("target").item(0) != null) {
                    //got target from xform
                    target = ((Document) instance).getElementsByTagName("target").item(0).getTextContent();
                } else {
                    // use default target
                    target = "default";
                }

                LOGGER.debug("AntSubmissionHandler.runTarget() BuildFile: " + buildFile.getAbsolutePath()
                        + " with Target:" + target);
                runTarget(buildFile, target, outputStream, errorStream);

                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                factory.setNamespaceAware(true);
                factory.setValidating(false);
                Document document = factory.newDocumentBuilder().newDocument();
                document.appendChild(document.createElementNS(null, "ant"));

                Element rootElement = document.getDocumentElement();
                Attr filename = document.createAttribute("fileName");
                filename.setValue(buildFile.getName());
                rootElement.setAttributeNode(filename);
                Element element = document.createElement("buildFile");
                DOMUtil.setElementValue(element, buildFile.getAbsolutePath());
                rootElement.appendChild(element);

                element = document.createElement("target");
                DOMUtil.setElementValue(element, target);
                rootElement.appendChild(element);

                element = document.createElement("output-stream");
                DOMUtil.setElementValue(element, outputStream.toString());
                rootElement.appendChild(element);

                element = document.createElement("error-stream");
                DOMUtil.setElementValue(element, errorStream.toString());
                rootElement.appendChild(element);
                DOMUtil.prettyPrintDOM(document, stream);
            } else {
                throw new XFormsException("submission method '" + submission.getMethod() + "' at: "
                        + DOMUtil.getCanonicalPath(submission.getElement()) + " not supported");
            }
        } catch (Exception e) {
            throw new XFormsException(e);
        }
    } else {
        throw new XFormsException("submission method '" + submission.getMethod() + "' at: "
                + DOMUtil.getCanonicalPath(submission.getElement()) + " not supported");
    }

    Map response = new HashMap();
    response.put(XFormsProcessor.SUBMISSION_RESPONSE_STREAM, new ByteArrayInputStream(stream.toByteArray()));
    return response;
}

From source file:XMLWriteTest.java

/**
 * Creates an SVG document of the current drawing.
 * @return the DOM tree of the SVG document
 *///from w  ww.j av  a  2 s  .  com
public Document buildDocument() {
    Document doc = builder.newDocument();
    Element svgElement = doc.createElement("svg");
    doc.appendChild(svgElement);
    svgElement.setAttribute("width", "" + getWidth());
    svgElement.setAttribute("height", "" + getHeight());
    for (int i = 0; i < rects.size(); i++) {
        Color c = colors.get(i);
        Rectangle2D r = rects.get(i);
        Element rectElement = doc.createElement("rect");
        rectElement.setAttribute("x", "" + r.getX());
        rectElement.setAttribute("y", "" + r.getY());
        rectElement.setAttribute("width", "" + r.getWidth());
        rectElement.setAttribute("height", "" + r.getHeight());
        rectElement.setAttribute("fill", colorToString(c));
        svgElement.appendChild(rectElement);
    }
    return doc;
}

From source file:channellistmaker.channelfilemaker.ChannelDocumentMaker.java

/**
 * @return ????X???ML????????/*  w w w . ja  va 2  s .c om*/
 */
public String getChannelList() {
    try {
        final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        final DocumentBuilder db = dbf.newDocumentBuilder();
        final Document document = db.newDocument();
        // >>>>> DOM??
        Element channels_e = document.createElement("channels");//<-root
        document.appendChild(channels_e);

        final Set<MultiKey<Integer>> keys = this.channels.keySet();
        for (MultiKey<Integer> key : keys) {
            Channel ch = channels.get(key);
            this.addChannelElement(document, channels_e, ch);
        }

        TransformerFactory tf = TransformerFactory.newInstance();

        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        StringWriter writer = new StringWriter();// <-??????????
        StreamResult result = new StreamResult(writer);

        DOMSource source = new DOMSource(document);
        transformer.transform(source, result);

        return writer.toString();
    } catch (ParserConfigurationException | TransformerConfigurationException ex) {
        LOG.fatal(ex);
        return "";
    } catch (TransformerException ex) {
        LOG.fatal(ex);
        return "";
    }
}

From source file:me.mayo.telnetkek.config.ConfigLoader.java

private boolean generateXML(final File file) {
    try {//from   w  ww.j a  v  a 2  s.  com
        final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();

        final Element rootElement = doc.createElement("configuration");
        doc.appendChild(rootElement);

        rootElement.appendChild(this.servers.listToXML(doc));
        rootElement.appendChild(this.playerCommands.listToXML(doc));
        rootElement.appendChild(this.favoriteButtons.listToXML(doc));

        final Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        transformer.transform(new DOMSource(doc), new StreamResult(file));

        return true;
    } catch (IllegalArgumentException | ParserConfigurationException | TransformerException | DOMException ex) {
        TelnetKek.LOGGER.log(Level.SEVERE, null, ex);
    }

    return false;
}

From source file:com.oprisnik.semdroid.SemdroidServlet.java

public String getResults(SemdroidReport results, InputStream transformationStyle) {
    try {/*from  w w w  . j a va2  s.com*/
        Document doc = XmlUtils.createDocument();
        Element rootElement = doc.createElement("AnalysisResults");
        doc.appendChild(rootElement);
        XmlUtils.addResults(results, doc, rootElement);

        StringWriter writer = new StringWriter();

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        StreamSource stylesource = new StreamSource(transformationStyle);
        Transformer transformer = transformerFactory.newTransformer(stylesource);
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(writer);
        transformer.transform(source, result);
        return writer.toString();

    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
        log.warning("Exception: " + pce.getMessage());
        log.throwing(this.getClass().getName(), "getResults", pce);
    } catch (TransformerConfigurationException e) {
        e.printStackTrace();
        log.warning("Exception: " + e.getMessage());
        log.throwing(this.getClass().getName(), "getResults", e);
    } catch (TransformerException e) {
        e.printStackTrace();
        log.warning("Exception: " + e.getMessage());
        log.throwing(this.getClass().getName(), "getResults", e);
    }
    return null;
}

From source file:de.crowdcode.movmvn.plugin.general.GeneralPlugin.java

private Element createPomRootAndTitle(Document doc) {
    Element rootElement = doc.createElement("project");
    doc.appendChild(rootElement);
    rootElement.setAttribute("xmlns", "http://maven.apache.org/POM/4.0.0");
    rootElement.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
    rootElement.setAttribute("xsi:schemaLocation",
            "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd");

    Element modelVersion = doc.createElement("modelVersion");
    modelVersion.appendChild(doc.createTextNode("4.0.0"));
    rootElement.appendChild(modelVersion);

    createPomGroupArtifactVersion(doc, rootElement, "de.xxx", context.getProjectName(), "1.0.0-SNAPSHOT");

    Element packaging = doc.createElement("packaging");
    packaging.appendChild(doc.createTextNode("jar"));
    rootElement.appendChild(packaging);//from  w  w w  .j  av  a 2 s .  com
    Element name = doc.createElement("name");
    name.appendChild(doc.createTextNode(context.getProjectName()));
    rootElement.appendChild(name);
    Element url = doc.createElement("url");
    url.appendChild(doc.createTextNode("http://maven.apache.org"));
    rootElement.appendChild(url);
    return rootElement;
}

From source file:de.betterform.xml.dom.DOMUtil.java

public static Node importAndAppendNode(Document document, Node toImport) {
    if (toImport != null) {
        Node imported = document.importNode(toImport, true);
        //            Node root = document.getDocumentElement();
        return document.appendChild(imported);
    }//from  ww w .  ja v  a2s.  co  m
    return null;
}

From source file:gov.medicaid.services.impl.FileNetServiceBean.java

/**
 * Creates the XML.//w ww  .j a  v a 2  s . co  m
 * 
 * @param outFile
 *            the output file handler
 * @param attributes
 *            the content
 * @throws PortalServiceException
 *             if any error occurs
 */
private void createXML(File outFile, Map<String, String> attributes) throws PortalServiceException {
    try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // root elements
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("Document");
        doc.appendChild(rootElement);
        for (String key : attributes.keySet()) {
            Element indexVal = doc.createElement("Indexvalue");
            Attr attr = doc.createAttribute("name");
            attr.setValue(key);
            indexVal.setAttributeNode(attr);
            if (attributes.get(key) != null) {
                indexVal.appendChild(doc.createTextNode(attributes.get(key)));
            }
            rootElement.appendChild(indexVal);
        }
        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(outFile);

        transformer.transform(source, result);

    } catch (ParserConfigurationException e) {
        throw new PortalServiceException("Failed to create FileNet xml", e);
    } catch (TransformerException e) {
        throw new PortalServiceException("Failed to create FileNet xml", e);
    }

}