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.iontorrent.vaadin.utils.JFreeChartWrapper.java

@Override
public Resource getSource() {
    if (res == null) {
        res = new ApplicationResource() {

            private ByteArrayInputStream bytestream = null;

            ByteArrayInputStream getByteStream() {
                if (chart != null && bytestream == null) {
                    int widht = getGraphWidth();
                    int height = getGraphHeight();
                    info = new ChartRenderingInfo();

                    if (mode == RenderingMode.SVG) {

                        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
                        DocumentBuilder docBuilder = null;
                        try {
                            docBuilder = docBuilderFactory.newDocumentBuilder();
                        } catch (ParserConfigurationException e1) {
                            throw new RuntimeException(e1);
                        }/*from  w w w  .  ja  v  a2 s . com*/
                        Document document = docBuilder.newDocument();
                        Element svgelem = document.createElement("svg");
                        document.appendChild(svgelem);

                        // Create an instance of the SVG Generator
                        SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

                        // draw the chart in the SVG generator

                        chart.draw(svgGenerator, new Rectangle(widht, height), info);
                        Element el = svgGenerator.getRoot();
                        el.setAttributeNS(null, "viewBox", "0 0 " + widht + " " + height + "");
                        el.setAttributeNS(null, "style", "width:100%;height:100%;");
                        el.setAttributeNS(null, "preserveAspectRatio", getSvgAspectRatio());

                        // Write svg to buffer
                        ByteArrayOutputStream baoutputStream = new ByteArrayOutputStream();
                        Writer out;
                        try {
                            OutputStream outputStream = gzipEnabled ? new GZIPOutputStream(baoutputStream)
                                    : baoutputStream;
                            out = new OutputStreamWriter(outputStream, "UTF-8");
                            /*
                             * don't use css, FF3 can'd deal with the result
                             * perfectly: wrong font sizes
                             */
                            boolean useCSS = false;
                            svgGenerator.stream(el, out, useCSS, false);
                            outputStream.flush();
                            outputStream.close();
                            bytestream = new ByteArrayInputStream(baoutputStream.toByteArray());
                        } catch (UnsupportedEncodingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (SVGGraphics2DIOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    } else {
                        // Draw png to bytestream
                        try {

                            byte[] bytes = ChartUtilities.encodeAsPNG(chart.createBufferedImage(widht, height));
                            bytestream = new ByteArrayInputStream(bytes);
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                    }

                } else {
                    bytestream.reset();
                }
                return bytestream;
            }

            public Application getApplication() {
                return JFreeChartWrapper.this.getApplication();
            }

            public int getBufferSize() {
                if (getByteStream() != null) {
                    return getByteStream().available();
                } else {
                    return 0;
                }
            }

            public long getCacheTime() {
                return 0;
            }

            public String getFilename() {
                if (mode == RenderingMode.PNG) {
                    return "graph.png";
                } else {
                    return gzipEnabled ? "graph.svgz" : "graph.svg";
                }
            }

            public DownloadStream getStream() {
                DownloadStream downloadStream = new DownloadStream(getByteStream(), getMIMEType(),
                        getFilename());
                if (gzipEnabled && mode == RenderingMode.SVG) {
                    downloadStream.setParameter("Content-Encoding", "gzip");
                }
                return downloadStream;
            }

            public String getMIMEType() {
                if (mode == RenderingMode.PNG) {
                    return "image/png";
                } else {
                    return "image/svg+xml";
                }
            }
        };
    }
    return res;
}

From source file:com.axway.ebxml.KeyInfoWriter.java

/**
 * Builds <code>KeyInfo</code> instance given an array of <code>X509Certificate</code>. The
 * <code>KeyInfo</code> can be serialized and used within the Certificate element of an ebXML CPP or CPA
 * @param certs Array of certificates to include. The certificates in the array must be related in a certificate chain
 *      The first certificate in the array must be the end-entity certificate.
 * @return Initialized <code>KeyInfo</code> ready to be serialized
 * @throws IllegalArgumentException Null or Empty certificate list is passed as parameter
 * @throws KeyInfoWriterException Thrown when there is any other error encountered. The <code>KeyInfoWriterException</code>
 *  may wrap other exceptions caught within this method.
 *///from   w w w .ja  v  a 2 s  . co m
public KeyInfo buildKeyInfo(X509Certificate[] certs) throws KeyInfoWriterException {
    if (certs == null || certs.length == 0)
        throw new IllegalArgumentException("cert is null or empty");

    try {
        org.w3c.dom.Document doc = XmlUtil.buildDocument();

        KeyInfo keyInfo = new KeyInfo(doc);
        X509Data x509Data;
        for (X509Certificate cert : certs) {
            if (cert == certs[0]) // Only add KeyInfo for the first certificate in the chain (the end entity certificate)
                keyInfo.add(cert.getPublicKey());
            x509Data = buildX509Data(doc, cert); // Add X509Data elements for all the certificates in the chain
            keyInfo.add(x509Data);
        }

        doc.appendChild(keyInfo.getElement());
        return keyInfo;
    } catch (ParserConfigurationException e) {
        logger.error("Exception writing KeyInfo", e);
        throw new KeyInfoWriterException(e);
    } catch (XMLSecurityException e) {
        logger.error("Exception writing KeyInfo", e);
        throw new KeyInfoWriterException(e);
    }
}

From source file:com.mirth.connect.server.migration.Migrate3_0_0.java

private void migrateCodeTemplateTable() {
    Logger logger = Logger.getLogger(getClass());
    PreparedStatement preparedStatement = null;
    ResultSet results = null;/*ww  w.java2 s . c o  m*/

    try {
        /*
         * MIRTH-1667: Derby fails if autoCommit is set to true and there are a large number of
         * results. The following error occurs: "ERROR 40XD0: Container has been closed"
         */
        Connection connection = getConnection();
        connection.setAutoCommit(false);

        preparedStatement = connection.prepareStatement(
                "SELECT ID, NAME, CODE_SCOPE, CODE_TYPE, TOOLTIP, CODE FROM OLD_CODE_TEMPLATE");
        results = preparedStatement.executeQuery();

        while (results.next()) {
            String id = "";

            try {
                id = results.getString(1);
                String name = results.getString(2);
                String codeScope = results.getString(3);
                String codeType = results.getString(4);
                String toolTip = results.getString(5);
                String code = results.getString(6);

                Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
                Element element = document.createElement("codeTemplate");
                document.appendChild(element);
                DonkeyElement codeTemplate = new DonkeyElement(element);

                codeTemplate.addChildElement("id", id);
                codeTemplate.addChildElement("name", name);
                codeTemplate.addChildElement("tooltip", toolTip);
                codeTemplate.addChildElement("code", code);
                codeTemplate.addChildElement("type", codeType);
                codeTemplate.addChildElement("scope", codeScope);

                // If the starting schema version is 2.0 or later, we need to add the version node to the XML.
                if (getStartingVersion() != null && getStartingVersion().ordinal() >= Version.V7.ordinal()) {
                    codeTemplate.addChildElement("version", "2.0");
                }

                String serializedCodeTemplate = new DonkeyElement(element).toXml();

                PreparedStatement updateStatement = null;
                try {
                    updateStatement = connection
                            .prepareStatement("INSERT INTO CODE_TEMPLATE (ID, CODE_TEMPLATE) VALUES (?, ?)");
                    updateStatement.setString(1, id);
                    updateStatement.setString(2, serializedCodeTemplate);
                    updateStatement.executeUpdate();
                    updateStatement.close();
                } finally {
                    DbUtils.closeQuietly(updateStatement);
                }
            } catch (Exception e) {
                logger.error("Error migrating code template " + id + ".", e);
            }
        }

        connection.commit();
    } catch (Exception e) {
        logger.error("Error migrating code templates.", e);
    } finally {
        DbUtils.closeQuietly(results);
        DbUtils.closeQuietly(preparedStatement);
    }
}

From source file:org.vaadin.addon.JFreeChartWrapper.java

@Override
public Resource getSource() {
    if (res == null) {
        StreamSource streamSource = new StreamResource.StreamSource() {
            private ByteArrayInputStream bytestream = null;

            ByteArrayInputStream getByteStream() {
                if (chart != null && bytestream == null) {
                    int widht = getGraphWidth();
                    int height = getGraphHeight();

                    if (mode == RenderingMode.SVG) {

                        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
                        DocumentBuilder docBuilder = null;
                        try {
                            docBuilder = docBuilderFactory.newDocumentBuilder();
                        } catch (ParserConfigurationException e1) {
                            throw new RuntimeException(e1);
                        }//  w w w .  jav  a  2 s .  c om
                        Document document = docBuilder.newDocument();
                        Element svgelem = document.createElement("svg");
                        document.appendChild(svgelem);

                        // Create an instance of the SVG Generator
                        SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

                        // draw the chart in the SVG generator
                        chart.draw(svgGenerator, new Rectangle(widht, height));
                        Element el = svgGenerator.getRoot();
                        el.setAttributeNS(null, "viewBox", "0 0 " + widht + " " + height + "");
                        el.setAttributeNS(null, "style", "width:100%;height:100%;");
                        el.setAttributeNS(null, "preserveAspectRatio", getSvgAspectRatio());

                        // Write svg to buffer
                        ByteArrayOutputStream baoutputStream = new ByteArrayOutputStream();
                        Writer out;
                        try {
                            OutputStream outputStream = gzipEnabled ? new GZIPOutputStream(baoutputStream)
                                    : baoutputStream;
                            out = new OutputStreamWriter(outputStream, "UTF-8");
                            /*
                             * don't use css, FF3 can'd deal with the result
                             * perfectly: wrong font sizes
                             */
                            boolean useCSS = false;
                            svgGenerator.stream(el, out, useCSS, false);
                            outputStream.flush();
                            outputStream.close();
                            bytestream = new ByteArrayInputStream(baoutputStream.toByteArray());
                        } catch (UnsupportedEncodingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (SVGGraphics2DIOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    } else {
                        // Draw png to bytestream
                        try {
                            byte[] bytes = ChartUtilities.encodeAsPNG(chart.createBufferedImage(widht, height));
                            bytestream = new ByteArrayInputStream(bytes);
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                    }

                } else {
                    bytestream.reset();
                }
                return bytestream;
            }

            @Override
            public InputStream getStream() {
                return getByteStream();
            }
        };

        res = new StreamResource(streamSource, String.format("graph%d", System.currentTimeMillis())) {

            @Override
            public int getBufferSize() {
                if (getStreamSource().getStream() != null) {
                    try {
                        return getStreamSource().getStream().available();
                    } catch (IOException e) {
                        return 0;
                    }
                } else {
                    return 0;
                }
            }

            @Override
            public long getCacheTime() {
                return 0;
            }

            @Override
            public String getFilename() {
                if (mode == RenderingMode.PNG) {
                    return super.getFilename() + ".png";
                } else {
                    return super.getFilename() + (gzipEnabled ? ".svgz" : ".svg");
                }
            }

            @Override
            public DownloadStream getStream() {
                DownloadStream downloadStream = new DownloadStream(getStreamSource().getStream(), getMIMEType(),
                        getFilename());
                if (gzipEnabled && mode == RenderingMode.SVG) {
                    downloadStream.setParameter("Content-Encoding", "gzip");
                }
                return downloadStream;
            }

            @Override
            public String getMIMEType() {
                if (mode == RenderingMode.PNG) {
                    return "image/png";
                } else {
                    return "image/svg+xml";
                }
            }
        };
    }
    return res;
}

From source file:de.tudarmstadt.ukp.dkpro.core.io.mmax2.MMAXWriter.java

public String createMMAXFile(String mmaxFilename) throws MMAXWriterException {

    log.info("Writing Basedata");
    File basedataFile = new File(basedataPath, mmaxFilename + ".xml");
    basedata.save(basedataFile);/* w w  w. jav  a2  s.  c  o  m*/

    Document doc = createXML();
    Element toplevel = doc.createElement("mmax_project");

    Element elem = doc.createElement("words");
    elem.appendChild(doc.createTextNode(mmaxFilename + ".xml"));
    toplevel.appendChild(elem);

    File mmaxFile = new File(projectPath, mmaxFilename + ".mmax");
    doc.appendChild(toplevel);
    saveXML(doc, mmaxFile, null, null);

    // load the current discourse
    loadDiscourse(mmaxFile.getPath());

    return basedataFile.getName();
}

From source file:com.alfaariss.oa.util.configuration.handler.dummy.DummyConfigurationHandler.java

/**
 * Parse the configuration from the file.
 * @see IConfigurationHandler#parseConfiguration()
 *///w  w w  .j  a va 2  s .com
public Document parseConfiguration() throws ConfigurationException {
    Document dRet = null;
    //create DocumentBuilderFactory to parse config file.
    DocumentBuilderFactory oDocumentBuilderFactory = DocumentBuilderFactory.newInstance();

    //Create parser
    DocumentBuilder oDocumentBuilder = null;
    try {
        oDocumentBuilder = oDocumentBuilderFactory.newDocumentBuilder();
        //parse
        dRet = oDocumentBuilder.newDocument();

        Element eRoot = dRet.createElement("config");
        eRoot.appendChild(dRet.createElement(_root));
        dRet.appendChild(eRoot);
    } catch (ParserConfigurationException e) {
        _logger.error("Error reading configuration, parse error", e);
        throw new ConfigurationException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
    }
    return dRet;
}

From source file:com.centeractive.ws.builder.soap.XmlUtils.java

public static String createJdbcXmlResult(Statement statement)
        throws SQLException, ParserConfigurationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document xmlDocumentResult = builder.newDocument();
    Element resultsElement = xmlDocumentResult.createElement("Results");
    xmlDocumentResult.appendChild(resultsElement);

    if (statement != null) {
        ResultSet resultSet = statement.getResultSet();
        if (resultSet != null) {
            resultSet.setFetchSize(statement.getFetchSize());
            xmlDocumentResult = addResultSetXmlPart(resultsElement, resultSet, xmlDocumentResult);
            while (statement.getMoreResults()) {
                xmlDocumentResult = addResultSetXmlPart(resultsElement, statement.getResultSet(),
                        xmlDocumentResult);
            }/*from w  w w.  j  a va 2s .c  om*/
        } else {
            Element errorElement = xmlDocumentResult.createElement("UpdateCount");
            errorElement
                    .appendChild(xmlDocumentResult.createTextNode(String.valueOf(statement.getUpdateCount())));
            resultsElement.appendChild(errorElement);
        }
    }

    StringWriter out = new StringWriter();

    OutputFormat outputFormat = new OutputFormat(xmlDocumentResult);
    outputFormat.setOmitComments(true);
    outputFormat.setOmitDocumentType(true);
    outputFormat.setOmitXMLDeclaration(true);
    // outputFormat.setLineSeparator( "\n" );
    // add this line //
    // outputFormat.setPreserveSpace( true );
    outputFormat.setIndent(3);
    outputFormat.setIndenting(true);

    try {
        XMLSerializer serializer = new XMLSerializer(new PrintWriter(out), outputFormat);
        serializer.asDOMSerializer();
        serializer.serialize(xmlDocumentResult);
    } catch (IOException e) {
        throw new SoapBuilderException(e);
    }

    return out.toString();
}

From source file:com.mirth.connect.server.migration.Migrate3_0_0.java

private void migrateChannelTable() {
    PreparedStatement preparedStatement = null;
    ResultSet results = null;/*from  www  .ja v a2s .com*/

    try {
        /*
         * MIRTH-1667: Derby fails if autoCommit is set to true and there are a large number of
         * results. The following error occurs: "ERROR 40XD0: Container has been closed"
         */
        Connection connection = getConnection();
        connection.setAutoCommit(false);

        preparedStatement = connection.prepareStatement(
                "SELECT ID, NAME, DESCRIPTION, IS_ENABLED, VERSION, REVISION, LAST_MODIFIED, SOURCE_CONNECTOR, DESTINATION_CONNECTORS, PROPERTIES, PREPROCESSING_SCRIPT, POSTPROCESSING_SCRIPT, DEPLOY_SCRIPT, SHUTDOWN_SCRIPT FROM OLD_CHANNEL");
        results = preparedStatement.executeQuery();

        while (results.next()) {
            String channelId = "";

            try {
                channelId = results.getString(1);
                String name = results.getString(2);
                String description = results.getString(3);
                Boolean isEnabled = results.getBoolean(4);
                String version = results.getString(5);
                Integer revision = results.getInt(6);

                Calendar lastModified = Calendar.getInstance();
                lastModified.setTimeInMillis(results.getTimestamp(7).getTime());

                String sourceConnector = results.getString(8);
                String destinationConnectors = results.getString(9);
                String properties = results.getString(10);
                String preprocessingScript = results.getString(11);
                String postprocessingScript = results.getString(12);
                String deployScript = results.getString(13);
                String shutdownScript = results.getString(14);

                Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
                Element element = document.createElement("channel");
                document.appendChild(element);
                DonkeyElement channel = new DonkeyElement(element);

                channel.addChildElement("id", channelId);
                channel.addChildElement("name", name);
                channel.addChildElement("description", description);
                channel.addChildElement("enabled", Boolean.toString(isEnabled));
                channel.addChildElement("version", version);

                DonkeyElement lastModifiedElement = channel.addChildElement("lastModified");
                lastModifiedElement.addChildElement("time", String.valueOf(lastModified.getTimeInMillis()));
                lastModifiedElement.addChildElement("timezone", lastModified.getTimeZone().getDisplayName());

                channel.addChildElement("revision", String.valueOf(revision));

                channel.addChildElementFromXml(sourceConnector).setNodeName("sourceConnector");
                channel.addChildElementFromXml(destinationConnectors).setNodeName("destinationConnectors");
                channel.addChildElementFromXml(properties);

                channel.addChildElement("preprocessingScript", preprocessingScript);
                channel.addChildElement("postprocessingScript", postprocessingScript);
                channel.addChildElement("deployScript", deployScript);
                channel.addChildElement("shutdownScript", shutdownScript);

                String serializedChannel = channel.toXml();

                PreparedStatement updateStatement = null;

                try {
                    updateStatement = connection.prepareStatement(
                            "INSERT INTO CHANNEL (ID, NAME, REVISION, CHANNEL) VALUES (?, ?, ?, ?)");
                    updateStatement.setString(1, channelId);
                    updateStatement.setString(2, name);
                    updateStatement.setInt(3, revision);
                    updateStatement.setString(4, serializedChannel);
                    updateStatement.executeUpdate();
                    updateStatement.close();
                } finally {
                    DbUtils.closeQuietly(updateStatement);
                }
            } catch (Exception e) {
                logger.error("Error migrating channel " + channelId + ".", e);
            }
        }

        connection.commit();
    } catch (SQLException e) {
        logger.error("Error migrating channels.", e);
    } finally {
        DbUtils.closeQuietly(results);
        DbUtils.closeQuietly(preparedStatement);
    }
}

From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionMessageHandler.java

/**
 * Xpath performance degrades on large documents so this workaround was needed to improve performance. See link inline in the code.
 * // ww  w  .  j ava2 s.c  o  m
 * @param entityElement
 * @return
 * @throws ParserConfigurationException
 */
private Element createOrphanElement(Element entityElement) throws ParserConfigurationException {

    // this is necessary to avoid a performance bottleneck in the Xalan xpath engine
    // see http://stackoverflow.com/questions/6340802/java-xpath-apache-jaxp-implementation-performance

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document dummyDocument = db.newDocument();
    dummyDocument.appendChild(dummyDocument.importNode(entityElement, true));
    entityElement = dummyDocument.getDocumentElement();

    return entityElement;

}

From source file:com.photon.phresco.util.Utility.java

public static DOMSource createXML(String browsePath, String fileType) throws PhrescoException {
    try {/*from ww  w. ja  v a  2s  .  c  om*/
        File inputPath = new File(browsePath);
        if (!inputPath.isDirectory() || inputPath.isFile()) {
            return null;
        }
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.newDocument();
        Element rootElement = document.createElement("root");
        document.appendChild(rootElement);

        Element mainFolder = document.createElement("Item");
        mainFolder.setAttribute("name", inputPath.getName());
        mainFolder.setAttribute("path", inputPath.toString());
        mainFolder.setAttribute("type", "Folder");
        rootElement.appendChild(mainFolder);

        listDirectories(mainFolder, document, inputPath, fileType);

        DOMSource source = new DOMSource(document);
        return source;
    } catch (DOMException e) {
        throw new PhrescoException(e);
    } catch (ParserConfigurationException e) {
        throw new PhrescoException(e);
    }
}