How to Add new Namespace to SOAP Envelope


There are some points you may face instead of keeping the body content’s namespace in the SOAP envelope, in such scenarios you can use Enrich Mediator to get this done.

Add the following enrich mediators three times and add new namespace to envelope where ever you want. And then use the new namespace inside a payload factory mediator.

   <enrich>
      <source type="body" />
      <target type="property" property="ORG_BODY" />
   </enrich>
   <enrich>
      <source type="inline">
         <soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope" xmlns:newns="http://abc.com">
            <soapenv:Body />
         </soapenv:Envelope>
      </source>
      <target type="envelope" />
   </enrich>
   <enrich>
      <source type="property" property="ORG_BODY" />
      <target type="body" />
   </enrich>
   <payloadfactory>
      <!--we have to define the new namespace here too but it doesn't appear in the new body since it's already defined in the envelope tag -->
      <newns:bodycontent xmlsns:newns="http://abc.com">.....</newns:bodycontent>
   </payloadfactory>

Adding CA Signed certificate to WSO2 UES.


Many users prefer to install a CA signed certificate into the product, in-order to make products more secure.

You will get root certificate, intermediate certificates and the domain certificate from the CA as follows

AddTrustExternalCARoot.crt
COMODORSADomainValidationSecureServerCA.crt
COMODORSAAddTrustCA.crt
demo.abc.com.crt

The what you have to do is import these certificates in following order to the keystore file which the -genkeypair and -certreq were done (wso2carbon.jks).

keytool -importcert -keystore wso2carbon.jks -file AddTrustExternalCARoot.crt -alias somealias1 -trustcacerts
keytool -importcert -keystore wso2carbon.jks -file COMODORSAAddTrustCA.crt -alias somealias2
keytool -importcert -keystore wso2carbon.jks -file COMODORSADomainValidationSecureServerCA.crt -alias somealias3
keytool -importcert -keystore wso2carbon.jks -file demo_site_domain.crt -alias wso2carbon

If the response of the last command should be

Certificate reply was installed in keystore

not the

Certificate was added to keystore

Then copy the wso2carbon.jks to UES_HOME/repository/resources/security and it will replace the existing wso2carbon.jks file.

Then change the
Password and KeyPassword found in following classes with the one you used.

 repository/conf/identity.xml
repository/conf/carbon.xml

Then restart the server, if it doesn’t complain any password issue then it means, you have successfully configured the new keystore with CA signed certificate.

Usage of a Respond Mediator in WSO2 ESB


In a situation like you want to send a message back to the client depending on some conditions, we can use Respond Mediator. This mediator stops the processing on the current message and sends the message back to the client as a response. So just before this mediator we can use mediator like Payload Factory Mediator to construct the response.

Following is a simple use case for this,

Continue reading

How to move to out sequence from in sequence in WSO2 ESB


I faced a situation, where I need to send a custom response after the request is being sent to the message queue. I couldn’t use FORCE_SC_ACCEPT property as I need to send a response. In such a case we can use loopback mediator which switch from in sequence to out sequence and in side the out sequence payload factory mediator can be used to construct the custom response.

Simple skeleton as follows,

Continue reading

JSON Support for WSO2 ESB Class Mediator


In WSO2 documentation you can find how the following mediators can be used with json payloads.

  • Log Mediator
  • Property Mediator
  • PayloadFactory Mediator
  • Switch Mediator
  • Filter Mediator

But there’s no any clue about how the class mediator can be used with json payloads. Following is the way you can do manipulation to json payload using class mediator.

In this post I just add a new tag to existing json payload

package com.wso2.test;

import org.apache.synapse.MessageContext;
import org.apache.synapse.commons.json.JsonUtil;
import org.json.JSONObject;
import org.apache.synapse.core.axis2.Axis2MessageContext;
import org.apache.synapse.mediators.AbstractMediator;

/**
* Class mediator for JSON transformation.
*
* @author isuru
*
*/
public class JSONClassMediator extends AbstractMediator {

/**
* Holds the name.
*/
private String nameParam;

/**
* Mediate overridden method to set the token property.
*/
@Override
public boolean mediate(MessageContext context) {

try {

// Getting the json payload to string
String jsonPayloadToString = JsonUtil
.jsonPayloadToString(((Axis2MessageContext) context)
.getAxis2MessageContext());
// Make a json object
JSONObject jsonBody = new JSONObject(jsonPayloadToString);

// Adding the name:nameParam.
jsonBody.put("name", getNameParam());

String transformedJson = jsonBody.toString();

// Setting the new json payload.
JsonUtil.newJsonPayload(
((Axis2MessageContext) context).getAxis2MessageContext(),
transformedJson, true, true);

System.out.println("Transformed JSON body:\n" + transformedJson);

} catch (Exception e) {
System.err.println("Error occurred: " + e);
return false;
}

return true;
}

/**
* @return the nameParam
*/
public final String getNameParam() {
return nameParam;
}

/**
* @param nameParam
* the nameParam to set
*/
public final void setNameParam(String nameParam) {
this.nameParam = nameParam;
}
}

Continue reading

Usage of Fault mediator in WSO2 ESB


This post explains, an usage of Fault mediator in wso2 ESB.

The sample scenario, refuses and sends an exception back to the client based on the Content-Type header property.

This example is tested in ESB 4.7.0

First validate the content-type - using filter mediator

If true, send back an exception to the client - using fault mediator

If false, continue the flow

Here is the sample proxy,

Continue reading

How to send an Email using WSO2 ESB


This post explains how to send an email in WSO2 ESB using Payload Factory mediator . You can find plenty of examples which do the same by using Script mediator.

This example is tested in WSO2 ESB 4.8

1.Uncomment and configure the SMTP server information ESB_HOME/repository/conf/axis/axis2.xml file as below

<transportSender name="mailto" class="org.apache.axis2.transport.mail.MailTransportSender">
   <parameter name="mail.smtp.host">smtp.gmail.com</parameter>
   <parameter name="mail.smtp.port">587</parameter>
   <parameter name="mail.smtp.starttls.enable">true</parameter>
   <parameter name="mail.smtp.auth">true</parameter>
   <parameter name="mail.smtp.user">esbadmin</parameter>
   <parameter name="mail.smtp.password">*****</parameter>
   <parameter name="mail.smtp.from">esbadmin@gmail.com</parameter>
</transportSender>

Continue reading

WSO2 DSS Scheduled Task Example


This post explains how the scheduled task works in WSO2 DSS

This example is tested in WSO2 DSS 3.0.1

1. Write the following class which extends the org.wso2.carbon.dataservices.task.DataTask interface.

package com.example.DssSchedlueTask;

import java.util.HashMap;
import java.util.Map;
import org.wso2.carbon.dataservices.core.DataServiceFault;
import org.wso2.carbon.dataservices.core.engine.ParamValue;
import org.wso2.carbon.dataservices.task.DataTask;
import org.wso2.carbon.dataservices.task.DataTaskContext;

public class ScheduledDataTask_abcCompany implements DataTask {

	public void execute(DataTaskContext ctx) {
		System.out.println("Data Task executing...");
		String soldItems = getSoldItems();
		Map<String, ParamValue> params = new HashMap<String, ParamValue>();
		params.put("soldItems", new ParamValue(soldItems));
		params.put("productCode", new ParamValue("0001a3"));
		try {
			ctx.invokeOperation("abcCompany", "UpdateSales", params);
			System.out.println("Successfully updated the database. \tSoldItems = "+soldItems);
		} catch (DataServiceFault e) {
			System.out.println("Error...."+e.getMessage());
		}
    }

	private String getSoldItems(){
		int soldItems = (int )(Math.random() * 10000 + 1);
		return Integer.toString(soldItems);
	}
}

Assume that you are getting sold items from another service, here you will get a random number for the sold items, and you are going to update your system with that value.

2.Then create the jar of the above class and copy it to the DSS_HOME/repository/components/lib folder and start the WSO2 DSS server.

3. Create a Keyspace name ‘abcCompany’ in cassandra db.  Then create a columnfamily name ‘salesDetails’ in abcCompany keyspace.

cqlsh:abccompany> CREATE COLUMNFAMILY salesDetails ( productCode varchar PRIMARY KEY , productName varchar , soldItems int, instock int) ;

4. Insert following dummy values to the above created column family.

cqlsh:abccompany> INSERT INTO abcCompany.salesDetails (productCode, productName, soldItems, instock) VALUES ( '0001a3', 'phone a3', 9999, 10000);
cqlsh:abccompany> INSERT INTO abcCompany.salesDetails (productCode, productName, soldItems, instock) VALUES ( '0001b2', 'phone b2', 99, 100);
cqlsh:abccompany> INSERT INTO abcCompany.salesDetails (productCode, productName, soldItems, instock) VALUES ( '0002x5', 'phone x5', 9, 10);

Continue reading

WSO2 ESB Rule Mediator Example


This post is to demonstrate how to write Rule mediator in WSO2 ESB.
This example is tested in WSO2 ESB 4.7.0
The example, get the list of students with marks for their subjects and, inside the proxy it check whether the each student has passed the each subject and print the result. To define type of the input data POJO adapters are used in this example.

1.Write the following POJO classes.

Student class

package com.example.rulemediator;

public class Student {

	private String indexNumber;
	private String name;
	private Subject[] subjects;

	public String getIndexNumber() {
		return indexNumber;
	}
	public void setIndexNumber(String indexNumber) {
		this.indexNumber = indexNumber;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Subject[] getSubjects() {
		return subjects;
	}
	public void setSubjects(Subject[] subjects) {
		this.subjects = subjects;
	}
}

Subject class

package com.example.rulemediator;

public class Subject {

	private String subjectCode;
	private String subjectName;
	private int score;

	public String getSubjectCode() {
		return subjectCode;
	}
	public void setSubjectCode(String subjectCode) {
		this.subjectCode = subjectCode;
	}
	public String getSubjectName() {
		return subjectName;
	}
	public void setSubjectName(String subjectName) {
		this.subjectName = subjectName;
	}
	public int getScore() {
		return score;
	}
	public void setScore(int score) {
		this.score = score;
	}
}

2. Then create a Jar file containing above classes and copy it to ESB_HOME/repository/components/lib folder and start the ESB.

Continue reading