use of org.apache.axiom.soap.impl.dom.soap11.SOAP11Factory in project wso2-synapse by wso2.
the class ClientHandler method responseReceived.
/**
* Process a response received for the request sent out
*
* @param conn the connection being processed
*/
public void responseReceived(final NHttpClientConnection conn) {
setServerContextAttribute(NhttpConstants.RES_FROM_BACKEND_READ_START_TIME, System.currentTimeMillis(), conn);
HttpContext context = conn.getContext();
// set the current message size to zero
if (isMessageSizeValidationEnabled) {
context.setAttribute(NhttpConstants.MESSAGE_SIZE_VALIDATION_SUM, 0);
}
HttpResponse response = conn.getHttpResponse();
ProxyTunnelHandler tunnelHandler = (ProxyTunnelHandler) context.getAttribute(TUNNEL_HANDLER);
if (tunnelHandler != null && !tunnelHandler.isCompleted()) {
context.removeAttribute(TUNNEL_HANDLER);
tunnelHandler.handleResponse(response, conn);
if (tunnelHandler.isSuccessful()) {
log.debug(conn + ": Tunnel established");
conn.resetInput();
conn.requestOutput();
return;
} else {
Axis2HttpRequest axis2Req = (Axis2HttpRequest) context.getAttribute(ATTACHMENT_KEY);
context.setAttribute(AXIS2_HTTP_REQUEST, axis2Req);
context.setAttribute(OUTGOING_MESSAGE_CONTEXT, axis2Req.getMsgContext());
ContentOutputBuffer outputBuffer = new NhttpSharedOutputBuffer(bufferSize, conn, allocator, socketTimeout);
axis2Req.setOutputBuffer(outputBuffer);
context.setAttribute(REQUEST_SOURCE_BUFFER, outputBuffer);
context.setAttribute(NhttpConstants.DISCARD_ON_COMPLETE, Boolean.TRUE);
}
}
setServerContextAttribute(NhttpConstants.RES_HEADER_ARRIVAL_TIME, System.currentTimeMillis(), conn);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CONTINUE) {
if (log.isDebugEnabled()) {
log.debug(conn + ": Received a 100 Continue response");
}
// and wait for the response
return;
}
ClientConnectionDebug ccd = (ClientConnectionDebug) conn.getContext().getAttribute(CLIENT_CONNECTION_DEBUG);
if (ccd != null) {
ccd.recordResponseStartTime(response.getStatusLine().toString());
}
// Have we sent out our request fully in the first place? if not, forget about it now..
Axis2HttpRequest req = (Axis2HttpRequest) conn.getContext().getAttribute(AXIS2_HTTP_REQUEST);
if (req != null) {
req.setCompleted(true);
if (log.isDebugEnabled()) {
log.debug(conn + ": Response Received for Request : " + req);
}
if (!req.isSendingCompleted()) {
req.getMsgContext().setProperty(NhttpConstants.ERROR_CODE, NhttpConstants.SEND_ABORT);
NhttpSharedOutputBuffer outputBuffer = (NhttpSharedOutputBuffer) conn.getContext().getAttribute(REQUEST_SOURCE_BUFFER);
if (outputBuffer != null) {
outputBuffer.shutdown();
}
if (log.isDebugEnabled()) {
log.debug(conn + ": Remote server aborted request being sent and replied : " + conn + " for request : " + conn.getContext().getAttribute(NhttpConstants.HTTP_REQ_METHOD));
}
context.setAttribute(NhttpConstants.DISCARD_ON_COMPLETE, Boolean.TRUE);
if (metrics != null) {
metrics.incrementFaultsSending(NhttpConstants.SEND_ABORT, req.getMsgContext());
}
}
}
switch(response.getStatusLine().getStatusCode()) {
case HttpStatus.SC_ACCEPTED:
{
if (log.isDebugEnabled()) {
log.debug(conn + ": Received a 202 Accepted response");
}
// Process response body if Content-Type header is present in the response
// If Content-Type header is null, We will ignore entity body
Header contentType = response.getFirstHeader(HTTP.CONTENT_TYPE);
if (contentType != null) {
processResponse(conn, context, response);
return;
}
// sometimes, some http clients sends an "\r\n" as the content body with a
// HTTP 202 OK.. we will just get it into this temp buffer and ignore it..
ContentInputBuffer inputBuffer = new SharedInputBuffer(8, conn, allocator);
context.setAttribute(RESPONSE_SINK_BUFFER, inputBuffer);
// create a dummy message with an empty SOAP envelope and a property
// NhttpConstants.SC_ACCEPTED set to Boolean.TRUE to indicate this is a
// placeholder message for the transport to send a HTTP 202 to the
// client. Should / would be ignored by any transport other than
// nhttp. For example, JMS would not send a reply message for one-way
// operations.
MessageContext outMsgCtx = (MessageContext) context.getAttribute(OUTGOING_MESSAGE_CONTEXT);
MessageReceiver mr = outMsgCtx.getAxisOperation().getMessageReceiver();
// 202 Accepted message
if (!outMsgCtx.isPropertyTrue(NhttpConstants.IGNORE_SC_ACCEPTED)) {
try {
MessageContext responseMsgCtx = outMsgCtx.getOperationContext().getMessageContext(WSDL2Constants.MESSAGE_LABEL_IN);
if (responseMsgCtx == null || outMsgCtx.getOptions().isUseSeparateListener() || outMsgCtx.getOperationContext().isComplete()) {
if (responseMsgCtx != null && responseMsgCtx.getProperty("synapse.send") == null) {
return;
}
} else if (responseMsgCtx == null || outMsgCtx.getOptions().isUseSeparateListener()) {
// Since we need to notify the SynapseCallback receiver to remove the
// call backs registered we set a custom property
setHeaders(context, response, outMsgCtx, responseMsgCtx);
outMsgCtx.setProperty(NhttpConstants.HTTP_202_RECEIVED, "true");
mr.receive(outMsgCtx);
return;
}
if (responseMsgCtx == null) {
return;
}
setHeaders(context, response, outMsgCtx, responseMsgCtx);
responseMsgCtx.setServerSide(true);
responseMsgCtx.setDoingREST(outMsgCtx.isDoingREST());
responseMsgCtx.setProperty(MessageContext.TRANSPORT_IN, outMsgCtx.getProperty(MessageContext.TRANSPORT_IN));
responseMsgCtx.setTransportIn(outMsgCtx.getTransportIn());
responseMsgCtx.setTransportOut(outMsgCtx.getTransportOut());
responseMsgCtx.setAxisMessage(outMsgCtx.getAxisOperation().getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE));
responseMsgCtx.setOperationContext(outMsgCtx.getOperationContext());
responseMsgCtx.setConfigurationContext(outMsgCtx.getConfigurationContext());
responseMsgCtx.setTo(null);
if (!outMsgCtx.isDoingREST() && !outMsgCtx.isSOAP11()) {
responseMsgCtx.setEnvelope(new SOAP12Factory().getDefaultEnvelope());
} else {
responseMsgCtx.setEnvelope(new SOAP11Factory().getDefaultEnvelope());
}
responseMsgCtx.setProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES, Boolean.TRUE);
responseMsgCtx.setProperty(NhttpConstants.SC_ACCEPTED, Boolean.TRUE);
int statusCode = response.getStatusLine().getStatusCode();
responseMsgCtx.setProperty(NhttpConstants.HTTP_SC, statusCode);
mr.receive(responseMsgCtx);
} catch (org.apache.axis2.AxisFault af) {
log.debug(conn + ": Unable to report back " + "202 Accepted state to the message receiver");
}
}
return;
}
case HttpStatus.SC_OK:
{
processResponse(conn, context, response);
return;
}
case HttpStatus.SC_INTERNAL_SERVER_ERROR:
{
if (warnOnHttp500(response)) {
log.warn(getErrorMessage("Received an internal server error : " + response.getStatusLine().getReasonPhrase(), conn));
}
processResponse(conn, context, response);
return;
}
default:
{
if (log.isDebugEnabled()) {
log.debug(conn + ": " + getErrorMessage("HTTP status code received : " + response.getStatusLine().getStatusCode() + " :: " + response.getStatusLine().getReasonPhrase(), conn));
}
Header contentType = response.getFirstHeader(HTTP.CONTENT_TYPE);
if (contentType != null) {
if ((contentType.getValue().indexOf(SOAP11Constants.SOAP_11_CONTENT_TYPE) >= 0) || contentType.getValue().indexOf(SOAP12Constants.SOAP_12_CONTENT_TYPE) >= 0) {
if (log.isDebugEnabled()) {
log.debug(conn + ": Received an unexpected response with a SOAP payload");
}
} else if (contentType.getValue().indexOf("html") == -1) {
if (log.isDebugEnabled()) {
log.debug(conn + ": Received an unexpected response with a POX/REST payload");
}
} else {
log.warn(getErrorMessage("Received an unexpected response - " + "of content type : " + contentType.getValue() + " and status code : " + response.getStatusLine().getStatusCode() + " with reason : " + response.getStatusLine().getReasonPhrase(), conn));
}
} else {
if (log.isDebugEnabled()) {
log.debug(conn + ": " + getErrorMessage("Received a response - " + "without a content type with status code : " + response.getStatusLine().getStatusCode() + " and reason : " + response.getStatusLine().getReasonPhrase(), conn));
}
}
processResponse(conn, context, response);
}
}
}
use of org.apache.axiom.soap.impl.dom.soap11.SOAP11Factory in project wso2-synapse by wso2.
the class ClientWorker method run.
/**
* Process the received response through Axis2
*/
public void run() {
CustomLogSetter.getInstance().clearThreadLocalContent();
setServerContextAttribute(NhttpConstants.CLIENT_WORKER_START_TIME, System.currentTimeMillis(), outMsgCtx);
// response and populate it with the soap envelope
if (responseMsgCtx == null) {
return;
}
try {
if (in != null) {
Header cType = response.getFirstHeader(HTTP.CONTENT_TYPE);
String contentType;
if (cType != null) {
// This is the most common case - Most of the time servers send the Content-Type
contentType = cType.getValue();
} else {
// Server hasn't sent the header - Try to infer the content type
contentType = inferContentType();
}
String charSetEnc = BuilderUtil.getCharSetEncoding(contentType);
if (charSetEnc == null) {
charSetEnc = MessageContext.DEFAULT_CHAR_SET_ENCODING;
}
responseMsgCtx.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc);
// workaround for Axis2 TransportUtils.createSOAPMessage() issue, where a response
// of content type "text/xml" is thought to be REST if !MC.isServerSide(). This
// question is still under debate and due to the timelines, I am commiting this
// workaround as Axis2 1.2 is about to be released and Synapse 1.0
responseMsgCtx.setServerSide(false);
SOAPEnvelope envelope;
try {
envelope = TransportUtils.createSOAPMessage(responseMsgCtx, HTTPTransportUtils.handleGZip(responseMsgCtx, in), contentType);
} catch (OMException e) {
// handle non SOAP and POX/REST payloads (probably text/html)
String errorMessage = "Unexpected response received. HTTP response code : " + this.response.getStatusLine().getStatusCode() + " HTTP status : " + this.response.getStatusLine().getReasonPhrase() + " exception : " + e.getMessage();
log.warn(errorMessage);
if (log.isDebugEnabled()) {
log.debug(errorMessage, e);
log.debug("Creating the SOAPFault to be injected...");
}
SOAPFactory factory = new SOAP11Factory();
envelope = factory.getDefaultFaultEnvelope();
SOAPFaultDetail detail = factory.createSOAPFaultDetail();
detail.setText(errorMessage);
envelope.getBody().getFault().setDetail(detail);
SOAPFaultReason reason = factory.createSOAPFaultReason();
reason.setText(errorMessage);
envelope.getBody().getFault().setReason(reason);
SOAPFaultCode code = factory.createSOAPFaultCode();
code.setText(Integer.toString(this.response.getStatusLine().getStatusCode()));
envelope.getBody().getFault().setCode(code);
}
responseMsgCtx.setServerSide(true);
responseMsgCtx.setEnvelope(envelope);
} else {
// there is no response entity-body
responseMsgCtx.setProperty(NhttpConstants.NO_ENTITY_BODY, Boolean.TRUE);
responseMsgCtx.setEnvelope(new SOAP11Factory().getDefaultEnvelope());
}
// copy the HTTP status code as a message context property with the key HTTP_SC to be
// used at the sender to set the propper status code when passing the message
int statusCode = this.response.getStatusLine().getStatusCode();
responseMsgCtx.setProperty(NhttpConstants.HTTP_SC, statusCode);
if (statusCode >= 400) {
responseMsgCtx.setProperty(NhttpConstants.FAULT_MESSAGE, NhttpConstants.TRUE);
}
responseMsgCtx.setProperty(NhttpConstants.NON_BLOCKING_TRANSPORT, true);
if (endpointURLPrefix != null) {
responseMsgCtx.setProperty(NhttpConstants.ENDPOINT_PREFIX, endpointURLPrefix);
}
// process response received
try {
AxisEngine.receive(responseMsgCtx);
} catch (AxisFault af) {
// This will be reached if an exception is thrown within an Axis2 handler
String errorMessage = "Fault processing response message through Axis2: " + af.getMessage();
log.warn(errorMessage);
if (log.isDebugEnabled()) {
log.debug(errorMessage, af);
log.debug("Directly invoking SynapseCallbackReceiver after setting " + "error properties");
}
responseMsgCtx.setProperty(NhttpConstants.SENDING_FAULT, Boolean.TRUE);
responseMsgCtx.setProperty(NhttpConstants.ERROR_CODE, NhttpConstants.RESPONSE_PROCESSING_FAILURE);
responseMsgCtx.setProperty(NhttpConstants.ERROR_MESSAGE, errorMessage.split("\n")[0]);
responseMsgCtx.setProperty(NhttpConstants.ERROR_DETAIL, JavaUtils.stackToString(af));
responseMsgCtx.setProperty(NhttpConstants.ERROR_EXCEPTION, af);
responseMsgCtx.getAxisOperation().getMessageReceiver().receive(responseMsgCtx);
}
} catch (AxisFault af) {
log.error("Fault creating response SOAP envelope", af);
return;
} catch (XMLStreamException e) {
log.error("Error creating response SOAP envelope", e);
} catch (IOException e) {
log.error("Error closing input stream from which message was read", e);
} finally {
// to read the response back from the server.
try {
if (in != null) {
in.close();
}
} catch (IOException ignore) {
}
}
}
use of org.apache.axiom.soap.impl.dom.soap11.SOAP11Factory in project wso2-synapse by wso2.
the class DeferredMessageBuilder method getDocument.
public OMElement getDocument(MessageContext msgCtx, InputStream in) throws XMLStreamException, IOException {
// that the payload stream is empty or not.
if (HTTPConstants.HEADER_DELETE.equals(msgCtx.getProperty(Constants.Configuration.HTTP_METHOD)) && MessageUtils.isEmptyPayloadStream(in)) {
msgCtx.setProperty(BridgeConstants.NO_ENTITY_BODY, Boolean.TRUE);
return TransportUtils.createSOAPEnvelope(null);
}
String contentType = (String) msgCtx.getProperty(Constants.Configuration.CONTENT_TYPE);
String contentType1 = getContentType(contentType, msgCtx);
Map transportHeaders = (Map) msgCtx.getProperty(MessageContext.TRANSPORT_HEADERS);
String contentLength = null;
String transferEncoded;
if (transportHeaders != null) {
contentLength = (String) transportHeaders.get(BridgeConstants.CONTENT_LEN);
transferEncoded = (String) transportHeaders.get(BridgeConstants.TRANSFER_ENCODING);
if (contentType.equals(BridgeConstants.CONTENT_TYPE_APPLICATION_OCTET_STREAM) && (contentLength == null || Integer.parseInt(contentLength) == 0) && transferEncoded == null) {
msgCtx.setProperty(BridgeConstants.NO_ENTITY_BODY, true);
msgCtx.setProperty(Constants.Configuration.CONTENT_TYPE, "");
return new SOAP11Factory().getDefaultEnvelope();
}
}
OMElement element = null;
Builder builder;
if (contentType != null) {
// loading builder from externally..
// builder = configuration.getMessageBuilder(_contentType,useFallbackBuilder);
builder = MessageProcessorSelector.getMessageBuilder(contentType1, msgCtx);
if (builder != null) {
try {
if ("0".equals(contentLength)) {
element = new SOAP11Factory().getDefaultEnvelope();
// since we are setting an empty envelop to achieve the empty body, we have to set a different
// content-type other than text/xml, application/soap+xml or any other content-type which will
// invoke the soap builder, otherwise soap builder will get hit and an empty envelope
// will be send out
msgCtx.setProperty(Constants.Configuration.MESSAGE_TYPE, "application/xml");
} else {
element = builder.processDocument(in, contentType, msgCtx);
}
} catch (AxisFault axisFault) {
LOG.error("Error building message", axisFault);
throw axisFault;
}
}
}
if (element == null) {
if (msgCtx.isDoingREST()) {
try {
element = BuilderUtil.getPOXBuilder(in, null).getDocumentElement();
} catch (XMLStreamException e) {
LOG.error("Error building message using POX Builder", e);
throw e;
}
} else {
// switch to default
builder = new SOAPBuilder();
try {
if ("0".equals(contentLength)) {
element = new SOAP11Factory().getDefaultEnvelope();
// since we are setting an empty envelop to achieve the empty body, we have to set a different
// content-type other than text/xml, application/soap+xml or any other content-type which will
// invoke the soap builder, otherwise soap builder will get hit and an empty envelope
// will be send out
msgCtx.setProperty(Constants.Configuration.MESSAGE_TYPE, "application/xml");
} else {
element = builder.processDocument(in, contentType, msgCtx);
}
} catch (AxisFault axisFault) {
LOG.error("Error building message using SOAP builder");
throw axisFault;
}
}
}
// build the soap headers and body
if (element instanceof SOAPEnvelope) {
SOAPEnvelope env = (SOAPEnvelope) element;
env.hasFault();
}
// setting up original contentType (resetting the content type)
if (contentType != null && !contentType.isEmpty()) {
msgCtx.setProperty(Constants.Configuration.CONTENT_TYPE, contentType);
}
return element;
}
use of org.apache.axiom.soap.impl.dom.soap11.SOAP11Factory in project wso2-synapse by wso2.
the class ServerWorker method processNonEntityEnclosingRESTHandler.
public void processNonEntityEnclosingRESTHandler(SOAPEnvelope soapEnvelope, MessageContext msgContext, boolean injectToAxis2Engine) {
String soapAction = request.getHeaders().get(SOAP_ACTION_HEADER);
if ((soapAction != null) && soapAction.startsWith("\"") && soapAction.endsWith("\"")) {
soapAction = soapAction.substring(1, soapAction.length() - 1);
}
msgContext.setSoapAction(soapAction);
msgContext.setTo(new EndpointReference(request.getUri()));
msgContext.setServerSide(true);
msgContext.setDoingREST(true);
if (!(request.isEntityEnclosing())) {
msgContext.setProperty(PassThroughConstants.NO_ENTITY_BODY, Boolean.TRUE);
}
try {
if (soapEnvelope == null) {
msgContext.setEnvelope(new SOAP11Factory().getDefaultEnvelope());
} else {
msgContext.setEnvelope(soapEnvelope);
}
if (injectToAxis2Engine) {
AxisEngine.receive(msgContext);
}
} catch (AxisFault axisFault) {
handleException("Error processing " + request.getMethod() + " request for : " + request.getUri(), axisFault);
} catch (Exception e) {
String encodedURL = StringEscapeUtils.escapeHtml(request.getUri());
handleException("Error processing " + request.getMethod() + " request for : " + encodedURL + ". ", e);
}
}
use of org.apache.axiom.soap.impl.dom.soap11.SOAP11Factory in project wso2-synapse by wso2.
the class FIXUtils method setSOAPEnvelope.
/**
* FIX messages are non-XML. So convert them into XML using the AXIOM API.
* Put the FIX message into an Axis2 MessageContext.The basic format of the
* generated SOAP envelope;
* <p/>
* <soapEnvelope>
* <soapBody>
* <message>
* <header> ....</header>
* <body> .... </body>
* <trailer> .... </trailer>
* </message>
* </soapBody>
* </soapEnvelope>
*
* @param message the FIX message
* @param counter application level sequence number of the message
* @param sessionID the incoming session
* @param msgCtx the Axis2 MessageContext to hold the FIX message
* @throws AxisFault the exception thrown when invalid soap envelopes are set to the msgCtx
*/
public void setSOAPEnvelope(Message message, int counter, String sessionID, MessageContext msgCtx) throws AxisFault {
if (log.isDebugEnabled()) {
log.debug("Creating SOAP envelope for FIX message...");
}
SOAPFactory soapFactory = new SOAP11Factory();
OMElement msg = soapFactory.createOMElement(FIXConstants.FIX_MESSAGE, null);
msg.addAttribute(soapFactory.createOMAttribute(FIXConstants.FIX_MESSAGE_INCOMING_SESSION, null, sessionID));
msg.addAttribute(soapFactory.createOMAttribute(FIXConstants.FIX_MESSAGE_COUNTER, null, String.valueOf(counter)));
OMElement header = soapFactory.createOMElement(FIXConstants.FIX_HEADER, null);
OMElement body = soapFactory.createOMElement(FIXConstants.FIX_BODY, null);
OMElement trailer = soapFactory.createOMElement(FIXConstants.FIX_TRAILER, null);
// process FIX header
Iterator<Field<?>> iter = message.getHeader().iterator();
if (iter != null) {
while (iter.hasNext()) {
Field<?> field = iter.next();
OMElement msgField = soapFactory.createOMElement(FIXConstants.FIX_FIELD, null);
msgField.addAttribute(soapFactory.createOMAttribute(FIXConstants.FIX_FIELD_ID, null, String.valueOf(field.getTag())));
Object value = field.getObject();
if (value instanceof byte[]) {
DataSource dataSource = new ByteArrayDataSource((byte[]) value);
DataHandler dataHandler = new DataHandler(dataSource);
String contentID = msgCtx.addAttachment(dataHandler);
OMElement binaryData = soapFactory.createOMElement(FIXConstants.FIX_BINARY_FIELD, null);
String binaryCID = "cid:" + contentID;
binaryData.addAttribute(FIXConstants.FIX_MESSAGE_REFERENCE, binaryCID, null);
msgField.addChild(binaryData);
} else {
createOMText(soapFactory, msgField, value.toString());
}
header.addChild(msgField);
}
}
// process FIX body
convertFIXBodyToXML(message, body, soapFactory, msgCtx);
// process FIX trailer
iter = message.getTrailer().iterator();
if (iter != null) {
while (iter.hasNext()) {
Field<?> field = iter.next();
OMElement msgField = soapFactory.createOMElement(FIXConstants.FIX_FIELD, null);
msgField.addAttribute(soapFactory.createOMAttribute(FIXConstants.FIX_FIELD_ID, null, String.valueOf(field.getTag())));
Object value = field.getObject();
if (value instanceof byte[]) {
DataSource dataSource = new ByteArrayDataSource((byte[]) value);
DataHandler dataHandler = new DataHandler(dataSource);
String contentID = msgCtx.addAttachment(dataHandler);
OMElement binaryData = soapFactory.createOMElement(FIXConstants.FIX_BINARY_FIELD, null);
String binaryCID = "cid:" + contentID;
binaryData.addAttribute(FIXConstants.FIX_MESSAGE_REFERENCE, binaryCID, null);
msgField.addChild(binaryData);
} else {
createOMText(soapFactory, msgField, value.toString());
}
trailer.addChild(msgField);
}
}
msg.addChild(header);
msg.addChild(body);
msg.addChild(trailer);
SOAPEnvelope envelope = soapFactory.getDefaultEnvelope();
envelope.getBody().addChild(msg);
msgCtx.setEnvelope(envelope);
}
Aggregations