use of org.apache.synapse.core.SynapseEnvironment in project wso2-synapse by wso2.
the class XSLTMediator method performXSLT.
/**
* Perform actual XSLT transformation
* @param synCtx current message
* @param synLog the logger to be used
*/
private void performXSLT(MessageContext synCtx, SynapseLog synLog) {
OMNode sourceNode = source.selectOMNode(synCtx, synLog);
boolean isSoapEnvelope = (sourceNode == synCtx.getEnvelope());
boolean isSoapBody = (sourceNode == synCtx.getEnvelope().getBody());
boolean isSoapHeader = (sourceNode == synCtx.getEnvelope().getHeader());
// Derive actual key from message context
String generatedXsltKey = xsltKey.evaluateValue(synCtx);
// get templates from generatedXsltKey
Templates cachedTemplates = null;
if (synLog.isTraceTraceEnabled()) {
synLog.traceTrace("Transformation source : " + sourceNode.toString());
}
// determine if it is needed to create or create the template
if (isCreationOrRecreationRequired(synCtx)) {
// many threads can see this and come here for acquiring the lock
synchronized (transformerLock) {
// only first thread should create the template
if (isCreationOrRecreationRequired(synCtx)) {
cachedTemplates = createTemplate(synCtx, synLog, generatedXsltKey);
} else {
cachedTemplates = cachedTemplatesMap.get(generatedXsltKey);
}
}
} else {
// If already cached template then load it from cachedTemplatesMap
synchronized (transformerLock) {
cachedTemplates = cachedTemplatesMap.get(generatedXsltKey);
}
}
try {
// perform transformation
Transformer transformer = null;
try {
transformer = cachedTemplates.newTransformer();
} catch (NullPointerException ex) {
handleException("Unable to create Transformer using cached template", ex, synCtx);
}
if (!properties.isEmpty()) {
// set the parameters which will pass to the Transformation
applyProperties(transformer, synCtx, synLog);
}
transformer.setErrorListener(new ErrorListenerImpl(synLog, XSLT_TRANSFORMATION_ACTIVITY));
String outputMethod = transformer.getOutputProperty(OutputKeys.METHOD);
String encoding = transformer.getOutputProperty(OutputKeys.ENCODING);
if (synLog.isTraceOrDebugEnabled()) {
synLog.traceOrDebug("output method: " + outputMethod + "; encoding: " + encoding);
}
ResultBuilderFactory.Output output;
if ("text".equals(outputMethod)) {
synLog.traceOrDebug("Processing non SOAP/XML (text) transformation result");
output = ResultBuilderFactory.Output.TEXT;
} else if (isSoapEnvelope) {
output = ResultBuilderFactory.Output.SOAP_ENVELOPE;
} else {
output = ResultBuilderFactory.Output.ELEMENT;
}
SynapseEnvironment synEnv = synCtx.getEnvironment();
ResultBuilder resultBuilder = resultBuilderFactory.createResultBuilder(synEnv, output);
SourceBuilder sourceBuilder = sourceBuilderFactory.createSourceBuilder(synEnv);
if (synLog.isTraceOrDebugEnabled()) {
synLog.traceOrDebug("Using " + sourceBuilder.getClass().getName());
synLog.traceOrDebug("Using " + resultBuilder.getClass().getName());
}
try {
transformer.transform(sourceBuilder.getSource((OMElement) sourceNode), resultBuilder.getResult());
} finally {
sourceBuilder.release();
}
synLog.traceOrDebug("Transformation completed - processing result");
/**
* If user have set transform.xslt.result.disableBuild property to true, we do not build the message to
* OMElement,
*/
if (targetPropertyName != null && resultBuilder instanceof StreamResultBuilder && synCtx.getProperty(TRANSFORM_XSLT_RESULT_DISABLE_BUILD) != null && synCtx.getProperty(TRANSFORM_XSLT_RESULT_DISABLE_BUILD) instanceof String && "true".equalsIgnoreCase((String) synCtx.getProperty(TRANSFORM_XSLT_RESULT_DISABLE_BUILD))) {
// add result XML string as a message context property to the message
if (synLog.isTraceOrDebugEnabled()) {
synLog.traceOrDebug("Adding result string as message context property : " + targetPropertyName);
}
synCtx.setProperty(targetPropertyName, ((StreamResultBuilder) resultBuilder).getResultAsString());
return;
}
// get the result OMElement
OMElement result = null;
try {
result = resultBuilder.getNode(encoding == null ? null : Charset.forName(encoding));
} catch (Exception e) {
throw new SynapseException("Unable to create an OMElement using XSLT result ", e);
}
if (synLog.isTraceTraceEnabled()) {
synLog.traceTrace("Transformation result : " + result.toString());
}
if (targetPropertyName != null) {
// add result XML as a message context property to the message
if (synLog.isTraceOrDebugEnabled()) {
synLog.traceOrDebug("Adding result as message context property : " + targetPropertyName);
}
synCtx.setProperty(targetPropertyName, result);
} else {
if (synLog.isTraceOrDebugEnabled()) {
synLog.traceOrDebug("Replace " + (isSoapEnvelope ? "SOAP envelope" : isSoapBody ? "SOAP body" : "node") + " with result");
}
if (isSoapEnvelope) {
try {
synCtx.setEnvelope((SOAPEnvelope) result);
} catch (AxisFault ex) {
handleException("Unable to replace SOAP envelope with result", ex, synCtx);
}
} else if (isSoapBody) {
for (Iterator itr = synCtx.getEnvelope().getBody().getChildElements(); itr.hasNext(); ) {
OMElement child = (OMElement) itr.next();
child.detach();
}
for (Iterator itr = result.getChildElements(); itr.hasNext(); ) {
OMElement child = (OMElement) itr.next();
synCtx.getEnvelope().getBody().addChild(child);
}
} else if (isSoapHeader) {
for (Iterator itr = synCtx.getEnvelope().getHeader().getChildElements(); itr.hasNext(); ) {
OMElement child = (OMElement) itr.next();
child.detach();
}
for (Iterator itr = result.getChildElements(); itr.hasNext(); ) {
OMElement child = (OMElement) itr.next();
synCtx.getEnvelope().getHeader().addChild(child);
}
} else {
sourceNode.insertSiblingAfter(result);
sourceNode.detach();
}
}
} catch (TransformerException e) {
handleException("Error performing XSLT transformation using : " + xsltKey, e, synCtx);
}
}
use of org.apache.synapse.core.SynapseEnvironment in project wso2-synapse by wso2.
the class QuartzTaskManager method schedule.
@Override
public boolean schedule(TaskDescription taskDescription) {
assertInitialized();
assertStarted();
if (taskDescription == null) {
throw new SynapseTaskException("Task Description cannot be found", logger);
}
Trigger trigger;
JobDetail jobDetail;
synchronized (lock) {
if (triggerFactory == null) {
throw new SynapseTaskException("TriggerFactory cannot be found", logger);
}
if (jobDetailFactory == null) {
throw new SynapseTaskException("JobDetailFactory cannot be found", logger);
}
trigger = triggerFactory.createTrigger(taskDescription);
if (trigger == null) {
throw new SynapseTaskException("Trigger cannot be created from : " + taskDescription, logger);
}
jobDetail = jobDetailFactory.createJobDetail(taskDescription, taskDescription.getResources(), SimpleQuartzJob.class);
if (jobDetail == null) {
throw new SynapseTaskException("JobDetail cannot be created from : " + taskDescription + " and job class " + taskDescription.getTaskImplClassName(), logger);
}
}
Object clsInstance = taskDescription.getResource(TaskDescription.INSTANCE);
if (clsInstance == null) {
String className = (String) taskDescription.getProperty(TaskDescription.CLASSNAME);
try {
clsInstance = Class.forName(className).newInstance();
if (clsInstance instanceof ManagedLifecycle) {
Object se = properties.get(TaskConstants.SYNAPSE_ENV);
if (!(se instanceof SynapseEnvironment)) {
return false;
}
((ManagedLifecycle) clsInstance).init((SynapseEnvironment) se);
}
for (Object property : taskDescription.getXmlProperties()) {
OMElement prop = (OMElement) property;
logger.debug("Found Property : " + prop.toString());
PropertyHelper.setStaticProperty(prop, clsInstance);
}
} catch (ClassNotFoundException e) {
logger.error("Could not schedule task[" + name + "].", e);
return false;
} catch (InstantiationException e) {
logger.error("Could not schedule task[" + name + "].", e);
return false;
} catch (IllegalAccessException e) {
logger.error("Could not schedule task[" + name + "].", e);
return false;
}
}
if (!(clsInstance instanceof Task)) {
logger.error("Could not schedule task[" + name + "]. Cannot load class " + "org.apache.synapse.startup.quartz.SimpleQuartzJob");
return false;
}
jobDetail.getJobDataMap().put(TaskDescription.INSTANCE, clsInstance);
jobDetail.getJobDataMap().put(TaskDescription.CLASSNAME, clsInstance.getClass().toString());
jobDetail.getJobDataMap().put(TaskConstants.SYNAPSE_ENV, getProperty(TaskConstants.SYNAPSE_ENV));
try {
if (logger.isDebugEnabled()) {
logger.debug("scheduling job : " + jobDetail + " with trigger " + trigger);
}
if (taskDescription.getCount() != 0 && !isTaskRunning(jobDetail.getKey())) {
try {
synchronized (lock) {
scheduler.scheduleJob(jobDetail, trigger);
}
} catch (ObjectAlreadyExistsException e) {
logger.warn("did not schedule the job : " + jobDetail + ". the job is already running.");
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("did not schedule the job : " + jobDetail + ". count is zero.");
}
}
} catch (SchedulerException e) {
throw new SynapseTaskException("Error scheduling job : " + jobDetail + " with trigger " + trigger);
}
logger.info("Scheduled task [" + taskDescription.getName() + "::" + taskDescription.getTaskGroup() + "]");
return true;
}
use of org.apache.synapse.core.SynapseEnvironment in project wso2-synapse by wso2.
the class SimpleQuartzJob method execute.
public void execute(JobExecutionContext ctx) throws JobExecutionException {
String jobName = ctx.getJobDetail().getKey().getName();
if (log.isDebugEnabled()) {
log.debug("Executing task : " + jobName);
}
JobDataMap jdm = ctx.getMergedJobDataMap();
String jobClassName = (String) jdm.get(CLASSNAME);
if (jobClassName == null) {
handleException("No " + CLASSNAME + " in JobDetails");
}
boolean initRequired = false;
Task task = (Task) jdm.get(TaskDescription.INSTANCE);
if (task == null) {
initRequired = true;
}
SynapseEnvironment se = (SynapseEnvironment) jdm.get("SynapseEnvironment");
if (initRequired) {
try {
task = (Task) getClass().getClassLoader().loadClass(jobClassName).newInstance();
} catch (Exception e) {
handleException("Cannot instantiate task : " + jobClassName, e);
}
Set properties = (Set) jdm.get(PROPERTIES);
for (Object property : properties) {
OMElement prop = (OMElement) property;
log.debug("Found Property : " + prop.toString());
PropertyHelper.setStaticProperty(prop, task);
}
// 1. Initialize
if (task instanceof ManagedLifecycle && se != null) {
((ManagedLifecycle) task).init(se);
}
}
// 2. Execute
if (se != null && task != null && se.isInitialized()) {
task.execute();
}
if (initRequired) {
// 3. Destroy
if (task instanceof ManagedLifecycle && se != null) {
((ManagedLifecycle) task).destroy();
}
}
}
use of org.apache.synapse.core.SynapseEnvironment in project wso2-synapse by wso2.
the class IndirectEndpoint method reLoadAndInitEndpoint.
/**
* Reload as needed , either from registry , local entries or predefined endpoints
* @param cc ConfigurationContext
*/
private synchronized void reLoadAndInitEndpoint(ConfigurationContext cc) {
Parameter parameter = cc.getAxisConfiguration().getParameter(SynapseConstants.SYNAPSE_CONFIG);
Parameter synEnvParameter = cc.getAxisConfiguration().getParameter(SynapseConstants.SYNAPSE_ENV);
if (parameter.getValue() instanceof SynapseConfiguration && synEnvParameter.getValue() instanceof SynapseEnvironment) {
SynapseConfiguration synCfg = (SynapseConfiguration) parameter.getValue();
SynapseEnvironment synapseEnvironment = (SynapseEnvironment) synEnvParameter.getValue();
boolean reLoad = (realEndpoint == null);
if (!reLoad) {
Entry entry = synCfg.getEntryDefinition(key);
if (entry != null && entry.isDynamic()) {
if (!entry.isCached() || entry.isExpired()) {
reLoad = true;
}
} else {
// If the endpoint is static we should reload it from the Synapse config
reLoad = true;
}
}
if (reLoad) {
if (log.isDebugEnabled()) {
log.debug("Loading real endpoint with key : " + key);
}
realEndpoint = synCfg.getEndpoint(key);
if (realEndpoint != null && !realEndpoint.isInitialized()) {
realEndpoint.init(synapseEnvironment);
}
} else {
Endpoint epr = synCfg.getEndpoint(key);
if (epr != realEndpoint) {
realEndpoint = epr;
if (realEndpoint != null && !realEndpoint.isInitialized() && realEndpoint instanceof ManagedLifecycle) {
realEndpoint.init(synapseEnvironment);
}
}
}
}
}
use of org.apache.synapse.core.SynapseEnvironment in project wso2-synapse by wso2.
the class SynapseEventSource method receive.
/**
* Override the Message receiver method to accept subscriptions and events
*
* @param mc message context
* @throws AxisFault
*/
public void receive(MessageContext mc) throws AxisFault {
// Create synapse message context from the axis2 message context
SynapseConfiguration synCfg = (SynapseConfiguration) mc.getConfigurationContext().getAxisConfiguration().getParameter(SynapseConstants.SYNAPSE_CONFIG).getValue();
SynapseEnvironment synEnv = (SynapseEnvironment) mc.getConfigurationContext().getAxisConfiguration().getParameter(SynapseConstants.SYNAPSE_ENV).getValue();
org.apache.synapse.MessageContext smc = new Axis2MessageContext(mc, synCfg, synEnv);
// initialize the response message builder using the message context
ResponseMessageBuilder messageBuilder = new ResponseMessageBuilder(mc);
try {
if (EventingConstants.WSE_SUBSCRIBE.equals(mc.getWSAAction())) {
// add new subscription to the SynapseSubscription store through subscription manager
processSubscriptionRequest(mc, messageBuilder);
} else if (EventingConstants.WSE_UNSUBSCRIBE.equals(mc.getWSAAction())) {
// Unsubscribe the matching subscription
processUnSubscribeRequest(mc, messageBuilder);
} else if (EventingConstants.WSE_GET_STATUS.equals(mc.getWSAAction())) {
// Response with the status of the subscription
processGetStatusRequest(mc, messageBuilder);
} else if (EventingConstants.WSE_RENEW.equals(mc.getWSAAction())) {
// Renew subscription
processReNewRequest(mc, messageBuilder);
} else {
// Treat as an Event
if (log.isDebugEnabled()) {
log.debug("Event received");
}
dispatchEvents(smc);
}
} catch (EventException e) {
handleException("Subscription manager processing error", e);
}
}
Aggregations