Search in sources :

Example 1 with SynapseEnvironment

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);
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) ResultBuilder(org.apache.synapse.util.jaxp.ResultBuilder) StreamResultBuilder(org.apache.synapse.util.jaxp.StreamResultBuilder) Transformer(javax.xml.transform.Transformer) StreamResultBuilder(org.apache.synapse.util.jaxp.StreamResultBuilder) SynapseException(org.apache.synapse.SynapseException) SynapseEnvironment(org.apache.synapse.core.SynapseEnvironment) SourceBuilder(org.apache.synapse.util.jaxp.SourceBuilder) Templates(javax.xml.transform.Templates) OMElement(org.apache.axiom.om.OMElement) TransformerException(javax.xml.transform.TransformerException) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) SynapseException(org.apache.synapse.SynapseException) OMNode(org.apache.axiom.om.OMNode) Iterator(java.util.Iterator) StreamResultBuilderFactory(org.apache.synapse.util.jaxp.StreamResultBuilderFactory) DOOMResultBuilderFactory(org.apache.synapse.util.jaxp.DOOMResultBuilderFactory) ResultBuilderFactory(org.apache.synapse.util.jaxp.ResultBuilderFactory) TransformerException(javax.xml.transform.TransformerException)

Example 2 with SynapseEnvironment

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;
}
Also used : Task(org.apache.synapse.task.Task) SchedulerException(org.quartz.SchedulerException) SynapseEnvironment(org.apache.synapse.core.SynapseEnvironment) OMElement(org.apache.axiom.om.OMElement) SynapseTaskException(org.apache.synapse.task.SynapseTaskException) ManagedLifecycle(org.apache.synapse.ManagedLifecycle) JobDetail(org.quartz.JobDetail) Trigger(org.quartz.Trigger) ObjectAlreadyExistsException(org.quartz.ObjectAlreadyExistsException)

Example 3 with SynapseEnvironment

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();
        }
    }
}
Also used : JobDataMap(org.quartz.JobDataMap) Task(org.apache.synapse.task.Task) Set(java.util.Set) SynapseEnvironment(org.apache.synapse.core.SynapseEnvironment) OMElement(org.apache.axiom.om.OMElement) ManagedLifecycle(org.apache.synapse.ManagedLifecycle) JobExecutionException(org.quartz.JobExecutionException)

Example 4 with SynapseEnvironment

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);
                }
            }
        }
    }
}
Also used : Entry(org.apache.synapse.config.Entry) SynapseEnvironment(org.apache.synapse.core.SynapseEnvironment) Axis2SynapseEnvironment(org.apache.synapse.core.axis2.Axis2SynapseEnvironment) Parameter(org.apache.axis2.description.Parameter) SynapseConfiguration(org.apache.synapse.config.SynapseConfiguration) ManagedLifecycle(org.apache.synapse.ManagedLifecycle)

Example 5 with 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);
    }
}
Also used : EventException(org.wso2.eventing.exceptions.EventException) SynapseEnvironment(org.apache.synapse.core.SynapseEnvironment) ResponseMessageBuilder(org.apache.synapse.eventing.builders.ResponseMessageBuilder) SynapseConfiguration(org.apache.synapse.config.SynapseConfiguration) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Aggregations

SynapseEnvironment (org.apache.synapse.core.SynapseEnvironment)67 Axis2SynapseEnvironment (org.apache.synapse.core.axis2.Axis2SynapseEnvironment)50 SynapseConfiguration (org.apache.synapse.config.SynapseConfiguration)49 AxisConfiguration (org.apache.axis2.engine.AxisConfiguration)44 ConfigurationContext (org.apache.axis2.context.ConfigurationContext)43 Test (org.junit.Test)40 OMElement (org.apache.axiom.om.OMElement)35 Parameter (org.apache.axis2.description.Parameter)29 MessageContext (org.apache.synapse.MessageContext)18 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)18 ArrayList (java.util.ArrayList)8 AddressEndpoint (org.apache.synapse.endpoints.AddressEndpoint)8 Endpoint (org.apache.synapse.endpoints.Endpoint)8 SOAPEnvelope (org.apache.axiom.soap.SOAPEnvelope)6 HashMap (java.util.HashMap)5 OMDocument (org.apache.axiom.om.OMDocument)4 SynapseException (org.apache.synapse.SynapseException)4 TestMessageContext (org.apache.synapse.TestMessageContext)4 IOException (java.io.IOException)3 ManagedLifecycle (org.apache.synapse.ManagedLifecycle)3