Archive for the ‘Webservices’ 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)

Consuming a Web Service from Your Java Class

Wednesday, September 30th, 2009
To use a web service over a network, which is called “consuming” a web service, you need to create a web service client. For the creation of web service clients, we have various methods, we can generate the client JAR by using IDE’’s build functionality. IDE’’s like Netbeans,MyEclipse are having good support for doing these operations.
If you decided to do it on your own, still we have the method to generate the client jar and import in your application. In this example i have used clientgent task from Weblogic, By using an simple ant script we can achive this.
The clientgen task(cutom ant task from weblogic) is available in Weblogic 8.1 under bea\\weblogic81\\server\\lib\\webservices.jar. According to Oracle(BEA) clientgen does the followingThe clientgen Ant task generates, from an existing WSDL file, the client component files that client applications use to invoke both WebLogic and non-WebLogic Web Services. These files include:
  • The Java source code for the JAX-RPC or JAX-WS Stub and Service interface implementations for the particular Web Service you want to invoke.
  • The Java source code for any user-defined XML Schema data types included in the WSDL file.
  • The JAX-RPC mapping deployment descriptor file which contains information about the mapping between the Java user-defined data types and their corresponding XML Schema types in the WSDL file.
  • A client-side copy of the WSDL file.Two types of client applications use the generated artifacts of clientgen to invoke Web Services:
  • Stand-alone Java clients that do not use the J2EE client container.
  • J2EE clients, such as EJBs, JSPs, and Web Services, that use the J2EE client container

.

For example we”ll take the SpellChecker Web service, which is offered by Cdyne. The WSDL is made available to all. From the WSDL we”ll be able to generate the classes for consuming the webserivce.The ant script i have used to build the client jar looks like the following
		<?xml version="1.0" encoding="UTF-8"?>
		<project name="MyFirstWSClient" default="build-client">
			<taskdef name="clientgen" classname="weblogic.ant.taskdefs.webservices.clientgen.ClientGenTask" />
			<target name="build-client">
				<clientgen wsdl="http://ws.cdyne.com/SpellChecker/check.asmx?wsdl"
				clientJar="C:\\SpellCheckerClient.jar"
				packageName="com.techmaddy.ws"/>
			</target>
		</project>
	
The above given ant script, will give you an client stubs by whcih you can make a request to a Webservice and get the results.
Now we”ll write an stand alone java class, from that we”ll make a request an webservice using the above created client stubs.

		package com.techmaddy;

		import java.io.IOException;
		import java.rmi.RemoteException;
		import java.util.ArrayList;
		import java.util.List;
		import javax.xml.namespace.QName;
		import javax.xml.rpc.ServiceException;
		import javax.xml.rpc.handler.HandlerInfo;
		import javax.xml.rpc.handler.HandlerRegistry;
		import weblogic.webservice.context.WebServiceContext;
		import weblogic.webservice.context.WebServiceSession;
		import weblogic.webservice.core.handler.WSSEClientHandler;
		import weblogic.xml.security.UserInfo;
		import weblogic.xml.security.wsse.Security;
		import weblogic.xml.security.wsse.SecurityElementFactory;
		import com.cdyne.ws.Check;
		import com.cdyne.ws.CheckSoap;
		import com.cdyne.ws.Check_Impl;

		public class SpellChecker {
			private Check spellService = null;
			private CheckSoap soapPortType = null;

			private synchronized Check getService() throws IOException {
				spellService = new Check_Impl();
				WebServiceContext context = spellService.context();
				WebServiceSession session = context.getSession();
				HandlerRegistry registry = spellService.getHandlerRegistry();
				List list = new ArrayList();
				list.add(new HandlerInfo(WSSEClientHandler.class, null, null));
				registry.setHandlerChain(new QName("SpellChecker"), list);
				UserInfo ui = new UserInfo("", "");
				session.setAttribute(WSSEClientHandler.REQUEST_USERINFO, ui);
				SecurityElementFactory factory = SecurityElementFactory.getDefaultFactory();
				Security security = factory.createSecurity(null);
				security.addToken(ui);
				Session.setAttribute(WSSEClientHandler.REQUEST_SECURITY, security);
				return spellService;
			}

			private CheckSoap getPort() throws ServiceException, IOException {
				if (spellService == null) {
					try {
						soapPortType = getService().getcheckSoap();
					}
					catch (ServiceException e) {
						throw e;
					}
					catch (IOException e) {
						throw e;
					}
				}
				return soapPortType;
			}

			public void checkTextBody() throws RemoteException, ServiceException, IOException {
				com.cdyne.ws.DocumentSummary doc = getPort().checkTextBody("Minr pupppy iss Wrong", "0");
				String allcontent = doc.getBody();
				System.out.println("The Content is "+allcontent);
				System.out.println("The misspelled word is "+doc.getMisspelledWordCount());
			}

			public static void main(String[] args) {
				SpellChecker sc = new SpellChecker();
					try {
						sc.checkTextBody();
					}
					catch(IOException ee) {
						ee.printStackTrace();
					}
				catch (ServiceException e) {
					e.printStackTrace();
				}
			}
		}
	
The above class queries the WS and returns the result. But If we use the above class, we”ll get the following exception SOAP header Security was not understood
The SpellChecker classes, getService() method will get changed like the following. Because this webserivce doesn”t require any authentication, So when we SOAP header, we”ll get the above said exeception.
			private synchronized Check getService() throws IOException {
				spellService = new Check_Impl();
				return spellService;
			}
		
The WEB-INF/lib should have the following JARS. WS Lib
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