Archive for the ‘java’ Category

Pedro Newsletter 16.07.2010

Friday, July 16th, 2010

Spring jdbc namespace

Thursday, July 1st, 2010

One of the new feature of Spring Framework 3.0 is more namespaces. Today I want to write about jdbc namespace, which I’m using in last project.

The namespace is really simple, it has two main elements

  • initialize-database – which allow us to initialize database with scripts.
  • embedded-database – which allow us to start embedded database.

initialize-database

So we can use that xml tag to initialize our datasource with SQL scripts. There are some properties we should set:

  • data-source – which is javax.sql.DataSource bean reference. It will be used to connect and execute all the scripts.
  • enabled – if we should do anything so if we are enabled or not. (remember it can be property ${} or even spring EL), by default it is enabled.
  • ignore-failures – if we should ignore when statements end with errors.
    • NONE – do not ignore default value.
    • DROPS – we are ignoring failed DROP statements.
    • ALL – we ignore all failed statements.

And what is more important this tag has zero or more scripts tags. All this tags has location property which behave exactly the same as spring resources. In my application I create schema for production (I don’t use any ORM) and for tests I have the same schema with one more script (test data/fixtures – no more DbUnit problems :) ).

It is soooo simple.

<jdbc:initialize-database data-source="dataSource">
<jdbc:script location="classpath:/schema.sql">
</jdbc:script></jdbc:initialize-database>

embedded-database

The second tag, is really helpful when you want to use embedded database. Embedded database is helpful for things like storing configuration or other persistent application stuff.

It allow to simple start embedded database and make them visible as javax.sql.DataSource, ready to be injected to our JDBCTemplete objects. It has just two attributes:

  • id – which value becomes the bean name.
  • type – embedded database type

Actually those types are supported:


        
        
    

Under The Hood

All things starts at JdbcNamespaceHandler class, which register two parsers for elements. There is EmbeddedDatabaseBeanDefinitionParser for embedded-database element and InitializeDatabaseBeanDefinitionParser for initialize-database.

When everything is ok this elements build and configure two beans.

And that’s all.


Spring MVC Exception Handler

Saturday, June 19th, 2010

In previous version of Spring Framework to handle exception we used HandlerExceptionResolver interface. Spring also provides simple implementations which was suitable in most of cases. Since 3.0 version we have few additional exception resolvers plus we can use annotation to specify our exception handler methods or classes without implementing HandleExceptionResolver interface.

  1. AnnotationMethodHandlerExceptionResolver (new in 3.0)
  2. ResponseStatusExceptionResolver (new in 3.0)
  3. DefaultHandlerExceptionResolver (new in 3.0)
  4. SimpleMappingExceptionResolver

SimpleMappingExceptionResolver

Should be configured in XML, there are few properties which drives this resolver behaviors.

  • defaultErrorView -> this view name will be returned if no mapping will be found.
  • defaultStatusCode -> once the view name was resolved if the view hasn’t status code the defaultStatusCode will be applied.
  • statusCodes -> Map with “view name” to “status code” mapping.
  • exceptionAttribute -> the name of attribute where exception is hold by default “exception” is used.
  • exceptionMappings -> Properties which maps Exception “class name” to “view name”. Watch out as you can easily maps more than you want, this is because only String.contains is checked, so a=viewName mapping will catch all exception with “a” in the name.
    Another thing to consider is that if you provide deep Exception hierarchy (n) and you provide a lot of exception mapping (m), you will end up with O(n*m) lookup algorithm. It may seem not problem, but if somebody spots that (Error page which render time is quite long), than it may be used with DDOS to increase load on ours machines.

DefaultHandlerExceptionResolver

First at all it has pageNotFound logger which is org.springframework.web.servlet.PageNotFound logger category, second it decides what to do depending on exception type, it is base class to extend when we want change default behavior:

  • NoSuchRequestHandlingMethodException : no request handler method was found by default it sends 404 error. Override handleNoSuchRequestHandlingMethod.
  • HttpRequestMethodNotSupportedException : no request handler method was found for the particular HTTP request method by default 405 error.Override handleHttpRequestMethodNotSupported.
  • HttpMediaTypeNotSupportedException : no HttpMessageConverter were found for the PUT or POSTed content by default 415 error. Override handleHttpMediaTypeNotSupported.
  • HttpMediaTypeNotAcceptableException : no HttpMessageConverter were found that were acceptable for the client (Accept header) by default 406 error. Override handleHttpMediaTypeNotAcceptable.
  • MissingServletRequestParameterException : required parameter is missing by default 400 error. Override handleMissingServletRequestParameter.
  • ConversionNotSupportedException : WebDataBinder conversion cannot occur by default 500 error. Override handleConversionNotSupported.
  • TypeMismatchException : WebDataBinder conversion error occurs by default 400. Override handleTypeMismatch.
  • HttpMessageNotReadableException : HttpMessageConverter cannot read from HTTP request by default 400 error. Override handleHttpMessageNotReadable.
  • HttpMessageNotWritableException : HttpMessageConverter cannot write to HTTP response by default 500 error. Override handleHttpMessageNotWritable.

ResponseStatusExceptionResolver

This resolver allows us to use @ResponseStatus annotation. If we annotate our Exception with @ResponseStatus annotation than the response will get status code from annotation.

  • ResponseStatus.value as status code (it is HttpStatus enum)
  • ResponseStatus.reason as reason or default HttpResponse reason if not set.

AnnotationMethodHandlerExceptionResolver

Last but not least, and from my point of view this resolver is the most important. This exception resolver allows us to use @ExceptionHandler annotation, every method annotated by @ExceptionHandler will become exception handler. As parameters @ExceptionHandler need an array of Throwable. We also should use @ResponseStatus to indicate status code.

The method signatures possibilities are vary so see documentation to get all the proper combinations of parameters and return types.

The idea is pretty simple, for all the ExceptionHandler.value exception the exception -> Method handler is created, when Exception happens Method will be invoked.

Conclusions

Since 3.0 we rather has no need to setup handlers by ourself, the most useful way is to use @ExceptionHandler annotation. By default DispatcherServlet will setup AnnotationMethodHandlerExceptionResolver, ResponseStatusExceptionResolver and DefaultHandlerExceptionResolver as handlers resolvers. So we are ready to start with annotation based approach.

My approach is that I try to create moduleExceptionHandler class which has all methods annotated by @ExceptionHandler (except utility methods of course) and I always annotate them by @ResponseStatus as well. The methods parameters and return type vary depending on my needs. It a little bit central approach but it avoids problem with more than one handler per Exception.

If you need a code, please send me a comment. I’m currently in the process of choosing git repository.


Pedro Newsletter 11.06.2010

Saturday, June 12th, 2010

Today is shopping day @ SF, I’ve got a long list of stuff to buy, we’ll see if I manage that :) .


Java Master

Thursday, June 10th, 2010

That was great training and from today I will use Java Master title with pleasure. Every java developer should get this training. And here is my online certificate.


about me

My name is Sebastian Pietrowski. I've finished Warsaw University as Master degree. I started my journey with Java 1.1 with Thread and JDBC programing in 1998 as I worked for merlin.pl. In 1999 I've passed Java Programer Certificate for Java 1.2, and was solution architect of merlin.pl infrastructure when we was moving from pl/sql to J2EE. It was great performance optimization with 10 times more req/sec than in requirements and 85 times faster as original solution.

Currently I work as Expert Software Development Java at F.Hoffmann-La Roche. The company was founded in 1896 and today, Roche employs over 80.000 people. After work I'm involved in activities related to Scala/Lift, Ruby/Rails/Merb, Python/Django. This is because I try to be pragmatic also I'm focused on application performance and tuning with success in my daily work.

My Yoda's motto: Do, or do not. There is no try.