use of org.apache.axiom.om.OMOutputFormat in project wso2-synapse by wso2.
the class HttpCoreNIOSender method sendAsyncResponse.
/**
* Send the passed in response message, asynchronously
* @param msgContext the message context to be sent
* @throws AxisFault on error
*/
private void sendAsyncResponse(MessageContext msgContext) throws AxisFault {
int contentLength = extractContentLength(msgContext);
// remove unwanted HTTP headers (if any from the current message)
removeUnwantedHeaders(msgContext);
// Check whether original messageType value is changed. if not set the correct value to engage correct message formatter
String cType = (String) msgContext.getProperty(NhttpConstants.MC_CONTENT_TYPE);
String messageType = (String) msgContext.getProperty(NhttpConstants.MESSAGE_TYPE);
String oriMessageType = (String) msgContext.getProperty(NhttpConstants.ORIGINAL_MESSAGE_TYPE);
if (cType != null && cType.indexOf(HTTPConstants.MEDIA_TYPE_MULTIPART_RELATED) != -1 && messageType != null && messageType.equals(oriMessageType)) {
msgContext.setProperty(NhttpConstants.MESSAGE_TYPE, HTTPConstants.MEDIA_TYPE_MULTIPART_RELATED);
}
Map transportHeaders = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);
ServerWorker worker = (ServerWorker) msgContext.getProperty(Constants.OUT_TRANSPORT_INFO);
NHttpServerConnection conn = worker.getConn();
if (null == conn.getHttpRequest()) {
// this is a special case we dropped the connection when message size exceeds the user defined threshold
if (conn.getContext().getAttribute(NhttpConstants.CONNECTION_DROPPED) != null && (Boolean) conn.getContext().getAttribute(NhttpConstants.CONNECTION_DROPPED)) {
// already submitted response for this case, hence return
return;
}
}
HttpResponse response = worker.getResponse();
OMOutputFormat format = NhttpUtil.getOMOutputFormat(msgContext);
MessageFormatter messageFormatter = MessageFormatterDecoratorFactory.createMessageFormatterDecorator(msgContext);
Boolean noEntityBody = (Boolean) msgContext.getProperty(NhttpConstants.NO_ENTITY_BODY);
if (noEntityBody == null || Boolean.FALSE == noEntityBody) {
response.setHeader(HTTP.CONTENT_TYPE, messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction()));
} else if (Boolean.TRUE == noEntityBody) {
((BasicHttpEntity) response.getEntity()).setChunked(false);
((BasicHttpEntity) response.getEntity()).setContentLength(0);
// as synapse cannot calculate content length without providing message body.
if (transportHeaders.get(NhttpConstants.HTTP_REQUEST_METHOD) != null && NhttpConstants.HTTP_HEAD.equals(transportHeaders.get(NhttpConstants.HTTP_REQUEST_METHOD)) && transportHeaders.get(NhttpConstants.ORIGINAL_CONTENT_LEN) != null) {
((BasicHttpEntity) response.getEntity()).setContentLength(Long.parseLong(String.valueOf(transportHeaders.get(NhttpConstants.ORIGINAL_CONTENT_LEN))));
transportHeaders.remove(NhttpConstants.ORIGINAL_CONTENT_LEN);
transportHeaders.remove(NhttpConstants.HTTP_REQUEST_METHOD);
}
}
response.setStatusCode(determineHttpStatusCode(msgContext, response));
// Override the Standard Reason Phrase
if (msgContext.getProperty(NhttpConstants.HTTP_REASON_PHRASE) != null && !msgContext.getProperty(NhttpConstants.HTTP_REASON_PHRASE).equals("")) {
response.setReasonPhrase(msgContext.getProperty(NhttpConstants.HTTP_REASON_PHRASE).toString());
}
// set any transport headers
if (transportHeaders != null && !transportHeaders.values().isEmpty()) {
Iterator iter = transportHeaders.keySet().iterator();
while (iter.hasNext()) {
Object header = iter.next();
Object value = transportHeaders.get(header);
if (value != null && header instanceof String && value instanceof String) {
response.addHeader((String) header, (String) value);
String excessProp = NhttpConstants.EXCESS_TRANSPORT_HEADERS;
Map map = (Map) msgContext.getProperty(excessProp);
if (map != null && map.get(header) != null) {
log.debug("Number of excess values for " + header + " header is : " + ((Collection) (map.get(header))).size());
for (Iterator iterator = map.keySet().iterator(); iterator.hasNext(); ) {
String key = (String) iterator.next();
for (String excessVal : (Collection<String>) map.get(key)) {
if (header.equals(key)) {
response.addHeader((String) header, (String) excessVal);
}
}
}
}
}
}
}
boolean forceContentLength = msgContext.isPropertyTrue(NhttpConstants.FORCE_HTTP_CONTENT_LENGTH);
boolean forceContentLengthCopy = msgContext.isPropertyTrue(NhttpConstants.COPY_CONTENT_LENGTH_FROM_INCOMING);
BasicHttpEntity entity = (BasicHttpEntity) response.getEntity();
MetricsCollector lstMetrics = worker.getServiceHandler().getMetrics();
try {
if (forceContentLength) {
entity.setChunked(false);
if (forceContentLengthCopy && contentLength > 0) {
entity.setContentLength(contentLength);
} else {
setStreamAsTempData(entity, messageFormatter, msgContext, format);
}
}
worker.getServiceHandler().commitResponse(worker.getConn(), response);
lstMetrics.reportResponseCode(response.getStatusLine().getStatusCode());
OutputStream out = worker.getOutputStream();
/*
* if this is a dummy message to handle http 202 case with non-blocking IO
* write an empty byte array as body
*/
if (msgContext.isPropertyTrue(NhttpConstants.SC_ACCEPTED) || Boolean.TRUE == noEntityBody) {
out.write(new byte[0]);
} else {
if (forceContentLength) {
if (forceContentLengthCopy && contentLength > 0) {
messageFormatter.writeTo(msgContext, format, out, false);
} else {
writeMessageFromTempData(out, msgContext);
}
} else {
messageFormatter.writeTo(msgContext, format, out, false);
}
}
out.close();
if (lstMetrics != null) {
lstMetrics.incrementMessagesSent();
}
} catch (ProtocolException e) {
log.error(e + " (Synapse may be trying to send an exact response more than once )");
} catch (HttpException e) {
if (lstMetrics != null) {
lstMetrics.incrementFaultsSending();
}
handleException("Unexpected HTTP protocol error sending response to : " + worker.getRemoteAddress(), e);
} catch (ConnectionClosedException e) {
if (lstMetrics != null) {
lstMetrics.incrementFaultsSending();
}
log.warn("Connection closed by client : " + worker.getRemoteAddress());
} catch (IllegalStateException e) {
if (lstMetrics != null) {
lstMetrics.incrementFaultsSending();
}
log.warn("Connection closed by client : " + worker.getRemoteAddress());
} catch (IOException e) {
if (lstMetrics != null) {
lstMetrics.incrementFaultsSending();
}
handleException("IO Error sending response message to : " + worker.getRemoteAddress(), e);
} catch (Exception e) {
if (lstMetrics != null) {
lstMetrics.incrementFaultsSending();
}
handleException("General Error sending response message to : " + worker.getRemoteAddress(), e);
}
InputStream is = worker.getIs();
if (is != null) {
try {
is.close();
} catch (IOException ignore) {
}
}
}
use of org.apache.axiom.om.OMOutputFormat in project wso2-synapse by wso2.
the class SourceResponse method calculateContentlengthForChunckDisabledResponse.
/**
* Calculates the content-length when chunking is disabled.
* @param responseMsgContext outflow message context
* @throws IOException
*/
private void calculateContentlengthForChunckDisabledResponse(MessageContext responseMsgContext) throws IOException {
String forceHttp10 = (String) responseMsgContext.getProperty(PassThroughConstants.FORCE_HTTP_1_0);
boolean isChunkingDisabled = responseMsgContext.isPropertyTrue(PassThroughConstants.DISABLE_CHUNKING, false);
if ("true".equals(forceHttp10) || isChunkingDisabled) {
if (!responseMsgContext.isPropertyTrue(PassThroughConstants.MESSAGE_BUILDER_INVOKED, false)) {
try {
RelayUtils.buildMessage(responseMsgContext, false);
responseMsgContext.getEnvelope().buildWithAttachments();
} catch (Exception e) {
throw new AxisFault(e.getMessage());
}
}
if ("true".equals(forceHttp10)) {
version = HttpVersion.HTTP_1_0;
versionChangeRequired = true;
}
Boolean noEntityBody = (Boolean) responseMsgContext.getProperty(PassThroughConstants.NO_ENTITY_BODY);
if (noEntityBody != null && Boolean.TRUE == noEntityBody) {
headers.remove(HTTP.CONTENT_TYPE);
return;
}
String contentType = headers.get(HTTP.CONTENT_TYPE) != null ? headers.get(HTTP.CONTENT_TYPE).toString() : null;
// Stream should be preserved to support disable chunking for SOAP based responses. This checks
// whether chunking is disabled and response Content-Type is SOAP or FORCE_HTTP_1.0 is true.
boolean preserveStream = (isChunkingDisabled && isSOAPContentType(contentType)) || "true".equals(forceHttp10);
MessageFormatter formatter = MessageProcessorSelector.getMessageFormatter(responseMsgContext);
OMOutputFormat format = PassThroughTransportUtils.getOMOutputFormat(responseMsgContext);
ByteArrayOutputStream out = new ByteArrayOutputStream();
formatter.writeTo(responseMsgContext, format, out, preserveStream);
TreeSet<String> header = new TreeSet<String>();
header.add(String.valueOf(out.toByteArray().length));
headers.put(HTTP.CONTENT_LEN, header);
}
}
use of org.apache.axiom.om.OMOutputFormat in project wso2-synapse by wso2.
the class JsonDataSourceTest method testSerializeStringWriterXml.
public void testSerializeStringWriterXml() throws FileNotFoundException, XMLStreamException {
JsonDataSource jsonDataSource = createJsonDatasource();
Writer stringWriter = new StringWriter();
OMOutputFormat outputFormat = new OMOutputFormat();
outputFormat.setContentType("text/xml");
jsonDataSource.serialize(stringWriter, outputFormat);
assertEquals("Invalid serialization", expectedXML, stringWriter.toString());
}
use of org.apache.axiom.om.OMOutputFormat in project wso2-synapse by wso2.
the class FIXMessageFromatterTest method testWriteTo.
public void testWriteTo() {
String input = "8=FIX.4.0\u00019=105\u000135=D\u000134=2\u000149=BANZAI\u000152=20080711-06:42:26\u000156=SYNAPSE\u0001" + "11=1215758546278\u000121=1\u000138=90000000\u000140=1\u000154=1\u000155=DEL\u000159=0\u000110=121\u0001";
MessageContext msgCtx = new MessageContext();
FIXMessageBuilder builder = new FIXMessageBuilder();
OMElement element = null;
try {
element = builder.processDocument(new ByteArrayInputStream(input.getBytes()), "fix/j", msgCtx);
Assert.assertNotNull(element);
// System.out.println(element);
} catch (AxisFault e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FIXMessageFromatter fixMessageFromatter = new FIXMessageFromatter();
// msgCtx = new MessageContext();
// msgCtx.seten
OutputStream output = new ByteArrayOutputStream();
SOAPFactory factory = OMAbstractFactory.getSOAP12Factory();
SOAPEnvelope env = factory.getDefaultEnvelope();
env.getBody().addChild(element);
try {
msgCtx.setEnvelope(env);
} catch (AxisFault e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
OMOutputFormat myOutputFormat = new OMOutputFormat();
try {
fixMessageFromatter.writeTo(msgCtx, myOutputFormat, output, false);
assertTrue(output.toString().length() > 0);
} catch (AxisFault e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Aggregations