Monday, November 15, 2010

jQuery trim example

[sourcecode language="html"]
<html>
<head>
<title>
jQuery trim example
</title>
<script src="http://code.jquery.com/jquery-1.4.4.js"></script>
</head>
<body>
<button>Click on me to see the effect</button>
<script>
$("button").click(function () {
var exampleStr = " jQuery trim example ";
alert("'" + exampleStr + "'");
exampleStr = jQuery.trim(exampleStr);
alert("'" + exampleStr + "'");
});
</script>
</body>
</html>
[/sourcecode]

Email Sender using Apache commons mail

[sourcecode language="css"]
/*
Amobile - The Enterprise Open Source Mobile Billing System
Copyright (C) 2009-2010 Amobile Inc.

This file is part of aOneMobileVAS.

aOneMobileVAS is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

aOneMobileVAS is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with Amobile. If not, see <http://www.gnu.org/licenses/>.

File Name : EmailSender.java
Date : 20-Feb-2010:3:22:31 AM
User : Rahul Jain

*/
package com.thinkideas.client.emailengine;

/**
* @author Rahul Jain
*
*/

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.log4j.Logger;

/**
* This Class Sends a Email.This class don't have any dependency.
*
* @author rahul.jain
* @version :1.0.0
* @HowToUse :
*/
public class EMailSender {

/** Instance of Logger : LOG. */
private static final Logger LOG = Logger.getLogger(EMailSender.class);
/** String: CONFIG_LOC location of email config file. */
/** Getting the Config Properties file Location. */
/*
* public static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
* .getBundle(CONFIG_LOC);
*/
/** Email Host Name server. */
public static String hostName;
/** Getting the Sender Name. */
public static String senderName;
/** Getting the Sender Email Id. */
public static String senderEmail;
/** Getting the Sender Email user name. */
public static String fromEmailUserName;
/** Getting the Sender email password. */
public static String fromEmailPassword;
/** Getting the email subject. */
public static String emailSubject;
/**
*
*/
public static String emailContent;
public static String adminEmailId;

private static void getEmailConfig() {
Properties emailProps = new Properties();
try {
emailProps.load(new FileInputStream("emailconfig.properties"));
hostName = emailProps.getProperty("HostName");
senderName = emailProps.getProperty("SenderName");
senderEmail = emailProps.getProperty("SenderEmail");
fromEmailUserName = emailProps.getProperty("SenderEmailUserName");
fromEmailPassword = emailProps.getProperty("SenderEmailPassword");
emailSubject = emailProps.getProperty("EMailSubject");
emailContent = emailProps.getProperty("EmailContent");
adminEmailId = emailProps.getProperty("AdminEmail");

} catch (FileNotFoundException fnfExe) {
LOG.error(fnfExe.getMessage());
} catch (IOException ioe) {
LOG.error(ioe.getMessage());
}
}

/**
* This Method is a internal method for sending email to a email recipient
* with some html content that includes the message to be send. This can be
* also extends for sending attachements.
*
* @param userName
* : user name of the user.
* @param newPassword
* : new password to be sent.
* @param recipientName
* : Recipient name like "Abc".
* @param recipientEmail
* : Recipient email id like "abc@abc.com".
* @param message
* : Message content to be sent like :
* "Dear User, Your password is reseted"
* @param attachementLocation
* : Attachment location if any.
* @param fileName
* : file name if any.
* @return boolean : True if sent successfully.
* @throws EmailException
* : email exception is thrown if any error occurs.
*/
private boolean sendMail(String userName, String newPassword, String recipientName, String recipientEmail,
String message, String attachementLocation, String[] fileName) throws EmailException {

getEmailConfig();
// Creating the email message
HtmlEmail email = new HtmlEmail();
System.out.println("hostName:" + hostName + " fromEmailUserName:" + fromEmailUserName + " fromEmailPassword:"
+ fromEmailPassword + " recipientEmail:" + recipientEmail + " senderEmail:" + senderEmail);

email.setHostName(hostName);
email.setAuthentication(fromEmailUserName, fromEmailPassword);
email.addTo(recipientEmail, recipientName);
email.setFrom(senderEmail, senderName);
email.setSubject(emailSubject);
email.setHtmlMsg(message);
email.setTLS(true);
String msg = null;
try {
msg = email.send();
} catch (Exception e) {
LOG.error("Error occurred while emailing:" + e.getMessage() + "cause?" + e.getCause());
return false;
}
LOG.debug("Returning Message Email Sending Program:" + msg);
return true;
}
/**
* This Method sends the email and it get some information from caller and
* add some information from its own. This method formats the received
* message and make appropriate changes in that.
*
* @param userName
* : user name of the user.
* @param newPassword
* @param userFirstName
* : first name of the user.
* @param recipientEmail
* : Recipient email id like "abc@abc.com".
* @param remoteIpAddr
* : Ip address of the User from where request has been made.
* @return
* @throws EmailException
* : email exception is thrown if any error occurs.
*/
public boolean sendEmailToUser(String userName, String newPassword, String userFirstName, String recipientEmail,
String remoteIpAddr) throws EmailException {
getEmailConfig();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy HH:MM:SS");
Date toDayDate = new java.util.Date();
String currentTime = sdf.format(toDayDate);

LOG.debug("Cuurent time is :" + currentTime);

StringBuffer sb = new StringBuffer();
/*
* String emailContent = RESOURCE_BUNDLE.getProperty("EmailContent");
* String adminEmailId = RESOURCE_BUNDLE.getString("AdminEmail");
*/

LOG.debug("User:" + userName + " newPassword:" + newPassword + " userFirstName:" + userFirstName
+ " recipientEmail:" + recipientEmail + " remoteIpAddr:" + remoteIpAddr);

// If due to any reason user first name is coming as null then it will
// make default User. so in email it will become "Dear User" rather than
// "Dear null"
if (userFirstName == null || userFirstName.length() == 0) {
userFirstName = "User";
}

StringBuffer sb1 = new StringBuffer();
sb1.append(userFirstName.substring(0, 1).toUpperCase());
sb1.append(userFirstName.substring(1, userFirstName.length()));
userFirstName = sb1.toString();
sb1 = null;// Making null so can be collected by Java GarbageCollector.

emailContent = emailContent.replaceAll("%userName%", userName);
emailContent = emailContent.replaceAll("%newPassword%", newPassword);
emailContent = emailContent.replaceAll("%userFirstName%", userFirstName);
emailContent = emailContent.replaceAll("%requestIpAddress%", remoteIpAddr.toString());
emailContent = emailContent.replaceAll("%toDayDate%", toDayDate.toString());
emailContent = emailContent.replaceAll("%requestTime%", currentTime.toString());
emailContent = emailContent.replaceAll("%adminEmailId%", adminEmailId);

emailContent = sb.append(emailContent).toString();

sb = null;// Making null so can be collected by Java GarbageCollector.

// attachementLocation is null and fileName array is null;
// can be used if adding more functionalities in this program.
boolean emailSentStatus =
sendMail(userName, newPassword, userFirstName, recipientEmail, emailContent, null, null);
System.out.println("email content:" + emailContent);
if (emailSentStatus) {
LOG.info("Email Sent Sucsessfully");
} else {
LOG.info("Email Couldn't Sent Sucsessfully");
}
return emailSentStatus;

}

public static void main(String[] args) {
EMailSender emailSender = new EMailSender();
try {
emailSender.sendEmailToUser("", "", "testuser", "testuser@gmail.com", "");
} catch (EmailException e) {
System.out.println("Exception message:" + e.getMessage() + "cause?" + e.getCause());
e.printStackTrace();
}
}
}
[/sourcecode]

Java crawler

package com.myjobalert.crawler;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public abstract class Crawler {

public String getURLContents(String urlStr, HttpParam[] httpParams) throws IOException {
URL url = new URL(urlStr);
URLConnection conn = url.openConnection();
HttpURLConnection httpconn = (HttpURLConnection) conn;

if (httpParams != null) {
httpconn.setRequestMethod("POST");
for (HttpParam param : httpParams) {
httpconn.setRequestProperty(param.getName(), param.getValue());
}
conn = httpconn;
}
InputStreamReader bis = new InputStreamReader(conn.getInputStream());
System.out.println("page size:"+conn.getContentLength());
final int char_per_page = 5000;
char[] buff = new char[char_per_page];
StringBuilder sb = new StringBuilder(char_per_page);
int read = 0;
while (read != -1) {
read = bis.read(buff);
if (read != -1)
sb.append(buff, 0, read);
}
System.out.println("page size:"+(sb.length()/1000)+"KB");
System.out.println("page is downloaded");
return sb.toString();
}
}

class HttpParam {

private String name;
private String value;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getValue() {
return value;
}

public void setValue(String value) {
this.value = value;
}
}

http://ws.amazon.com/widgets/q?rt=qf_br_asin_ssw&ServiceVersion=20070822&MarketPlace=US&ID=V20070822%2FUS%2Fmyknowledgebo-20%2F8003%2F13de8fda-f06a-4d41-9041-b4aeab627f25&Operation=GetDisplayTemplate Amazon.com Widgets

Wednesday, October 27, 2010

Hibernate for beginners

Contents
1. Introduction
2. Hibernate Architecture
3. Building a simple application using hibernate
4. Application Configuration – hibernate.cfg.xml
5. Creating the POJO(Plain Old Java Objects)
6. Creating the Dao(Data Access Objects)
7. Testing the Dao functionality using Junit Test
8. Conclusion
9. References
10. Glosssary

1. Introduction

Hibernate is an open source java based library used to work with relational databases. Hibernate is an Object/Relational Mapping (ORM) tool for Java environments. The term Object/Relational Mapping (ORM) refers to the technique of mapping a data representation from an object model to a relational data model with a SQL-based schema. It is a very powerful ORM solution built on top of JDBC (Java Database Connectivity) API.

Hibernate not only takes care of the mapping from Java classes to database tables (and from Java data types to SQL data types), but also provides data query and retrieval facilities. It can also significantly reduce development time otherwise spent with manual data handling in SQL and JDBC.

Hibernate makes uses of persistent object called as POJO (Plain Old Java Objects) having simple getter and setter methods along with XML mapping documents for persisting objects into database.


2. Hibernate Architecture

hibernate architecture
Here are some definitions of the objects depicted in the diagrams:

SessionFactory (org.hibernate.SessionFactory)
Session factory is a threadsafe, immutable cache of compiled mappings for a single database. A factory for Session and a client of ConnectionProvider, SessionFactory can hold an optional (second-level) cache of data that is reusable between transactions at a process, or cluster, level. Only single instance of session factory is required for an application, so it is based on a singleton pattern. SessionFactory object is loaded at the start of the application.


Session (org.hibernate.Session)
Session is a single-threaded, short-lived object representing a conversation between the application and the persistent store (database, xml). It wraps a JDBC connection and is a factory for Transaction. Session holds a mandatory first-level cache of persistent objects that are used when navigating the object graph or looking up objects by identifier.

Persistent objects and collections
Short-lived, single threaded objects containing persistent state and business function. These can be ordinary JavaBeans/POJOs. They are associated with exactly one Session. Once the Session is closed, they will be detached and free to use in any application layer (for example, directly as data transfer objects to and from presentation).

Transient and detached objects and collections
Instances of persistent classes that are not currently associated with a Session. They may have been instantiated by the application and not yet persisted, or they may have been instantiated by a closed Session.

Transaction (org.hibernate.Transaction)
(Optional) A single-threaded, short-lived object used by the application to specify atomic units of work. It abstracts the application from the underlying JDBC, JTA or CORBA transaction. A Session might span several Transactions in some cases. However, transaction demarcation, either using the underlying API or Transaction, is never optional.

ConnectionProvider (org.hibernate.connection.ConnectionProvider)
(Optional) A factory for, and a pool of, JDBC connections . It abstracts the application from underlying Datasource or DriverManager. It is not exposed to application, but it can be extended and/or implemented by the developer.

TransactionFactory (org.hibernate.TransactionFactory)
(Optional) A factory for Transaction instances . It is not exposed to the application, but it can be extended and/or implemented by the developer.
Extension Interfaces

Hibernate offers a range of optional extension interfaces you can implement to customize the behavior of your persistence layer. See the API documentation for details.
Given a "minimal" architecture, the application bypasses the Transaction/TransactionFactory and/or ConnectionProvider APIs to communicate with JTA or JDBC directly.

Instance States :

An instance of persistent class can be in three different states,
These states are defined in relation to a persistence context. The Hibernate Session object is the persistence context. The three different states are as follows:

Transient
The instance is not associated with any persistence context. It has no persistent identity or primary key value.

Persistent
The instance is currently associated with a persistence context. It has a persistent identity (primary key value) and can have a corresponding row in the database. For a particular persistence context, Hibernate guarantees that persistent identity is equivalent to Java identity in relation to the in-memory location of the object.

Detached
The instance was once associated with a persistence context, but that context was closed, or the instance was serialized to another process. It has a persistent identity and can have a corresponding row in the database. For detached instances, Hibernate does not guarantee the relationship between persistent identity and Java identity.

Transaction Management :

Transaction Management service provides the ability to the user to execute more than one database statement at a time. For starting a transaction a method of begin transaction should be invoked on a Session object.(session.beginTransaction()).

If transaction is successfully executed it should be commited to persist the data in database using commit method transaction.commit();

In case of any exception or failure the transaction must be rollback to synchronize the database state otherwise database will throw an exception as current transaction is aborted. transaction .rollback();

3. Building a simple application using hibernate
Now we need to add the Hibernate and below libraries into the project . You can download the latest version of hibernate if you haven't already got if from www.hibernate.org. The version used in this tutorial is 3.0. you may find it easier to download the package containing all the dependencies so that you know that all the necessary jar files are present.

hibernate libraries
In this tutorial we are using database as postgressql 8.3 so we have to add the database dialect as per the database.
Database: Postgresql8.3.1
Hibernate version: hibernate 3.0

User_Details.sql : The below Sql query will be used for creating the table in the database.
[sourcecode language="css"]
CREATE TABLE user_details (
user_id integer NOT NULL,
user_name character varying(20),
user_password character varying(20),
CONSTRAINT "USER_pkey" PRIMARY KEY (user_id)
)
[/sourcecode]
4. Application Configuration – hibernate.cfg.xml
The hibernate.cfg.xml is a configuration file that is used for defining the db parameters like db username, password, connection url, connection pool size etc . This also includes the definig hbm (xml based hibernate mapping) files that have mapping of database column to java attributes.
hibernate.cfg.xml
[sourcecode language="css"]
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.url">jdbc:postgresql://127.0.0.1:5432/qc</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.connection.password">postgres</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<property name="show_sql">true</property>
<mapping resource="com/hibernatetest/demo/User.hbm.xml" />
</session-factory>
</hibernate-configuration>
[/sourcecode]


User.hbm.xml
[sourcecode language="css"]
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.hibernatetest.demo.User" table="user_details" schema="public" optimistic-lock="version">
<id name="userId" type="java.lang.Integer">
<column name="user_id" />
<generator class="increment" />
</id>
<property name="userName" type="string">
<column name="user_name" length="20" />
</property>
<property name="userPassword" type="string">
<column name="user_password" length="20" />
</property>
</class>
</hibernate-mapping>
[/sourcecode]


HibernateUtil.java : It is a java class that returns a session factory object that is used for getting the session(connection) object.
[sourcecode language="css"]
package com.hibernatetest.demo;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;


/**
* @author rjain6
*/
public class HibernateUtil
{

private static SessionFactory sessionfactory = null;

public static SessionFactory getSessionFactory()
{
Configuration cfg = new Configuration();
sessionfactory = cfg.configure("com/hibernatetest/demo/hibernate.cfg.xml").buildSessionFactory();
return sessionfactory;
}

}
[/sourcecode]
5. Creating the POJO(Plain Old Java Objects)
Now for persisting data to the database, hibernate requires a Java bean (POJO) object to be passed. For this we are writing a User’s pojo object having all getter and setter methods of attributes. These attributes will be work as carrier of data that will be stored in database. As these POJO Objects will travel across the network, these objects should implement the Serializable interface.
package com.hibernatetest.demo;

[sourcecode language="css"]
import java.io.Serializable;


/**
* This class is a POJO that works as a carrier of the
* data and will be stored in database by hibernate.
* @author rjain6
*/
public class User implements Serializable
{

private int userId;
private String userName;
private String userPassword;

public int getUserId()
{
return userId;
}

public void setUserId(int userId)
{
this.userId = userId;
}

public String getUserName()
{
return userName;
}

public String getUserPassword()
{
return userPassword;
}

public void setUserName(String userName)
{
this.userName = userName;
}

public void setUserPassword(String userPassword)
{
this.userPassword = userPassword;
}
}
[/sourcecode]
6. Creating the Dao (Data Access Objects)
Since this is a very simple application, there are only 1 Dao(Data Access object). is involved. This Dao class have methods to perform all the basic CRUD (Create, Read , Update, Delete ) functionalities.
[sourcecode language="css"]
package com.hibernatetest.demo;


import java.io.Serializable;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;


/**
* This is DAO class for performing database related functionalities.
* @author rjain6
*/
public class UserDAO
{

/**
* Creating a user in the database
*/
public int createRecord(User user)
{
Transaction tx = null;
Session session = HibernateUtil.getSessionFactory().openSession();
tx = session.beginTransaction();
Serializable s = session.save(user);
tx.commit();
return ((Integer)s).intValue();
}

/**
* Updating a user’s details in the database
*/
public boolean updateRecord(User user)
{
boolean isSuccess = false;
Transaction tx = null;
Session session = HibernateUtil.getSessionFactory().openSession();
try
{
tx = session.beginTransaction();
session.update(user);
tx.commit();
isSuccess = true;
} catch (HibernateException e)
{
isSuccess = false;
}
return isSuccess;
}

/**
* Deleting the user from the database
*/
public boolean deleteRecord(User user)
{
boolean isSuccess = false;
Transaction tx = null;
Session session = HibernateUtil.getSessionFactory().openSession();
try
{
tx = session.beginTransaction();
session.delete(user);
tx.commit();
isSuccess = true;
} catch (HibernateException e)
{
isSuccess = false;
}
return isSuccess;
}

/**
* Retrieving All users’ details from the database
*/
public List retrieveAllRecord()
{
Transaction tx = null;
Session session = HibernateUtil.getSessionFactory().openSession();
List ls = null;
tx = session.beginTransaction();
Query q = session.createQuery("from User");
ls = q.list();
return ls;
}

/**
* Retrieving All users’ names from the database
*/
public List retrieveAllUserName()
{
Transaction tx = null;
Session session = HibernateUtil.getSessionFactory().openSession();
List ls = null;
tx = session.beginTransaction();
//Native Query
Query q = session.createSQLQuery("select user_name from User_Details");
ls = q.list();
return ls;
}

}
[/sourcecode]
7. Testing the Dao functionality using Junit Test
The final stage in this simple tutorial is to create Junit test class to check the Session factory object and functionality of the data layer.
The contents of the class are shown below.
HibernateUtilTest.java : It is Test class for testing the working of session factory object. If Session factory object is not null, that means hibernate is able to get the database connection from DB.
[sourcecode language="css"]
package com.hibernatetest.demo;

import org.junit.Test;


/**
* This is a test class for chcecking is sessionfactory(database connection) is loaded by hibernate properly.
* @author rjain6
*/
public class HibernateUtilTest
{

/**
* Test method for {@link com.hibernatetest.demo.HibernateUtil#getSessionFactory()}.
*/
@Test
public void testGetSessionFactory()
{
System.out.println("session factory:"
+ HibernateUtil.getSessionFactory());
}

}[/sourcecode]
UserDAOTest.java :
[sourcecode language="css"]
package com.hibernatetest.demo;


import java.util.Collection;
import java.util.List;

import org.junit.Test;


/**
* This is test class having test methods to check the functionality of UserDAO class .
* @author rjain6
*/
public class UserDAOTest
{

@Test
public void createRecordTest()
{
UserDAO userDAO = new UserDAO();
User user = new User();
user.setUserName("demo");
user.setUserPassword("demo");
int recordId = userDAO.createRecord(user);
System.out.println("recordId:" + recordId);
}

@Test
public void updateRecordTest()
{
UserDAO userDAO = new UserDAO();
User user = new User();
user.setUserId(2);
user.setUserName("demo123");
user.setUserPassword("demo123");
boolean status = userDAO.updateRecord(user);
System.out.println("status:" + status);
}

@Test
public void deleteRecordTest()
{
UserDAO userDAO = new UserDAO();
User user = new User();
user.setUserId(3);
boolean status = userDAO.deleteRecord(user);
System.out.println("status:" + status);
}

@Test
public void retrieveRecordTest()
{
UserDAO userDAO = new UserDAO();
List list = userDAO.retrieveAllRecord();
if (isNullSafe(list))
{
for (int i = 0;i < list.size();i++)
{
System.out.println("UserName:" + ((User)list.get(i)).getUserName());
System.out.println("UserPassord:" + ((User)list.get(i)).getUserPassword());
}
}
}

@Test
public void retrieveAllUserNameTest()
{
UserDAO userDAO = new UserDAO();
List ls = userDAO.retrieveAllUserName();
if (isNullSafe(ls))
{
for (int i = 0;i < ls.size();i++)
{
System.out.println("UserName:" + ls.get(i));
}
}
}

/**
* @param ls
* @return
*/
private boolean isNullSafe(Collection col)
{
if (col != null && col.size() > 0)
return true;
else
return false;
}
}
[/sourcecode]

8. Conclusion
Hibernate is an ORM tool that is used to map the database structures to java objects at run time. Using a persistence framework like Hibernate allows developers to focus on writing business logic code instead of writing an accurate and good persistence layer which include writing the SQL Queries, JDBC Code , connection management etc.
9. References
1. https://www.hibernate.org/
2. http://docs.jboss.org/hibernate/core/3.3/reference/en/html/architecture.html

10. Glosssary
• ORM : Obejct Relational Mapping
• SQL : Structural Query Language
• HQL : Hibernate Query Language
• POJO : Plain Old Java Objects
• JDBC : Java Database Connectivity API
• HBM : Hibernate Mapping


Sunday, May 2, 2010

Sorting a list in java using comparator

[sourcecode language="css"]
public class SortTest {
    public static void main(String[] args) {
        List<Integer> ls = new ArrayList<Integer>();
        for (int i = 1; i &lt; 10; i++) {
            Random r = new Random();
            int randomNo = r.nextInt(i);
            ls.add(randomNo);
        }
        System.out.println("before sorting:" + ls);
        Comparator c = new Comparator() {
            @Override
            public int compare(Object arg0, Object arg1) {
                if ((Integer) arg0 &gt; (Integer) arg1) {
                    return 1;
                } else if ((Integer) arg0 == (Integer) arg1) {
                    return 0;
                } else {
                    return -1;
                }
            }
        };
        Collections.sort(ls, c);
        System.out.println("after sorting:" + ls);

    }
}
[/sourcecode]