Jan 31, 2010

Kill your application with Hibernate subselect!

If you want to kill your application silently the best way is to use Hibernate 'subselect' fetching strategy. Lets discuss the issue in details. Imagine that you have entities 'Post' and 'Comment' in the domain model with corresponding tables in the database:

public class Post {
    private Long id;
    private String title;
    private String body;
    private Set<Comment> comments;
    ...
}

public class Comment {
    private Long id;
    private String text;
    ...
}


Of course you use 'one to many' relationship to map relations between posts and comments (using 'post_id' column from comments table). It doesn't matter what mapping type you prefer (annotations of XML based). All seems good at this moment and you decide to choose 'subselect' fetching strategy for comments collection. You also create a number of unit tests to make sure that you mapping is well done and works fine. Now you want to create method to find last 10 posts for your home page. You decide to use Criteria API for this purpose:

List posts = session.createCriteria(Post.class)
     .addOrder(Order.desc("id"))
     .setMaxResults(10)
     .list();


You again create some unit tests to make sure that method works as expected. But of course you don't review SQL queries in Hibernate logs to check if all is as you expect to be. Hibernate generates following SQL queries for you (example from PostgreSQL database):

select post0_.id as id0_, 
post0_.title as title0_, 
post0_.body as body0_ 
from Post post0_ 
order by
post0_.id desc
limit 10;

select
comment0_.post_id as post5_1_,
comment0_.id as id1_0_,
comment0_.text as text1_0_
from Comment comment0_ 
where comment0_.post_id in (
   select post0_.id 
   from Post post0_
); 


Pay attention to the second query, especially to its subquery part. Limitation is not included in the subquery! What is going on here? It seems that Hibernate is going to load full comments table in memory and then select from them related to top posts selected before. Crazy behavior! Initially, when database is empty or there is low amount of comments, your application will work well. But every time somebody opens your home page with top blogs shown query loads all comments in memory, so you have performance penalty. This penalty is proportional to the number of comments in the database. Once (may be after some monthes of usage in production) you will find that all memory allocated to your application is filled and garbage collector eats 100% of CPU time. Thanks god for profilers, especially for VisualVM. It is hard to believe that such small issue in Hibernate may cause such dramatic effects. There is an opened issue in Hibernate bug tracker, but it has minor priority. We need to keep living with it, so another approach should be applied. The best way to avoid these issues is to use 'batch select' fetching strategy with lazy loading (or without it depending on application needs). Be careful and develop with pleasure!

Oct 19, 2009

Defining batch size for batch fetching in Hibernate

One of the Hibernate performance tuning ways when you need to work with parent/children relationships is to use lazy loading collections with batch fetching. This way allows you to perform far less than n+1 SQL queries to initialize your entities. To enable this mode you just need to specify batch-size attribute in XML mapping for collection or mark it with @BatchSize annotation in Java code. But how to define appropriate batch size? You need to understand how it works internally to do it well.

From examples you may see that if there are 25 objects in the database and batch size is set to 10 then Hibernate will perform 3 SQL queries: 10, 10, 5 items. But it is not so simple in the case of larger batch size. Hibernate internally creates an array of batch sizes using following strategy: if batch size <= 10 (for example 5) then it fills array with numbers from 1 to batch size ([1,2,3,4,5] for 5), else (for example 50) it fills array with numbers from 1 to 10 and integer parts of division batch size by powers of 2 ([1,2,3,4,5,6,7,8,9,10,12,25,50] for 50). So, now lets see how many SQL queries will Hibernate perform in case when batch size is 50 and there are 38 records in the database. The answer is 3: 25, 12, 1. Are you surprised? Hibernate doesn't create too many JDBC prepared statements for batch fetching so it performs querying using array of batch sizes. So, when you know the truth how to define the best batch size for your application? The answer is simple and relies on the mathematical theory: you should use powers of 2 multiplied by 10 (for example 10, 20, 40, 80, etc.) because each positive integer may be represented as a sum of powers of 2 (for example 13 = 8 + 4 + 1). If you select 40 instead of 50 in the previous example you will see benefit for example when number of records is 23: 2 SQL queries (20, 3) instead of 3 SQL queries (12, 10, 1). Of course if you know that a number of records in the database will always be small enough then use smallest batch size from recommended - 10. If you don't know how many records will be in the database then switch on logs for SQL queries and analyze how many of them are performed to define batch size from the recommended formula. I hope this will help you make Hibernate more productive. Develop with pleasure!

Oct 18, 2009

Ideal project video

Recently I have viewed video presentation from the InfoQ about one team experience report. This team uses a lot of great engineering and collaboration practices, always experiments and analyzes results of their work. Its really only one right way to build products quickly, within the budget and with the highest level of quality. They always communicate with customers and gather feedback from them to build product according to the real needs of the market. Try this way and you will success!

Oct 14, 2009

XP injection at ITjam

In September Kiev became a little more Agile because of the largest Agile conference in the Eastern Europe. On Agilee I have presented "People factor as failure reason of Agile adoption". This presentation is about people and requirements for them from Agile world, how everybody may improve his skills and become Agile team member.

The next conference I'm going to participate in is ITjam. I will present "Kanban VS Scrum" and "XP injection" with my friend Aleksey Solntsev. From first presentation your will learn more about Kanban, its principals and compare it to Scrum. In the second presentation we are going to show on the real project how to inject XP engineering practices like unit testing, TDD, CI, automated build, code review, etc. You will find how to simplify your daily work and start producing better products. Registration is free, so you are welcome!

Oct 13, 2009

Agile Coaching site launched

Some weeks ago I have launched Agile Coaching web site. It contains a lot of trainings available for ordering and participating, presentations from different conferences and video materials. I'm going to continuously fill this site with new useful information. I hope that you find something interesting for you there. Develop with pleasure!

Manage dependent projects in Maven

If you have been used Maven for a long time you probably know that it supports both project inheritance and aggregation. There is detailed description with samples on Maven site how both of them work. But sometimes you have really separated projects one of them depends on another, but both of them are continuously in development phase. So you need to use latest build artifacts of the base project without wasting time to run all its tests. There are some ways to resolve this issue. Lets say that we have project B witch depends on project A. Both of them contain many modules and base pom.xml files to build their own hierarchy.

So the first natural way to resolve the issue is to build projects in the right order manually (A and then B). But if project A was not changed from the last time then you will just waste your build time. Also in this case you should use some commands instead of one (it may be problematic for your CI server). Maven has release plugin that may help you. You just need to setup internal (company or project level) Maven repository and configure releasing policy for your project build. There are a lot of players on the market of Maven repositories: Archiva, Nexus, Proximity, Artifactory, etc. All of them supports local releasing of project artifacts. When setting releasing policy for the project you should decide if you will support only stable versions or snapshots as well. In case of snapshots Maven may generate build time version of artifacts after each release build. After all parts are configured you may use release plugin commands to publish project artifacts to the internal repository and make them available for all local repositories. So you need to build project A only when changes are made (for example on each commit to VCS). When you build project B Maven will automatically check for new versions of the project A artifacts and download them to the local repository if changes was found.

But sometimes your project contains modules that are not written in Java and are very platform dependent (for example install C++ library code on each build). In this case the previous solution can't be applied. You need to change main pom.xml of the project B to add information about dependency on project A, but you want to apply it only if project A sources are available on your machine. Use following profile for this purpose:

<profile>
<id>Build A project</id>

<modules>
<module>${a.relative.path}</module>
</modules>

<activation>
<property>
<name>a.relative.path</name>
</property>
</activation>
</profile>

This profile will be activated only if system property a.relative.path is passed. Note that value of this property should be related to root of project B (for example ../../a). Maven will build project A as part of each project B build. But how to avoid running tests in the project B? We use aggregation so no settings are inherited from the project B pom.xml except system properties. So, lets use them. Add following profile to the project A base pom.xml:

<profile>
<id>Disable tests for external build</id>
<properties>
<maven.test.skip>true</maven.test.skip>
</properties>
<activation>
<property>
<name>a.test.skip</name>
</property>
</activation>
</profile>

This profile will be activated when a.test.skip system variable is present and will disable all tests execution like -Dmaven.test.skip does. If you need additional settings for quick build of project A set them using system properties as well. Now you may build both projects with one Maven command: mvn -Da.relative.path=../../a -Da.tesk.skip clean install. If you don't have access to the project A sources then rely on the current version of the artifacts from local repository and build phase of the project A will be skipped.
Maven is very powerful build tool and even complex scenarios may be implemented using it. Develop with pleasure.

Mar 12, 2009

Be careful of large log files using TeamCity

Previous week I had very interesting experience with TeamCity continuous integration server. From some moment it became unable to perform any actions, just hanging and them crashing. After analysis of the server logs and running processes we identified that it uses 100% CPU time and then fail with errors related to memory limitations. The first level of the issue was that it runs garbage collector very often and without success (GC couldn't release memory in any generation). But why? To understand such behavior we used one of the very well done open source profilers - VisualVM. We found that one of the threads created a very large list of strings (more than 100000) and continued to add new strings. The root of the issue was very large log file from one of our builds (this build always works some hours and gathers all actions in log). TeamCity saved this log and on each start it tried to read it all in memory line by line to allow users view build history logs. We have already configured TeamCity to perform clean up procedure for all historical artifacts and logs one per week, but it didn't save us from crash. To fix the issue we cleaned manually all historical data from .BuildServer/system/messages. Also we configured problematic build to output all log messages in log file and now we use this log file only as artifact of the build. So, logging is well, but be aware of large log files especially when somebody read them. Develop with pleasure!

Dec 19, 2008

Risk of inheritance

Inheritance is one of the basics in any object oriented language but you always should think a lot before use it in your code. Of course inheritance is very useful when you design your code for it, use abstract classes, template method design pattern, create different implementations overriding well defined protected methods and so on. But in some cases inheritance may make damage to your application in future very silently.

Imagine situation when you want to add some behavior to class and decided to override its public methods in the child class. The following hidden issues are waiting for you:

* You don't know how this method is used and how it will be used in future in code of the parent class. Your changes may cause unpredictable behavior.
* You want to control some access points of the parent class, but in future some more points can be added and your code will fail in unpredictable time interval.
* Overridden methods will be removed in future, deprecated or change their access level.
* Some other issues depending of concrete scenario.

To avoid most of these issues use composition instead of inheritance. Create new class and declare needed behavior by implementing the same set of interfaces such a basic class. May be you need only some of them, so you can localize your needs and have easier implementation saving time for support. Then implement some methods and delegate all other to the instance of basic class.

Composition has its own disadvantages when basic class is too large or creation of the instances is too complicated, then you need to duplicate a lot of code or logic. IDE or other automation tools can help you with generation of such kind of code.

But what to do if basic class doesn't implement any interfaces and declared abstract? In this case you have to protect yourself from as many issues as possible. Create unit tests to control basic class methods and validate if all of them are known by you. These tests will notify you if basic class was changed so you need to look at new implementation and may be make changes in code or tests. To access information about declared methods use reflection API or some open source libraries that simplify access to this information. But think before if you really need inheritance in this case (if class was not designed for inheritance) and try to avoid it if possible. Develop with pleasure!

Crisis in action

As far as you know in many countries economical crisis came and many "experienced" people was fired in IT market. But crisis makes a good job for some companies. I want to share my experience in interviewing one of such "experienced" guys. This person has a lot of practical experience with Java language at all levels from core to web. After some general questions I proposed following interface declaration:

public interface I {
int b = 5;
void a();
}

The question was if this declaration is correct. A received the following answer: "No. You need to change it to be correct." Here is what he wrote:

public interface I {
int b = 5;
private void a();
}

The explanation was great: "Instead this method will have visibility only in the package". The next question was about difference between abstract class and interface. The answer makes me smile: "The advantage of abstract class is that I can declare method in it and don't think about it anymore". Imagine how hard is to think about method in all other cases. :) "And why do you ask all these stupid questions? All this is so simple and doesn't matter" - he continued. After that phrase interview was finished.

So, do you want your code to be developed by such guys? If no be aware of crisis. And develop with pleasure...

Sep 13, 2008

Generics commons collections

Everybody of you who have large experience with Java thanks Apache for their commons project. This project includes a lot of libraries to extend or simplify work with JDK. One of these libraries is commons-collections.

It was very helpful when you needed to work with specific kinds of collections like multi map, lazy collections, bidirectional map, etc. Also it had a great number of iterators, comparators and utilities to avoid writing unnecessary code in your application. It allowed us to transform one collection to another, filter collection elements and many other things very easy. It introduced completely new types of collections like buffer (collection that allows objects to be removed in some well-defined order), bag (collection that counts the number of times an object appears in the collection), bidirectional map (map that allows bidirectional lookup between key and values) and created a great number of custom implementations of existing collections types.

But why I always use past sentences? Because from the beginning of Java 5 usage this library is not more so helpful. One of the main features introduced in Java 5 was generics. And of course the most useful place for generics to be applied is collections framework. I hoped that it takes not more than year to refactor existing library and add support of generics by commons-collections developers. But it didn't happen. :( But don't worry! There are some solutions of this issue. First one is to use generics version of commons-collections developed in parallel with main Apache version. At this moment they have functionality synchronized with version 3.1. Another option is to use google-collections instead. This project was started as free time development of one developer in Google for internal usage and now it contains a lot of features in comparison to commons-collections. It is driven by community, so only really needed things are included. To start work with this library or to get your own opinion take a look at the video presentation. Develop with pleasure!

Jul 20, 2008

Acceptance Test Driven Development training in Kiev

In august I'm going to conduct a training on the Acceptance Test Driven Development in Kiev. Date and agenda of the training was announced with help of Agile Ukraine. Most of the presented tools for automated acceptance testing will be related to Java language (have implementation for Java or native Java support). You are welcome!

Jul 19, 2008

Advanced EasyMock techniques

EasyMock is one of many mock libraries available for Java testing. Now it archive version 2.4 and is very powerful. For those of you who are not familiar with mock concepts start with Martin Fowler article. Detailed guide about EasyMock you can read here. I'm going to show some advanced techniques of using EasyMock in your tests.

Imagine that you have following document processing code:

public class DocumentService {
private DocumentProcessor processor;

public Document getDocument(long id) {
Document doc = //code to retrive document
processor.process(doc);
return doc;
}

public void setProcessor(DocumentProcessor processor) {
this.processor = processor;
}
}

public interface DocumentProcessor {
void process(Document document);
}

public class Document {
private String text;
private long wordsCount;

public Document(String text) {
this.text = text;
}

public String getText() {
return text;
}

public void setText(String text) {
this.text = text;
}

public long getWordsCount() {
return wordsCount;
}

public void setWordsCount(long wordsCount) {
this.wordsCount = wordsCount;
}
}

In your tests you want to check if changes made by processor really change returned document. To check this you want to set 'wordsCount' variable value to 5. You may create your own processor to do this:

public class DocumentServiceTest {
private DocumentService documentService = new DocumentService();
private DocumentProcessor processor = new DocumentProcessor() {
public void process(Document document) {
document.setWordsCount(5);
}
};

@Test
public void testGetDocument() {
documentService.setProcessor(processor);
Document document = documentService.getDocument(3);
Assert.assertEquals(5, document.getWordsCount());
}
}

But also you can use EasyMock (in my example I use Unitils to easy manage mocks):

@RunWith(UnitilsJUnit4TestClassRunner.class)
public class DocumentServiceTest {
private DocumentService documentService = new DocumentService();

@RegularMock
private DocumentProcessor processor;

@Test
public void testGetDocument() {
expectDocumentProcessed();

documentService.setProcessor(processor);
Document document = documentService.getDocument(3);
Assert.assertEquals(5, document.getWordsCount());
}

private void expectDocumentProcessed() {
processor.process(isA(Document.class));
expectLastCall().andAnswer(new IAnswer<Object>() {
public Object answer() throws Throwable {
((Document) getCurrentArguments()[0]).setWordsCount(5);
return null;
}
});
replay(processor);
}
}

Why this is more powerful solution? Because you can change behavior of the processor in runtime and reuse the same mock in different tests with different behavior. Some times your dependencies are not so simple as document processor in my example and it is not so easy to extend or implements their methods (for example interface has 10 methods and you need only one of them). There is one more side effect of this usage - you have access to the parameters passed to the methods. You can save the parameter instance to use it in asserts or for other dependencies behavior mocking.

In 2.4 version of EasyMock 'capture' option was introduced to simplify work with method parameters. Document class from previous example doesn't have custom 'equals' method, so you can't use 'eq' method of EasyMock to check parameter of 'process' method. You can implement your own argument matcher (see IArgumentMatcher in the EasyMock guide) or use Unitils reflection comparison 'refEq', but another good option for you is to use new 'capture' option:

Capture<Document> capture = new Capture<Document>();
processor.process(and(isA(Document.class), capture(capture)));
replay(processor);

Document captured = capture.getValue();

These two techniques must be in your arsenal to use full power of EasyMock library and make your tests better. Develop with pleasure!

Jul 16, 2008

Design for scalability

If you develop large J2EE or WEB application using Java you should always think about scalability of your application (of course if you expect your application to be popular). Nobody tell you that you should scale your application initially, but take in mind that some architecture solutions may make it really hard to scale in the future. You have two common approaches: vertical and horizontal scalability. Both approaches has their requirements for code base to be applied effectively. I have found very interesting article on the www.theserverside.com about J2EE scalability written by Wang Yu from of Sun Microsystems. Article contains two parts: vertical and horizontal scalability. Take this information in mind when make architectural decisions. Develop with pleasure!

Jul 14, 2008

Make your tests excellent with Unitils

I am going to share my experience in using Unitils - framework that makes life easier. I have started to work with this framework from early release candidates and can't imagine my tests without it now. If you need to test application that use Hibernate, Spring, other ways of database access, but you don't want to write much test code and create some homegrown frameworks, then Unitils is your choice. If you already use some specific testing frameworks like EasyMock or DbUnit, but your tests are hard to create and maintain then Unitils will remove this pain for you.

Unitils started as a discussion group on unit testing. The result of these discussions is the list of guidelines that will be useful without Unitils itself. Then some people decide to build framework that will contains all in one, but be flexible enough to use it in different applications. So Unitils was born. To help developers with mapping guidelines to the framework there are tutorial and cookbook both published on the Unitils web site.

Unitils supports JUnit3, JUnit4 and TestNG and contains following modules:

- Spring module (for loading application contexts and retrieving and injecting Spring beans)
- Hibernate module (Hibernate configuration support and automatic database mapping checking)
- DbUnit module (test data management using DbUnit)
- Database module (unit-test database maintenance and connection pooling)
- EasyMock module (for creating mocks and lenient reflection argument matching)
- Inject module (for injecting (mock) objects into other objects)

Unitils configuration is very flexible and very small (if you are satisfied with default behavior). You can select any modules for your application and don't use others. Unitils work is based on annotations, so you will not need additional configuration files like except general settings file. Also Unitils provide to developers very useful assertion utilities, that based on reflection and support different modes for asserts.

Unitils has modular architecture so you can easy write your own modules to extend existing functionality. It is open source project so your modules may be included in future releases. General Maven repository contains last version of the framework so those of you who use Maven will not need manually install it. One important part is missed in Unitils - mocks for Java 'native' technologies like Servlets, JSP, JNDI and etc. I use a part of Spring framework (spring-test) for this purpose and it makes job very well.

From June 25, 2008 Unitils 1.1 became available. This release includes support of JPA, Spring transactions and complex database scripts structure. Also many integration bugs was fixed for database module.

I don't want to include examples for Unitils usage, you can find them in the tutorial or cookbook with detailed descriptions. Also there is useful video presentation with concrete samples. Make your tests better and your application code will be better. Develop with pleasure!

Jul 12, 2008

Evil 'System.currentTimeMillis()' and 'new Date()'

If you use TDD like me or just write unit tests for your code then you have already met issues with testing dates. There are two common ways to retrieve current time in Java: 'System.currentTimeMillis()' and 'new Date()'. Both of them make your code untestable. To illustrate this effect imagine that you test service for user registration and user record in the database contains registration date. When you create database record you put current date as registration date. But how to check that record is created correctly? Yes, perform assert operation. But what date should you place in your expected object? There is no easy answer. Of course you can check that registration date is in the interval of date when test was started and date when assert is performed. But then you will introduce additional variables and still can't assert full domain object using for equals. Similar issues exist for asserting method parameters and other parts of your testing. So I have created very useful utility class:

public class Clock {
private static long time;

private Clock() {
}

public static Date getCurrentDate() {
return new Date(getTimeMillis());
}

public static long getTimeMillis() {
return (time == 0 ? System.currentTimeMillis() : time);
}

public static void setTimeMillis(long millis) {
Clock.time = millis;
}

public static void resetTime() {
Clock.time = 0;
}
}

This class encapsulate all work with date creation and can be easy stubbed by setting internal time for particular usage. After test invocation it should be reset to disable stub behavior (DON'T FORGET TO DO IT). For some projects I extend this class with methods to retrieve shifted data to represent data in the future or in the past. If you need more complex logic (for example you will invoke date creation some times in the tested logic) then you may change 'time' static variable with 'DateTimeStrategy' class instance:

public interface DateTimeStrategy {
long getTimeMillis();
}

Then you will have more control on the data creation in your tests by implementing your own strategies. This approach not only helps me with testing but also encapsulate logic for dates creation in one place but makes my code clearer. I hate Java native implementation of work with dates and hope that in future it will be changed with something like Joda Time. I hope this approach will make your tests better. Develop with pleasure!

Be careful with your 'hashCode()'!

Every Java developer know that there are some methods common for all objects. One of them is 'hashCode()'. By default it returns internal address of the object, but should be overridden when your overrides another common method 'equals()'. Contract for the 'hashCode()' is following:

  • Whenever it is invoked on the same object more than once during
    an execution of a Java application, the hashCode method
    must consistently return the same integer, provided no information
    used in equals comparisons on the object is modified.
    This integer need not remain consistent from one execution of an
    application to another execution of the same application.

  • If two objects are equal according to the equals(Object)
    method, then calling the hashCode method on each of
    the two objects must produce the same integer result.

  • It is not required that if two objects are unequal
    according to the equals(Object) method, then calling the
    hashCode method on each of the two objects must produce
    distinct integer results. However, the programmer should be aware
    that producing distinct integer results for unequal objects may
    improve the performance of hashtables.



From this contract you can draw a conclusion that 'hashCode()' implementation should use only immutable fields of the object. Why? Lets create user domain object:

public class User {
private Long id;
private String name;

public User(String name) {
this.name = name;
}

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getName() {
return name;
}

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

public boolean equals(Object obj) {
return (this == obj) ||
(obj instanceof User && equals((User) obj));
}

public boolean equals(User that) {
EqualsBuilder builder = new EqualsBuilder()
.append(id, that.id)
.append(name, that.name);
return builder.isEquals();
}

public int hashCode() {
HashCodeBuilder builder = new HashCodeBuilder()
.append(id)
.append(name);
return builder.toHashCode();
}
}

I have used commons-lang to generate 'equals()' and 'hashCode()' but it doesn't matter. Now lets test if our 'hashCode()' is correct by running JUnit test:

public class UserTest {
@Test
public void testMutableName() {
Set users = new HashSet();
User user = new User("user");
user.setId(5L);
users.add(user);
user.setName("user2");
Assert.assertTrue(users.contains(user));
}
}

This test will fail because hash code of the user object was changed while user object itself was saved in the collection that uses it to save objects more efficiently.

Try to include in the 'hashCode()' only immutable fields, because you can have hidden issues not only with your own code but also with frameworks like Hibernate. If you don't have immutable fields, then be very careful and take described issues into account (recreate objects instead of changing them, don't use long live collections, return constant from 'hashCode()' or 'ID' field value). I hope this article will save you time for debugging. Develop with pleasure!

Jul 11, 2008

Effective Java (2nd Edition)


May 2008 brings us second edition of the Java bible "Effective Java" from Joshua Bloch. First edition takes first positions in many 'must read' lists for Java developers. This edition additionally includes features from Java 5 and 6. You can order it at Amazon.

FreeMarker integration with Intellij IDEA

Some of you who uses FreeMarker as your favorite template engine and Intellij IDEA as your favorite IDE will understand my pain. At the moment there is no support of FreeMarker in IDEA, so developers try to find other ways while waiting for IDEA 8.0 roadmap will be finished.

One of the best approaches is to use live templates - very powerful feature of the IDEA. Originally I have found basic templates with full explanation here. Then I refactor all templates to work with square brackets and add some new for Spring integration:

<template name="fm.spring.bind" value="[@spring.bind '$MODEL_KEY$' /]"
description="Sping bind function for the freemarker template"
toReformat="false" toShortenFQNames="true">
<variable name="MODEL_KEY" expression=""
defaultValue="" alwaysStopAt="true" />
<context>
<option name="JAVA_CODE" value="false" />
<option name="JAVA_COMMENT" value="false" />
<option name="JAVA_STRING" value="false" />
<option name="XML" value="false" />
<option name="HTML" value="true" />
<option name="JSP" value="false" />
<option name="COMPLETION" value="false" />
<option name="OTHER" value="false" />
</context>
</template>

<template name="fm.spring.expr" value="${spring.status.expression}"
description="Spring binded name for the freemarker template"
toReformat="false" toShortenFQNames="true">
<context>
<option name="JAVA_CODE" value="false" />
<option name="JAVA_COMMENT" value="false" />
<option name="JAVA_STRING" value="false" />
<option name="XML" value="false" />
<option name="HTML" value="true" />
<option name="JSP" value="false" />
<option name="COMPLETION" value="false" />
<option name="OTHER" value="false" />
</context>
</template>

<template name="fm.spring.url"
value="[@spring.url relativeUrl=$RELATIVE_URL$ /]"
shortcut="SPACE"
description="Insert URL to another page of the application"
toReformat="false" toShortenFQNames="true">
<variable name="RELATIVE_URL" expression=""
defaultValue="" alwaysStopAt="true" />
<context>
<option name="JAVA_CODE" value="false" />
<option name="JAVA_COMMENT" value="false" />
<option name="JAVA_STRING" value="false" />
<option name="XML" value="false" />
<option name="HTML" value="true" />
<option name="JSP" value="false" />
<option name="COMPLETION" value="false" />
<option name="OTHER" value="true" />
</context>
</template>

<template name="fm.spring.val" value="${spring.status.value}"
description="Spring binded value for the freemarker template"
toReformat="false" toShortenFQNames="true">
<context>
<option name="JAVA_CODE" value="false" />
<option name="JAVA_COMMENT" value="false" />
<option name="JAVA_STRING" value="false" />
<option name="XML" value="false" />
<option name="HTML" value="true" />
<option name="JSP" value="false" />
<option name="COMPLETION" value="false" />
<option name="OTHER" value="false" />
</context>
</template>

These templates help me every day and save time to manual typing. May be it will be starting point of using live templates for some of us. Develop with pleasure!

Select implementation of Spring bean in runtime

Some of you who uses Spring in your application as dependency injection framework or as development platform may be need change implementation of one particular dependency in runtime. Some examples of this need: integration testing with fake external subsystem, local and remote versions of services, mock implementation to speed up development.

I have found very useful to have such option in my applications and implemented special factory bean for this purpose:

public class SelectImplementationFactoryBean implements FactoryBean {
private String key;
private Map<String, Object> implementations;

public Object getObject() {
Object impl = implementations.get(key);
if (impl == null) {
throw new IllegalStateException("There is no implementation for key = "
+ key);
}
return impl;
}

public Class getObjectType() {
return getObject().getClass();
}

public boolean isSingleton() {
return false;
}

@Required
public void setKey(String key) {
this.key = key;
}

@Required
public void setImplementations(Map<String, Object> implementations) {
this.implementations = implementations;
}
}

Simple enough but very powerful. I will demonstrate how to use it to control database properties for integration with Hibernate:

<bean id="hibernateProperties" class="com.example.SelectImplementationFactoryBean">
<property name="key" value="${database.dialect}"/>
<property name="implementations">
<map>
<entry key="postgre">
<util:map map-class="java.util.Properties">
<entry key="hibernate.hbm2ddl.auto" value="validate"/>
<entry key="hibernate.show_sql" value="true"/>
<entry key="hibernate.dialect"
value="org.hibernate.dialect.PostgreSQLDialect"/>
<entry key="hibernate.default_schema" value="test"/>
<entry key="hibernate.cache.use_second_level_cache" value="false"/>
<entry key="hibernate.cache.provider_class"
value="org.hibernate.cache.NoCacheProvider"/>
</util:map>
</entry>
<entry key="hsqldb">
<util:map map-class="java.util.Properties">
<entry key="hibernate.hbm2ddl.auto" value="validate"/>
<entry key="hibernate.show_sql" value="true"/>
<entry key="hibernate.dialect"
value="org.hibernate.dialect.HSQLDialect"/>
<entry key="hibernate.cache.use_second_level_cache" value="false"/>
<entry key="hibernate.cache.provider_class"
value="org.hibernate.cache.NoCacheProvider"/>
</util:map>
</entry>
</map>
</property>
</bean>

Now to switch your tests to another database you should change value of the property database.dialect between postgre and hsqldb (it can be configuration properties file or system property). I hope it will save your time. Develop with pleasure!

Jul 10, 2008

Access SVN version and build date from maven

Sometimes we need to show or save information about application build. This information may include sources version (from VCS that you use), build date, database versions, etc. If you build your application with Maven there is easy way to access this information.

To do this check buildnumber-maven-plugin. This plugin is used to build extended build version. To access SVN version and build timestamp (not formatted date) you need to add following plugin configuration to maven pom.xml:

<plugins>
....
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>buildnumber-maven-plugin</artifactId>
<configuration>
<buildNumberPropertyName>sources.version</buildNumberPropertyName>
<timestampPropertyName>build.timestamp</timestampPropertyName>
</configuration>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>create</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>

These variables may be used to build project version, to label project artifacts or just to provide this information to end user like in following example:

- Add file version.properties to you maven module resources:

application.sources.version=${sources.version}
application.build.date=${build.timestamp}

- Add filtering section for this file to the maven pom.xml:

<resources>
....

<resource>
<directory>${basedir}/src/main/resources</directory>
<includes>
<include>version.properties</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>

Now you have more control on application version. Develop with pleasure!