<?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>Gridshore &#187; google appengine</title>
	<atom:link href="http://www.gridshore.nl/tag/google-appengine/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.gridshore.nl</link>
	<description>A weblog about software engineering, Architecture, Technology an other things we like.</description>
	<lastBuildDate>Tue, 13 Dec 2011 15:36:58 +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>Doing grails, yes I like it</title>
		<link>http://www.gridshore.nl/2009/11/09/doing-grails-yes-i-like-it/</link>
		<comments>http://www.gridshore.nl/2009/11/09/doing-grails-yes-i-like-it/#comments</comments>
		<pubDate>Mon, 09 Nov 2009 07:30:54 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[groovy and grails]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[google appengine]]></category>
		<category><![CDATA[grails]]></category>
		<category><![CDATA[intellij]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=920</guid>
		<description><![CDATA[<p>Last week I attended a groovy &#038; grails training by SpringSource. My first introduction into grails is about 2 years a go. I attended a talk at the spring experience. Back than I liked it, tried it, but did not really use it. By now a lot has changed, most of all very good [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.gridshore.nl/wp-content/uploads/F0720E8F-2336-4FEE-BB96-7F8FA9B9FD9C.jpg" alt="F0720E8F-2336-4FEE-BB96-7F8FA9B9FD9C.jpg" border="0" width="134" height="117" align="left" />Last week I attended a <a href="http://www.springsource.com/training/grv001">groovy &#038; grails training</a> by SpringSource. My first introduction into grails is about 2 years a go. I attended a talk at the spring experience. Back than I liked it, tried it, but did not really use it. By now a lot has changed, most of all very good tool integration by <a href="http://www.jetbrains.com/idea/nextversion/">intellij</a>. Last week I had the change to go to a training, now I am motivated to start using grails more often.</p>
<p>This post I will talk you through a grails application I have created for a project of mine. I also take you through some of the things I learned last week. Finally I&#8217;ll show you that you can create a google app engine application using grails. There are ways to create grails applications, I&#8217;ll show you how to do it using the latest intellij 9 beta release.</p>
<p><span id="more-920"></span><br />
<h2>Training</h2>
<p>As mentioned in the introduction I attended the spring source groovy and grails training. The training was given by Peter Ledbrook, author of <a href="http://www.manning.com/gsmith/">grails in action</a>. I am not going to give a detailed description of the training. I did like the training, it gave a good overview of the possibilities of grails as well as the groovy language. And yes, I am now very interested in the options of groovy. Especially for creating web based applications with grails, groovy just shines. Not sure when I should use groovy and when normal java. Have to explore to find out. Some of the things I liked about groovy are:</p>
<ul>
<li>Assignment of parameters that are evaluated immediately ${age} or when used ${->age}</li>
<li>Using negative indexes in arrays: [1 .. -2] strips of the first and last item from an array</li>
<li>Groovy truth, explicit use of values in a comparison. null, 0, &#8220;&#8221; and [] are all false in a comparison</li>
<li>Closures, still hard to determine when to use a closure and when a method. But closures are used very often in groovy.</li>
<li>Out of the box test integration with things like: MockFor, Expando, and as a plugin GMock.</li>
</ul>
<p>Of course we learned a lot more than this, check the training or the book yourself if you want more. Next up was grails. I did look at grails before at grails, but tool support was pretty limited back than, and the plugins were not really widely available. A lot has changed since than. SpringSource came out with grails support in SpringSource Tool Suite, and Intellij has grails support as well. To be honest, intellij was much more productive than STS. Actually STS was almost not useable. Since it was the first release with grails support it will most probably improve the coming releases. Intellij worked very nice out of the box (I did use the beta version of intellij 9. Some of the features I liked during the training are:</p>
<ul>
<li>Gorm, I must mention this Groovy/Grails Object Relational Mapping framework first. This is very important for grails and why it is so productive. I just love these dynamic finders (more later).</li>
<li>Plugin architecture, the easy of installtion and usage of plugins is very nice. I like the db-util plugin for its simplicity and the help when working with internal memory databases. A killer plugin during development.</li>
<li>Scaffolding, for auto responding to CRUD like operations.</li>
<li>flash parameter to be used for adding something to the session for just one request. Ideal for passing messages.</li>
<li>Using templates, ideal for doing ajax calls and reuse of small view elements.</li>
</ul>
<p>Oke time to get our hands dirty, next up is a short introduction in the sample I am going to create. Than some code (which is acutally not that much)</p>
<h2>The application to create</h2>
<p>For a customer at <a href="http://www.jteam.nl">JTeam</a>, we have a large amount of servers that we need to prepare. The actual preparation is mostly done by the hosting provider. Sometime we have no idea what the status is of some servers. We started to use an excel sheet to communicate the status among our team. This is not ideal and I decided to create a small grails application for this. It&#8217;s all very basic, but useable.</p>
<p>Every server has a status, some comments and an external ip address. Each server is also part of a number of vlans and belongs to an environment (dev,test,accep,prod).</p>
<h2>The code</h2>
<p>The code is available online at github. Yes I know, it is not at google code. I got extra motivated to start using git since the training. Peter was working so flexible with his source code, I want that too. The best way to learn something is by doing it. Therefore I create a git repository at github. You can find out more at the following url. There is a very easy way to download the complete source code without using git, check the page.</p>
<p><a href="http://github.com/jettro/MyServerPark">http://github.com/jettro/MyServerPark</a></p>
<h2>The basics</h2>
<p>Starting a grails project is very well documented on the grails website. Except for one controller, the OverviewController, all controllers use: def scaffold = true. Which means I don&#8217;t write any code. Also not view components. I did create some domain classes that have relationships with each other. The next sections cover the different elements of the application.</p>
<h3>The domain model</h3>
<p><img src="http://www.gridshore.nl/wp-content/uploads/DomainModelServerpark.png" alt="DomainModelServerpark.png" border="0" width="555" height="376" align=" center" /></p>
<p>Some things to know about the domain model:</p>
<ul>
<li>belongsTo is used to declare a relationship of many-to-one, the next line gives an example for Comment. This gives the comment a property server.</li>
<p>static belongsTo = [server:Server]</p>
<li>The comment class also gives meta data about the mapping and the type used for the database as well as constraints. In the example we create a field for larger amounts of text.</li>
<pre class="brush: groovy; title: ; notranslate">
class Comment {
    String name
    String content

    static belongsTo = [server:Server]

    static mapping = {
        content type: &quot;text&quot;
    }

    static constraints = {
        name(blank:false, maxSize:50)
        content(blank:false, widget:&quot;textarea&quot;)
    }
}
</pre>
<li>The previous code block also shows one of the things that might be a bit strange. With <strong>widget:&#8221;textarea&#8221;</strong> you indicate the type of field to be used at the front end. Might be a bit strange in a domain model.</li>
<li>A one-to-many relationship is also easy to implement, check the following line from Environment:</li>
<p>static hasMany = [servers:Server]
</ul>
<p>Check the code for more examples of relationships.</p>
<h3>Scaffolding controllers and views</h3>
<p>Grails makes use of scaffolding, this can be static and dynamic. In the static case, code is being generated and can be altered. The dynamic case is evaluated runtime. In this project I tried to use dynamic scaffolding as much as possible. Usability might not always be what you want. In that case you should use static scaffolding or create something yourself. I managed to do well with the scaffolding on dynamic (except for the google app engine sample). But let us focus on the customer controller.</p>
<h2>The overview controller</h2>
<p>Grails makes use of convention over configuration. This is also true for controllers and views. The overview controller listens to the /overview url and points to the overview.gsp file. The following code block gives the complete OverviewController groovy class.</p>
<pre class="brush: groovy; title: ; notranslate">
class OverviewController {
    def show = {
        redirect(uri:&quot;/server/show/${params.id}&quot;)
    }

    def comments = {
        def currentServer = Server.findById(params.id.toLong())
        def allComments = Comment.withCriteria {
            server {
                eq(&quot;id&quot;,currentServer.id)
            }
        }
        render(template:&quot;/shared/comment&quot;,model:[comments:allComments, server:currentServer])
    }

    def index = {
        def environments = Environment.list()
        [environments:environments]
    }
}
</pre>
<p>There are three methods in the controller. The show does a redirect to the show method of the server controller. The index returns list of all environments and uses the view index.gsp. The comments method is a different cup of thee. This responds to an ajax call and returns a fragment. focus on the last line for now. You can see we use the render call. This makes use of a template. Using the render call, we obtain the html and push it back to the client. The section about views will give a bit more detail. Next up are the dynamic finders</p>
<h3>Dynamic finders</h3>
<p>The previous code block gives a few examples of finders. In index we obtain all the environments with <strong>Environment.list()</strong>. This is the most basic finder. Another finder is in the comments method. There we obtain the server by an id. The call is findServerById and you provided an id. Another calls could be: findByFunction, findByFunctionLike &#8220;%database%&#8221;, findByFunctionIlike &#8220;%DataBase%&#8221;. You can also make combinations with And/Or and multiple parameters. Pretty cool.</p>
<p>The comments method also shows the Criteria API for looking up all comments for a specific server. These type of queries, limited by a related item, are not supported by the dynamic finders.</p>
<h3>Gsp for views</h3>
<p>Creating the views is not very hard. If you want to learn how it works, I suggest generating the scaffolding views. I want to focus on something that is just a little bit more advanced. Ajax calls. In my project I want to obtain all comments for a server using an ajax call. In the overview page we use a special tag from grails, the remoteLink. This tag does an ajax call to the server and prints the result in the div with provided id.</p>
<p>&lt;g:remoteLink action=&#8221;comments&#8221; params=&#8221;[id:server.id]&#8221; update=&#8221;comments&#8221;&gt;comments&lt;/g:remoteLink&gt;</p>
<p>As you can see, we provide the <strong>server.id</strong> and we update the div with id <strong>comments</strong>.</p>
<p>This does not work out of the box, you must specify the prototype javascript library to be included. You can do this in the file:</p>
<p>views > layouts > main.gsp</p>
<p>Add the following line:</p>
<p>&lt;g:javascript library=&#8221;prototype&#8221; /&gt;</p>
<p>Now everything should be fine and you can test the application. A command like grails run-app should be enough.</p>
<h2>Documentation</h2>
<p>If you want more information about grails, try the following references:</p>
<ul>
<li><a href="http://grails.org/doc/1.1.x/">http://grails.org/doc/1.1.x/</a></li>
<li><a href="http://groovy.codehaus.org/groovy-jdk/">http://groovy.codehaus.org/groovy-jdk/</a></li>
<li><a href="http://www.manning.com/gsmith/">http://www.manning.com/gsmith/</a></li>
<li><a href="http://www.jetbrains.com/idea/nextversion/index.html">http://www.jetbrains.com/idea/nextversion/index.html</a></li>
<li><a href="http://www.springsource.com/training/grv001">http://www.springsource.com/training/grv001</a></li>
<li><a href="http://www.springsource.com/products/sts">http://www.springsource.com/products/sts</a></li>
</ul>
<h2>Grails and google app engine</h2>
<p>Grails uses plugins for all additional functionality. There is also a plugins available for google app engine. There is already good documentation available for this plugin. Therefore I keep this short. The following code block shows the commands. For more information, check the website of the plugin:</p>
<p><a href="http://grails.org/plugin/app-engine">http://grails.org/plugin/app-engine</a><br />
<br/></p>
<pre>
# grails create-app share-this
# grails uninstall-plugin hibernate
# grails install-plugin app-engine
choose jpa when asked
# export APPENGINE_HOME=&lt;path to your sdk install of google app engine&gt;
# grails app-engine run
# grails set-version 1
# grails app-engine package
# $APPENGINE_HOME/bin/appcfg.sh update ./target/war
# grails install-plugin gorm-jpa
</pre>
<p>Than I used intellij to create some domain classes and controllers. Take the following into consideration.</p>
<ul>
<li>Put domain classes in a package or it won&#8217;t work</li>
<li>Put Controller classes in the same package</li>
<li>generate views, the auto scaffolding seems not to work.</li>
</ul>
<p>You can look at the result here : <a href="http://share-this.appspot.com/">http://share-this.appspot.com/</a>. It could well be that the app does not start the first time, a refresh might help. I&#8217;ll have a look at this in the future. There is a problem with the CPU consumption and my grails application.</p>
<div class='dd_post_share'><div class='dd_buttons'><div class='dd_button'><iframe src='http://widgets.dzone.com/links/widgets/zoneit.html?url=http%3A%2F%2Fwww.gridshore.nl%2F2009%2F11%2F09%2Fdoing-grails-yes-i-like-it%2F&amp;title=Doing%20grails%2C%20yes%20I%20like%20it&amp;t=2' height='25' width='155' frameborder='0' scrolling='no'></iframe></div></div><div style='clear:both'></div></div><!-- Social Buttons Generated by Digg Digg plugin v4.5.3.4, 
    Author : Yong Mook Kim
    Website : http://www.diggdigg2u.com -->]]></content:encoded>
			<wfw:commentRss>http://www.gridshore.nl/2009/11/09/doing-grails-yes-i-like-it/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Serving static files in Google app engine development edition</title>
		<link>http://www.gridshore.nl/2009/06/26/serving-static-files-in-google-app-engine-development-edition/</link>
		<comments>http://www.gridshore.nl/2009/06/26/serving-static-files-in-google-app-engine-development-edition/#comments</comments>
		<pubDate>Fri, 26 Jun 2009 21:51:22 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[google appengine]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=811</guid>
		<description><![CDATA[<p>There are a lot of questions about serving static files in the development edition of google app engine. There are also a few answers, but none of them gave me a clear solution. Therefore I decided to look for one myself. In the end I have created a sub-optimal solution that works for me. [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.gridshore.nl/wp-content/uploads/appengine-silver-120x30.gif" alt="appengine-silver-120x30.gif" border="0" width="120" height="30" align="left" />There are a lot of questions about serving static files in the development edition of google app engine. There are also a few answers, but none of them gave me a clear solution. Therefore I decided to look for one myself. In the end I have created a sub-optimal solution that works for me. So maybe it can work for you as well.</p>
<p>Read on to find out what I did.</p>
<p><span id="more-811"></span>
<p>Google app engine uses the concept of static files. This is a performance optimization. Using the file appengine-web.xml you can configure the way google handles static files. You can include and exclude certain files using their extension or name. More information can be found <a href="http://code.google.com/appengine/docs/java/gettingstarted/staticfiles.html">here at google</a>. This all works nice in the online version, however there seems to be a problem with the development server. Some solutions try to configure the local version as well, still that did not work for me. I decided to look for a servlet that serves static files. Yes it can be that easy.</p>
<p>Check the following post serving <a href="http://stackoverflow.com/questions/132052/servlet-for-serving-static-content">static content using a servlet</a>. This post gives you a servlet implementation to serve static files. I used the StaticServlet.java, read the post for more information. Adding this servlet to your web.xml solves the problems in your local environment.</p>
<pre class="brush: xml; title: ; notranslate">
    &lt;servlet&gt;
        &lt;servlet-name&gt;default&lt;/servlet-name&gt;
        &lt;servlet-class&gt;org.yourscrum.web.StaticServlet&lt;/servlet-class&gt;
        &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
    &lt;/servlet&gt;

    &lt;servlet-mapping&gt;
        &lt;servlet-name&gt;default&lt;/servlet-name&gt;
        &lt;url-pattern&gt;*.png,*.jpg,*.css,*.js&lt;/url-pattern&gt;
    &lt;/servlet-mapping&gt;
</pre>
<p>That is it, now you can test your stuff locally and all your scripts, images, styles are loaded by your application. Of course you have to remove this servlet before uploading your application.</p>
<p>Hope it helps people with their local debugging of jquery scripts or other javascript things. Speaking about jquery, the next post will be about a component used for sorting items using the jquery ui component. I had an issue adding an image to the items in the sortable component.</p>
<div class='dd_post_share'><div class='dd_buttons'><div class='dd_button'><iframe src='http://widgets.dzone.com/links/widgets/zoneit.html?url=http%3A%2F%2Fwww.gridshore.nl%2F2009%2F06%2F26%2Fserving-static-files-in-google-app-engine-development-edition%2F&amp;title=Serving%20static%20files%20in%20Google%20app%20engine%20development%20edition&amp;t=2' height='25' width='155' frameborder='0' scrolling='no'></iframe></div></div><div style='clear:both'></div></div><!-- Social Buttons Generated by Digg Digg plugin v4.5.3.4, 
    Author : Yong Mook Kim
    Website : http://www.diggdigg2u.com -->]]></content:encoded>
			<wfw:commentRss>http://www.gridshore.nl/2009/06/26/serving-static-files-in-google-app-engine-development-edition/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Java on Google app engine with intelliJ</title>
		<link>http://www.gridshore.nl/2009/04/08/java-on-google-app-engine-with-intellij/</link>
		<comments>http://www.gridshore.nl/2009/04/08/java-on-google-app-engine-with-intellij/#comments</comments>
		<pubDate>Wed, 08 Apr 2009 22:19:02 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[appengine]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[google appengine]]></category>
		<category><![CDATA[intellij]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=737</guid>
		<description><![CDATA[<p>This is a short post about the new java support for google appengine. The Basic steps are described very well at google, check the getting started manual. Here I just describe my experiences with my first java based application for google appengine. I concentrate on the usage of intellij. In coming posts I will [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.gridshore.nl/wp-content/uploads/appengine-silver-120x30.gif" alt="appengine-silver-120x30.gif" border="0" width="120" height="30" align="left" />This is a short post about the new java support for google appengine. The Basic steps are described very well at google, check the <a href="http://code.google.com/appengine/docs/java/gettingstarted/">getting started manual</a>. Here I just describe my experiences with my first java based application for google appengine. I concentrate on the usage of intellij. In coming posts I will create the same application as the one I used for my previous post: <a href="http://www.gridshore.nl/2008/10/09/using-google-appengine/">using google appengine</a>.</p>
<p><span id="more-737"></span><br />
<h2>Quick intro</h2>
<p>For an eclipse user there are other steps to get things done. There is something like a plugin that might work depending on other plugins that you have installed and some eclipse magic. Sorry, I am a non believer. I prefer another IDE.</p>
<p>So for the non eclipse guys you need to download a zip file with all the resources you need to start working with the new sdk. I create a symbolic link to the downloaded version, that way it is easy to change for future releases.</p>
<p><code>ln -s appengine-java-sdk-1.2.0/ appengine-java-sdk</code></p>
<p>As the getting started suggest, you can now test your infrastructure with one of the provided demo&#8217;s.</p>
<p><code>./appengine-java-sdk/bin/dev_appserver.sh appengine-java-sdk/demos/guestbook/war/</code></p>
<p>Open your browser and go to the link <a href="http://localhost:8080/">http://localhost:8080/</a>. You should see the following screen.</p>
<div style="text-align:center;"><img src="http://www.gridshore.nl/wp-content/uploads/screendump-google-demoapp.png" alt="Screendump_google_demoapp.png" border="0" width="300" height="190" /></div>
<p>Oke, time to take the next step. The structure for an application is the same as for a web archive. There is a catch, you cannot use the war file itself, you need the exploded directory. Luckily it is very easy to do this with maven or with Intellij. Those eclipse users that are still reading this post have an easier life. They can use the wizard from the google plugin. I start off with a normal intellij java project with a web facet.</p>
<p>Google app engine works with servlets, so we need to create a servlet, we also need to add this servlet to the web.xml. Since the code I used is at the google tutorial, I&#8217;ll not repeat it here.</p>
<p>Google appengine needs an additional xml configuration file. This file is called <em></em> and it looks like this:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;appengine-web-app xmlns=&quot;http://appengine.google.com/ns/1.0&quot;&gt;
    &lt;application&gt;&lt;/application&gt;
    &lt;version&gt;1&lt;/version&gt;
&lt;/appengine-web-app&gt;
</pre>
<p>Next step in intelliJ is to make the module, you can find the exploded war in the folder out > exploded > GoogleAppEngineGuestbookWeb. Using this exploded folder you can start the appengine. We need a runner in intellij. This is not very hard to do.There are two important steps. The first step is to create a library that you add to your module. This library contains one jar file : <strong>appengine-tools-api.jar</strong>. You can find this jar in the distribution of google appengine you downloaded. If you do not know how to add a library, open the module settings (apple: command + <img src='http://www.gridshore.nl/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> . Create a new library and when asked say yes to add it to your module. The screen should look like the following image.</p>
<div style="text-align:center;"><img src="http://www.gridshore.nl/wp-content/uploads/intellij-configure-library.png" alt="Intellij_configure_library.png" border="0" width="400" height="261" /></div>
<p>Next up is configuring a runner. Create a runner of type <strong>Application</strong>. Now use the script <strong>dev_appserver.sh</strong>, that you can find in the distribution of google appengine in the bin folder. We need to set the environment variables, the program parameters and the main class.</p>
<h3>Main class</h3>
<p><code>com.google.appengine.tools.KickStart</code></p>
<h3>Program parameters</h3>
<p><code><br />
com.google.appengine.tools.development.DevAppServerMain<br />
out/exploded/GoogleAppEngineGuestbookWeb<br />
</code></p>
<p>Check the second parameter, this is the location of the exploded war file that intellij creates for you.</p>
<h3>Environment variables</h3>
<p><code><br />
SDK_LIB=YOUR_GOOGLE_APPENGINE_HOME/appengine-java-sdk/lib<br />
SDK_CONFIG=YOUR_GOOGLE_APPENGINE_HOME/appengine-java-sdk/config/sdk<br />
</code></p>
<p>The screen for configuring your runner now looks like this</p>
<div style="text-align:center;"><img src="http://www.gridshore.nl/wp-content/uploads/intellij-configure-runner.png" alt="Intellij_configure_runner.png" border="0" width="600" height="363" /></div>
<p>That is about it, now you can run the application. After running, the output in the console is:</p>
<p><code><br />
2009-04-08 23:53:44.332 java[3557:10b] [Java CocoaComponent compatibility mode]: Enabled<br />
2009-04-08 23:53:44.333 java[3557:10b] [Java CocoaComponent compatibility mode]: Setting timeout for SWT to 0.100000<br />
The server is running at http://localhost:8080/<br />
</code></p>
<p>Now you can point your browser to the following url : <a href="http://localhost:8080/guestbook">http://localhost:8080/guestbook</a> and <strong>Hello world</strong> should be yours.</p>
<h2>Deployment</h2>
<p>Before you can upload, you need to register yourself with google. If you already have an appengine account, you can request the java beta admittance. After that create a new google appengine application in your domain. That&#8217;s it, remember the name of the app you just registered because you need it in the next step.</p>
<p>Next up is the actual deployment, this is not a very complicated process. You can use the same directory that you use for the test server. Be sure to change the file <strong>appengine-web.xml</strong>. Add your name of the application to the application tag. If your using intellij do not forget to make the module. In my case this application name is doingjava. Now all you need during the upload is your google account name and password. Next is the command to do the actual upload</p>
<p><code><br />
./appengine-java-sdk/bin/appcfg.sh update PATH_TO_YOUR_INTELLIJAPP/out/exploded/GoogleAppEngineGuestbookWeb<br />
</code></p>
<p>In my case you can check if it works on the following url: <a href="http://doingjava.appspot.com/guestbook">http://doingjava.appspot.com/guestbook</a>.</p>
<h2>Conclusion</h2>
<p>This is not a conclusion on the usage of google appengine and java. For me it was an exercise to create a project in intellij and be able to use the google mock webapp runner. This seems to work nicely. The future will bring more posts about google appengine which now support java.</p>
<p>I do want to stress this is not a best practice, I advise to use an ant script that you can get from google at the following url. <a href="http://code.google.com/appengine/docs/java/tools/ant.html">http://code.google.com/appengine/docs/java/tools/ant.html</a></p>
<h2>Some important url&#8217;s</h2>
<ul>
<li><a href="http://www.gridshore.nl/2008/10/09/using-google-appengine/">http://www.gridshore.nl/2008/10/09/using-google-appengine/</a></li>
<li><a href="http://appengine.google.com/">http://appengine.google.com/</a></li>
<li><a href="http://code.google.com/appengine/docs/java/gettingstarted/">http://code.google.com/appengine/docs/java/gettingstarted/</a></li>
<li><a href="http://code.google.com/appengine/docs/java/tools/ant.html">http://code.google.com/appengine/docs/java/tools/ant.html</a></li>
</ul>
<div class='dd_post_share'><div class='dd_buttons'><div class='dd_button'><iframe src='http://widgets.dzone.com/links/widgets/zoneit.html?url=http%3A%2F%2Fwww.gridshore.nl%2F2009%2F04%2F08%2Fjava-on-google-app-engine-with-intellij%2F&amp;title=Java%20on%20Google%20app%20engine%20with%20intelliJ&amp;t=2' height='25' width='155' frameborder='0' scrolling='no'></iframe></div></div><div style='clear:both'></div></div><!-- Social Buttons Generated by Digg Digg plugin v4.5.3.4, 
    Author : Yong Mook Kim
    Website : http://www.diggdigg2u.com -->]]></content:encoded>
			<wfw:commentRss>http://www.gridshore.nl/2009/04/08/java-on-google-app-engine-with-intellij/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Using google appengine</title>
		<link>http://www.gridshore.nl/2008/10/09/using-google-appengine/</link>
		<comments>http://www.gridshore.nl/2008/10/09/using-google-appengine/#comments</comments>
		<pubDate>Thu, 09 Oct 2008 21:30:20 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[gdata]]></category>
		<category><![CDATA[google appengine]]></category>
		<category><![CDATA[google docs]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=272</guid>
		<description><![CDATA[<p>When attending the JAOO in Denmark, I was amazed by the easy setup of google application engine. There is a good step by step guide to creating a hello world application. It would be silly to recreate that guide here. Therefore this post takes a different approach. I&#8217;ll explain what kind of steps you [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.gridshore.nl/wp-content/uploads/appengine-logo.jpg" alt="appengine_logo.jpg" border="0" width="100" height="79" align="left" />When attending the JAOO in Denmark, I was amazed by the easy setup of google application engine. There is a good step by step guide to creating a hello world application. It would be silly to recreate that guide here. Therefore this post takes a different approach. I&#8217;ll explain what kind of steps you need to take between downloading the SDK and looking at your application online. I&#8217;ll also talk about my experiences in getting a somewhat more difficult application running, the actual integration with google docs. How to get a list of all of your documents on the screen?</p>
<p>Read on if your are interested in the possibilities of google apps.</p>
<p>I do want to give a warning, this is my first google apps experience and on top of that also my first Python experience. Do not take this code as a best practice, just learn about the possibilities.</p>
<p><span id="more-272"></span>
<p>Starting your first google apps engine application starts by downloading the right software and registering. By registering yourself, you get the rights to register and deploy a certain amount of applications. At the time of writing it is ten applications. If you do not want to pay, there are some limitations in the amount of storage that you get and the amount of visits your application can receive. It is a fair way of setting your first steps, I think it will take a while before you reach your limits. Unless you want to store images, documents or videos within your application. If that is what you are up to, you are better of using the other services of google and than integrate with these services. There are apis for google docs, images, mail, calendar and lots of other services. That was one of the reasons I wanted to try this integration.</p>
<p>During the JAOO I followed the following tutorial, it took me around an hour including downloads and uploads. This is a nice way of getting up to speed.</p>
<p><a href="http://code.google.com/appengine/docs/gettingstarted/">http://code.google.com/appengine/docs/gettingstarted/</a></p>
<p>Time to introduce my application, I am going to create an application that shows all your documents within google docs. Sounds impossible? Well it isn&#8217;t. Let&#8217;s start with the basic elements of the application:</p>
<ul>
<li>app.yaml &#8211; config file of the application redirecting all calls to the mydocs.py script.</li>
<li>main.css &#8211; just like you think, a stylesheets in the static stylesheets folder</li>
<li>index.html &#8211; template file with html and placeholders</li>
<li>mydocs.py &#8211; the python script containing all important code</li>
</ul>
<p>For now, focus on the python script. The first time I show this code, it contains only the generation of the login or the logout link.</p>
<pre class="brush: python; title: ; notranslate">
import os
from google.appengine.ext.webapp import template
import cgi

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class MainPage(webapp.RequestHandler):
  def get(self):

    if users.get_current_user():
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Logout'
    else:
      url = users.create_login_url(self.request.uri)
      url_linktext = 'Login'

    template_values = {
      'url': url,
      'url_linktext': url_linktext,
      }

    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, template_values))

application = webapp.WSGIApplication(
                                     [('/', MainPage)],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == &quot;__main__&quot;:
  main()
</pre>
<p>What can you see in this code? First of all, some imports. We use the users object and the special webapp and a templating engine. Then you see a class called MainPage. This class responds to the root, as is configured in the construction of the application using the special webapp method WSGIApplication. The final part is the actual runner. The MainPage class contains code to check if the current is logged in and it changes the text and the presented link based on this information. You can also see the templating in action. The values are set, then the template file with placeholders is chosen and finally the output is rendered.</p>
<p>If you want to check out the sources of my application, go to my google code project.</p>
<p><strong><a href="http://code.google.com/p/gridshore/">http://code.google.com/p/gridshore/</a></strong></p>
<p>With all the files in place, we can start our first test run. Google provides a test environment, there are some facilities for mocking a login form, the database, and other things as well. Another thing that comes out of the box is a special admin console. Here you can get more information about what happens in your application and you can issue python command in a command line environment.</p>
<p>Run the application using the following command and go to the two provided urls. The image presented is the mentioned admin console.</p>
<p><strong>dev_appserver.py jettrodocs</strong> &#8211; Starts the developement application server.<br />
<a href="http://localhost:8080/">http://localhost:8080/</a> &#8211; locally running application<br />
<a href="http://localhost:8080/_ah/admin/">http://localhost:8080/_ah/admin/</a> &#8211; admin console</p>
<div style="text-align:center;"><img src="http://www.gridshore.nl/wp-content/uploads/localdevconsolegoogleapps.png" alt="localdevconsolegoogleapps.png" border="0" width="928" height="586" /></div>
<p>Now we upload the application for the first time. In the command jettrodocs is the directory that contains all my sources. Therefore you must issue the command one directory higher than your sources.</p>
<p><strong>appcfg.py update jettrosdocs</strong></p>
<p>My application is now deployed to the live google environment. Next I&#8217;ll give you the url. As a developer of your own applications, you also have access to an online dashboard with all different kind of information about your running application. This is also the place where you can register your application.</p>
<p><a href="http://docsjettro.appspot.com/">http://docsjettro.appspot.com/</a> &#8211; The running application<br />
<a href="http://appengine.google.com/">http://appengine.google.com/</a> &#8211; The dashboard for all your apps</p>
<div style="text-align:center;"><img src="http://www.gridshore.nl/wp-content/uploads/googleappsonlineconsole.png" alt="googleappsonlineconsole.png" border="0" width="963" height="679" /></div>
<p>Up till now, I have shown you the hard way of starting the application, uploading your application, typing the url&#8217;s to go to your local console and the online dashboard. Basically because I use the terminal for a large part of my day, I feel comfortable with it. There however a nice other way. That is the <em>GoogleAppEngineLauncher</em>. This small app enables you to start, stop, upload your application by pushing some buttons. One nice thing is that you can run your apps on different ports easily, so you can keep on developing them at the same time. The following images gives a screen dump of this google app engine launcher.</p>
<div style="text-align:center;"><img src="http://www.gridshore.nl/wp-content/uploads/googleappenginelauncher.png" alt="GoogleAppEngineLauncher.png" border="0" width="567" height="404" /></div>
<p>The final step is getting the document retrieval working. This turned out to be more difficult than I expected. There is a lot of information to be found on the web, some very good documents as well as nice examples. In the end I managed to get it working. I&#8217;ll focus on the bits that were harder for me to grasp. be sure to check out documentation from google. Check the references at the end for a few of the articles I used to get this going.</p>
<p>To be able to connect to google docs api, or feeds, your application needs to be approved by the user that runs it. The whole approval works with a token that is generated and than passed from the authentication service of google to your application. A user gets to see a special google screen that asks him to approve the access to the documents. Next to this approval, the user needs to be logged in as well. So without the user logging in, the application cannot see the documents. By default the mentioned token is only valid for 1 request. There is a mechanism to store the token in the session, that way it will be valid during the complete session.</p>
<p>When the user has authorized the application access to his documents and the user is logged in, the application can do a query for the documents and than print it on the screen.</p>
<p>Time to have a look at the code, for a complete view of the file, please <a href="http://code.google.com/p/gridshore/source/browse/trunk/python/jettrosdocs/mydocs.py" target="_blank">click here</a>. First let&#8217;s have a look at the get function that is called when a request comes in. We have seen most of it already, therefore we begin with the new stuff. The following piece of code analyzes the requested url and reads the token as well as the token_scope. To be honest, I think I could have hard coded this token_scope since I am only reading one feed. In the original example you could enter your own feed. Other than that the code speaks for itself.</p>
<pre class="brush: python; title: ; notranslate">
for param in self.request.query.split('&amp;'):
  # Get the token scope variable we specified when generating the URL
  if param.startswith('token_scope'):
    self.token_scope = urllib.unquote_plus(param.split('=')[1])
  # Google Data will return a token, get that
  elif param.startswith('token'):
    self.token = param.split('=')[1]
</pre>
<p>Next steps are authenticating the user and checking the session for an existing token. I&#8217;ll get back to that later on. Next step is do the actual call to the feed and read the documents from the feed. The feed is called in a separate method. When this method throws an error, the following code reads the error message and stores it in the template values collection. This error handling is done in the following piece of code.</p>
<pre class="brush: python; title: ; notranslate">
documents=[]
responseMessage = ''
try:
  documents = self.FetchFeed()
except Exception, strerror:
  responseMessage = strerror
</pre>
<p>Finally the template is filled with values and outputted to the browser. That is pretty straightforward. Next step, the authentication.</p>
<pre class="brush: python; title: ; notranslate">
def ManageAuth(self):
  self.client = gdata.docs.service.DocsService()
  gdata.alt.appengine.run_on_appengine(self.client)
  if self.token and self.current_user:
    self.UpgradeAndStoreToken()

def UpgradeAndStoreToken(self):
  self.client.SetAuthSubToken(self.token)
  self.client.UpgradeToSessionToken()
  if self.current_user:
    # Create a new token object for the data store which associates the
    # session token with the requested URL and the current user.
    new_token = StoredToken(user_email=self.current_user.email(),
        session_token=self.client.GetAuthSubToken(), target_url=self.token_scope)
    new_token.put()
def LookupToken(self):
  if self.feed_url and self.current_user:
    stored_tokens = StoredToken.gql('WHERE user_email = :1',self.current_user.email())
    for token in stored_tokens:
      if self.feed_url.startswith(token.target_url):
        self.client.SetAuthSubToken(token.session_token)
        return
</pre>
<p>Here you are introduced with the gdata library. This is a google project to enable developers to easier integrate the google apis using python. You add the required files to your project, check the references for a link to the download and the tutorial. Using this library it becomes easy to add the token to the session, you just call the method UpgradeToSessionToken. The token are stored in the database, that way you can create different tokens for different feeds. Again something I probably could have lived without. Querying for the right token is done in the method LookupToken. We query for the tokens for the current user and look for a token for the requested feed.</p>
<p>Now that we have the token, we can finally call the feed and handle the result.</p>
<pre class="brush: python; title: ; notranslate">
def FetchFeed(self):
  # The following creation of the client is necessary for the case a client is not authenticated
  if not self.client:
    self.client = gdata.docs.service.DocsService()
    gdata.alt.appengine.run_on_appengine(self.client)

  try:
    return self.ListAllDocuments()
  except gdata.service.RequestError, request_error:
    # If fetching fails, then tell the user that they need to login to
    # authorize this app by logging in at the following URL.
    if request_error[0]['status'] == 401:
      # Get the URL of the current page so that our AuthSub request will
      # send the user back to here.
      next = self.request.uri
      auth_sub_url = self.client.GenerateAuthSubURL(next, self.feed_url,secure=False, session=True)
      raise Exception('&lt;a href=&quot;%s&quot;&gt;Click here to authorize this application to view the feed&lt;/a&gt;' % (auth_sub_url))
    else:
      raise Exception( 'Something else went wrong, here is the error object: %s ' % (str(request_error[0])))

def ListAllDocuments(self):
  feed = self.client.GetDocumentListFeed()
  documents = []
  for i, entry in enumerate(feed.entry):
    doc = Document()
    doc.title = entry.title.text.encode('UTF-8')
    doc.author = entry.author[0].name.text.encode('UTF-8')
    documents.append(doc)
  return documents
</pre>
<p>The ListAllDocuments method does the actual call and uses the result to create new Document instances that are than provide to the template engine. The FetchFeed function does an interesting thing. It handles exceptions. If the user is not authorized an exception is thrown with a link how a user can authorize the application to read his documents as described before. In case of any other errors, the error is just returned to the screen.</p>
<p>The application is done, you can deploy it using the command line tool or the gui. The actual solution looks like this.</p>
<div style="text-align:center;"><img src="http://www.gridshore.nl/wp-content/uploads/jettrosdocsscreensump.png" alt="JettrosDocsScreensump.png" border="0" width="624" height="369" /></div>
<p>You can try it out yourself here</p>
<p><strong><a href="http://docsjettro.appspot.com/docs">http://docsjettro.appspot.com/docs</a></strong></p>
<h3>References</h3>
<ul>
<li><a href="http://code.google.com/appengine/docs/gettingstarted/">getting started</a> &#8211; tutorial walking you through all the required steps to deploy a hello world application</li>
<li><a href="http://code.google.com/apis/documents/developers_guide_protocol.html">google docs protocol</a> &#8211; manual for the protocol of interacting with documents</li>
<li><a href="http://code.google.com/apis/documents/developers_guide_python.html">google docs python</a> &#8211; Manual for using python to interact with the google doc feeds.</li>
<li><a href="http://code.google.com/p/gdata-python-client/">gdata python client</a> &#8211; python client that acts as a wrapper around a lot of different google apis, including google docs and google authentication.</li>
<li><a href="http://code.google.com/appengine/docs/datastore/">using the google datastore</a> &#8211; manual for using the google datastore from python.</li>
<li><a href="http://code.google.com/apis/accounts/docs/AuthSub.html">authentication module</a> &#8211; documentation for the google authentication model</li>
</ul>
<div class='dd_post_share'><div class='dd_buttons'><div class='dd_button'><iframe src='http://widgets.dzone.com/links/widgets/zoneit.html?url=http%3A%2F%2Fwww.gridshore.nl%2F2008%2F10%2F09%2Fusing-google-appengine%2F&amp;title=Using%20google%20appengine&amp;t=2' height='25' width='155' frameborder='0' scrolling='no'></iframe></div></div><div style='clear:both'></div></div><!-- Social Buttons Generated by Digg Digg plugin v4.5.3.4, 
    Author : Yong Mook Kim
    Website : http://www.diggdigg2u.com -->]]></content:encoded>
			<wfw:commentRss>http://www.gridshore.nl/2008/10/09/using-google-appengine/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

