Search in sources :

Example 21 with StreamResult

use of javax.xml.transform.stream.StreamResult in project OpenAM by OpenRock.

the class MarshallerImpl method marshal.

public void marshal(Object obj, Result result) throws JAXBException {
    //XMLSerializable so = Util.toXMLSerializable(obj);
    XMLSerializable so = context.getGrammarInfo().castToXMLSerializable(obj);
    if (so == null)
        throw new MarshalException(Messages.format(Messages.NOT_MARSHALLABLE));
    if (result instanceof SAXResult) {
        write(so, ((SAXResult) result).getHandler());
        return;
    }
    if (result instanceof DOMResult) {
        Node node = ((DOMResult) result).getNode();
        if (node == null) {
            try {
                DocumentBuilder db = XMLUtils.getSafeDocumentBuilder(false);
                Document doc = db.newDocument();
                ((DOMResult) result).setNode(doc);
                write(so, new SAX2DOMEx(doc));
            } catch (ParserConfigurationException pce) {
                throw new JAXBAssertionError(pce);
            }
        } else {
            write(so, new SAX2DOMEx(node));
        }
        return;
    }
    if (result instanceof StreamResult) {
        StreamResult sr = (StreamResult) result;
        XMLWriter w = null;
        if (sr.getWriter() != null)
            w = createWriter(sr.getWriter());
        else if (sr.getOutputStream() != null)
            w = createWriter(sr.getOutputStream());
        else if (sr.getSystemId() != null) {
            String fileURL = sr.getSystemId();
            if (fileURL.startsWith("file:///")) {
                if (fileURL.substring(8).indexOf(":") > 0)
                    fileURL = fileURL.substring(8);
                else
                    fileURL = fileURL.substring(7);
            }
            try {
                w = createWriter(new FileOutputStream(fileURL));
            } catch (IOException e) {
                throw new MarshalException(e);
            }
        }
        if (w == null)
            throw new IllegalArgumentException();
        write(so, w);
        return;
    }
    // unsupported parameter type
    throw new MarshalException(Messages.format(Messages.UNSUPPORTED_RESULT));
}
Also used : MarshalException(javax.xml.bind.MarshalException) DOMResult(javax.xml.transform.dom.DOMResult) StreamResult(javax.xml.transform.stream.StreamResult) Node(org.w3c.dom.Node) IOException(java.io.IOException) Document(org.w3c.dom.Document) XMLWriter(com.sun.xml.bind.marshaller.XMLWriter) SAXResult(javax.xml.transform.sax.SAXResult) JAXBAssertionError(com.sun.xml.bind.JAXBAssertionError) DocumentBuilder(javax.xml.parsers.DocumentBuilder) FileOutputStream(java.io.FileOutputStream) SAX2DOMEx(com.sun.xml.bind.marshaller.SAX2DOMEx) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 22 with StreamResult

use of javax.xml.transform.stream.StreamResult in project opennms by OpenNMS.

the class XmlSystemReportFormatter method write.

@Override
public void write(final SystemReportPlugin plugin) {
    if (!hasDisplayable(plugin))
        return;
    if (m_handler == null) {
        try {
            StreamResult streamResult = new StreamResult(getOutputStream());
            SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
            m_handler = tf.newTransformerHandler();
            Transformer serializer = m_handler.getTransformer();
            serializer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "entry");
            m_handler.setResult(streamResult);
        } catch (final Exception e) {
            LOG.error("Unable to create XML stream writer.", e);
            m_handler = null;
        }
        try {
            m_handler.startDocument();
            m_handler.startElement("", "", "systemReportPlugins", null);
        } catch (final Exception e) {
            LOG.warn("Unable to start document.", e);
            m_handler = null;
        }
    }
    if (m_handler == null) {
        LOG.warn("Unable to write, no handler defined!");
        return;
    }
    try {
        AttributesImpl atts = new AttributesImpl();
        atts.addAttribute("", "", "name", "CDATA", plugin.getName());
        atts.addAttribute("", "", "description", "CDATA", plugin.getDescription());
        m_handler.startElement("", "", "plugin", atts);
        for (final Map.Entry<String, Resource> entry : plugin.getEntries().entrySet()) {
            final boolean displayable = isDisplayable(entry.getValue());
            atts = new AttributesImpl();
            atts.addAttribute("", "", "key", "CDATA", entry.getKey());
            if (!displayable) {
                atts.addAttribute("", "", "skipped", "CDATA", "true");
            }
            m_handler.startElement("", "", "entry", atts);
            if (displayable) {
                final String value = getResourceText(entry.getValue());
                if (value != null) {
                    m_handler.startCDATA();
                    m_handler.characters(value.toCharArray(), 0, value.length());
                    m_handler.endCDATA();
                }
            }
            m_handler.endElement("", "", "entry");
        }
        m_handler.endElement("", "", "plugin");
    } catch (final Exception e) {
        LOG.warn("An error occurred while attempting to write XML data.", e);
    }
}
Also used : Transformer(javax.xml.transform.Transformer) AttributesImpl(org.xml.sax.helpers.AttributesImpl) StreamResult(javax.xml.transform.stream.StreamResult) SAXTransformerFactory(javax.xml.transform.sax.SAXTransformerFactory) Resource(org.springframework.core.io.Resource) Map(java.util.Map)

Example 23 with StreamResult

use of javax.xml.transform.stream.StreamResult in project opennms by OpenNMS.

the class QuickBaseAPITest method XXXtestCreateLead.

public void XXXtestCreateLead() {
    PrintWriter out = null;
    try {
        out = new PrintWriter(System.out);
        out.println("Welcome to QuickBase\n");
        QuickBaseClient qdb = createClient();
        qdb.findDbByName("TPMG Support");
        HashMap tables = (HashMap) qdb.grantedDBs(false, false, true);
        if (tables == null) {
            out.println("No tables belong to this user.");
        }
        Set tableNames = tables.keySet();
        String tableName = "";
        String tableDbid = "";
        for (Iterator it = tableNames.iterator(); it.hasNext(); ) {
            tableName = (String) it.next();
            tableDbid = (String) tables.get(tableName);
            out.println("Name: " + tableName + " DBID: " + tableDbid);
            Document schema = qdb.getSchema(tableDbid);
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.transform(new DOMSource(schema), new StreamResult(out));
            NodeList fields = schema.getElementsByTagName("field");
            out.println("The QuickBase application " + tableName + " has " + fields.getLength() + " fields.");
            out.println("The fields are listed below.");
            for (int i = 0; i < fields.getLength(); i++) {
                out.println("Field ID: " + fields.item(i).getAttributes().getNamedItem("id").getNodeValue());
                out.println("Field Type: " + fields.item(i).getAttributes().getNamedItem("type").getNodeValue());
                out.println("Field Label: " + fields.item(i).getChildNodes().item(0).getNodeValue());
            }
        }
    } catch (QuickBaseException qdbe) {
        System.err.println("Exception in main " + qdbe.toString() + " error code: " + qdbe.getErrorCode());
        qdbe.printStackTrace();
    } catch (Throwable e) {
        System.err.println("Exception in main " + e.toString());
        e.printStackTrace();
    } finally {
        if (null != out) {
            out.flush();
            out.close();
        }
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) Set(java.util.Set) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) HashMap(java.util.HashMap) NodeList(org.w3c.dom.NodeList) QuickBaseException(com.intuit.quickbase.util.QuickBaseException) QuickBaseClient(com.intuit.quickbase.util.QuickBaseClient) Document(org.w3c.dom.Document) Iterator(java.util.Iterator) PrintWriter(java.io.PrintWriter)

Example 24 with StreamResult

use of javax.xml.transform.stream.StreamResult in project tdi-studio-se by Talend.

the class FeaturesModel method internalGetContent.

private InputStream internalGetContent() throws Exception {
    Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    Element features = document.createElement("features");
    features.setAttribute("xmlns", "http://karaf.apache.org/xmlns/features/v1.0.0");
    features.setAttribute("name", getArtifactId());
    document.appendChild(features);
    Element feature = document.createElement("feature");
    feature.setAttribute("name", getArtifactId());
    feature.setAttribute("version", getVersion());
    features.appendChild(feature);
    // add sub features
    for (FeatureModel fm : subFeatures) {
        Element subFeature = document.createElement("feature");
        if (null != fm.getVersion() && !fm.getVersion().isEmpty()) {
            subFeature.setAttribute("version", fm.getVersion());
        }
        subFeature.appendChild(document.createTextNode(fm.getArtifactId()));
        feature.appendChild(subFeature);
    }
    // add sub bundles
    for (BundleModel bm : subBundles) {
        Element bundle = document.createElement("bundle");
        bundle.appendChild(document.createTextNode(toBundleString(bm)));
        feature.appendChild(bundle);
    }
    if (null == contexts || contexts.isEmpty()) {
        // add config
        Element config = document.createElement("config");
        config.setAttribute("name", configName);
        StringBuilder sb = new StringBuilder("talendcontext=\"");
        for (int i = 0; i < contextList.length; i++) {
            if (i != 0) {
                sb.append(',');
            }
            sb.append(contextList[i]);
        }
        sb.append('"');
        config.appendChild(document.createTextNode(sb.toString()));
        feature.appendChild(config);
    } else {
        // add contexts config
        for (Map.Entry<String, Map<String, String>> context : contexts.entrySet()) {
            Element config = document.createElement("config");
            config.setAttribute("name", name + ".talendcontext." + context.getKey());
            StringBuilder sb = new StringBuilder("\n");
            for (Map.Entry<String, String> property : context.getValue().entrySet()) {
                sb.append(property.getKey());
                sb.append('=');
                sb.append(property.getValue());
                sb.append('\n');
            }
            config.appendChild(document.createTextNode(sb.toString()));
            feature.appendChild(config);
        }
    }
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    transformer.transform(new DOMSource(document), new StreamResult(os));
    return new ByteArrayInputStream(os.toByteArray());
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) Element(org.w3c.dom.Element) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(org.w3c.dom.Document) ByteArrayInputStream(java.io.ByteArrayInputStream) HashMap(java.util.HashMap) Map(java.util.Map)

Example 25 with StreamResult

use of javax.xml.transform.stream.StreamResult in project voltdb by VoltDB.

the class JDBCSQLXML method init.

/**
     * Initializes this object's SQLXML value from the given Source
     * object. <p>
     *
     * @param source the Source representing the SQLXML value
     * @throws SQLException if the argument does not represent a
     *      valid SQLXML value
     */
protected void init(Source source) throws SQLException {
    if (source == null) {
        throw Util.nullArgument("source");
    }
    Transformer transformer = JDBCSQLXML.getIdentityTransformer();
    StreamResult result = new StreamResult();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gzos;
    try {
        gzos = new GZIPOutputStream(baos);
    } catch (IOException ex) {
        throw Exceptions.transformFailed(ex);
    }
    result.setOutputStream(gzos);
    try {
        transformer.transform(source, result);
    } catch (TransformerException ex) {
        throw Exceptions.transformFailed(ex);
    }
    try {
        gzos.close();
    } catch (IOException ex) {
        throw Exceptions.transformFailed(ex);
    }
    byte[] data = baos.toByteArray();
    setGZipData(data);
    setReadable(true);
    setWritable(false);
}
Also used : Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) GZIPOutputStream(java.util.zip.GZIPOutputStream) ClosableByteArrayOutputStream(org.hsqldb_voltpatches.lib.ClosableByteArrayOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) TransformerException(javax.xml.transform.TransformerException)

Aggregations

StreamResult (javax.xml.transform.stream.StreamResult)1328 DOMSource (javax.xml.transform.dom.DOMSource)881 Transformer (javax.xml.transform.Transformer)775 StringWriter (java.io.StringWriter)447 TransformerFactory (javax.xml.transform.TransformerFactory)445 Document (org.w3c.dom.Document)415 TransformerException (javax.xml.transform.TransformerException)366 ByteArrayOutputStream (java.io.ByteArrayOutputStream)337 DocumentBuilder (javax.xml.parsers.DocumentBuilder)332 ByteArrayInputStream (java.io.ByteArrayInputStream)288 IOException (java.io.IOException)266 InputStream (java.io.InputStream)249 Test (org.junit.Test)246 StreamSource (javax.xml.transform.stream.StreamSource)213 XMLStreamReader (javax.xml.stream.XMLStreamReader)185 Source (javax.xml.transform.Source)183 File (java.io.File)175 Element (org.w3c.dom.Element)157 InboundXMLSec (org.apache.xml.security.stax.ext.InboundXMLSec)149 XMLSecurityProperties (org.apache.xml.security.stax.ext.XMLSecurityProperties)149