Search in sources :

Example 1 with RelatesTo

use of org.apache.axis2.addressing.RelatesTo in project wso2-synapse by wso2.

the class FaultMediator method makeSOAPFault.

/**
 * Actual transformation of the current message into a fault message
 * @param synCtx the current message context
 * @param soapVersion SOAP version of the resulting fault desired
 * @param synLog the Synapse log to use
 */
private void makeSOAPFault(MessageContext synCtx, int soapVersion, SynapseLog synLog) {
    if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug("Creating a SOAP " + (soapVersion == SOAP11 ? "1.1" : "1.2") + " fault");
    }
    // get the correct SOAP factory to be used
    SOAPFactory factory = (soapVersion == SOAP11 ? OMAbstractFactory.getSOAP11Factory() : OMAbstractFactory.getSOAP12Factory());
    // create the SOAP fault document and envelope
    OMDocument soapFaultDocument = factory.createOMDocument();
    SOAPEnvelope faultEnvelope = factory.getDefaultFaultEnvelope();
    soapFaultDocument.addChild(faultEnvelope);
    // create the fault element  if it is need
    SOAPFault fault = faultEnvelope.getBody().getFault();
    if (fault == null) {
        fault = factory.createSOAPFault();
    }
    // populate it
    setFaultCode(synCtx, factory, fault, soapVersion);
    setFaultReason(synCtx, factory, fault, soapVersion);
    setFaultNode(factory, fault);
    setFaultRole(factory, fault);
    setFaultDetail(synCtx, factory, fault);
    // set the all headers of original SOAP Envelope to the Fault Envelope
    if (synCtx.getEnvelope() != null) {
        SOAPHeader soapHeader = synCtx.getEnvelope().getHeader();
        if (soapHeader != null) {
            for (Iterator iter = soapHeader.examineAllHeaderBlocks(); iter.hasNext(); ) {
                Object o = iter.next();
                if (o instanceof SOAPHeaderBlock) {
                    SOAPHeaderBlock header = (SOAPHeaderBlock) o;
                    faultEnvelope.getHeader().addChild(header);
                } else if (o instanceof OMElement) {
                    faultEnvelope.getHeader().addChild((OMElement) o);
                }
            }
        }
    }
    if (synLog.isTraceOrDebugEnabled()) {
        String msg = "Original SOAP Message : " + synCtx.getEnvelope().toString() + "Fault Message created : " + faultEnvelope.toString();
        if (synLog.isTraceTraceEnabled()) {
            synLog.traceTrace(msg);
        }
        if (log.isTraceEnabled()) {
            log.trace(msg);
        }
    }
    // overwrite current message envelope with new fault envelope
    try {
        synCtx.setEnvelope(faultEnvelope);
    } catch (AxisFault af) {
        handleException("Error replacing current SOAP envelope " + "with the fault envelope", af, synCtx);
    }
    if (synCtx.getFaultTo() != null) {
        synCtx.setTo(synCtx.getFaultTo());
    } else if (synCtx.getReplyTo() != null) {
        synCtx.setTo(synCtx.getReplyTo());
    } else {
        synCtx.setTo(null);
    }
    // set original messageID as relatesTo
    if (synCtx.getMessageID() != null) {
        RelatesTo relatesTo = new RelatesTo(synCtx.getMessageID());
        synCtx.setRelatesTo(new RelatesTo[] { relatesTo });
    }
    synLog.traceOrDebug("End : Fault mediator");
}
Also used : AxisFault(org.apache.axis2.AxisFault) Iterator(java.util.Iterator) RelatesTo(org.apache.axis2.addressing.RelatesTo)

Example 2 with RelatesTo

use of org.apache.axis2.addressing.RelatesTo in project wso2-synapse by wso2.

the class GetPropertyFunction method evaluate.

/**
 * Returns the string value of the property using arg one as key and arg two as scope
 *
 * @param scopeObject scope will decide from where property will be picked up from
 *        i.e. axis2, transport, default/synapse
 * @param keyObject the key of the property
 * @param navigator object model which can be used for navigation around
 * @param dateformat The dateformat that need to convert
 * @return The String value of property using arg one as key and arg two as scope
 */
public Object evaluate(Object scopeObject, Object keyObject, Object dateformat, Navigator navigator) {
    boolean traceOn = synCtx.getTracingState() == SynapseConstants.TRACING_ON;
    boolean traceOrDebugOn = traceOn || log.isDebugEnabled();
    String scope = StringFunction.evaluate(scopeObject, navigator);
    String key = StringFunction.evaluate(keyObject, navigator);
    if (key == null || "".equals(key)) {
        if (traceOrDebugOn) {
            traceOrDebug(traceOn, "property-name should be provided when executing synapse:get-property" + "(scope,prop-name) or synapse:get-property(prop-name) Xpath function");
        }
        return NULL_STRING;
    }
    if (SynapseConstants.SYSTEM_DATE.equals(key)) {
        if (dateformat != null) {
            Format formatter = new SimpleDateFormat(dateformat.toString());
            return formatter.format(new java.util.Date());
        } else {
            Format formatter = new SimpleDateFormat();
            return formatter.format(new java.util.Date());
        }
    }
    // return the current system time as a string , don't care scope
    if (SynapseConstants.SYSTEM_TIME.equals(key)) {
        return Long.toString(System.currentTimeMillis());
    }
    if (XMLConfigConstants.SCOPE_DEFAULT.equals(scope)) {
        if (SynapseConstants.HEADER_TO.equals(key)) {
            EndpointReference toEPR = synCtx.getTo();
            if (toEPR != null) {
                return toEPR.getAddress();
            } else {
                return NULL_STRING;
            }
        } else if (SynapseConstants.HEADER_FROM.equals(key)) {
            EndpointReference fromEPR = synCtx.getFrom();
            if (fromEPR != null) {
                return fromEPR.getAddress();
            } else {
                return NULL_STRING;
            }
        } else if (SynapseConstants.HEADER_ACTION.equals(key)) {
            String wsaAction = synCtx.getWSAAction();
            if (wsaAction != null) {
                return wsaAction;
            } else {
                return NULL_STRING;
            }
        } else if (SynapseConstants.HEADER_FAULT.equals(key)) {
            EndpointReference faultEPR = synCtx.getFaultTo();
            if (faultEPR != null) {
                return faultEPR.getAddress();
            } else {
                return NULL_STRING;
            }
        } else if (SynapseConstants.HEADER_REPLY_TO.equals(key)) {
            EndpointReference replyToEPR = synCtx.getReplyTo();
            if (replyToEPR != null) {
                return replyToEPR.getAddress();
            } else {
                return NULL_STRING;
            }
        } else if (SynapseConstants.HEADER_RELATES_TO.equals(key)) {
            RelatesTo relatesTo = synCtx.getRelatesTo();
            if (relatesTo != null) {
                return relatesTo.getValue();
            } else {
                return NULL_STRING;
            }
        } else if (SynapseConstants.HEADER_MESSAGE_ID.equals(key)) {
            String messageID = synCtx.getMessageID();
            if (messageID != null) {
                return messageID;
            } else {
                return NULL_STRING;
            }
        } else if (SynapseConstants.PROPERTY_FAULT.equals(key)) {
            if (synCtx.getEnvelope().hasFault()) {
                return SynapseConstants.TRUE;
            } else if (synCtx instanceof Axis2MessageContext) {
                org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
                if (axis2MessageContext.getProperty(BaseConstants.FAULT_MESSAGE) != null && SynapseConstants.TRUE.equals(axis2MessageContext.getProperty(BaseConstants.FAULT_MESSAGE))) {
                    return SynapseConstants.TRUE;
                }
            } else {
                return NULL_STRING;
            }
        } else if (SynapseConstants.PROPERTY_MESSAGE_FORMAT.equals(key)) {
            if (synCtx.isDoingPOX())
                return SynapseConstants.FORMAT_POX;
            else if (synCtx.isDoingGET())
                return SynapseConstants.FORMAT_GET;
            else if (synCtx.isSOAP11())
                return SynapseConstants.FORMAT_SOAP11;
            else
                return SynapseConstants.FORMAT_SOAP12;
        } else if (SynapseConstants.PROPERTY_OPERATION_NAME.equals(key) || SynapseConstants.PROPERTY_OPERATION_NAMESPACE.equals(key)) {
            if (synCtx instanceof Axis2MessageContext) {
                AxisOperation axisOperation = ((Axis2MessageContext) synCtx).getAxis2MessageContext().getAxisOperation();
                if (axisOperation != null) {
                    if (SynapseConstants.PROPERTY_OPERATION_NAMESPACE.equals(key)) {
                        return axisOperation.getName().getNamespaceURI();
                    } else {
                        return axisOperation.getName().getLocalPart();
                    }
                }
            }
        } else {
            Object result = synCtx.getProperty(key);
            if (result != null) {
                return result;
            } else {
                return synCtx.getLocalEntry(key);
            }
        }
    } else if (XMLConfigConstants.SCOPE_AXIS2.equals(scope) && synCtx instanceof Axis2MessageContext) {
        org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
        return axis2MessageContext.getProperty(key);
    } else if (XMLConfigConstants.SCOPE_FUNC.equals(scope)) {
        Stack<TemplateContext> functionStack = (Stack) synCtx.getProperty(SynapseConstants.SYNAPSE__FUNCTION__STACK);
        TemplateContext topCtxt = functionStack.peek();
        if (topCtxt != null) {
            return topCtxt.getParameterValue(key);
        }
    } else if (XMLConfigConstants.SCOPE_TRANSPORT.equals(scope) && synCtx instanceof Axis2MessageContext) {
        org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
        Object headers = axis2MessageContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
        if (headers != null && headers instanceof Map) {
            Map headersMap = (Map) headers;
            return headersMap.get(key);
        }
    } else if (XMLConfigConstants.SCOPE_OPERATION.equals(scope) && synCtx instanceof Axis2MessageContext) {
        Axis2MessageContext axis2smc = (Axis2MessageContext) synCtx;
        org.apache.axis2.context.MessageContext axis2MessageCtx = axis2smc.getAxis2MessageContext();
        return axis2smc.getAxis2MessageContext().getOperationContext().getProperty(key);
    } else if (XMLConfigConstants.SCOPE_REGISTRY.equals(scope)) {
        String[] regParam = key.split("@");
        String regPath = null;
        String propName = null;
        if (regParam.length == 2) {
            regPath = regParam[0];
            propName = regParam[1];
        } else if (regParam.length == 1) {
            regPath = regParam[0];
        }
        Entry propEntry = synCtx.getConfiguration().getEntryDefinition(regPath);
        if (propEntry == null) {
            propEntry = new Entry();
            propEntry.setType(Entry.REMOTE_ENTRY);
            propEntry.setKey(key);
        }
        Registry registry = synCtx.getConfiguration().getRegistry();
        if (registry != null) {
            registry.getResource(propEntry, new Properties());
            if (propName != null) {
                Properties reqProperties = propEntry.getEntryProperties();
                if (reqProperties != null) {
                    if (reqProperties.get(propName) != null) {
                        return reqProperties.getProperty(propName);
                    }
                }
            } else if (propEntry.getValue() != null) {
                if (propEntry.getValue() instanceof OMText) {
                    return ((OMText) propEntry.getValue()).getText();
                }
                return propEntry.getValue().toString();
            }
        }
    } else if (XMLConfigConstants.SCOPE_SYSTEM.equals(scope)) {
        String propVal = System.getProperty(key);
        if (propVal != null) {
            return propVal;
        } else {
            if (traceOrDebugOn) {
                traceOrDebug(traceOn, "System property " + key + " not found");
            }
            return NULL_STRING;
        }
    } else {
        if (traceOrDebugOn) {
            traceOrDebug(traceOn, "Invalid scope : '" + scope + "' has been set for the " + "synapse:get-property(scope,prop-name) XPath function");
        }
    }
    return NULL_STRING;
}
Also used : AxisOperation(org.apache.axis2.description.AxisOperation) Properties(java.util.Properties) RelatesTo(org.apache.axis2.addressing.RelatesTo) Entry(org.apache.synapse.config.Entry) Format(java.text.Format) SimpleDateFormat(java.text.SimpleDateFormat) OMText(org.apache.axiom.om.OMText) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) Registry(org.apache.synapse.registry.Registry) TemplateContext(org.apache.synapse.mediators.template.TemplateContext) EndpointReference(org.apache.axis2.addressing.EndpointReference) Stack(java.util.Stack) SimpleDateFormat(java.text.SimpleDateFormat) Map(java.util.Map)

Example 3 with RelatesTo

use of org.apache.axis2.addressing.RelatesTo in project wso2-synapse by wso2.

the class SynapseCallbackReceiver method handleMessage.

/**
 * Handle the response or error (during a failed send) message received for an outgoing request
 *
 * @param messageID        Request message ID
 * @param response         the Axis2 MessageContext that has been received and has to be handled
 * @param synapseOutMsgCtx the corresponding (outgoing) Synapse MessageContext for the above
 *                         Axis2 MC, that holds Synapse specific information such as the error
 *                         handler stack and local properties etc.
 * @throws AxisFault       if the message cannot be processed
 */
private void handleMessage(String messageID, MessageContext response, org.apache.synapse.MessageContext synapseOutMsgCtx, AsyncCallback callback) throws AxisFault {
    // apply the tenant information to the out message context
    TenantInfoConfigurator configurator = synapseOutMsgCtx.getEnvironment().getTenantInfoConfigurator();
    if (configurator != null) {
        configurator.applyTenantInfo(synapseOutMsgCtx);
    }
    Boolean isConcurrencyThrottleEnabled = (Boolean) synapseOutMsgCtx.getProperty(SynapseConstants.SYNAPSE_CONCURRENCY_THROTTLE);
    if (isConcurrencyThrottleEnabled != null && isConcurrencyThrottleEnabled) {
        ConcurrentAccessController concurrentAccessController = (ConcurrentAccessController) synapseOutMsgCtx.getProperty(SynapseConstants.SYNAPSE_CONCURRENT_ACCESS_CONTROLLER);
        int available = concurrentAccessController.incrementAndGet();
        int concurrentLimit = concurrentAccessController.getLimit();
        if (log.isDebugEnabled()) {
            log.debug("Concurrency Throttle : Connection returned" + " :: " + available + " of available of " + concurrentLimit + " connections");
        }
        ConcurrentAccessReplicator concurrentAccessReplicator = (ConcurrentAccessReplicator) synapseOutMsgCtx.getProperty(SynapseConstants.SYNAPSE_CONCURRENT_ACCESS_REPLICATOR);
        String throttleKey = (String) synapseOutMsgCtx.getProperty(SynapseConstants.SYNAPSE_CONCURRENCY_THROTTLE_KEY);
        if (concurrentAccessReplicator != null) {
            concurrentAccessReplicator.replicate(throttleKey, true);
        }
    }
    Object o = response.getProperty(SynapseConstants.SENDING_FAULT);
    if (o != null && Boolean.TRUE.equals(o)) {
        // This path hits with a fault. Sequence mediator threads should not remove faultSequence.
        // SynapseCallbackReceiver thread should handle the faultStack.
        Pipe pipe = (Pipe) ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext().getProperty(PassThroughConstants.PASS_THROUGH_PIPE);
        if (pipe != null && pipe.isSerializationComplete()) {
            NHttpServerConnection conn = (NHttpServerConnection) ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext().getProperty("pass-through.Source-Connection");
            SourceConfiguration sourceConfiguration = (SourceConfiguration) ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext().getProperty("PASS_THROUGH_SOURCE_CONFIGURATION");
            Pipe newPipe = new Pipe(conn, sourceConfiguration.getBufferFactory().getBuffer(), "source", sourceConfiguration);
            ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext().setProperty(PassThroughConstants.PASS_THROUGH_PIPE, newPipe);
        }
        // there is a sending fault. propagate the fault to fault handlers.
        Stack faultStack = synapseOutMsgCtx.getFaultStack();
        if (faultStack != null && !faultStack.isEmpty()) {
            // fault envelope
            try {
                synapseOutMsgCtx.getEnvelope().build();
            } catch (Exception x) {
                synapseOutMsgCtx.setEnvelope(response.getEnvelope());
            }
            Exception e = (Exception) response.getProperty(SynapseConstants.ERROR_EXCEPTION);
            synapseOutMsgCtx.setProperty(SynapseConstants.SENDING_FAULT, Boolean.TRUE);
            synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_CODE, response.getProperty(SynapseConstants.ERROR_CODE));
            synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_MESSAGE, response.getProperty(SynapseConstants.ERROR_MESSAGE));
            synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_DETAIL, response.getProperty(SynapseConstants.ERROR_DETAIL));
            synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_EXCEPTION, e);
            if (synapseOutMsgCtx.getEnvironment().isContinuationEnabled()) {
                synapseOutMsgCtx.setContinuationEnabled(true);
            }
            if (log.isDebugEnabled()) {
                log.debug("[Failed Request Message ID : " + messageID + "]" + " [New to be Retried Request Message ID : " + synapseOutMsgCtx.getMessageID() + "]");
            }
            int errorCode = (Integer) response.getProperty(SynapseConstants.ERROR_CODE);
            // If a timeout has occured and the timeout action of the callback is to discard the message
            if (errorCode == SynapseConstants.NHTTP_CONNECTION_TIMEOUT && callback.getTimeOutAction() == SynapseConstants.DISCARD) {
                // Do not execute any fault sequences. Discard message
                if (log.isWarnEnabled()) {
                    log.warn("Synapse timed out for the request with Message ID : " + messageID + ". Ignoring fault handlers since the timeout action is DISCARD");
                }
                faultStack.removeAllElements();
            } else {
                ((FaultHandler) faultStack.pop()).handleFault(synapseOutMsgCtx, null);
            }
        }
    } else {
        // there can always be only one instance of an Endpoint in the faultStack of a message
        // if the send was successful, so remove it before we proceed any further
        Stack faultStack = synapseOutMsgCtx.getFaultStack();
        Endpoint successfulEndpoint = null;
        if (faultStack != null && !faultStack.isEmpty() && faultStack.peek() instanceof Endpoint) {
            successfulEndpoint = (Endpoint) faultStack.pop();
        }
        if (log.isDebugEnabled()) {
            log.debug("Synapse received an asynchronous response message");
            log.debug("Received To: " + (response.getTo() != null ? response.getTo().getAddress() : "null"));
            log.debug("SOAPAction: " + (response.getSoapAction() != null ? response.getSoapAction() : "null"));
            log.debug("WSA-Action: " + (response.getWSAAction() != null ? response.getWSAAction() : "null"));
            String[] cids = null;
            try {
                cids = response.getAttachmentMap().getAllContentIDs();
            } catch (Exception ex) {
                // partially read stream could lead to corrupted attachment map and hence this exception
                // corrupted attachment map leads to inconsistent runtime exceptions and behavior
                // discard the attachment map for the fault handler invocation
                // ensure the successful completion for fault handler flow
                response.setAttachmentMap(null);
                log.error("Synapse encountered an exception when reading attachments from bytes stream. " + "Hence Attachments map is dropped from the message context.", ex);
            }
            if (cids != null && cids.length > 0) {
                for (String cid : cids) {
                    log.debug("Attachment : " + cid);
                }
            }
            log.debug("Body : \n" + response.getEnvelope());
        }
        MessageContext axisOutMsgCtx = ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext();
        // Processes 'Accept-Encoding'
        ResponseAcceptEncodingProcessor.process(response, axisOutMsgCtx);
        response.setServiceContext(null);
        response.setOperationContext(axisOutMsgCtx.getOperationContext());
        response.setAxisMessage(axisOutMsgCtx.getAxisOperation().getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE));
        // set properties on response
        response.setServerSide(true);
        response.setProperty(SynapseConstants.ISRESPONSE_PROPERTY, Boolean.TRUE);
        response.setProperty(MessageContext.TRANSPORT_OUT, axisOutMsgCtx.getProperty(MessageContext.TRANSPORT_OUT));
        response.setProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO, axisOutMsgCtx.getProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO));
        response.setTransportIn(axisOutMsgCtx.getTransportIn());
        response.setTransportOut(axisOutMsgCtx.getTransportOut());
        // response.setDoingREST(axisOutMsgCtx.isDoingREST()); This information already present, hence removing
        if (axisOutMsgCtx.isDoingMTOM() && (axisOutMsgCtx.getProperty(org.apache.axis2.Constants.Configuration.ENABLE_MTOM) == null || Boolean.getBoolean((String) axisOutMsgCtx.getProperty(org.apache.axis2.Constants.Configuration.ENABLE_MTOM)) == true)) {
            response.setDoingMTOM(true);
            response.setProperty(org.apache.axis2.Constants.Configuration.ENABLE_MTOM, org.apache.axis2.Constants.VALUE_TRUE);
        }
        if (axisOutMsgCtx.isDoingSwA()) {
            response.setDoingSwA(true);
            response.setProperty(org.apache.axis2.Constants.Configuration.ENABLE_SWA, org.apache.axis2.Constants.VALUE_TRUE);
        }
        // property state to original state.
        if (axisOutMsgCtx.getProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES) != null) {
            response.setProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES, axisOutMsgCtx.getProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES));
        } else {
            response.removeProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES);
        }
        Object messageType = axisOutMsgCtx.getProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE);
        if (!HTTPConstants.MEDIA_TYPE_X_WWW_FORM.equals(messageType)) {
            // copy the message type property that's used by the out message to the
            // response message
            response.setProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE, messageType);
        }
        if (axisOutMsgCtx.getMessageID() != null) {
            response.setRelationships(new RelatesTo[] { new RelatesTo(axisOutMsgCtx.getMessageID()) });
        }
        response.setReplyTo(axisOutMsgCtx.getReplyTo());
        response.setFaultTo(axisOutMsgCtx.getFaultTo());
        if (axisOutMsgCtx.isPropertyTrue(NhttpConstants.IGNORE_SC_ACCEPTED)) {
            response.setProperty(NhttpConstants.FORCE_SC_ACCEPTED, Constants.VALUE_TRUE);
        }
        // axis2 client options still contains properties such as policy files used in
        // outgoing request. Need to remove those.
        removeUnwantedClientOptions(response);
        // create the synapse message context for the response
        Axis2MessageContext synapseInMessageContext = new Axis2MessageContext(response, synapseOutMsgCtx.getConfiguration(), synapseOutMsgCtx.getEnvironment());
        synapseInMessageContext.setResponse(true);
        Object obj = synapseOutMsgCtx.getProperty(SynapseConstants.FORCE_ERROR_PROPERTY);
        String errorOnSOAPFault = (String) obj;
        if (Constants.VALUE_TRUE.equals(errorOnSOAPFault) && successfulEndpoint != null) {
            if (log.isDebugEnabled()) {
                log.debug("FORCE_ERROR_ON_SOAP_FAULT is true, checking for SOAPFault");
            }
            try {
                RelayUtils.buildMessage(((Axis2MessageContext) synapseInMessageContext).getAxis2MessageContext(), true);
            } catch (Exception e) {
            // handleException("Error while building message", e, synapseInMessageContext);
            }
            if ((synapseInMessageContext.getEnvelope() != null) && synapseInMessageContext.getEnvelope().hasFault()) {
                if (log.isDebugEnabled()) {
                    log.debug("SOAPFault found in response message, forcing endpoint " + successfulEndpoint.getName() + " to fail");
                }
                // setup new pipe configuration..if failure happens (this will be setup as the source writer and during the TargetContext
                // clean up operation the writer will be reset and pull to the buffer
                MessageContext axis2OUTMC = ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext();
                NHttpServerConnection conn = (NHttpServerConnection) axis2OUTMC.getProperty("pass-through.Source-Connection");
                if (conn != null) {
                    SourceConfiguration sourceConfiguration = (SourceConfiguration) axis2OUTMC.getProperty("PASS_THROUGH_SOURCE_CONFIGURATION");
                    Pipe pipe = new Pipe(conn, sourceConfiguration.getBufferFactory().getBuffer(), "source", sourceConfiguration);
                    axis2OUTMC.setProperty(PassThroughConstants.PASS_THROUGH_PIPE, pipe);
                }
                synapseOutMsgCtx.setProperty(SynapseConstants.SENDING_FAULT, Boolean.TRUE);
                synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_CODE, SynapseConstants.ENDPOINT_CUSTOM_ERROR);
                boolean failOver = false;
                if (successfulEndpoint instanceof AbstractEndpoint) {
                    Endpoint endpoint = ((AbstractEndpoint) successfulEndpoint).getParentEndpoint();
                    if (endpoint != null && (endpoint instanceof FailoverEndpoint)) {
                        failOver = true;
                    }
                }
                for (Object key : synapseOutMsgCtx.getPropertyKeySet()) {
                    synapseInMessageContext.setProperty((String) key, synapseOutMsgCtx.getProperty((String) key));
                }
                if (failOver) {
                    // we may required to handle same message for failover cases only other than that
                    // should treat based on the incoming message
                    ((FaultHandler) successfulEndpoint).handleFault(synapseOutMsgCtx, null);
                } else {
                    faultStack = synapseOutMsgCtx.getFaultStack();
                    if (faultStack != null) {
                        synapseInMessageContext.getFaultStack().addAll(faultStack);
                        ((FaultHandler) successfulEndpoint).handleFault(synapseInMessageContext, null);
                    }
                }
                return;
            } else {
                successfulEndpoint.onSuccess();
            }
        } else if (successfulEndpoint != null) {
            successfulEndpoint.onSuccess();
        }
        synapseInMessageContext.setTo(new EndpointReference(AddressingConstants.Final.WSA_ANONYMOUS_URL));
        synapseInMessageContext.setTracingState(synapseOutMsgCtx.getTracingState());
        synapseInMessageContext.setMessageFlowTracingState(synapseOutMsgCtx.getMessageFlowTracingState());
        for (Object key : synapseOutMsgCtx.getPropertyKeySet()) {
            synapseInMessageContext.setProperty((String) key, synapseOutMsgCtx.getProperty((String) key));
        }
        // Copy SequenceCallStack from original MC to the new MC
        Boolean isContinuationCall = (Boolean) synapseOutMsgCtx.getProperty(SynapseConstants.CONTINUATION_CALL);
        if (isContinuationCall != null && isContinuationCall) {
            // Set the message direction
            if (!synapseOutMsgCtx.isResponse()) {
                synapseInMessageContext.setResponse(false);
            }
            Stack<ContinuationState> seqContinuationStates = synapseOutMsgCtx.getContinuationStateStack();
            for (int i = 0; i < seqContinuationStates.size(); i++) {
                synapseInMessageContext.pushContinuationState(seqContinuationStates.get(i));
            }
        }
        // If this response is related to session affinity endpoints -Server initiated session
        Dispatcher dispatcher = (Dispatcher) synapseOutMsgCtx.getProperty(SynapseConstants.PROP_SAL_ENDPOINT_CURRENT_DISPATCHER);
        if (dispatcher != null && dispatcher.isServerInitiatedSession()) {
            dispatcher.updateSession(synapseInMessageContext);
        }
        // send the response message through the synapse mediation flow
        try {
            synapseOutMsgCtx.getEnvironment().injectMessage(synapseInMessageContext);
        } catch (Exception syne) {
            // introduced to handle runtime exceptions which are occurred inside Synapse handlers
            // partially read stream could lead to corrupted attachment map and hence this exception
            // corrupted attachment map leads to inconsistent runtime exceptions and behavior
            // discard the attachment map for the fault handler invocation
            // ensure the successful completion for fault handler flow
            // even we drop attachment map for both cases messages which have attachment /
            // messages which do not have attachments it would still not be any impact.
            // However setting attachment map to null for messages which do not have attachments is not required.
            // introduced due to the fact conflicts between Axiom exceptions for attachment/ non attachments cases
            // and performance impact that could cause of regular expression matching of exceptional stack traces.
            Axis2MessageContext axis2smc = (Axis2MessageContext) synapseInMessageContext;
            org.apache.axis2.context.MessageContext axis2MessageCtx = axis2smc.getAxis2MessageContext();
            // Set correct status code
            axis2MessageCtx.setProperty(PassThroughConstants.HTTP_SC, HttpStatus.SC_INTERNAL_SERVER_ERROR);
            axis2MessageCtx.setAttachmentMap(null);
            Stack stack = synapseInMessageContext.getFaultStack();
            if (stack != null && stack.isEmpty()) {
                registerFaultHandler(synapseInMessageContext);
            }
            if (stack != null && !stack.isEmpty()) {
                ((FaultHandler) stack.pop()).handleFault(synapseInMessageContext, syne);
            } else {
                log.error("Synapse encountered an exception, " + "No error handlers found - [Message Dropped]\n" + syne.getMessage());
            }
        }
    }
}
Also used : Dispatcher(org.apache.synapse.endpoints.dispatch.Dispatcher) FailoverEndpoint(org.apache.synapse.endpoints.FailoverEndpoint) RelatesTo(org.apache.axis2.addressing.RelatesTo) NHttpServerConnection(org.apache.http.nio.NHttpServerConnection) Endpoint(org.apache.synapse.endpoints.Endpoint) AbstractEndpoint(org.apache.synapse.endpoints.AbstractEndpoint) FailoverEndpoint(org.apache.synapse.endpoints.FailoverEndpoint) ConcurrentAccessController(org.apache.synapse.commons.throttle.core.ConcurrentAccessController) MessageContext(org.apache.axis2.context.MessageContext) FaultHandler(org.apache.synapse.FaultHandler) MediatorFaultHandler(org.apache.synapse.mediators.MediatorFaultHandler) AbstractEndpoint(org.apache.synapse.endpoints.AbstractEndpoint) Pipe(org.apache.synapse.transport.passthru.Pipe) Endpoint(org.apache.synapse.endpoints.Endpoint) AbstractEndpoint(org.apache.synapse.endpoints.AbstractEndpoint) FailoverEndpoint(org.apache.synapse.endpoints.FailoverEndpoint) ConcurrentAccessReplicator(org.apache.synapse.commons.throttle.core.ConcurrentAccessReplicator) Stack(java.util.Stack) EndpointReference(org.apache.axis2.addressing.EndpointReference) ContinuationState(org.apache.synapse.ContinuationState) TenantInfoConfigurator(org.apache.synapse.carbonext.TenantInfoConfigurator) SourceConfiguration(org.apache.synapse.transport.passthru.config.SourceConfiguration)

Example 4 with RelatesTo

use of org.apache.axis2.addressing.RelatesTo in project wso2-synapse by wso2.

the class SynapseCallbackReceiver method removeDuplicateRelatesTo.

/**
 * It is possible for us (Synapse) to cause the creation of a duplicate relatesTo as we
 * try to hold onto the outgoing message ID even for POX messages using the relates to
 * Now once we get a response, make sure we remove any trace of this before we proceed any
 * further
 * @param mc the message context from which a possibly duplicated relatesTo should be removed
 * @param relates the existing relatedTo array of the message
 */
private void removeDuplicateRelatesTo(MessageContext mc, RelatesTo[] relates) {
    int insertPos = 0;
    RelatesTo[] newRelates = new RelatesTo[relates.length];
    for (RelatesTo current : relates) {
        boolean found = false;
        for (int j = 0; j < newRelates.length && j < insertPos; j++) {
            if (newRelates[j].equals(current) || newRelates[j].getValue().equals(current.getValue())) {
                found = true;
                break;
            }
        }
        if (!found) {
            newRelates[insertPos++] = current;
        }
    }
    RelatesTo[] trimmedRelates = new RelatesTo[insertPos];
    System.arraycopy(newRelates, 0, trimmedRelates, 0, insertPos);
    mc.setRelationships(trimmedRelates);
}
Also used : Endpoint(org.apache.synapse.endpoints.Endpoint) AbstractEndpoint(org.apache.synapse.endpoints.AbstractEndpoint) FailoverEndpoint(org.apache.synapse.endpoints.FailoverEndpoint) RelatesTo(org.apache.axis2.addressing.RelatesTo)

Example 5 with RelatesTo

use of org.apache.axis2.addressing.RelatesTo in project carbon-apimgt by wso2.

the class Utils method setSOAPFault.

public static void setSOAPFault(MessageContext messageContext, String code, String reason, String detail) {
    SOAPFactory factory = (messageContext.isSOAP11() ? OMAbstractFactory.getSOAP11Factory() : OMAbstractFactory.getSOAP12Factory());
    OMDocument soapFaultDocument = factory.createOMDocument();
    SOAPEnvelope faultEnvelope = factory.getDefaultFaultEnvelope();
    soapFaultDocument.addChild(faultEnvelope);
    SOAPFault fault = faultEnvelope.getBody().getFault();
    if (fault == null) {
        fault = factory.createSOAPFault();
    }
    SOAPFaultCode faultCode = factory.createSOAPFaultCode();
    if (messageContext.isSOAP11()) {
        faultCode.setText(new QName(fault.getNamespace().getNamespaceURI(), code));
    } else {
        SOAPFaultValue value = factory.createSOAPFaultValue(faultCode);
        value.setText(new QName(fault.getNamespace().getNamespaceURI(), code));
    }
    fault.setCode(faultCode);
    SOAPFaultReason faultReason = factory.createSOAPFaultReason();
    if (messageContext.isSOAP11()) {
        faultReason.setText(reason);
    } else {
        SOAPFaultText text = factory.createSOAPFaultText();
        text.setText(reason);
        text.setLang("en");
        faultReason.addSOAPText(text);
    }
    fault.setReason(faultReason);
    SOAPFaultDetail soapFaultDetail = factory.createSOAPFaultDetail();
    soapFaultDetail.setText(detail);
    fault.setDetail(soapFaultDetail);
    // set the all headers of original SOAP Envelope to the Fault Envelope
    if (messageContext.getEnvelope() != null) {
        SOAPHeader soapHeader = messageContext.getEnvelope().getHeader();
        if (soapHeader != null) {
            for (Iterator iterator = soapHeader.examineAllHeaderBlocks(); iterator.hasNext(); ) {
                Object o = iterator.next();
                if (o instanceof SOAPHeaderBlock) {
                    SOAPHeaderBlock header = (SOAPHeaderBlock) o;
                    faultEnvelope.getHeader().addChild(header);
                } else if (o instanceof OMElement) {
                    faultEnvelope.getHeader().addChild((OMElement) o);
                }
            }
        }
    }
    try {
        messageContext.setEnvelope(faultEnvelope);
    } catch (AxisFault af) {
        log.error("Error while setting SOAP fault as payload", af);
        return;
    }
    if (messageContext.getFaultTo() != null) {
        messageContext.setTo(messageContext.getFaultTo());
    } else if (messageContext.getReplyTo() != null) {
        messageContext.setTo(messageContext.getReplyTo());
    } else {
        messageContext.setTo(null);
    }
    // set original messageID as relatesTo
    if (messageContext.getMessageID() != null) {
        RelatesTo relatesTo = new RelatesTo(messageContext.getMessageID());
        messageContext.setRelatesTo(new RelatesTo[] { relatesTo });
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) SOAPFaultCode(org.apache.axiom.soap.SOAPFaultCode) QName(javax.xml.namespace.QName) SOAPFaultReason(org.apache.axiom.soap.SOAPFaultReason) SOAPFaultValue(org.apache.axiom.soap.SOAPFaultValue) SOAPFaultDetail(org.apache.axiom.soap.SOAPFaultDetail) SOAPHeaderBlock(org.apache.axiom.soap.SOAPHeaderBlock) OMElement(org.apache.axiom.om.OMElement) SOAPEnvelope(org.apache.axiom.soap.SOAPEnvelope) SOAPFaultText(org.apache.axiom.soap.SOAPFaultText) SOAPFactory(org.apache.axiom.soap.SOAPFactory) RelatesTo(org.apache.axis2.addressing.RelatesTo) OMDocument(org.apache.axiom.om.OMDocument) SOAPFault(org.apache.axiom.soap.SOAPFault) JSONObject(org.json.JSONObject) SOAPHeader(org.apache.axiom.soap.SOAPHeader)

Aggregations

RelatesTo (org.apache.axis2.addressing.RelatesTo)8 EndpointReference (org.apache.axis2.addressing.EndpointReference)4 Map (java.util.Map)3 SOAPEnvelope (org.apache.axiom.soap.SOAPEnvelope)3 HashMap (java.util.HashMap)2 Stack (java.util.Stack)2 OMElement (org.apache.axiom.om.OMElement)2 SOAPHeader (org.apache.axiom.soap.SOAPHeader)2 AxisFault (org.apache.axis2.AxisFault)2 AxisOperation (org.apache.axis2.description.AxisOperation)2 MessageContext (org.apache.synapse.MessageContext)2 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)2 AbstractEndpoint (org.apache.synapse.endpoints.AbstractEndpoint)2 Endpoint (org.apache.synapse.endpoints.Endpoint)2 FailoverEndpoint (org.apache.synapse.endpoints.FailoverEndpoint)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 Format (java.text.Format)1 SimpleDateFormat (java.text.SimpleDateFormat)1 ArrayList (java.util.ArrayList)1