Monday, January 28, 2008

Hibernate SQL Logging

If you use Hibernate (2.x or 3.x), then you most probably already know how to turn on/off the SQL logging (to System.out).

This post is to show how you can weak small settings for log4j to enable the logging rather in a application log file than System.out. Also included is nifty tip to get the values which were assigned to the the prepared statements that hibernate would have used for retrieval of data from database.


[PS: This is nothing new. I am just posting here so that I can remember and may be some other guys would benefit from it]

  1. Basic SQL debugging on and off

  2. <property name="show_sql">true</property>
  3. Moving your SQL queries to Log a file using log4j configuration. Just add following lines into you log4j.properties.
  4. # setup for HQL to log
    log4j.logger.net.sf.hibernate.SQL=DEBUG, consoleName
    log4j.additivity.org.hibernate.SQL=false
  5. Logging the parameters passed to the Prepared statement to log file using log4.properties file setting.

  6. # to read the values attached to Prepared statments of Hibernate
    log4j.logger.net.sf.hibernate.type=DEBUG, consoleName
NOTE: If you are using hibernate 3.x then just replace net.sf.hibernate with org.hibernate in above log4j.properties file settings
That's all for now!

Regards,
Vijay Dharap

Saturday, January 26, 2008

showModalDialog communication with parent window

As pointed out in the MSDN link for showModalDialog Modal Dialog created in IE by showModalDialog() command can send a return val back to calling window. This is a sample code as to how to send lot of information across in such case.

<html>
<head>
<script type="text/javascript">
function fnOpen(){
var sFeatures=fnSetValues();
var returnVal = window.showModalDialog("showModalDialog_target.htm", "",
"dialogHeight: 200px;");
alert(returnVal.amount);
}
</script>
</head>

<body>
Create Modal Dialog Box
<input type="button" value="Push To Create Modal Dialog" onclick="fnOpen()">
</body>
</html>

Then add following code to modal dialog page.

<html>
<head>
<script type="text/javascript">
// a Sample JS object definition (you can include it from external js also)
function PayoffData(){
this.amount=null;
this.vehicle=null;
this.dealType=null;
}
function window.onbeforeunload()
{
var payoffData = new PayoffData();
// sample hardcoding. you can read data from your modal dialog page
payoffData.amount=1200;
payoffData.vehicle='dodge ram';
payoffData.dealType='lease';
window.returnValue = payoffData;
}
</script>
<head>
<body>
<h1>this is ModalDialog.htm<h1>
</body>
</html>
Important things to note:
  • You can now have complete Javascript object sent to and fro between parent and modal dialog.
  • window.onbeforeunload was overridden. that means whether you use a custom close button inside your modal dialog or you use the close button in right top corner of the modal dialog, your data would always be sent back.
  • the parent window script gets blocked when we call window.showModalDialog. We just need to understand that if we have script block after this call, it would be executed only after the modal window closes. (Showing modal window is a synchronous event).
That's all for the day!

Friday, January 25, 2008

Testing With SyntaxHighligher

function PayoffData(){
this.amount=null;
this.vehicle=null;
this.dealType=null;
}
function window.onbeforeunload()
{
var payoffData = new PayoffData();
payoffData.amount=1200;
payoffData.vehicle='dodge ram';
payoffData.dealType='lease';
window.returnValue = payoffData;
}

Thursday, January 24, 2008

Wicket vs Struts : Head on Head

Mentioned below few of the prominant differences in Struts and Wicket framework

Feature

Struts

Wicket

Basic philosophy

Request-Response based MVC web application framework

Component based web application framework

Object orientation

Struts (even though has internally Object orientation) follows more procedure approach. Developers end up writing procedure codes in the actions.

Wicket follows a very strong object oriented component hierarchy similar to that of swing components

Presentation Layer Language

Needs JSP and at least a few decent taglibs (like jstl) for rending the view part

Wicket markup files are just pure HTML.

Separation of concerns

Presentation layer (being JSPs) is not possible for graphic designers to write independently.

Graphic designers can independently create the impressive presentation layer in pure (X)HTML.

Object Management

Struts is managed framework. [Developers do not have to create new instances of Action / Form etc. Struts provides developers the appropriate instances at the runtime based on xml configuration]

Wicket is unmanaged framework. [Developers would create needed component instances themselves]

Event and state management

In Struts, developer must handle each event fired on the screen. If there are 20 possible action happening on a page, developer would end up writing 20 action / if-else logic in single action class.

In Wicket, all the components know how to handle their own events. You would just need to add the components to Page class

Application Configuration

Struts need a complicated xml configuration file to initialize and maintain application configurration.

Wicket does not need any special configuration files. Application initialization is done by adding 4-6 lines in web.xml to declare a filter

Saturday, January 19, 2008

Ye Ol' STRUTies, Wake Up!! The new world is here!

There are more than 60 active web frameworks in the market! How many do you know??

If you ask me... I only know Struts 1.x framework pretty good. So good that I know where are its dark alleys, how to avoid them, how to venture into some of those alleys without getting seriously hurt.

We all have grown so much accustomed with Struts 1.x that we have now blindfolded ourselves from looking into anything new.. Something which would break away from traditional way of framing a web-application. Enter Wicket, and you are due for a surprise!

I am NOT going to tell you here how to work in Wicket. This post is NOT a tutorial for wicket. I would try to give that one soon as well.. But there are numerous tutorials on net.
This post is just raise your curiosity about this new framework. Here are few highlights about how wicket does things differently.

  1. Real separation of concerns

  2. In Wicket, the entire presentation work is done in plain-old HTML (!!! Yes boss. You can kiss goodbye to all jsp, jsf, jakarta taglib, jstl, custom taglib). Due to this, now you can really have one team working on presentation layer (the designers) and other team working on development of server side dynamic pages (java geeks).

  3. No JSPs

  4. Did you ever feel that you had to write soooo much of jsp code to achieve so little? Try wicket. Since you don't have to force yourself to write stuff in jsp which was really meant to be done in java, you would feel liberated! The productivity increase would be clearly visible to you. E.g. Remember when you wanted to display a dynamic HTML table, you had to create the soup in jsp files by using logic:iterate (or c:forEach) and all sorts of logic tags to check present of fields etc etc. This is supposed to be a java code but we were forced into writing cumbersome taglib code to avoid the scriptlet usage in jsp. With wicket. You just write your regular HTML table with a dummy data row and then let java do the trick of iterating over the collection, checking for nulls / empty, anything. Whatever you can do in java, you can do to get your HTML table generated. No limitations.

  5. AJAX

  6. Wicket has has built in support for ajax. If you want to extend the support, you can easily do so. Also Wicket can easily coexist with existing JS lib like prototype / Dojo.

  7. URL Mounting

  8. You can create bookmarkable "friendly" Urls with one line. [If the url is behind a security, it would be displayed after intercepting login screen]

  9. Unit Testing

  10. The new world Java development is all about Unit test driven Extreme Programming. Wicket component are completely testable by using EasyMock objects.

  11. Validators

  12. Rich and far-reaching validator framework. don't need to use commons-validator. Validation failure message can be easily shown back to user in feedback panel / or you can customize to show the field in error highlighted. You can also ajaxify the process of validation.

  13. Spring Integration

  14. Easy in making coexistance with Spring and Hibernate, if that is selling point for you.

  15. Compile time issue detection

  16. You can catch problems at compile time which are not possible with JSP. For example if in JSTL you were referring to a non-existent Javabean property, you may not know until the page renders.

  17. Consistent look and feel for the pages: Templates without jsp / tiles

  18. No need to have jsp:include or tiles to define the template for your portal page to achieve consistent look. Wicket gives two ways to handle this functionality. Using "markup inheritance" (add link) and panel (add link)

  19. Lighter app requirements.

  20. You do not need tools.jar anymore in classpath since there are no jsps! Neither you need jsp-api.jar from j2ee web-container.

  21. No jsp compilation for the first time.

  22. Pages are no longer slow the first time you access them because there is no more JSP compilation step

  23. Standards compliant

  24. Your pages are guaranteed to be XHTML compliant

  25. Active and helpful community

  26. Help is fast on mailing list.



If you think that wickets seems to be any worthy of your attention..
Here are quick links for you to explore further:

Credits and Thanks:
I would like to thank the authors of few internet posts who elicited many of the above points beautifully in their wicket posts.


Regards,
Vijay Dharap

Open Session in View Pattern for Hibrnate

We all face the common problem with Hibernate of LazyInitializationException.

This happens to any decent application which has hibernate related code separated out in DAO layer and lazy loading is been turned on.
What happens is
  1. You retrieve some object from database using hibernate session and pass it back to helper / service layer for further processing.
  2. Service layer start processing the bean that was passed to it. it tries to read some property etc. and then we hit the dreaded LazyInitializationException: Session is closed.
  3. What happened was, DAO got the object from the session and before passing on the object to service layer, the session was closed!
  4. Since the session is closed without initializing the proxies, when you try to access the object properties (or contained sub-objects) you would face the exception.
There is no "Real" solution to this issue. we can only come up with few strategies. one of the strategies that I liked is "Open Session in View" pattern.
"Open Session in View" basically means, you open the database session when you start servicing for your view; and keep the session open till you have fully rendered your view and then only close the hibernate session.

Simple way to implement this is to write a web-app filter which would intercept your request, open a db session. let you work on your request. anywhere (DAO / Service / Action) you work on the objects retrieved from database, proxies would still hold good. Once your view (jsp) is completely rendered, filter on its way of finishing the activity closes the session.

Another nice side effect of this pattern is now your DAO does not need to have boilerplate code to open / close the session. Just get the current session from a singleton instance of HibernateUtil.

More details on this pattern implementation for hibernate: Open Session in View
Looks really promising.

If you are using Spring, spring already has such filter written for you. : Open Session In View Filter

Caveats:
  • Above pattern would not hold good in 3 tier application (e.g. where EJBs decouple the web and service layer). thats because the session that you got initialized in web layer wont be available inside EJB Container.
  • Few people DO think that this pattern binds Presentation layer with Hibernate (Data Access implementation). As of now, I do not think that's the case. My thought process was driven by following discussion threads.
i. hibernate forum thread
ii. Raible design thread
Would be looking for making implementation of this one in my next project.

That's all till the next time.


--VJ

Monday, July 16, 2007

Migration from dojo 0.4x to dojo 0.9

If you are using dojo 0.4.x javascript library.. then ther is a news for you.. dojo 0.9 is out (only in beta yet :-( )
But 0.9 is a huge huge improvement over 0.4.x version
first and most important thing is the size... now dojo.js stands at around 48kb in stead of beastly 150kb of 0.4.3
They have also done a lot of reorg..
now the.. this has caused 0.9 to be incompatible with the existing html source based on 0.4 dojo.
If you plan to upgrade.. please visit this general info page
If you are using Any of the widgets : make sure to find out ur widget from here.. n read about it.. espl ContentPane and Dialog.. am sure many would be using these two...


These are few of things that i found out...
1. All the changes from general info page are must!
2. u also need to import dijit.js if you plan to use the widgets.
3, if particular attribute / method is removed.. better read the description as to how to get it similar work done.. many attributes are now controlled via css. so.. need to update your css.

Saturday, March 17, 2007

  1. Program to interfaces rather than to Concrete Objects.
  2. Favor Object Composition over class inheritance.
  3. Delgation can be a good addition to Composition to achieve good things from inheritance.... e.g. Composition wont have all method access which inheritance will have.. but what can be done is you can write encapsuling methods in composing class which refer to composed class' methods. this way you can achieve run time change of objects. e.g. window (being a rectangle) should have inherited from rectangle.. in stead.. it containts a referance to rectangle.. so any method that you would rather go to rectangle for imlementation would be called by Window on to internal referance of window. Also if we have defined the Rectangle as a shape.. then we can also replace rectangle ref with a circle ref at runtime..