<?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>Xebia Blog &#187; Google App Engine</title>
	<atom:link href="http://blog.xebia.com/tag/google-app-engine/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.xebia.com</link>
	<description>Software development done right!</description>
	<lastBuildDate>Wed, 01 Feb 2012 00:30:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Using Spring JavaConfig on Google App Engine</title>
		<link>http://blog.xebia.com/2010/01/17/using-springs-java-configuration-on-google-app-engine/</link>
		<comments>http://blog.xebia.com/2010/01/17/using-springs-java-configuration-on-google-app-engine/#comments</comments>
		<pubDate>Sun, 17 Jan 2010 20:26:23 +0000</pubDate>
		<dc:creator>Andrew Phillips</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Amazon Webservices]]></category>
		<category><![CDATA[Frameworks]]></category>
		<category><![CDATA[GAE]]></category>
		<category><![CDATA[Google App Engine]]></category>
		<category><![CDATA[Guice]]></category>
		<category><![CDATA[Javaconfig]]></category>
		<category><![CDATA[jclouds]]></category>
		<category><![CDATA[Spring]]></category>

	<!-- AutoMeta Start -->
	<category></category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=3975</guid>
		<description><![CDATA[Recently, I put together a Spring demonstration for jclouds, the Java cloud library. This quickly turned into unexpected multi-dimensional experiment in integrating Guice, Google App Engine and Spring, but after much trial-and-error I finally came across a configuration that does the trick &#8211; or at least works1 as well as seems possible on GAE. The [...]]]></description>
			<content:encoded><![CDATA[<p>Recently, I put together a Spring demonstration for <a href="http://code.google.com/p/jclouds" target="_new">jclouds</a>, the Java cloud library. This quickly turned into unexpected multi-dimensional experiment in integrating <a href="http://code.google.com/p/google-guice/wiki/Motivation?tm=6" target="_new">Guice</a>, <a href="http://code.google.com/appengine/" target="_new">Google App Engine</a> and <a href="http://www.springsource.org/about" target="_new">Spring</a>, but after much trial-and-error I finally came across <a href="http://code.google.com/p/jclouds/source/browse/trunk/demos/#demos/gae-tweetstore-spring/src/main/webapp/WEB-INF" target="_new">a configuration</a> that <a href="http://jclouds-tweetstore-spring.appspot.com/" target="_new">does the trick</a> &#8211; or at least works<sup>1</sup> as well as seems possible on GAE.<span id="more-3975"></span></p>
<h3>The tweetstore demo</h3>
<p><a href="http://anyweight.blogspot.com/2009/10/save-your-tweets-forever-with-jclouds.html" target="_new">Tweetstore</a> is a simple web application that demonstrates jclouds&#8217; cloud capabilities. It queries Twitter for mentions of the user&#8217;s account and creates a &#8220;backup&#8221; of this priceless record of your contemporary image in three cloud stores: <a href="http://aws.amazon.com/s3/" target="_new">Amazon S3</a>, <a href="http://www.microsoft.com/windowsazure/" target="_new">Microsoft&#8217;s Azure</a> and <a href="http://www.rackspacecloud.com/cloud_hosting_products/files" target="_new">Rackspace</a>. Nothing less than double redundancy is good enough for your popularity!</p>
<p>The original tweetstore application uses <a href="http://code.google.com/p/google-guice/wiki/GoogleAppEngine" target="_new">Guice</a> for dependency injection and request mapping. In order to make it as easy as possible to compare the Spring version to the original, I decided to try to similarly do as much in Java code as possible. A perfect opportunity for me to get my hands dirty with Spring 3.0&#8242;s support for <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-java" target="_new">Java configuration</a>.</p>
<h3>Bootstrapping Spring&#8217;s Java Configuration</h3>
<p>The first, relatively straight-forward step was to convert the Guice <a href="http://code.google.com/p/jclouds/source/browse/trunk/demos/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/GuiceServletConfig.java" target="_new">servlet module</a> into an equivalent <a href="http://code.google.com/p/jclouds/source/browse/trunk/demos/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/config/SpringServletConfig.java" target="_new">Spring @Configuration</a>:</p>
<pre class="brush: java; title: ; notranslate">
@Configuration
public class SpringServletConfig extends LoggingConfig implements ServletConfigAware {
    private ServletConfig servletConfig;
    ...

    @PostConstruct
    public void initialize() {
        ...
    }

    @Bean
    public StoreTweetsController storeTweetsController() {
        StoreTweetsController controller = new StoreTweetsController(providerTypeToBlobStoreMap,
                container, twitterClient);
        injectServletConfig(controller);
        return controller;
    }

    @Bean
    public AddTweetsController addTweetsController() {
        AddTweetsController controller = new AddTweetsController(providerTypeToBlobStoreMap,
                serviceToStoredTweetStatuses());
        injectServletConfig(controller);
        return controller;
    }

    private void injectServletConfig(Servlet servlet) {
        try {
            servlet.init(checkNotNull(servletConfig));
        } catch (ServletException exception) {
            throw new BeanCreationException(&quot;Unable to instantiate &quot; + servlet, exception);
        }
    }

    @Bean
    ServiceToStoredTweetStatuses serviceToStoredTweetStatuses() {
        return new ServiceToStoredTweetStatuses(providerTypeToBlobStoreMap, container);
    }

    @Bean
    public HandlerMapping handlerMapping() {
        SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
        Map&lt;String, Object&gt; urlMap = Maps.newHashMapWithExpectedSize(2);
        urlMap.put(&quot;/store/*&quot;, storeTweetsController());
        urlMap.put(&quot;/tweets/*&quot;, addTweetsController());
        mapping.setUrlMap(urlMap);
        /*
         * &quot;/store&quot; and &quot;/tweets&quot; are part of the servlet mapping and thus stripped
         * by the mapping if using default settings.
         */
        mapping.setAlwaysUseFullPath(true);
        return mapping;
    }

    @Bean
    public HandlerAdapter servletHandlerAdapter() {
        return new SimpleServletHandlerAdapter();
    }

    ...
}
</pre>
<p>Being <a href="http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/web/context/ServletConfigAware.html" target="_new">ServletConfigAware</a> isn&#8217;t exactly Spring best practice but then the chosen aim was to stay as close as possible to the original set-up rather than building a Spring reference application.</p>
<p>Hooking Spring into the GAE startup was the next step. The <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-java-instantiating-container-web" target="_new">Spring reference example</a> was my first attempt:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;web-app&gt;
    &lt;servlet&gt;
        &lt;servlet-name&gt;dispatcher&lt;/servlet-name&gt;
        &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;
        &lt;!-- Configure DispatcherServlet to use JavaConfigWebApplicationContext
             instead of the default XmlWebApplicationContext --&gt;
        &lt;init-param&gt;
            &lt;param-name&gt;contextClass&lt;/param-name&gt;
            &lt;param-value&gt;org.springframework.web.context.support.AnnotationConfigWebApplicationContext&lt;/param-value&gt;
        &lt;/init-param&gt;
        &lt;init-param&gt;
            &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
            &lt;param-value&gt;org.jclouds.demo.tweetstore.config.SpringServletConfig&lt;/param-value&gt;
        &lt;/init-param&gt;
    &lt;/servlet&gt;

    &lt;servlet-mapping&gt;
    ...
&lt;/web-app&gt;
</pre>
<p>Unfortunately, this unceremonially blew up in my face with a security violation: <tt>AnnotationConfigWebApplicationContext</tt> (and all Spring contexts that register a <a href="http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.html" target="_new">CommonAnnotationBeanPostProcessor</a>) attempts to load <tt>javax.annotation.Resource</tt> to determine support for <a href="https://jsr250.dev.java.net/" target="_new">JSR-250</a>, and that class, unlike others in the <tt>javax.annotation</tt> package, happens to be <a href="http://www.mail-archive.com/google-appengine-java@googlegroups.com/msg05241.html" target="_new">missing</a> <a href="http://code.google.com/p/googleappengine/issues/detail?id=2564" target="_new">from</a> the GAE whitelist.</p>
<h3>It ain&#8217;t over until the App Engine sings</h3>
<p>Moving back to a standard <tt>-servlet.xml</tt> file gets rid of the <tt>@Resource</tt> problem, but I was still left with an exception caused by Guice, which jclouds uses internally for dependency injection. I later discovered that the exception is relatively harmless and can be ignored<sup>2</sup>. But of course no developer likes exceptions &#8211; however harmless &#8211; in the boot logs, so I wondered whether executing this call earlier in the boot sequence might resolve the problem.</p>
<p>So I moved the offending call from the servlet to the application context, guessing that the <tt>ContextLoaderListener</tt> might have more permissions than a servlet:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;web-app&gt;
    &lt;!-- can't use Java sconfiguration due to GAE's security restrictions --&gt;
    &lt;context-param&gt;
        &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
        &lt;param-value&gt;/WEB-INF/tweetstoreContext.xml&lt;/param-value&gt;
    &lt;/context-param&gt;

    &lt;listener&gt;
        &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
    &lt;/listener&gt;

    &lt;servlet&gt;
    ...
</pre>
<p>And it worked! Or rather, it worked on the <a href="http://code.google.com/appengine/docs/java/tools/devserver.html" target="_new">Java Development Server</a>, the App Engine &#8220;simulator&#8221; provided with the SDK which is intended for development testing. <strong>But it didn&#8217;t work on App Engine itself</strong><sup>3</sup>.<br />
A word of caution, therefore: test on the &#8220;real&#8221; App Engine before concluding that something works, especially if it&#8217;s related to security restrictions!</p>
<h3>Salvaging some @AnnotationConfig</h3>
<p>By this time I knew that I wasn&#8217;t going to get away without writing at least a bit of Spring XML, but I was still trying to stick to Java as much as possible. After plenty of digging around in the Spring sources and a bit of experimentation, I discovered that, of the bean post processors <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-annotation-config" target="_new">currently registered by <tt>&lt;context:annotation-config/&gt;</tt></a><sup>4</sup> that I was interested in, only the <tt>CommonAnnotationBeanPostProcessor</tt> actually causes a problem. In fact, you can even use its immediate superclass, <tt>InitDestroyAnnotationBeanPostProcessor</tt>, which provides the <tt>@PostConstruct</tt> and <tt>@PreDestroy</tt> support I was looking for:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;beans xmlns=&quot;...&gt;
    &lt;!-- the usual &lt;context:annotation-config/&gt; can't be used because the
      CommonAnnotationBeanPostProcessor causes a security exception in GAE when it
      tries to load javax.annotation.Resource --&gt;
    &lt;bean class=&quot;org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor&quot; /&gt;
    &lt;bean class=&quot;org.springframework.context.annotation.ConfigurationClassPostProcessor&quot; /&gt;
    &lt;bean class=&quot;org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor&quot;&gt;
        &lt;property name=&quot;initAnnotationType&quot; value=&quot;javax.annotation.PostConstruct&quot; /&gt;
        &lt;property name=&quot;destroyAnnotationType&quot; value=&quot;javax.annotation.PreDestroy&quot; /&gt;
    &lt;/bean&gt;
    &lt;bean class=&quot;org.jclouds.demo.tweetstore.config.SpringServletConfig&quot; /&gt;
&lt;/beans&gt;
</pre>
<p>So if you can live without <tt>@Resource</tt>, it seems that you can get away with most of Spring&#8217;s annotation-driven configuration on the GAE.</p>
<div style="background-color: #EFEEE6; border: 1px solid grey; margin: 0.8em; padding: 0.8em;">
<strong>Debugging the Java Development Server</strong></p>
<p>The GAE SDK starts the Java Development Server using a platform-independent launcher called KickStart, which is quite <a href="http://code.google.com/p/jclouds/source/browse/trunk/demos/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/GoogleDevServer.java" target="_new">easy to integrate</a> into your test suite.<br />
Unfortunately, KickStart doesn&#8217;t start the server in a new <em>thread</em>, but in a completely separate <em>process</em>, so attaching a debugger from your IDE is, well, tricky.<br />
Luckily KickStart accepts <a href="http://andskiba.blogspot.com/2009/05/debugging-appengine-application-on.html" target="_new"><tt>jvm_flag</tt> arguments</a>, as outlined in the Javadocs<sup>5</sup>:</p>
<p><em>At present, the only valid option to KickStart itself is:<br />
&#8211;jvm_flag=&lt;vm_arg&gt;<br />
Passes &lt;vm_arg&gt; as a JVM argument for the child JVM. May be repeated</em></p>
<p>Here you can add the standard <a href="http://java.sun.com/javase/6/docs/technotes/guides/jpda/conninv.html#Invocation" target="_new">JVM debugging parameters</a>.
</div>
<div style="background-color: #EFEEEA; border: 1px solid #AAAAAA; margin: 0.8em; padding: 0.4em; font-size: 85%;">
<strong>Footnotes</strong></p>
<ol>
<li>Well, actually it&#8217;s running into a timeout at the time of writing, but that&#8217;s not related to the Spring config. Really <img src='http://blog.xebia.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </li>
<li>Which is to say that it doesn&#8217;t interrupt the bootstrapping process (it occurs in a separate thread), and your application will run fine. Here it is:
<p><code><br />
com.google.inject.internal.FinalizableReferenceQueue <init>: Failed to start reference finalizer thread. Reference cleanup will only occur when new references are created.<br />
java.lang.reflect.InvocationTargetException<br />
...<br />
  at com.google.inject.internal.InjectorBuilder.initializeStatically(InjectorBuilder.java:134)<br />
  at com.google.inject.internal.InjectorBuilder.build(InjectorBuilder.java:108)<br />
  at com.google.inject.Guice.createInjector(Guice.java:93)<br />
  at com.google.inject.Guice.createInjector(Guice.java:70)<br />
</code></li>
<li>I suspect this has something to do with how and when the security manager is installed in the Dev Server, but haven&#8217;t investigated this in any detail.</li>
<li>The Spring docs don&#8217;t mention <tt>ConfigurationClassPostProcessor</tt>, for some reason, but according to <a href="http://static.springsource.org/spring/docs/3.0.0.RELEASE/api/org/springframework/context/annotation/ConfigurationClassPostProcessor.html" target="_new">its Javadoc</a> it is <em>&#8220;Registered by default when using &lt;context:annotation-config/&gt; or &lt;context:component-scan/&gt;.&#8221;</em>
<li>Which don&#8217;t appear to be available online, for some reason.</li>
</ol>
</div>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2010/01/17/using-springs-java-configuration-on-google-app-engine/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2010%2F01%2F17%2Fusing-springs-java-configuration-on-google-app-engine%2F&amp;title=Using%20Spring%20JavaConfig%20on%20Google%20App%20Engine" id="wpa2a_2"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2010/01/17/using-springs-java-configuration-on-google-app-engine/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
<!-- This Quick Cache file was built for (  blog.xebia.com/tag/google-app-engine/feed/ ) in 0.61943 seconds, on Feb 9th, 2012 at 5:58 pm UTC. -->
<!-- This Quick Cache file will automatically expire ( and be re-built automatically ) on Feb 9th, 2012 at 6:58 pm UTC -->
