Axis2 Web Service and Java Client…

I googled hours for java client for axis 2 web service with the help of  WSO2 Application Server .Finally figured out by looking at a written code by some one else. This post just covers very basic things. In this article I m gonna show you folks how to write simple web service using axis2. , and a simple java client to consume the web service.  Thing we are gonna do in this tutorial mentioned below as steps.

1. Write a axis 2 web service called “CalculaterService” which contained one operation “add”,which takes two numbers and returns the addition of those two.

2.Write a simple java client to consume the web service,that means,  we provide two numbers to the web service and get the addition of it.

So enough talking, Let’s get started….

you will need following servers and Tools to do this in that quick… Other wise it will take some time :).

  1.  WSO2 Developer Studio –  One of the best IDEs I’ve ever seen , Creating projects like Axis2 is just one click away . You can download it here.
  2. WSO2 Application Server – We use this to host our Axis2 web service. We don’t use this just for hosting the web service. As you  go through the tutorial, you will see a bit of it’s capabilities. 🙂 You can download it from here.

If you have downloaded these two.. now its time get our hands dirty.

Fisrt, Let’s create the web service. In this post my intention is not to describe you fundamentals of web services, so I assume that you have at least a tiny knowledge about web services.

run the eclipse …

In the menu bar go to Developer Studio -> Open Dashboard.

You will see a screen like below.

t

Click on Axis2 Service Project to create the web service.

In next window you see , select Create New Axis2 Service. and click Next.

Then enter following details on relevant fields.

Project Name : Calculator

Package: com.example.calculator

Class : CalculatorService

Then click next, and then click  Finish.

In this service class, let’s implement addition as an operation . We can add operations to the service as public methods. So they are consumable as service. In the mean time , we can define private methods to be used in side the service. Those won’t be exposed as operations in the web service.

package com.example.cal;
public class CalculatorService{</pre>
 public int Addition(int firstNum,int secondNum) {
 return firstNum+secondNum;
 }

}

Then Right Click on the Calculator project in the project explorer.

and click on  Export Project as Deployable Archive .There you will see a window like below. Give the destination for the resulting file and click finish.

Selection_124

So in the destination you will find a file with name Calculator_1.0.0.aar

hmm.. we are done with creating simple web service . now we are going to deploy it on wso2 application server and test with the Try it feature of wso2 applicaiton server.:)

So now let’s start application server. If you are a linux user goto downloaded and extracted folder and and run following command


sh bin/wso2server.sh

if you are a windows user run wso2server.bat file which can be found in <AS_HOME>/bin/

(AS_HOME is extracted folder of wso2 as)

go to the link

https://localhost:9443/carbon/

then login with following credentials

user name: admin

password: admin

Then you will see a screen like below.

Selection_126

You will see a menu on left side..

Under the sub section Add , click on AAR Service.

Selection_125

Then click on Choose File and select that .aar file exported form wso2 developer studio.

And then click Upload.

Then click on List under the Service tab.

Selection_127

There you will see list of web services deployed in the application server. You will see “Calculator Service” among them if nothing has went wrong ;).

Selection_129

Click on it and then you will see a screen. Let’s test the web service using Try it.

Selection_130

in the left side window set payload as


<body>
 <p:Addition xmlns:p="http://cal.example.com">
 <!--0 to 1 occurrence-->
 <xs:firstNum xmlns:xs="http://cal.example.com">3</xs:firstNum>
 <!--0 to 1 occurrence-->
 <xs:secondNum xmlns:xs="http://cal.example.com">2</xs:secondNum>
 </p:Addition>
</body>

and click on  Send. Then you will see a result like below in the right side window.


<ns:AdditionResponse xmlns:ns="http://cal.example.com">
 <ns:return>5</ns:return>
</ns:AdditionResponse>

.

Our web service is working correctly .. Now let’s begin the second part .. writing a simple java client to consume the web service.

Now let’s start writing the client. Create New Java Project 

Add a class “MyClient”  to the project with package name com.my.client .

Now we need to get those generated classes in this project.

Again go to Developer Studio dash board…

click on Generate Axis2 Web Service Client

Selection_135

Then we need to provide wsdl URI to generate clients. We can find it form the wso2 application server. In the service page click on “WSDL1.1” and copy url in the browser . And paste it in the “WSDL URI” field as below.

WDL URI is like “http://localhost:9763/services/CalculatorService?wsdl&#8221;

Selection_136

Then click next and set the source folder of the MyClient project. Then add main method to the MyClient class as below.


public static void main(String[] args) {
 try {
 //create service stub with the endpoint of the sercer
 CalculatorServiceStub stub=new CalculatorServiceStub("http://localhost:9763/services/CalculatorService/");
 //calling for addition operation in the service
 Addition add=new Addition();
 //passing input parameters to operation
 //setting them with the
 add.setFirstNum(3);
 add.setSecondNum(4);
 //consume the service using stub and get the response
 AdditionResponse response=stub.addition(add);

 System.out.println("Reponse from Axis2 Service: "+response.get_return());
 } catch (AxisFault e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 } catch (RemoteException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }

 }

Before running the sample .. add following jars to the class path.

  • axis-wsdl4j-1.5.1.jar
  •  commons-codec-1.4.jar
  • commons-httpclient-3.1.jar
  • commons-logging-1.0.4.jar
  • httpcore-4.0.1.jar
  •  neethi-2.0.4.jar
  • org.wso2.securevault-1.0.0.jar
  • XmlSchema-1.4.jar

Then run it .. 🙂 you will see the repsonse …

Advertisements

Obtaining certificate from thumbprint of a JWT

I think you are familiar with JWT (Jason Web Token) . There is a use case that JWT is used to pass user information from WSO2 API Manager to ESB. You can get more knowledge on this from here.

First go through the above link and create the working setup for the above mentioned use case. Then we can have a look at how to extend it to get the certificate used to sign the JWT.

Certificate that is used to sign the JWT can not be obtained from message context directly , you will have to more than reading a property from the message context. As an abstract ,steps are as below.
1. Get the JWT
2.Decode it
3.get Thumbprint
4.get alias of thumprint
5.get certificate from the keystore of the tenant while providing alias acquired in thumbprint.

So let’s get started….

Encoded JWT is coming as a HTTP header ,so first you have to set the a encoded JWT to the message context as a property. It can be done using following code segment at the appropriate place in the synapse-config.


<property name="authheader" expression="get-property('transport','X-JWT-Assertion')"></property>

So now, This property can be retrieved from the message context programmatically as mentioned below.


String auth = (String) context.getProperty("authheader");
 

now in the String auth, there is encoded JWT. It can be decoded using as mentioned below.

byte[] decoded = Base64.decode(auth);

String dec = new String(decoded, "UTF-8").trim();//get jwt token
 

now in the variable dec , you can get the decoded jwt. which is look like

{"typ":"JWT","alg":"SHA256withRSA","x5t":"NmJmOGUxMzZlYjM2ZDRhNTZlYTA1YzdhZTRiOWE0NWI2M2JmOTc1ZA=="}{"iss":"wso2.org/products/am","exp":1386239361238,"http://wso2.org/claims/subscriber":"admin","http://wso2.org/claims/applicationid":"1","http://wso2.org/claims/applicationname":"DefaultApplication","http://wso2.org/claims/applicationtier":"Unlimited","http://wso2.org/claims/apicontext":"/test1","http://wso2.org/claims/version":"1.0.0","http://wso2.org/claims/tier":"Unlimited","http://wso2.org/claims/keytype":"PRODUCTION","http://wso2.org/claims/usertype":"APPLICATION","http://wso2.org/claims/enduser":"admin","http://wso2.org/claims/enduserTenantId":"-1234", "http://wso2.org/claims/role":"everyone,admin"}

In this JWT, Thumprint is available as element “x5t” ,in this case it is

"x5t":"NmJmOGUxMzZlYjM2ZDRhNTZlYTA1YzdhZTRiOWE0NWI2M2JmOTc1ZA=="

Thumbprint can be retrieved by following method ,which requires decoded string of the jwt.

private String getThumbPrint(String jwt) {
		String[] elements = jwt.split(",");
		for (String string : elements) {
			if (string.indexOf("x5t") == 1) {
				String tmpResult = string.split(":")[1].trim();
				String result = StringUtils.substringsBetween(tmpResult, "\"", "\"")[0];
				return result;

			}
		}
		return null;
	}

Now let’s keep this aside for a while….

We need the keystore manager of the tenant. Following line of code can be used to get the key store manager of the tenant.

		KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId);

in wso2 products there is convetion used to name keystores for tenant, so key store for tenant is a wso2 product can be used as below.


String ksName = tenantDomain.trim().replace(".", "-");
String jksName = ksName + ".jks";
keyStore = tenantKSM.getKeyStore(jksName);

Right, let’s get back to thumbprint….

This thumbprint we get from the JWT ,it is also encoded before getting the alias ,it must be decoded. in the following code segment it is shown that how to decode it and retrieving the alias, which is required when obtaining the certificate.


String alias = getAliasForX509CertThumb(decodedThumb, keyStore);//get the alias
 

getAliasForX509CertThumb method gives the alias of the thumbprint, this method requires decoded thumb print,which is a byte array and the keystore we obtained in earlier step.


private String getAliasForX509CertThumb(byte[] thumb, KeyStore keyStore) {
		Certificate cert = null;
		MessageDigest sha = null;

		try {
			sha = MessageDigest.getInstance("SHA-1");
		} catch (NoSuchAlgorithmException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}

		try {
			for (Enumeration e = keyStore.aliases(); e.hasMoreElements();) {
				String alias = (String) e.nextElement();
				Certificate[] certs = keyStore.getCertificateChain(alias);
				if (certs == null || certs.length == 0) {
					// no cert chain, so lets check if getCertificate gives us a
					// result.
					cert = keyStore.getCertificate(alias);
					if (cert == null) {
						return null;
					}
				} else {
					cert = certs[0];
				}
				if (!(cert instanceof X509Certificate)) {
					continue;
				}
				sha.reset();
				try {
					sha.update(cert.getEncoded());
				} catch (CertificateEncodingException e1) {
				}
				byte[] data = sha.digest();
				if (new String(thumb).equals(hexify(data))) {
					return alias;
				}
			}
		} catch (KeyStoreException e) {
		}
		return null;
	}

	private String hexify(byte bytes[]) {

		char[] hexDigits =
		                   { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
		                    'e', 'f' };

		StringBuffer buf = new StringBuffer(bytes.length * 2);

		for (int i = 0; i < bytes.length; ++i) {
			buf.append(hexDigits[(bytes[i] & 0xf0) >> 4]);
			buf.append(hexDigits[bytes[i] & 0x0f]);
		}

		return buf.toString();
	}

 

Now we can get the certificate by passing the alias to the keystore.


Certificate certificate = keyStore.getCertificate(alias);//get the certificate for the particular thumb print
 

Now we are done … you can do whatever you want to do with the certificate now 🙂 ..
You can find the source code for the custom mediator written for wso2esb at [1]. If you are running the sample ,you have to do it as below in the synapse config.

    <property name="authheader" expression="get-property('transport','X-JWT-Assertion')"/>
    <class name="org.wso2.carbon.esb.jwthandler.JWTHandler"/>

[1] https://svn.wso2.org/repos/wso2/people/asankad/JWTHandler/

Download videos from just one command in Linux terminal

Hey.. guyz.. I was looking for a tool to download you tube videos in linux. On the way, I met a nice tool. it is “youtube-dl”. So let’s get started.

First you have to install it…

sudo apt-get install youtube-dl

you can do plenty of things with this command, but in this post.. I am going to explain how it can be used to achieve the basic purpose. I mean downloading a video. Convert videos, etc… will be discussed in the future.

After getting this installed you can start downloading your favorite videos not only from youtube… it supports metacafe,dailymotion and so many other video sites.Command syntax is as below.

youtube-dl -f {formatcode} {vedioURL}

-f is the option that states, you are going to download a video with the specified quality. for example 380p,720p,720pHD,1080pHD which is represented by the formatcode in the command.Following table contains the values and video quality.

Format Code File Format Video Quality
13 3GP N/A
17 3GP 144p
18 MP4 270p/360p
22 MP4 720p
34 FLV 360p
35 FLV 480p
36 3GP 240p
37 MP4 1080p
38 MP4 3072p

for example.. if you want to download a 1080p quality vedio with url http://www.youtube.com/watch?v=VAOpIxh_lXI to a particular location.
First go to the particular folder and type below command.

youtube-dl -f 37 http://www.youtube.com/watch?v=VAOpIxh_lXI

That’s it …. then the downloading will start..

I have tested this for youtube,dailymotion … it saved a hell of a time for me …

Perform bulk user Import for a tenant in wso2 products

Bulk user import is an Admin Service so it can only be performed by the tenant admin. In this post I am going to guide you how to perform a bulk user import as a tenant admin.

First you need to create a csv file or xlsx file which contains the user names. Here I am going to use a csv file. First lets create a csv file which contains user name that we need to add to the tenant.

UserNames
uhsani
ruwan
harsha
harin
ranil

NOTE:Please make sure to keep first line empty,start entering names as above from the second line.

then save the file as XXX.csv . Here I am using the file name as names.csv.

then create soap ui project with the wsdl

https://localhost:9443/services/UserAdmin?wsdl

Before this you have to set

 <HideAdminServiceWSDLs>false</HideAdminServiceWSDLs>

in the carbon.xml which can be found in PRODUCT_HOME/repository/conf

After creating the project you can see as following.

Selection_067

then select the operation bulk user import and create a request from it. create the payload as in the below image.

Selection_068

here the handler is the csv file. we have to send it as an attachment with the soap request. Now let’s attach the csv file to the soap request.

dia1

click on tab show in red circle 1 and click on icon in red circle 2 to open the csv file. Then it will prompt asking for caching the file ,click “No”.

Selection_069

Then click on the cell of the relevant row of your file which belongs column “part”, and you will see some values. select the value you have given for cid:XXXXXX in handler tag.

Since this is a admin service you have to pass tenant admin credentials.

Selection_070

click on the Aut tab and provide tenant admin details according to this figure. make sure Authorization type is set to Preemtive .

Now you are good to go… send the request .Now users in the csv file are added to the user store of the tenant with given default password in the payload.

Cloud for Examination System in Sri Lanka

If the word “cloud” mean more than just a cloud in the sky for you , then continue reading. But if not I suggest you to go through this link Cloud Computing

“Examinations” must be the most horrible words in the society these days. We all know how they have spoiled it. In the education system in Sri Lanka GCE O/L and GCE A/L are the most two important examinations for students in the schools. The whole future of a person is decided by these exams (Not true always 🙂 ). We all know the importance of an examination and it’s results. One wrong calculation or printing mistake can make a life up side down.

As far as the examination results are concerned, there are two vital factors ,

Theya are

  • Accuracy
  • Quick Publishing

I am not going to talk more about the fact “Accuracy”, because it is so obvious .GCE Advanced Level and GCE Ordinary Level results were one of the most controversial topics recently.Inaccuracy of the prevailing system was obviously revealed. GCE A/L is the most important benchmark of the life of a student. Inaccuracy of such a thing may ruin the life of the student. Erroneous marking of the paper is not the only reason here. Improper manipulating of the data can cause the same problem. Then the second fact. Most of the students seating for exam are not passed or get higher ranks in the  first time. So majority of them seek a second try. To get this decision quick publishing of the results in very important. It takes months to finalize the results after the paper marking is completed. So where is the mistake.

Here is the procedure….

  1. Mark the paper
  2. records the marks in a sheet and send it to the Ministry of Office or whateva
  3. then they manually enter the marks in to a database
  4. then process

for 3rd and 4th steps they take months, Folks!!! what  if we can do 3rd step inside the marking center and 4th step later. Results can be published maximum within 2 days after the marking is finished. Awesome !!! isn’t it.

(usually paper marking is taken place for 3 weeks, so within 3 weeks and 2 days after the exam results are published)

The solution is the CLOUD…… cloud for examinations.  You guys cam argue with me “Teachers!!! Their IT literacy is not that high!!”… yeah.. may be.. But there are teachers dedicated to IT at schools may be we can use them.

Note: This is part of my dream , that I shared with you in the first article of this blog….

My Dream

It’s about FB, but not just an article

Facebook”, it may be the most popular word in Sri Lanka for past decade (other competitive words are “Rajapaksha”,”Changumee”, etc 🙂 :)). and also the most popular social networking site yet implemented. This is some what like a knife, we can use a knife to slice a bread as well as slice a throat. But the purpose of using it rest in our hands and the consequences of the action also has to be beared by ourselves.

Facebook ,as i mentioned earlier has numerous similarities against knife 🙂 :). We can use it for the betterment of ourselves and the rest of the community,and also for the opposite of it. If you can recall your memory few months back, I guess you can remember that incident of murdering his wife and two children by a person due a love started in FB. I know, some fellas read this will blame me … “WTF are you talking,It is about him .. not about FB”…

I would say like this

“FB is like a platform (like WSO2 Carbon), It provides you various base services. But the thing you develop on it depends on you. It can be a good social connection or can be a connection that has very very bad effect on some others. But folks, there is something about the platform . Without it’s services you won’t be able to do anything…. (Screwed???? don’t mind . go ahead…).

There are something called FB ethics, that you should follow.

  1. No Fake profiles.
  2. Don’t insult others for their physical appearance,race,religion etc.
  3. Have your own privacy with you, they are not to share.
  4. Don’t upload or share pictures that is not suitable for public display (you know what i mean). 🙂

there are many…. just google it…

You may not know this,  when a company recieved your CV , they just check your FB profile(If possible). Because it is kind a reflection of your personality , attitudes (you know ,any one can fake it) .Don’t share every damn thing about your private life in the public. You will regret. You can find thousands of FB friends , but find a true friend to share your joy and pain. There are many places to do that. But FB is not in that list.

When you update a status,or share anything, just think before you do it. I am saying this because, now there are group of people out there trying to create a conflict again in sri lanka, and the FB is the main media that they are using. So my friends, don’t let them make a fool out of you.

Final words, FB is not your home, it is just a road house. So treat it as it deserves.

Dreaming about IT everywhere country..

Just came from WSO2 Con 2013. Was a fantastic event organized by WSO2 team. Lots of topics were discussed there. session on e- governance ringed my bell. Actually when I was doing my level 3 project at the university I was dreaming about the same thing that they (WSO2 and Rapsere) are doing now. Everything is e-nized (don’t worry it “e-nized” is a word in my vocabulary 🙂 ). I was doing a School Management System (SMS) for the level 3 project, it was a very sophisticated web application that facilitates to manage almost every thing in the school.

  • Teachers
  • Students
  • Examinations

and I planned about lot more like asset management etc.. I called it School Management at finger tips.because every thing was away with few keystrokes or a click. I will list out some features I Included in the SMS.

  • General Module for Authentication for students,teachers,sectional heads, vice principals and principal. and they are provided with different user levels with different privileges. As in the hierarchy, student with the least privileges and principal is the boss 🙂 🙂 as usual.
  • only registering user can be done by vice principal and principal.
  • Each person has his own account with different views based on the authentication level.
  • Teachers can be assigned wit subjects and classes for those subjects.
  • Student are registered and assigned in to classes at every December 31st , classes are updated according to the cut-off markds defined by the class teacher. (by default everyone is passed to next class)
  • Separate Module to take care of Examinations. Only principal can start an examination. After the exam is finished, teachers are notified with a sms (here sms is the sms in our day to day terminology) to enter marks.
  • When all the marks are entered class teacher have the authorization to process the marks and get ranks, averages all the stuffs needed.
  • during this process , examination results is sent to student’s parents mobile, so before student reaches the home results has gone there (I know that is not fair 🙂 :). but had to to that )
  • Discipline Notifier ( night mare for naughty students 🙂 🙂 ). Teachers can add remarks about the behavior of the student in the school. Each remarks reaches parents in a flash ( I know that is bad too…. 🙂 ).

umm…. There is another interesting thing I included, I included this because of my real life experience. After passing out from the school I went to get my character certificate, and sports certificate. Then vice principal gave me a big big form and asked to write things I did in the school and asked to get signatures from relevant teachers as a confirmation. 🙂 🙂 . That’s how thing were….

So I wanted to include feature that store every thing of  a student Discipline,Sports, Ex-curricular activities, Awards etc. So I included this thing. that records these all. So when a student want to get any certificate . Then who ever the person issue the certificate just have to have a look at those records which are easily can be retrieved ( authentication level should be greater than student)

As above there are lots features of SMS. I was not going to talk about it.. Let’s get back on the track… umm…Eventhough Sri Lanka has above 90% literacy , in the case of IT literacy it is not that much. Most of the folks in the higher positions of government institution have not been exposed to IT that much. I’ll tell you a little story.

Few months back , I was asked to design and develop a IT System for Badulla Private Passenger Company ,which is the largest private bus company in Badulla. It was a proposed to me by a young person working there. because he has the idea of the comfortability of  using an IT system instead of bulky files ( It saves trees too :)) Then I was asked to do a presentation for the director board.(there were 12 , out of 12 , 11 of them were businessmen and the other was a lawyer ) 🙂 🙂 . Now the fun part begins… I gave the presentation. They were stared at me during entire presentation and finally asked how much does it cost??? 🙂 kind a funny question, I was expecting it 🙂 🙂 . Then I told them the price with no discount policy (same as WSO2 🙂 :)) . There eye brows went up :).And all them told that they are fine with bulky files and paperwork. I felt that , I would have been very easy for my to convince my granny to wear jeans rather than convincing those folks to use an IT system.

That’s how the things works in Sri Lanka, most of the people working in the Government only know about how to use the MS Office Pakage 🙂 .  and still there are people who thinks that MS Words is a typewriter with a Screen. 🙂 🙂 . because , Once they made a mistake at the beginning of the sentence , and if they saw it in the end of the sentence , then they delete the whole sentence and type it again. 🙂 🙂 . It is just a one example , I can give lots of them ( guess it is better to write another article for it ).

To make my dream true , to see a Sri Lanka with IT Every where.. first we should come up with significant change in education system. and persuade people to use IT and stick with technology. Still there are people that prefer being in the queue at the counter of the bank holding the Pass book rather than using ATM card to withdraw money.

e-governance would be a huge step to make my dream a reality.I know that day is not that far. Not only for governance , for health services ,education,transportation etc.. We can use IT, in my words we can e-nize them.

cheerz!!!!