Translate

Creating a Carbon Component using WSO2 Carbon Component Archetype

A Carbon Component is an OSGi bundle which has a dependency on Carbon Kernel.
Using WSO2 Carbon Component Archetype which has been published to maven central, you can create a simple Carbon Component with one command.

Eg:
mvn archetype:generate -DarchetypeGroupId=org.wso2.carbon -DarchetypeArtifactId=org.wso2.carbon.archetypes.component -DarchetypeVersion=5.0.0  -DgroupId=org.sample -DartifactId=org.sample.project -Dversion=1.0.0 -Dpackage=org.sample.project


Above command will create a Carbon Component with the following structure.

org.sample.project
├── pom.xml
└── src
    └── main
        └── java
            └── org
                └── sample
                    └── project
                        ├── GreeterImpl.java
                        ├── Greeter.java
                        └── internal
                            ├── DataHolder.java
                            └── ServiceComponent.java

This Carbon Component consumes an OSGi service which is exposed from Carbon Core and also registers an OSGi service of its own.

If you do not pass the parameters for the project then the default values will be applied.

You can find the source for this archetype here.

Creating a generic OSGi bundle using WSO2 Carbon Bundle Archetype

You can create a generic OSGi bundle using one command with WSO2 Carbon Bundle Archetype.
Even though the name is WSO2 Carbon Bundle Archetype which has been published to maven central, this is a generic OSGi bundle.

Eg:
Execute the following command. The groupID of the archetype is org.wso2.carbon,
The artifactID of the archetype is org.wso2.carbon.archetypes.bundle  and the version of the archetype is  5.0.0

mvn archetype:generate -DarchetypeGroupId=org.wso2.carbon -DarchetypeArtifactId=org.wso2.carbon.archetypes.bundle -DarchetypeVersion=5.0.0  -DgroupId=org.sample -DartifactId=org.sample.project -Dversion=1.0.0 -Dpackage=org.sample.project


 This will create a project with the following structure.

org.sample.project
├── pom.xml
└── src
    ├── main
    │   └── java
    │       └── org
    │           └── sample
    │               └── project
    │                   ├── Greeter.java
    │                   └── internal
    │                       └── Activator.java
    └── test
        └── java
            └── org
                └── sample
                    └── project
                        └── GreeterTest.java

If you do not pass the parameters for the project then the default values will be applied.

The source for the archetype can be found here.

Unmarshalling an XML file with JAXB

This is a simple example for unmarshalling an XML file.

This is the XML file we are going to unmarshall
<?xml version="1.0" encoding="utf-8"?>
<order>
<order-id>002</order-id>
<price>1000000</price>
<items>
<no-of-items>4</no-of-items>
<itemList>
<item-name>item-a</item-name>
<item-name>item-b</item-name>
<item-name>item-c</item-name>
<item-name>item-d</item-name>
</itemList>
</items>
</order>
view raw order.xml hosted with ❤ by GitHub
This is the schema of the above XML file
<?xml version="1.0" encoding="UTF-8"?>
<schema version="1.0" xmlns="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" >
<element name="order">
<complexType>
<sequence>
<element name="order-id" type="string" minOccurs="1" maxOccurs="1"/>
<element name="price" type="string" minOccurs="1" maxOccurs="1"/>
<element name="items" minOccurs="1" maxOccurs="1">
<complexType>
<sequence>
<element name="no-of-items" type="int" minOccurs="1" maxOccurs="1"/>
<element name="itemList" minOccurs="1" maxOccurs="1">
<complexType>
<sequence>
<element name="item-name" type="string" minOccurs="1" maxOccurs="unbounded"/>
</sequence>
</complexType>
</element>
</sequence>
</complexType>
</element>
</sequence>
</complexType>
</element>
</schema>
view raw schema.xsd hosted with ❤ by GitHub
Now let's create Order.java
Here for each complex type I have created an inner class.
And for the element "item-name" which has the maxOccurs=unbounded, I have used a List.
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"orderId",
"price",
"items"
})
@XmlRootElement(name = "order")
public class Order {
@XmlElement(name = "order-id", required = true)
private String orderId;
@XmlElement(name = "price" ,required = true)
private String price;
@XmlElement(name="items", required = true)
private Items items;
public String getOrderId() {
return orderId;
}
public void setOrderId(String value) {
orderId = value;
}
public String getPrice() {
return price;
}
public void setPrice(String value) {
price = value;
}
public Items getItems() {
return items;
}
public void setItems(Items value) {
items = value;
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"noOfItems",
"itemList"
})
public static class Items {
@XmlElement(name = "no-of-items")
private int noOfItems;
@XmlElement(name="itemList", required = true)
private ItemList itemList;
public int getNoOfItems() {
return noOfItems;
}
public void setNoOfItems(int value) {
noOfItems = value;
}
public ItemList getItemList() {
return itemList;
}
public void setItemList(ItemList value) {
itemList = value;
}
@XmlAccessorType(XmlAccessType.FIELD)
public static class ItemList {
@XmlElement(name = "item-name", required = true)
private List<String> itemName;
public List<String> getItemName() {
if (itemName == null) {
itemName = new ArrayList<String>();
}
return itemName;
}
}
}
}
view raw Order.java hosted with ❤ by GitHub
Another thing is @XmlAccessorType(XmlAccessType.FIELD) is needed only if the annotated fields inside the class have public setters.  If you don't have public setters for the annotated fields inside the class you don't need to annotate the class.

Now let's write the code for unmarshalling.
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;
/**
* Created by manurip on 7/12/15.
*/
public class OrderUnmarshallar {
private static OrderUnmarshallar instance = null;
private OrderUnmarshallar(){
}
public static OrderUnmarshallar getJAXBUnmarshallar(){
if(instance==null){
instance=new OrderUnmarshallar();
}
return instance;
}
public Order unmarshall(File XMLfile){
Order order=null;
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Order.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
order = (Order) jaxbUnmarshaller.unmarshal(XMLfile);
} catch (JAXBException e) {
e.printStackTrace();
}
return order;
}
public static void main(String[] args) {
Order order=getJAXBUnmarshallar().unmarshall(new File("/path/to/order.xml"));
System.out.println(order.getOrderId());
System.out.println(order.getPrice());
System.out.println(order.getItems().getNoOfItems());
for(String item:order.getItems().getItemList().getItemName()){
System.out.println(item);
}
}
}
  

Google Summer of Code 2015



This year also I'm participating Google Summer of Code with Eclipse foundation.

My project is Implementing translation between Proj4 and Well-Known-Text in Geotrellis which is a high performance geoprocessing engine and programming toolkit.

Project description in Google Melange can be found here.

Writing a simple web service and a client with Axis2

1. The service

Here a simple POJO service will be created. For simplicity the service will have only two operations.

1. Save an order which consists of an index(String) and a price(Double)
The order will be saved to an xml file.

2. Retrieve the price given the index.



First create a Java Project.

Now inside package orderprocessing.data I create the Order POJO.

package orderprocessing.data;
/**
* Created by manurip on 6/28/15.
*/
public class Order{
private double price;
private String index;
public Order(String index, double price){
this.index = index;
this.price = price;
}
public String getIndex(){
return index;
}
public double getPrice() {
return price;
}
}
view raw Order.java hosted with ❤ by GitHub
Inside the package orderprocessing.service I create OrderProcessingService Class.

package orderprocessing.service;
import orderprocessing.data.Order;
/**
* Created by manurip on 6/28/15.
*/
public class OrderProcessingService {
/*
* This is a test method
*/
public String sayHello() {
return "Hello";
}
public String addOrder(String index,Double price) {
Order newOrder = new Order(index,price);
XMLWriterDOM.getInstance().saveOrder(newOrder);
Order retrieved = XMLReaderDOM.getInstance().retrieveOrder(index);
if(retrieved!= null){
return "Added Order. Index:"+retrieved.getIndex()+" Price:"+retrieved.getPrice();
}
else{
return "Unable to add order";
}
}
public String getPrice(String index) {
String result = "NONE";
Order order = XMLReaderDOM.getInstance().retrieveOrder(index);
if(order!=null){
result = Double.toString(order.getPrice());
}
System.out.println("Price Retrived. Index=" + index
+ ", Price=" + result);
return result;
}
}
In order to save orders to an XML file I create XMLWriterDOM.java.
package orderprocessing.service;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import orderprocessing.data.Order;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class XMLWriterDOM {
private static XMLWriterDOM instance = null;
private final String retrievePath;
private XMLWriterDOM(){
retrievePath="/path/to/orders.xml";
}
public static XMLWriterDOM getInstance() {
if(instance == null){
instance= new XMLWriterDOM();
}
return instance;
}
public void saveOrder(Order order){
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
try {
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(retrievePath);
Element rootElement = doc.getDocumentElement();
rootElement.appendChild(getOrder(order, doc));
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult console = new StreamResult(System.out);
StreamResult file = new StreamResult(new File(retrievePath));
transformer.transform(source, console);
transformer.transform(source, file);
System.out.println("DONE");
} catch (Exception e) {
e.printStackTrace();
}
}
private Node getOrder(Order order,Document doc){
Element orderElement = doc.createElement("Order");
Element indexElement = doc.createElement("index");
indexElement.setTextContent(order.getIndex());
Element priceElement = doc.createElement("price");
priceElement.setTextContent(Double.toString(order.getPrice()));
orderElement.appendChild(indexElement);
orderElement.appendChild(priceElement);
return orderElement;
}
}
To retrieve orders from the XML file I create XMLReader.java
package orderprocessing.service;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import orderprocessing.data.Order;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XMLReaderDOM {
private static XMLReaderDOM instance = null;
private final String savePath;
private XMLReaderDOM(){
savePath="/path/to/orders.xml";
}
public static XMLReaderDOM getInstance() {
if(instance == null){
instance= new XMLReaderDOM();
}
return instance;
}
public Order retrieveOrder(String requiredIndex){
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
try {
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(savePath);
Element rootElement = doc.getDocumentElement();
NodeList orderList = rootElement.getElementsByTagName("Order");
System.out.println(orderList.getLength());
Node orderElement ;
NodeList children;
int counter;
double price = 0;
String index =null;
for(int i=0;i<orderList.getLength();i++){
orderElement = orderList.item(i);
children = orderElement.getChildNodes();
counter =0;
for(int j=0;j<children.getLength();j++ ){
if(children.item(j).getNodeType()==Node.ELEMENT_NODE){
if(counter==0){
index = children.item(j).getTextContent();
counter++;
}
else
price = Double.parseDouble(children.item(j).getTextContent());
}
}
if(requiredIndex.trim().equals(index)){
return new Order(requiredIndex,price);
}
}
System.out.println("DONE");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Create an XML file orders.xml somewhere and change the "savePath", and "retrievePath" attributes inside the above two classes according to that.


Now create a folder META-INF at the src folder level and create services.xml inside META-INF.
<?xml version="1.0" encoding="UTF-8"?>
<service name="OrderProcessingService">
<description>
Order Processing Service
</description>
<messageReceivers>
<messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-only"
class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver" />
<messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out"
class="org.apache.axis2.rpc.receivers.RPCMessageReceiver" />
</messageReceivers>
<parameter name="ServiceClass">orderprocessing.service.OrderProcessingService
</parameter>
</service>
view raw services.xml hosted with ❤ by GitHub

Here, If you do not specify the message receiver, then the default message receiver which is RawXMLINOutMessageReceiver will perform the operation[1]

And since the service implementation class is in Java, all the public methods in that service will be exposed. No need to specifically include them in services.xml[1]


This is the folder structure of my service.


Now export the project as a jar. In eclipse this can be done by, right click on the project->export
Save it to somewhere and change it's extension to .aar (eg: if your jar is OrderProcessingService.jar rename it as OrderProcessingService.aar ) and save it to axis2-1.6.2/repository/services
(I am using axis2-1.6.2)

Start the axis2server. (In linux run axis2server.sh inside axis2-1.6.2/bin)



Now if you go to http://localhost:8080/axis2/services/ it should be shown as below.



And you can access the wsdl at, http://localhost:8080/axis2/services/OrderProcessingService?wsdl


2. The client

Create another Java project.

Now in order to use the service we need to create the stub.

Go to axis2-1.6.2/bin in the terminal and run,
sh wsdl2java.sh -uri http://localhost:8080/axis2/services/OrderProcessingService?wsdl -o /source/folder/of/client/project
view raw command.sh hosted with ❤ by GitHub
Now create another package orderprocessing.client inside your client project and create OrderProcessingClient.java

package orderprocessing.client;
import java.rmi.RemoteException;
import orderprocessing.service.OrderProcessingServiceStub;
import org.apache.axis2.AxisFault;
public class OrderProcessingClient {
private OrderProcessingServiceStub stub;
public OrderProcessingClient() throws AxisFault {
stub = new OrderProcessingServiceStub(
"http://localhost:8080/axis2/services/OrderProcessingService");
}
public String sayHello() throws Exception {
try {
OrderProcessingServiceStub.SayHello req = new OrderProcessingServiceStub.SayHello();
OrderProcessingServiceStub.SayHelloResponse res = stub
.sayHello(req);
return res.get_return();
} catch (RemoteException e) {
String msg = "Cannot say hello"
+ " . Backend service may be unavailable";
throw new Exception(msg, e);
}
}
public String addOrder(String index, double price) throws Exception {
try {
OrderProcessingServiceStub.AddOrder req = new OrderProcessingServiceStub.AddOrder();
req.setIndex(index);
req.setPrice(price);
OrderProcessingServiceStub.AddOrderResponse res = stub
.addOrder(req);
return res.get_return();
} catch (RemoteException e) {
String msg = "Cannot add order"
+ " . Backend service may be unavailable";
throw new Exception(msg, e);
}
}
public String getPrice(String index) throws Exception {
try {
OrderProcessingServiceStub.GetPrice req = new OrderProcessingServiceStub.GetPrice();
req.setIndex(index);
OrderProcessingServiceStub.GetPriceResponse res = stub
.getPrice(req);
return res.get_return();
} catch (RemoteException e) {
String msg = "Cannot get price"
+ " . Backend service may be unavailable";
throw new Exception(msg, e);
}
}
public static void main(String[] args) {
OrderProcessingClient client;
try {
//To test if our client works
client = new OrderProcessingClient();
String res = client.addOrder("013", 5000000);
System.out.println(res);
res = client.getPrice("013");
System.out.println(res);
} catch (AxisFault e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is my folder structure of the client

Run the client and see if it works.

Making SBT(Simple Build Tool) use JDK 7 having both JDK 7 and 8 installed

I was following a scala tutorial and I was using SBT as the build tool. This SBT version required JDK 7 but I had environmental variables set for JDK8 even though I had both installed on my machine.

To make SBT use JDK7 without changing JAVA_HOME environmental variable, this is what I did.

First created a new environmental variable JAVA_HOME7(any name which is not already being used) with the path to JDK7 as the value.

Then replaced JAVA_HOME in the sbt.bat file(which is inside the sbt folder inside program files folder) with JAVA_HOME7.

MATLAB - Applying a function for each element in an array using arrayfun

I'm not a big matlab fan. For a project I needed to apply a function for each element in an array. For that arrayfun can be used.

Here is a simple example.

Say you have 3 arrays as follows.

A = [1,2,3,4]
B = [5,6,7,8]
C = [9,10,11,12]

And you need to calculate the value of a function myf, for A[i], B[i] and C[i] (i=1,2,3,4) which returns A[i] x B[i] + C[i]

You can do it as follows.

First define your function considering a single element.

function output=myf(a,b,c)
  output=a*b + c;
end

Then,

A = [1,2,3,4]
B = [5,6,7,8]
C = [9,10,11,12]

D = arrayfun(@myf,A,B,C)


Remember to have "@" before myf. It denotes a handle in matlab. If you forget it, matlab will try to evaluate the function instead of considering its handle, which may result in "Not enough input arguments" error.