<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

  <title><![CDATA[TechBeats]]></title>
  <link href="https://techbeats.deluan.com/atom.xml" rel="self"/>
  <link href="https://techbeats.deluan.com/"/>
  <updated>2021-07-11T16:51:46+00:00</updated>
  <id>https://techbeats.deluan.com/</id>
  <author>
    <name><![CDATA[Deluan Quintão]]></name>
    
  </author>
  <generator uri="http://octopress.org/">Octopress</generator>

  
  <entry>
    <title type="html"><![CDATA[Processing large templates with Gradle and FreeMarker]]></title>
    <link href="https://techbeats.deluan.com/processing-large-templates-with-gradle-and-freemarker/"/>
    <updated>2015-07-11T00:44:24+00:00</updated>
    <id>https://techbeats.deluan.com/processing-large-templates-with-gradle-and-freemarker</id>
    <content type="html"><![CDATA[<p><strong>TL;DR</strong> This article shows a solution for overcoming the issue <a href="https://issues.gradle.org/browse/GRADLE-3122">GRADLE-3122</a>.
You can <a href="https://techbeats.deluan.com/processing-large-templates-with-gradle-and-freemarker/#final-solution">jump straight to the implementation</a>
at the bottom of this post.</p>

<p>In my current project we have a need to generate a set of files for each environment, using templates. As this is a
<a href="http://gradle.org">Gradle</a> project, this requirement is easily accomplished with a <code>CopyTask</code>:</p>

<!-- more -->




<figure class='code'><figcaption><span>build.gradle</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
</pre></td><td class='code'><pre><code class='groovy'><span class='line'><span class="n">task</span> <span class="nf">processTemplates</span><span class="o">(</span><span class="nl">type:</span> <span class="n">Copy</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>     <span class="n">from</span> <span class="s1">&#39;src/templates&#39;</span><span class="o">,</span> <span class="o">{</span>
</span><span class='line'>         <span class="n">include</span> <span class="s1">&#39;**/*.*&#39;</span>
</span><span class='line'>     <span class="o">}</span>
</span><span class='line'>
</span><span class='line'>     <span class="kt">def</span> <span class="n">env</span> <span class="o">=</span> <span class="n">loadEnvironment</span><span class="o">()</span>
</span><span class='line'>     <span class="n">eachFile</span> <span class="o">{</span> <span class="n">FileCopyDetails</span> <span class="n">file</span> <span class="o">-&gt;</span>
</span><span class='line'>         <span class="k">if</span> <span class="o">(</span><span class="n">file</span><span class="o">.</span><span class="na">name</span><span class="o">.</span><span class="na">endsWith</span><span class="o">(</span><span class="s1">&#39;.template&#39;</span><span class="o">))</span> <span class="o">{</span>
</span><span class='line'>             <span class="n">expand</span><span class="o">(</span><span class="n">env</span><span class="o">)</span>
</span><span class='line'>             <span class="n">file</span><span class="o">.</span><span class="na">name</span> <span class="o">=</span> <span class="n">file</span><span class="o">.</span><span class="na">sourceName</span> <span class="o">-</span> <span class="s1">&#39;.template&#39;</span>
</span><span class='line'>         <span class="o">}</span>
</span><span class='line'>     <span class="o">}</span>
</span><span class='line'>
</span><span class='line'>     <span class="n">inputs</span><span class="o">.</span><span class="na">file</span> <span class="s2">&quot;env/${envName}.properties&quot;</span>
</span><span class='line'>     <span class="n">into</span> <span class="s2">&quot;$buildDir/output/$envName&quot;</span>
</span><span class='line'><span class="o">}</span>
</span><span class='line'>
</span><span class='line'><span class="kt">def</span> <span class="nf">getEnvName</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'>    <span class="n">hasProperty</span><span class="o">(</span><span class="s1">&#39;env&#39;</span><span class="o">)</span> <span class="o">?</span> <span class="n">env</span> <span class="o">:</span> <span class="s1">&#39;dev&#39;</span>
</span><span class='line'><span class="o">}</span>
</span><span class='line'>
</span><span class='line'><span class="kt">def</span> <span class="nf">loadEnvironment</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'>    <span class="kt">def</span> <span class="n">properties</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Properties</span><span class="o">()</span>
</span><span class='line'>    <span class="k">new</span> <span class="nf">File</span><span class="o">(</span><span class="s2">&quot;env/${envName}.properties&quot;</span><span class="o">).</span><span class="na">withInputStream</span> <span class="o">{</span> <span class="n">properties</span><span class="o">.</span><span class="na">load</span><span class="o">(</span><span class="n">it</span><span class="o">)</span> <span class="o">}</span>
</span><span class='line'>    <span class="n">properties</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>The <code>processTemplates</code> task above will copy all files from <code>src/templates</code> to <code>build/output/&lt;envName&gt;</code>. All files whose
name ends with <code>.template</code> will be processed and tokens (ex: <code>${variable}</code>) will be replaced by their values from the
<code>env/&lt;envName&gt;.properties</code> file. Adding the properties file as an input for the task is important (<code>inputs.file</code> method
call), so when you change it, the task will be re-executed on the next build.</p>

<p>Simple, right?</p>

<h3>Not so fast, Johnny&hellip;</h3>

<p>This worked fine until we had one template that was really big (120KB) and we found out about issue
<a href="https://issues.gradle.org/browse/GRADLE-3122">GRADLE-3122</a>. Gradle uses Groovy&rsquo;s
<a href="http://docs.groovy-lang.org/latest/html/documentation/template-engines.html#_simpletemplateengine">SimpleTemplateEngine</a>,
that can only process files up to 64KB!</p>

<p>Newest versions of Groovy (2.4+) include
<a href="http://docs.groovy-lang.org/latest/html/documentation/template-engines.html#_streamingtemplateengine">StreamingTemplateEngine</a>
that does not have this limit, but the most recent version of Gradle (2.5 as of this post)
still uses Groovy 2.3&hellip;</p>

<p>One way to overcome this would be to use Ant&rsquo;s <code>ReplaceTokens</code> filter, simply by changing our templates to use Ant&rsquo;s
token syntax (ex: <code>@variable@</code>) and changing the line <code>expand(env)</code> to <code>filter(ReplaceTokens, tokens: env)</code></p>

<p>But because we need to use logic in our templates (if&rsquo;s and loops), we had to come up with a different approach.
The solutions available were too simple for our needs or too complicated to implement in a clear way, making them
unsuitable for our project. So we decided to roll&hellip;</p>

<h3><a name="final-solution"></a>Our own solution</h3>

<p>Finally we decided to implement a simple template processor using <a href="http://freemarker.org">FreeMarker</a>. We select
this awesome template engine for its feature set, IDE support and excelent OSS reputation, although the solution bellow
could be adapted to be used with any other template engine (<a href="http://velocity.apache.org">Velocity</a>,
<a href="https://github.com/samskivert/jmustache">JMustache</a>, etc&hellip;)</p>

<figure class='code'><figcaption><span>buildSrc/src/main/groovy/your/package/TemplateProcessor.groovy</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
<span class='line-number'>33</span>
<span class='line-number'>34</span>
<span class='line-number'>35</span>
<span class='line-number'>36</span>
<span class='line-number'>37</span>
<span class='line-number'>38</span>
<span class='line-number'>39</span>
<span class='line-number'>40</span>
<span class='line-number'>41</span>
<span class='line-number'>42</span>
<span class='line-number'>43</span>
<span class='line-number'>44</span>
<span class='line-number'>45</span>
<span class='line-number'>46</span>
<span class='line-number'>47</span>
<span class='line-number'>48</span>
<span class='line-number'>49</span>
<span class='line-number'>50</span>
<span class='line-number'>51</span>
<span class='line-number'>52</span>
<span class='line-number'>53</span>
<span class='line-number'>54</span>
<span class='line-number'>55</span>
<span class='line-number'>56</span>
<span class='line-number'>57</span>
<span class='line-number'>58</span>
</pre></td><td class='code'><pre><code class='groovy'><span class='line'><span class="kn">package</span> <span class="n">your</span><span class="o">.</span><span class="na">package</span>
</span><span class='line'>
</span><span class='line'><span class="kn">import</span> <span class="nn">freemarker.template.Configuration</span>
</span><span class='line'><span class="kn">import</span> <span class="nn">org.apache.commons.io.FileUtils</span>
</span><span class='line'><span class="kn">import</span> <span class="nn">org.apache.tools.ant.DirectoryScanner</span>
</span><span class='line'>
</span><span class='line'><span class="kn">import</span> <span class="nn">static</span> <span class="n">freemarker</span><span class="o">.</span><span class="na">template</span><span class="o">.</span><span class="na">TemplateExceptionHandler</span><span class="o">.</span><span class="na">RETHROW_HANDLER</span>
</span><span class='line'>
</span><span class='line'><span class="kd">class</span> <span class="nc">TemplateProcessor</span> <span class="o">{</span>
</span><span class='line'>    <span class="kd">private</span> <span class="kd">static</span> <span class="kd">final</span> <span class="n">String</span> <span class="n">TEMPLATE_EXTENSION</span> <span class="o">=</span> <span class="s1">&#39;.ftl&#39;</span>
</span><span class='line'>    <span class="kd">private</span> <span class="n">String</span> <span class="n">templatesDir</span>
</span><span class='line'>    <span class="kd">private</span> <span class="n">String</span> <span class="n">outputDir</span>
</span><span class='line'>    <span class="kd">private</span> <span class="n">Configuration</span> <span class="n">cfg</span>
</span><span class='line'>
</span><span class='line'>    <span class="nf">TemplateProcessor</span><span class="o">(</span><span class="n">String</span> <span class="n">templatesDir</span><span class="o">,</span> <span class="n">String</span> <span class="n">outputDir</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>        <span class="k">this</span><span class="o">.</span><span class="na">templatesDir</span> <span class="o">=</span> <span class="n">templatesDir</span>
</span><span class='line'>        <span class="k">this</span><span class="o">.</span><span class="na">outputDir</span> <span class="o">=</span> <span class="n">outputDir</span>
</span><span class='line'>
</span><span class='line'>        <span class="n">cfg</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Configuration</span><span class="o">()</span>
</span><span class='line'>        <span class="n">cfg</span><span class="o">.</span><span class="na">setDirectoryForTemplateLoading</span><span class="o">(</span><span class="k">new</span> <span class="n">File</span><span class="o">(</span><span class="n">templatesDir</span><span class="o">))</span>
</span><span class='line'>        <span class="n">cfg</span><span class="o">.</span><span class="na">setDefaultEncoding</span><span class="o">(</span><span class="s2">&quot;UTF-8&quot;</span><span class="o">)</span>
</span><span class='line'>        <span class="n">cfg</span><span class="o">.</span><span class="na">setTemplateExceptionHandler</span><span class="o">(</span><span class="n">RETHROW_HANDLER</span><span class="o">)</span>
</span><span class='line'>    <span class="o">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="kt">void</span> <span class="nf">execute</span><span class="o">(</span><span class="n">Map</span> <span class="n">properties</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>        <span class="n">DirectoryScanner</span> <span class="n">scanner</span> <span class="o">=</span> <span class="n">createScanner</span><span class="o">()</span>
</span><span class='line'>        <span class="n">scanner</span><span class="o">.</span><span class="na">scan</span><span class="o">()</span>
</span><span class='line'>        <span class="n">scanner</span><span class="o">.</span><span class="na">includedFiles</span><span class="o">.</span><span class="na">each</span> <span class="o">{</span> <span class="n">String</span> <span class="n">fileName</span> <span class="o">-&gt;</span>
</span><span class='line'>            <span class="k">if</span> <span class="o">(</span><span class="n">fileName</span><span class="o">.</span><span class="na">endsWith</span><span class="o">(</span><span class="n">TEMPLATE_EXTENSION</span><span class="o">))</span> <span class="o">{</span>
</span><span class='line'>                <span class="n">process</span><span class="o">(</span><span class="n">fileName</span><span class="o">,</span> <span class="n">properties</span><span class="o">)</span>
</span><span class='line'>            <span class="o">}</span> <span class="k">else</span> <span class="o">{</span>
</span><span class='line'>                <span class="n">copy</span><span class="o">(</span><span class="n">fileName</span><span class="o">)</span>
</span><span class='line'>            <span class="o">}</span>
</span><span class='line'>        <span class="o">}</span>
</span><span class='line'>    <span class="o">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="kd">private</span> <span class="nf">process</span><span class="o">(</span><span class="n">String</span> <span class="n">fileName</span><span class="o">,</span> <span class="n">Map</span> <span class="n">properties</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>        <span class="kt">def</span> <span class="n">outputFile</span> <span class="o">=</span> <span class="k">new</span> <span class="n">File</span><span class="o">(</span><span class="n">outputDir</span><span class="o">,</span> <span class="n">fileName</span> <span class="o">-</span> <span class="n">TEMPLATE_EXTENSION</span><span class="o">)</span>
</span><span class='line'>        <span class="kt">def</span> <span class="n">template</span> <span class="o">=</span> <span class="n">cfg</span><span class="o">.</span><span class="na">getTemplate</span><span class="o">(</span><span class="n">fileName</span><span class="o">)</span>
</span><span class='line'>
</span><span class='line'>        <span class="n">outputFile</span><span class="o">.</span><span class="na">withWriter</span> <span class="o">{</span> <span class="n">out</span> <span class="o">-&gt;</span>
</span><span class='line'>            <span class="n">template</span><span class="o">.</span><span class="na">process</span><span class="o">(</span><span class="n">properties</span><span class="o">,</span> <span class="n">out</span><span class="o">)</span>
</span><span class='line'>        <span class="o">}</span>
</span><span class='line'>    <span class="o">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="kd">private</span> <span class="nf">copy</span><span class="o">(</span><span class="n">String</span> <span class="n">fileName</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>        <span class="kt">def</span> <span class="n">inputFile</span> <span class="o">=</span> <span class="k">new</span> <span class="n">File</span><span class="o">(</span><span class="n">templatesDir</span><span class="o">,</span> <span class="n">fileName</span><span class="o">)</span>
</span><span class='line'>        <span class="kt">def</span> <span class="n">outputFile</span> <span class="o">=</span> <span class="k">new</span> <span class="n">File</span><span class="o">(</span><span class="n">outputDir</span><span class="o">,</span> <span class="n">fileName</span><span class="o">)</span>
</span><span class='line'>        <span class="n">FileUtils</span><span class="o">.</span><span class="na">copyFile</span><span class="o">(</span><span class="n">inputFile</span><span class="o">,</span> <span class="n">outputFile</span><span class="o">)</span>
</span><span class='line'>    <span class="o">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="kd">private</span> <span class="n">DirectoryScanner</span> <span class="nf">createScanner</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'>        <span class="kt">def</span> <span class="n">scanner</span> <span class="o">=</span> <span class="k">new</span> <span class="n">DirectoryScanner</span><span class="o">()</span>
</span><span class='line'>        <span class="n">scanner</span><span class="o">.</span><span class="na">includes</span> <span class="o">=</span> <span class="o">[</span><span class="s1">&#39;**/*&#39;</span><span class="o">]</span>
</span><span class='line'>        <span class="n">scanner</span><span class="o">.</span><span class="na">basedir</span> <span class="o">=</span> <span class="k">new</span> <span class="n">File</span><span class="o">(</span><span class="n">templatesDir</span><span class="o">)</span>
</span><span class='line'>        <span class="n">scanner</span>
</span><span class='line'>    <span class="o">}</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Note that we now use the <code>.ftl</code> file extension for our templates, to enable support in our
<a href="http://jetbrains.com/idea">IDE of choice</a>. To use the processor, you have to put it under the
<a href="https://docs.gradle.org/current/userguide/organizing_build_logic.html#sec:build_sources">buildSrc project</a>.
This is a special &ldquo;module&rdquo; in your project that is a simple way to organize build logic in your build scripts. It is
all automatically handled by Gradle. You&rsquo;ll also need a small <code>build.gradle</code> just for  declaring the dependencies for
FreeMarker and Apache Commons IO (used for the <code>copyFile</code> method):</p>

<figure class='code'><figcaption><span>buildSrc/build.gradle</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='groovy'><span class='line'><span class="n">repositories</span> <span class="o">{</span> <span class="n">mavenCentral</span><span class="o">()</span> <span class="o">}</span>
</span><span class='line'>
</span><span class='line'><span class="n">dependencies</span> <span class="o">{</span>
</span><span class='line'>    <span class="n">compile</span> <span class="s1">&#39;org.freemarker:freemarker:2.3.23&#39;</span>
</span><span class='line'>    <span class="n">compile</span> <span class="s1">&#39;commons-io:commons-io:2.4&#39;</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>To have this code available to your main build script, add this two files in your project, in the following paths:</p>

<ul>
<li><em>buildSrc/build.gradle</em></li>
<li><em>buildSrc/src/main/groovy/your/package/TemplateProcessor.groovy</em></li>
</ul>


<p>The last step is to actually use it in our <code>processTemplates</code> task:</p>

<figure class='code'><figcaption><span>build.gradle</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
</pre></td><td class='code'><pre><code class='groovy'><span class='line'><span class="kn">import</span> <span class="nn">your.package.TemplateProcessor</span>
</span><span class='line'>
</span><span class='line'><span class="n">task</span> <span class="nf">processTemplates</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'>    <span class="kt">def</span> <span class="n">fromDir</span> <span class="o">=</span> <span class="s1">&#39;src/templates&#39;</span>
</span><span class='line'>    <span class="kt">def</span> <span class="n">intoDir</span> <span class="o">=</span> <span class="s2">&quot;$buildDir/output/$envName&quot;</span>
</span><span class='line'>    <span class="n">doLast</span> <span class="o">{</span>
</span><span class='line'>      <span class="kt">def</span> <span class="n">env</span> <span class="o">=</span> <span class="n">loadEnvironment</span><span class="o">()</span>
</span><span class='line'>      <span class="k">new</span> <span class="nf">TemplateProcessor</span><span class="o">(</span><span class="n">fromDir</span><span class="o">,</span> <span class="n">intoDir</span><span class="o">).</span><span class="na">execute</span><span class="o">(</span><span class="n">env</span><span class="o">)</span>
</span><span class='line'>    <span class="o">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="n">inputs</span><span class="o">.</span><span class="na">dir</span> <span class="n">fromDir</span>
</span><span class='line'>    <span class="n">inputs</span><span class="o">.</span><span class="na">file</span> <span class="s2">&quot;env/${envName}.properties&quot;</span>
</span><span class='line'>    <span class="n">outputs</span><span class="o">.</span><span class="na">dir</span> <span class="n">intoDir</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Not hard, eh? Note that this task is not a <code>CopyTask</code> anymore, so we now need to specify its inputs and outputs.</p>

<p>My plan is to convert this code into a proper Gradle plugin. But for now: That&rsquo;s all, folks!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[File encoding auto-detection for ZK Fileupload component]]></title>
    <link href="https://techbeats.deluan.com/file-encoding-auto-detection-for-zk-fileupload-component/"/>
    <updated>2015-06-12T02:09:24+00:00</updated>
    <id>https://techbeats.deluan.com/file-encoding-auto-detection-for-zk-fileupload-component</id>
    <content type="html"><![CDATA[<p>Proper handling of file encoding can be a royal headache. Recently I spent an
unreasonable amount of time trying to figure out why <a href="http://www.zkoss.org">ZK&rsquo;s</a>
Fileupload component was messing with the contents of my CSV file:</p>

<!-- more -->


<p><img src="https://techbeats.deluan.com/images/blog/2015-06-11-file-encoding-auto-detection-for-zk-fileupload-component/0.png"></p>

<p>The data should be: <code>código redome;;código hemocentro;nome;nome da mãe;</code></p>

<p>The file was generated with Windows Excel, using the encoding ISO-8859-2
(common encoding for Windows). After some investigation I found
out that Fileupload by default treats all files with content type <code>text/...</code>
as UTF-8! Ouch!!</p>

<p>If all your files will be generated using the same file encoding, this can be
fixed with the following configuration:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='xml'><span class='line'><span class="nt">&lt;zk&gt;</span>
</span><span class='line'>  <span class="nt">&lt;system-config&gt;</span>
</span><span class='line'>    <span class="nt">&lt;upload-charset&gt;</span>YOUR ENCODING<span class="nt">&lt;/upload-charset&gt;</span> <span class="c">&lt;!-- ISO-8859-2 in my case --&gt;</span>
</span><span class='line'>    ...
</span><span class='line'>  <span class="nt">&lt;/system-config&gt;</span>
</span><span class='line'>  ...
</span><span class='line'><span class="nt">&lt;/zk&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>The <a href="http://books.zkoss.org/wiki/ZK_Configuration_Reference/zk.xml/The_system-config_Element/The_upload-charset_Element">upload-charset</a> tag did the trick! But what if my user decides to
move to a different (better?) platform in the future, and generates the file
with UTF-8? Or any other encoding?</p>

<p>Then the proper solution is to use the tag <a href="http://books.zkoss.org/wiki/ZK_Configuration_Reference/zk.xml/The_system-config_Element/The_upload-charset-finder-class_Element">upload-charset-finder-class</a>:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='xml'><span class='line'><span class="nt">&lt;upload-charset-finder-class&gt;</span>a_class_name<span class="nt">&lt;/upload-charset-finder-class&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>The <a href="http://books.zkoss.org/wiki/ZK_Configuration_Reference/zk.xml/The_system-config_Element/The_upload-charset-finder-class_Element">documentation</a> says that this class has to implement
the interface <a href="http://www.zkoss.org/javadoc/latest/zk/org/zkoss/zk/ui/util/CharsetFinder.html">CharsetFinder</a>
and its sole method <code>String getCharset(String contentType, InputStream content)</code>:</p>

<blockquote><p>When a text file is uploaded, the getCharset method is called and it can
determines the encoding based on the content type and/or the content of the
uploaded file.</p></blockquote>

<p>Which leads us to the main reason of this post: <em>How to detect the file
encoding, if ZK itself does not provide a default implementation for this
interface?</em></p>

<p>More research pointed me to <a href="http://stackoverflow.com/questions/499010/java-how-to-determine-the-correct-charset-encoding-of-a-stream">some solutions</a>, but the one that I ended up implementing was using the
<a href="https://any23.apache.org">Apache Any23</a>. It includes the <code>TikaEncodingDetector</code>,
that can be used to auto-detect the file encoding of a stream. The final code
for the CharsetFinder implementation is the following:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="kn">package</span> <span class="n">util</span><span class="o">;</span>
</span><span class='line'>
</span><span class='line'><span class="kn">import</span> <span class="nn">org.apache.any23.encoding.TikaEncodingDetector</span><span class="o">;</span>
</span><span class='line'><span class="kn">import</span> <span class="nn">org.zkoss.zk.ui.util.CharsetFinder</span><span class="o">;</span>
</span><span class='line'>
</span><span class='line'><span class="kn">import</span> <span class="nn">java.nio.charset.Charset</span><span class="o">;</span>
</span><span class='line'>
</span><span class='line'><span class="kd">public</span> <span class="kd">class</span> <span class="nc">TikaCharsetFinder</span> <span class="kd">implements</span> <span class="n">CharsetFinder</span> <span class="o">{</span>
</span><span class='line'>    <span class="nd">@Override</span>
</span><span class='line'>    <span class="kd">public</span> <span class="n">String</span> <span class="nf">getCharset</span><span class="o">(</span><span class="n">String</span> <span class="n">contentType</span><span class="o">,</span> <span class="n">InputStream</span> <span class="n">content</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">IOException</span> <span class="o">{</span>
</span><span class='line'>        <span class="k">return</span> <span class="k">new</span> <span class="nf">TikaEncodingDetector</span><span class="o">().</span><span class="na">guessEncoding</span><span class="o">(</span><span class="n">content</span><span class="o">);</span>
</span><span class='line'>    <span class="o">}</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Yep, it is that simple. The final ZK configuration to use this class is:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='xml'><span class='line'><span class="nt">&lt;zk&gt;</span>
</span><span class='line'>  <span class="nt">&lt;system-config&gt;</span>
</span><span class='line'>    <span class="nt">&lt;upload-charset-finder-class&gt;</span>util.TikaCharsetFinder<span class="nt">&lt;/upload-charset-finder-class&gt;</span>
</span><span class='line'>    ...
</span><span class='line'>  <span class="nt">&lt;/system-config&gt;</span>
</span><span class='line'>  ...
</span><span class='line'><span class="nt">&lt;/zk&gt;</span>
</span></code></pre></td></tr></table></div></figure>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Profiling web requests in your Grails application]]></title>
    <link href="https://techbeats.deluan.com/profiling-web-requests-in-your-grails-application/"/>
    <updated>2010-12-29T06:11:39+00:00</updated>
    <id>https://techbeats.deluan.com/profiling-web-requests-in-your-grails-application</id>
    <content type="html"><![CDATA[<p>Here’s a simple filter I’ve been using to help me detect points of improvement in my application:</p>

<div><pre><code>class UtilFilters {

    def filters = {

        profiler(controller: &#39;*&#39;, action: &#39;*&#39;) {
            before = {
                request._timeBeforeRequest = System.currentTimeMillis()
            }

            after = {
                request._timeAfterRequest = System.currentTimeMillis()
            }

            afterView = {
                if (params.showTime) {
                    session._showTime = params.showTime == &quot;on&quot;
                }
                if (session._showTime) {
                    def actionDuration = request._timeAfterRequest - request._timeBeforeRequest
                    def viewDuration = System.currentTimeMillis() - request._timeAfterRequest
                    log.debug(&quot;Request duration for (${controllerName}/${actionName}): ${actionDuration}ms/${viewDuration}ms&quot;)
                }
            }
        }
    }

}

</code></pre></div>


<p>To use it, put this class in the <code>grails-app/conf</code> folder of your project. To activate the profile, call any URL
of your application with the <code>showTime=on</code> parameter, like this:</p>

<!-- more -->




<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>http://localhost:8080/my-grails-app/book/list?showTime=on</span></code></pre></td></tr></table></div></figure>


<p>After calling that URL, all request times will be measured and informed on the application’s log, like this:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>2010-12-21 12:02:31,698 [http-8080-5] DEBUG filters.UtilFilters  - Request duration for (book/list): 20ms/50ms</span></code></pre></td></tr></table></div></figure>


<p>The first time informed (20ms) is the time spent executing the action (list in this case) and the second (50ms) is
the time spent rendering the view (<code>list.gsp</code>).</p>

<p>To turn off the profiler, call any URL with <code>showTime=off</code>:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>http://localhost:8080/my-grails-app?showTime=on</span></code></pre></td></tr></table></div></figure>


<p>Enjoy :)</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Using Cache-Headers plugin in a non-english server]]></title>
    <link href="https://techbeats.deluan.com/using-cache-headers-plugin-in-a-non-english-server/"/>
    <updated>2010-12-21T06:03:35+00:00</updated>
    <id>https://techbeats.deluan.com/using-cache-headers-plugin-in-a-non-english-server</id>
    <content type="html"><![CDATA[<p><strong>UPDATE: This problem has been fixed in version 1.1.3 of the plugin. Thanks Marc and Luke Daley!</strong></p>

<p>This week I tried the <a href="http://www.anyware.co.uk/2005/">Marc Palmer</a>’s excelent plugin
<a href="http://www.grails.org/plugin/cache-headers">Cache-Headers</a>, and it really rocks! Using it I can make all my
server-side generated images be cached on the client, reducing significantly the bandwidth and cpu-power necessary by
my application.</p>

<p>But there’s a little gotcha: The plugin (as of version 1.1.2) uses a SimpleDateFormat to generate and check the
Last-Modified header, and the implementation creates this SimpleDateFormat with the system’s default Locale, in my
case Portuguese. This causes errors like this:</p>

<!-- more -->




<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>java.lang.IllegalArgumentException: Ter, 21 dez 2010 15:10:33 GMT
</span><span class='line'>    at com.grailsrocks.cacheheaders.CacheHeadersService.withCacheHeaders(CacheHeadersService.groovy:140)
</span><span class='line'>    at com.grailsrocks.cacheheaders.CacheHeadersService$withCacheHeaders.call(Unknown Source)
</span><span class='line'>    at CacheHeadersGrailsPlugin$_addCacheMethods_closure7_closure11.doCall(CacheHeadersGrailsPlugin.groovy:61)
</span><span class='line'>    at org.weceem.controllers.WcmContentController$_closure3.doCall(WcmContentController.groovy:172)
</span><span class='line'>    at org.weceem.controllers.WcmContentController$_closure3.doCall(WcmContentController.groovy)
</span><span class='line'>    at org.apache.shiro.web.servlet.ShiroFilter.executeChain(ShiroFilter.java:687)
</span><span class='line'>    at org.apache.shiro.web.servlet.ShiroFilter.doFilterInternal(ShiroFilter.java:616)
</span><span class='line'>    at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:81)</span></code></pre></td></tr></table></div></figure>


<p>The workaround I found was to override the construction of that SimpleDateFormat. Luckily it’s been created in a small
class, that is easy to extend:</p>

<div><pre><code>package com.deluan.grails.util

import java.text.SimpleDateFormat
import com.grailsrocks.cacheheaders.DateFormatterThreadLocal

/**
 * This class is used to force CacheHeadersService (from the cache-headers 
 * plugin) to generate http-dates in english. It MUST be used when the 
 * locale of your server is not English.
 * &lt;p/&gt;
 * To use it, put the following configuration in your Config.groovy:
 * &lt;pre&gt;
 * beans {
 *    cacheHeadersService {
 *        dateFormatters = new com.deluan.grails.util.EnglishDateFormatterThreadLocal()
 *    }
 * }
 * &lt;/pre&gt;
 * 
 * @author Deluan
 */
class EnglishDateFormatterThreadLocal extends DateFormatterThreadLocal {
    SimpleDateFormat initialValue() {
        def v = new SimpleDateFormat(RFC1123_DATE_FORMAT, Locale.ENGLISH)
        v.timeZone = TimeZone.getTimeZone(&#39;GMT&#39;)
        return v
    }
}
</code></pre></div>


<p>All you have to do is put this class in your project (in the <code>src/groovy</code> folder) and add the following configuration
override in your <code>Config.groovy</code>:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='groovy'><span class='line'><span class="n">beans</span> <span class="o">{</span>
</span><span class='line'>    <span class="n">cacheHeadersService</span> <span class="o">{</span>
</span><span class='line'>        <span class="n">dateFormatters</span> <span class="o">=</span> <span class="k">new</span> <span class="n">com</span><span class="o">.</span><span class="na">deluan</span><span class="o">.</span><span class="na">grails</span><span class="o">.</span><span class="na">util</span><span class="o">.</span><span class="na">EnglishDateFormatterThreadLocal</span><span class="o">()</span>
</span><span class='line'>    <span class="o">}</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>I already filled a bug report here: <a href="http://jira.codehaus.org/browse/GRAILSPLUGINS-2707,">http://jira.codehaus.org/browse/GRAILSPLUGINS-2707,</a> and probably this post will be
obsolete in a near future :)</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Apache Shiro tags for Facelets - Securing your JSF pages]]></title>
    <link href="https://techbeats.deluan.com/apache-shiro-tags-for-jsffacelets"/>
    <updated>2010-11-01T05:49:27+00:00</updated>
    <id>https://techbeats.deluan.com/apache-shiro-tags-for-facelets-securing-your-jsf-pages</id>
    <content type="html"><![CDATA[<p><strong>UPDATE</strong> There is now a JSF 2.0 version of this library available in the
<a href="http://github.com/deluan/shiro-faces">project repo</a></p>

<p>First, a small introduction. You can skip it and go straight to the
<a href="http://github.com/deluan/shiro-faces">source code</a>, if you want.</p>

<p>I started working with <a href="http://shiro.apache.org/">Apache Shiro</a> when it was still called JSecurity, and I have to
say that it really rocks! I tried to use Spring Security (Acegi) in some projects, but the easiness and lean approach
of Shiro is unbeatable. For a quick introduction, here&rsquo;s a quote from the project&rsquo;s site:</p>

<blockquote><p>Apache Shiro is a powerful and easy-to-use Java security framework that performs authentication, authorization, cryptography, and session management.<br/>With Shiro’s easy-to-understand API, you can quickly and easily secure any application – from the smallest mobile applications to the largest web and enterprise applications.</p></blockquote>


<!-- more -->


<p>I&rsquo;ve used it in Java and Grails projects, and recently I&rsquo;ve even been
<a href="https://code.google.com/p/shiro-gae">experimenting it with Google App Engine</a>. It fits very well in almost any Java
platform project that needs security.</p>

<p>Shiro already works great in a JSF/Facelets project. You can use its <a href="http://shiro.apache.org/web.html">filters</a> to
grant and deny access to some parts of your application and to force authentication (redirect to login).</p>

<p>The only functionality missing is the power of its JSP taglib, that is used to conditionally render some parts of
your HTML, based on user&rsquo;s authorization, roles and permissions (you can learn how to use them with this
<a href="http://svn.apache.org/repos/asf/shiro/trunk/samples/web/">simple example project</a>). The problem is that this
conditional rendering <a href="http://www.devx.com/Java/Article/21020/1954">is not totally compatible with JSF&rsquo;s phases</a>.
Better than trying to fit a cube into a spherical hole, I decided to rewrite Shiro&rsquo;s JSP tags into a
<a href="http://en.wikipedia.org/wiki/Facelets">Facelets</a> taglib, totally compatible with JSF.</p>

<p>All original tags are available as their Facelets equivalents, and I have introduced two new ones:</p>

<p><code>&lt;shiro:hasAnyPermission&gt;</code> - Displays body content only if the current user has one of the specified permissions from
a comma-separated list of permission strings.</p>

<p><code>&lt;shiro:remembered&gt;</code> - Displays body content only if the current user has a known identity that has been obtained from
&lsquo;RememberMe&rsquo; services. Note that this is semantically different from the <code>&lt;shiro:authenticated&gt;</code> tag, which is more restrictive.</p>

<p>I&rsquo;ve already submitted a <a href="https://issues.apache.org/jira/browse/SHIRO-206">patch</a> to Shiro&rsquo;s development team, but
they&rsquo;re very busy at the moment packaging the new 1.1 version for release. So I decided to
<a href="http://deluan.github.com/shiro-faces">share the taglib on GitHub</a>, and host the artifacts in my personal maven
repository, as I need to use the tags in an on-going project.</p>

<p>If you want to try it in your maven project, add my repository to your pom.xml:</p>

<div><pre><code>        &lt;repositories&gt;
                &lt;repository&gt;
                    &lt;snapshots&gt;
                        &lt;enabled&gt;false&lt;/enabled&gt;
                    &lt;/snapshots&gt;
                    &lt;id&gt;bintray-deluan-maven&lt;/id&gt;
                    &lt;name&gt;bintray&lt;/name&gt;
                    &lt;url&gt;http://dl.bintray.com/deluan/maven&lt;/url&gt;
                &lt;/repository&gt;
        &lt;/repositories&gt;</code></pre></div>


<p>and add the jar dependency:</p>

<div><pre><code>        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.shiro&lt;/groupId&gt;
            &lt;artifactId&gt;shiro-faces&lt;/artifactId&gt;
            &lt;!-- See the latest version on the project&#39;s homepage --&gt;
            &lt;version&gt;2.0&lt;/version&gt;
        &lt;/dependency&gt;</code></pre></div>


<p>Now you can declare Shiro&rsquo;s namespace in your xhtml pages and use the tags like this:</p>

<div><pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot; xml:lang=&quot;en&quot; lang=&quot;en&quot;
      xmlns:ui=&quot;http://java.sun.com/jsf/facelets&quot;
      xmlns:shiro=&quot;http://shiro.apache.org/tags&quot;&gt;
&lt;head&gt;
    &lt;title&gt;&lt;ui:insert name=&quot;titulo&quot;&gt;Shiro Faces Test&lt;/ui:insert&gt;&lt;/title&gt;
&lt;/head&gt;

&lt;body&gt;
    &lt;p&gt;Hi, &lt;shiro:guest&gt;Guest&lt;/shiro:guest&gt;
          &lt;shiro:user&gt;&lt;shiro:principal/&gt;&lt;/shiro:user&gt;!
    &lt;/p&gt;
&lt;/body&gt;

&lt;/html&gt;</code></pre></div>


<p>That&rsquo;s it! Just keep in mind that as soon as this lib gets incorporated officially in Shiro, I&rsquo;ll stop updating it
in GitHub and all future enhancements will only be available in the official version. If you want to see the tags
incorporated officially into Shiro sooner than later, you can vote here: <a href="https://issues.apache.org/jira/browse/SHIRO-206">https://issues.apache.org/jira/browse/SHIRO-206</a></p>

<p>And if you have any suggestion, please let me know.</p>

<p>Enjoy ;)</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Using Spring DI in your Gaelyk projects]]></title>
    <link href="https://techbeats.deluan.com/using-spring-di-in-your-gaelyk-projects/"/>
    <updated>2010-10-11T05:07:55+00:00</updated>
    <id>https://techbeats.deluan.com/using-spring-di-in-your-gaelyk-projects</id>
    <content type="html"><![CDATA[<p>Since I started using <a href="http://gaelyk.appspot.com/">Gaelyk</a>, one of the features I missed most (coming from a Grails
background) is Spring&rsquo;s dependency injection. Until recently I didn&rsquo;t even know if it was possible to use Spring in
<a href="http://appengine.google.com/">Google App Engine</a>, so I decided to do a little investigation on the subject, and
found out that it&rsquo;s very easy indeed.</p>

<p>Here&rsquo;s a little tutorial on how to configure Spring in your Gaelyk project. I&rsquo;m assuming you have basic knowledge of
Spring, Gaelyk and Maven.</p>

<p>First, let&rsquo;s create a Gaelyk project. The easiest way is using the excellent
<a href="http://code.google.com/p/maven-gaelyk/">maven-gaelyk archetype</a>:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>mvn archetype:generate -DarchetypeGroupId=org.codeconsole -DarchetypeArtifactId=gaelyk-archetype -DarchetypeVersion=0.5.5 -DarchetypeRepository=http://maven-gaelyk.googlecode.com/svn/repository/ -DartifactId=gaelyk-spring -DgroupId=com.deluan.gaelyk -DgaeApplicationName=gaelyk-spring</span></code></pre></td></tr></table></div></figure>


<!-- more -->


<p>Now open the project in your favorite IDE, so we can edit the configuration files. First, add the Spring dependency to your <code>pom.xml</code>:</p>

<div><pre><code>        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-web&lt;/artifactId&gt;
            &lt;version&gt;${spring.version}&lt;/version&gt;
        &lt;/dependency&gt;</code></pre></div>


<p>Next we need to configure Spring&rsquo;s ContextLoaderListener in <code>web.xml</code>:</p>

<div><pre><code>    &lt;context-param&gt;
        &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
        &lt;param-value&gt;
            /WEB-INF/spring/*.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;</code></pre></div>


<p>As you can see from above, we configured Spring to load all context configuration files under the directory <code>WEB-INF/spring</code>.</p>

<p>With these configurations in place, your project is already Spring enabled. Now we need a easy way to access the
Spring&rsquo;s Application Context. One good way to do this is using a singleton that implements the ApplicationContextAware
interface. To keep this post as small as possible, I borrowed an implementation from
<a href="http://sujitpal.blogspot.com/2007/03/accessing-spring-beans-from-legacy-code.html">this blog post</a>, where you can learn
more about the details. Create the directory <code>src/main/groovy</code> and put the following SpringApplicationContext singleton
there (in the correct package):</p>

<div><pre><code>package com.deluan.gaelyk;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * Wrapper to always return a reference to the Spring Application Context from
 * within non-Spring enabled beans. Unlike Spring MVC&#39;s WebApplicationContextUtils
 * we do not need a reference to the Servlet context for this. All we need is
 * for this bean to be initialized during application startup.
 *
 * Original from http://sujitpal.blogspot.com/2007/03/accessing-spring-beans-from-legacy-code.html
 */
public class SpringApplicationContext implements ApplicationContextAware {

    private static ApplicationContext CONTEXT;

    /**
     * This method is called from within the ApplicationContext once it is
     * done starting up, it will stick a reference to itself into this bean.
     * @param context a reference to the ApplicationContext.
     */
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        CONTEXT = context;
    }

    /**
     * This is about the same as context.getBean(&quot;beanName&quot;), except it has its
     * own static handle to the Spring context, so calling this method statically
     * will give access to the beans by name in the Spring application context.
     * As in the context.getBean(&quot;beanName&quot;) call, the caller must cast to the
     * appropriate target class. If the bean does not exist, then a Runtime error
     * will be thrown.
     * @param beanName the name of the bean to get.
     * @return an Object reference to the named bean.
     */
    public static Object getBean(String beanName) {
        return CONTEXT.getBean(beanName);
    }

    public static ApplicationContext getContext() {
        return CONTEXT;
    }
}
</code></pre></div>


<p>Configure the singleton in your spring context:</p>

<div><pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd&quot;&gt;

    &lt;bean id=&quot;springApplicationContext&quot; class=&quot;com.deluan.gaelyk.SpringApplicationContext&quot;/&gt;

    &lt;bean id=&quot;dateFormat&quot; class=&quot;java.text.SimpleDateFormat&quot;&gt;
        &lt;constructor-arg value=&quot;yyyy/MM/dd&quot; /&gt;
    &lt;/bean&gt;

    &lt;bean id=&quot;timeFormat&quot; class=&quot;java.text.SimpleDateFormat&quot;&gt;
        &lt;constructor-arg value=&quot;hh:mm:ss&quot; /&gt;
    &lt;/bean&gt;

    &lt;bean id=&quot;dateTimeFormat&quot; class=&quot;java.text.SimpleDateFormat&quot;&gt;
        &lt;constructor-arg value=&quot;yyyy/MM/dd hh:mm:ss&quot; /&gt;
    &lt;/bean&gt;

&lt;/beans&gt;</code></pre></div>


<p>As you can see, I also declared some SimpleDateFormat instances as beans to be used in our examples.</p>

<p>Now everything is configured and ready to be used. Let&rsquo;s see how we can obtain a spring bean inside a Groovlet.
Create the file <code>WEB-INF/groovy/index.groovy</code> with the following content:</p>

<div><pre><code>import com.deluan.gaelyk.SpringApplicationContext

def dateFormat = SpringApplicationContext.getBean(&#39;dateFormat&#39;)
def now = new Date()

println dateFormat.format(now)</code></pre></div>


<p>Now run your application with the command <code>mvn gae:run</code>, point your browser to <a href="http://localhost:8080/index.groovy">http://localhost:8080/index.groovy</a> and
you should see something like this:</p>

<p><img src="https://techbeats.deluan.com/images/blog/2010-10-11-using-spring-di-in-your-gaelyk-projects/Screen_Shot.png"></p>

<p>Well, that&rsquo;s it! Nothing much different from what you are used to do in a normal Web application, right? But
remember: Gaelyk is NOT your normal Web framework so let&rsquo;s spice things a little bit.</p>

<p>The solution for looking up beans depicted above is a bit cumbersome. Let&rsquo;s use
<a href="http://gaelyk.appspot.com/tutorial/plugins">Gaelyk&rsquo;s plugin system</a> to make things a little more &ldquo;groovy&rdquo;.
Using the plugin descriptor bellow, we can provide shortcuts to our SpringApplicationContext&rsquo;s methods, getContext()
and getBean(). Save it in the file <code>WEB-INF/plugins/spring.groovy</code>:</p>

<div><pre><code>import com.deluan.gaelyk.SpringApplicationContext

binding {
    appCtx = SpringApplicationContext.context

    getBean = {
        SpringApplicationContext.getBean(it)
    }

    autowire = { self, beanNames -&gt;
        beanNames.each {
            self.setProperty(it, SpringApplicationContext.getBean(it))
        }
    }
}</code></pre></div>


<p>Before you can use these shortcuts, you need to tell Gaelyk about your descriptor by &ldquo;installing&rdquo; it in your project.
Save the code bellow in the file <code>WEB-INF/plugins.groovy</code>:</p>

<div><pre><code>install spring</code></pre></div>


<p>Now you can use the shortcuts in your Groovlets this way:</p>

<div><pre><code>
def now = new Date()

// Simple context lookup
def dateFormat = getBean(&#39;dateFormat&#39;)

// Resolve a list of bean names and create bindings for each one of them
autowire this, [&#39;timeFormat&#39;, &#39;dateTimeFormat&#39;]

html.html {
    body {
        p appCtx.displayName  // Access the ApplicationContext
        p dateFormat.format(now)
        p timeFormat.format(now)
        p dateTimeFormat.format(now)
    }
}</code></pre></div>


<p>Cool, isn&rsquo;t it? A note on the <code>autowire</code> binding: It creates bindings &ldquo;automagically&rdquo; for each bean you passed as a
parameter, as if the beans were declared in your Groovlet.</p>

<p>You can download the sample project used in this post from GitHub: <a href="http://github.com/deluan/gaelyk-spring.">http://github.com/deluan/gaelyk-spring.</a>
You can follow each commit to see exactly what was changed in each step of this tutorial.</p>

<p>If you have any suggestion or question, please let me know.</p>

<p><strong>UPDATE</strong>: I&rsquo;ve refactored the <code>autowire</code>method into a Category, so now it&rsquo;s not necessary to pass <code>this</code> as the first
parameter.  The new version is available at <a href="http://github.com/deluan/gaelyk-spring">GitHub</a></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Calling the correct Grails version automatically from command line]]></title>
    <link href="https://techbeats.deluan.com/calling-the-correct-grails-version-automatically-from-command-line/"/>
    <updated>2010-10-05T04:48:53+00:00</updated>
    <id>https://techbeats.deluan.com/calling-the-correct-grails-version-automatically-from-command-line</id>
    <content type="html"><![CDATA[<p><strong>UPDATE</strong>: For latest version and instructions, see <a href="http://github.com/deluan/grails.sh">http://github.com/deluan/grails.sh</a></p>

<p>Now that I decided to organize and publish some of my code/hacks here, I thought
it would be a good thing to republish here my Grails caller script.</p>

<p>I work on and maintain various Grails projects at the same time, and some of
them uses versions of Grails as old as 1.0.3! So the question is: How to call
the right version of grails command for a given project, the version that the
project was created with?</p>

<!-- more -->


<p>First I tried changing the <code>GRAILS_HOME</code> environment variable every time I was
going to work with a project that uses a different version than the default.
But it’s just too much work for a thing that should be transparent. So I decided
to create a shell script to solve this problem. The script should detect which
Grails version to call when it’s executed. Here’s the script I came up with:</p>

<div><pre><code>#!/bin/sh
# Author: Deluan (http://techbeats.deluan.com)

# Check if GRAILS_HOME is set
if [ -z &quot;$GRAILS_HOME&quot; -o ! -d &quot;$GRAILS_HOME&quot; ]; then
    echo &quot;Error: GRAILS_HOME not set&quot;
    exit 2
fi

# Extract the base path from GRAILS_HOME
BASE_GRAILS_PATH=`echo $GRAILS_HOME | sed -e &quot;s/[^\/\\]*$//&quot; -e &quot;s/^$/./&quot;`
APP_PROP=&quot;application.properties&quot;

# Try to get the version from the command line
TRY_VERSION=$1
if [ -d &quot;${BASE_GRAILS_PATH}/grails-${TRY_VERSION}&quot; ]; then
    VERSION=$TRY_VERSION
    shift
fi 

# Or else get the version from the application.properties in the current directory
[ -z &quot;$VERSION&quot; -a -f &quot;$APP_PROP&quot; ] &amp;&amp;
    VERSION=`awk -F&#39;=&#39; &#39;/app.grails.version/ { print $2 }&#39; $APP_PROP | tr -d &#39;\r\n&#39;`

# Or else use the default version
if [ -z &quot;$VERSION&quot; ]; then  
    VERSION=`basename $GRAILS_HOME | cut -f 2 -d &quot;-&quot;`
fi

export GRAILS_HOME=${BASE_GRAILS_PATH}/grails-${VERSION}
GRAILS_CMD=${GRAILS_HOME}/bin/grails

if [ ! -x &quot;$GRAILS_CMD&quot; ]; then
    echo &quot;Error: grails command not found at &#39;$GRAILS_CMD&#39;!&quot;
    exit 3
fi

exec $GRAILS_CMD $*
</code></pre></div>


<h2>How it Works?</h2>

<p>The script first checks if you specified a version in the command line,
like: <code>grails 1.3.5-SNAPSHOT create-app</code>. If not, it looks for an
<code>application.properties</code> file in the current folder. This file keeps some
metadata for Grails projects, including the Grails version the project was
created with. If it does not find any <code>application.properties</code> in the current
folder, it then just calls the
<a href="http://grails.org/Installation">default Grails installed</a> in your system,
the one that <code>GRAILS_HOME</code> points to.</p>

<h2>Prerequisites</h2>

<ul>
<li>All your Grails versions must be installed under the same base directory. Ex:</li>
</ul>


<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>  /opt/grails-1.0.3
</span><span class='line'>  /opt/grails-1.1.1
</span><span class='line'>  /opt/grails-1.2-M2
</span><span class='line'>  /opt/grails-1.3.3
</span><span class='line'>  /opt/grails-1.3.5-SNAPSHOT</span></code></pre></td></tr></table></div></figure>


<ul>
<li><p><code>GRAILS_HOME</code> environment variable must be set and point to your “default”
Grails installation</p></li>
<li><p>This script was tested on Mac OS X (Snow Leopard), Linux (Ubuntu) and
Windows (with cygwin)</p></li>
</ul>


<h2>Installation</h2>

<ul>
<li>Download the script: <a href="http://github.com/deluan/grails.sh/raw/master/grails">http://github.com/deluan/grails.sh/raw/master/grails</a></li>
<li>Include the folder where it is installed in your <code>PATH</code>.</li>
<li>Exclude <code>$GRAILS_HOME/bin</code> from your <code>PATH</code></li>
</ul>


<h2>Usage</h2>

<p>Using the script is as transparent as possible:</p>

<ul>
<li>If you invoke it from a project folder, it will detect the version used by
the project and call the correct grails (if it is installed in your system)</li>
<li>If you invoke it from any other folder that does not contain a Grails project,
it will call the “default” Grails installation</li>
<li>If you want to call a specific Grails version (i.e. when doing an upgrade) you
can specify the version you want in the first parameter. Ex:</li>
</ul>


<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>$ grails 1.3.3 upgrade</span></code></pre></td></tr></table></div></figure>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[How to use an external log4j.properties in you Grails project]]></title>
    <link href="https://techbeats.deluan.com/how-to-use-an-external-log4j-dot-properties-in-you-grails-project/"/>
    <updated>2010-10-01T03:33:52+00:00</updated>
    <id>https://techbeats.deluan.com/how-to-use-an-external-log4j-dot-properties-in-you-grails-project</id>
    <content type="html"><![CDATA[<p>In a recent Grails project, I had to follow some corporate guidelines regarding application deployment, and one of
those were that the log4j configuration for an application must be externalized in a properties file.</p>

<p>I searched for a <a href="http://grails.org/plugin/home">Grails plugin</a> that could help me with this, with no luck.
Then I remembered that a Grails application is just a
<a href="http://blog.springsource.com/2010/06/08/spring-the-foundation-for-grails/">Spring application in disguise</a>,
so I looked for a Spring way to do this.</p>

<p>There are at least two ways to do this using Spring:
<a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/util/Log4jConfigListener.html">Log4jConfigListener</a>
and
<a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/util/Log4jConfigurer.html">Log4jConfigurer</a>.
I chose the later because the former assumes an expanded WAR file, which was not my case.</p>

<p>Here’s the recipe I came up with:</p>

<!-- more -->


<ul>
<li>Configure a Log4jConfigurer Spring bean in your <code>grails-app/conf/resources.groovy</code>:
(click <a href="https://gist.github.com/deluan/605359#file-resources-xml">here for a xml version</a>)</li>
</ul>


<div><pre><code>beans = {
    log4jConfigurer(org.springframework.beans.factory.config.MethodInvokingFactoryBean) {
        targetClass = &quot;org.springframework.util.Log4jConfigurer&quot;
        targetMethod = &quot;initLogging&quot;
        arguments = [&quot;classpath:myapp/log4j.properties&quot;]
    }

    ...

}</code></pre></div>


<ul>
<li><p>Install the templates in your project with grails install-templates, so you can change some files used for Grails&#8217;
code generation. The one we are interested in is the web.xml template.</p></li>
<li><p>Comment out the Grails&#8217; Log4jConfigListener from the <code>src/templates/war/web.xml</code> template:</p></li>
</ul>


<div><pre><code>    &lt;filter-mapping&gt;
        &lt;filter-name&gt;sitemesh&lt;/filter-name&gt;
        &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
    &lt;/filter-mapping&gt;


    &lt;!-- Comment this out!
    &lt;listener&gt;
        &lt;listener-class&gt;org.codehaus.groovy.grails.web.util.Log4jConfigListener&lt;/listener-class&gt;
    &lt;/listener&gt;
    --&gt;

    &lt;listener&gt;
        &lt;listener-class&gt;org.codehaus.groovy.grails.web.context.GrailsContextLoaderListener&lt;/listener-class&gt;
    &lt;/listener&gt;</code></pre></div>


<ul>
<li><p>You can (and should) remove the log4j configuration block from your Config.groovy</p></li>
<li><p>That’s it!</p></li>
</ul>


<p>This was tested with Grails 1.3.3, deploying to an Oracle WebLogic 10.3.0 container.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Creating permalinks with Grails]]></title>
    <link href="https://techbeats.deluan.com/creating-permalinks-with-grails/"/>
    <updated>2009-03-19T02:51:37+00:00</updated>
    <id>https://techbeats.deluan.com/creating-permalinks-with-grails</id>
    <content type="html"><![CDATA[<p>I&rsquo;ve been working with <a href="http://grails.org">Grails</a> for some time now and if I had to choose just one good thing
to say about it is how it&rsquo;s community is really great!</p>

<p>I think it&rsquo;s time to start giving back some contribution, and here&rsquo;s the first one: A Permalink Codec to generate
permalinks based on strings. It strips out all non word chars and convert the resulting string to lowercase:</p>

<!-- more -->




<div><pre><code>/*
 * Copyright 2010 Deluan Cotts (grails@deluan.com.br)
 *
 * Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an &quot;AS IS&quot; BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.deluan.grails.codecs

import java.util.regex.Matcher
import java.util.regex.Pattern

/**
 * Strip all non word chars, convert to lowercase
 */
class PermalinkCodec {
    private static final String[] CARACTERES_SEM_ACENTO
    private static final Pattern[] PATTERNS

    static {
        CARACTERES_SEM_ACENTO = [&quot;a&quot;, &quot;e&quot;, &quot;i&quot;, &quot;o&quot;, &quot;u&quot;, &quot;c&quot;, &quot;n&quot;]
        PATTERNS = new Pattern[CARACTERES_SEM_ACENTO.length]
        PATTERNS[0] = Pattern.compile(&quot;[áàãâä]&quot;, Pattern.CASE_INSENSITIVE)
        PATTERNS[1] = Pattern.compile(&quot;[éèêë]&quot;, Pattern.CASE_INSENSITIVE)
        PATTERNS[2] = Pattern.compile(&quot;[íìïî]&quot;, Pattern.CASE_INSENSITIVE)
        PATTERNS[3] = Pattern.compile(&quot;[óòöõô]&quot;, Pattern.CASE_INSENSITIVE)
        PATTERNS[4] = Pattern.compile(&quot;[úùüû]&quot;, Pattern.CASE_INSENSITIVE)
        PATTERNS[5] = Pattern.compile(&quot;ç&quot;, Pattern.CASE_INSENSITIVE)
        PATTERNS[6] = Pattern.compile(&quot;ñ&quot;, Pattern.CASE_INSENSITIVE)
    }

    private static String replaceSpecial(String text) {
        String result = text
        for (int i = 0; i &lt; PATTERNS.length; i++) {
            Matcher matcher = PATTERNS[i].matcher(result)
            result = matcher.replaceAll(CARACTERES_SEM_ACENTO[i])
        }
        return result
    }

    static encode = {str -&gt;
        str = replaceSpecial(str.toString().toLowerCase())
        return str.replaceAll(&quot;\\W&quot;, &quot;-&quot;)
    }

}</code></pre></div>


<p>To use it in your Grails project, save it in <code>grails-app/utils/com/deluan/grails/codecs</code> folder as <code>PermalinkCodec.groovy</code>.</p>

<p>Please read the (excelent) <a href="http://grails.org/doc/latest">Grails manual</a> for more info
on <a href="http://grails.org/doc/latest/guide/single.html#codecs">how to use codecs</a>.</p>
]]></content>
  </entry>
  
</feed>
