Friday, October 10, 2008

Comparing object and sorting them in java using Comparator and Comparable interfaces

As we know sorting is one of the very common tasks especially when we have a list or collection of objects. For example if we have a list of Employees then we would like to display it in some order may be by sorting them by EmpId or name. In these situations both (Comparator and Comparable) will become handy.

About Comparators and Comparables

Simply putting java.lang.Comparator and java.lang.Comparable are used for comparing objects in java.

Comparator

A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.lang.Comparator interface.

Comparable

A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances.

Now lets see how we can use these interfaces

Each of these has one method to be implemented by user.

java.lang.Comparable: int compareTo(Object obj1)
This method compares this object with obj1 object. Returned int value has the following meanings.

  1. positive – this object is greater than obj1
  2. zero – this object equals to obj1
  3. negative – this object is less than obj1


java.lang.Comparator: int compare(Object obj1, Object obj2)
This method compares obj1 and obj2 objects. Returned int value has the following meanings.

  1. positive – obj1 is greater than obj2
  2. zero – obj1 equals to obj2
  3. negative – obj1 is less than obj1

Note:

java.util.Collections.sort(List) and java.util.Arrays.sort(Object[]) methods can be used to sort using natural ordering of objects.
java.util.Collections.sort(List, Comparator) and java.util.Arrays.sort(Object[], Comparator) methods can be used if a Comparator is available for comparison.

Now let’s do a simple example to see these concepts in real scenario.

(1) First we will write a simple Employee class as below..

public class Employee {

private int empId;

private String name;

public Employee(int empId, String name) {

this.empId=empId;

this.name=name;

}

public int getEmpId() {

return empId;

}

public void setEmpId(int empId) {

this.empId = empId;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

(2) Next we will write a class to implement compare() method of comparator interface. You can see below in the code that we are comparing Employee object by name attribute. Instead of name we can use Empid attribute to compare objects for sorting. The choice depends on the need.

public class NameComparator implements Comparator{

public int compare(Object emp1, Object emp2) {

String emp1Name = ( (Employee) emp1).getName();

String emp2Name = ( (Employee) emp2).getName();

return emp1Name.compareTo(emp2Name);

}

}

(3) Finally we will write a test class to use our NameComparator class for comparing and sorting Employee objects.

import java.util.ArrayList;

import java.util.Collections;

import java.util.HashSet;

import java.util.Iterator;

import java.util.List;

import java.util.Set;

public class TestEmployeeSort {

public static void main(String args[]){

//create a set of Employee object without any specific order

Set<Employee> set = new HashSet<Employee>();

set.add(new Employee(3, "Raj"));

set.add(new Employee(1, "Sajid"));

set.add(new Employee(6, "Sowmya"));

set.add(new Employee(2, "Manu"));

set.add(new Employee(7, "Larry"));

set.add(new Employee(4, "Suresh" ));

set.add(new Employee(8, "Harry"));

set.add(new Employee(5, "Ashu"));

//converting set to list

List<Employee> list=new ArrayList<Employee>(set);

System.out.println("Order of employee before sorting is");

Iterator i=list.iterator();

while(i.hasNext())

{

Employee e1=(Employee) i.next();

System.out.println(e1.getEmpId() + "\t" + e1.getName() );

}

//calling sort method and passing the list of employees and a new instance of our NameComparator class

Collections.sort(list,new NameComparator());

System.out.println("Order of employee after sorting is");

for (Employee e: list) {

System.out.println(e.getEmpId() + "\t" + e.getName() );

}

}

}

After running this test class we would get following output.

Order of employee before sorting is

3 Raj

8 Harry

6 Sowmya

1 Sajid

4 Suresh

5 Ashu

7 Larry

2 Manu

Order of employee after sorting is

5 Ashu

8 Harry

7 Larry

2 Manu

3 Raj

1 Sajid

6 Sowmya

4 Suresh

Send free SMS using Google Labs SMS channel

Google Labs in India (http://labs.google.co.in/ ) have launched their latest mobile service named Google SMS channel. This service is designed to enable users to send free group SMS messages across India. The good thing is that they currently support messages in several languages including English, Hindi, Kannada etc. You can receive alerts for latest news, cricket updates, blog feeds, daily quotes, horoscope , jokes, news from MoneyControl, and lot more and all for free.

I think it would be a great way to connect 200+ million mobile subscribers in India who still don’t have access to valuable information. Subscribers to this service can join as many as 30 channels but they will not receive more than 10 SMS messages a day. Other features are like message senders can send the message using a web based interface and the subscribers can set the time when they want to receive the messages.

I am also planning to create one SMS channel to connect with friends and family..

Visit the FAQ section (http://labs.google.co.in/smschannels/help ) for more details.

Enjoy sending free SMS to your friends and family members.

Friday, August 08, 2008

The world of Web Services

A web service is a piece of business logic, located somewhere on the Internet, that is accessible through standard Internet protocols such as HTTP or SMTP.
Let’s see the definition for web service as provided by W3C. According to them, a web service is a software application which is identified by a URI, whose interfaces and binding are capable of being defined, described and discovered by XML using XML-based messages via Internet-based protocols.
A web service is usually identified by a URI (Unified Recourse Identifier). A web service has WSDL (Web Service Description Language) definitions. To communicate with web services we need to use SOAP messages, which are XML based messages transported over Internet protocols like HTTP, SMTP, and FTP. Web services can be better described with the following diagram.
Here, the service requester is the client of the web service, and the service provider is the host of the web service. A requester makes SOAP requests to the provider and the provider responses accordingly. A service registry can be thought of as a database of web services. It has the definitions and URIs for web services. Developers of web services can publish their services to a service registry if they wish. After that someone can query the registry and choose the service from the registry. Since a registry has all the information required to develop a web client, developers can search and find necessary information from a service registry using UDDI (Universal Description, Discovery and Integration).
A developer usually publishes the WSDL for their services in the registry. A client can query the registry using UDDI and get the WSDL from the registry. After that the client can establish a connection with the service and send SOAP requests to the service, whose response will also be SOAP messages.

SOAP is used for communication between applications via the Internet. SOAP is platform independent. SOAP is also language independent; it is based on XML. Each SOAP message has a mandatory SOAP envelope, and multiple optional attachments. A SOAP envelope consists of an optional SOAP header, a mandatory body, and optional fault sections. Usually a SOAP body contains the original requests or the responses.

WSDL is an XML document, which is used to describe web services. WSDL is also used to locate web services.

Let’s define Web services platform elements.

SOAP
The basic Web services platform is XML plus HTTP.

  • SOAP stands for Simple Object Access Protocol
  • SOAP is a communication protocol
  • SOAP is for communication between applications
  • SOAP is a format for sending messages
  • SOAP is designed to communicate via Internet
  • SOAP is platform independent
  • SOAP is language independent
  • SOAP is based on XML
  • SOAP is simple and extensible
  • SOAP allows you to get around firewalls
  • SOAP will be developed as a W3C standard

WSDL

WSDL is an XML-based language for describing Web services and how to access them.

  • WSDL stands for Web Services Description Language
  • WSDL is written in XML
  • WSDL is an XML document
  • WSDL is used to describe Web services
  • WSDL is also used to locate Web services
  • WSDL is not yet a W3C standard

UDDI

UDDI is a directory service where businesses can register and search for Web services.

  • UDDI stands for Universal Description, Discovery and Integration
  • UDDI is a directory for storing information about web services
  • UDDI is a directory of web service interfaces described by WSDL
  • UDDI communicates via SOAP
  • UDDI is built into the Microsoft .NET platform

Using Apache Axis for developing web services..

Axis is essentially a SOAP engine -- a framework for constructing SOAP processors such as clients, servers, gateways, etc.
Or we can simply say that Axis is an implementation of SOAP which turns Java code into Web services.
The latest version of Axis can be downloaded from their Web site, http://ws.apache.org/axis.

After downloading the latest version of Axis Unzip the package downloaded to a folder in your system. Further we can create on axis.war and copy it to tomcat webapps folder.

To validate the proper installation try http://localhost:8080/axis in explorer.. you should see the Apache-Axis start page. If you are not able to see the page then probably your web application is not deployed properly.
We can create one sample web service using axis in few steps..
(1) first create a normal project in Eclipse IDE by simple importing the axis.war
use file --> import option and then select War file.

(2) Create a simple Hello.jws and save it in the WebContent folder of Axis project. see the code below.

public class Hello {
public String sayHello(String name){

System.out.println("in hello service");

return "Hello"+name;

}

}

Note: any .java file can be simply be saved as .jws
(3) Now create another java project (a client) which will use our hello web service. See the sample code below .it shows how we can call our service.
import java.net.URL;

import javax.xml.namespace.QName;

import javax.xml.rpc.ParameterMode;

import org.apache.axis.client.Call;

import org.apache.axis.client.Service;

import org.apache.axis.encoding.XMLType;

public class HelloClient {

public static void main(String[] args) {

try {

Service service=new Service();

Call call=(Call) service.createCall();

call.setTargetEndpointAddress(new URL(http://localhost:8080/axis/Hello.jws));

call.setOperation(new QName("Hello"), "sayHello");

call.addParameter("in0", XMLType.XSD_STRING, ParameterMode.IN);

call.setReturnType(XMLType.XSD_STRING);

Object returnval=call.invoke(new Object[] {"India"});

System.out.println(returnval.toString());

} catch(Exception e)

{ e.printStackTrace();

}

}

}

Now we can run our client which will call our service internally. Make sure that your tomcat server is up and running when you run the client program.We can even use other tools like BEA Weblogic Workshop to create web services. These tools generate most of the code automatically. It also provides features to provide security and test our web services as well.

Tuesday, July 29, 2008

For knowledge, ask Cuil

Well yet another search engine that too from ex-googlers ..interesting. They have claimed that Cuil searches more pages on the Web than anyone else—three times as many as Google and ten times as many as Microsoft. I think its too early to compare it with google, thought Cuil has come up with some cool features like Drilldown, Tabs and Navigation suggestion etc on the search page.

Their success truly depends on the methods and techniques/algos they use for indexing the web because only good indexing can give you good results.

Another Interesting fact is that search technologies continue to come from Stanford University Comp Science PhDs (Yahoo, Google, Cuil…).

Checkout the feature and the people behind this new search engine at http://www.cuil.com

Monday, March 03, 2008

Sun Tech Days Plus, Bangalore

Sun Tech Days Plus was an exclusive annual event of Sun Microsystems which happened in Bangalore on 27th Feb, 08 at Hotel Grand Ashok. Actually it was an extension to the main event which was happening in Hyderabad. They started with the Keynotes of Rich Green live from Hyderabad. After the speech of Rich green there was a Demo showcase and that was really cool. Guys were showcasing their work using java technologies like Swing, J2me and JavaFX.

After the demo showcase they started with the sessions. The first session was on Java SE 6 Update N. Update N is the new release of java SE 6 that introduces new features and enhancements. It was pretty interesting to know that how Sun is taking quick moves to enhance java features and capabilities.

Another interesting session was on Batch processing with Spring Batch. Spring Batch is a lightweight batch framework designed to enable the development of robust batch applications vital for the daily operations of enterprise systems. This session was from Accenture and they showcased a simple example as well for doing a batch processing using Spring batch.

Apart from other sessions I liked one interesting session on Metro and REST. Project Metro is the new name for the web services stack from Sun. So we can say Metro is nothing but JAX-WS + Project Tango combination. JAX-WS is the standardized web services stack and Project Tango (also known as WSIT) is the interoperability toolkit (interoperability with .Net 3.0). REST (Representational State Transfer) describes an architecture style of networked systems. There’s a debate going on in the industry that says REST is better method for building Web services than SOAP. The whole web services space looks quite interesting and Sun has given good support for web services development in the new release of NetBeans IDE. There were some other sessions as well on JavaFX and Java Persistence API by Sun guys and there was a session on Unit testing J2EE applications using JUnit by Accenture guys. Overall the event was good with the main focus on showcasing Sun’s new technologies and initiatives which will really create some sort of awareness among the techies about the new technologies.

Friday, February 15, 2008

A dozen free & essential apps for Windows

A dozen free & essential apps for Windows by ZDNet's George Ou -- Every time I build a new Windows computer, there are a dozen free and essential applications that I always install for other people. These applications all seem to fill essential functions and they all seem to be well-behaved installers and uninstallers, in other words it won’t crash your computer or drag it down with gunk. [...]

Wednesday, February 13, 2008

Small utility program to unlock PDF documents

Ever downloaded a PDF document from internet which doesn’t have print option or its disabled? I hope you must have come across this situation.

Try this small java program to unlock PDF document for printing etc.

I am using iText API for doing it. They have a very rich collection of classes and methods to play with PDF files.

 

You need itext-1.4.6.jar to run this program. You can download this jar from http://www.lowagie.com/iText/download.html . If you are using eclipse IDE then set this jar in your project build path or if you are running this code from command prompt then you need to set this jar in your classpath.

 

So here is the code… just copy it and run it. You can see we are passing PDF file name to unlockPdf() method though command prompt. inputFile name is your original file which you want to unlock and outputFile name can be anything which you like.

 

package my.examples;

 

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

 

import com.lowagie.text.DocumentException;

import com.lowagie.text.pdf.PdfEncryptor;

import com.lowagie.text.pdf.PdfReader;

import com.lowagie.text.pdf.PdfWriter;

 

public class UnlockPdf

{

  public static void main(String[] args)

  {

    if (args.length < 2)

    {

      System.err.println("usage: java my.examples.UnlockPdf inputfile.pdf outputfile.pdf");

    }

   else

    {

      new UnlockPdf().unlock(args[0], args[1]);

    }

  }

 

  private void unlock(String inputFile, String outputFile)

  {   

 

    try

    {

      PdfReader reader = new PdfReader(inputFile);

      PdfEncryptor.encrypt(reader, new FileOutputStream(outputFile), null, null,

  PdfWriter.AllowAssembly | PdfWriter.AllowCopy

              | PdfWriter.AllowDegradedPrinting | PdfWriter.AllowFillIn

              | PdfWriter.AllowModifyAnnotations | PdfWriter.AllowModifyContents

              | PdfWriter.AllowPrinting | PdfWriter.AllowScreenReaders, false);

    }

    catch (FileNotFoundException e)

    {

      e.printStackTrace();

    }

    catch (IOException e)

    {

      e.printStackTrace();

    }

    catch (DocumentException e)

    {

      e.printStackTrace();

    }

  }

}

 

 

 

 

 

Popular Posts