Search in sources :

Example 46 with Axis2MessageContext

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

the class CloneMediator method mediate.

/**
 * This will implement the mediate method of the Mediator interface and will provide the
 * functionality of cloning message into the specified targets and mediation
 *
 * @param synCtx - MessageContext which is subjected to the cloning
 * @return boolean true if this needs to be further mediated (continueParent=true)
 */
public boolean mediate(MessageContext synCtx) {
    if (synCtx.getEnvironment().isDebuggerEnabled()) {
        if (super.divertMediationRoute(synCtx)) {
            return true;
        }
    }
    SynapseLog synLog = getLog(synCtx);
    if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug("Start : Clone mediator");
        if (synLog.isTraceTraceEnabled()) {
            synLog.traceTrace("Message : " + synCtx.getEnvelope());
        }
    }
    synCtx.setProperty(id != null ? EIPConstants.EIP_SHARED_DATA_HOLDER + "." + id : EIPConstants.EIP_SHARED_DATA_HOLDER, new SharedDataHolder());
    // get the targets list, clone the message for the number of targets and then
    // mediate the cloned messages using the targets
    Iterator<Target> iter = targets.iterator();
    int i = 0;
    while (iter.hasNext()) {
        if (synLog.isTraceOrDebugEnabled()) {
            synLog.traceOrDebug("Submitting " + (i + 1) + " of " + targets.size() + " messages for " + (isSequential() ? "sequential processing" : "parallel processing"));
        }
        MessageContext clonedMsgCtx = getClonedMessageContext(synCtx, i++, targets.size());
        ContinuationStackManager.addReliantContinuationState(clonedMsgCtx, i - 1, getMediatorPosition());
        iter.next().mediate(clonedMsgCtx);
    }
    // if the continuation of the parent message is stopped from here set the RESPONSE_WRITTEN
    // property to SKIP to skip the blank http response
    OperationContext opCtx = ((Axis2MessageContext) synCtx).getAxis2MessageContext().getOperationContext();
    if (!continueParent && opCtx != null) {
        opCtx.setProperty(Constants.RESPONSE_WRITTEN, "SKIP");
    }
    // finalize tracing and debugging
    synLog.traceOrDebug("End : Clone mediator");
    // mediation of the message which is subjected for clonning (parent message)
    return continueParent;
}
Also used : OperationContext(org.apache.axis2.context.OperationContext) Target(org.apache.synapse.mediators.eip.Target) SynapseLog(org.apache.synapse.SynapseLog) SharedDataHolder(org.apache.synapse.mediators.eip.SharedDataHolder) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) Endpoint(org.apache.synapse.endpoints.Endpoint)

Example 47 with Axis2MessageContext

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

the class IterateMediator method mediate.

/**
 * Splits the message by iterating over the results of the given XPath expression
 *
 * @param synCtx - MessageContext to be mediated
 * @return boolean false if need to stop processing of the parent message
 */
public boolean mediate(MessageContext synCtx) {
    if (synCtx.getEnvironment().isDebuggerEnabled()) {
        if (super.divertMediationRoute(synCtx)) {
            return true;
        }
    }
    SynapseLog synLog = getLog(synCtx);
    if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug("Start : Iterate mediator");
        if (synLog.isTraceTraceEnabled()) {
            synLog.traceTrace("Message : " + synCtx.getEnvelope());
        }
    }
    try {
        // get a copy of the message for the processing, if the continueParent is set to true
        // this original message can go in further mediations and hence we should not change
        // the original message context
        SOAPEnvelope envelope = MessageHelper.cloneSOAPEnvelope(synCtx.getEnvelope());
        synCtx.setProperty(id != null ? EIPConstants.EIP_SHARED_DATA_HOLDER + "." + id : EIPConstants.EIP_SHARED_DATA_HOLDER, new SharedDataHolder());
        // get the iteration elements and iterate through the list,
        // this call will also detach all the iteration elements
        List splitElements = EIPUtils.getDetachedMatchingElements(envelope, synCtx, expression);
        if (synLog.isTraceOrDebugEnabled()) {
            synLog.traceOrDebug("Splitting with XPath : " + expression + " resulted in " + splitElements.size() + " elements");
        }
        // if not preservePayload remove all the child elements
        if (!preservePayload && envelope.getBody() != null) {
            for (Iterator itr = envelope.getBody().getChildren(); itr.hasNext(); ) {
                ((OMNode) itr.next()).detach();
            }
        }
        int msgCount = splitElements.size();
        int msgNumber = 0;
        // iterate through the list
        for (Object o : splitElements) {
            // for the moment iterator will look for an OMNode as the iteration element
            if (!(o instanceof OMNode)) {
                handleException("Error splitting message with XPath : " + expression + " - result not an OMNode", synCtx);
            }
            if (synLog.isTraceOrDebugEnabled()) {
                synLog.traceOrDebug("Submitting " + (msgNumber + 1) + " of " + msgCount + (target.isAsynchronous() ? " messages for processing in parallel" : " messages for processing in sequentially"));
            }
            MessageContext iteratedMsgCtx = getIteratedMessage(synCtx, msgNumber++, msgCount, envelope, (OMNode) o);
            ContinuationStackManager.addReliantContinuationState(iteratedMsgCtx, 0, getMediatorPosition());
            if (target.isAsynchronous()) {
                target.mediate(iteratedMsgCtx);
            } else {
                try {
                    /*
                         * if Iteration is sequential we won't be able to execute correct fault
                         * handler as data are lost with clone message ending execution. So here we
                         * copy fault stack of clone message context to original message context
                         */
                    target.mediate(iteratedMsgCtx);
                } catch (SynapseException synEx) {
                    copyFaultyIteratedMessage(synCtx, iteratedMsgCtx);
                    throw synEx;
                } catch (Exception e) {
                    copyFaultyIteratedMessage(synCtx, iteratedMsgCtx);
                    handleException("Exception occurred while executing sequential iteration " + "in the Iterator Mediator", e, synCtx);
                }
            }
        }
    } catch (JaxenException e) {
        handleException("Error evaluating split XPath expression : " + expression, e, synCtx);
    } catch (AxisFault af) {
        handleException("Error creating an iterated copy of the message", af, synCtx);
    } catch (SynapseException synEx) {
        throw synEx;
    } catch (Exception e) {
        handleException("Exception occurred while executing the Iterate Mediator", e, synCtx);
    }
    // if the continuation of the parent message is stopped from here set the RESPONSE_WRITTEN
    // property to SKIP to skip the blank http response
    OperationContext opCtx = ((Axis2MessageContext) synCtx).getAxis2MessageContext().getOperationContext();
    if (!continueParent && opCtx != null) {
        opCtx.setProperty(Constants.RESPONSE_WRITTEN, "SKIP");
    }
    synLog.traceOrDebug("End : Iterate mediator");
    // whether to continue mediation on the original message
    return continueParent;
}
Also used : AxisFault(org.apache.axis2.AxisFault) OperationContext(org.apache.axis2.context.OperationContext) SynapseException(org.apache.synapse.SynapseException) SharedDataHolder(org.apache.synapse.mediators.eip.SharedDataHolder) SOAPEnvelope(org.apache.axiom.soap.SOAPEnvelope) Endpoint(org.apache.synapse.endpoints.Endpoint) JaxenException(org.jaxen.JaxenException) SynapseException(org.apache.synapse.SynapseException) OMNode(org.apache.axiom.om.OMNode) SynapseLog(org.apache.synapse.SynapseLog) JaxenException(org.jaxen.JaxenException) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Example 48 with Axis2MessageContext

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

the class EnrichMediator method mediate.

public boolean mediate(MessageContext synCtx) {
    if (synCtx.getEnvironment().isDebuggerEnabled()) {
        if (super.divertMediationRoute(synCtx)) {
            return true;
        }
    }
    SynapseLog synLog = getLog(synCtx);
    if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug("Start : Enrich mediator");
        if (synLog.isTraceTraceEnabled()) {
            synLog.traceTrace("Message : " + synCtx.getEnvelope());
        }
    }
    ArrayList<OMNode> sourceNodeList;
    try {
        sourceNodeList = source.evaluate(synCtx, synLog);
        if (sourceNodeList == null) {
            handleException("Failed to get the source for Enriching : ", synCtx);
        } else {
            target.insert(synCtx, sourceNodeList, synLog);
        }
    } catch (JaxenException e) {
        handleException("Failed to get the source for Enriching", e, synCtx);
    }
    // If enrich mediator modifies JSON payload update JSON stream in the axis2MessageContext
    org.apache.axis2.context.MessageContext axis2MsgCtx = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
    if (JsonUtil.hasAJsonPayload(axis2MsgCtx)) {
        JsonUtil.setJsonStream(axis2MsgCtx, JsonUtil.toJsonStream(axis2MsgCtx.getEnvelope().getBody().getFirstElement()));
    }
    synLog.traceOrDebug("End : Enrich mediator");
    return true;
}
Also used : OMNode(org.apache.axiom.om.OMNode) SynapseLog(org.apache.synapse.SynapseLog) JaxenException(org.jaxen.JaxenException) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Example 49 with Axis2MessageContext

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

the class MessageConverter method toStorableMessage.

/**
 * Converts a Synapse Message Context to a representation that can be stored in the
 * Message store queue.
 * @param synCtx Source Synapse message context.
 * @return Storable representation of the provided message context.
 */
public static StorableMessage toStorableMessage(MessageContext synCtx) {
    StorableMessage message = new StorableMessage();
    Axis2Message axis2msg = new Axis2Message();
    SynapseMessage synMsg = new SynapseMessage();
    Axis2MessageContext axis2MessageContext;
    if (synCtx instanceof Axis2MessageContext) {
        axis2MessageContext = (Axis2MessageContext) synCtx;
        org.apache.axis2.context.MessageContext msgCtx = axis2MessageContext.getAxis2MessageContext();
        axis2msg.setMessageID(UUIDGenerator.getUUID());
        if (msgCtx.getAxisOperation() != null) {
            axis2msg.setOperationAction(msgCtx.getAxisOperation().getSoapAction());
            axis2msg.setOperationName(msgCtx.getAxisOperation().getName());
        }
        if (JsonUtil.hasAJsonPayload(msgCtx)) {
            axis2msg.setJsonStream(JsonUtil.jsonPayloadToByteArray(msgCtx));
        }
        axis2msg.setAction(msgCtx.getOptions().getAction());
        if (msgCtx.getAxisService() != null) {
            axis2msg.setService(msgCtx.getAxisService().getName());
        }
        if (msgCtx.getRelatesTo() != null) {
            axis2msg.setRelatesToMessageId(msgCtx.getRelatesTo().getValue());
        }
        if (msgCtx.getReplyTo() != null) {
            axis2msg.setReplyToAddress(msgCtx.getReplyTo().getAddress());
        }
        if (msgCtx.getFaultTo() != null) {
            axis2msg.setFaultToAddress(msgCtx.getFaultTo().getAddress());
        }
        if (msgCtx.getTo() != null) {
            axis2msg.setToAddress(msgCtx.getTo().getAddress());
        }
        axis2msg.setDoingPOX(msgCtx.isDoingREST());
        axis2msg.setDoingMTOM(msgCtx.isDoingMTOM());
        axis2msg.setDoingSWA(msgCtx.isDoingSwA());
        String soapEnvelope = msgCtx.getEnvelope().toString();
        axis2msg.setSoapEnvelope(soapEnvelope);
        axis2msg.setFLOW(msgCtx.getFLOW());
        if (msgCtx.getTransportIn() != null) {
            axis2msg.setTransportInName(msgCtx.getTransportIn().getName());
        }
        if (msgCtx.getTransportOut() != null) {
            axis2msg.setTransportOutName(msgCtx.getTransportOut().getName());
        }
        Iterator<String> abstractMCProperties = msgCtx.getPropertyNames();
        Map<String, Object> copy = new HashMap<String, Object>(msgCtx.getProperties().size());
        while (abstractMCProperties.hasNext()) {
            String propertyName = abstractMCProperties.next();
            Object propertyValue = msgCtx.getProperty(propertyName);
            if (propertyValue instanceof String || propertyValue instanceof Boolean || propertyValue instanceof Integer || propertyValue instanceof Double || propertyValue instanceof Character) {
                copy.put(propertyName, propertyValue);
            }
            if (JMS_PRIORITY.equals(propertyName)) {
                if (propertyValue instanceof Integer) {
                    message.setPriority((Integer) propertyValue);
                } else if (propertyValue instanceof String) {
                    try {
                        int value = Integer.parseInt((String) propertyValue);
                        message.setPriority(value);
                    } catch (NumberFormatException e) {
                    }
                }
            }
        }
        axis2msg.addProperty(ABSTRACT_MC_PROPERTIES, copy);
        Map<String, String> transportHeaders = getTransportHeaders(msgCtx);
        axis2msg.addProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, transportHeaders);
        Iterator<String> properties = msgCtx.getProperties().keySet().iterator();
        while (properties.hasNext()) {
            String key = properties.next();
            Object value = msgCtx.getProperty(key);
            if (value instanceof String) {
                axis2msg.addProperty(key, value);
            }
        }
        message.setAxis2message(axis2msg);
        synMsg.setFaultResponse(synCtx.isFaultResponse());
        synMsg.setTracingState(synCtx.getTracingState());
        synMsg.setMessageFlowTracingState(synCtx.getMessageFlowTracingState());
        synMsg.setResponse(synCtx.isResponse());
        properties = synCtx.getPropertyKeySet().iterator();
        while (properties.hasNext()) {
            String key = properties.next();
            Object value = synCtx.getProperty(key);
            if (value instanceof String) {
                synMsg.addProperty(key, (String) value);
            }
            if (value instanceof ArrayList && ((ArrayList) value).size() > 0 && ((ArrayList) value).get(0) instanceof OMElement) {
                OMElement elem = ((OMElement) ((ArrayList) value).get(0));
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                try {
                    elem.serialize(bos);
                    byte[] bytes = bos.toByteArray();
                    synMsg.addPropertyObject(OM_ELEMENT_PREFIX + key, bytes);
                } catch (XMLStreamException e) {
                    logger.error("Error while converting OMElement to byte array", e);
                }
            }
        }
        message.setSynapseMessage(synMsg);
    } else {
        throw new SynapseException("Cannot store message to store.");
    }
    return message;
}
Also used : SynapseException(org.apache.synapse.SynapseException) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) OMElement(org.apache.axiom.om.OMElement) ByteArrayOutputStream(org.apache.commons.io.output.ByteArrayOutputStream) XMLStreamException(javax.xml.stream.XMLStreamException) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Example 50 with Axis2MessageContext

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

the class HeaderMediator method mediate.

/**
 * Sets/Removes a SOAP header on the current message
 *
 * @param synCtx the current message which is altered as necessary
 * @return true always
 */
public boolean mediate(MessageContext synCtx) {
    if (synCtx.getEnvironment().isDebuggerEnabled()) {
        if (super.divertMediationRoute(synCtx)) {
            return true;
        }
    }
    SynapseLog synLog = getLog(synCtx);
    if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug("Start : Header mediator");
        if (synLog.isTraceTraceEnabled()) {
            synLog.traceTrace("Message : " + synCtx.getEnvelope());
        }
    }
    String value = (getExpression() == null ? getValue() : expression.stringValueOf(synCtx));
    if (scope == null || XMLConfigConstants.SCOPE_DEFAULT.equals(scope)) {
        if (action == ACTION_SET) {
            if (synLog.isTraceOrDebugEnabled()) {
                synLog.traceOrDebug("Set SOAP header : " + qName + " to : " + value);
            }
            if (!isImplicit() && (qName.getNamespaceURI() == null || "".equals(qName.getNamespaceURI()))) {
                // is this a "well known" Synapse header?
                if (SynapseConstants.HEADER_TO.equals(qName.getLocalPart())) {
                    synCtx.setTo(new EndpointReference(value));
                } else if (SynapseConstants.HEADER_FROM.equals(qName.getLocalPart())) {
                    synCtx.setFrom(new EndpointReference(value));
                } else if (SynapseConstants.HEADER_ACTION.equals(qName.getLocalPart())) {
                    synCtx.setWSAAction(value);
                } else if (SynapseConstants.HEADER_FAULT.equals(qName.getLocalPart())) {
                    synCtx.setFaultTo(new EndpointReference(value));
                } else if (SynapseConstants.HEADER_REPLY_TO.equals(qName.getLocalPart())) {
                    synCtx.setReplyTo(new EndpointReference(value));
                } else if (SynapseConstants.HEADER_RELATES_TO.equals(qName.getLocalPart())) {
                    synCtx.setRelatesTo(new RelatesTo[] { new RelatesTo(value) });
                } else {
                    addCustomHeader(synCtx, value);
                }
            } else {
                addCustomHeader(synCtx, value);
            }
        } else {
            if (synLog.isTraceOrDebugEnabled()) {
                synLog.traceOrDebug("Removing SOAP Header : " + qName);
            }
            if (qName.getNamespaceURI() == null || "".equals(qName.getNamespaceURI())) {
                // is this a "well known" Synapse header?
                if (SynapseConstants.HEADER_TO.equals(qName.getLocalPart())) {
                    synCtx.setTo(null);
                } else if (SynapseConstants.HEADER_FROM.equals(qName.getLocalPart())) {
                    synCtx.setFrom(null);
                } else if (SynapseConstants.HEADER_ACTION.equals(qName.getLocalPart())) {
                    synCtx.setWSAAction(null);
                } else if (SynapseConstants.HEADER_FAULT.equals(qName.getLocalPart())) {
                    synCtx.setFaultTo(null);
                } else if (SynapseConstants.HEADER_REPLY_TO.equals(qName.getLocalPart())) {
                    synCtx.setReplyTo(null);
                } else if (SynapseConstants.HEADER_RELATES_TO.equals(qName.getLocalPart())) {
                    synCtx.setRelatesTo(null);
                } else {
                    SOAPEnvelope envelope = synCtx.getEnvelope();
                    if (envelope != null) {
                        SOAPHeader header = envelope.getHeader();
                        if (header != null) {
                            removeFromHeaderList(header.getHeaderBlocksWithNSURI(""));
                        }
                    }
                }
            } else {
                SOAPEnvelope envelope = synCtx.getEnvelope();
                if (envelope != null) {
                    SOAPHeader header = envelope.getHeader();
                    if (header != null) {
                        removeFromHeaderList(header.getHeaderBlocksWithNSURI(qName.getNamespaceURI()));
                    }
                }
            }
        }
    } else if (XMLConfigConstants.SCOPE_TRANSPORT.equals(scope)) {
        String headerName = qName.getLocalPart();
        if (action == ACTION_SET) {
            if (synLog.isTraceOrDebugEnabled()) {
                synLog.traceOrDebug("Set HTTP header : " + headerName + " to : " + value);
            }
            // Setting Transport Headers
            Axis2MessageContext axis2smc = (Axis2MessageContext) synCtx;
            org.apache.axis2.context.MessageContext axis2MessageCtx = axis2smc.getAxis2MessageContext();
            Object headers = axis2MessageCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
            if (headers != null && headers instanceof Map) {
                Map headersMap = (Map) headers;
                headersMap.put(headerName, value);
            }
            if (headers == null) {
                Map headersMap = new HashMap();
                headersMap.put(headerName, value);
                axis2MessageCtx.setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, headersMap);
            }
        } else {
            if (synLog.isTraceOrDebugEnabled()) {
                synLog.traceOrDebug("Removing HTTP Header : " + qName);
            }
            // Removing transport headers
            Axis2MessageContext axis2smc = (Axis2MessageContext) synCtx;
            org.apache.axis2.context.MessageContext axis2MessageCtx = axis2smc.getAxis2MessageContext();
            Object headers = axis2MessageCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
            if (headers != null && headers instanceof Map) {
                Map headersMap = (Map) headers;
                headersMap.remove(headerName);
            } else {
                synLog.traceOrDebug("No transport headers found for the message");
            }
        }
    }
    // NOTE: We dont' use an else here because the HTTPMediatorFactory should capture cases where scope is not default or transport.
    synLog.traceOrDebug("End : Header mediator");
    return true;
}
Also used : HashMap(java.util.HashMap) SOAPEnvelope(org.apache.axiom.soap.SOAPEnvelope) RelatesTo(org.apache.axis2.addressing.RelatesTo) EndpointReference(org.apache.axis2.addressing.EndpointReference) SynapseLog(org.apache.synapse.SynapseLog) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) HashMap(java.util.HashMap) Map(java.util.Map) SOAPHeader(org.apache.axiom.soap.SOAPHeader) 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