Sunday, March 16, 2014

How to enable wire log in WSO2 ESB Server?

When working with WSO2 ESB server implementing connectors to connect to several APIs, one of the main problem I faced was the difficulty in monitoring the server while a request is sent to it from a connector. It was realized that things would be much easier if we can see how and what are the parameter going towards the ESB and what are coming from the ESB server while we make each request. 

Here comes the usage of enabling wire log in WSO2 ESB server. It's pretty simple but I hope the outcome will be so helpful to identify the behavior of the server.

Follow the simple steps. But before that make sure that you have the latest and properly running ESB in your local machine. If you want to know basic steps of running the WSO2 ESB, please follow the blog post here. 

If your ESB server is already running, make sure to follow the steps below and restart the server to apply the changes and monitor the enables wire log.

Enable the wire log as instructed below

Go to the extracted folder of the running instance of your WSO2 ESB server and move to the below shown location.

~\wso2esb-4.8.0\wso2esb-4.8.0\repository\conf

Now, open the log4j.properties file in some text editor like Notepad ++

find for the word "wire" and locate to the below shown lines of the file.



















Now, uncomment the highlighted two lines that are shown in the above image. Save and close the file. You are done.

As I have already mentioned, if you already have the server instance running, do restart it to apply the changes. 

How to restart your ESB Server?

Follow the coupe of screenshots below






















Hope it was useful to you. If so, please leave a comment.

Saturday, February 8, 2014

How to test Google Contacts functions through Google Contacts API using Postman?

In my previous post, I have explained you how you can install Postman- Rest- Client extension in your Google Chrome Web browser and why we need such tool. In the same post, I mentioned that I will be explaining it more in another post on how to use postman to test a real world API and make sure its functionalists are working as expected. So, here we go guys.

This post is based on testing Google Contacts API functions (not all but few of them) in Postman-Rest-Client tool.

Prerequisites

  • As u already know, we need to have Google Chrome running in your machine with the Postman extension installed in it.
  • You must have a Google Contacts account. Don't worry, if you do have a gmail account, you will be having a Google Contacts account as well. All you need to do is to login to it at least once using the following url.
  • Of course, you need to have Contacts in your account to start testing any function given in the api.
  • You need to refer the Google Contacts API documentation well before starting to test them. The below link will direct you to the latest version of it.
  • The most important thing is you need to obtain an authorization access token from Google Developers' OAuth 2.0 Playground. Follow the below link to obtain it and note i will explain you how to get the access token step by step.

Great. Now, let's go from point zero :) 

I assume everyone has a gmail account so that a Google Contacts account too. So, let me explain you how to obtain an access token from Google Developers' OAuth 2.0 playground.

Obtaining an Autherization access token from Google Developers' OAuth 2.0 playground for Google Contacts


1.Go to the link below


2.



3.



4.




5.




6.





Note that the obtained access token expires within the time that is mentioned above so that you have to use that for testing before it expires. But once it's expired, you can refresh and obtain  a new access token to continue testing.

So, I hope it's clear up to this level. Next is simply to get a function, identify its parameters etc and test for it's response through postman-Rest client tool.

Before that, we have to confirm the function that we are going to test, don't we? Refer the below link and focus on the function that is highlighted in the below screenshot that is taken from the Google Contacts API documentation page.





















Check the below shown screenshot to identify the function correctly.
















How to test the Retrieve All contacts function in postman?


Open Postman-Rest-API plugin in your Google Chrome Web Browser and Click Reset button to clear any existing tests that you have been working with. Then set the below values in front of the below shown fields accordingly.

Set the url in the below format:-
https://www.google.com/m8/feeds/contacts/<your email address>/full

Add a Header call Authorization and add the value as shown below (note that your access token shouldn't be expired at the time you are using it to test):-

Bearer <the access token you obtained above>

Select the type of the http call as :-

GET

and finally click Send button to obtain the response.

for an example, refer the below screenshot




















If you didn't enter an email in the request url, then the default email will be used which means the account that you have currently logged in.

I hope the post was clear enough for you to start with Postman to test API functions. Hope it was useful to you :) See you in another interesting post ...

Using Postman to test API functions easily

Hi all, after a long break for blogging, I wanted to post something really interesting that I found while working with my new client project which basically needs to create connectors for an ESB to connect to a large set of popular APIs.

While working in the project, we faced so many issues where we wanted to make sure that the functionalists of APIs work as expected. Note the words "as expected". So, how are we going to make sure what the functions going to return and in which format will they be? Of course a well documented API should mention them but what if they didn't? And speaking with my own experience that some of the API documentations even contain functions that are deprecated or not in use but not mentioned them clearly in the API documentation. Here comes the usage of 'postman'. I assume you guys heard the word before and have experience in using it to test APIs but don't worry if u heard the word for the very first time since this post is for you guys.

So, What is Postman?


Please follow this Link to find more information about this plugin.


Postman Rest Client is an extension in Google Chrome web browser which can be found in Google Web Store. You can simply install it in your browser by following the above link and following the below screenshots.





















Notice that the extension will be downloaded and installed automatically in your web browser as shown below.




















Once it's installed, then open a new tab in chrome and you will see the postman icon as shown below.



















So, there we go. We can start using postman as we wish.

Short Description of what Postman does

Postman helps you be more efficient while working with APIs. Postman is a scratch-your-own-itch project. The need for it arose while one of the developers was creating an API for his project. After looking around for a number of tools, nothing felt just right. The primary features added initially were a history of sent requests and collections. A number of other features have been added since then.

If you found an API and if you want to test a function having the necessary headers, parameters and method type basically, you can simply test them in postman to make sure that it works as expected.

My next post will be on how to use postman for a selected API. In that, I wish I can explain more about it. 

Hope this post was useful to you guys :)

Find more information from the below Link

Wednesday, January 15, 2014

How to setup a Maven repository?

Setting up a Maven repository was a major requirement in one of my projects. It is a simple task but since it was first time I tried it out, I faced few issues in that, So that I have decided to add a small post to my blog this time. 

First of all, you have to make sure that the latest JDK is installed in your machine and the paths for bin folder is set accordingly. 

Then you have to download and install maven in your machine. Follow the below link and get the zip file downloaded.


select the below highlighted link to get the zip file downloaded



















extract the zip file to the below location 

C:\Program Files\Apache Software Foundation 

Note that I initially didn't have such folder in my machine, so that I created a folder named Apache Software Foundation in the above location. 

Though I mentioned above as 'download maven and install', it's not going to be an installation following a wizard but it's the matter of setting some environment variables for the bin folder.

Set the M2_HOME environment variable


Type env under startup search box ( in windows) and select Edit the system environment variables option from the search results box. under User variables for <username> panel, click New. Then add the following

Variable Name: M2_HOME
Variable Value: C:\Program Files\Apache Software Foundation\apache-maven-3.1.1

Then close all three opened windows by clicking OK buttons in each of them.

Append the maven bin folder path to the path variable


Type env under startup search box ( in windows) and select Edit the system environment variables option from the search results box. Next click Environment Variables under Advanced tab and then focus on path under System variables. Select it and then click Edit. Then place the cursor under variable value text box and go towards its end then add a semicolon and paste the path to the maven bin folder (e.g :- C:\Program Files\Apache Software Foundation\apache-maven-3.1.1\bin). Then close all three opened windows by clicking OK buttons in each of them.

now you are almost done with the installation. To make sure that you have set the paths correctly, type the below command in a command prompt (in windows)

mvn -v





















Note: the correct version of maven that you installed should be shown above. 

now depending on the maven project and the required dependencies the command that you use to create the m2 repository differs. 

I use a connector project that requires java libraries as dependencies from maven repository. so, that it has a connector project folder, I have to go to the location where there is a pom file and type the below command to build the project, if in case the m2 repository is not yet created, this command will create it.

first naaviagte to the drive where your project is by typing the below command (assume that the project is in drive E)

E:

then navigate to the project folder by typing the below (note that the om file should bemlocated in the below shown location as well)

cd E:\Connectors\org.cmp.carbon.connector

now type the below command

mvn clean install

now go to the below shown location and check whether the .m2 folder is created for you.




















Additional tip:

If you want to get this maven project to eclipse as an eclipse project then type the below command inside the project folder (where the pom file is located)

mvneclipse:eclipse -Dwtpversion=2.0

hope it was useful to you. If so, please leave a comment 

Sunday, December 22, 2013

Using WSO2 Enterprise Service Bus

In order to use the WSO2 ESB, you need to download the following.

Latest version of WSO2 ESB Binary
I use the currently available latest version which is 4.8.0 that is available in the WSO2 website. 
Click here to navigate to the downloads page and click on Binary button to start the download as shown below.























Latest version of Java Development Kit
 I use the currently available latest jdk which is jdk7.
Click here to navigate to the downloads page of Oracle to start the download. The below image could help you.























once you are done with the jdk download, you can install it and then do not forget to set the path for the bin folder and set the JAVA_HOME variable in your machine.

Setting the java path to the bin folder


Once you install jdk in your machine, do navigate to the jdk bin folder of the correct version as shown below and copy the path to it.
































then type env under startup search box ( in windows) and select Edit the system environment variables option from the search results box. Next click Environment Variables under Advanced tab and then focus on path under System variables. Select it and then click Edit. Then place the cursor under variable value text box and go towards its end then add a semicolon and paste the path that you copied to clipboard (e.g :- C:\Program Files\Java\jdk1.7.0_45\bin). Then close all three opened windows by clicking OK buttons in each of them.

Note, if you don't have administrative privileges then you can temporarily set the path as below usinga command prompt (remeber you should use the correct path of your jdk bin folder)

set path=%path%;C:\Program Files\Java\jdk1.7.0_45\bin

Setting the JAVA_HOME variable


type env under startup search box ( in windows) and select Edit the system environment variables option from the search results box. under User variables for <username> panel, click New. Then add the following

Variable Name: JAVA_HOME
Variable Value: C:\Program Files\Java\jdk1.7.0_45

Then close all three opened windows by clicking OK buttons in each of them.

Note, if you don't have administrative privileges then you can temporarily set the path as below usinga command prompt (remeber you should use the correct path of your jdk bin folder)

set JAVA_HOME=C:\Program Files\Java\jdk1.7.0_45

Checking whether jdk path to bin and the JAVA_HOME variables are correctly set in your machine


open a command prompt and type,
java -version to check the java version installed is correctly identified

type,

set JAVA_HOME and observe whether the path to java home is correctly identified






















Now you are ready to run the WSO2 ESB.

Running the WSO2 ESB Server


First of all, extract the wso2esb-4.8.0.zip file that you have just downloaded. then navigate to the bin folder as shown below. Meanwhile open a command prompt getting ready to run the esb sever in your machine.






























use the command prompt to navigate to the bin folder which is shown above and then type,

cd C:\Users\Sherihan\Downloads\wso2esb-4.8.0\wso2esb-4.8.0\bin\wso2server.bat

and hit Enter. Or simply drag and drop the wso2server.bat in to the command prompt so that it will paste the complete file to the bat file and then hit Enter.

carefully observe the command line where it stops at a certain point providing you a URL to start the WSO2 esb server in a browser as shown below. 



Copy the url and paste it in a web browser to start the ESB server from an interface. Once it gives you the login page, enter admin as the username and admin as the password and you are ready to run the Wso2 ESB server to do what ever the required task that you wished to do with the ESB server.






Hope It was useful to you. Please leave a comment for any clarification :)

Thursday, November 7, 2013

Parsing XML files in iOS using XPath

Hi all. After a long break I have decided to add another post to my blogger about another interesting post and a technique that found really challenging to me while working on a certain project recently. OK, this time I'm going to explain how I solved a bit of a tough task of parsing an XML file from an iOS Application easily. Keep one thing in your mind that I will not be using 100% of my own code in this post but I will be instructing you to download few header and implementation files to your project in order to perform this task. Also note that you also require a well formatted valid XML file to test your app and ensure that the parsing of XML task is done as you expected.

By the way, let's quickly go through some very simple questions before starting with the code. Try to understand the following and make sure you know the background of what I'm going to perform here.

XML... what's it about?

XML stands for Extensible Markup Language and it is a markup language (everything is marked as a tag) that defines a set of rules for encoding documents in a format that both human-readable and machine-readable. 

Why XML is so popular?

I don't think that anyone in the field of Information Technology will ever tell that they have never heard the word XML since it is so popular because the design goals of XML highlight simplicity, generality and usability over the Internet. XML files are simply text files and no mater of the platform or technology we are using XML can be understood by all of them.

Well Formed Vs Valid XML Documents

A "Well Formed" XML Document has correct XML syntax. For an example, 
  • XML documents must have a root element
  • XML elements have a closing tag
  • XML tags are case sensitive
  • XML elements must be properly nested
  • XML attribute values must be quoted

A "Valid" XML document is a "Well Formed" XML document which is also confirms to the rules of Document Type Definition (DTD)

How to Validate your XML file?

Let's say that you have an XML file with you and you want to validate it to check for it's syntax. you have a number of tools to do this but let's make it simple. Follow the below links to find out how this task can be easily done through online tools within few seconds. All what you have to do is to simply copy paste the content of your XML file or browse your XML file in the given URL and use the validator to check your file.


OK, now let's move to the most interesting part of our post today. As I told you earlier, we need to have a valid and well formed XML file and it is going to be the below shown file.


File content is as below,

<services>
<service name="Service1" url="/utilities/service1.xml">
<type>GET</type>
<parameter-mapping enumvalue="ID">ID</parameter-mapping>
<parameter-mapping enumvalue="NAMEOFDEVICE">DeviceName</parameter-mapping>
<parameter-mapping enumvalue="SERIALOFDEVICE">Serial</parameter-mapping>
<parameter-mapping enumvalue="IPADDRESS">IP_Address</parameter-mapping>
<parameter-mapping enumvalue="STATUS">status</parameter-mapping>
</service>
<service name="Service2" url="/utilities/service2.xml">
<type>POST</type>
<parameter-mapping enumvalue="DEVICEUNIQUEID">UniqueId</parameter-mapping>
<parameter-mapping enumvalue="PASSWORD">password</parameter-mapping>
<parameter-mapping enumvalue="PAIREDDEVICEID">PairedTabletID</parameter-mapping>
<parameter-mapping enumvalue="STATUS">status</parameter-mapping>
</service>
</services>

I have added this xml file to my project resources in the sample XCode project that I've created by just dragging and dropping it to the project file hierarchy as below.


























OK, Now we have simply added the required XML file to our XCode project. Now it's time to get the content of the XML file and start parsing it using our app.

By the way, Do you know how to read an embedded file from an XCode project in Objective-C?


It's simple. Just a matter of adding few lines of code to get the file content to an NSString. Refer the code below.


NSData *configXmlData;
/*
*Function reads the embedded SampleXMLFile.xml file and saves to an instance variable call configXmlData of type NSData
*@return : no data returned
*/

-(void)setConfigurationFile
{
    //reading the resources from the mainBundle of where it search for a file named SampleXMLFile with file extension of xml
  NSString *configXmlFilePath=[[NSBundle mainBundle] pathForResource:@"SampleXMLFile" ofType:@"xml"];

  @try
  {
   //if the file exist, then get the contents of the file to the configXmlData variable 
   if([[NSFileManager defaultManager]fileExistsAtPath:configXmlFilePath])
   {
    configXmlData=[NSData dataWithContentsOfFile:configXmlFilePath];
   }

  }

  //if incase of an error occurs (file doesn't exist or user has no privilege to access it etc ), then print this error message in NSLog
  @catch (NSException *exception)
  {
   NSLog(@"Exception Occurred in reading setConfigurationFile: %@ ",exception);
  }
}


Now Let's turn on the XPath related work now. Keep in mind that I am going to use some files for this purpose that are available in GitHub in the Hppl Project. Use the below shown link to access the Hppl project.

Access Hppl Project From Here

download the project above and add these files to your project.
  • TFHppl.h
  • TFHppl.m
  • TFHpplElement.h
  • TFHpplElement.m
  • XPathQuery.h
  • XPathQuery.m
remember that you need to add reference to these header files from your Xcode project.

What Am I going to do now...

Ok, let's come to the main target of this post. Here's what I am going to do. I hope you have noticed the structure of the above shown XML file. All what I m going to do is to extract the data of that file as I wanted. Let's say I don't need the entire file content always but a part of it is sufficient for me to perform a task as shown below.

When I pass a string called 'Service1' then the app should display the output as below.

url=/utilities/service1.xml
type=GET
ID=ID
NAMEOFDEVICE=DeviceName
SERIALOFDEVICE=Serial
IPADDRESS=IP_Address
STATUS=status

when I pass s string 'Service2' then the app should display the output as below.

url=/utilities/service2.xml
type=POST
DEVICEUNIQUEID=UniqueId
PASSWORD=password
PAIREDDEVICEID=PairedTabletID
STATUS=status

My plan is to write a simple XML parser function to read tags, attributes, elements and values of the XML file accordingly with the help of the methods included in Hppl Project that we have just added to the project. It's really easy and all what you have to pay a little more attention is for the XPath query that you are suppose to write to extract the matching XML elements.
For simplicity, I'll explain you the methods one by one and then you can download the sample app and monitor how things are handled as a whole.

Note that MetaConfigurationHandler is the name of the class that I have and you need to add two more reference for it as below.

#import "TFHpple.h"
#import "Discovery.h"
 
 
/*
*Function creates an NSDictionary containing all the data required for a specific http connection as key value pairs
*@return : an NSDictionary containing the required key value pairs
*/

-(NSDictionary *)generateConfigurationDictionary:(NSString *)request
{
//calls the above mentioned function to read the embedded xml

//file contents to the instance variable configXmlData
  [self setConfigurationFile];

//holds each value for each key of the dictionary
  NSString *valueForKey=nil;

//holds each key of the dictionary
  NSString *key=nil;

//holds the name of the tag
  NSString *tagName=nil;

//holds the xPath query (what matching string we are searching for)
  NSString *xPathQuery=nil;

//holds all the elements of the Services tag
  NSArray *configurationServiceElements=[NSMutableArray array];

//this will be returned as an output containing the aforementioned
//NSMutableDictionary with keys and values respectively
  NSMutableDictionary *configurationDictionary =[NSMutableDictionary dictionary];

@try
{
//xpath query string to search for the children of service tag

//where the service's name= request (here, request is a string
//as Service1 or Service2 that is passed to this function as
//a parameter
  xPathQuery=[NSString stringWithFormat:@"/services/service[@name='%@']",request];

//passing the xPath query, retrieving all the tags that are

//matching with the above xPath query
//configurationServiceElements array will hold elements like url,
//type,ID,NAMEOFDEVICE,SERIALOFDEVICE,IPADDRESS and STATUS

//when request=Service1

  configurationServiceElements=[self getConfigurationElementArray:xPathQuery];

 //valueForKey is going to hold /utilities/service1.xml

//(when request=Service1)
  valueForKey=[[configurationServiceElements objectAtIndex:0] objectForKey:@"url"];

//add value=/utilities/service1.xml where key=url

//(when request=Service1) which
//means configurationDictionary will hold one entry with a key-value pair
  [configurationDictionary setObject:valueForKey forKey:@"url"];

//clear the xPathQuery
  xPathQuery=nil;

//xpath query string to search for the value under the tag named as type and
//which is a sub element od Services/service where service name is equal to
//request
  xPathQuery=[NSString stringWithFormat:@"/services/service[@name='%@']/type",request];

//pass the query to get the value
  configurationServiceElements=[self getConfigurationElementArray:xPathQuery];

//how to get the value of the tag which is type
  valueForKey=[[[configurationServiceElements objectAtIndex:0] firstChild] content];

//add this key value pair to the dictionary,  configurationDictionary
  [configurationDictionary setObject:valueForKey forKey:@"type"];


/*Now, I'm trying to get all the tags under /services/service that are named as
parameter-mapping, then get(element) each of its attribute values and element values to form the key-value pairs for the dictionary as
ID: ID
NAMEOFDEVICE=DeviceName
SERIALOFDEVICE:Serial etc
*/


//first the xPath query search for parameter-mapping elements
//under services/service
  xPathQuery=[NSString stringWithFormat:@"/services/service[@name='%@']/parameter-mapping", request];

//get all those elements that matches the xpath query above to an array
configurationServiceElements=[self getConfigurationElementArray: xPathQuery];
 

//now for each element in the configurationServiceElements array...
  for (TFHppleElement *element in configurationServiceElements)
  {

         //get the name of the tag and assign to tagName variable
     tagName=element.tagName;
       

     //check if that tagName is equal to parameter-mapping
     if[tagName isEqualToString:@"parameter-mapping"])

     //if true, assign it to key          
      key=element.tagName;

     //get the attribute of parameter-mapping which is enumvalue and
     //make it a key
     key=[element objectForKey:@"enumvalue"];


          //get the value of the attribute named key (which means enumvalue)and
     //assign it to valueForKey
     valueForKey=[[element firstChild]content];
     

     //now add those key-value pair to the configurationDictionary as
     //another entry 
     [configurationDictionary setObject:valueForKey forKey:key];          
  }
}

  //if incase an exception occurs then handle it by printing the exception
  //in NSLog
  @catch (NSException *exception)
  {
    NSLog(@"Exception Occurred in generateConfigurationDictionary:%@ ",exception);  
  }

 //finally, return the configurationDictionary NDmutableDictionary
  @finally
  {
    return configurationDictionary;
  }

}
 

/*
*Function executes an xpath query and returns the matching nodes as an NSArray to the callee
*@xPathQuery : xpath query as a string should be passed
*@return : an NSArray containing the matching elements will be returned
*/

-(NSArray *)getConfigurationElementArray:(NSString *)xPathQuery
{
  NSArray *servicesNodes;
  TFHpple *servicesParser = [TFHpple hppleWithXMLData:configXmlData];
  NSString *servicesXpathQueryString = xPathQuery;               
  servicesNodes = [servicesParser searchWithXPathQuery:servicesXpathQueryString];
  return servicesNodes;
}


Now, the most required or I would rather say most difficult part of our XML parsing is done. All what you have to do is to make relevant function calls passing proper parameters to get the output as you want.


for an example, I can call the parser functions as shown below. Assume that I am going to call these functions from another class

MetaConfigurationHandler *meta=[[MetaConfigurationHandler alloc]init];

NSDictionary  *configDic=[NSDictionary  dictionary];

*configDic=[meta generateConfigurationDictionary:@"Service1"];


Now you can simply print the configDic contents in NSLog or as you preferred. 

Hope this post was interesting to you guys  :)

Further reading :

http://www.w3schools.com/xml/default.asp
http://www.raywenderlich.com/14172/how-to-parse-html-on-ios