use of org.apache.synapse.SynapseLog in project wso2-synapse by wso2.
the class SendMediator method mediate.
/**
* This will call the send method on the messages with implicit message parameters
* or else if there is an endpoint, with that endpoint parameters
*
* @param synCtx the current message to be sent
* @return false always as this is a leaf mediator
*/
public boolean mediate(MessageContext synCtx) {
if (synCtx.getEnvironment().isDebuggerEnabled()) {
// this needs to be set only in mediators where outgoing messages are present
MessageHelper.setWireLogHolderProperties(synCtx, isBreakPoint(), getRegisteredMediationFlowPoint());
if (super.divertMediationRoute(synCtx)) {
return true;
}
}
SynapseLog synLog = getLog(synCtx);
synLog.traceOrDebug("Start : Send mediator");
if (synLog.isTraceTraceEnabled()) {
synLog.traceTrace("Message : " + synCtx.getEnvelope());
}
// Set the last sequence fault handler for future use
synCtx.setProperty(SynapseConstants.LAST_SEQ_FAULT_HANDLER, getLastSequenceFaultHandler(synCtx));
if (buildMessage) {
synCtx.getEnvelope().buildWithAttachments();
}
// clear the message context properties related to endpoint in last service invocation
Set keySet = synCtx.getPropertyKeySet();
if (keySet != null) {
keySet.remove(SynapseConstants.RECEIVING_SEQUENCE);
keySet.remove(SynapseConstants.CONTINUATION_CALL);
keySet.remove(EndpointDefinition.DYNAMIC_URL_VALUE);
keySet.remove(SynapseConstants.LAST_ENDPOINT);
}
if (receivingSequence != null) {
if (synLog.isTraceOrDebugEnabled()) {
synLog.traceOrDebug("Receiving sequence is set to: " + receivingSequence);
}
synCtx.setProperty(SynapseConstants.RECEIVING_SEQUENCE, receivingSequence.evaluateValue(synCtx));
}
// if no endpoints are defined, send where implicitly stated
if (endpoint == null) {
if (synLog.isTraceOrDebugEnabled()) {
StringBuffer sb = new StringBuffer();
sb.append("Sending ").append(synCtx.isResponse() ? "response" : "request").append(" message using implicit message properties..");
sb.append("\nSending To: ").append(synCtx.getTo() != null ? synCtx.getTo().getAddress() : "null");
sb.append("\nSOAPAction: ").append(synCtx.getWSAAction() != null ? synCtx.getWSAAction() : "null");
synLog.traceOrDebug(sb.toString());
}
if (synLog.isTraceTraceEnabled()) {
synLog.traceTrace("Envelope : " + synCtx.getEnvelope());
}
synCtx.getEnvironment().send(null, synCtx);
} else {
endpoint.send(synCtx);
}
synLog.traceOrDebug("End : Send mediator");
// mediators will not executed after send mediator in the sequence.
return false;
}
use of org.apache.synapse.SynapseLog in project wso2-synapse by wso2.
the class ValidateMediator method mediate.
@SuppressWarnings({ "ThrowableResultOfMethodCallIgnored" })
public boolean mediate(MessageContext synCtx) {
// This is the actual schema instance used to create a new schema
Schema cachedSchema = null;
JsonSchema cachedJsonSchema = null;
if (synCtx.getEnvironment().isDebuggerEnabled()) {
if (super.divertMediationRoute(synCtx)) {
return true;
}
}
SynapseLog synLog = getLog(synCtx);
synLog.traceOrDebug("Start : Validate mediator");
if (synLog.isTraceTraceEnabled()) {
synLog.traceTrace("Message : " + synCtx.getEnvelope());
}
org.apache.axis2.context.MessageContext a2mc = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
if (JsonUtil.hasAJsonPayload(a2mc)) {
ProcessingReport report;
// This JsonSchema used if user decide not to cache the schema. In such a situation jsonSchema will not used.
JsonSchema uncachedJsonSchema = null;
JsonNode uncachedJsonSchemaNode = null;
// flag to check if we need to initialize/re-initialize the schema
StringBuilder combinedPropertyKey = new StringBuilder();
StringBuilder cachedJsonSchemaKey = new StringBuilder();
// if any of the schemas are not loaded, or have expired, load or re-load them
boolean reCreate = !cacheSchema || isReCreate(synCtx, combinedPropertyKey);
/*
* Check for the cached schema in the map and if it's available get
* the cached schema else re initialize the schema
*/
if (cachedJsonSchemaMap.containsKey(combinedPropertyKey.toString())) {
cachedJsonSchema = cachedJsonSchemaMap.get(combinedPropertyKey.toString());
} else {
reCreate = true;
}
// do not re-initialize schema unless required
synchronized (validatorLock) {
if (reCreate || cachedJsonSchema == null) {
Object jsonSchemaObj = null;
for (Value schemaKey : schemaKeys) {
// Derive actual key from message context
String propName = schemaKey.evaluateValue(synCtx);
jsonSchemaObj = synCtx.getEntry(propName);
cachedJsonSchemaKey.append(propName);
}
if (jsonSchemaObj == null) {
handleException("Can not find JSON Schema " + cachedJsonSchemaKey.toString(), synCtx);
}
try {
if (jsonSchemaObj instanceof String) {
if (cacheSchema) {
jsonSchemaNode = JsonLoader.fromString((String) jsonSchemaObj);
} else {
uncachedJsonSchemaNode = JsonLoader.fromString((String) jsonSchemaObj);
}
} else if (jsonSchemaObj instanceof OMTextImpl) {
// if Schema provides from registry
InputStreamReader reader = null;
try {
reader = new InputStreamReader(((OMTextImpl) jsonSchemaObj).getInputStream());
if (cacheSchema) {
jsonSchemaNode = JsonLoader.fromReader(reader);
} else {
uncachedJsonSchemaNode = JsonLoader.fromReader(reader);
}
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
log.warn("Error while closing registry resource stream. " + e);
}
}
}
} else {
handleException("Can not find valid JSON Schema content", synCtx);
}
if (cacheSchema) {
cachedJsonSchema = jsonSchemaFactory.getJsonSchema(jsonSchemaNode);
/*
* Initially adds the cached schema to the map if it's
* not available
*/
if (!cachedJsonSchemaMap.containsKey(cachedJsonSchemaKey.toString())) {
cachedJsonSchemaMap.put(cachedJsonSchemaKey.toString(), cachedJsonSchema);
/*
* Removes the existing cached schema and adds the
* new cached schema This is used when editing a
* registry resource or when the cache expires
*/
} else if (cachedJsonSchemaMap.containsKey(cachedJsonSchemaKey.toString())) {
cachedJsonSchemaMap.remove(cachedJsonSchemaKey.toString());
cachedJsonSchemaMap.put(cachedJsonSchemaKey.toString(), cachedJsonSchema);
}
} else {
uncachedJsonSchema = jsonSchemaFactory.getJsonSchema(uncachedJsonSchemaNode);
}
} catch (ProcessingException | IOException e) {
handleException("Error while validating the JSON Schema", e, synCtx);
}
}
}
try {
if (cachedJsonSchema == null && uncachedJsonSchema == null) {
handleException("Failed to create JSON Schema Validator", synCtx);
}
String jsonPayload = null;
if (sourcePath != null) {
// evaluating
if (sourcePath instanceof SynapseJsonPath) {
jsonPayload = sourcePath.stringValueOf(synCtx);
} else {
handleException("Could not find the JSONPath evaluator for Source", synCtx);
}
} else {
jsonPayload = JsonUtil.jsonPayloadToString(a2mc);
}
if (jsonPayload == null || jsonPayload.length() == 0) {
// making empty json string
jsonPayload = "{}";
}
if (cacheSchema) {
report = cachedJsonSchema.validate(JsonLoader.fromString(jsonPayload));
} else {
report = uncachedJsonSchema.validate(JsonLoader.fromString(jsonPayload));
}
if (report.isSuccess()) {
return true;
} else {
if (synLog.isTraceOrDebugEnabled()) {
String msg = "Validation of JSON failed against the given schema(s) " + cachedJsonSchemaKey.toString() + " with error : " + report + " Executing 'on-fail' sequence";
synLog.traceOrDebug(msg);
// write a warning to the service log
synCtx.getServiceLog().warn(msg);
if (synLog.isTraceTraceEnabled()) {
synLog.traceTrace("Failed message envelope : " + synCtx.getEnvelope());
}
}
// set error message and detail (stack trace) into the message context
Iterator<ProcessingMessage> itrErrorMessages = report.iterator();
// there is only one element in the report
if (itrErrorMessages.hasNext()) {
ProcessingMessage processingMessage = itrErrorMessages.next();
String errorMessage = processingMessage.getMessage();
synCtx.setProperty(SynapseConstants.ERROR_MESSAGE, errorMessage);
synCtx.setProperty(SynapseConstants.ERROR_DETAIL, "Error while validating Json message " + errorMessage);
}
// invokes the "on-fail" sequence of mediator
return invokeOnFailSequence(synCtx);
}
} catch (ProcessingException | IOException e) {
String msg = "";
if (sourcePath != null) {
msg = " for JSONPath " + sourcePath.getExpression();
}
handleException("Error while validating the JSON Schema" + msg, e, synCtx);
}
} else {
Source validateSrc;
try {
// Input source for the validation
validateSrc = getValidationSource(synCtx, synLog);
} catch (SynapseException e) {
/* Catches the exception here to forward to 'on-fail' sequence.
The 'on-fail' sequence will get invoked when the given xpath source is not available
in the message.
*/
String errorMessage = "Error occurred while accessing source element: " + source;
if (synLog.isTraceOrDebugEnabled()) {
String msg = "Error occurred while accessing source element : " + source + "with error : '" + e.getMessage() + "'. Executing 'on-fail' sequence";
synLog.traceOrDebug(msg);
// write a warning to the service log
synCtx.getServiceLog().warn(msg);
if (synLog.isTraceTraceEnabled()) {
synLog.traceTrace("Failed message envelope : " + synCtx.getEnvelope());
}
}
synCtx.setProperty(SynapseConstants.ERROR_MESSAGE, errorMessage);
synCtx.setProperty(SynapseConstants.ERROR_DETAIL, e.getMessage());
// invokes the "on-fail" sequence of mediator
return invokeOnFailSequence(synCtx);
}
StringBuilder combinedPropertyKey = new StringBuilder();
// flag to check if we need to initialize/re-initialize the schema
// if any of the schemas are not loaded, or have expired, load or re-load them
boolean reCreate = !cacheSchema || isReCreate(synCtx, combinedPropertyKey);
/*
* Check for the cached schema in the map and if it's available get
* the cached schema else re initialize the schema
*/
if (cachedSchemaMap.containsKey(combinedPropertyKey.toString())) {
cachedSchema = cachedSchemaMap.get(combinedPropertyKey.toString());
} else {
reCreate = true;
}
// This is the reference to the DefaultHandler instance
ValidateMediatorErrorHandler errorHandler = new ValidateMediatorErrorHandler();
// This instance used to handle schema not cached scenarios.
Schema uncachedSchema = null;
// do not re-initialize schema unless required
synchronized (validatorLock) {
if (reCreate || cachedSchema == null) {
factory.setErrorHandler(errorHandler);
StreamSource[] sources = new StreamSource[schemaKeys.size()];
StringBuilder cachedSchemaKey = new StringBuilder();
int i = 0;
for (Value schemaKey : schemaKeys) {
// Derive actual key from message context
String propName = schemaKey.evaluateValue(synCtx);
Object schemaObject = synCtx.getEntry(propName);
if (schemaObject == null) {
throw new SynapseException("No Schema is available with the key : " + propName);
}
sources[i++] = SynapseConfigUtils.getStreamSource(schemaObject);
// Generating a cached schema key
cachedSchemaKey.append(propName);
}
// load the UserDefined SchemaURIResolver implementations
try {
SynapseConfiguration synCfg = synCtx.getConfiguration();
if (synCfg.getProperty(SynapseConstants.SYNAPSE_SCHEMA_RESOLVER) != null) {
setUserDefinedSchemaResourceResolver(synCtx);
} else {
factory.setResourceResolver(new SchemaResourceResolver(synCtx.getConfiguration(), resourceMap));
}
if (cacheSchema) {
cachedSchema = factory.newSchema(sources);
/*
* Initially adds the cached schema to the map if it's
* not available
*/
if (!cachedSchemaMap.containsKey(cachedSchemaKey.toString())) {
cachedSchemaMap.put(cachedSchemaKey.toString(), cachedSchema);
/*
* Removes the existing cached schema and adds the
* new cached schema This is used when editing a
* registry resource or when the cache expires
*/
} else if (cachedSchemaMap.containsKey(cachedSchemaKey.toString())) {
cachedSchemaMap.remove(cachedSchemaKey.toString());
cachedSchemaMap.put(cachedSchemaKey.toString(), cachedSchema);
}
} else {
uncachedSchema = factory.newSchema(sources);
}
} catch (SAXException e) {
handleException("Error creating a new schema objects for " + "schemas : " + schemaKeys.toString(), e, synCtx);
} catch (RuntimeException e) {
handleException("Error creating a new schema objects for " + "schemas : " + schemaKeys.toString(), e, synCtx);
}
if (errorHandler.isValidationError()) {
// reset the errorhandler state
errorHandler.setValidationError(false);
cachedSchema = null;
// Removes the erroneous cached schema from the map
if (cachedSchemaMap.containsKey(cachedSchemaKey.toString())) {
cachedSchemaMap.remove(cachedSchemaKey.toString());
}
handleException("Error creating a new schema objects for schemas : " + schemaKeys.toString(), errorHandler.getSaxParseException(), synCtx);
}
}
}
// no need to synchronize, schema instances are thread-safe
try {
Validator validator;
if (cacheSchema) {
validator = cachedSchema.newValidator();
} else {
validator = uncachedSchema.newValidator();
}
validator.setErrorHandler(errorHandler);
// perform actual validation
validator.validate(validateSrc);
if (errorHandler.isValidationError()) {
if (synLog.isTraceOrDebugEnabled()) {
String msg = "Validation of element returned by XPath : " + source + " failed against the given schema(s) " + schemaKeys + "with error : " + errorHandler.getSaxParseException().getMessage() + " Executing 'on-fail' sequence";
synLog.traceOrDebug(msg);
// write a warning to the service log
synCtx.getServiceLog().warn(msg);
if (synLog.isTraceTraceEnabled()) {
synLog.traceTrace("Failed message envelope : " + synCtx.getEnvelope());
}
}
// set error message and detail (stack trace) into the message context
synCtx.setProperty(SynapseConstants.ERROR_MESSAGE, errorHandler.getAllExceptions());
synCtx.setProperty(SynapseConstants.ERROR_EXCEPTION, errorHandler.getSaxParseException());
synCtx.setProperty(SynapseConstants.ERROR_DETAIL, FaultHandler.getStackTrace(errorHandler.getSaxParseException()));
// invokes the "on-fail" sequence of the mediator
return invokeOnFailSequence(synCtx);
}
} catch (SAXException e) {
handleException("Error validating " + source + " element", e, synCtx);
} catch (IOException e) {
handleException("Error validating " + source + " element", e, synCtx);
}
}
if (synLog.isTraceOrDebugEnabled()) {
synLog.traceOrDebug("Validation of element returned by the XPath expression : " + source + " succeeded against the given schemas and the current message");
synLog.traceOrDebug("End : Validate mediator");
}
return true;
}
use of org.apache.synapse.SynapseLog in project wso2-synapse by wso2.
the class BeanMediator method mediate.
/**
* Manipulates a JavaBean attached to the current message context according to the supplied
* semantics.
* @param synCtx The current message for mediation
* @return true If mediation should continue
*/
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 : Bean mediator");
if (synLog.isTraceTraceEnabled()) {
synLog.traceTrace("Message : " + synCtx.getEnvelope());
}
}
boolean output = false;
switch(action) {
case CREATE:
if (synLog.isTraceOrDebugEnabled()) {
synLog.traceOrDebug("Creating a new bean of type '" + clazz.getName() + "' with var name '" + varName + "'.");
}
output = mediateCreateBeanAction(synCtx);
break;
case REMOVE:
if (synLog.isTraceOrDebugEnabled()) {
synLog.traceOrDebug("Removing the bean with var name '" + varName + "'.");
}
output = mediateRemoveBeanAction(synCtx);
break;
case SET_PROPERTY:
if (synLog.isTraceOrDebugEnabled()) {
synLog.traceOrDebug("Setting the '" + propertyName + "' property of the bean " + "with var name '" + varName + "'.");
}
output = mediateSetPropertyAction(synCtx);
break;
case GET_PROPERTY:
if (synLog.isTraceOrDebugEnabled()) {
synLog.traceOrDebug("Retrieving the '" + propertyName + "' property of the " + "bean with var name '" + varName + "'.");
}
output = mediateGetPropertyAction(synCtx);
break;
default:
assert false;
}
if (synLog.isTraceOrDebugEnabled()) {
synLog.traceOrDebug("End : Bean mediator");
}
return output;
}
use of org.apache.synapse.SynapseLog in project wso2-synapse by wso2.
the class DropMediator method mediate.
/**
* Halts further mediation of the current message by returning false.
*
* @param synCtx the current message
* @return false 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 : Drop mediator");
if (synLog.isTraceTraceEnabled()) {
synLog.traceTrace("Message : " + synCtx.getEnvelope());
}
}
synCtx.setTo(null);
if (synLog.isTraceOrDebugEnabled()) {
synLog.traceOrDebug("End : Drop mediator");
}
return false;
}
use of org.apache.synapse.SynapseLog in project wso2-synapse by wso2.
the class AggregateMediator method mediate.
/**
* Aggregate messages flowing through this mediator according to the correlation criteria
* and the aggregation algorithm specified to it
*
* @param synCtx - MessageContext to be mediated and aggregated
* @return boolean true if the complete condition for the particular aggregate is validated
*/
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 : Aggregate mediator");
if (synLog.isTraceTraceEnabled()) {
synLog.traceTrace("Message : " + synCtx.getEnvelope());
}
}
try {
Aggregate aggregate = null;
String correlationIdName = (id != null ? EIPConstants.AGGREGATE_CORRELATION + "." + id : EIPConstants.AGGREGATE_CORRELATION);
// if a correlateExpression is provided and there is a coresponding
// element in the current message prepare to correlate the messages on that
Object result = null;
if (correlateExpression != null) {
result = correlateExpression.evaluate(synCtx);
if (result instanceof List) {
if (((List) result).isEmpty()) {
handleException("Failed to evaluate correlate expression: " + correlateExpression.toString(), synCtx);
}
}
}
if (result != null) {
while (aggregate == null) {
synchronized (lock) {
if (activeAggregates.containsKey(correlateExpression.toString())) {
aggregate = activeAggregates.get(correlateExpression.toString());
if (aggregate != null) {
if (!aggregate.getLock()) {
aggregate = null;
}
}
} else {
if (synLog.isTraceOrDebugEnabled()) {
synLog.traceOrDebug("Creating new Aggregator - " + (completionTimeoutMillis > 0 ? "expires in : " + (completionTimeoutMillis / 1000) + "secs" : "without expiry time"));
}
if (isAggregationCompleted(synCtx)) {
return false;
}
Double minMsg = Double.parseDouble(minMessagesToComplete.evaluateValue(synCtx));
Double maxMsg = Double.parseDouble(maxMessagesToComplete.evaluateValue(synCtx));
aggregate = new Aggregate(synCtx.getEnvironment(), correlateExpression.toString(), completionTimeoutMillis, minMsg.intValue(), maxMsg.intValue(), this, synCtx.getFaultStack().peek());
if (completionTimeoutMillis > 0) {
synCtx.getConfiguration().getSynapseTimer().schedule(aggregate, completionTimeoutMillis);
}
aggregate.getLock();
activeAggregates.put(correlateExpression.toString(), aggregate);
}
}
}
} else if (synCtx.getProperty(correlationIdName) != null) {
// if the correlattion cannot be found using the correlateExpression then
// try the default which is through the AGGREGATE_CORRELATION message property
// which is the unique original message id of a split or iterate operation and
// which thus can be used to uniquely group messages into aggregates
Object o = synCtx.getProperty(correlationIdName);
String correlation;
if (o != null && o instanceof String) {
correlation = (String) o;
while (aggregate == null) {
synchronized (lock) {
if (activeAggregates.containsKey(correlation)) {
aggregate = activeAggregates.get(correlation);
if (aggregate != null) {
if (!aggregate.getLock()) {
aggregate = null;
}
} else {
break;
}
} else {
if (synLog.isTraceOrDebugEnabled()) {
synLog.traceOrDebug("Creating new Aggregator - " + (completionTimeoutMillis > 0 ? "expires in : " + (completionTimeoutMillis / 1000) + "secs" : "without expiry time"));
}
if (isAggregationCompleted(synCtx)) {
return false;
}
Double minMsg = -1.0;
if (minMessagesToComplete != null) {
minMsg = Double.parseDouble(minMessagesToComplete.evaluateValue(synCtx));
}
Double maxMsg = -1.0;
if (maxMessagesToComplete != null) {
maxMsg = Double.parseDouble(maxMessagesToComplete.evaluateValue(synCtx));
}
aggregate = new Aggregate(synCtx.getEnvironment(), correlation, completionTimeoutMillis, minMsg.intValue(), maxMsg.intValue(), this, synCtx.getFaultStack().peek());
if (completionTimeoutMillis > 0) {
synchronized (aggregate) {
if (!aggregate.isCompleted()) {
synCtx.getConfiguration().getSynapseTimer().schedule(aggregate, completionTimeoutMillis);
}
}
}
aggregate.getLock();
activeAggregates.put(correlation, aggregate);
}
}
}
} else {
synLog.traceOrDebug("Unable to find aggrgation correlation property");
return true;
}
} else {
synLog.traceOrDebug("Unable to find aggrgation correlation XPath or property");
return true;
}
// if there is an aggregate continue on aggregation
if (aggregate != null) {
// this is a temporary fix
synCtx.getEnvelope().build();
boolean collected = aggregate.addMessage(synCtx);
if (synLog.isTraceOrDebugEnabled()) {
if (collected) {
synLog.traceOrDebug("Collected a message during aggregation");
if (synLog.isTraceTraceEnabled()) {
synLog.traceTrace("Collected message : " + synCtx);
}
}
}
if (aggregate.isComplete(synLog)) {
synLog.traceOrDebug("Aggregation completed - invoking onComplete");
boolean onCompleteSeqResult = completeAggregate(aggregate);
synLog.traceOrDebug("End : Aggregate mediator");
isAggregateComplete = onCompleteSeqResult;
return onCompleteSeqResult;
} else {
aggregate.releaseLock();
}
} else {
// if the aggregation correlation cannot be found then continue the message on the
// normal path by returning true
synLog.traceOrDebug("Unable to find an aggregate for this message - skip");
return true;
}
} catch (JaxenException e) {
handleException("Unable to execute the XPATH over the message", e, synCtx);
}
synLog.traceOrDebug("End : Aggregate mediator");
// When Aggregation is not completed return false to hold the flow
return false;
}
Aggregations