<?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>The Software Chef &#187; java</title>
	<atom:link href="http://katastrophos.net/magnus/blog/category/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://katastrophos.net/magnus/blog</link>
	<description>nuts and bolts of software development, and anything else that comes to my mind - by Magnus Jungsbluth</description>
	<lastBuildDate>Sat, 18 Jul 2009 07:33:23 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.3</generator>
		<item>
		<title>Having &#8220;fun&#8221; with JSR-303 Beans Validation and OSGi + Spring DM</title>
		<link>http://katastrophos.net/magnus/blog/2009/07/18/having-fun-with-jsr-303-beans-validation-and-osgi-spring-dm/</link>
		<comments>http://katastrophos.net/magnus/blog/2009/07/18/having-fun-with-jsr-303-beans-validation-and-osgi-spring-dm/#comments</comments>
		<pubDate>Sat, 18 Jul 2009 07:31:24 +0000</pubDate>
		<dc:creator>Magnus Jungsbluth</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[OSGi]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Beans Validation]]></category>
		<category><![CDATA[JSR-303]]></category>
		<category><![CDATA[Spring DM]]></category>

		<guid isPermaLink="false">http://katastrophos.net/magnus/blog/?p=52</guid>
		<description><![CDATA[Most Java standards are implemented using an api jar and an concrete implementation jar. The API constists maninly of interfaces but a class that looks up the default implementation. This lookup normally happens by trying to load a specific resource bundle which is located in the implementation jar. This can lead to &#8220;interesting&#8221; classloader problems [...]]]></description>
			<content:encoded><![CDATA[<p>Most Java standards are implemented using an api jar and an concrete implementation jar. The API constists maninly of interfaces but a class that looks up the default implementation. This lookup normally happens by trying to load a specific resource bundle which is located in the implementation jar. This can lead to &#8220;interesting&#8221; classloader problems when used with OSGi and Spring DM specifically<br />
<span id="more-52"></span><br />
In the case of Beans Validation (using the Hibernate Validator 4.0 reference implementation) we have a javax.validation and org.hibernate.validator artifact. Both jars are no valid OSGi bundles so you have to wrap them to add valid Import-Packages and Export-Packages directives to the appropiate MANIFEST.MF files. To make the configuration file contained in the implementation bundle visible to the api bundle you have to configure the implementation as OSGi Fragment by specifying a *Fragment-Host: javax.validation* in its manifest.</p>
<p>Depending on the classloader used to find the configuration resource it either works or not. Using Spring Dynamic Modules this means that it does not work if you try to aquire a ValidatorFactory while the Spring OSGi extender is loading your Spring application context. It works however when aquired from within the Activator of the using bundle. This is no bug in Spring DM but rather an inherent problem in the default implementation lookup of the Beans Validation API. Spring extender loads the application context of a bundle with the BundleClassLoader set as current thread classloader. This classloader restricts loading of resource bundles to the current bundle.</p>
<p>To solve this problem, create a third bundle and put implement the following class:</p>
<pre name="code" class="java">public final class ValidatorFactoryBean {

	/**
	 * Custom provider resolver is needed since the default provider resolver
	 * relies on current thread context loader and doesn't find the default
	 * META-INF/services/.... configuration file
	 *
	 */
    private static class HibernateValidationProviderResolver implements ValidationProviderResolver {

        @Override
        public List getValidationProviders() {
            List providers = new ArrayList(1);
            providers.add(new HibernateValidationProvider());
            return providers;
        }
    }

    private final static ValidatorFactory instance;

    static {
        ProviderSpecificBootstrap validationBootStrap =
                Validation.byProvider(HibernateValidatorConfiguration.class);
        validationBootStrap.providerResolver(new HibernateValidationProviderResolver());
        instance = validationBootStrap.configure().buildValidatorFactory();
    }

    public final static ValidatorFactory getInstance() {
        return instance;
    }
}</pre>
<p>Additionally put the following spring config in META-INF/spring/beans.xml:</p>
<pre name="code" class="xml">
&lt;beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:osgi="http://www.springframework.org/schema/osgi"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                      http://www.springframework.org/schema/osgi http://www.springframework.org/schema/osgi/spring-osgi.xsd"&gt;
	&lt;bean id="validatorFactory"
  	  class="de.ivu.combitour.commoninfrastructure.validation.ValidatorFactoryBean"
  	  factory-method="getInstance"/&gt;

	&lt;osgi:service ref="validatorFactory" interface="javax.validation.ValidatorFactory"/&gt;
&lt;/beans&gt;
</pre>
<p>Note however that this file <strong>should be split in two files</strong> if you follow Springsource&#8217;s advice. This separated the osgi specific part from the pure spring configuration. </p>
<p>What this snipet does is to provide an OSGi service called &#8220;validatorFactory&#8221; and to use hibernate validator as default implementation. </p>
]]></content:encoded>
			<wfw:commentRss>http://katastrophos.net/magnus/blog/2009/07/18/having-fun-with-jsr-303-beans-validation-and-osgi-spring-dm/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Detached Service Methods with Spring AOP</title>
		<link>http://katastrophos.net/magnus/blog/2009/07/07/detached-service-methods-with-spring-aop/</link>
		<comments>http://katastrophos.net/magnus/blog/2009/07/07/detached-service-methods-with-spring-aop/#comments</comments>
		<pubDate>Tue, 07 Jul 2009 19:44:40 +0000</pubDate>
		<dc:creator>Magnus Jungsbluth</dc:creator>
				<category><![CDATA[AOP]]></category>
		<category><![CDATA[AspectJ]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[background jobs]]></category>

		<guid isPermaLink="false">http://katastrophos.net/magnus/blog/?p=10</guid>
		<description><![CDATA[In a typical spring based server application there is a service layer responsible for infrastructure tasks and communication with the clients. Service methods can be long running and execution would normally block the user-interface. Putting the client side end of the call in a thread solves the blocking but leaves the network connection open while [...]]]></description>
			<content:encoded><![CDATA[<p>In a typical spring based server application there is a service layer responsible for infrastructure tasks and communication with the clients.  Service methods can be long running and execution would normally block the user-interface. Putting the client side end of the call in a thread solves the blocking but leaves the network connection open while the server side of the call is active. This can lead to all sorts of time-out issues and seems to be the wrong end to fix the problem .</p>
<p>Using spring AOP it is remarkably easy to declaratively enable service methods to execute detached from the regular call context.</p>
<h4>The Goal</h4>
<pre  name="code" class="java">@DeferredExecution
public myServiceMethod() throws DeferredExecutionException {
}</pre>
<p>This method would execute with the following sematics:</p>
<ol>
<li>The regular method call is wrapped in a thread</li>
<li>The thread is executed</li>
<li>If the thread does not finish within x seconds, raise a checked exception</li>
<li>If it does finish in time, return the result of the method</li>
</ol>
<p>This way clients of this method are forced to handle detached execution (i.e. show a progress dialog querying the server) and the client side of the call not langer lasts longer than a set time.<br />
<span id="more-10"></span></p>
<h4>Implementation</h4>
<p>Define a new Annotation</p>
<pre  name="code" class="java">
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DeferredExecution {
}</pre>
<p>Define a spring aspect (note that altough it uses AspectJ annotations, AspectJ is not required)</p>
<pre  name="code" class="java">
@Aspect
public class DeferredExecutionInterceptor implements Ordered {

	private int order;

	@Pointcut("execution(* *.*(..)) &amp;&amp; @annotation(DeferredExecution)")
	public void inServiceMethod() {}

	@Around("inServiceMethod()")
	public Object doDeferredExecution(ProceedingJoinPoint joinPoint)
			throws Throwable {
		JoinPointExecutionThread thread = new JoinPointExecutionThread(joinPoint);
		thread.start();

		//wait for the thread to finish and
		//- either throw a DeferredExecutionException
		//- or return the result
	}

	@Override
	public int getOrder() {
		return order;
	}

	public void setOrder(int order) {
		this.order = order;
	}
}</pre>
<p>It is important to implement the Ordered interface since you most likely want to influence the order of the created AOP-Proxy. It should run after a security advisor and before any transaction interceptor.</p>
<p>The following spring config brings this aspect to life. The aspect is applied to all spring managed instances.</p>
<pre name="code" class="xml">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;beans
  xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:aop="http://www.springframework.org/schema/aop"
  xsi:schemaLocation="

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

http://www.springframework.org/schema/aop

    http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"&gt;

    &lt;aop:aspectj-autoproxy /&gt;

    &lt;bean id="deferredExecutionInterceptor" class="DeferredExecutionInterceptor"&gt;
        &lt;property name="order" value="100" /&gt;
    &lt;/bean&gt;

    &lt;bean id="testService" class="TestServiceImpl"&gt;
    &lt;/bean&gt;
&lt;/beans&gt;
</pre>
<p>There is one tiny bit that is optional: Nothing prevents a developer not to declare a throws clause on an annotated service method. Since client code <strong>must</strong> handle the case when execution is detached, this is crucial. </p>
<p>To enforce this at <strong>compile time</strong> we can use AspectJ&#8217;s declare error feature to generate a compile error when such an inconsistency is found.</p>
<p>Create a <strong>separate</strong> Aspect with</p>
<pre  name="code" class="java">
public aspect DeferredExecutionMethodCheckAspect {

	public pointcut deferredExecutionMethodWithoutThrows():
		execution(@DeferredExecution public * *.* (..))
		&#038;&#038; !execution(@DeferredExecution public * *.* (..)
				throws DeferredExecutionException);

	declare error: deferredExecutionMethodWithoutThrows():
		"Method must declare throws DeferredExecutionException for annotation to work";
}
</pre>
<p>When configuring compile time weaving in maven or AJDT it is crucial <strong>not to weave</strong> DeferredExecutionInterceptor, since this would make it impossible to set the order in which spring executes the AOP Proxies. </p>
<h4>Remarks</h4>
<p>This is of course only a rough sketch but it worked almost instantly. Note that there is no documentation concerning the thread safety of the joinPoint passed into the around advice. Since the joinPoint is only used within one thread it seems safe to to so. </p>
<p>In a real world scenario you would most likely not use threads directly but your choice for handling background jobs (for example backed by Quartz).</p>
<p>Note that there is no mechanism to handle cascaded service calls. You would most likely want only one background job created along the way. This could easily be solved using ThreadLocals&#8230;</p>
<p><script src="js/shCore.js"></script> <script src="js/shBrushCSharp.js"></script><br />
<script src="js/shBrushXml.js"></script> <script type="text/javascript"><!--
dp.SyntaxHighlighter.ClipboardSwf = '/flash/clipboard.swf';
dp.SyntaxHighlighter.HighlightAll('code');
// --></script></p>
]]></content:encoded>
			<wfw:commentRss>http://katastrophos.net/magnus/blog/2009/07/07/detached-service-methods-with-spring-aop/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

