Author Archive

Redirect to Error page in Wicket

I was looking for a solution to redirect to an error page in wicket and found this class , RestartResponseAtInterceptPageException , causes wicket to interrupt current request processing and immediately redirect to an intercept page.

For example,
throw new RestartResponseAtInterceptPageException(new ErrorPage(“User does not have permission to view this screen”));

If you need to redirect to an intercept page without interrupting the current request processing , call RedirectToInteceptPage(Page) instead.

-Dhanya

List files sorted by date in java

File inboxDir = new File(“Path to your directory”);
File[] files = inboxDir.listFiles();
Arrays.sort( files, new Comparator()
{
public int compare(Object o1, Object o2) {
return new Long(((File)o1).lastModified()).compareTo(new Long(((File) o2).lastModified()));
}

});

Calling Oracle Stored Procedure from Hibernate

While calling Oracle stored procedure from Hibernate  there is couple of rules that we need to follow. There can be only one return value and this must be a reference cursor. This return reference cusor must be the first and only out value for the stored procedure. It is required that stored procedure must return a reference cursor to be used from Hibernate.

Here is my stored procedure which return book name and ISBN number for a given branch and for a given author

CREATE OR REPLACE PROCEDURE SP_LIB_DTL(p_cursor    out sys_refcursor,
                                       in_brnch_cd in number,
                                       in_auth_cd in number)
as
  bookName varchar2(8);
  ISBN     number;
begin
  bookName := null;
  ISBN     := 0;
  open p_cursor for
    select l.book_name, l.isbn_nbr
      into bookName, ISBN
      from LIB_BRNCH_DTL l
     where l.branch_code = in_brnch_cd
     and l.auth_code = in_auth_cd;

end;

HIbernate Mapping for return class and Named Query:

<?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.org.lib.LibraryDetails”>
<id name=”ISBN” type=”long” />
<property name=”bookName” type=”string” />
</class>
 <sql-query name=”LIB_SP” callable=”true”>
 <return class=”com.org.lib.LibraryDetails”>
   <return-property name=”ISBN” column=”isbn_nbr” />
   <return-property name=”bookName” column=”book_name” />
 </return>
  {  call SP_LIB_DTL(? , :branchCD ,:authorCD) }
 </sql-query>
</hibernate-mapping>

Make sure you have used the correct database field name value for the column attribute for the return property mapping. You will get the following error if you don’t map the correct databse field name

could not execute query; bad SQL grammar [{  call SP_LIB_DTL(? , ?) }];
nested exception is java.sql.SQLException: Invalid column name

Here is the DAO implementation for executing query and to set the bind parameter values.

public  List selectBooks(final BigDecimal branchCode,final BigDecimal authorCode){
        return (List) getHibernateTemplate().execute(new HibernateCallback() {
              public Object doInHibernate(Session session) throws HibernateException, SQLException
              {
                  Query q = session.getNamedQuery(“LIB_SP”);
                  q.setLong(“branchCD”, branchCode.longValue());
                  q.setLong(“authorCD”, authorCode.longValue());
                  return q.list();
              }
          });
      }

Java Calendar and Date Operations

Java – Find a given date belongs in which quarter:
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.applyPattern(“MM/dd/yyyy”);
Calendar calendar = Calendar.getInstance();
Date processDate = sdf.parse(“4/10/2007″);
calendar.setTime(processDate);
Date date1 = calendar.getTime();
int quarter = TestDate.getQuarter(date1);
System.out.println(“Quarter for the date : “+sdf.format(calendar.getTime())+” is : “+quarter);
Prints the following Result :
Quarter for the date : 04/10/2007 is : 2

Java – Code for getQuarter() function:
public static int getQuarter(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int[] months = { 3, 6, 9, 12 };
int count = 0;
do {
calendar.set(year, months[count++], 1);
Date tempDt = calendar.getTime();
if(date.compareTo(tempDt)
return count;
} while(count
return 0;
}

Java – Find previous quarter begin and end dates for a given date:
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.applyPattern(“MM/dd/yyyy”);
Calendar calendar = Calendar.getInstance();
Date processDate = sdf.parse(“4/10/2007″);
calendar.setTime(processDate);
Date date1 = calendar.getTime();
int quarter = TestDate.getQuarter(date1);
String currentQuarterBeginDate = “”;
String fromDt=”";
String toDt=”";
if ( quarter ==1){
currentQuarterBeginDate = “01/01/”+calendar.get(Calendar.YEAR);
}
if ( quarter ==2){
currentQuarterBeginDate = “04/01/”+calendar.get(Calendar.YEAR);
}
if ( quarter ==3){
currentQuarterBeginDate = “07/01/”+calendar.get(Calendar.YEAR);
}
if ( quarter ==4){
currentQuarterBeginDate = “10/01/”+calendar.get(Calendar.YEAR);
}
calendar.setTime(sdf.parse(currentQuarterBeginDate));
calendar.add(Calendar.MONTH, 3*-1);
fromDt = sdf.format(calendar.getTime());
String formmatedQuarterBeginDate = sdf.format(calendar.getTime());
calendar.setTime(new java.util.Date(formmatedQuarterBeginDate));
calendar.add(Calendar.MONTH, 3);
calendar.add(Calendar.DAY_OF_MONTH, -1);
toDt = sdf.format(calendar.getTime());
System.out.println(“Previous Quarter Begin Date : “+fromDt);
System.out.println(“Previous Quarter End Date : “+toDt);

Prints the following Result :
Previous Quarter Begin Date : 01/01/2007
Previous Quarter End Date : 03/31/2007

Java – Find previous Date for a given date:
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.applyPattern(“MM/dd/yyyy”);
Calendar calendar = Calendar.getInstance();
Date processDate = sdf.parse(“4/10/2007″);
calendar.setTime(processDate);
calendar.add(Calendar.DAY_OF_MONTH, -1);
String previousDate = sdf.format(calendar.getTime());
System.out.println(“Previous Date is :”+previousDate);
Prints the following Result :
Previous Date is :04/09/2007

Java – Find previous Sunday for a given date:
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.applyPattern(“MM/dd/yyyy”);
Calendar calendar = Calendar.getInstance();
Date processDate = sdf.parse(“4/24/2007″);
calendar.setTime(processDate);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
calendar.add(Calendar.DAY_OF_MONTH,-1*(dayOfWeek-1));
calendar.setTime(calendar.getTime());
String endDt = sdf.format(calendar.getTime());
System.out.println(“Previous Sunday is :”+endDt);
Prints the following Result :
Previous Sunday is :04/22/2007

Enjoy!!!!

Add Interactive Map to your website using Google Maps API

Interactive maps has become an inevitable part of modern web applications and introduction of Google Map API has made it even easier to integrate an interactive map to your website. Areas on which interactive maps have proved itself are tourism related websites and service oriented websites. In this blog we will see how we can add an interactive map to your website using Google Map API and AJAX to process the response from the server.

The first step in integrating a map in your website is to request  a Google map API key. You can request  a Google Maps API key here. If you have URL for your website, you need to specify the URL while requesting key. If you are playing around with the API, you can very well request for http://localhost. If you are using a port number , you need to specify the port number also. For example http://localhost:8080. Once you get the key you can use the key for all subfolders of http://localhost.

This is Source of an HTML page that displays map of 1415 Elbridge Payne Rd,Chesterfield,MO 63017. You need to know the latitude and longitude of the address to display map in your web page. If you don’t know the latitude and longitude , there are many online services that provide services to get latitude and longitude of an address . Another way of implementing this is to use geoCoder provided by Google Map API to get the latitude and longitude by providing an address. We will come to this in a while.

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
  “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd“>
<html xmlns=”http://www.w3.org/1999/xhtml“>
  <head>
    <meta http-equiv=”content-type” content=”text/html;
                                     charset=utf-8″/>
    <title>Google Maps JavaScript API Example</title>
    <script  src=”http://maps.google.com/maps?file=api&v=2&key=
         ABQIAAAAR7yXyXxWnmYNsvbV6JWv5hT2yXp_ZAY8_ufC3CFXhHIE1NvwkxTvGi-   GhomVbgkbC6tv2C8JocyNEg”
      type=”text/javascript”></script>
    <script type=”text/javascript”>
    //<![CDATA[
    function load() {
      if (GBrowserIsCompatible()) {
     var map = new GMap2(document.getElementById("map"));
     map.setCenter(new GLatLng(38.65, -90.56), 8);
     map.addControl(new GSmallMapControl());
     map.addControl(new GOverviewMapControl());
     var point = new GLatLng(38.65, -90.56);
     marker = new GMarker(point);
     map.addOverlay(marker)
     GEvent.addListener(marker, "click", function() {
     marker.openInfoWindowHtml("<p>Unidev: Custom Software and Applicaton Development</p>”});
  }

    }
    //]]>
    </script>
  </head>
  <body onload=”load()”>
    <div id=”map” style=”width: 800px; height: 600px”></div>
  </body>
</html>

Map of Unidev

Class GMap2 represents a map instance and you can create as many instances as you want. addcontrol() method can be used to add controls to your map.GSmallMapControl() enables Zoom functionality. Event handling is implemented using GEvent.addListener() method. GMarker class marks a point of interest in your map.OpenInfoWindowHtml() method opens an informational window on ‘OnClick’ event. Place holder for map in this example is a <div> tag with id ‘map’.
Adding an Interactive Map to your web application:
This example shows how to add a user driven map in your web application. First step in creating an interactive map is to have a form in your web page where users can enter the address and description of their point of interest.
Given below is the bean and DAO implementation class.
public class GMarker
{
    private Long id;
    private String address;
    private String description;
// Need to have setters , getters and a costructor that takes all the varaibales)
}

We have another Location object that stores data entered by users. We read data from the Location table(which is populated by the data submitted by users) and create Gmarker object. This DAO implementation is not Table  driven , we read hardcoded data from a Map. In realworld DAO Implmentation would be Table driven.

DAO implementation:
public class PickDAOImpl implements PickDAO
{
private static final Map myPicks = new HashMap();
    static {
    myPicks.put(“1″,new GMarker(new Long(1),”1415 Elbridge Payne  Rd,Chesterfield,MO,63017″,”Unidev: Custom Software and Application Development”));
    myPicks.put(“2″,new GMarker(new Long(2),”1400 Douglas Street,Omaha,NE”,”Union Pacific Railroad”));
    }
 public List findAllAsMarkers() {
        List results = new ArrayList();
        Collection allLocations = myPicks.values();
        Iterator locIt = allLocations.iterator();
        GMarker location = null;
        while(locIt.hasNext()){
            location = (GMarker)locIt.next();
            results.add(new GMarker(location.getId(),
                    location.getAddress(),
                    location.getDescription()));
        }
   return results;
    }
}

Heart of Ajax is XMLHttpRequest object and however in this example we are using Google’s version of XMLHttpRequest object, that is GXmlHttp class. Ajax makes the request to the servlet, which would be processed by the servlet  and Servlet returned XML Document object can be processed by Javascript DOM functions. We are using Xsteam implementation provided by http://xstream.codehaus.org/ to generate XML document from Java object. Other open source libraries like Apache and Castor can also be used to generate XML document from Java objects.

XML document generated by the servlet for the request to get all user submitted addresses in the database would look like this.
<list>
  <marker>
    <id>2</id>
    <address>1400 Douglas Street,Omaha,NE</address>
    <description>Union Pacific Railroad</description>
  </marker>
  <marker>
    <id>1</id>
    <address>1415 Elbridge Payne Rd,Chesterfield,MO,63017</address>
    <description>Unidev: Custom Software and Application Development</description>
  </marker>
</list>

Given below is the Servlet that generated the above XML document.

public class MyPickServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet
{
    private PickDAO pickDAO;
    public PickDAO getPickDAO()
    {
        if (pickDAO == null) {pickDAO = new PickDAOImpl();
        }
       return pickDAO;
    }

    public void setPickDAO(PickDAO pickDAO)
    {
        this.pickDAO = pickDAO;
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws  ServletException, IOException {
        String method=request.getParameter(“method”);
        XStream xstream = new XStream();
        xstream.alias(“marker”, GMarker.class);
        response.setContentType(“application/xml”);
 if (method.equals(“findAll”)) {
            List locations = getPickDAO().findAllAsMarkers();
            String xml = xstream.toXML(locations);
            response.getWriter().write(xml);
        }
}

The response generated by the Servlet is processed by javascript DOM functions. Given below is the HML page, that makes AJAX request to Server and process the response from the Server. The Javascript code has comments added to explain the important points.

<html>
 <head>
 <meta http-equiv=”content-type” content=”text/html; charset=utf-8″ />
  <title>Google Maps JavaScript API Example</title>
  <script
       src=”http://maps.google.com/maps?file=api&v=2&key=
                     ABQIAAAAR7yXyXxWnmYNsvbV6JWv5hT2yXp_ZAY8_ufC3CFXhHIE1NvwkxTvGi-GhomVbgkbC6tv2C8JocyNEg”
       type=”text/javascript”></script>
  <script type=”text/javascript”>
     var map = null;
         var gmarkers = [];
         var i =0;
         var address = null;
         var geocoder = null;
        var id = null;
      // method called on onLoad event
    function loadUserPicks() {
   map = new GMap2(document.getElementById(“map”));
         var request = GXmlHttp.create();
         request.open(“GET”, “myPick?method=findAll”, true);
         request.onreadystatechange = getCallbackFunction(request, processGmapData);
         request.send(null);
     }
    function getCallbackFunction(req, processData) {
          // Return an function that listens to the
          // XMLHttpRequest instance
              return function () {
         // If the request status is “complete”
           if (req.readyState == 4) {
             if (req.status == 200) {
                  // Got a response
                  // Pass the XML payload of the response to the
                  // handler function
          processData(req.responseXML);
 } else {
          // An HTTP problem has occurred
          alert(“HTTP error: “+req.status);
        }
      }
    }
  }
  var locMarkers = null;

function processGmapData(xmlDoc){
             // obtain the array of markers and loop through it
             locMarkers = xmlDoc.documentElement.getElementsByTagName(“marker”);
             displayPicks();
     }

    function displayPicks() {
      map.clearOverlays();
            for (var i = 0; i < locMarkers.length; i++) {
              // obtain the attribues of each marker
              var label = locMarkers[i].getElementsByTagName(“address”)[0].firstChild.nodeValue;
              address = label;
              map = new GMap2(document.getElementById(“map”));

            // Create new geocoding client object
          geocoder = new GClientGeocoder();

           // Retrieve location information for the address, pass it to addToMap()
           geocoder.getLocations(address, addToMap); }
     }
    function addToMap(response)
       {
            // Retrieve the object
           var place = response.Placemark[0];
           // Retrieve the latitude and longitude
           var point = new GLatLng(place.Point.coordinates[1],
             place.Point.coordinates[0]);
          // Center the map on this point
          map.setCenter(new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]),4);
          map.addControl(new GSmallMapControl());
          map.addControl(new GOverviewMapControl());
         var marker = new GMarker(point);
        GEvent.addListener(marker,”mouseover”, function() {
              marker.openInfoWindowHtml(place.address + ‘<br>’+'<b>Country:</b>’
              +place.AddressDetails.Country.CountryNameCode);
          });

           gmarkers[i] = marker;
           i++;
           map.addOverlay(marker);
  }
 </script>
  <form name=”mypickform” action=”/myPick” method=”get”>
  <body onload=”loadUserPicks()”>
  <div id=”map” style=”width: 800px; height: 600px”></div>
  </body>
  </form>
 </html>

Map

Enjoy……

Clob Processing in Java, Spring and Hibernate

This blog  shows how to save CLOB to a Relational Database using Java, Spring and Hibernate.This example is implemented using two classes from Spring Framework

1)OracleLobHandler

2)NativeJdbcExtractor (This example has been tested in Weblogic J2ee Container and this example uses WebLogicNativeJdbcExtractor.)

Spring Framework applicationContext.xml configuration:

<bean id=”mySessionFactory class=”org.springframework.orm.hibernate3.LocalSessionFactoryBean”>

<property name=”dataSource” ref=”myDataSource” />

<property name=”lobHandler” ref=”lobHandler” />

<property name=”mappingResources”>

<list> <value>com/clob/hibernate/lohHandler.hbm.xml</value>

</list></property> <property name=”hibernateProperties”><props><prop key=”hibernate.dialect”>org.hibernate.dialect.OracleDialect </prop>

<prop key=”hibernate.show_sql”>true</prop>

<prop key=”hibernate.connection.autocommit”>false</prop>

<prop key=”hibernate.connection.release_mode”>auto </prop>

<prop key=”hibernate.jdbc.use_streams_for_binary”>true </prop>

<prop key=”SetBigStringTryClob”>true</prop>

</props>

</property>

</bean>

<bean id=”lobHandler” class=”org.springframework.jdbc.support.lob.OracleLobHandler”

lazy-init=”true”>

<property name=”nativeJdbcExtractor”>

<beanclass=”org.springframework.jdbc.support.nativejdbc.WebLogicNativeJdbcExtractor” />

</property>

</bean>

Code block from lobHandler.hbm.xml:

<property name=”extdXml” type=”java.sql.Clob”>

<column name=”DTL_XML” /> </property>

Java bean class:

public class lohHandler implements java.io.Serializable {

 private Clob extdXml;

public void setExtdXml(Clob extdXml) { this.extdXml = extdXml;} public Clob getExtdXml() { return this.extdXml;}

public void setClobContent( String sourceStream )throws IOException{

setExtdXml( Hibernate.createClob( sourceStream ) );

}} Spring Framework Controller class:Upload the xml file and store contents of xml file in a String.Instantiate the bean.

lohHandler lHandler = new lohHandler ();

lHandler.setClobContent(xmlString);

setClobContent() method inturn calls Hibernate.createClob() method, which creates a CLOB out of a String. Now we are ready to save the lHandler bean object in a Hibernate Session.