Picking Dates in Struts 2 and JQGrid

I have spent sometime analysing the power of Struts 2 and JQGrid. In a time when so many frameworks are out there, so many projects, some of which perform code generation, the question is can Struts 2 still have a place in the new world, the new era that has seen the rise of web technologies with mouth watering graphics and tantalizing visual effects?

I am happy to say that yes it can. Within the JQGrid Struts 2 is a framework that has the capability to make it through and past 2010 into the second decade of this new century that has dawned upon us.

Today I write about dates and date picking in the Struts 2 JQGrid plugin. The reason being there seems to be, to my knowledge, no clear explanation on this. In my next post I will give a full tutorial on the use of JQGrid and more comprehensive coverage on this wonderful plugin.

We want to be able to have a date picker in the Add Record screen. In the picture below confirmBy is a date field and when we click on it:

Also when we edit a record, on the Edit Record screen, we click on the date field we have:

The settings for this are as follows. First in the sjg:GridColumn we have:

Where the datePick function will be:

There we are. We have added date picking functionality in the Add Record screen and the Edit Record screen.

 

Advertisements
Posted in Computers and Internet, Java programming, JavaScript, Uncategorized | Leave a comment

Spring ROO and an Idea

 I have being playing around with Spring ROO. It is a project with great potential and the facility to integrate seamlessly with maven is an added advantage.

There are many tutorials on “An enterprise Java Application in 10 minutes with ROO”, this is not a tutorial but rather looks at enhancing ROO for use in projects The reader who is unfamiliar with Spring ROO is advised to look at .http://www.springsource.org/roo for an introduction to Spring ROO.

How one draw back that seems to plague Spring ROO is the lack of sorting and filtering functionality on the web frontend lists. In other words how do we sort tabular data? This question  is obviously an important one and vital to many web applications.

An answer that we could employ is displaytag a little known but help tag library that could assist us to sort and export tabular data to excel and csv files.

In the generated list.jspx we have:

 

If we had to use display tag instead we would have :

Now we could actually make changes to the code generation and the annotations to alter and create our default JSPs to use the display tag. However for this exercise we can assume that we did it by hand and produced the above.

The result when running the application with mvn tomcat:run we have in our browser( http://127.0.0.1:8080/truckmanagement/trucks?page=1&size=10 ):

We can even extend the above to use displaytags exporting abilities to export to excel:

Posted in Uncategorized | 4 Comments

Digesting Struts 2 and Dojo

Digesting Struts 2 and Dojo

I was playing around with Struts 2 and Ajax mainly Dojo. Now how would one wire a struts action to return Dojo – JavaScript object? We will examine this below and setup a sample app that will use Struts and Dojo. We offer this as an alternative to JSON. The advantage of this over JSON is that an exist Struts 2 application could still generate JavaScript Objects without interfering with the Java classes. So where as when JSON is used your program must return a JSON object here your program can return normal data to pages and from these JavaScript objects can be constructed and used.

We will load a user’s information on selection of the user and dynamically append the user’s details.

 

Once the user is selected we will have his information dynamically appended to the screen as below:

 

The way this application will function is that struts will on success return a result to a JSP that will then dynamically have the XML created. The dojo.io.bind will then read in this XML and generate a JavaScript object with which we can use to update the page. We will start by creating the project for the application in Eclipse (Similar process for Netbeans)

 

The classes look like:

LoadUser.java

package struts2dojoexample.action;

 

import java.io.IOException;

 

import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import org.apache.struts2.ServletActionContext;

import org.apache.struts2.interceptor.ServletRequestAware;

import org.apache.struts2.interceptor.ServletResponseAware;

 

import struts2dojoexample.pojo.User;

 

import com.opensymphony.xwork2.ActionSupport;

 

public class LoadUserAction extends ActionSupport implements ServletRequestAware,

ServletResponseAware {

 

private String user;

private String username;

private String password;

private HttpServletRequest request;

private HttpServletResponse response;

 

public String execute() {

User user1 = new User();

user1.setUsername(“Gabriel”);

user1.setSurname(“Campbell”);

user1.setEmailAddress(“gjcbell@hotmail.com”);

user1.setStreetAddress(“On Earth”);

 

// Put the DTO in request so we can use it to render XML in the JSP.

getServletRequest().setAttribute(“user”, user1);

return SUCCESS;

}

 

public void setUsername(String username) {

this.username = username;

}

 

public String getUsername() {

return username;

}

 

public void setPassword(String password) {

this.password = password;

}

 

public String getPassword() {

return password;

}

 

public void setUser(String user) {

this.user = user;

}

 

public String getUser() {

return user;

}

 

 

public void setServletRequest(HttpServletRequest request){

this.request = request;

}

 

public HttpServletRequest getServletRequest(){

return request;

}

 

public void setServletResponse(HttpServletResponse response){

this.response = response;

}

 

public HttpServletResponse getServletResponse(){

return response;

}

 

}

 

 

As you can see in Struts 2 you can implement ServletRequestAware and ServletResponseAware

When these are implemented we now have access to our session.

User.java

package struts2dojoexample.pojo;

 

import java.lang.reflect.Field;

 

public class User {

 

private String username;

private String password;

private String surname;

private String emailAddress;

private String streetAddress;

 

public void setUsername(String username) {

this.username = username;

}

 

public String getUsername() {

return username;

}

 

public void setPassword(String password) {

this.password = password;

}

 

public String getPassword() {

return password;

}

 

public void setSurname(String surname) {

this.surname = surname;

}

 

public String getSurname() {

return surname;

}

 

public void setEmailAddress(String emailAddress) {

this.emailAddress = emailAddress;

}

 

public String getEmailAddress() {

return emailAddress;

}

 

public void setStreetAddress(String streetAddress) {

this.streetAddress = streetAddress;

}

 

public String getStreetAddress() {

return streetAddress;

}

 

public String getAsXML(){

StringBuffer sb = new StringBuffer(512);

sb.append(“<user username=\”” + username + “\” “);

sb.append(“surname=\”” + surname + “\” “);

sb.append(“emailAddress=\”” + emailAddress + “\” “);

sb.append(“streetAddress=\”” + streetAddress + “\”>\n”);

sb.append(“</user>\n”);

return sb.toString();

}

/**

* Overriden toString method.

*

* @return A reflexivelybuilt string representation of this bean.

*/

public String toString() {

 

String str = null;

StringBuffer sb = new StringBuffer(1000);

sb.append(“[“ + super.toString() + “]={“);

boolean firstPropertyDisplayed = false;

try {

Field[] fields = this.getClass().getDeclaredFields();

for (int i = 0; i < fields.length; i++) {

if (firstPropertyDisplayed) {

sb.append(“, “);

} else {

firstPropertyDisplayed = true;

}

sb.append(fields[i].getName() + “=” + fields[i].get(this));

}

sb.append(“}”);

str = sb.toString().trim();

} catch (IllegalAccessException iae) {

iae.printStackTrace();

}

return str;

 

} // End toString().

}

 

Next we have the web.xml:

 

 

 

 

<?xml version=“1.0” encoding=“UTF-8”?>

 

<web-app version=“2.4” xmlns=http://java.sun.com/xml/ns/j2ee&#8221; xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance&#8221; xsi:schemaLocation=http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd&#8221;>

 

<display-name>Struts2Dojo</display-name>

<filter>

<filter-name>struts2</filter-name>

<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>

<init-param>

<param-name>actionPackages</param-name>

<param-value>struts2dojoexample</param-value>

</init-param>

</filter>

<filter-mapping>

<filter-name>struts2</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

<!– Session timeout config. –>

<session-config>

<session-timeout>30</session-timeout>

</session-config>

 

<!– Welcome file config. –>

<welcome-file-list>

<welcome-file>/LoadUser.jsp</welcome-file>

</welcome-file-list>

</web-app>

 

The struts.xml

<?xml version=“1.0” encoding=“UTF-8” ?>

<!DOCTYPE struts PUBLIC

“-//Apache Software Foundation//DTD Struts Configuration 2.0//EN”

http://struts.apache.org/dtds/struts-2.0.dtd&#8221;>

 

<struts>

 

<constant name=“struts.devMode” value=“true” />

 

<package name=“default” namespace=“/” extends=“struts-default”>

<action name=“LoadUserAction” class=“struts2dojoexample.action.LoadUserAction”>

<result name=“success”>/User.jsp</result>

</action>

</package>

</struts>

 

The javascript files are list below:

 

We have the ControlEvents.js this is where we control the events the user creates like the select list drop down menu.

Dojo.js is the dojo toolkit downloadable from http://www.dojotoolkit.org/

User.js is the script file container the user object in JavaScript. In the ControlEvents.js we use the JSDigester that is provided by the JavaWebparts tags. This enables us to generated JavaScript objects.

ControlEvents.js looks like this:

 

var user = null;

var aconsole = null;

// This function is called when the User dropdown selection changes.

function loadUser() {

// If an operation is in progress, usually involving the server, don’t do it.

//if (processing) { return false; }

// Get name of selected collection.

var username =document.getElementById(“userslist”).value;

// Ignore the first item, our “dummy” collection.

if (username == “none”) {

return false;

}

// Make AJAX call.

dojo.io.bind({

url: “LoadUserAction.action”,

content: {user: username},

error: function(type, errObj) { alert(“Error”); },

load: function(type, data, evt) {

// Now that we have received back the XML describing the collection,

// we’ll use JSDigester to parse it.

var jsDigester = new JSDigester();

jsDigester.addObjectCreate(“user”, “User”);

jsDigester.addSetProperties(“user”);

user = jsDigester.parse(data);

aconsole=document.getElementById(“console”);

if (aconsole != null ) {

removeAllChildren ( aconsole );

}

var div = document.createElement(“p”);

var txt=document.createTextNode(“Name: “ +user.username );

div.appendChild ( txt );

txt=document.createTextNode(“Surname: “ +user.surname );

var div1 = document.createElement(“p”);

div1.appendChild ( txt );

txt=document.createTextNode(“Email Address: “ +user.emailAddress );

var div2 = document.createElement(“p”);

div2.appendChild ( txt );

txt=document.createTextNode(“Street Address: “ +user.streetAddress );

var div3 = document.createElement(“p”);

div3.appendChild ( txt );

aconsole.appendChild(div);

aconsole.appendChild(div1);

aconsole.appendChild(div2);

aconsole.appendChild(div3);

},

mimetype: “text/plain”,

transport: “XMLHTTPTransport”

});

}

 

function removeAllChildren( node ){

var childCount = node.childNodes.length;

for ( var count = 1; count <= childCount; count++) {

node.removeChild ( node.childNodes[0] );

}

}

 

User.js :

// User object.

function User() {

this.username = null;

this.surname = null;

this.emailAddress = null;

this.streetAddress = null;

}

User.prototype.setUsername = function(inName) {

this.username = inName;

}

User.prototype.getUsername = function() {

return this.username;

}

User.prototype.setSurname = function(inSurname) {

this.surname = inSurname;

}

User.prototype.getSurname = function() {

return this.surname;

}

User.prototype.setEmailAddress = function(inEmailAddress) {

this.emailAddress = inEmailAddress;

}

User.prototype.getEmailAddress = function() {

return this.emailAddress;

}

User.prototype.setStreetAddress = function(inStreetAddress) {

this.streetAddress = inStreetAddress;

}

User.prototype.getStreetAddress = function() {

return this.streetAddress;

}

User.prototype.toString = function() {

return “User=[username=” + this.username +

“,surname=” + this.surname +

“,emailAddress=” + this.emailAddress + “,streetAddress=” + this.streetAddress + “]”;

}

 

The libraries:

 

 

There some additional libraries for expansion of this application like the MySQL driver for Database connectivity to MySQL.

There you are it runs. So we managed to dynamically update a page and translate our Java in to JavaScript. This example could be extended and enhanced to embrace the vast functionality of the Dojo Toolkit.

Cheers,

Gabriel

 

 

 

 

 

Posted in Computers and Internet, Java programming, JavaScript | Leave a comment

Hello world!

Welcome to WordPress.com. This is your first post. Edit or delete it and start blogging!

Posted in Uncategorized | 1 Comment

Dating, Where clauses and Hibernate

I recently ran into an interesting problem involving hibernate and dates across different database systems mainly Microsoft SQL 2008 and IBM Informix.

It appears that in HQL queries you can use Informix’s today for obtaining the current date and time:

query = session.createQuery();

String whereClause = "from myTable where myDateColumn > today -10";

This query finds the today 10 days from the current time.

When we run the query as below:

List<MyTable> myTableResults = query.list();

THis executes successfully in IBM Informix but in MSSQL we get the following error:

column today not found

So what do we do now? it appears that NOW() does not work.

Looking through various information and issues on the internet and hibernate tutorial and forums I found that hibernate can support certain functions of a specific database. This ties in with the hibernate dialect and JDBC driver.

I found that GETDATE() works within the where clause. So updating the above to:

String whereClause = "from myTable where myDateColumn > GETDATE() -10";

This worked well. So this raises more questions. How can we in general see which functions the RDMS provides that hibernate will support in its HQL queries – the where clause?

It should be noted that in the select part of the query we have more freedom. As dates can be retrieved.

Also it should be noticed that MS SQL has a newer driver sqljdbc4.jar and sqljdbc.jar. The difference in these two is quite big when we consider dates. For example SQL 2005 had fewer date types then SQl 2008. So this leads to problems when using the older driver(sqljdbc.jar) on SQL 2008.

 

Another important insight is in the Dialect class there exists the method Dialect.getCurrentTimestampSQLFunctionName() which can give us the database-specific SQL function for retrieving the current timestamp.

Also we cannot use Java’s

new Date() in the where clause part of the query as this does not always work. The format the date will be in might not translate well into a string. We could try parameters in queries using AbstractQueryImpl.setParameter(String name, Object val).

However a problem could arise when using Java’s new Date() in as a paramter in a query as opposed to using a database function, this problem would be that time from Java would be based on the application as opposed to the database server itself. So if the two are at different locations and setup differently we could have problems.

Hence we can make our application cater for different types of RDMS systems based on the type and hence use various functions to aid development.

Hence when dealing with date types one has to be cautious specially if developing on an open source RDMS and then using a commerial RDMS. This saves on licencing but when deploy issues like dates can give problems!

Posted in Computers and Internet | Leave a comment

Nice and Naughty Transactions in Hibernate and Spring

I came across a very interesting fact about Spring transaction management.

 

Spring provides us with two ways of handling transaction

1) Using proxies,

2) Using DI through the getTemplate() method.

 

Now what happens when we consider 1) we mean:

Declaring in an XML file the transactionManager and transactionTemplate bean:

 

<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" singleton="true">

            <property name="sessionFactory">

                  <ref bean="sessionFactory" />

            </property>

      </bean>

      <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate" singleton="false">

            <property name="transactionManager">

                  <ref bean="transactionManager" />

            </property>

      </bean>

 

Then we use proxies and provide:

 

<bean id="myTableManagerTx" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" singleton="true" lazy-init="true">

            <property name="transactionManager">

                  <ref bean="transactionManager"/>

            </property>

            <property name="target">

                  <ref bean="myTableManagerImpl"/>

            </property>

            <property name="transactionAttributes">

                  <props>

 

     

 

            <prop key=" *">PROPAGATION_NOT_SUPPORTED,readOnly</prop>

 

                  </props>

            </property>

            <property name="preInterceptors">

                  <list>

                        <ref bean="callMonitor"/>

                  </list>

            </property>

      </bean>

 

With the use of interceptors we can now use doInHibernate() and have transaction support without any extra coding:

 

protected Object updateObject(final Context ctx, final Object o) {

            return getHibernateTemplate().execute(new HibernateCallback() {

 

                  public Object doInHibernate(Session session) throws HibernateException, SQLException {

                        return update(ctx, session, o);

                  }

            });

      }

 

However we can use alternative 2)

 

            try {

                  TransactionTemplate transactionTemplate = SpringFactory.getTransactionTemplate( TransactionDefinition.ISOLATION_READ_COMMITTED, TransactionDefinition.PROPAGATION_REQUIRED, false );

                  return ( List )transactionTemplate.execute( new TransactionCallback() {

 

                        public Object doInTransaction( TransactionStatus transactionStatus ) {

                              return getMyTableDAO().find( ctx, myId );

                        }

                  } );

            } catch( Exception e ) {

                  log.error( e.getMessage(), e );                

            }

 

Here we are programmatically creating a transaction based on Spring’s DI.

 

What happens if we use both together? That is 1) and 2) in an application we could have errors like:

 

Session cannot be closed!

 

This is because we are using proxies for transactions and also programmatically controlling transactions. If our TransactionDefinition fields : PROPAGATION_REQUIRED, PROPAGATION_NEVER, PROPAGATION_NOT_SUPPORTED, PROPAGATION_REQUIRES_NEW etc are not adjusted and used correctly we could have problems and errors with sessions being closed prematurely and incorrectly controlled. Also the HibernateTemplate controls the sessions for us. As stated in the Spring documentation:

The central method is execute, supporting Hibernate access code implementing the HibernateCallback interface. It provides Hibernate Session handling such that neither the HibernateCallback implementation nor the calling code needs to explicitly care about retrieving/closing Hibernate Sessions, or handling Session lifecycle exceptions. For typical single step actions, there are various convenience methods (find, load, saveOrUpdate, delete).

 This can lead to sessions not being closed properly and resources not been freed and hence lead to memory leaks(Which I have experienced!).

 

Final word of advice is: carefully watch your transactions!

  

Posted in Computers and Internet | Leave a comment

JavaAssist and CGLIB Hibernate and Spring

I recently came across some legacy code that brought to mind some interesting aspects of Spring and Hibernate. This involves the code generation libaray CGLIB.

Javassist is a class library for editing bytecodes in Java; it enables Java programs to define a new class at runtime and to modify a class file when the JVM loads it.

Cglib It is used to extend JAVA classes and implements interfaces at runtime.

Hibernate v 3.2 and below utilize CGLIB to generate proxies for the database connections. Hibernate v3.3 and above use Javassist by default.

The way CGLIB (Older version 2.1.1 this should be fixed in new versions) generates proxies causes the memory to contain a lot of used but referenced objects hence increasing the size of the heap. So much so that the heap will grow until we get a Out Of Memory Error. This happens just before a proxy is instantiated when using the CGLIBLazyInitializer.getProxy().  

Please refer to http://opensource.atlassian.com/projects/hibernate/browse/HHH-2481 for more information. First and formost Spring managed Hibernate sessions and transactions can be very powerful and have advantages such as cleaning up of sessions.  However combining Spring with Hibernate v3.2 and below leads to memory mismanagement due to the CGLIB which has some internal issues.

If you are however stuck to modifying or maintaining applications that are utilizing CGLIB you could add the following code snipplet to improve performance and fix the above issue:

cfg.setListeners("load", new LoadEventListener [] {new DefaultLoadEventListener(), new LoadEventListener() {

            public void onLoad(LoadEvent event, LoadType loadType) throws HibernateException {

                Object obj = event.getResult();

                if (obj instanceof HibernateProxy) {

                    Enhancer.registerCallbacks(obj.getClass(),null);

                }

            }

        }});

 

The cfg variable is the configuration variable of hibernate.

In addition when upgrading to Hibernate v3.5 be aware that it implements strick checks on whether SQL queries are well formed.

Having implemented Hibernate v3.5 some of my memory issues were gone and the application was left in a stable state.

 

Posted in Computers and Internet | Leave a comment