use of org.apache.synapse.SynapseException in project wso2-synapse by wso2.
the class AbstractDBMediator method getPreparedStatement.
/**
* Return a Prepared statement for the given Statement object, which is ready to be executed
*
* @param stmnt SQL stataement to be executed
* @param con The connection to be used
* @param msgCtx Current message context
* @return a PreparedStatement
* @throws SQLException on error
*/
protected PreparedStatement getPreparedStatement(Statement stmnt, Connection con, MessageContext msgCtx) throws SQLException {
SynapseLog synLog = getLog(msgCtx);
if (synLog.isTraceOrDebugEnabled()) {
synLog.traceOrDebug("Getting a connection from DataSource " + getDSName() + " and preparing statement : " + stmnt.getRawStatement());
}
if (con == null) {
String msg = "Connection from DataSource " + getDSName() + " is null.";
log.error(msg);
throw new SynapseException(msg);
}
if (dataSource instanceof BasicDataSource) {
BasicDataSource basicDataSource = (BasicDataSource) dataSource;
int numActive = basicDataSource.getNumActive();
int numIdle = basicDataSource.getNumIdle();
String connectionId = Integer.toHexString(con.hashCode());
DBPoolView dbPoolView = getDbPoolView();
if (dbPoolView != null) {
dbPoolView.setNumActive(numActive);
dbPoolView.setNumIdle(numIdle);
dbPoolView.updateConnectionUsage(connectionId);
}
if (synLog.isTraceOrDebugEnabled()) {
synLog.traceOrDebug("[ DB Connection : " + con + " ]");
synLog.traceOrDebug("[ DB Connection instance identifier : " + connectionId + " ]");
synLog.traceOrDebug("[ Number of Active Connection : " + numActive + " ]");
synLog.traceOrDebug("[ Number of Idle Connection : " + numIdle + " ]");
}
}
PreparedStatement ps = con.prepareStatement(stmnt.getRawStatement());
// set parameters if any
List<Statement.Parameter> params = stmnt.getParameters();
int column = 1;
for (Statement.Parameter param : params) {
if (param == null) {
continue;
}
String value = (param.getPropertyName() != null ? param.getPropertyName() : param.getXpath().stringValueOf(msgCtx));
if (synLog.isTraceOrDebugEnabled()) {
synLog.traceOrDebug("Setting as parameter : " + column + " value : " + value + " as JDBC Type : " + param.getType() + "(see java.sql.Types for valid " + "types)");
}
switch(param.getType()) {
// according to J2SE 1.5 /docs/guide/jdbc/getstart/mapping.html
case Types.CHAR:
case Types.VARCHAR:
case Types.LONGVARCHAR:
{
if (value != null && value.length() != 0) {
ps.setString(column++, value);
} else {
ps.setString(column++, null);
}
break;
}
case Types.NUMERIC:
case Types.DECIMAL:
{
if (value != null && value.length() != 0) {
ps.setBigDecimal(column++, new BigDecimal(value));
} else {
ps.setBigDecimal(column++, null);
}
break;
}
case Types.BIT:
{
if (value != null && value.length() != 0) {
ps.setBoolean(column++, Boolean.parseBoolean(value));
} else {
ps.setNull(column++, Types.BIT);
}
break;
}
case Types.TINYINT:
{
if (value != null && value.length() != 0) {
ps.setByte(column++, Byte.parseByte(value));
} else {
ps.setNull(column++, Types.TINYINT);
}
break;
}
case Types.SMALLINT:
{
if (value != null && value.length() != 0) {
ps.setShort(column++, Short.parseShort(value));
} else {
ps.setNull(column++, Types.SMALLINT);
}
break;
}
case Types.INTEGER:
{
if (value != null && value.length() != 0) {
ps.setInt(column++, Integer.parseInt(value));
} else {
ps.setNull(column++, Types.INTEGER);
}
break;
}
case Types.BIGINT:
{
if (value != null && value.length() != 0) {
ps.setLong(column++, Long.parseLong(value));
} else {
ps.setNull(column++, Types.BIGINT);
}
break;
}
case Types.REAL:
{
if (value != null && value.length() != 0) {
ps.setFloat(column++, Float.parseFloat(value));
} else {
ps.setNull(column++, Types.REAL);
}
break;
}
case Types.FLOAT:
{
if (value != null && value.length() != 0) {
ps.setDouble(column++, Double.parseDouble(value));
} else {
ps.setNull(column++, Types.FLOAT);
}
break;
}
case Types.DOUBLE:
{
if (value != null && value.length() != 0) {
ps.setDouble(column++, Double.parseDouble(value));
} else {
ps.setNull(column++, Types.DOUBLE);
}
break;
}
// skip BINARY, VARBINARY and LONGVARBINARY
case Types.DATE:
{
if (value != null && value.length() != 0) {
ps.setDate(column++, Date.valueOf(value));
} else {
ps.setNull(column++, Types.DATE);
}
break;
}
case Types.TIME:
{
if (value != null && value.length() != 0) {
ps.setTime(column++, Time.valueOf(value));
} else {
ps.setNull(column++, Types.TIME);
}
break;
}
case Types.TIMESTAMP:
{
if (value != null && value.length() != 0) {
ps.setTimestamp(column++, Timestamp.valueOf(value));
} else {
ps.setNull(column++, Types.TIMESTAMP);
}
break;
}
// skip CLOB, BLOB, ARRAY, DISTINCT, STRUCT, REF, JAVA_OBJECT
default:
{
String msg = "Trying to set an un-supported JDBC Type : " + param.getType() + " against column : " + column + " and statement : " + stmnt.getRawStatement() + " used by a DB mediator against DataSource : " + getDSName() + " (see java.sql.Types for valid type values)";
handleException(msg, msgCtx);
}
}
}
if (synLog.isTraceOrDebugEnabled()) {
synLog.traceOrDebug("Successfully prepared statement : " + stmnt.getRawStatement() + " against DataSource : " + getDSName());
}
return ps;
}
use of org.apache.synapse.SynapseException in project wso2-synapse by wso2.
the class XSLTMediator method addAttribute.
/**
* Add an attribute to be set on the {@link TransformerFactory} used by this mediator instance.
* This method can also be used to enable some Synapse specific optimizations and
* enhancements as described in the documentation of this class.
*
* @param name The name of the feature
* @param value should this feature enable?
*
* @see TransformerFactory#setAttribute(String, Object)
* @see XSLTMediator
*/
public void addAttribute(String name, String value) {
MediatorProperty mp = new MediatorProperty();
mp.setName(name);
mp.setValue(value);
transformerFactoryAttributes.add(mp);
if (SOURCE_BUILDER_FACTORY.equals(name) || RESULT_BUILDER_FACTORY.equals(name)) {
Object instance;
try {
instance = Class.forName(value).newInstance();
} catch (ClassNotFoundException e) {
String msg = "The class specified by the " + name + " attribute was not found";
log.error(msg, e);
throw new SynapseException(msg, e);
} catch (Exception e) {
String msg = "The class " + value + " could not be instantiated";
log.error(msg, e);
throw new SynapseException(msg, e);
}
if (SOURCE_BUILDER_FACTORY.equals(name)) {
sourceBuilderFactory = (SourceBuilderFactory) instance;
} else {
resultBuilderFactory = (ResultBuilderFactory) instance;
}
} else {
try {
transFact.setAttribute(name, value);
} catch (IllegalArgumentException e) {
String msg = "Error occurred when setting attribute to the TransformerFactory";
log.error(msg, e);
throw new SynapseException(msg, e);
}
}
}
use of org.apache.synapse.SynapseException 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.SynapseException in project wso2-synapse by wso2.
the class Target method insert.
public void insert(MessageContext synContext, ArrayList<OMNode> sourceNodeList, SynapseLog synLog) throws JaxenException {
if (targetType == EnrichMediator.CUSTOM) {
assert xpath != null : "Xpath cannot be null for CUSTOM";
if (sourceNodeList.isEmpty()) {
synLog.error("Cannot Enrich message from an empty source.");
return;
}
Object targetObj = xpath.selectSingleNode(synContext);
// if the type custom is used to enrich a property, It'll be handled in a different method
if (xpath.getExpression().startsWith(SynapseXPathConstants.GET_PROPERTY_FUNCTION)) {
this.handleProperty(xpath, synContext, sourceNodeList, synLog);
} else {
if (targetObj instanceof SOAPHeaderImpl) {
OMElement targetElem = (OMElement) targetObj;
ArrayList<OMNode> headerSourceNodeList = new ArrayList<>();
for (OMNode o : sourceNodeList) {
OMElement ins = ((OMElement) o).cloneOMElement();
SOAPFactory fac = (SOAPFactory) synContext.getEnvelope().getOMFactory();
try {
headerSourceNodeList.add(ElementHelper.toSOAPHeaderBlock(ins, fac));
} catch (Exception e) {
log.error("Error occurred while transforming the OMElement to SOAPHeaderBlock ", e);
throw new JaxenException(e);
}
}
insertElement(headerSourceNodeList, targetElem, synLog);
} else if (targetObj instanceof OMElement) {
OMElement targetElem = (OMElement) targetObj;
insertElement(sourceNodeList, targetElem, synLog);
} else if (targetObj instanceof OMText) {
OMText targetText = (OMText) targetObj;
if (sourceNodeList.get(0) instanceof OMText) {
if (targetText.getParent() != null) {
Object parent = targetText.getParent();
if (parent instanceof OMElement) {
((OMElement) parent).setText(((OMText) sourceNodeList.get(0)).getText());
}
}
} else if (sourceNodeList.get(0) instanceof OMElement) {
Object targetParent = targetText.getParent();
if (targetParent instanceof OMElement) {
targetText.detach();
synchronized (sourceNodeList.get(0)) {
((OMElement) targetParent).addChild(sourceNodeList.get(0));
}
}
}
} else if (targetObj instanceof OMAttribute) {
OMAttribute attribute = (OMAttribute) targetObj;
attribute.setAttributeValue(((OMText) sourceNodeList.get(0)).getText());
} else {
synLog.error("Invalid Target object to be enrich.");
throw new SynapseException("Invalid Target object to be enrich.");
}
}
} else if (targetType == EnrichMediator.BODY) {
SOAPEnvelope env = synContext.getEnvelope();
SOAPBody body = env.getBody();
OMElement e = body.getFirstElement();
if (e != null) {
insertElement(sourceNodeList, e, synLog);
} else {
// if the body is empty just add as a child
for (OMNode elem : sourceNodeList) {
if (elem instanceof OMElement) {
synchronized (elem) {
body.addChild(elem);
}
} else {
synLog.error("Invalid Object type to be inserted into message body");
}
}
}
} else if (targetType == EnrichMediator.ENVELOPE) {
OMNode node = sourceNodeList.get(0);
if (node instanceof SOAPEnvelope) {
try {
synContext.setEnvelope((SOAPEnvelope) node);
} catch (AxisFault axisFault) {
synLog.error("Failed to set the SOAP Envelope");
throw new SynapseException("Failed to set the SOAP Envelope");
}
} else {
synLog.error("SOAPEnvelope is expected");
throw new SynapseException("A SOAPEnvelope is expected");
}
} else if (targetType == EnrichMediator.PROPERTY) {
assert property != null : "Property cannot be null for PROPERTY type";
if (action != null && property != null) {
Object propertyObj = synContext.getProperty(property);
OMElement documentElement = null;
try {
if (isOMElement(propertyObj)) {
documentElement = (OMElement) propertyObj;
} else {
documentElement = AXIOMUtil.stringToOM((String) propertyObj);
}
} catch (Exception e1) {
// just ignoring the phaser error
}
if (documentElement != null && action.equals(ACTION_ADD_CHILD)) {
// logic should valid only when adding child elements, and other cases
// such as sibling and replacement using the else condition
insertElement(sourceNodeList, documentElement, synLog);
if (isOMElement(propertyObj)) {
synContext.setProperty(property, documentElement);
} else {
synContext.setProperty(property, documentElement.getText());
}
} else {
synContext.setProperty(property, sourceNodeList);
}
} else {
synContext.setProperty(property, sourceNodeList);
}
}
}
use of org.apache.synapse.SynapseException 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() + "]");
}
}
Aggregations