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();
}
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);
}
}
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());
}
}
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 "";
}
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);
}
}
}
};
}
Aggregations