Long Time, I’m missing my Blog.

Wanted to Come back now. Lets See.

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

Google URL Shortner API

One of the most important Google Tool i use regularly is Google URL Shortner, this is very helpful when you work with Social networking sites especially, When we wanted to share an URL which is too long and can’t fit into the char limit, that time this tool becomes handy. Even though we had few URL Shortner utilities like bit.ly, tinyurl earlier, when Google launched it’s own tool, i started using this more. Even though bit.ly is also giving you the option to analyze your URL traffics and etc, I love to work with Google, since most of the time i’m logged into any of the Google services. So it’ll be easy to use goo.gl
Basically it takes the URL and convert into a small/tiny with very few characters. We can use tools like Unshort me to unshorten the URL which are shortern by bit.ly etc. This can be applied to goo.gl URL’s also. As like all other services, Google provides API for this also. The API details can be found here. As like Google’s other API’s we need to have the Key to use this API as well.
To get your API activated on your profile, Please visit here. In the left hand panel, you can get your Key created for your profile and you can use it on your code. You can use programming languages of your choice and get the JSON data parsed which is returned from Google API Service.
We’ll look at two examples, of how to make a call to URL Shortner API. One with PHP and other one with Java.
Using PHP to Call API Service
			<?php

				$myURL = 'http://www.dzone.com/links/index.html';
				$googleAPIKey = 'URAPIKey';

				$requestData = array('longUrl' => $myURL, 'key' => $googleAPIKey);
				$jsonDetails = json_encode($requestData);

				$curl = curl_init();

				curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
				curl_setopt($curl, CURLOPT_POSTFIELDS, $jsonDetails);
				curl_setopt($curl, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url');
				curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
				curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);

				$responseData = curl_exec($curl);

				$jsonData = json_decode($responseData);

				curl_close($curl);

				echo 'Shortened URL is '.$jsonData->id;

			?>
		
Code in Action,Click Here
Using Java to Call API Service
I have used the basic “HttpsURLConnection”, but still you have plenty of other options to call Google’s API using Java.
			package com.techmaddy;

			import java.io.BufferedInputStream;
			import java.io.PrintWriter;
			import java.net.URL;
			import javax.net.ssl.HttpsURLConnection;

			public class URLShortnerDemo {

				public static void main(String[] args) {
					System.out.println("The URL is "+getShortURL());
				} //End of main

				public static String getShortURL() {
					URL simpleURL = null;
					HttpsURLConnection url = null;
					BufferedInputStream bStream = null;
					StringBuffer resultString = new StringBuffer("");
					String inputString = "{\"longUrl\":\"" + "http://news.google.com.sg/news?cf=all&ned=in&hl=en&edchanged=1" + "\"}";
					try {
						simpleURL = new URL("https://www.googleapis.com/urlshortener/v1/url?key=yourAPIKey");
						url = (HttpsURLConnection)simpleURL.openConnection();
						url.setDoOutput(true);
						url.setRequestProperty("content-type", "application/json");
						PrintWriter pw = new PrintWriter(url.getOutputStream());
						pw.print(inputString);
						pw.close();
					}
					catch (Exception ex) {
					  return "Exception in Connecting to API";
					}

					  try {
						  bStream = new BufferedInputStream(url.getInputStream());
						  int i;
						  while ((i = bStream.read()) >= 0) {
							  resultString.append((char)i);
						  }
					  }
					  catch (Exception ex) {
							return "Exception in Reading Result";
					  }

					return resultString.toString();

				} //End of getShortURL

			} //End of URLShortnerDemo
		
Output for JAVA
Google URL Shortner API Java OP
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

Ant-Custom Tasks and Built-In Tasks.html

In my previous post we have seen how to configure ant and how to use with IDE’s like eclipse. In this post we’ll look into some of the Built-In ant tasks and Custom Tasks. Ant provides lots of built-in tasks. Those task can be categorized as follows
  • Archive Tasks - Has list of all the archiving tools like JAR,WAR,EAR,TAR,ZIP and etc…
  • Audit/Coverage Tasks - Has a single task under this group which is an Code Coverage tool for Design Quality Metrics.
  • Compile Tasks - Includes the task for Code Compilation.
  • Deployment Tasks - Hot deployment task for J2EE Servers.
  • Documentation Tasks - Has JavaDoc task in this category.
  • EJB Tasks - Couple EJB related task specific to App servers.
  • Execution Tasks
  • File Tasks
  • Java2 Extensions Tasks
  • Logging Tasks
  • Mail Tasks
  • Miscellaneous Tasks
  • Pre-process Tasks
  • Property Tasks
  • Remote Tasks - Task like FTP, SCP and etc.
  • SCM Tasks - Includes few popular SCM tasks like ClearCase,CVS and VSS.
  • Testing Tasks - Supports jUnit tasks.
We’ll take few tasks like Mail tasks, Remote tasks and SCM Tasks and try to run a task from each group.
Mail Task
While running the build in an environment where a team is using SCM to commit their changes, this task will be very useful if the build is broke. By using this we can send a mail to the team along with the build errors. Since the MAIL task supports attachment also, it’ll be a very good idea to log all the errors and send it in the mail, so that the team can correct their code base and commit to SCM. The below build script has an example task which shows a simple steps to send a mail using mail task.
		<?xml version="1.0" encoding="UTF-8"?>
		<project name="AntDemo" default="sendMail">
			<target name="sendMail">
				<mail mailhost="smtp.xx.com" subject="Build Broken"  user="kumarasamy@xx.com" password="XXXXXXX">
					  <from name='Build Admin' address="buildadmin@yourcompany.com"/>
					  <to address="usersDL@domain.com"/>
					  <message>The Build has been Completed.</message>
				</mail>
			</target>
		</project>
		
Remote Task - FTP
When we run the build sometimes we use a different machine only for build and finally we’ll copy to the remote machine to deploy it on application servers, for that we can use this ftp task.The below example will show how to use the FTP
		<?xml version="1.0" encoding="UTF-8"?>
		<project name="AntDemo" default="uploadFile">
			<target name="uploadFile">
				<ftp server="ftp.xx.com"
						userid="username"
						password="password">
					<fileset dir="dist">
						<include name="*.war"/>
					</fileset>
				</ftp>
			</target>
		</project>
		
The above FTP task has very simple example, which just uploads your WAR file to your FTP server.
SCM Task - ClearCase
Clearcase is one of the widely used SCM in the industry, sometimes automating the build process is important and we can have these ant tasks provided in ant and perform few SCM tasks in ClearCase. The first step in check-in and checkout process is locking the current stream we use it for building the code base. In the same manner when these check-in and checkout process are completed we’ll have to unlock the stream we have locked it. For this Clearcase provides an command line tool called cleartool, by using this we can achieve these task in command line, Let’s see how we can use it ant by using the ClearCase ant task. Before that we’ll have the following assumptions, We’ll consider the branch name as “BuildFortheFixX.X”.
		<?xml version="1.0" encoding="UTF-8"?>
		<project name="AntDemo" default="lockStream">
			<target name="lockStream">
				<cclock objsel="brtype:BuildFortheFixX.X" />
			</target>
			<target name="unlockStream">
				<ccunlock objsel="brtype:BuildFortheFixX.X" />
			</target>
		</project>
		
The above CC tasks are equal to the following cleartool commands,

			cleartool lock brtype:project_int

			cleartool unlock brtype:project_int
		
Custom Task - ClientGen
Ant provides a way to write our own tasks, the best example will be clientgen task from weblogic which is used to generate the webservice clients from WSDL file. First We’ll we how to use this clientgen task to generate the Service Clients, then we’ll look at how to write an simple custom ant task and call it from the build script. If you are using WL8.1, We have the task defined weblogic.ant.taskdefs.webservices.clientgen.ClientGenTask in webservices.jar. We can use this task to generate the client JAR. The following example will show how to generate the Service Client JAR from a WSDL.
		<?xml version="1.0" encoding="UTF-8"?>
		<project name="AntDemo" default="buildClientJar">
		  <taskdef name="clientgen" classname="weblogic.ant.taskdefs.webservices.clientgen.ClientGenTask" />
			<target name="buildClientJar">
				<clientgen	wsdl="http://myapplication/services/MyAppWebService?wsdl"
										clientjar="dist/MyApprClient.jar"
										packageName="com.techmaddy.client"
										serviceName="MyAppWebService" />
			</target>
		</project>
		
If we look at the taskdef, it points to class ClientGenTask, As we explained earlier every ant task is associated with individual java class. If we write an custom ant task, that should extend a Class org.apache.tools.ant.Task. This is the first and foremost thing we should be doing this. Then it should be overriding the execute() from Task. These two are the important thing we have to notice while writing the custom AntTask. After this we can package this class into a JAR and use it like “clientgen” from Weblogic, by making use of taskdef.
Custom Task - MySimpleTask
In this example we’ll look into how to create our own task and call it from a build script. As i mentioned earlier we need to have class with extends Task and overriding the execute() method. Look at the below example
			package com.techmaddy.ant.taskdefs;

			import org.apache.tools.ant.Project;
			import org.apache.tools.ant.Task;

			public class MySimpleTask extends Task  {
				public void execute() {
					  log("My Simple Task", Project.MSG_INFO);
					  System.out.println("Demo MySimpleTask");
				   }
			}
		
I have used the log method from Task, to place the logs to exact place where the logs from ant is getting added, using SOP is not recommended. Complie this class and package into a JAR and use it your build script. The below is the example for the Build Script which makes a call to MySimpleTask.
			<?xml version="1.0" encoding="UTF-8"?>
			<project name="AntDemo" default="myOwnCustomTask">

				<taskdef name="mysimpletask" classname="com.techmaddy.ant.taskdefs.MySimpleTask" />

				<target name="myOwnCustomTask">
					<mysimpletask/>
				</target>

			</project>
		
The below image shows the output.
Ant-Custom Task
Library Dependencies
1. For Mail task you need to have mail.jar and activation.jar.
2. For FTP task you need to have commons-net.x.x.jar and jakarta-oro-x.x.jar.
3. For Clientgen task you need to have weblogic.jar, webservice.jar and tools.jar.
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Get Adobe Flash playerPlugin by wpburn.com wordpress themes