Search in sources :

Example 61 with DOMSource

use of javax.xml.transform.dom.DOMSource in project camel by apache.

the class XmlJsonDataFormatTest method testMarshalXMLSources.

@Test
public void testMarshalXMLSources() throws Exception {
    InputStream inStream = getClass().getResourceAsStream("testMessage1.xml");
    DOMSource inDOM = context.getTypeConverter().convertTo(DOMSource.class, inStream);
    inStream = getClass().getResourceAsStream("testMessage1.xml");
    SAXSource inSAX = context.getTypeConverter().convertTo(SAXSource.class, inStream);
    inStream = getClass().getResourceAsStream("testMessage1.xml");
    Document inDocument = context.getTypeConverter().convertTo(Document.class, inStream);
    // save the expected body of the message to set it later
    Object expectedBody = template.requestBody("direct:marshal", inDOM);
    MockEndpoint mockJSON = getMockEndpoint("mock:json");
    // reset the mock endpoint to get rid of the previous message
    mockJSON.reset();
    // all three messages should arrive, should be of type byte[] and
    // identical to one another
    mockJSON.expectedMessageCount(3);
    mockJSON.allMessages().body().isInstanceOf(byte[].class);
    mockJSON.expectedBodiesReceived(Arrays.asList(expectedBody, expectedBody, expectedBody));
    // start bombarding the route
    Object json = template.requestBody("direct:marshal", inDOM);
    String jsonString = context.getTypeConverter().convertTo(String.class, json);
    JSONObject obj = (JSONObject) JSONSerializer.toJSON(jsonString);
    assertEquals("JSONObject doesn't contain 7 keys", 7, obj.entrySet().size());
    template.requestBody("direct:marshal", inSAX);
    template.requestBody("direct:marshal", inDocument);
    mockJSON.assertIsSatisfied();
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) SAXSource(javax.xml.transform.sax.SAXSource) JSONObject(net.sf.json.JSONObject) MockEndpoint(org.apache.camel.component.mock.MockEndpoint) InputStream(java.io.InputStream) JSONObject(net.sf.json.JSONObject) Document(org.w3c.dom.Document) Test(org.junit.Test)

Example 62 with DOMSource

use of javax.xml.transform.dom.DOMSource in project camel by apache.

the class DefaultRestletBinding method populateRestletResponseFromExchange.

public void populateRestletResponseFromExchange(Exchange exchange, Response response) throws Exception {
    Message out;
    if (exchange.isFailed()) {
        // 500 for internal server error which can be overridden by response code in header
        response.setStatus(Status.valueOf(500));
        Message msg = exchange.hasOut() ? exchange.getOut() : exchange.getIn();
        if (msg.isFault()) {
            out = msg;
        } else {
            // print exception as message and stacktrace
            Exception t = exchange.getException();
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            t.printStackTrace(pw);
            response.setEntity(sw.toString(), MediaType.TEXT_PLAIN);
            return;
        }
    } else {
        out = exchange.hasOut() ? exchange.getOut() : exchange.getIn();
    }
    // get content type
    MediaType mediaType = out.getHeader(Exchange.CONTENT_TYPE, MediaType.class);
    if (mediaType == null) {
        Object body = out.getBody();
        mediaType = MediaType.TEXT_PLAIN;
        if (body instanceof String) {
            mediaType = MediaType.TEXT_PLAIN;
        } else if (body instanceof StringSource || body instanceof DOMSource) {
            mediaType = MediaType.TEXT_XML;
        }
    }
    // get response code
    Integer responseCode = out.getHeader(Exchange.HTTP_RESPONSE_CODE, Integer.class);
    if (responseCode != null) {
        response.setStatus(Status.valueOf(responseCode));
    }
    // set response body according to the message body
    Object body = out.getBody();
    if (body instanceof WrappedFile) {
        // grab body from generic file holder
        GenericFile<?> gf = (GenericFile<?>) body;
        body = gf.getBody();
    }
    if (body == null) {
        // empty response
        response.setEntity("", MediaType.TEXT_PLAIN);
    } else if (body instanceof Response) {
        // its already a restlet response, so dont do anything
        LOG.debug("Using existing Restlet Response from exchange body: {}", body);
    } else if (body instanceof Representation) {
        response.setEntity(out.getBody(Representation.class));
    } else if (body instanceof InputStream) {
        response.setEntity(new InputRepresentation(out.getBody(InputStream.class), mediaType));
    } else if (body instanceof File) {
        response.setEntity(new FileRepresentation(out.getBody(File.class), mediaType));
    } else if (body instanceof byte[]) {
        byte[] bytes = out.getBody(byte[].class);
        response.setEntity(new ByteArrayRepresentation(bytes, mediaType, bytes.length));
    } else {
        // fallback and use string
        String text = out.getBody(String.class);
        response.setEntity(text, mediaType);
    }
    LOG.debug("Populate Restlet response from exchange body: {}", body);
    if (exchange.getProperty(Exchange.CHARSET_NAME) != null) {
        CharacterSet cs = CharacterSet.valueOf(exchange.getProperty(Exchange.CHARSET_NAME, String.class));
        response.getEntity().setCharacterSet(cs);
    }
    // set headers at the end, as the entity must be set first
    // NOTE: setting HTTP headers on restlet is cumbersome and its API is "weird" and has some flaws
    // so we need to headers two times, and the 2nd time we add the non-internal headers once more
    Series<Header> series = new Series<Header>(Header.class);
    for (Map.Entry<String, Object> entry : out.getHeaders().entrySet()) {
        String key = entry.getKey();
        Object value = entry.getValue();
        if (!headerFilterStrategy.applyFilterToCamelHeaders(key, value, exchange)) {
            boolean added = setResponseHeader(exchange, response, key, value);
            if (!added) {
                // we only want non internal headers
                if (!key.startsWith("Camel") && !key.startsWith("org.restlet")) {
                    String text = exchange.getContext().getTypeConverter().tryConvertTo(String.class, exchange, value);
                    if (text != null) {
                        series.add(key, text);
                    }
                }
            }
        }
    }
    // set HTTP headers so we return these in the response
    if (!series.isEmpty()) {
        response.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, series);
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) Message(org.apache.camel.Message) StringWriter(java.io.StringWriter) WrappedFile(org.apache.camel.WrappedFile) MediaType(org.restlet.data.MediaType) CharacterSet(org.restlet.data.CharacterSet) PrintWriter(java.io.PrintWriter) InputRepresentation(org.restlet.representation.InputRepresentation) InputStream(java.io.InputStream) EmptyRepresentation(org.restlet.representation.EmptyRepresentation) StringRepresentation(org.restlet.representation.StringRepresentation) InputRepresentation(org.restlet.representation.InputRepresentation) ByteArrayRepresentation(org.restlet.representation.ByteArrayRepresentation) FileRepresentation(org.restlet.representation.FileRepresentation) StreamRepresentation(org.restlet.representation.StreamRepresentation) Representation(org.restlet.representation.Representation) DecodeRepresentation(org.restlet.engine.application.DecodeRepresentation) ParseException(java.text.ParseException) RuntimeCamelException(org.apache.camel.RuntimeCamelException) ChallengeResponse(org.restlet.data.ChallengeResponse) Response(org.restlet.Response) Series(org.restlet.util.Series) Header(org.restlet.data.Header) FileRepresentation(org.restlet.representation.FileRepresentation) ByteArrayRepresentation(org.restlet.representation.ByteArrayRepresentation) StringSource(org.apache.camel.StringSource) WrappedFile(org.apache.camel.WrappedFile) GenericFile(org.apache.camel.component.file.GenericFile) File(java.io.File) Map(java.util.Map) GenericFile(org.apache.camel.component.file.GenericFile)

Example 63 with DOMSource

use of javax.xml.transform.dom.DOMSource in project liquibase by liquibase.

the class DefaultXmlWriter method write.

@Override
public void write(Document doc, OutputStream outputStream) throws IOException {
    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        try {
            factory.setAttribute("indent-number", 4);
        } catch (Exception e) {
            //guess we can't set it, that's ok
            ;
        }
        Transformer transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, LiquibaseConfiguration.getInstance().getConfiguration(GlobalConfiguration.class).getOutputEncoding());
        //need to nest outputStreamWriter to get around JDK 5 bug.  See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6296446
        OutputStreamWriter writer = new OutputStreamWriter(outputStream, LiquibaseConfiguration.getInstance().getConfiguration(GlobalConfiguration.class).getOutputEncoding());
        transformer.transform(new DOMSource(doc), new StreamResult(writer));
        writer.flush();
        writer.close();
    } catch (TransformerException e) {
        throw new IOException(e.getMessage());
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) OutputStreamWriter(java.io.OutputStreamWriter) IOException(java.io.IOException) TransformerException(javax.xml.transform.TransformerException) IOException(java.io.IOException) TransformerException(javax.xml.transform.TransformerException)

Example 64 with DOMSource

use of javax.xml.transform.dom.DOMSource in project CoreNLP by stanfordnlp.

the class Ssurgeon method writeToString.

public static String writeToString(SsurgeonPattern pattern) {
    try {
        List<SsurgeonPattern> patterns = new LinkedList<>();
        patterns.add(pattern);
        Document domDoc = createPatternXMLDoc(patterns);
        if (domDoc != null) {
            Transformer tformer = TransformerFactory.newInstance().newTransformer();
            tformer.setOutputProperty(OutputKeys.INDENT, "yes");
            StringWriter sw = new StringWriter();
            tformer.transform(new DOMSource(domDoc), new StreamResult(sw));
            return sw.toString();
        } else {
            log.warning("Was not able to create XML document for pattern list.");
        }
    } catch (Exception e) {
        log.info("Error in writeToString, could not process pattern=" + pattern);
        log.info(e);
        return null;
    }
    return "";
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) Document(org.w3c.dom.Document)

Example 65 with DOMSource

use of javax.xml.transform.dom.DOMSource in project bazel by bazelbuild.

the class XmlOutputFormatter method createPostFactoStreamCallback.

@Override
public OutputFormatterCallback<Target> createPostFactoStreamCallback(final OutputStream out, final QueryOptions options) {
    return new OutputFormatterCallback<Target>() {

        private Document doc;

        private Element queryElem;

        @Override
        public void start() {
            try {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                doc = factory.newDocumentBuilder().newDocument();
            } catch (ParserConfigurationException e) {
                // This shouldn't be possible: all the configuration is hard-coded.
                throw new IllegalStateException("XML output failed", e);
            }
            doc.setXmlVersion("1.1");
            queryElem = doc.createElement("query");
            queryElem.setAttribute("version", "2");
            doc.appendChild(queryElem);
        }

        @Override
        public void processOutput(Iterable<Target> partialResult) throws IOException, InterruptedException {
            for (Target target : partialResult) {
                queryElem.appendChild(createTargetElement(doc, target));
            }
        }

        @Override
        public void close(boolean failFast) throws IOException {
            if (!failFast) {
                try {
                    Transformer transformer = TransformerFactory.newInstance().newTransformer();
                    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                    transformer.transform(new DOMSource(doc), new StreamResult(out));
                } catch (TransformerFactoryConfigurationError | TransformerException e) {
                    // This shouldn't be possible: all the configuration is hard-coded.
                    throw new IllegalStateException("XML output failed", e);
                }
            }
        }
    };
}
Also used : TransformerFactoryConfigurationError(javax.xml.transform.TransformerFactoryConfigurationError) DOMSource(javax.xml.transform.dom.DOMSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) Element(org.w3c.dom.Element) SynchronizedDelegatingOutputFormatterCallback(com.google.devtools.build.lib.query2.engine.SynchronizedDelegatingOutputFormatterCallback) ThreadSafeOutputFormatterCallback(com.google.devtools.build.lib.query2.engine.ThreadSafeOutputFormatterCallback) OutputFormatterCallback(com.google.devtools.build.lib.query2.engine.OutputFormatterCallback) Document(org.w3c.dom.Document) FakeSubincludeTarget(com.google.devtools.build.lib.query2.FakeSubincludeTarget) Target(com.google.devtools.build.lib.packages.Target) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) TransformerException(javax.xml.transform.TransformerException)

Aggregations

DOMSource (javax.xml.transform.dom.DOMSource)392 StreamResult (javax.xml.transform.stream.StreamResult)231 Transformer (javax.xml.transform.Transformer)204 Document (org.w3c.dom.Document)161 TransformerFactory (javax.xml.transform.TransformerFactory)112 TransformerException (javax.xml.transform.TransformerException)107 DocumentBuilder (javax.xml.parsers.DocumentBuilder)102 StringWriter (java.io.StringWriter)97 IOException (java.io.IOException)93 Element (org.w3c.dom.Element)81 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)77 Source (javax.xml.transform.Source)67 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)62 SAXException (org.xml.sax.SAXException)56 File (java.io.File)55 InputSource (org.xml.sax.InputSource)50 StreamSource (javax.xml.transform.stream.StreamSource)47 Node (org.w3c.dom.Node)45 InputStream (java.io.InputStream)35 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)35