Wednesday, December 12, 2007

Something is wrong between me and the design patterns book

About a year ago, I bought Head First Design Patterns, which is a really great book. I started reading it right away, and I was reading Head First Servlets and JSP together with it while I was on an assignment in Alexandria. Suddenly, something weird happened. I reached the chapter on the command design pattern, and then got back to Cairo to get stuck in crisis mode for two months, which didn't leave much reading time for me. I lent the book to a friend of mine, and kept the servlets & jsp book to read in my free time.

After the crisis mode I had a knee operation to regenerate my torn ACL, had a month sick leave, and went to visit my family in Abu Dhabi, but without the book. Went back to Cairo after that month to get an assignment in Dubai, and I got the book this time, only to leave it on the shelf until I study for the SCWCD certificate from the servlets & jsp book.

When I had time to read it, I ignored it for a while to read The Jesus Papers, which I loved by the way. Finally, I had a chance to start reading the design patterns book again. I revised what I had already read a very long time ago, and again reached the command pattern chapter, and guess what?! I had to travel between Dubai and Abu Dhabi twice a week, since my wife and kid were in Abu Dhabi with my parents, and I was in Dubai for work. Of course this didn't leave me any reading time. I went back to Cairo a couple of weeks ago for ten days, where I didn't even have time to sleep. I'm back in Dubai, and I have the book with me, and I hope that I would be able to start reading it again. Wish me luck.

Monday, December 3, 2007

Netbeans 6 is finally here

Finally, NetBeans 6 is released. It has some really great features like profiling and support for ruby. Also their Swing GUI builder (formerly known as Matisse) is really great, and it now supports Beans Binding and Swing Application Framework. The only thing I don't like about the use of the GUI builder is that it doesn't allow you to edit the code it generates yourself, which is really annoying for hardcore developers. Overall, NetBeans is really great, and it really excels in some great areas. For the full feature list, please check this link.

Tuesday, November 20, 2007

Spring 2.5 is out

Spring 2.5 is out, and it introduces several new exciting features. One of the most exciting features in the new version is the java configuration, and automatic discovery of spring beans. Well, since the beginning of the Spring framework, wiring components to each other and configuring which class will be injected where was done only using XML. Yes, the people behind spring always said that any format can be used to do the configuration, but you have to write your own classes to implement the format you are going to use. Hence, there was nothing but XML until today.

As of now, you can use the auto-wiring features provided by the new version of spring to put the wiring configurations as annotations in your java code. You will still be using XML, but the amount of XML you need to write will be reduced significantly. Mark Fisher wrote a great article on InfoQ titled What's New in Spring 2.5: Part 1. Looking forward for part 2.

Saturday, November 17, 2007

Politics in Software Development

Politics is present in every aspect of our life, whether we realize it or not. It's present in the way you treat your family, your in-laws, and your coworker. It's even present in software development.

Ever wonder why Microsoft made Windows Mail in Vista not able to have Hotmail (now Windows Live Hotmail) accounts (unlike Outlook Express), and then months later they release Windows Live Mail which has this feature? Haven't you ever thought why when you want to download the new version of MSN Messenger (now Windows Live Messenger), you have to download an installer which has the options of downloading several other new Windows Live products that you never heard of (Mail, Writer, Photo Sharing, etc)?

Why does Microsoft's Windows Live Family Safety require that each and every member of your household should have a windows live ID so that he/she can access the internet? You say marketing? I say marketing falls under the umbrella of politics.

If the above examples don't strongly show clearly how company politics affect software development, the following ones will certainly do so.

Sun's business is mainly hardware, servers to be specific. Sun is also the company that maintains java. Now java is supposed to be platform independent, and we (java developers) claim that it runs on each and every availabal platform, right? WRONG! Sun creates JDKs and JREs for Windows, Linux and Solaris only, meaning that if you have an HP or an IBM server, you will not be able to get Sun's JVM. HP and IBM develop their own JVMs, but of course the available Java version on those machines is always behind that of Sun. Currently, HP and IBM have JVMs that run java 5, which is more than three years old.

Sun simply won't release versions of java for AIX or HP-UX since it will be releasing it for competitors in the hardware business. If it did, enterprises that have java applications and need to use the latest features may go to Sun's competitors. Sun releases versions for Windows to stop Microsoft from dominating the software development market, and if this is done, the market share of dot net will increase while that of java will decrease, and since dot net doesn't work on anything other than Windows, Sun will be losing a large part of the hardware market for windows based servers.

Sun also open sourced it's star office suite to create openoffice.org, and they open sourced Solaris, and made it compatible with desktop and laptop hardware. Why? To go another step in stopping Microsoft Windows from dominating the desktop market, so that it would slow down the growth of the dot net community, so that software in the market would be runnable on UNIX and not just Windows, so that it would increase it's the possibility of people going for Sun servers.

I believe that Sun's war with Microsoft could simply be over (or at least won't be as strong) if Microsoft made dot net platform independent, but Microsoft will never go for such a move. Microsoft wants to dominate the desktop environment with Windows, and it's very strong competition from Apple and Linux. Microsoft is using the dot net technology, with their fabulous IDE to market Windows. If suddenly dot net applications ran on Linux, for example, Microsoft may lose a huge market share.

I think that projects like WINE must make Microsoft live in fear. Maybe that's why Microsoft made a lot of changes to Vista that made a lot of programs not compatible with it. What had happened is that the software vendors made their software compatible with Vista, and everything went back to normal, except that projects like WINE and REACTOS went one step behind.

I believe that a lot of changes that were introduced to Vista were just to make it incompatible with such projects (such as changing "Documents and Settings" to "Users" and a lot of folders under the user folder like "Local Settings" for example to "AppData\Local" or something like that, and a countless more changes). I believe that such changes have no meaning other that what I assumed earlier.

Now let's go back to Sun again. Sun is THE supporter for Netbeans, which is a great IDE by the way. On the other side of the table, we have the more popular Eclipse, and guess what, IBM led the Eclipse Consortium (and it's the one that created Eclipse). Now someone would say that both are open source projects, and it doesn't make a difference to the companies what IDE developers use, right?. I again say WRONG!

IBM is in the software business, and being familiar with Eclipse makes you somewhat familiar with Websphere and Rational Tools, that are built over Eclipse. Being familiar with those IBM products may lead to you using the Websphere application server, and if you do, which operating system and hardware are the best for such a server? IBM hardware and AIX is the answer. What was Sun's response? Open source Sun application server and create project glassfish, hence you have a high end application server from Sun for free, and of course it supports the latest java technologies months (or even years) before other application servers (like servlets 2.5, JSP 2.1 and other JEE 5 features for example).

Back to Netbeans and Eclipse. Both IDEs allow developers to create custom plugins, but Eclipse recently (not very recently, actually about a year and a half ago) changed their framework to use Equinox, which is Eclipse's implementation of OSGi. OSGi is maintained by a large group of corporations, that include both IBM and Sun Microsystems, and both were founders of the OSGi Alliance. Having IBM and Sun working together is not something to be surprised from, because, as I mentioned before, it's all about politics.

Now Eclipse implemented OSGi by creating Equinox, what will Netbeans do? Well, as an active member of the Netbeans team told me once, they are waiting. They already have their pluggable framework. If they go to OSGi, they have to choose an implementation, and for sure they won't use Equinox. Even if they go for any other implementation (Apache Felix or Knopflerfish for example) or even create their own, they would still be switching to OSGi after eclipse did, hence Netbeans would be following Eclipse's steps (or as someone else would be seeing it, Sun would be following IBM's steps).

So, what's next? Well, there is a JSR (JSR 277) which was created to create Java Module System, which is very similar to OSGi, and guess what, IBM is not in the expert group. As I mentioned seconds ago, the Netbeans team is waiting to see which one will win, Java Modules or OSGi, but I reckon that they will either go for Java Modules once the JSR is finalized, or they will stay as they are. I'm quiet confident that they will never go for OSGi.

I believe that this post became much longer, than I wanted it to be, but I can still go on with the subject for much longer. I wanted to get to a point, and that is, politics between large companies have a great effect on software development. Even with open source projects, when a project becomes very popular, large companies tend to create standards similar it. Examples in java include log4j & JDK 1.4 logging, Hibernate & JPA and of course OSGi & java modules (OSGI and java modules have some differences of course). It's then up to the original creator of the open source project to implement the standard (like hibernate implementing JPA).

I'm not at all against Sun (actually I'm a huge fan), but I took it as an example. I'm also not against standardization. I just wanted to speak about the subject of why large corporations do what they do.

Edit on 12/12/2007
HP released java 6 in November and IBM release java 6 just this month, which is still two years after the release by Sun.

Saturday, November 10, 2007

Logback web configurer for Spring

On thing that should be mentioned about logback is that spring doesn't have a ConfigListener for it like the one it has for log4j (the org.springframework.web.util.Log4jConfigListener class). Well, you can write your own code based on the spring source. Thankfully to Davide Baroncelli, he already did that for us. He had already sent the code to the logback user mailing list. The the thread is available online on Nabble, so that if you would like to view it. He also has an updated version that supports auto reloading for logback configurations. Thanks Davide

Saturday, October 20, 2007

Windows Vista Screen Flicker

Well, this post has nothing to do with java, but I though it would be important, since this issue caused me a lot of frustration. I recently bought a laptop with Windows Vista Home Premium, and I was frustrated at what seemed to me that it was a hardware problem. Well, it wasn't. It was a windows "feature" ;-)

The "feature" that annoyed me was that the screen blinked a couple of times when I was logging in, in a matter that seemed as if the screen is faulty. The same thing happened when I wanted to do something that windows think that I shouldn't do, like moving a read only file, or run an executable program (yet another windows "feature"). When I tried to do any of those actions that would cause a security problem, I got a prompt to ask me if I allow this action, with the desktop disabled, and with an occasional screen blink (totally random).

Well, after some googling, I found the causes of those two really annoying "features". The first "feature" was the Transient Multimon Manager (TMM). This TMM is "a Microsoft Windows Vista operating system feature" responsible for detecting your monitors as you connect/disconnect them to/from your mobile PC. You may regard TMM as a good feature in case you use multiple displays (external monitor, projector, etc.) especially that "TMM persists the user's settings on a per-display basis when possible".

When you seldom use multiple displays (like me), TMM is of no value. So, how do we turn it off? Simple. Go to task scheduler (present under "Accessories/System Tools"), then go to "Task Scheduler Library/Microsoft/Windows/MobilePC", and you'll find a TMM task. Disable it, and you're done (of course you'll have to restart your system for the change to take effect, because the task will already be running). You can also disable the trigger of the task. I do not recommend deleting the task altogether, since you might need it in the future.

Now for the second "feature". Windows vista has what's called "secure desktop". Well, it is a good feature to be frank. When you try to do an action that Vista thinks that it might be the result of a malicious action, it will prompt you whether you allow this action or not. This is not "secure desktop" by the way. Secure desktop is responsible for locking all the processes running in the background so that if the action was really performed by a piece of malicious software, it wouldn't give this piece of software the ability to mimic the user allowing the action to be performed.

So, if you think that you will never have malicious software, and you don't want secure desktop, all you have to do is to run your registry editor (just type "regedit" in the "run" screen), and go to "HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Windows/
CurrentVersion/Policies/System", and change the value of the "PromptOnSecureDesktop" to "0" (that's a zero not an O) instead of "1". This will remove secure desktop (hence the occasional blinking) but will not remove the prompting. I recommend that you keep secure desktop for the security reasons, but that's just me.

Edit on 6/1/2008:
I would like to thank Matt for supplying this link in his comment. I think that the screen shot woul give you a little help. Thanks Matt

Saturday, October 13, 2007

Commons Logging may be harmful to your health

All of us know that decoupling your code from the frameworks you use is a really great thing. This is why bridge libraries like commons logging are really wonderful. Just imagine how much code you will be changing if you are using log4j APIs in all of you application classes, and then a decision was made to start using the java APIs instead. Think of how much code would be changed. But with commons logging, the code changes would be minimal. Another thing, look at how many open source projects that are using commons logging. This must mean that commons logging is a good thing, right? WRONG!

First, let us define the meanings of "good" and "bad" concerning libraries such as commons logging. I think, that a "good" library would be able to bridge your logging requests to the logging framework of your preference with minimum interference and a very small overhead. I don't have to mention here that it should be stable and bug free of course. Another thing, which I personally think that it's very important, is that it should be as simple as possible.

If we take a look at JCL (Jakarta Commons Logging), we'll find that a lot of those aspects are not met. JCL works in a quiet complex way. It has a discovery mechanism to see which logging library you have in your application, and then uses class loading to load the logger that will be used. Even though this does the job, this class loading solution has its drawbacks. First of all, this may cause a lot of problems if your application is in a strict class loading environment (like OSGI for example). Another thing, JCL has a bad history with it's class loading solution.

Version 1.04 of JCL that was released on the 16th of June 2004 had some serious problems with its class loading mechanism. Ceki Gülcü (the original author of log4j) wrote a marvelous article on the subject. He also wrote a great piece on JCL, but might be a little outdated. Even though version 1.1 of JCL, released about 2 years after 1.04, claims that the bug is fixed, it's still a risk to use it, especially for the complexity of this library.

Another thing that needs to be mentioned here is that Rod Waldhoff, the author of commons logging, wrote a blog entry in 2003, titled "Commons Logging was my fault", where, in the last part of it, he says where to use and, more importantly, not to use JCL. To conclude it, JCL should be used in small and tiny components that are intended to be used by other developers in their projects. Even with that, Erik van Oosten created a project called "Version 99 Does Not Exist", which is an empty JAR with a pom file and maven meta data, so that you would put it in your maven repository, so that libraries that depend on JCL would not download it from the net, since the empty JAR is version 99.

So what else should we use? Well, I think that SLF4J is a great project. It's a simple facade for various logging APIs. The beauty of it is that instead of the class loading solution, it is just a simple facade, where you just plug in the desired implementation at deployment time. It's a very simple solution, "perhaps even laughably so" as stated in their FAQ.

SLF4J is wonderful, simple, stable and can be used in strict class loading environments like OSGI. It can be used with log4j, jdk1.4 logging, SimpleLogger, logback and x4juli (the latter 2 provide native implementation of SLF4J APIs). It's very simple to migrate to SLF4J from JCL. Simply download "jcl104-over-slf4j.jar", and it will delegate JCL calls to SLF4J.

SLF4J also has a couple of great features, parameterized logging and MDC support. Parameterized logging can cause a significant increase in the performance. One last thing that I have noticed, which is quiet funny really, several apache projects use SLF4J instead of commons logging. This sure shows that SLF4J is on the right track.

Saturday, September 15, 2007

Complete Java 2 Certification Study Guide (Sybex)

This is my second review, and again, it's a java certification book. This was the book I studied from for my certification exam, and thanks to God, I did pretty well.

The book is well constructed, with a lot of info, and a lot of great exercises at the end of each chapter, plus a mock exam, and four sample exams on the accompanying CD. Unfortunately, the book is full of typos, and there are several mistakes with the exam and the review questions, which is quiet a shame. Those mistakes turn this book from a great book, to a "just quiet satisfactory" book. Some of the mistakes are clearly due to lack of revision of the changes done to this edition, so conflicts show up in a couple of places.

An example to what I mean is that starting from Java 5.0, the return type of the overriding method could be a child of the return type of the overridden method, and it's stated clearly in the middle of the chapter, but in the summary at the of the chapter, it's mentioned that the return type of the overriding method must be exactly the same as the overridden method, and can't even be a subclass of it (which is true for pre-5.0). This is clearly something that was in previous editions of the book, and wasn't changed where it was supposed to be. Several mistakes like this occur in the book.

The book is worth it's price, but only if you are going to be careful while studying from it, and check other sources, whether they are other books, or freely available resources on the internet. If you are going to study from one book, and one book only, and will not rely on any other resources, then this is not the book for you. The book is not a bad choice, but there are several other better study guides in the market, like Katherine's Sierra's and Bert Bate's SCJP Sun Certified Programmer for Java 5 Study Guide from Osbourne. I checked it out, and it looks great.

Buy Complete Java 2 Certification Study Guide from amazon
Buy SCJP Sun Certified Programmer for Java 5 Study Guide from amazon


Saturday, August 11, 2007

Dynamic roles management in acegi security: Part 2

Last time we stopped at a problem, and that was the fact that the bean holding the secure URL patterns is loaded only once at application startup. Now, when we need to alter the access rights of roles, we will need to restart the application, and this is really not very flexible.

There are a couple of solutions to this problem. The first is to reload the filter invocation interceptor, and set the object definition source in it with an instance that holds the new values, like the following example:






UrlPatternRolesDefinitionSource myRoles = (UrlPatternRolesDefinitionSource) applicationContext.getBean ("objectDefinitionSource");



FilterSecurityInterceptor filterSecurityInterceptor = (FilterSecurityInterceptor) applicationContext.getBean ("filterInvocationInterceptor");



filterSecurityInterceptor.setObjectDefinitionSource (myRoles);



Only here we have a trick that should be done. The bean objectDefinitionSource should be declared as non-singleton in the XML configuration, either by specifying its scope="prototype" or by specifying singleton="false". This solution has a problem, and it is that the whole list of roles and secure URL patterns will be reloaded from the database (or whatever your datasource is).

The other solution is to create your own ConfigAttributeDefinition that extends the one supplied by acegi. The main reason for doing this is that the one supplied by acegi doesn't have a removeAttribute method.I suggest overriding this implementation to add a removeAttribute method. I also prefer if you would use an ArrayList or a Map instead of the Vector used by the acegi implementation to represent the configAttributes

This ConfigAttributeDefinition should be the one you use in the UrlPatternDefinitionSource that we created in part one of this article.

In the class(es) that will be manipulating the the roles, you should inject the UrlPatternDefinitionSource instance that acegi creates (using spring's configuration files). You then get the ConfigAttributeDefinition for your role using the lookupAttribute method in the UrlPatternDefinitionSource class. A code snippet is shown below.






UrlPatternRolesDefinitionSource uprds = definitionSource;


ConfigAttribute config = new SecurityConfig(role.getName());


Set patternsSet = role.getUrlPatterns();


List list = urlPatternDao.listUrlPatternsOfRole(role);


List oldUrlPatternsOfRole = new ArrayList();


//get list of old url patterns of role


for (UrlPattern urlWithRole : list) {


oldUrlPatternsOfRole.add(urlWithRole);
}


//update role in database


roleDao.updateRole(role);


//do not allow the role to access old url patterns


for (UrlPattern pattern : oldUrlPatternsOfRole) {


MyConfigAttributeDefinition configDefinition = (MyConfigAttributeDefinition) uprds.lookupAttributes(pattern.getUrlPattern());


configDefinition.removeConfigAttribute(config);


}


//allow the role to access the new set of url patterns


for (UrlPattern pattern : patternsSet) {


//get the pattern itself from DB, since all we have is the id of the pattern only


pattern = urlPatternDao.retrieveUrlPattern(pattern.getId());


MyConfigAttributeDefinition configDefinition = (MyConfigAttributeDefinition) uprds.lookupAttributes(pattern.getUrlPattern());


configDefinition.addConfigAttribute(config);


}




The previous code may need some optimization, but it was just to give you a general idea about how to implement dynamic role management.

I hope that this article was useful, and I apologize once more for the delay.

Tuesday, August 7, 2007

Apology

I just want to apologize for being late with the second part of the ACEGI security article, but I had some work pressure, and a lot of traveling between Cairo, Dubai and Abu Dhabi lately, which made it quiet hard to complete the article, but I promise that I'll try my best to finish the article before the beginning of next week, in spite of the fact that I'm still traveling between Dubai and Abu Dhabi every weekend. I apologize again.

Wednesday, July 11, 2007

Dynamic roles management in acegi security: Part 1

Acegi security is a great powerful and flexible security solution. What I don't like about it is the lack of documentation and samples provided, and this is why I thought of writing about this subject today.

The example that comes with acegi security, and the one that comes with appfuse define secure URL patterns, and the roles that can access them in the XML configuration file, which is not a very flexible solution. It is a good approach if you have predefined roles and access rights , that are never going to change (or the changes are very rare). In case you have a security module, where you define which role can access which URL patterns, this method is the worst thing you could do.

The solution to this problem is to define your own data source, which loads the secure URL patterns and the corresponding roles that can access it from somewhere (database for example). A simple way to do that is by extending PathBasedFilterInvocationDefinitionMap and loading the secure URL patterns and the roles that can access them in an initialization method or in the constructor. Here's an example:

public class UrlPatternRolesDefinitionSource extends PathBasedFilterInvocationDefinitionMap {

public void init(){
Session session = sessionFactory.openSession();
try{

List urlPatternsList = urlPatternDao.listUrlPatterns(session);

for (UrlPattern pattern : urlPatternsList) {

ConfigAttributeDefinition configDefinition = new ConfigAttributeDefinition();

for(Role role: pattern.getRoles()){

ConfigAttribute config = new SecurityConfig(role.getAuthority());

configDefinition.addConfigAttribute(config);
}

addSecureUrl(pattern.getUrlPattern(), configDefinition);

}
}
catch (FindException e) {
// Handle exception
}
finally {
session.close();
}
}
}


In this example I used a Hibernate DAO I created (urlPatternDao) to retrieve the secure URL patterns which is defined and initialized with the sessionFactory somewhere else in the code (using spring's dependency injection). You can implement it anyway you like (JDBC, with any other ORM framework, or any other method you like).

In this example, each URL pattern can has a set roles that can access it, so I loop over this set to create the ConfigAttributeDefinition. I prefer if you have your own implementation of the ConfigAttributeDefinition, but this is going to be discussed in part 2 of this article. Of course the Role class used in this code implements the GrantedAuthority interface.

As for the XML configuration of this entry, it's shown below:
<bean id="filterInvocationInterceptor" class="org.acegisecurity.intercept.web. FilterSecurityInterceptor">

<property name="authenticationManager" ref="authenticationManager"/>

<property name="accessDecisionManager" ref="accessDecisionManager"/>

<property name="objectDefinitionSource" ref="objectDefinitionSource"/>

</bean>


<bean id="objectDefinitionSource" class= "net.jnassef.security.UrlPatternRolesDefinitionSource" init-method="init">

<property name="convertUrlToLowercaseBeforeComparison">
<value type="boolean">false</value>
</property>

<property name="urlPatternDao" ref="urlPatternDao"/>
<property name="sessionFactory" ref="sessionFactory"/>
</bean>


As for the first bean in the previous snippet, this definition is the default that comes with the sample acegi application and with appfuse, except to the reference to the objectDefinitionSource bean which was added by us, to allow dynamic role management. The second bean maps to the class we created, and defines the initialization method, that will load the secured URL patterns, and the roles associated with them. This definition also sets the DAO and the hibernate session factory used by the class. Of course you don't need those if you want to have any other implementation.

The previous implementation seems good as a solution for dynamic role management, but if we look more closely, it's not a very good solution (or to be more accurate, it's not a complete solution). The problem that is going to face us here is that secure URL patterns are loaded only ONCE at the application start up, and any change done to the role access rights will not effective until the application is started, and this is not dynamic at all. In fact, there is no difference between this solution, and having the access rights in the XML configuration file, except that you will not need to redeploy your application, but you will need to restart it. There are several solutions to this problem, and this will be the main focus of the next part of this article.

Tuesday, June 12, 2007

Head First Servlets & JSP

Studying is never fun for a lot of people, and reading technical books is always taken as a boring task by a lot of people. This will never be the case with any of the head first series of books.


The head first approach depends on a lot of images, since an image says more than a thousand words. It also depends on repeating the information in different styles, and dialogue like text.

Even though this might seem as if it's a very simple approach, but the result is amazing. The book is fun to read, full of information, and yet very simple. Never thought I would love to study that much again.

Now enough about the head first approach, and into the book itself. The book is very informative, and covers nearly everything in the exam. Very few subjects were not covered, but most of them are covered in the questions at the end of each chapter, with a reference to the place of the information in the specs.

Few mistakes are there (like any book in the market), but most of them are spelling mistakes. The O’Reilly website has a great errata page covering every single mistake in the book (even spelling and grammar mistakes).

A lot of topics covered in the book do not even appear in other books, and a lot of those come in the exam. I studied from that book, and got 94% in the exam. Great book, and really fun to read.


Buy the book from amazon.com

Sunday, May 20, 2007

Open Session In View

I was a part of a team that have developed several applications using Struts, Spring and Hibernate together, and one of the problems that have faced us while using Hibernate was the rendering of the view. The problem is that when you retrieve an object 'a' of persistence class 'A' that has an instance 'b' of persistence class 'B', and this relation is lazily loaded, the value of 'b' will be 'null'. This will cause a "LazyInitializationException" while rendering the view (if you need the value of 'b' in the view of course).

A quick and easy solution to that is to set the "lazy" attribute to "false" so that 'b' would be initialized while fetching 'a', but this is not always a good idea. In case of many-to-many relationships, using non-lazy relations might result in loading the entire database into the memory using a great number of "select" statements, which will result to very poor performance, and to massive memory consumption.

Another solution is to open another unit of work in the view, which is really bad for several reasons. First of all, as a design concept, the layers of your application should be loosely coupled, and by doing the previous practice you have coupled the presentation layer with you DB layer, which is bad. Another thing is that this destroys the separation of concerns concept.

The solution to this problem can be done by keeping the hibernate session alive until the view is rendered, and this is what Hibernate introduced as the Open Session In View Design Pattern. Since the Hibernate session will be opened, trying to retrieve 'b' in the view will cause Hibernate to go and fetch it from the DB. In a web application, this can be done through a filter/interceptor.

Spring framework comes with both a filter and an interceptor, so that you don't have to write your own. The problem that might face you, if you're using spring's HibernateTemplate,without doing your own session and transaction management, is that you will not be able to save, edit or delete anything, since both the filter and the interceptor provided by spring set the flush mode of the session to "NONE".

A solution to that, which I've learned from a friend of mine recently is to extend the filter provided by spring, override the getSession method to set a different flush mode, and override the closeSession method to flush the session before closing it. The sample code is shown below:



public class HibernateFilter extends OpenSessionInViewFilter {

@Override

protected Session getSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {

Session session = SessionFactoryUtils.getSession(sessionFactory, true);

//set the FlushMode to auto in order to save objects.

session.setFlushMode(FlushMode.AUTO);

return session;

}


@Override

protected void closeSession(Session session, SessionFactory sessionFactory) {

try{

if (session != null && session.isOpen() && session.isConnected()) {

try {
session.flush();
}

catch (HibernateException e) {
throw new CleanupFailureDataAccessException("Failed to flush session before close: " + e.getMessage(), e);
}

catch(Exception e){
}
}
}

finally{
super.closeSession(session, sessionFactory);
}
}
}


By using this filter, you will be able to render the view easily, without having to set the "lazy" attribute to "false", or to open a hibernate session in the view, but you have to take care not to change any values of the persistence object in the view, because those changes will be saved to the DB at the end of the request. This is the main reason why the flush mode is set to "NONE" in the original filter and interceptor.

Why this blog?

Well, why do I set up a java blog? I'm not that super java guru who will write great articles that are going to help thousands of java developers. I'm a normal java web developer with only three years of experience. So why do I make a technical blog? Well, think of it as my personal notebook, where I write the technical stuff that I want to remember, and the tips and tricks I've learned, so that when I need them I would get back to them instead of searching the net for what I already know, but forgot.

So again, why a blog? I can do that on a document, or a real notebook. Well, The other reason is giving something back to the community. I've learned a lot through articles and blog entries by developers much more experienced than I am, so why don't I give something back? That's it.



One last thing to note is that I'm planning that most of my posts will not go into a lot details that are out of the scope of the article. To give an example, if I'm writing an article about a solution to a specific problem in struts with spring, I will not go into details of how to integrate struts with spring.



I hope that those entries are going to be useful to web developers, like other blogs were useful to me.