Search in sources :

Example 1 with SynapseHandler

use of org.apache.synapse.SynapseHandler in project wso2-synapse by wso2.

the class SynapseHandlersLoader method loadHandlers.

/**
 * Load and get all synapse handlers
 *
 * @return List of loaded synapse handlers
 */
public static List<SynapseHandler> loadHandlers() {
    List<SynapseHandler> handlers = new ArrayList<>();
    OMElement handlersConfig = MiscellaneousUtil.loadXMLConfig(SynapseConstants.SYNAPSE_HANDLER_FILE);
    if (handlersConfig != null) {
        if (!ROOT_Q.equals(handlersConfig.getQName())) {
            handleException("Invalid handler configuration file");
        }
        Iterator iterator = handlersConfig.getChildrenWithName(HANDLER_Q);
        while (iterator.hasNext()) {
            OMElement handlerElem = (OMElement) iterator.next();
            String name = null;
            if (handlerElem.getAttribute(NAME_ATT) != null) {
                name = handlerElem.getAttributeValue(NAME_ATT);
            } else {
                handleException("Name not defined in one or more handlers");
            }
            if (handlerElem.getAttribute(CLASS_Q) != null) {
                String className = handlerElem.getAttributeValue(CLASS_Q);
                if (!"".equals(className)) {
                    SynapseHandler handler = createHandler(className);
                    if (handler != null) {
                        handlers.add(handler);
                        handler.setName(name);
                        populateParameters(handlerElem, handler);
                    }
                } else {
                    handleException("Class name is null for handle name : " + name);
                }
            } else {
                handleException("Class name not defined for handler named : " + name);
            }
        }
    }
    return handlers;
}
Also used : ArrayList(java.util.ArrayList) Iterator(java.util.Iterator) OMElement(org.apache.axiom.om.OMElement) SynapseHandler(org.apache.synapse.SynapseHandler)

Example 2 with SynapseHandler

use of org.apache.synapse.SynapseHandler in project wso2-synapse by wso2.

the class Axis2Sender method sendBack.

/**
 * Send a response back to a client of Synapse
 *
 * @param smc the Synapse message context sent as the response
 */
public static void sendBack(org.apache.synapse.MessageContext smc) {
    if (preventMultipleResponses(smc)) {
        return;
    }
    MessageContext messageContext = ((Axis2MessageContext) smc).getAxis2MessageContext();
    // prevent it from going into any other transport sender
    if (messageContext.isPropertyTrue(NhttpConstants.SC_ACCEPTED) && messageContext.getTransportOut() != null && !messageContext.getTransportOut().getName().startsWith(Constants.TRANSPORT_HTTP)) {
        return;
    }
    // fault processing code
    if (messageContext.isDoingREST() && messageContext.isFault() && isMessagePayloadHasASOAPFault(messageContext)) {
        POXUtils.convertSOAPFaultToPOX(messageContext);
    }
    try {
        messageContext.setProperty(SynapseConstants.ISRESPONSE_PROPERTY, Boolean.TRUE);
        if (AddressingHelper.isReplyRedirected(messageContext) && !messageContext.getReplyTo().hasNoneAddress()) {
            messageContext.setTo(messageContext.getReplyTo());
            messageContext.setReplyTo(null);
            messageContext.setWSAAction("");
            messageContext.setSoapAction("");
            messageContext.setProperty(NhttpConstants.IGNORE_SC_ACCEPTED, Constants.VALUE_TRUE);
            messageContext.setProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES, Boolean.FALSE);
        }
        if (messageContext.getEnvelope().hasFault() && AddressingHelper.isFaultRedirected(messageContext) && (messageContext.getFaultTo() == null || !messageContext.getFaultTo().hasNoneAddress())) {
            messageContext.setTo(messageContext.getFaultTo());
            messageContext.setFaultTo(null);
            messageContext.setWSAAction("");
            messageContext.setSoapAction("");
            messageContext.setProperty(NhttpConstants.IGNORE_SC_ACCEPTED, Constants.VALUE_TRUE);
            messageContext.setProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES, Boolean.FALSE);
        }
        String preserveAddressingProperty = (String) smc.getProperty(SynapseConstants.PRESERVE_WS_ADDRESSING);
        if (preserveAddressingProperty != null && Boolean.parseBoolean(preserveAddressingProperty)) {
            /*Avoiding duplicate addressing headers*/
            messageContext.setProperty(AddressingConstants.REPLACE_ADDRESSING_HEADERS, "true");
            messageContext.setMessageID(smc.getMessageID());
        } else {
            MessageHelper.removeAddressingHeaders(messageContext);
            messageContext.setMessageID(UIDGenerator.generateURNString());
        }
        // determine weather we need to preserve the processed headers
        String preserveHeaderProperty = (String) smc.getProperty(SynapseConstants.PRESERVE_PROCESSED_HEADERS);
        if (preserveHeaderProperty == null || !Boolean.parseBoolean(preserveHeaderProperty)) {
            // remove the processed headers
            MessageHelper.removeProcessedHeaders(messageContext, (preserveAddressingProperty != null && Boolean.parseBoolean(preserveAddressingProperty)));
        }
        // temporary workaround for https://issues.apache.org/jira/browse/WSCOMMONS-197
        if (messageContext.isEngaged(SynapseConstants.SECURITY_MODULE_NAME) && messageContext.getEnvelope().getHeader() == null) {
            SOAPFactory fac = messageContext.isSOAP11() ? OMAbstractFactory.getSOAP11Factory() : OMAbstractFactory.getSOAP12Factory();
            fac.createSOAPHeader(messageContext.getEnvelope());
        }
        Axis2FlexibleMEPClient.clearSecurtityProperties(messageContext.getOptions());
        // Invoke Synapse Handlers
        Iterator<SynapseHandler> iterator = smc.getEnvironment().getSynapseHandlers().iterator();
        while (iterator.hasNext()) {
            SynapseHandler handler = iterator.next();
            if (!handler.handleResponseOutFlow(smc)) {
                return;
            }
        }
        doSOAPFormatConversion(smc);
        // handles concurrent throttling based on the messagecontext.
        handleConcurrentThrottleCount(smc);
        // If the request arrives through an inbound endpoint
        if (smc.getProperty(SynapseConstants.IS_INBOUND) != null && (Boolean) smc.getProperty(SynapseConstants.IS_INBOUND)) {
            if (smc.getProperty(InboundEndpointConstants.INBOUND_ENDPOINT_RESPONSE_WORKER) != null) {
                InboundResponseSender inboundResponseSender = (InboundResponseSender) smc.getProperty(InboundEndpointConstants.INBOUND_ENDPOINT_RESPONSE_WORKER);
                inboundResponseSender.sendBack(smc);
            } else {
                String msg = "Inbound Response Sender not found -" + " Inbound Endpoint may not support sending a response back";
                log.error(msg);
                throw new SynapseException(msg);
            }
        } else {
            // If the request arrives through a conventional transport listener
            AxisEngine.send(messageContext);
        }
    } catch (AxisFault e) {
        handleException(getResponseMessage(messageContext), e);
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) SynapseException(org.apache.synapse.SynapseException) MessageContext(org.apache.axis2.context.MessageContext) SynapseHandler(org.apache.synapse.SynapseHandler) SOAPFactory(org.apache.axiom.soap.SOAPFactory) InboundResponseSender(org.apache.synapse.inbound.InboundResponseSender)

Example 3 with SynapseHandler

use of org.apache.synapse.SynapseHandler in project wso2-synapse by wso2.

the class Axis2Sender method sendOn.

/**
 * Send a message out from the Synapse engine to an external service
 *
 * @param endpoint                the endpoint definition where the message should be sent
 * @param synapseInMessageContext the Synapse message context
 */
public static void sendOn(EndpointDefinition endpoint, org.apache.synapse.MessageContext synapseInMessageContext) {
    try {
        // Invoke Synapse Handlers
        Iterator<SynapseHandler> iterator = synapseInMessageContext.getEnvironment().getSynapseHandlers().iterator();
        while (iterator.hasNext()) {
            SynapseHandler handler = iterator.next();
            if (!handler.handleRequestOutFlow(synapseInMessageContext)) {
                return;
            }
        }
        Axis2FlexibleMEPClient.send(// The endpoint where we are sending to
        endpoint, // The Axis2 Message context of the Synapse MC
        synapseInMessageContext);
    } catch (Exception e) {
        handleException("Unexpected error during sending message out", e);
    }
}
Also used : SynapseHandler(org.apache.synapse.SynapseHandler) SynapseException(org.apache.synapse.SynapseException)

Example 4 with SynapseHandler

use of org.apache.synapse.SynapseHandler in project wso2-synapse by wso2.

the class ProxyServiceMessageReceiver method receive.

public void receive(org.apache.axis2.context.MessageContext mc) throws AxisFault {
    boolean traceOn = proxy.getAspectConfiguration().isTracingEnabled();
    boolean traceOrDebugOn = traceOn || log.isDebugEnabled();
    CustomLogSetter.getInstance().setLogAppender(proxy.getArtifactContainerName());
    String remoteAddr = (String) mc.getProperty(org.apache.axis2.context.MessageContext.REMOTE_ADDR);
    if (traceOrDebugOn) {
        traceOrDebug(traceOn, "Proxy Service " + name + " received a new message" + (remoteAddr != null ? " from : " + remoteAddr : "..."));
        traceOrDebug(traceOn, ("Message To: " + (mc.getTo() != null ? mc.getTo().getAddress() : "null")));
        traceOrDebug(traceOn, ("SOAPAction: " + (mc.getSoapAction() != null ? mc.getSoapAction() : "null")));
        traceOrDebug(traceOn, ("WSA-Action: " + (mc.getWSAAction() != null ? mc.getWSAAction() : "null")));
        if (traceOn && trace.isTraceEnabled()) {
            String[] cids = null;
            try {
                cids = mc.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
                mc.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) {
                    trace.trace("With attachment content ID : " + cid);
                }
            }
            trace.trace("Envelope : " + mc.getEnvelope());
        }
    }
    MessageContext synCtx = MessageContextCreatorForAxis2.getSynapseMessageContext(mc);
    Integer statisticReportingIndex = null;
    // Statistic reporting
    boolean isStatisticsEnabled = RuntimeStatisticCollector.isStatisticsEnabled();
    if (isStatisticsEnabled) {
        statisticReportingIndex = OpenEventCollector.reportEntryEvent(synCtx, this.name, proxy.getAspectConfiguration(), ComponentType.PROXYSERVICE);
    }
    Object inboundServiceParam = proxy.getParameterMap().get(SynapseConstants.INBOUND_PROXY_SERVICE_PARAM);
    Object inboundMsgCtxParam = mc.getProperty(SynapseConstants.IS_INBOUND);
    // check whether the message is from Inbound EP
    if (inboundMsgCtxParam == null || !(boolean) inboundMsgCtxParam) {
        // check whether service parameter is set to true or null, then block this request
        if (inboundServiceParam != null && (Boolean.valueOf((String) inboundServiceParam))) {
            /*
                return because same proxy is exposed via InboundEP and service parameter(inbound.only) is set to
                true, which disable normal http transport proxy
                */
            if (!synCtx.getFaultStack().isEmpty()) {
                if (log.isDebugEnabled()) {
                    log.debug("Executing fault handler - message discarded due to the proxy is allowed only via InboundEP");
                }
                (synCtx.getFaultStack().pop()).handleFault(synCtx, new Exception("Proxy Service " + name + " message discarded due to the proxy is allowed only via InboundEP"));
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Proxy Service " + name + " message discarded due to the proxy is " + "allowed only via InboundEP");
                }
            }
            return;
        }
    }
    TenantInfoConfigurator configurator = synCtx.getEnvironment().getTenantInfoConfigurator();
    if (configurator != null) {
        configurator.extractTenantInfo(synCtx);
    }
    TransportInDescription trpInDesc = mc.getTransportIn();
    if (trpInDesc != null) {
        synCtx.setProperty(SynapseConstants.TRANSPORT_IN_NAME, trpInDesc.getName());
    }
    // get service log for this message and attach to the message context also set proxy name
    Log serviceLog = LogFactory.getLog(SynapseConstants.SERVICE_LOGGER_PREFIX + name);
    ((Axis2MessageContext) synCtx).setServiceLog(serviceLog);
    synCtx.setProperty(SynapseConstants.PROXY_SERVICE, name);
    // synCtx.setTracingState(proxy.getTraceState());
    synCtx.setProperty(SynapseConstants.IS_CLIENT_DOING_REST, mc.isDoingREST());
    synCtx.setProperty(SynapseConstants.IS_CLIENT_DOING_SOAP11, mc.isSOAP11());
    try {
        if (synCtx.getEnvironment().isDebuggerEnabled()) {
            SynapseDebugManager debugManager = synCtx.getEnvironment().getSynapseDebugManager();
            debugManager.acquireMediationFlowLock();
            debugManager.advertiseMediationFlowStartPoint(synCtx);
            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(SynapseConstants.PROXY_SERVICE) != null && !synCtx.getProperty(SynapseConstants.PROXY_SERVICE).toString().isEmpty()) {
                    wireLogHolder.setProxyName(synCtx.getProperty(SynapseConstants.PROXY_SERVICE).toString());
                }
                ((Axis2MessageContext) synCtx).getAxis2MessageContext().setProperty(SynapseDebugInfoHolder.SYNAPSE_WIRE_LOG_HOLDER_PROPERTY, wireLogHolder);
            }
        }
        synCtx.setProperty(SynapseConstants.RESPONSE_STATE, new ResponseState());
        List handlers = synCtx.getEnvironment().getSynapseHandlers();
        Iterator<SynapseHandler> iterator = handlers.iterator();
        while (iterator.hasNext()) {
            SynapseHandler handler = iterator.next();
            if (!handler.handleRequestInFlow(synCtx)) {
                return;
            }
        }
        Mediator mandatorySeq = synCtx.getConfiguration().getMandatorySequence();
        if (mandatorySeq != null) {
            if (log.isDebugEnabled()) {
                log.debug("Start mediating the message in the " + "pre-mediate state using the mandatory sequence");
            }
            if (!mandatorySeq.mediate(synCtx)) {
                if (log.isDebugEnabled()) {
                    log.debug("Request message for the proxy service " + name + " dropped in " + "the pre-mediation state by the mandatory sequence : \n" + synCtx);
                }
                return;
            }
        }
        // setup fault sequence - i.e. what happens when something goes wrong with this message
        proxy.registerFaultHandler(synCtx);
        boolean inSequenceResult = true;
        // Using inSequence for the incoming message mediation
        if (proxy.getTargetInSequence() != null) {
            Mediator inSequence = synCtx.getSequence(proxy.getTargetInSequence());
            if (inSequence != null) {
                traceOrDebug(traceOn, "Using sequence named : " + proxy.getTargetInSequence() + " for incoming message mediation");
                inSequenceResult = inSequence.mediate(synCtx);
            } else {
                handleException("Unable to find in-sequence : " + proxy.getTargetInSequence(), synCtx);
            }
        } else if (proxy.getTargetInLineInSequence() != null) {
            traceOrDebug(traceOn, "Using the anonymous " + "in-sequence of the proxy service for mediation");
            inSequenceResult = proxy.getTargetInLineInSequence().mediate(synCtx);
        }
        // if inSequence returns true, forward message to endpoint
        if (inSequenceResult) {
            if (proxy.getTargetEndpoint() != null) {
                Endpoint endpoint = synCtx.getEndpoint(proxy.getTargetEndpoint());
                if (endpoint != null) {
                    traceOrDebug(traceOn, "Forwarding message to the endpoint : " + proxy.getTargetEndpoint());
                    endpoint.send(synCtx);
                } else {
                    handleException("Unable to find the endpoint specified : " + proxy.getTargetEndpoint(), synCtx);
                }
            } else if (proxy.getTargetInLineEndpoint() != null) {
                traceOrDebug(traceOn, "Forwarding the message to the anonymous " + "endpoint of the proxy service");
                proxy.getTargetInLineEndpoint().send(synCtx);
            }
        }
    } catch (SynapseException syne) {
        if (!synCtx.getFaultStack().isEmpty()) {
            warn(traceOn, "Executing fault handler due to exception encountered", synCtx);
            ((FaultHandler) synCtx.getFaultStack().pop()).handleFault(synCtx, syne);
        } else {
            warn(traceOn, "Exception encountered but no fault handler found - " + "message dropped", synCtx);
        }
    } finally {
        // Statistic reporting
        if (isStatisticsEnabled) {
            CloseEventCollector.tryEndFlow(synCtx, this.name, ComponentType.PROXYSERVICE, statisticReportingIndex, true);
        }
        if (synCtx.getEnvironment().isDebuggerEnabled()) {
            SynapseDebugManager debugManager = synCtx.getEnvironment().getSynapseDebugManager();
            debugManager.advertiseMediationFlowTerminatePoint(synCtx);
            debugManager.releaseMediationFlowLock();
        }
        doPostInjectUpdates(synCtx);
    }
}
Also used : SynapseException(org.apache.synapse.SynapseException) Log(org.apache.commons.logging.Log) SynapseWireLogHolder(org.apache.synapse.transport.http.conn.SynapseWireLogHolder) TransportInDescription(org.apache.axis2.description.TransportInDescription) SynapseHandler(org.apache.synapse.SynapseHandler) SynapseDebugManager(org.apache.synapse.debug.SynapseDebugManager) SynapseException(org.apache.synapse.SynapseException) TenantInfoConfigurator(org.apache.synapse.carbonext.TenantInfoConfigurator) Endpoint(org.apache.synapse.endpoints.Endpoint) List(java.util.List) Mediator(org.apache.synapse.Mediator) MessageContext(org.apache.synapse.MessageContext)

Aggregations

SynapseHandler (org.apache.synapse.SynapseHandler)4 SynapseException (org.apache.synapse.SynapseException)3 ArrayList (java.util.ArrayList)1 Iterator (java.util.Iterator)1 List (java.util.List)1 OMElement (org.apache.axiom.om.OMElement)1 SOAPFactory (org.apache.axiom.soap.SOAPFactory)1 AxisFault (org.apache.axis2.AxisFault)1 MessageContext (org.apache.axis2.context.MessageContext)1 TransportInDescription (org.apache.axis2.description.TransportInDescription)1 Log (org.apache.commons.logging.Log)1 Mediator (org.apache.synapse.Mediator)1 MessageContext (org.apache.synapse.MessageContext)1 TenantInfoConfigurator (org.apache.synapse.carbonext.TenantInfoConfigurator)1 SynapseDebugManager (org.apache.synapse.debug.SynapseDebugManager)1 Endpoint (org.apache.synapse.endpoints.Endpoint)1 InboundResponseSender (org.apache.synapse.inbound.InboundResponseSender)1 SynapseWireLogHolder (org.apache.synapse.transport.http.conn.SynapseWireLogHolder)1