use of org.apache.synapse.MessageContext in project wso2-synapse by wso2.
the class PropertyMediator method mediate.
/**
* Sets a property into the current (local) Synapse Context or into the Axis Message Context
* or into Transports Header and removes above properties from the corresponding locations.
*
* @param synCtx the message context
* @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 : Property mediator");
if (synLog.isTraceTraceEnabled()) {
synLog.traceTrace("Message : " + synCtx.getEnvelope());
}
}
if (action == ACTION_SET) {
Object resultValue = getResultValue(synCtx);
// choose part of it
if (resultValue instanceof String && pattern != null) {
resultValue = getMatchedValue((String) resultValue, synLog);
}
if (synLog.isTraceOrDebugEnabled()) {
synLog.traceOrDebug("Setting property : " + name + " at scope : " + (scope == null ? "default" : scope) + " to : " + resultValue + " (i.e. " + (value != null ? "constant : " + value : "result of expression : " + expression) + ")");
}
if (scope == null || XMLConfigConstants.SCOPE_DEFAULT.equals(scope)) {
// Setting property into the Synapse Context
if (resultValue != null && resultValue instanceof OMElement) {
((OMElement) resultValue).build();
}
synCtx.setProperty(name, resultValue);
} else if (XMLConfigConstants.SCOPE_AXIS2.equals(scope) && synCtx instanceof Axis2MessageContext) {
// Setting property into the Axis2 Message Context
Axis2MessageContext axis2smc = (Axis2MessageContext) synCtx;
org.apache.axis2.context.MessageContext axis2MessageCtx = axis2smc.getAxis2MessageContext();
axis2MessageCtx.setProperty(name, resultValue);
MediatorPropertyUtils.handleSpecialProperties(name, resultValue, axis2MessageCtx);
} else if (XMLConfigConstants.SCOPE_CLIENT.equals(scope) && synCtx instanceof Axis2MessageContext) {
// Setting property into the Axis2 Message Context client options
Axis2MessageContext axis2smc = (Axis2MessageContext) synCtx;
org.apache.axis2.context.MessageContext axis2MessageCtx = axis2smc.getAxis2MessageContext();
axis2MessageCtx.getOptions().setProperty(name, resultValue);
} else if (XMLConfigConstants.SCOPE_TRANSPORT.equals(scope) && synCtx instanceof Axis2MessageContext) {
// 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 null is passed as header value at AbstractHTTPSender in Axis2 when header
* value is read causes a null-pointer issue
*/
if (resultValue == null) {
resultValue = "";
}
if (headers != null && headers instanceof Map) {
Map headersMap = (Map) headers;
headersMap.put(name, resultValue);
}
if (headers == null) {
Map headersMap = new HashMap();
headersMap.put(name, resultValue);
axis2MessageCtx.setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, headersMap);
}
} else if (XMLConfigConstants.SCOPE_OPERATION.equals(scope) && synCtx instanceof Axis2MessageContext) {
// Setting Transport Headers
Axis2MessageContext axis2smc = (Axis2MessageContext) synCtx;
org.apache.axis2.context.MessageContext axis2MessageCtx = axis2smc.getAxis2MessageContext();
axis2smc.getAxis2MessageContext().getOperationContext().setProperty(name, resultValue);
} else if (XMLConfigConstants.SCOPE_REGISTRY.equals(scope) && synCtx instanceof Axis2MessageContext) {
String[] args = name.split("@");
String path = "";
String propertyName = "";
// with the property mentioned and the value as its value
if (args.length == 1) {
path = args[0];
} else if (args.length == 2) {
path = args[0];
propertyName = args[1];
}
Registry registry = synCtx.getConfiguration().getRegistry();
registry.newNonEmptyResource(path, false, CONTENT_TYPE, resultValue.toString(), propertyName);
}
} else {
if (synLog.isTraceOrDebugEnabled()) {
synLog.traceOrDebug("Removing property : " + name + " (scope:" + (scope == null ? "default" : scope) + ")");
}
if (scope == null || XMLConfigConstants.SCOPE_DEFAULT.equals(scope)) {
// Removing property from the Synapse Context
Set pros = synCtx.getPropertyKeySet();
if (pros != null) {
pros.remove(name);
}
} else if (XMLConfigConstants.SCOPE_AXIS2.equals(scope) && synCtx instanceof Axis2MessageContext) {
// Removing property from the Axis2 Message Context
Axis2MessageContext axis2smc = (Axis2MessageContext) synCtx;
org.apache.axis2.context.MessageContext axis2MessageCtx = axis2smc.getAxis2MessageContext();
axis2MessageCtx.removeProperty(name);
} else if (XMLConfigConstants.SCOPE_CLIENT.equals(scope) && synCtx instanceof Axis2MessageContext) {
// Removing property from the Axis2-client Message Context
Axis2MessageContext axis2smc = (Axis2MessageContext) synCtx;
org.apache.axis2.context.MessageContext axis2MessageCtx = axis2smc.getAxis2MessageContext();
// Property value is set to null since axis2MessageCtx.getOptions()
// does not have an option to remove properties
axis2MessageCtx.getOptions().setProperty(name, null);
} else if (XMLConfigConstants.SCOPE_TRANSPORT.equals(scope) && synCtx instanceof Axis2MessageContext) {
// 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(name);
} else {
synLog.traceOrDebug("No transport headers found for the message");
}
} else if (XMLConfigConstants.SCOPE_OPERATION.equals(scope) && synCtx instanceof Axis2MessageContext) {
// Removing operation scope headers
Axis2MessageContext axis2smc = (Axis2MessageContext) synCtx;
org.apache.axis2.context.MessageContext axis2MessageCtx = axis2smc.getAxis2MessageContext();
OperationContext axis2oc = axis2MessageCtx.getOperationContext();
axis2oc.removeProperty(name);
}
}
synLog.traceOrDebug("End : Property mediator");
return true;
}
use of org.apache.synapse.MessageContext in project wso2-synapse by wso2.
the class IterateMediator method getIteratedMessage.
/**
* Create a new message context using the given original message context, the envelope
* and the split result element.
*
* @param synCtx - original message context
* @param msgNumber - message number in the iteration
* @param msgCount - total number of messages in the split
* @param envelope - envelope to be used in the iteration
* @param o - element which participates in the iteration replacement
* @return newCtx created by the iteration
* @throws AxisFault if there is a message creation failure
* @throws JaxenException if the expression evauation failure
*/
private MessageContext getIteratedMessage(MessageContext synCtx, int msgNumber, int msgCount, SOAPEnvelope envelope, OMNode o) throws AxisFault, JaxenException {
// clone the message context without cloning the SOAP envelope, for the mediation in iteration.
MessageContext newCtx = MessageHelper.cloneMessageContext(synCtx, false);
if (id != null) {
// set the parent correlation details to the cloned MC -
// for the use of aggregation like tasks
newCtx.setProperty(EIPConstants.AGGREGATE_CORRELATION + "." + id, synCtx.getMessageID());
// set the messageSequence property for possibal aggreagtions
newCtx.setProperty(EIPConstants.MESSAGE_SEQUENCE + "." + id, msgNumber + EIPConstants.MESSAGE_SEQUENCE_DELEMITER + msgCount);
} else {
newCtx.setProperty(EIPConstants.MESSAGE_SEQUENCE, msgNumber + EIPConstants.MESSAGE_SEQUENCE_DELEMITER + msgCount);
}
// get a clone of the envelope to be attached
SOAPEnvelope newEnvelope = MessageHelper.cloneSOAPEnvelope(envelope);
// node specified by the attachPath
if (preservePayload) {
Object attachElem = attachPath.evaluate(newEnvelope, synCtx);
if (attachElem != null && attachElem instanceof List && !((List) attachElem).isEmpty()) {
attachElem = ((List) attachElem).get(0);
}
// for the moment attaching element should be an OMElement
if (attachElem != null && attachElem instanceof OMElement) {
((OMElement) attachElem).addChild(o);
} else {
handleException("Error in attaching the splitted elements :: " + "Unable to get the attach path specified by the expression " + attachPath, synCtx);
}
} else if (newEnvelope.getBody() != null) {
// if not preserve payload then attach the iteration element to the body
if (newEnvelope.getBody().getFirstElement() != null) {
newEnvelope.getBody().getFirstElement().detach();
}
newEnvelope.getBody().addChild(o);
}
// set the envelope and mediate as specified in the target
newCtx.setEnvelope(newEnvelope);
return newCtx;
}
use of org.apache.synapse.MessageContext in project wso2-synapse by wso2.
the class FailoverForwardingService method execute.
/**
* Starts the execution of this task which grabs a message from the message
* queue and dispatch it to a given endpoint.
*/
public void execute() {
final long startTime = new Date().getTime();
if (isDeactivatedAtStartup) {
// inactive
try {
TimeUnit.MILLISECONDS.sleep(MessageProcessorConstants.INITIAL_EXECUTION_DELAY);
} catch (InterruptedException exception) {
log.warn("Initial delay interrupted when Failover Forwarding service started as inactive ", exception);
}
isDeactivatedAtStartup = false;
}
/*
* Initialize only if it is NOT already done. This will make sure that
* the initialization is done only once.
*/
try {
if (!initialized) {
this.init(synapseEnvironment);
}
} catch (SynapseException e) {
throw new SynapseException("Error while initializing forwarding service " + this.targetMessageStoreName, e);
}
do {
resetService();
MessageContext messageContext = null;
try {
if (!this.messageProcessor.isDeactivated()) {
messageContext = fetch(messageConsumer);
if (messageContext != null) {
// Now it is NOT terminated anymore.
isTerminated = messageProcessor.isDeactivated();
dispatch(messageContext);
} else {
// massages.
if (log.isDebugEnabled()) {
log.debug("No messages were received for message processor [" + messageProcessor.getName() + "]");
}
// this means we have consumed all the messages
if (isRunningUnderCronExpression()) {
break;
}
}
} else {
/*
* we need this because when start the server while the
* processors in deactivated mode
* the deactivation may not come in to play because the
* service may not be running.
*/
isTerminated = true;
if (log.isDebugEnabled()) {
log.debug("Exiting service since the message processor is deactivated");
}
}
} catch (Throwable e) {
/*
* All the possible recoverable exceptions are handles case by
* case and yet if it comes this
* we have to shutdown the processor
*/
log.fatal("Deactivating the message processor [" + this.messageProcessor.getName() + "]", e);
deactivateMessageProcessor(messageContext);
}
if (log.isDebugEnabled()) {
log.debug("Exiting the iteration of message processor [" + this.messageProcessor.getName() + "]");
}
/*
* This code wrote handle scenarios in which cron expressions are
* used for scheduling task
*/
if (isRunningUnderCronExpression()) {
try {
Thread.sleep(throttlingInterval);
} catch (InterruptedException e) {
// no need to worry. it does have any serious consequences
log.debug("Current Thread was interrupted while it is sleeping.");
}
}
/*
* If the interval is less than 1000 ms, then the scheduling is done
* using the while loop since ntask rejects any intervals whose
* value is less then 1000 ms.
*/
if (interval > 0 && interval < MessageProcessorConstants.THRESHOULD_INTERVAL) {
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
log.debug("Current Thread was interrupted while it is sleeping.");
}
}
/*
* Gives the control back to Quartz scheduler. This needs to be done
* only if the interval value is less than the Threshould interval
* value of 1000 ms, where the scheduling is done outside of Quartz
* via the while loop. Otherwise the schedular will get blocked.
* For cron expressions this scenario is already
* handled above.
*/
if (isThrottling && new Date().getTime() - startTime > 1000) {
break;
}
} while ((isThrottling || isRunningUnderCronExpression()) && !isTerminated);
if (log.isDebugEnabled()) {
log.debug("Exiting service thread of message processor [" + this.messageProcessor.getName() + "]");
}
}
use of org.apache.synapse.MessageContext in project wso2-synapse by wso2.
the class ForwardingService method execute.
/**
* Starts the execution of this task which grabs a message from the message
* queue and dispatch it to a given endpoint.
*/
public void execute() {
final long startTime = new Date().getTime();
if (isDeactivatedAtStartup) {
// inactive
try {
TimeUnit.MILLISECONDS.sleep(MessageProcessorConstants.INITIAL_EXECUTION_DELAY);
} catch (InterruptedException exception) {
log.warn("Initial delay interrupted when Forwarding service started as inactive ", exception);
}
isDeactivatedAtStartup = false;
}
/*
* Initialize only if it is NOT already done. This will make sure that
* the initialization is done only once.
*/
if (!initialized) {
try {
this.init(synapseEnvironment);
} catch (SynapseException e) {
log.fatal("Deactivating the message processor [" + this.messageProcessor.getName() + "] due to initialization issue", e);
deactivateMessageProcessor(null);
}
}
do {
resetService();
MessageContext messageContext = null;
try {
if (!this.messageProcessor.isDeactivated()) {
messageContext = fetch();
if (messageContext != null) {
Set proSet = messageContext.getPropertyKeySet();
if (proSet != null) {
if (proSet.contains(ForwardingProcessorConstants.BLOCKING_SENDER_ERROR)) {
proSet.remove(ForwardingProcessorConstants.BLOCKING_SENDER_ERROR);
}
}
// Now it is NOT terminated anymore.
isTerminated = messageProcessor.isDeactivated();
dispatch(messageContext);
} else {
// massages.
if (log.isDebugEnabled()) {
log.debug("No messages were received for message processor [" + messageProcessor.getName() + "]");
}
// this means we have consumed all the messages
if (isRunningUnderCronExpression()) {
break;
}
}
} else {
/*
* we need this because when start the server while the
* processors in deactivated mode
* the deactivation may not come in to play because the
* service may not be running.
*/
isTerminated = true;
if (log.isDebugEnabled()) {
log.debug("Exiting service since the message processor is deactivated");
}
}
} catch (Throwable e) {
/*
* All the possible recoverable exceptions are handles case by
* case and yet if it comes this
* we have to shutdown the processor
*/
log.fatal("Deactivating the message processor [" + this.messageProcessor.getName() + "]", e);
deactivateMessageProcessor(messageContext);
}
if (log.isDebugEnabled()) {
log.debug("Exiting the iteration of message processor [" + this.messageProcessor.getName() + "]");
}
/*
* This code wrote handle scenarios in which cron expressions are
* used for scheduling task
*/
if (isRunningUnderCronExpression()) {
try {
Thread.sleep(throttlingInterval);
} catch (InterruptedException e) {
// no need to worry. it does have any serious consequences
log.debug("Current Thread was interrupted while it is sleeping.");
}
}
/*
* If the interval is less than 1000 ms, then the scheduling is done
* using the while loop since ntask rejects any intervals whose
* value is less then 1000 ms. Cron expressions are handled above so
* we need to skip it here. Otherwise the cron expression is kept
* sleeping twice as the forwarding interval.
*/
if (interval > 0 && interval < MessageProcessorConstants.THRESHOULD_INTERVAL && !isRunningUnderCronExpression()) {
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
log.debug("Current Thread was interrupted while it is sleeping.");
}
}
/*
* Gives the control back to Quartz scheduler. This needs to be done
* only if the interval value is less than the Threshould interval
* value of 1000 ms, where the scheduling is done outside of Quartz
* via the while loop. Otherwise the schedular will get blocked.
* For cron expressions with interval < 1000ms this scenario is not
* applicable hence skipping it here. For cron expressions, all the
* messages in the queue at the moment are sent to the backend. If
* you give control back to the Quartz that behavior can not be
* achieved, only a portion of the messages will get dispatched
* while other messages will remain in the queue.
*/
if (isThrottling && new Date().getTime() - startTime > 1000 && !isRunningUnderCronExpression()) {
break;
}
} while ((isThrottling || isRunningUnderCronExpression()) && !isTerminated);
if (log.isDebugEnabled()) {
log.debug("Exiting service thread of message processor [" + this.messageProcessor.getName() + "]");
}
}
use of org.apache.synapse.MessageContext in project wso2-synapse by wso2.
the class MessageStoreMediator method mediate.
public boolean mediate(MessageContext synCtx) {
boolean produceStatus;
if (synCtx.getEnvironment().isDebuggerEnabled()) {
if (super.divertMediationRoute(synCtx)) {
return true;
}
}
if (synCtx != null) {
MessageStore messageStore;
if (messageStoreExp != null) {
messageStore = synCtx.getConfiguration().getMessageStore(messageStoreExp.stringValueOf(synCtx));
} else {
messageStore = synCtx.getConfiguration().getMessageStore(messageStoreName);
}
if (messageStore != null) {
if (messageStore.getParameters().get(PRODUCER_GUARANTEED_DELIVERY) != null) {
isGuaranteedDeliveryEnabled = Boolean.parseBoolean(messageStore.getParameters().get(PRODUCER_GUARANTEED_DELIVERY).toString());
}
if (messageStore.getParameters().get(FAILOVER_MESSAGE_STORE_NAME) != null) {
failoverMessageStoreName = (String) messageStore.getParameters().get(FAILOVER_MESSAGE_STORE_NAME);
}
if (onStoreSequence != null) {
Mediator sequence = synCtx.getSequence(onStoreSequence);
if (sequence != null) {
sequence.mediate(synCtx);
}
}
if (log.isDebugEnabled()) {
log.debug("Message Store mediator storing the message : \n " + synCtx.getEnvelope());
}
// Ensure that the message is fully read
synCtx.getEnvelope().buildWithAttachments();
// Clone the message before sending to the producer
// Fix ESBJAVA-3650
MessageContext newCtx = null;
try {
newCtx = MessageHelper.cloneMessageContext(synCtx);
ContinuationStackManager.clearStack(newCtx);
} catch (AxisFault af) {
handleException("Error when cloning the message context", af, synCtx);
}
synchronized (storeMessageLock) {
produceStatus = messageStore.getProducer().storeMessage(newCtx);
}
if (!produceStatus) {
// Fix ESBJAVA-5011, since connection is already null need to nullify producer also
if (messageStore instanceof JmsStore) {
((JmsStore) messageStore).setProducer(null);
}
if (isGuaranteedDeliveryEnabled && failoverMessageStoreName != null && !failoverMessageStoreName.isEmpty()) {
MessageStore failoverMessageStore = synCtx.getConfiguration().getMessageStore(failoverMessageStoreName);
boolean failoverProduceStatus = failoverMessageStore.getProducer().storeMessage(newCtx);
if (!failoverProduceStatus) {
synCtx.setProperty(NhttpConstants.HTTP_SC, 500);
synCtx.setProperty(NhttpConstants.ERROR_DETAIL, "Failed to store message.");
synCtx.setProperty(NhttpConstants.ERROR_MESSAGE, "Failed to store message [" + synCtx.getMessageID() + "] in store [" + messageStore.getName() + "].");
handleException("Failed to store message [" + synCtx.getMessageID() + "] in failover store [" + failoverMessageStoreName + "].", synCtx);
}
if (shouldTrace(synCtx)) {
trace.error("Message [" + synCtx.getMessageID() + "] store in the failover message store [" + failoverMessageStoreName + "]");
}
} else {
synCtx.setProperty(NhttpConstants.HTTP_SC, 500);
synCtx.setProperty(NhttpConstants.ERROR_DETAIL, "Failed to store message.");
synCtx.setProperty(NhttpConstants.ERROR_MESSAGE, "Failed to store message [" + synCtx.getMessageID() + "] in store [" + messageStore.getName() + "].");
handleException("Failed to store message [" + synCtx.getMessageID() + "] in store [" + messageStore.getName() + "].", synCtx);
}
}
// with the nio transport, this causes the listener not to write a 202
// Accepted response, as this implies that Synapse does not yet know if
// a 202 or 200 response would be written back.
Axis2MessageContext msgCtx = (Axis2MessageContext) synCtx;
if (null != msgCtx.getAxis2MessageContext() && null != msgCtx.getAxis2MessageContext().getOperationContext()) {
msgCtx.getAxis2MessageContext().getOperationContext().setProperty(org.apache.axis2.Constants.RESPONSE_WRITTEN, "SKIP");
}
return true;
} else {
handleException("Message Store does not exist.", synCtx);
}
}
return false;
}
Aggregations