Search in sources :

Example 51 with Axis2MessageContext

use of org.apache.synapse.core.axis2.Axis2MessageContext in project wso2-synapse by wso2.

the class RewriteRule method getHeaders.

private Map<String, String> getHeaders(MessageContext synCtx) {
    Axis2MessageContext axis2smc = (Axis2MessageContext) synCtx;
    org.apache.axis2.context.MessageContext axis2MessageCtx = axis2smc.getAxis2MessageContext();
    Object headers = axis2MessageCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
    Map<String, String> evaluatorHeaders = new HashMap<String, String>();
    if (headers != null && headers instanceof Map) {
        Map headersMap = (Map) headers;
        for (Object entryObj : headersMap.entrySet()) {
            Map.Entry entry = (Map.Entry) entryObj;
            if (entry.getKey() instanceof String && entry.getValue() instanceof String) {
                evaluatorHeaders.put((String) entry.getKey(), (String) entry.getValue());
            }
        }
    }
    return evaluatorHeaders;
}
Also used : HashMap(java.util.HashMap) Map(java.util.Map) HashMap(java.util.HashMap) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Example 52 with Axis2MessageContext

use of org.apache.synapse.core.axis2.Axis2MessageContext in project wso2-synapse by wso2.

the class BlockingMsgSenderUtils method fillMessageContext.

/**
 * Fill the target message context extracting the required properties of the original message
 * context and the endpoint
 *
 * @param endpoint endpoint definition
 * @param axisOutMsgCtx target message axis2 context
 * @param synapseInMsgCtx original synapse message context
 * @throws org.apache.axis2.AxisFault
 */
public static void fillMessageContext(EndpointDefinition endpoint, org.apache.axis2.context.MessageContext axisOutMsgCtx, MessageContext synapseInMsgCtx) throws AxisFault {
    org.apache.axis2.context.MessageContext axisInMsgCtx = ((Axis2MessageContext) synapseInMsgCtx).getAxis2MessageContext();
    // Copy properties
    setProperties(axisInMsgCtx, axisOutMsgCtx);
    // Copy Transport headers
    axisOutMsgCtx.setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, axisInMsgCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS));
    // Endpoint format
    if (endpoint.getFormat() != null) {
        String format = endpoint.getFormat();
        if (SynapseConstants.FORMAT_POX.equals(format)) {
            axisOutMsgCtx.setDoingREST(true);
            axisOutMsgCtx.setProperty(Constants.Configuration.MESSAGE_TYPE, org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_XML);
            axisOutMsgCtx.setProperty(Constants.Configuration.CONTENT_TYPE, org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_XML);
        } else if (SynapseConstants.FORMAT_GET.equals(format)) {
            axisOutMsgCtx.setDoingREST(true);
            axisOutMsgCtx.setProperty(Constants.Configuration.HTTP_METHOD, Constants.Configuration.HTTP_METHOD_GET);
            axisOutMsgCtx.setProperty(Constants.Configuration.MESSAGE_TYPE, org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_X_WWW_FORM);
        } else if (SynapseConstants.FORMAT_SOAP11.equals(format)) {
            axisOutMsgCtx.setDoingREST(false);
            axisOutMsgCtx.removeProperty(Constants.Configuration.MESSAGE_TYPE);
            // We need to set this explicitly here in case the request was not a POST
            axisOutMsgCtx.setProperty(Constants.Configuration.HTTP_METHOD, Constants.Configuration.HTTP_METHOD_POST);
            if (axisOutMsgCtx.getSoapAction() == null && axisOutMsgCtx.getWSAAction() != null) {
                axisOutMsgCtx.setSoapAction(axisOutMsgCtx.getWSAAction());
            }
            if (!axisOutMsgCtx.isSOAP11()) {
                SOAPUtils.convertSOAP12toSOAP11(axisOutMsgCtx);
            }
        } else if (SynapseConstants.FORMAT_SOAP12.equals(format)) {
            axisOutMsgCtx.setDoingREST(false);
            axisOutMsgCtx.removeProperty(Constants.Configuration.MESSAGE_TYPE);
            // We need to set this explicitly here in case the request was not a POST
            axisOutMsgCtx.setProperty(Constants.Configuration.HTTP_METHOD, Constants.Configuration.HTTP_METHOD_POST);
            if (axisOutMsgCtx.getSoapAction() == null && axisOutMsgCtx.getWSAAction() != null) {
                axisOutMsgCtx.setSoapAction(axisOutMsgCtx.getWSAAction());
            }
            if (axisOutMsgCtx.isSOAP11()) {
                SOAPUtils.convertSOAP11toSOAP12(axisOutMsgCtx);
            }
        } else if (SynapseConstants.FORMAT_REST.equals(format)) {
            if (axisInMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD) != null) {
                if (axisInMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD).toString().equals(Constants.Configuration.HTTP_METHOD_GET) || axisInMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD).toString().equals(Constants.Configuration.HTTP_METHOD_DELETE)) {
                    axisOutMsgCtx.removeProperty(Constants.Configuration.MESSAGE_TYPE);
                }
            }
            axisOutMsgCtx.setDoingREST(true);
        }
    }
    // MTOM/SWA
    if (endpoint.isUseMTOM()) {
        axisOutMsgCtx.setDoingMTOM(true);
        // fix / workaround for AXIS2-1798
        axisOutMsgCtx.setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_TRUE);
        axisOutMsgCtx.setDoingMTOM(true);
    } else if (endpoint.isUseSwa()) {
        axisOutMsgCtx.setDoingSwA(true);
        // fix / workaround for AXIS2-1798
        axisOutMsgCtx.setProperty(Constants.Configuration.ENABLE_SWA, Constants.VALUE_TRUE);
        axisOutMsgCtx.setDoingSwA(true);
    }
    if (endpoint.getCharSetEncoding() != null) {
        axisOutMsgCtx.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, endpoint.getCharSetEncoding());
    }
    // HTTP Endpoint : use the specified HTTP method TODO: Remove this after refactoring Http Endpoint logic
    if (endpoint.isHTTPEndpoint()) {
        axisOutMsgCtx.setProperty(Constants.Configuration.HTTP_METHOD, synapseInMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD));
    }
    boolean isRest = SynapseConstants.FORMAT_REST.equals(endpoint.getFormat()) | axisInMsgCtx.isDoingREST();
    if (!isRest && !endpoint.isForceSOAP11() && !endpoint.isForceSOAP12()) {
        isRest = isRequestRest(axisInMsgCtx);
    }
    String restURLPostfix = (String) axisOutMsgCtx.getProperty(NhttpConstants.REST_URL_POSTFIX);
    if (endpoint.getAddress() != null) {
        String address = endpoint.getAddress(synapseInMsgCtx);
        if (isRest && restURLPostfix != null && !"".equals(restURLPostfix)) {
            address = getEPRWithRestURLPostfix(restURLPostfix, address);
        }
        axisOutMsgCtx.setTo(new EndpointReference(address));
    } else {
        EndpointReference endpointReference = axisOutMsgCtx.getTo();
        if (endpointReference != null) {
            if (isRest && restURLPostfix != null && !"".equals(restURLPostfix)) {
                String address = endpointReference.getAddress();
                address = getEPRWithRestURLPostfix(restURLPostfix, address);
                axisOutMsgCtx.setTo(new EndpointReference(address));
            } else {
                axisInMsgCtx.setTo(endpointReference);
            }
        }
    }
    if (endpoint.isUseSeparateListener()) {
        axisOutMsgCtx.getOptions().setUseSeparateListener(true);
    }
    // set the SEND_TIMEOUT for transport sender
    if (endpoint.getEffectiveTimeout() > 0) {
        if (!endpoint.isDynamicTimeoutEndpoint()) {
            axisOutMsgCtx.setProperty(SynapseConstants.SEND_TIMEOUT, endpoint.getEffectiveTimeout());
        } else {
            axisOutMsgCtx.setProperty(SynapseConstants.SEND_TIMEOUT, endpoint.evaluateDynamicEndpointTimeout(synapseInMsgCtx));
        }
    }
    // Check for preserve WS-Addressing
    String preserveAddressingProperty = (String) synapseInMsgCtx.getProperty(SynapseConstants.PRESERVE_WS_ADDRESSING);
    if (preserveAddressingProperty != null && Boolean.parseBoolean(preserveAddressingProperty)) {
        axisOutMsgCtx.setMessageID(axisInMsgCtx.getMessageID());
    } else {
        MessageHelper.removeAddressingHeaders(axisOutMsgCtx);
        axisOutMsgCtx.setProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES, Boolean.TRUE);
    }
}
Also used : Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) EndpointReference(org.apache.axis2.addressing.EndpointReference)

Example 53 with Axis2MessageContext

use of org.apache.synapse.core.axis2.Axis2MessageContext in project wso2-synapse by wso2.

the class API method handleResourceNotFound.

/**
 * Helper method to use when no matching resource found
 *
 * @param synCtx
 */
private void handleResourceNotFound(MessageContext synCtx) {
    auditDebug("No matching resource was found for the request: " + synCtx.getMessageID());
    Mediator sequence = synCtx.getSequence(RESTConstants.NO_MATCHING_RESOURCE_HANDLER);
    if (sequence != null) {
        sequence.mediate(synCtx);
    } else {
        // Matching resource with method not found
        org.apache.axis2.context.MessageContext msgCtx = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
        msgCtx.setProperty(SynapseConstants.HTTP_SC, HttpStatus.SC_NOT_FOUND);
        msgCtx.removeProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
        msgCtx.setProperty("NIO-ACK-Requested", true);
    }
}
Also used : Mediator(org.apache.synapse.Mediator) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Example 54 with Axis2MessageContext

use of org.apache.synapse.core.axis2.Axis2MessageContext in project wso2-synapse by wso2.

the class API method process.

void process(MessageContext synCtx) {
    auditDebug("Processing message with ID: " + synCtx.getMessageID() + " through the " + "API: " + name);
    synCtx.setProperty(RESTConstants.SYNAPSE_REST_API, getName());
    synCtx.setProperty(RESTConstants.SYNAPSE_REST_API_VERSION, versionStrategy.getVersion());
    synCtx.setProperty(RESTConstants.REST_API_CONTEXT, context);
    synCtx.setProperty(RESTConstants.SYNAPSE_REST_API_VERSION_STRATEGY, versionStrategy.getVersionType());
    // get API log for this message and attach to the message context
    ((Axis2MessageContext) synCtx).setServiceLog(apiLog);
    // Calculate REST_URL_POSTFIX from full request path
    String restURLPostfix = (String) synCtx.getProperty(RESTConstants.REST_FULL_REQUEST_PATH);
    if (!synCtx.isResponse() && restURLPostfix != null) {
        // Skip for response path
        if (!restURLPostfix.startsWith("/")) {
            restURLPostfix = "/" + restURLPostfix;
        }
        if (restURLPostfix.startsWith(context)) {
            restURLPostfix = restURLPostfix.substring(context.length());
        }
        if (versionStrategy instanceof URLBasedVersionStrategy) {
            String version = versionStrategy.getVersion();
            if (restURLPostfix.startsWith(version)) {
                restURLPostfix = restURLPostfix.substring(version.length());
            } else if (restURLPostfix.startsWith("/" + version)) {
                restURLPostfix = restURLPostfix.substring(version.length() + 1);
            }
        }
        ((Axis2MessageContext) synCtx).getAxis2MessageContext().setProperty(NhttpConstants.REST_URL_POSTFIX, restURLPostfix);
    }
    for (Handler handler : handlers) {
        auditDebug("Processing message with ID: " + synCtx.getMessageID() + " through " + "handler: " + handler.getClass().getName());
        boolean proceed;
        if (synCtx.isResponse()) {
            proceed = handler.handleResponse(synCtx);
        } else {
            proceed = handler.handleRequest(synCtx);
        }
        if (!proceed) {
            return;
        }
    }
    if (synCtx.isResponse()) {
        String resourceName = (String) synCtx.getProperty(RESTConstants.SYNAPSE_RESOURCE);
        if (resourceName != null) {
            Resource resource = resources.get(resourceName);
            if (resource != null) {
                resource.process(synCtx);
            }
        } else if (log.isDebugEnabled()) {
            auditDebug("No resource information on the response: " + synCtx.getMessageID());
        }
        return;
    }
    String path = RESTUtils.getFullRequestPath(synCtx);
    String subPath;
    if (versionStrategy.getVersionType().equals(VersionStrategyFactory.TYPE_URL)) {
        // for URL based
        // request --> http://{host:port}/context/version/path/to/resource
        subPath = path.substring(context.length() + versionStrategy.getVersion().length() + 1);
    } else {
        subPath = path.substring(context.length());
    }
    if ("".equals(subPath)) {
        subPath = "/";
    }
    synCtx.setProperty(RESTConstants.REST_SUB_REQUEST_PATH, subPath);
    org.apache.axis2.context.MessageContext msgCtx = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
    String hostHeader = getHostHeader(msgCtx);
    if (hostHeader != null) {
        synCtx.setProperty(RESTConstants.REST_URL_PREFIX, msgCtx.getIncomingTransportName() + "://" + hostHeader);
    }
    Set<Resource> acceptableResources = new LinkedHashSet<Resource>();
    for (Resource r : resources.values()) {
        if (r.canProcess(synCtx)) {
            acceptableResources.add(r);
        }
    }
    boolean processed = false;
    if (!acceptableResources.isEmpty()) {
        for (RESTDispatcher dispatcher : RESTUtils.getDispatchers()) {
            Resource resource = dispatcher.findResource(synCtx, acceptableResources);
            if (resource != null) {
                if (synCtx.getEnvironment().isDebuggerEnabled()) {
                    if (!synCtx.isResponse()) {
                        SynapseWireLogHolder wireLogHolder = (SynapseWireLogHolder) ((Axis2MessageContext) synCtx).getAxis2MessageContext().getProperty(SynapseDebugInfoHolder.SYNAPSE_WIRE_LOG_HOLDER_PROPERTY);
                        if (wireLogHolder == null) {
                            wireLogHolder = new SynapseWireLogHolder();
                        }
                        if (synCtx.getProperty(RESTConstants.SYNAPSE_REST_API) != null && !synCtx.getProperty(RESTConstants.SYNAPSE_REST_API).toString().isEmpty()) {
                            wireLogHolder.setApiName(synCtx.getProperty(RESTConstants.SYNAPSE_REST_API).toString());
                            if (resource.getDispatcherHelper() != null) {
                                if (resource.getDispatcherHelper().getString() != null && !resource.getDispatcherHelper().getString().isEmpty()) {
                                    wireLogHolder.setResourceUrlString(resource.getDispatcherHelper().getString());
                                }
                            }
                        }
                        ((Axis2MessageContext) synCtx).getAxis2MessageContext().setProperty(SynapseDebugInfoHolder.SYNAPSE_WIRE_LOG_HOLDER_PROPERTY, wireLogHolder);
                    }
                }
                resource.process(synCtx);
                return;
            }
        }
        handleResourceNotFound(synCtx);
    } else {
        // This will get executed only in unhappy path. So ok to have the iterator.
        boolean resourceFound = false;
        boolean matchingMethodFound = false;
        for (RESTDispatcher dispatcher : RESTUtils.getDispatchers()) {
            Resource resource = dispatcher.findResource(synCtx, resources.values());
            if (resource != null) {
                resourceFound = true;
                String method = (String) msgCtx.getProperty(Constants.Configuration.HTTP_METHOD);
                matchingMethodFound = resource.hasMatchingMethod(method);
                break;
            }
        }
        if (!resourceFound) {
            handleResourceNotFound(synCtx);
        } else if (resourceFound && !matchingMethodFound) {
            // Resource found, but in that resource, requested method not allowed. So sending method not allowed http status (405)
            msgCtx.setProperty(SynapseConstants.HTTP_SC, HttpStatus.SC_METHOD_NOT_ALLOWED);
            msgCtx.removeProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
            msgCtx.setProperty("NIO-ACK-Requested", true);
        } else {
            // Resource found, and matching method also found, which means request is BAD_REQUEST(400)
            msgCtx.setProperty(SynapseConstants.HTTP_SC, HttpStatus.SC_BAD_REQUEST);
            msgCtx.setProperty("NIO-ACK-Requested", true);
        }
    }
}
Also used : SynapseWireLogHolder(org.apache.synapse.transport.http.conn.SynapseWireLogHolder) RESTDispatcher(org.apache.synapse.rest.dispatch.RESTDispatcher) URLBasedVersionStrategy(org.apache.synapse.rest.version.URLBasedVersionStrategy) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Example 55 with Axis2MessageContext

use of org.apache.synapse.core.axis2.Axis2MessageContext in project wso2-synapse by wso2.

the class ThrottleMediator method mediate.

public boolean mediate(MessageContext synCtx) {
    if (synCtx.getEnvironment().isDebuggerEnabled()) {
        if (super.divertMediationRoute(synCtx)) {
            return true;
        }
    }
    SynapseLog synLog = getLog(synCtx);
    boolean isResponse = synCtx.isResponse();
    boolean canAccess = true;
    if (!isResponse) {
        if (synLog.isTraceOrDebugEnabled()) {
            synLog.traceOrDebug("Start : Throttle mediator");
            if (synLog.isTraceTraceEnabled()) {
                synLog.traceTrace("Message : " + synCtx.getEnvelope());
            }
        }
        // we consider dynamic loading of policy loading only for the request flow mediation
        // we ignore policy initialization for the response flow case we use the existing policy
        // reference throttling only applies for request flow mediation
        doInitializeThrottleDynamicPolicy(synCtx, synLog);
        // checks we need to rollback the previous
        if (concurrentAccessController != null) {
            canAccess = doThrottleByConcurrency(isResponse, synLog);
        }
        // then do access rate based throttling
        if (throttle != null && !isResponse && canAccess) {
            org.apache.axis2.context.MessageContext axisMC = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
            canAccess = doThrottleByAccessRate(synCtx, axisMC, configContext, synLog);
        }
        if (concurrentAccessController != null) {
            // maintain properties in message context for the concurrency throttling
            synCtx.setProperty(SynapseConstants.SYNAPSE_CONCURRENCY_THROTTLE, true);
            // maintain properties in message context for the concurrency throttling
            synCtx.setProperty(SynapseConstants.SYNAPSE_CONCURRENCY_THROTTLE_KEY, key);
            // maintain properties in message context for the concurrency throttling
            synCtx.setProperty(SynapseConstants.SYNAPSE_CONCURRENT_ACCESS_CONTROLLER, concurrentAccessController);
        }
        // maintain properties in message context for the concurrency throttling
        if (isClusteringEnable) {
            synCtx.setProperty(SynapseConstants.SYNAPSE_CONCURRENT_ACCESS_REPLICATOR, concurrentAccessReplicator);
        }
        // onwards mediation flow branches to either accept sequence or reject sequence
        if (canAccess) {
            // to other cluster nodes as synchronous manner
            if (isClusteringEnable && concurrentAccessController != null) {
                if (synLog.isTraceOrDebugEnabled()) {
                    synLog.traceOrDebug("Going to replicates the  " + "states of the ConcurrentAccessController with key : " + key);
                }
                concurrentAccessReplicator.replicate(key, false);
            }
            // accept case
            // property is set to identify whether a request is accepted or rejected looking at
            // the throttling controller outcome.
            synCtx.setProperty(SynapseConstants.SYNAPSE_IS_CONCURRENT_ACCESS_ALLOWED, true);
            if (onAcceptSeqKey != null) {
                Mediator mediator = synCtx.getSequence(onAcceptSeqKey);
                if (mediator != null) {
                    ContinuationStackManager.updateSeqContinuationState(synCtx, getMediatorPosition());
                    return mediator.mediate(synCtx);
                } else {
                    handleException("Unable to find onAccept sequence with key : " + onAcceptSeqKey, synCtx);
                }
            } else if (onAcceptMediator != null) {
                ContinuationStackManager.addReliantContinuationState(synCtx, 0, getMediatorPosition());
                boolean result = onAcceptMediator.mediate(synCtx);
                if (result) {
                    ContinuationStackManager.removeReliantContinuationState(synCtx);
                }
                return result;
            } else {
                return true;
            }
        } else {
            // reject case
            // property is set to identify whether a request is accepted or rejected looking at
            // the throttling controller outcome.
            synCtx.setProperty(SynapseConstants.SYNAPSE_IS_CONCURRENT_ACCESS_ALLOWED, false);
            if (onRejectSeqKey != null) {
                Mediator mediator = synCtx.getSequence(onRejectSeqKey);
                if (mediator != null) {
                    ContinuationStackManager.updateSeqContinuationState(synCtx, getMediatorPosition());
                    return mediator.mediate(synCtx);
                } else {
                    handleException("Unable to find onReject sequence with key : " + onRejectSeqKey, synCtx);
                }
            } else if (onRejectMediator != null) {
                ContinuationStackManager.addReliantContinuationState(synCtx, 1, getMediatorPosition());
                boolean result = onRejectMediator.mediate(synCtx);
                if (result) {
                    ContinuationStackManager.removeReliantContinuationState(synCtx);
                }
                return result;
            } else {
                return false;
            }
        }
    }
    synLog.traceOrDebug("End : Throttle mediator");
    return canAccess;
}
Also used : FlowContinuableMediator(org.apache.synapse.mediators.FlowContinuableMediator) AbstractMediator(org.apache.synapse.mediators.AbstractMediator) SequenceMediator(org.apache.synapse.mediators.base.SequenceMediator) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Aggregations

Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)92 MessageContext (org.apache.synapse.MessageContext)50 Axis2SynapseEnvironment (org.apache.synapse.core.axis2.Axis2SynapseEnvironment)24 Map (java.util.Map)23 HashMap (java.util.HashMap)20 SynapseConfiguration (org.apache.synapse.config.SynapseConfiguration)19 SynapseEnvironment (org.apache.synapse.core.SynapseEnvironment)18 Test (org.junit.Test)16 OMElement (org.apache.axiom.om.OMElement)15 ConfigurationContext (org.apache.axis2.context.ConfigurationContext)14 SynapseException (org.apache.synapse.SynapseException)14 AxisConfiguration (org.apache.axis2.engine.AxisConfiguration)13 ArrayList (java.util.ArrayList)12 SOAPEnvelope (org.apache.axiom.soap.SOAPEnvelope)11 EndpointReference (org.apache.axis2.addressing.EndpointReference)10 SynapseLog (org.apache.synapse.SynapseLog)9 Endpoint (org.apache.synapse.endpoints.Endpoint)9 OperationContext (org.apache.axis2.context.OperationContext)8 AxisFault (org.apache.axis2.AxisFault)7 Entry (org.apache.synapse.config.Entry)7