Archive for the ‘Java’ Category

Google URL Shortner API

Monday, January 24th, 2011
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

Wednesday, January 5th, 2011
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)

Ant-The Complete Reference

Wednesday, December 1st, 2010
Apache Ant is a Java library and command-line tool which is used to build the Java applications. Ant supplies a number of built-in tasks allowing to compile,
assemble, test and run Java applications. Ant can also be used on non Java applications. In Ant every process is described as task and targets. The Ant consists of
few layers for building the applications. The default and the foremost layer is the Project. And the project will have at least one target and the targets will have one
or more task. These task elements can be of built-in or it can be user defined also. From this we can easily understand that each task attributed to a individual java
class. The below structure will explain basic the structure of the Ant build script
			<project>
				<target>
					<task/>
					<task/>
					.
					.
					.
					.
					<task/>
				</target>
				.
				.
				.
				.
				.
				<target>
					<task/>
					<task/>
					.
					.
					.
					.
					<task/>
				</target>
			</project>
		
And all these elements are put under a single XML file, by default Ant looks for build.xml in your project when you build the application. It’s up to the developer
to instruct the Ant to look for a different build script. Mode of use

  • Command Line
  • IDE Integration
Ant in Command Line
Ant can be invoked from command prompt. Ant provides many built-in command line arguments.We’ll consider few example which we’ll use frequently.
  •  ant - This will invoke the Ant with the default settings, i.e The Ant will look for build.xml in your project and run it.
  •  ant -debug - We are adding few more lines in output to understand the ant execution,It’ll be helpful when we are trying
    to debug the ant execution.Ant provides a rich set of options to run from the command prompt.Can be refered from here.
  •  ant -buildfile - If your project has a different name for the build file you can use this option.
  •  ant -buildfile AntDemoBuild.xml clean - Instructing ant to call AntDemoBuild.xml as a build script and the default target is clean
IDE Integration
Netbeans uses Ant as an default build tool to build the applications. Eclipse also provides the option to the user to use Ant as a build tool. When you create an
build.xml by default Eclipse gives you the option for running this as Ant Build. Apart from that the “Outline” view provides you the details about individual targets and
allows you run that separately. The below image show the Sample build script and it’s integration with Eclipse.
Ant-IDE
Defining Properties
Inside the build script file we can define few properties, either it can be internal to build script and we can define a external property file and include that
			<property name="project.name" value="AntDemo" />

			<property file="build.properties" />
		
The first line defines the property called “project.name” with the value of “AntDemo”. The second line includes all the property from the file into build script.
Defining Path
If we are using any IDE’s for the development of the project then we’ll be referring to common libraries using Build Path. If we wanted to use those libraries
during our build operation, we can use PATH attribute. And this can be refereed anywhere in the build script by using tag CLASSPATH.
			<path id="classpath">
				<fileset dir="${lib.dir}">
					<include name="*.jar"/>
				</fileset>
			</path>
		
The below script is the complete build script, which will provide you a complete set of examples to build an application and make an WAR.
		<project name="AntDemo" default="makeWar">

			<property name="project.name" value="AntDemo" />

			<property file="build.properties" />

			<path id="classpath">
				<fileset dir="${lib.dir}">
					<include name="*.jar"/>
				</fileset>
			</path>

			<target name="clean">
				<echo>Deleting the existing Build Directories</echo>
				<delete dir="${dist.dir}" />
				<delete dir="${classes.dir}" />
			</target>	

			<target name="init" depends="clean">
				<echo>Deleting the existing Build Directories</echo>
				<mkdir dir="${classes.dir}"/>
				<mkdir dir="${dist.dir}" />
			</target>

			<target name="compile" depends="init" >
				<javac destdir="${classes.dir}" debug="true" srcdir="src">
					<classpath refid="classpath"/>
				</javac>
			</target>

			<target name="makeWar" depends="compile">
				<war destfile="${dist.dir}/${project.name}.war" webxml="${web.dir}/WEB-INF/web.xml">
					<fileset dir="${web.dir}"/>
					<lib dir="${lib.dir}"/>
					<classes dir="${classes.dir}"/>
				</war>
			</target>

		</project>
		
When you run the build script, we’ll get the following output.
Ant-Run
I’ll add few more task including the custom tasks in the next post.
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 player