<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Pragmatic Programmer Issues - pietrowski.info &#187; springframework</title>
	<atom:link href="http://pietrowski.info/category/springframework/feed/" rel="self" type="application/rss+xml" />
	<link>http://pietrowski.info</link>
	<description></description>
	<lastBuildDate>Tue, 27 Jul 2010 07:31:08 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Spring MVC Exception Handler</title>
		<link>http://pietrowski.info/2010/06/spring-mvc-exception-handler/</link>
		<comments>http://pietrowski.info/2010/06/spring-mvc-exception-handler/#comments</comments>
		<pubDate>Sat, 19 Jun 2010 09:38:19 +0000</pubDate>
		<dc:creator>pedro</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[springframework]]></category>

		<guid isPermaLink="false">http://pietrowski.info/2010/06/spring-mvc-exception-handler/</guid>
		<description><![CDATA[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. AnnotationMethodHandlerExceptionResolver (new in 3.0) [...]]]></description>
			<content:encoded><![CDATA[<p style="clear: both">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.</p>
<ol style="clear: both">
<li><a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/portlet/mvc/annotation/AnnotationMethodHandlerExceptionResolver.html">AnnotationMethodHandlerExceptionResolver</a> (new in 3.0)</li>
<li><a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/servlet/mvc/annotation/ResponseStatusExceptionResolver.html">ResponseStatusExceptionResolver</a> (new in 3.0)</li>
<li><a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/servlet/mvc/support/DefaultHandlerExceptionResolver.html" title="">DefaultHandlerExceptionResolver</a> (new in 3.0)</li>
<li><a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/portlet/handler/SimpleMappingExceptionResolver.html">SimpleMappingExceptionResolver</a></li>
</ol>
<p style="clear: both">
<h3>SimpleMappingExceptionResolver</h3>
</p>
<p style="clear: both">Should be configured in XML, there are few properties which drives this resolver behaviors. </p>
<ul style="clear: both">
<li>defaultErrorView -> this view name will be returned if no mapping will be found.</li>
<li>defaultStatusCode -> once the view name was resolved if the view hasn&#8217;t status code the <em><strong>defaultStatusCode</strong></em> will be applied.</li>
<li>statusCodes -> Map with &#8220;view name&#8221; to &#8220;status code&#8221; mapping.</li>
<li>exceptionAttribute -> the name of attribute where exception is hold by default &#8220;exception&#8221; is used.</li>
<li>exceptionMappings -> Properties which maps Exception &#8220;class name&#8221; to &#8220;view name&#8221;. Watch out as you can easily maps more than you want, this is because only String.contains is checked, so <em>a=viewName</em> mapping will catch all exception with &#8220;a&#8221; in the name. <br />Another thing to consider is that if you provide deep Exception hierarchy (<strong>n</strong>) and you provide a lot of exception mapping (<strong>m</strong>), you will end up with <strong>O(n*m)</strong> 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. </li>
</ul>
<p style="clear: both">
<h3>DefaultHandlerExceptionResolver</h3>
</p>
<p style="clear: both"> First at all it has pageNotFound logger which is <strong>org.springframework.web.servlet.PageNotFound </strong>logger category, second it decides what to do depending on exception type, it is base class to extend when we want change default behavior:</p>
<ul style="clear: both">
<li>NoSuchRequestHandlingMethodException : no request handler method was found by default it sends 404 error. Override <em><strong>handleNoSuchRequestHandlingMethod</strong></em>.</li>
<li>HttpRequestMethodNotSupportedException : no request handler method was found for the particular HTTP request method by default 405 error.Override <em><strong>handleHttpRequestMethodNotSupported</strong></em>.</li>
<li>HttpMediaTypeNotSupportedException : no HttpMessageConverter were found for the PUT or POSTed content by default 415 error. Override <strong><em>handleHttpMediaTypeNotSupported</em></strong>.</li>
<li>HttpMediaTypeNotAcceptableException : no HttpMessageConverter were found that were acceptable for the client (Accept header) by default 406 error. Override <em><strong>handleHttpMediaTypeNotAcceptable</strong></em>.</li>
<li>MissingServletRequestParameterException : required parameter is missing by default 400 error. Override <em><strong>handleMissingServletRequestParameter</strong></em>.</li>
<li>ConversionNotSupportedException : WebDataBinder conversion cannot occur by default 500 error. Override <strong><em>handleConversionNotSupported</em></strong>.</li>
<li>TypeMismatchException : WebDataBinder conversion error occurs by default 400. Override <strong><em>handleTypeMismatch</em></strong>.</li>
<li>HttpMessageNotReadableException : HttpMessageConverter cannot read from HTTP request by default 400 error. Override <strong><em>handleHttpMessageNotReadable</em></strong>.</li>
<li>HttpMessageNotWritableException : HttpMessageConverter cannot write to HTTP response by default 500 error. Override <strong><em>handleHttpMessageNotWritable</em></strong>.</li>
</ul>
<p style="clear: both">
<h3>ResponseStatusExceptionResolver</h3>
</p>
<p style="clear: both">This resolver allows us to use @<a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/bind/annotation/ResponseStatus.html">ResponseStatus</a> annotation. If we annotate our Exception with @<a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/bind/annotation/ResponseStatus.html">ResponseStatus</a> annotation than the response will get status code from annotation. </p>
<ul style="clear: both">
<li>ResponseStatus.value as status code (it is HttpStatus enum)</li>
<li>ResponseStatus.reason as reason or default HttpResponse reason if not set. </li>
</ul>
<p style="clear: both">
<h3>AnnotationMethodHandlerExceptionResolver</h3>
</p>
<p style="clear: both">Last but not least, and from my point of view this resolver is the most important. This exception resolver allows us to use @<a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/bind/annotation/ExceptionHandler.html">ExceptionHandler</a> annotation, every method annotated by @<a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/bind/annotation/ExceptionHandler.html">ExceptionHandler</a> will become exception handler. As parameters @<a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/bind/annotation/ExceptionHandler.html">ExceptionHandler</a> need an array of Throwable. We also should use @<a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/bind/annotation/ResponseStatus.html">ResponseStatus</a> to indicate status code.</p>
<p style="clear: both">The method signatures possibilities are vary so see documentation to get all the proper combinations of parameters and return types. </p>
<p>The idea is pretty simple, for all the <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/bind/annotation/ExceptionHandler.html">ExceptionHandler</a>.value exception the exception -> Method handler is created, when Exception happens Method will be invoked.</p>
<p style="clear: both">
<h3>Conclusions</h3>
</p>
<p style="clear: both">Since 3.0 we rather has no need to setup handlers by ourself, the most useful way is to use @<a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/bind/annotation/ExceptionHandler.html">ExceptionHandler</a> annotation. By default DispatcherServlet will setup <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/portlet/mvc/annotation/AnnotationMethodHandlerExceptionResolver.html">AnnotationMethodHandlerExceptionResolver</a>, <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/servlet/mvc/annotation/ResponseStatusExceptionResolver.html">ResponseStatusExceptionResolver</a> and <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/servlet/mvc/support/DefaultHandlerExceptionResolver.html" title="Untitled">DefaultHandlerExceptionResolver</a> as handlers resolvers. So we are ready to start with annotation based approach.</p>
<p>My approach is that I try to create moduleExceptionHandler class which has all methods annotated by @<a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/bind/annotation/ExceptionHandler.html">ExceptionHandler</a> (except utility methods of course) and I always annotate them by @<a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/bind/annotation/ResponseStatus.html">ResponseStatus</a> 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.</p>
<p>If you need a code, please send me a comment. I&#8217;m currently in the process of choosing git repository.</p>
<p><br class="final-break" style="clear: both" /></p>
]]></content:encoded>
			<wfw:commentRss>http://pietrowski.info/2010/06/spring-mvc-exception-handler/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>How to extend SQLErrorCodesFactory</title>
		<link>http://pietrowski.info/2008/09/how-to-extend-sqlerrorcodesfactory/</link>
		<comments>http://pietrowski.info/2008/09/how-to-extend-sqlerrorcodesfactory/#comments</comments>
		<pubDate>Tue, 02 Sep 2008 20:28:43 +0000</pubDate>
		<dc:creator>pedro</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[springframework]]></category>

		<guid isPermaLink="false">http://pietrowski.info/?p=105</guid>
		<description><![CDATA[I found some interesting feature in springframework. Spring offers you to map sql error code to exception type. By default there is in springframework distribution file called sql-error-codes.xml which has definition for common databases ( DB2, Derby, H2, HSQL, Informix, MS-SQL, MySQL, Oracle, PostgreSQL, Sybase). This keys are taken form java.sql.DatabaseMetaData databaseProductName property. Each driver [...]]]></description>
			<content:encoded><![CDATA[<p>I found some interesting feature in springframework. Spring offers you to map sql error code to exception type. By default there is in springframework distribution file called sql-error-codes.xml which has definition for common databases ( DB2, Derby, H2, HSQL, Informix, MS-SQL, MySQL, Oracle, PostgreSQL, Sybase).</p>
<p>This keys are taken form <a href="http://java.sun.com/javase/6/docs/api/java/sql/DatabaseMetaData.html">java.sql.DatabaseMetaData</a> <a href="http://java.sun.com/javase/6/docs/api/java/sql/DatabaseMetaData.html#getDatabaseProductName()">databaseProductName</a> property. Each driver should provide proper implementation. This post will provide you the way how to add another databases or extends definition to more sql codes.</p>
<p>As we read javadoc, the default file is bundled in spring.jar and it&#8217;s location is &#8220;<code>org/springframework/jdbc/support/sql-error-codes.xml" </code>so first solution is to simple extract this file, add what we want, and than put it back. This solution has many drawbacks e.g. when we upgrade we must repeat our steps once again. If we keep reading javadoc we read<br />
<cite><br />
Reads the default file in this package if not overridden by a file in the root of the class path (for example in the &#8220;/WEB-INF/classes&#8221; directory).</cite></p>
<p>So the second option is to provide file called &#8216;sql-error-codes.xml&#8217; in the root path. Lets start coding.<br />
Our App.java is very simple.</p>
<p class="java-code">public class App {<br />
public static void main(String[] args) {<br />
SQLErrorCodesFactory errorCodes = SQLErrorCodesFactory.getInstance();<br />
SQLErrorCodes errorCode = errorCodes.getErrorCodes(&#8220;MySQL&#8221;);<br />
}<br />
}</p>
<p><a href="http://pietrowski.info/wp-content/uploads/2008/09/picture-4.png"><img class="alignnone size-full wp-image-106" title="sql error codes default " src="http://pietrowski.info/wp-content/uploads/2008/09/picture-4.png" alt="sql error codes default " width="500" height="297" /></a></p>
<p>If we run this in debug mode we can see something like this. This is default SQL error codes definition for MySQL database. Now we add the &#8216;sql-error-codes.xml&#8217;. I&#8217;ve just copied MySQL bean from default file and added some codes to badSqlGrammarCodes. This time the result look like this:</p>
<p><a href="http://pietrowski.info/wp-content/uploads/2008/09/picture-7.png"><img class="alignnone size-full wp-image-107" title="sql error codes override" src="http://pietrowski.info/wp-content/uploads/2008/09/picture-7.png" alt="sql error codes override" width="500" height="263" /></a></p>
<p>And here is execution log, interesting lines in bold:</p>
<pre>Sep 2, 2008 9:54:46 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [org/springframework/jdbc/support/sql-error-codes.xml]
Sep 2, 2008 9:54:46 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
<strong>INFO: Loading XML bean definitions from class path resource [sql-error-codes.xml]
Sep 2, 2008 9:54:46 PM org.springframework.beans.factory.support.DefaultListableBeanFactory registerBeanDefinition
INFO: Overriding bean definition for bean 'MySQL':
    replacing [Generic bean: ... defined in class path resource [org/springframework/jdbc/support/sql-error-codes.xml]]
    with [Generic bean: ...  defined in class path resource [sql-error-codes.xml]]
Sep 2, 2008 9:54:46 PM org.springframework.jdbc.support.SQLErrorCodesFactory
INFO: Found custom sql-error-codes.xml file at the root of the classpath</strong>
Sep 2, 2008 9:54:46 PM org.springframework.jdbc.support.SQLErrorCodesFactory
INFO: SQLErrorCodes loaded: [DB2, Derby, H2, HSQL, Informix, MS-SQL, MySQL, Oracle, PostgreSQL, Sybase]
</pre>
<p>The point to remember is that our definition didn&#8217;t override all the definition but only definition with the same bean id. This is not so clear in <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/jdbc/support/SQLErrorCodesFactory.html">SQLErrorCodesFactory javadoc</a>, which suggest that we override all beans.</p>
<p>We can use this mechanism if we have different database, or if we want to extend or change sql code mapping to exception. The application is really simple but you can<br />
<a href="http://pietrowski.info/wp-content/uploads/2008/09/sqlerrorcode.tgz">download it, and try by yourself</a>.</p>
<p>Bye.</p>
]]></content:encoded>
			<wfw:commentRss>http://pietrowski.info/2008/09/how-to-extend-sqlerrorcodesfactory/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>java spring config</title>
		<link>http://pietrowski.info/2008/08/java-spring-config/</link>
		<comments>http://pietrowski.info/2008/08/java-spring-config/#comments</comments>
		<pubDate>Fri, 29 Aug 2008 20:02:47 +0000</pubDate>
		<dc:creator>pedro</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[springframework]]></category>

		<guid isPermaLink="false">http://pietrowski.info/?p=102</guid>
		<description><![CDATA[There is a possibility to configure spring framework only in java. Yep no XML . There is a project spring-java-config. This project aims to provide a way to configure spring without XML. To use it with maven you should add repository to your pom and dependency &#60;repository&#62; &#60;id&#62;spring-milestone&#60;/id&#62; &#60;name&#62;Spring Milestone Repository&#60;/name&#62; &#60;url&#62;http://s3.amazonaws.com/maven.springframework.org/milestone&#60;/url&#62; &#60;/repository&#62; &#60;dependency&#62; &#60;groupId&#62;org.springframework.javaconfig&#60;/groupId&#62; [...]]]></description>
			<content:encoded><![CDATA[<p>There is a possibility to configure spring framework only in java. Yep no XML <img src='http://pietrowski.info/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> .</p>
<p>There is a project <a href="http://www.springframework.org/javaconfig">spring-java-config</a>. This project aims to provide a way to configure spring without XML. To use it with maven you should add repository to your pom and dependency</p>
<pre class="programlisting">&lt;repository&gt;
  &lt;id&gt;spring-milestone&lt;/id&gt;
  &lt;name&gt;Spring Milestone Repository&lt;/name&gt;
  &lt;url&gt;http://s3.amazonaws.com/maven.springframework.org/milestone&lt;/url&gt;
&lt;/repository&gt;

&lt;dependency&gt;
   &lt;groupId&gt;org.springframework.javaconfig&lt;/groupId&gt;
   &lt;artifactId&gt;spring-javaconfig&lt;/artifactId&gt;
   &lt;version&gt;1.0.0.m3&lt;/version&gt;
&lt;/dependency&gt;</pre>
<p>One thing to mention is to setup java 5 compiler, because spring java config use annotation.</p>
<pre class="programlisting">  &lt;plugin&gt;
    &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
    &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
    &lt;configuration&gt;
      &lt;source&gt;1.5&lt;/source&gt;
      &lt;target&gt;1.5&lt;/target&gt;
      &lt;encoding&gt;UTF-8&lt;/encoding&gt;
    &lt;/configuration&gt;
  &lt;/plugin&gt;</pre>
<p>This config will provide as all the dependencies, we can start to configure our beans. The class which has bean configuration must be annotated by <a href="http://static.springframework.org/spring-javaconfig/docs/1.0.0.m3/apidocs/org/springframework/config/java/annotation/Configuration.html">@Configuration</a> annotation, and methods with <a href="http://static.springframework.org/spring-javaconfig/docs/1.0.0.m3/apidocs/org/springframework/config/java/annotation/Bean.html">@Bean</a> annotation is equivalent to  element. Resume : klas with @Configuration equals xml file with beans, and method with @Bean equals  element.</p>
<p><a href="http://pietrowski.info/wp-content/uploads/2008/08/picture-3.png"><img class="alignnone size-full wp-image-104" title="config class" src="http://pietrowski.info/wp-content/uploads/2008/08/picture-3.png" alt="config class" width="312" height="177" /></a></p>
<p>And the last thing is to use <a href="http://static.springframework.org/spring-javaconfig/docs/1.0.0.m3/apidocs/org/springframework/config/java/context/JavaConfigApplicationContext.html">JavaConfigApplicationContext</a> which accepts as constructor class annotated with  @Configuration property. Below the main class.</p>
<p><a href="http://pietrowski.info/wp-content/uploads/2008/08/picture-2.png"><img class="alignnone size-full wp-image-103" title="main program" src="http://pietrowski.info/wp-content/uploads/2008/08/picture-2.png" alt="main program" width="598" height="80" /></a></p>
<p>And this is basis, we can probably stop here but I provide some additional information. Depends on method visibility our bean is visible or not in the context.</p>
<ul>
<li>The standard set of *Aware interfaces are supported.</li>
<li>You can use scopes, autowire and others features known from xml configuration</li>
<li>@Import is equivalent of xml&#8217;s &lt;import&gt;, and JavaConfigApplicationContext accepts more than one class as constructor parameter.</li>
<li>For web application we can use JavaConfigWebApplicationContext</li>
</ul>
<p>I&#8217;m still watching the future of the project. Stay tuned <img src='http://pietrowski.info/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://pietrowski.info/2008/08/java-spring-config/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
