Search in sources :

Example 21 with EndpointReference

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

the class JsonStreamingBuilderTest method testProcessDocumentNoJsonPayload.

public void testProcessDocumentNoJsonPayload() throws AxisFault {
    String defaultEnvelope = "<?xml version='1.0' encoding='utf-8'?>" + "<soapenv:Envelope xmlns:soapenv=\"http://www.w3.org/2003/05/soap-envelope\">" + "<soapenv:Body />" + "</soapenv:Envelope>";
    MessageContext messageContext = Util.newMessageContext();
    messageContext.setTo(new EndpointReference("http://localhost:8000"));
    Builder jsonBuilder = Util.newJsonStreamBuilder();
    OMElement element = jsonBuilder.processDocument(null, "application/json", messageContext);
    assertEquals("Default envelope expected", defaultEnvelope, element.toString());
}
Also used : Builder(org.apache.axis2.builder.Builder) OMElement(org.apache.axiom.om.OMElement) MessageContext(org.apache.axis2.context.MessageContext) EndpointReference(org.apache.axis2.addressing.EndpointReference)

Example 22 with EndpointReference

use of org.apache.axis2.addressing.EndpointReference 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);
        }
    }
    // get the original message context that went through the OAuth Configured HTTP endpoint
    // this is used to retry the call when there is any oauth related issue
    org.apache.synapse.MessageContext originalMC = MessageCache.getInstance().removeMessageContext(synapseOutMsgCtx.getMessageID());
    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.
        // We have to clone the message context to avoid Intermittently ConcurrentModificationException when request
        // burst on passthrough transport
        Axis2MessageContext axis2MC = (Axis2MessageContext) synapseOutMsgCtx;
        axis2MC.setAxis2MessageContext(MessageHelper.cloneAxis2MessageContext(((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext(), true, true, false));
        Pipe pipe = (Pipe) ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext().getProperty(PassThroughConstants.PASS_THROUGH_PIPE);
        SourceConfiguration sourceConfiguration = (SourceConfiguration) ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext().getProperty("PASS_THROUGH_SOURCE_CONFIGURATION");
        if (pipe != null && pipe.isSerializationComplete() && sourceConfiguration != null) {
            NHttpServerConnection conn = (NHttpServerConnection) ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext().getProperty("pass-through.Source-Connection");
            Pipe newPipe = new Pipe(conn, sourceConfiguration.getBufferFactory().getBuffer(), "source", sourceConfiguration);
            newPipe.setDiscardable(true);
            ((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);
            /* Clear the NO_KEEPALIVE property to prevent closing response connection when going through
                   the fault sequence due to sender error. Since the axis2 message context used here
                   is the same axis2 message context used in request path and the intention of this property
                   is to Disable HTTP keep alive for outgoing requests only. If it is required this can be put
                   in fault sequence.
               */
            ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext().removeProperty(PassThroughConstants.NO_KEEPALIVE);
            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() + "]");
            }
            Integer 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 != null && 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(CorrelationConstants.CORRELATION_ID, axisOutMsgCtx.getProperty(CorrelationConstants.CORRELATION_ID));
        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;
        boolean failOver = isChildOfFailOverEP(successfulEndpoint);
        if (Constants.VALUE_TRUE.equals(errorOnSOAPFault) && successfulEndpoint != null) {
            if (log.isDebugEnabled()) {
                log.debug("FORCE_ERROR_ON_SOAP_FAULT is true, checking for SOAPFault");
            }
            try {
                org.apache.axis2.context.MessageContext axis2MsgCtx = ((Axis2MessageContext) synapseInMessageContext).getAxis2MessageContext();
                MessageHandlerProvider.getMessageHandler(axis2MsgCtx).buildMessage(axis2MsgCtx, true);
            } catch (Exception e) {
            // handleException("Error while building message", e, synapseInMessageContext);
            }
            if ((synapseInMessageContext.getEnvelope() != null) && synapseInMessageContext.getEnvelope().hasFault()) {
                invokeHandlers(synapseInMessageContext);
                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");
                SourceConfiguration sourceConfiguration = (SourceConfiguration) axis2OUTMC.getProperty("PASS_THROUGH_SOURCE_CONFIGURATION");
                if (conn != null && sourceConfiguration != null) {
                    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);
                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();
                if (failOver) {
                    popFailOverEPFromFaultStack(synapseOutMsgCtx);
                }
            }
        } else if (successfulEndpoint != null) {
            successfulEndpoint.onSuccess();
            if (failOver) {
                popFailOverEPFromFaultStack(synapseOutMsgCtx);
            }
        }
        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));
        }
        if (successfulEndpoint instanceof OAuthConfiguredHTTPEndpoint) {
            OAuthConfiguredHTTPEndpoint httpEndpoint = (OAuthConfiguredHTTPEndpoint) successfulEndpoint;
            if (originalMC != null && OAuthUtils.retryOnOAuthFailure(httpEndpoint, synapseInMessageContext, synapseOutMsgCtx)) {
                httpEndpoint.retryCallWithNewToken(originalMC);
                return;
            }
        }
        // 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));
            }
            faultStack = synapseOutMsgCtx.getFaultStack();
            if (faultStack != null) {
                synapseInMessageContext.getFaultStack().addAll(faultStack);
            }
        }
        // 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()) {
                ((FaultHandler) stack.pop()).handleFault(synapseInMessageContext, syne);
            } else {
                log.error("Synapse encountered an exception, " + "No error handlers found - [Message Dropped]\n" + syne.getMessage());
            }
        }
    }
}
Also used : OAuthConfiguredHTTPEndpoint(org.apache.synapse.endpoints.OAuthConfiguredHTTPEndpoint) Dispatcher(org.apache.synapse.endpoints.dispatch.Dispatcher) RelatesTo(org.apache.axis2.addressing.RelatesTo) NHttpServerConnection(org.apache.http.nio.NHttpServerConnection) OAuthConfiguredHTTPEndpoint(org.apache.synapse.endpoints.OAuthConfiguredHTTPEndpoint) 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) Pipe(org.apache.synapse.transport.passthru.Pipe) OAuthConfiguredHTTPEndpoint(org.apache.synapse.endpoints.OAuthConfiguredHTTPEndpoint) 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) MessageContext(org.apache.axis2.context.MessageContext)

Example 23 with EndpointReference

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

the class SynapseDebugManager method setAxis2Property.

private void setAxis2Property(String propertyKey, String propertyValue, org.apache.axis2.context.MessageContext axis2MessageCtx) {
    // Do not change the Envelope, SoapHeaders and Transport Headers
    switch(propertyKey) {
        case SynapseDebugCommandConstants.AXIS2_PROPERTY_TO:
            axis2MessageCtx.setTo(new EndpointReference(propertyValue));
            break;
        case SynapseDebugCommandConstants.AXIS2_PROPERTY_FROM:
            axis2MessageCtx.setFrom(new EndpointReference(propertyValue));
            break;
        case SynapseDebugCommandConstants.AXIS2_PROPERTY_WSACTION:
            axis2MessageCtx.setWSAAction(propertyValue);
            break;
        case SynapseDebugCommandConstants.AXIS2_PROPERTY_SOAPACTION:
            axis2MessageCtx.setSoapAction(propertyValue);
            break;
        case SynapseDebugCommandConstants.AXIS2_PROPERTY_REPLY_TO:
            axis2MessageCtx.setReplyTo(new EndpointReference(propertyValue));
            break;
        case SynapseDebugCommandConstants.AXIS2_PROPERTY_MESSAGE_ID:
            axis2MessageCtx.setMessageID(propertyValue);
            break;
        case SynapseDebugCommandConstants.AXIS2_PROPERTY_MESSAGE_TYPE:
            axis2MessageCtx.setProperty("messageType", propertyValue);
            break;
        case SynapseDebugCommandConstants.AXIS2_PROPERTY_DIRECTION:
            if ("response".equalsIgnoreCase(propertyValue)) {
                synCtx.setResponse(true);
            } else if ("request".equalsIgnoreCase(propertyValue)) {
                synCtx.setResponse(false);
            } else {
                log.warn("unknown axis2 direction : " + propertyValue);
            }
            break;
        default:
            // MessageType, ContentType, ExcessTransportHeaders and other properties
            axis2MessageCtx.setProperty(propertyKey, propertyValue);
            Map<String, Set<String>> scopePropertiesMap;
            Set<String> axis2PropertyKeySet;
            String axis2MessageCtxKey = getAxis2MessagePropertiesKey(axis2MessageCtx);
            if (addedPropertyValuesMap.containsKey(axis2MessageCtxKey)) {
                scopePropertiesMap = (Map) addedPropertyValuesMap.get(axis2MessageCtxKey);
                if (scopePropertiesMap.containsKey(SynapseDebugCommandConstants.DEBUG_COMMAND_PROPERTY_CONTEXT_AXIS2)) {
                    axis2PropertyKeySet = scopePropertiesMap.get(SynapseDebugCommandConstants.DEBUG_COMMAND_PROPERTY_CONTEXT_AXIS2);
                } else {
                    axis2PropertyKeySet = new HashSet<>();
                }
                axis2PropertyKeySet.add(propertyKey);
            } else {
                scopePropertiesMap = new HashMap<>();
                axis2PropertyKeySet = new HashSet<>();
                axis2PropertyKeySet.add(propertyKey);
            }
            scopePropertiesMap.put(SynapseDebugCommandConstants.DEBUG_COMMAND_PROPERTY_CONTEXT_AXIS2, axis2PropertyKeySet);
            addedPropertyValuesMap.put(axis2MessageCtxKey, scopePropertiesMap);
    }
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) EndpointReference(org.apache.axis2.addressing.EndpointReference)

Example 24 with EndpointReference

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

the class BlockingMsgSender method send.

/**
 * Blocking Invocation
 *
 * @param endpointDefinition the endpoint being sent to.
 * @param synapseInMsgCtx the outgoing synapse message.
 * @throws AxisFault on errors.
 */
public void send(EndpointDefinition endpointDefinition, MessageContext synapseInMsgCtx) throws AxisFault {
    if (log.isDebugEnabled()) {
        log.debug("Start Sending the Message ");
    }
    org.apache.axis2.context.MessageContext axisInMsgCtx = ((Axis2MessageContext) synapseInMsgCtx).getAxis2MessageContext();
    org.apache.axis2.context.MessageContext axisOutMsgCtx = new org.apache.axis2.context.MessageContext();
    String endpointReferenceValue = null;
    if (endpointDefinition.getAddress() != null) {
        endpointReferenceValue = endpointDefinition.getAddress();
    } else if (axisInMsgCtx.getTo() != null) {
        endpointReferenceValue = axisInMsgCtx.getTo().getAddress();
    } else {
        handleException("Service url, Endpoint or 'To' header is required");
    }
    EndpointReference epr = new EndpointReference(endpointReferenceValue);
    axisOutMsgCtx.setTo(epr);
    AxisService anonymousService;
    if (endpointReferenceValue != null && endpointReferenceValue.startsWith(Constants.TRANSPORT_LOCAL)) {
        configurationContext = axisInMsgCtx.getConfigurationContext();
        anonymousService = AnonymousServiceFactory.getAnonymousService(configurationContext.getAxisConfiguration(), LOCAL_ANON_SERVICE);
    } else {
        anonymousService = AnonymousServiceFactory.getAnonymousService(null, configurationContext.getAxisConfiguration(), endpointDefinition.isAddressingOn() | endpointDefinition.isReliableMessagingOn(), endpointDefinition.isReliableMessagingOn(), endpointDefinition.isSecurityOn(), false);
    }
    axisOutMsgCtx.setConfigurationContext(configurationContext);
    axisOutMsgCtx.setEnvelope(axisInMsgCtx.getEnvelope());
    axisOutMsgCtx.setProperty(HTTPConstants.NON_ERROR_HTTP_STATUS_CODES, axisInMsgCtx.getProperty(HTTPConstants.NON_ERROR_HTTP_STATUS_CODES));
    axisOutMsgCtx.setProperty(HTTPConstants.ERROR_HTTP_STATUS_CODES, axisInMsgCtx.getProperty(HTTPConstants.ERROR_HTTP_STATUS_CODES));
    axisOutMsgCtx.setProperty(SynapseConstants.DISABLE_CHUNKING, axisInMsgCtx.getProperty(SynapseConstants.DISABLE_CHUNKING));
    axisOutMsgCtx.setProperty(SynapseConstants.NO_KEEPALIVE, axisInMsgCtx.getProperty(SynapseConstants.NO_KEEPALIVE));
    axisOutMsgCtx.setProperty(SynapseConstants.NO_DEFAULT_CONTENT_TYPE, axisInMsgCtx.getProperty(SynapseConstants.NO_DEFAULT_CONTENT_TYPE));
    // Fill MessageContext
    BlockingMsgSenderUtils.fillMessageContext(endpointDefinition, axisOutMsgCtx, synapseInMsgCtx);
    if (JsonUtil.hasAJsonPayload(axisInMsgCtx)) {
        JsonUtil.cloneJsonPayload(axisInMsgCtx, axisOutMsgCtx);
    }
    Options clientOptions;
    if (initClientOptions) {
        clientOptions = new Options();
    } else {
        clientOptions = axisInMsgCtx.getOptions();
        clientOptions.setTo(epr);
    }
    // Fill Client options
    BlockingMsgSenderUtils.fillClientOptions(endpointDefinition, clientOptions, synapseInMsgCtx);
    // Update To url if mock-service exists for unit test
    MediatorPropertyUtils.updateSendToUrlForMockServices(endpointDefinition, synapseInMsgCtx, axisOutMsgCtx);
    anonymousService.getParent().addParameter(SynapseConstants.HIDDEN_SERVICE_PARAM, "true");
    ServiceGroupContext serviceGroupContext = new ServiceGroupContext(configurationContext, (AxisServiceGroup) anonymousService.getParent());
    ServiceContext serviceCtx = serviceGroupContext.getServiceContext(anonymousService);
    axisOutMsgCtx.setServiceContext(serviceCtx);
    // Invoke
    boolean isOutOnly = isOutOnly(synapseInMsgCtx, axisOutMsgCtx);
    try {
        if (isOutOnly) {
            sendRobust(axisOutMsgCtx, clientOptions, anonymousService, serviceCtx, synapseInMsgCtx);
            final String httpStatusCode = String.valueOf(axisOutMsgCtx.getProperty(SynapseConstants.HTTP_SENDER_STATUSCODE)).trim();
            /*
                 * Though this is OUT_ONLY operation, we need to set the
                 * response Status code so that others can make use of it.
                 */
            axisInMsgCtx.setProperty(SynapseConstants.HTTP_SC, httpStatusCode);
            synapseInMsgCtx.setProperty(SynapseConstants.BLOCKING_SENDER_ERROR, "false");
        } else {
            org.apache.axis2.context.MessageContext result = sendReceive(axisOutMsgCtx, clientOptions, anonymousService, serviceCtx, synapseInMsgCtx);
            synapseInMsgCtx.setEnvelope(result.getEnvelope());
            if (JsonUtil.hasAJsonPayload(result)) {
                JsonUtil.cloneJsonPayload(result, ((Axis2MessageContext) synapseInMsgCtx).getAxis2MessageContext());
            }
            final String statusCode = String.valueOf(result.getProperty(SynapseConstants.HTTP_SENDER_STATUSCODE)).trim();
            /*
                 * We need to set the response status code so that users can
                 * fetch it later.
                 */
            axisInMsgCtx.setProperty(SynapseConstants.HTTP_SC, statusCode);
            if ("false".equals(synapseInMsgCtx.getProperty(SynapseConstants.BLOCKING_SENDER_PRESERVE_REQ_HEADERS))) {
                axisInMsgCtx.setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, result.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS));
            }
            synapseInMsgCtx.setProperty(SynapseConstants.BLOCKING_SENDER_ERROR, "false");
            this.invokeHandlers(synapseInMsgCtx);
        }
    } catch (Exception ex) {
        /*
             * Extract the HTTP status code from the Exception message.
             */
        final String errorStatusCode = extractStatusCodeFromException(ex);
        axisInMsgCtx.setProperty(SynapseConstants.HTTP_SC, errorStatusCode);
        synapseInMsgCtx.setProperty(SynapseConstants.BLOCKING_SENDER_ERROR, "true");
        synapseInMsgCtx.setProperty(SynapseConstants.ERROR_EXCEPTION, ex);
        if (ex instanceof AxisFault) {
            AxisFault fault = (AxisFault) ex;
            int errorCode = SynapseConstants.BLOCKING_SENDER_OPERATION_FAILED;
            if (fault.getFaultCode() != null && fault.getFaultCode().getLocalPart() != null && !"".equals(fault.getFaultCode().getLocalPart())) {
                try {
                    errorCode = Integer.parseInt(fault.getFaultCode().getLocalPart());
                } catch (NumberFormatException e) {
                    errorCode = SynapseConstants.BLOCKING_SENDER_OPERATION_FAILED;
                }
            }
            synapseInMsgCtx.setProperty(SynapseConstants.ERROR_CODE, errorCode);
            synapseInMsgCtx.setProperty(SynapseConstants.ERROR_MESSAGE, fault.getMessage());
            synapseInMsgCtx.setProperty(SynapseConstants.ERROR_DETAIL, fault.getDetail() != null ? fault.getDetail().getText() : "");
            if (!isOutOnly) {
                org.apache.axis2.context.MessageContext faultMC = fault.getFaultMessageContext();
                if (faultMC != null) {
                    Object statusCode = faultMC.getProperty(SynapseConstants.HTTP_SENDER_STATUSCODE);
                    synapseInMsgCtx.setProperty(SynapseConstants.HTTP_SC, statusCode);
                    axisInMsgCtx.setProperty(SynapseConstants.HTTP_SC, statusCode);
                    synapseInMsgCtx.setEnvelope(faultMC.getEnvelope());
                }
            }
        }
    }
    // get the original message context that went through the OAuth Configured HTTP endpoint
    // this is used to retry the call when there is any oauth related issue
    org.apache.synapse.MessageContext originalMC = MessageCache.getInstance().removeMessageContext(synapseInMsgCtx.getMessageID());
    // Check fault occure when send the request to endpoint
    if ("true".equals(synapseInMsgCtx.getProperty(SynapseConstants.BLOCKING_SENDER_ERROR))) {
        // Handle the fault
        synapseInMsgCtx.getFaultStack().pop().handleFault(synapseInMsgCtx, (Exception) synapseInMsgCtx.getProperty(SynapseConstants.ERROR_EXCEPTION));
    } else {
        // If a message was successfully processed to give it a chance to clear up or reset its state to active
        Stack<FaultHandler> faultStack = synapseInMsgCtx.getFaultStack();
        if (faultStack != null && !faultStack.isEmpty()) {
            AbstractEndpoint successfulEndpoint = null;
            if (faultStack.peek() instanceof AbstractEndpoint) {
                successfulEndpoint = (AbstractEndpoint) faultStack.pop();
                successfulEndpoint.onSuccess();
            }
            if (successfulEndpoint instanceof OAuthConfiguredHTTPEndpoint) {
                OAuthConfiguredHTTPEndpoint httpEndpoint = (OAuthConfiguredHTTPEndpoint) successfulEndpoint;
                if (originalMC != null && OAuthUtils.retryOnOAuthFailure(httpEndpoint, synapseInMsgCtx, synapseInMsgCtx)) {
                    MessageContext messageContext = httpEndpoint.retryCallWithNewToken(originalMC);
                    ((Axis2MessageContext) synapseInMsgCtx).setAxis2MessageContext(((Axis2MessageContext) messageContext).getAxis2MessageContext());
                }
            }
            // Remove all endpoint related fault handlers if any
            while (!faultStack.empty() && faultStack.peek() instanceof AbstractEndpoint) {
                faultStack.pop();
            }
        }
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) Options(org.apache.axis2.client.Options) AbstractEndpoint(org.apache.synapse.endpoints.AbstractEndpoint) ServiceContext(org.apache.axis2.context.ServiceContext) AxisService(org.apache.axis2.description.AxisService) OAuthConfiguredHTTPEndpoint(org.apache.synapse.endpoints.OAuthConfiguredHTTPEndpoint) SynapseException(org.apache.synapse.SynapseException) EndpointReference(org.apache.axis2.addressing.EndpointReference) ServiceGroupContext(org.apache.axis2.context.ServiceGroupContext) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) MessageContext(org.apache.synapse.MessageContext) FaultHandler(org.apache.synapse.FaultHandler) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Example 25 with EndpointReference

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

the class BlockingMsgSender method send.

public MessageContext send(Endpoint endpoint, MessageContext synapseInMsgCtx) throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("Start Sending the Message ");
    }
    if (endpoint instanceof IndirectEndpoint) {
        String endpointKey = ((IndirectEndpoint) endpoint).getKey();
        endpoint = synapseInMsgCtx.getEndpoint(endpointKey);
    }
    if (endpoint instanceof TemplateEndpoint) {
        endpoint = ((TemplateEndpoint) endpoint).getRealEndpoint();
    }
    // get the correct endpoint definition
    if (endpoint instanceof ResolvingEndpoint) {
        SynapseXPath keyExpression = ((ResolvingEndpoint) endpoint).getKeyExpression();
        String key = keyExpression.stringValueOf(synapseInMsgCtx);
        endpoint = ((ResolvingEndpoint) endpoint).loadAndInitEndpoint(((Axis2MessageContext) synapseInMsgCtx).getAxis2MessageContext().getConfigurationContext(), key);
    }
    AbstractEndpoint abstractEndpoint = (AbstractEndpoint) endpoint;
    if (!abstractEndpoint.isLeafEndpoint()) {
        handleException("Endpoint Type not supported");
    }
    // clear the message context properties related to endpoint in last service invocation
    Set keySet = synapseInMsgCtx.getPropertyKeySet();
    if (keySet != null) {
        keySet.remove(EndpointDefinition.DYNAMIC_URL_VALUE);
    }
    abstractEndpoint.executeEpTypeSpecificFunctions(synapseInMsgCtx);
    EndpointDefinition endpointDefinition = abstractEndpoint.getDefinition();
    org.apache.axis2.context.MessageContext axisInMsgCtx = ((Axis2MessageContext) synapseInMsgCtx).getAxis2MessageContext();
    org.apache.axis2.context.MessageContext axisOutMsgCtx = new org.apache.axis2.context.MessageContext();
    String endpointReferenceValue = null;
    if (endpointDefinition.getAddress() != null) {
        endpointReferenceValue = endpointDefinition.getAddress();
    } else if (axisInMsgCtx.getTo() != null) {
        endpointReferenceValue = axisInMsgCtx.getTo().getAddress();
    } else {
        handleException("Service url, Endpoint or 'To' header is required");
    }
    EndpointReference epr = new EndpointReference(endpointReferenceValue);
    axisOutMsgCtx.setTo(epr);
    AxisService anonymousService;
    if (endpointReferenceValue != null && endpointReferenceValue.startsWith(Constants.TRANSPORT_LOCAL)) {
        configurationContext = axisInMsgCtx.getConfigurationContext();
        anonymousService = AnonymousServiceFactory.getAnonymousService(configurationContext.getAxisConfiguration(), LOCAL_ANON_SERVICE);
    } else {
        anonymousService = AnonymousServiceFactory.getAnonymousService(null, configurationContext.getAxisConfiguration(), endpointDefinition.isAddressingOn() | endpointDefinition.isReliableMessagingOn(), endpointDefinition.isReliableMessagingOn(), endpointDefinition.isSecurityOn(), false);
    }
    axisOutMsgCtx.setConfigurationContext(configurationContext);
    axisOutMsgCtx.setEnvelope(axisInMsgCtx.getEnvelope());
    axisOutMsgCtx.setProperty(HTTPConstants.NON_ERROR_HTTP_STATUS_CODES, axisInMsgCtx.getProperty(HTTPConstants.NON_ERROR_HTTP_STATUS_CODES));
    axisOutMsgCtx.setProperty(HTTPConstants.ERROR_HTTP_STATUS_CODES, axisInMsgCtx.getProperty(HTTPConstants.ERROR_HTTP_STATUS_CODES));
    axisOutMsgCtx.setProperty(SynapseConstants.DISABLE_CHUNKING, axisInMsgCtx.getProperty(SynapseConstants.DISABLE_CHUNKING));
    axisOutMsgCtx.setProperty(SynapseConstants.NO_KEEPALIVE, axisInMsgCtx.getProperty(SynapseConstants.NO_KEEPALIVE));
    // Can't refer to the Axis2 constant 'NO_DEFAULT_CONTENT_TYPE' defined in 1.6.1.wso2v23-SNAPSHOT until
    // an API change is done.
    axisOutMsgCtx.setProperty(SynapseConstants.NO_DEFAULT_CONTENT_TYPE, axisInMsgCtx.getProperty(SynapseConstants.NO_DEFAULT_CONTENT_TYPE));
    // Fill MessageContext
    BlockingMsgSenderUtils.fillMessageContext(endpointDefinition, axisOutMsgCtx, synapseInMsgCtx);
    if (JsonUtil.hasAJsonPayload(axisInMsgCtx)) {
        JsonUtil.cloneJsonPayload(axisInMsgCtx, axisOutMsgCtx);
    }
    Options clientOptions;
    if (initClientOptions) {
        clientOptions = new Options();
    } else {
        clientOptions = axisInMsgCtx.getOptions();
        clientOptions.setTo(epr);
    }
    // Fill Client options
    BlockingMsgSenderUtils.fillClientOptions(endpointDefinition, clientOptions, synapseInMsgCtx);
    anonymousService.getParent().addParameter(SynapseConstants.HIDDEN_SERVICE_PARAM, "true");
    ServiceGroupContext serviceGroupContext = new ServiceGroupContext(configurationContext, (AxisServiceGroup) anonymousService.getParent());
    ServiceContext serviceCtx = serviceGroupContext.getServiceContext(anonymousService);
    axisOutMsgCtx.setServiceContext(serviceCtx);
    // Invoke
    boolean isOutOnly = isOutOnly(synapseInMsgCtx, axisOutMsgCtx);
    try {
        if (isOutOnly) {
            sendRobust(axisOutMsgCtx, clientOptions, anonymousService, serviceCtx, synapseInMsgCtx);
            final String httpStatusCode = String.valueOf(axisOutMsgCtx.getProperty(SynapseConstants.HTTP_SENDER_STATUSCODE)).trim();
            /*
                 * Though this is OUT_ONLY operation, we need to set the
                 * response Status code so that others can make use of it.
                 */
            axisInMsgCtx.setProperty(SynapseConstants.HTTP_SC, httpStatusCode);
        } else {
            org.apache.axis2.context.MessageContext result = sendReceive(axisOutMsgCtx, clientOptions, anonymousService, serviceCtx, synapseInMsgCtx);
            if (result.getEnvelope() != null) {
                synapseInMsgCtx.setEnvelope(result.getEnvelope());
                if (JsonUtil.hasAJsonPayload(result)) {
                    JsonUtil.cloneJsonPayload(result, ((Axis2MessageContext) synapseInMsgCtx).getAxis2MessageContext());
                }
            }
            final String statusCode = String.valueOf(result.getProperty(SynapseConstants.HTTP_SENDER_STATUSCODE)).trim();
            /*
                 * We need to set the response status code so that users can
                 * fetch it later.
                 */
            axisInMsgCtx.setProperty(SynapseConstants.HTTP_SC, statusCode);
            if ("false".equals(synapseInMsgCtx.getProperty(SynapseConstants.BLOCKING_SENDER_PRESERVE_REQ_HEADERS))) {
                axisInMsgCtx.setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, result.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS));
            }
            synapseInMsgCtx.setProperty(SynapseConstants.BLOCKING_SENDER_ERROR, "false");
            this.invokeHandlers(synapseInMsgCtx);
            return synapseInMsgCtx;
        }
    } catch (Exception ex) {
        /*
             * Extract the HTTP status code from the Exception message.
             */
        final String errorStatusCode = extractStatusCodeFromException(ex);
        axisInMsgCtx.setProperty(SynapseConstants.HTTP_SC, errorStatusCode);
        if (!isOutOnly) {
            // axisOutMsgCtx.getTransportOut().getSender().cleanup(axisOutMsgCtx);
            synapseInMsgCtx.setProperty(SynapseConstants.BLOCKING_SENDER_ERROR, "true");
            synapseInMsgCtx.setProperty(SynapseConstants.ERROR_EXCEPTION, ex);
            if (ex instanceof AxisFault) {
                AxisFault fault = (AxisFault) ex;
                setErrorDetails(synapseInMsgCtx, fault);
                org.apache.axis2.context.MessageContext faultMC = fault.getFaultMessageContext();
                if (faultMC != null) {
                    Object statusCode = faultMC.getProperty(SynapseConstants.HTTP_SENDER_STATUSCODE);
                    synapseInMsgCtx.setProperty(SynapseConstants.HTTP_SC, statusCode);
                    axisInMsgCtx.setProperty(SynapseConstants.HTTP_SC, statusCode);
                    synapseInMsgCtx.setEnvelope(faultMC.getEnvelope());
                }
            }
            return synapseInMsgCtx;
        } else {
            if (ex instanceof AxisFault) {
                AxisFault fault = (AxisFault) ex;
                setErrorDetails(synapseInMsgCtx, fault);
            }
        }
        handleException("Error sending Message to url : " + ((AbstractEndpoint) endpoint).getDefinition().getAddress(), ex);
    }
    return null;
}
Also used : AxisFault(org.apache.axis2.AxisFault) ResolvingEndpoint(org.apache.synapse.endpoints.ResolvingEndpoint) SynapseXPath(org.apache.synapse.util.xpath.SynapseXPath) AbstractEndpoint(org.apache.synapse.endpoints.AbstractEndpoint) Options(org.apache.axis2.client.Options) IndirectEndpoint(org.apache.synapse.endpoints.IndirectEndpoint) Set(java.util.Set) ServiceContext(org.apache.axis2.context.ServiceContext) AxisService(org.apache.axis2.description.AxisService) EndpointDefinition(org.apache.synapse.endpoints.EndpointDefinition) SynapseException(org.apache.synapse.SynapseException) EndpointReference(org.apache.axis2.addressing.EndpointReference) ServiceGroupContext(org.apache.axis2.context.ServiceGroupContext) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) TemplateEndpoint(org.apache.synapse.endpoints.TemplateEndpoint) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Aggregations

EndpointReference (org.apache.axis2.addressing.EndpointReference)126 Options (org.apache.axis2.client.Options)49 ServiceClient (org.apache.axis2.client.ServiceClient)29 OMElement (org.apache.axiom.om.OMElement)26 AxisFault (org.apache.axis2.AxisFault)26 ConfigurationContext (org.apache.axis2.context.ConfigurationContext)25 MessageContext (org.apache.axis2.context.MessageContext)25 MessageContext (org.apache.synapse.MessageContext)25 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)25 Map (java.util.Map)20 Test (org.junit.Test)14 URL (java.net.URL)13 HttpTransportProperties (org.apache.axis2.transport.http.HttpTransportProperties)13 SynapseConfiguration (org.apache.synapse.config.SynapseConfiguration)13 QName (javax.xml.namespace.QName)12 AxisService (org.apache.axis2.description.AxisService)12 SOAPEnvelope (org.apache.axiom.soap.SOAPEnvelope)11 MalformedURLException (java.net.MalformedURLException)10 ArrayList (java.util.ArrayList)10 HashMap (java.util.HashMap)10