<?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>It&#039;s not a blog, It&#039;s a feature</title>
	<atom:link href="https://javazquez.com/juan/feed/" rel="self" type="application/rss+xml" />
	<link>https://javazquez.com/juan</link>
	<description>Juan A. Vazquez</description>
	<lastBuildDate>Sat, 23 Apr 2022 14:18:13 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0</generator>
	<item>
		<title>Arnoldc interpreter using Clojure instaparse</title>
		<link>https://javazquez.com/juan/2017/02/27/arnoldc-interpreter-using-clojure-instaparse/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=arnoldc-interpreter-using-clojure-instaparse</link>
					<comments>https://javazquez.com/juan/2017/02/27/arnoldc-interpreter-using-clojure-instaparse/#comments</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Tue, 28 Feb 2017 03:07:53 +0000</pubDate>
				<category><![CDATA[Clojure]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Howto]]></category>
		<category><![CDATA[jvm]]></category>
		<category><![CDATA[Programming]]></category>
		<guid isPermaLink="false">http://javazquez.com/juan/?p=573</guid>

					<description><![CDATA[Wow, I didn&#8217;t realize I had taken such a long sabbatical since my last post. I haven&#8217;t let off the coding gas while I was away 🙂 One of the many things I have been working on is writing a clojure Arnoldc interpreter. If you are unfamiliar with Arnoldc, check out this link&#160; https://github.com/lhartikk/ArnoldC. &#160;I &#8230; <a href="https://javazquez.com/juan/2017/02/27/arnoldc-interpreter-using-clojure-instaparse/" class="more-link">Continue reading <span class="screen-reader-text">Arnoldc interpreter using Clojure instaparse</span> <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>Wow, I didn&#8217;t realize I had taken such a long sabbatical since my last post. I haven&#8217;t let off the coding gas while I was away <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> One of the many things I have been working on is writing a clojure Arnoldc interpreter. If you are unfamiliar with Arnoldc, check out this link&nbsp; <a href="https://github.com/lhartikk/ArnoldC">https://github.com/lhartikk/ArnoldC</a>. &nbsp;I had come across <a href="https://github.com/Engelberg/instaparse" target="_blank" rel="noopener">clojure instaparse</a>&nbsp;during the advent of code 2015 and used it to <a href="https://github.com/javazquez/advent-of-code/blob/master/clojure_advent_of_code_2015/src/clojure_advent_of_code/day7.clj" target="_blank" rel="noopener">solve day 7</a>&nbsp;and thought it was the perfect tool to accomplish my goal. &nbsp;Per the README on project page, &#8220;Instaparse aims to be the simplest way to build parsers in Clojure&#8221; and I couldn&#8217;t agree more.</p>
<p>The project is made up of the following clojure files:</p>
<ul>
<li><a href="https://github.com/javazquez/arnoldclj_interpreter/blob/master/src/arnoldclj_s/lexr.clj" target="_blank" rel="noopener">lexr.clj</a></li>
<li><a href="https://github.com/javazquez/arnoldclj_interpreter/blob/master/src/arnoldclj_s/interpreter.clj" target="_blank" rel="noopener">interpreter.clj</a></li>
</ul>
<h1>The <a href="https://github.com/javazquez/arnoldclj_interpreter/blob/master/src/arnoldclj_s/lexr.clj" target="_blank" rel="noopener">lexr.clj</a> (Parser)</h1>
<p>The lexr file contains the code utilizing the instaparse library to transform&nbsp;Arnoldc strings into&nbsp;<a href="https://github.com/weavejester/hiccup" target="_blank" rel="noopener">hiccup</a>&nbsp;structures. Below is a brief description of the clojure <strong>vars</strong> and functions within the lexr and interpreter.</p>
<p>NOTE: I left out code that supported <a href="https://github.com/javazquez/arnoldclj_interpreter/blob/master/src/arnoldclj_s/lexr.clj#L117" target="_blank" rel="noopener">my need to capture the actual thrown parse exception instead of the default</a>&nbsp;implemented within the library. Refer to <a href="http://stackoverflow.com/questions/26338945/how-to-test-for-texts-not-fitting-an-instaparse-grammar-clojure">http://stackoverflow.com/questions/26338945/how-to-test-for-texts-not-fitting-an-instaparse-grammar-clojure</a>&nbsp;for further details.</p>
<p>ADDITIONAL NOTE: I use ,,, in place of ellipsis as commas are whitespace with in clojure <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> I also bold parenthesis when used as part of clojure code in the hopes that it adds clarity.</p>
<h2>(def tokens ,,,)</h2>
<p>This contains a map of all the tokens of the Arnoldc language. I created this with the idea that I could show how easy it would be to transform the language and continue to have the same functionality. At the end of the post&nbsp;I describe&nbsp;an example of this with&nbsp;<a href="https://github.com/javazquez/arnoldclj_interpreter/blob/master/src/arnoldclj_s/pig_latin_lexr.clj" target="_blank" rel="noopener">arnoldc pig latin lexr</a>&nbsp;and the&nbsp;<a href="https://github.com/javazquez/arnoldclj_interpreter/blob/master/test/arnoldclj_s/pig_latin_arith_test.clj" target="_blank" rel="noopener">test</a></p>
<h2>(defn&nbsp;<a href="https://github.com/javazquez/arnoldclj_interpreter/blob/master/src/arnoldclj_s/lexr.clj#L51">arnold-grammar</a> ,,,)</h2>
<p>This function will create the string representation of the Arnoldc grammar. As clojure core doesn&#8217;t contain string interpolation, this is not the greatest&nbsp;looking&#8230; When you combine the tokens and the string you would receive the following string<br />
<script src="https://gist.github.com/javazquez/28b07357a601a7606b38726697077eab.js"></script></p>
<h2>(def arnoldc (insta/parser arnold-grammar))</h2>
<p>This is where the parsing magic happens. &nbsp;Passing in a string will parse it into hiccup structures according to the Arnoldc grammar that I defined.</p>
<p>example usage is <a href="https://github.com/javazquez/arnoldclj_interpreter/blob/master/src/arnoldclj_s/lexr.clj#L124" target="_blank" rel="noopener"><b>here</b></a></p>
<h2><a href="https://github.com/javazquez/arnoldclj_interpreter/blob/master/src/arnoldclj_s/lexr.clj#L5">(def transform-ops ,,,)</a></h2>
<p>This map&nbsp;was&nbsp;created to transform&nbsp;the parsed elements that match&nbsp;clojure keyswords. Early versions of the transform&nbsp;simply returned values &nbsp;0, 1 for <strong>@I LIED</strong> and <strong>@NO PROBLEMO </strong>that were not in&nbsp;the hiccup style [:key value] .&nbsp;I needed these specific elements to conform to a hiccup shape so that I could evaluate it in a consistent way when I wrote my interpreter. For clarity:</p>
<ul>
<li>I originally returned 0 then transformed it into &nbsp;[:false 0]</li>
<li>I originally returned 1 then transformed it into [:true 1]</li>
</ul>
<p>I found that the original version(returning just the value 0 or 1) made the interpreter much more complicated as I was having to check which kind of structure I was receiving after recursing down to the returned value. &nbsp;By adjusting the transform to return a hiccup structure I was able to remove the complex validation checks I was building due to&nbsp;the keyword that told me what I was dealing with. &nbsp;This allowed me to continue to rely on multimethods that were guaranteed to get the correct structure and use the&nbsp;same recursive function for all the tokens.</p>
<h2>(<span class="pl-k">defn</span> <span class="pl-e">lights-camera-action ,,,)&nbsp;</span></h2>
<p>This wraps the Arnoldc instaparse parser and is what should be used to <a href="https://github.com/javazquez/arnoldclj_interpreter/blob/master/test/arnoldclj_s/arithmetic_test.clj#L7" target="_blank" rel="noopener">parse Arnoldc strings.&nbsp;</a></p>
<h1><a href="https://github.com/javazquez/arnoldclj_interpreter/blob/master/src/arnoldclj_s/interpreter.clj" target="_blank" rel="noopener">The interpreter.clj</a></h1>
<p>The interpreter is mostly a multimethod that is dispatched on the first element within a hiccup structure(a clojure keyword). A global&nbsp;<strong>symbol-table&nbsp;</strong> is used to hold&nbsp;variables and state. I will describe a some&nbsp;of the more interesting items below.</p>
<h2>(<span class="pl-k">def</span> <span class="pl-e">symbol-table</span> (<span class="pl-en">atom</span> {}))</h2>
<p>This atom is a &nbsp;map that holds the state for an Arnoldc program.</p>
<p><strong>DISCLAIMER:&nbsp;</strong>I made a trade-off in my design with how I implemented garbage collection&#8230;. I haven&#8217;t done it yet. Completing a program will clear the <strong>symbol-table</strong>, however running a long enough loop that calls a function with parameters will eventually cause problems. Details on how variables are created can be found below in the <strong>&nbsp;(<span class="pl-k">defn</span> <span class="pl-e">transform-method-variables ,,,)&nbsp;</span></strong><span class="pl-e">section.</span></p>
<h2>(<span class="pl-k">defmulti</span> run (<span class="pl-k">fn</span> [s] (<span class="pl-en">nth</span> s <span class="pl-c1">0</span>)))</h2>
<p>This <a href="https://clojure.org/reference/multimethods" target="_blank" rel="noopener">multimethod</a> is the engine that powers the interpreter. It is dispatching on the keywords within each hiccup structure(clojure vector) which is always in the 0 position of each vector.</p>
<h2>(<span class="pl-k">defmethod</span> run <span class="pl-c1">:Program ,,,)</span></h2>
<p>The Arnoldc language allows methods to be declared before, after, or both before and after the main program. The <strong>let</strong> form(see below) separates out all the method declarations via the &nbsp;clojure&nbsp;<strong>group-by</strong>&nbsp;function so that I can define them(by run-statements which will dispatch to multimethods) before they are called within the main Arnoldc program(via <strong>(run bmain)&nbsp;</strong>). <strong>bmain&nbsp;</strong>gets all statements that evaluate to true via&nbsp;group-by, while <strong>method-des</strong> gets all the method declarations.</p>
<p>I reset the <strong>symbol-table</strong> when the program completes so that I don&#8217;t pollute subsequent runs. To see what can happen, comment out the <strong>(reset! symbol-table {})&nbsp;</strong>line and run the tests :). You will find that the symbol table keeps the state around and causes problems between tests that use the same method declarations and variables.</p>
<pre class="brush: java; gutter: true">(defmethod run :Program [[e &amp; rest :as statements]]
 (let [ {[bmain] true method-des false} 
                (group-by #(= :begin-main (first %)) rest)]
 (try 
   (run-statements method-des)
   (run bmain)
 (catch Exception e (throw e))
 (finally
  (reset! symbol-table {})))))</pre>
<h2>(<span class="pl-k">defn</span> <span class="pl-e">arithmetic-helper ,,,)</span></h2>
<p>This function handles the Arnoldc logic and arithmetic operators. The thing to note is the following <a href="https://github.com/javazquez/arnoldclj_interpreter/blob/master/src/arnoldclj_s/interpreter.clj#L104" target="_blank" rel="noopener">lines of code</a>.&nbsp;<strong>case&nbsp;</strong>is wrapped in a second set of parenthesis in order to immediately call the returned function from <strong>choose-logic-op</strong> or <strong>choose-op</strong>. The function will be invoked&nbsp;with&nbsp;<strong>operand</strong> and the result of&nbsp;<strong>(run varnum-node)</strong> as parameters.</p>
<p>A function case, will return a function and be passed and operand the the result of a multimethod dispatch against <strong>varnum-node</strong>.&nbsp;Higher order functions FTW!</p>
<pre class="brush: java; gutter: true">(recur ( (case arith-key
           :logical-op (choose-logic-op operator)
           :arithmetic-op (choose-op operator)) 
         operand 
         (run varnum-node)) 
  rest)</pre>
<h2>(<span class="pl-k">defn</span> <span class="pl-e">transform-method-variables ,,,)</span></h2>
<p>This function&nbsp;is called by the&nbsp;<a href="https://github.com/javazquez/arnoldclj_interpreter/blob/master/src/arnoldclj_s/interpreter.clj#L179" target="_blank" rel="noopener">:call-method multimethod</a>. I used&nbsp;<a href="https://github.com/javazquez/arnoldclj_interpreter/blob/master/src/arnoldclj_s/interpreter.clj#L182" target="_blank" rel="noopener">gensym and the method name</a>&nbsp;to create a prefix to be passed to the&nbsp;<strong><span class="pl-e">transform-method-variables&nbsp;</span></strong><span class="pl-e">function. I did this as I am storing the variables all in the &#8220;global&#8221;&nbsp;<strong>symbol-table</strong> atom. An&nbsp;issue this function resolved was one that I encountered in recursive test cases where I would stomp on variables declared in the methods as they were called multiple times. I created&nbsp;<a href="https://github.com/javazquez/arnoldclj_interpreter/issues/1" target="_blank" rel="noopener">an issue</a>&nbsp;to clean this up.</span></p>
<h2><a href="https://github.com/javazquez/arnoldclj_interpreter/blob/master/src/arnoldclj_s/interpreter.clj#L179" target="_blank" rel="noopener">(<span class="pl-k">defmethod</span> run <span class="pl-c1">:call-method ,,,)</span></a></h2>
<p>Most of the complexity of this code is in the handling of arguments passed to the method(if/when they are passed).&nbsp;<strong>new-meth-args</strong>&nbsp;gets the same treatment as the variables mentioned in the&nbsp;<strong><span class="pl-e">transform-method-variables&nbsp;</span></strong><span class="pl-e">function mentioned above and&nbsp;gets a prefix.&nbsp;</span></p>
<h2>(<span class="pl-k">defn</span> <span class="pl-e">roll-credits ,,,)</span></h2>
<p>This function is the preferred way to interpret Arnoldc code. See the <a href="https://github.com/javazquez/arnoldclj_interpreter/blob/master/test/arnoldclj_s/interpret_feature_test.clj#L7" target="_blank" rel="noopener">tests for an example</a>.</p>
<pre class="brush: groovy; gutter: true">(roll-credits  &quot;IT&#039;S SHOWTIME
         HEY CHRISTMAS TREE var
         YOU SET US UP 123
         YOU HAVE BEEN TERMINATED&quot; )</pre>
<h1><a href="https://github.com/javazquez/arnoldclj_interpreter/blob/master/src/arnoldclj_s/pig_latin_lexr.clj" target="_blank" rel="noopener">Pig Latin Arnoldc lexr</a></h1>
<p>As mentioned in the&nbsp;<strong>(def tokens ,,,)</strong> section above, we have finally reached the section where I describe why I defined the tokens outside of the&nbsp;<strong>arnoldc-grammar</strong>. The key to the transformation is&nbsp;the&nbsp;<strong><a href="https://github.com/javazquez/arnoldclj_interpreter/blob/master/src/arnoldclj_s/pig_latin_lexr.clj#L25" target="_blank" rel="noopener">update-map</a></strong>&nbsp;function which will transform all the values within a map.</p>
<h3>(def pig-latin-arnoldc ,,,)</h3>
<p>The following function code will</p>
<ol>
<li>use the <strong>update-map </strong>function and take&nbsp;the arnoldc <a href="https://github.com/javazquez/arnoldclj_interpreter/blob/master/src/arnoldclj_s/lexr.clj#L15" target="_blank" rel="noopener">tokens</a>&nbsp;map and return a map with the same keys, but with new pig latin arnoldc values(the qoutes that make up the language). The <strong>translate-to-pig-latin</strong>&nbsp;function will split a string on whitespace and map the&nbsp;<strong><span class="pl-e"><a href="https://github.com/javazquez/arnoldclj_interpreter/blob/master/src/arnoldclj_s/pig_latin_lexr.clj#L12" target="_blank" rel="noopener">pig-latin</a>&nbsp;</span></strong><span class="pl-e">function to all the strings from the split and then <strong>join&nbsp;</strong> them together to form a pig latin string.&nbsp;</span></li>
<li>pass the &#8220;new&#8221; map&nbsp;of the pig latin arnoldc language(described in #1) to the arnold-grammar function. Since the keywords stay the same, the function will simply pull out the new values mapped to the original arnoldc keys and insert them into the grammar.</li>
<li>Finally insta/parser will return an&nbsp;executable parser based on the pig-latin grammar.</li>
</ol>
<pre class="brush: groovy; gutter: true">(def pig-latin-arnoldc
  (-&amp;gt; (update-map arnie/tokens translate-to-pig-latin);#1
      (arnie/arnold-grammar);#2
      (insta/parser)));#3</pre>
<h3><a href="https://github.com/javazquez/arnoldclj_interpreter/blob/master/src/arnoldclj_s/pig_latin_lexr.clj#L40" target="_blank" rel="noopener">(<span class="pl-k">defn</span> <span class="pl-e">ights-camera-actionlay</span>&nbsp;,,,)</a></h3>
<p>This function is the pig latinified&nbsp;<strong>lights-camera-action</strong> function from the arnoldc lexr.</p>
<ol>
<li>pass the <a href="https://github.com/javazquez/arnoldclj_interpreter/blob/master/src/arnoldclj_s/lexr.clj#L117" target="_blank" rel="noopener">arnoldc lexr&#8217;s parser function</a>&nbsp;the pig latin transformed string(s) represented by&nbsp;<strong>expr.</strong></li>
<li>transform the parsed&nbsp;hiccup datastructures that match the keys within&nbsp;the&nbsp;<strong>transform-ops</strong> from the arnoldc lexr. This continues to work without modification because the map keys remain the same as the orignal arnoldc definitions(we only updated the values :D).</li>
<li>&nbsp;catch any thrown parse errors</li>
</ol>
<pre class="brush: groovy; gutter: true">(defn ights-camera-actionlay [&amp;amp; expr]
&quot;interpret pig-latin text&quot;
  (try (-&amp;gt;&amp;gt; (arnie/parser pig-latin-arnoldc (clojure.string/join expr));#1
            (insta/transform arnie/transform-ops));#2
       (catch Exception e 
         (throw (Exception.  (str &quot;EREWHAY ETHAY UCKFAY IDDAY IWAY OGAY ONGWRAY?&quot; (.getMessage e)))))))</pre>
<h1>Conclusion</h1>
<p>I was really satisfied with how quickly instaparse allowed me to create an interpreter. The hiccup structures were easy to work with and clojure is a joy to code in. I will certainly be keeping it within my toolbox and I encourage you to try it out.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://javazquez.com/juan/2017/02/27/arnoldc-interpreter-using-clojure-instaparse/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Grails Starter kit</title>
		<link>https://javazquez.com/juan/2015/01/06/grails-starter-kit/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=grails-starter-kit</link>
					<comments>https://javazquez.com/juan/2015/01/06/grails-starter-kit/#comments</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Wed, 07 Jan 2015 00:29:29 +0000</pubDate>
				<category><![CDATA[code]]></category>
		<category><![CDATA[Grails]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jvm]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[configuration]]></category>
		<category><![CDATA[Howto]]></category>
		<category><![CDATA[Programming]]></category>
		<guid isPermaLink="false">http://javazquez.com/juan/?p=533</guid>

					<description><![CDATA[After years of working with Grails, I thought I would put down in one placeÂ a few things I tend to use frequently in my Grails projects. These are thingsÂ I thought might help others getting started with Grails. Templates I often find that I need to extend the default session timeout(found in the src/templates). All that &#8230; <a href="https://javazquez.com/juan/2015/01/06/grails-starter-kit/" class="more-link">Continue reading <span class="screen-reader-text">Grails Starter kit</span> <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>After years of working with Grails, I thought I would put down in one placeÂ a few things I tend to use frequently in my Grails projects. These are thingsÂ I thought might help others getting started with Grails.</p>
<h2>Templates</h2>
<p>I often find that I need to extend the default session timeout(found in the src/templates). All that is needed is</p>
<pre class="brush: groovy; gutter: true">&gt; grails install-templates</pre>
<p>You will then need to edit the web.xml contained in the following directory structure that was generated from the above command.</p>
<p>src -&gt; templates -&gt; war -&gt; web.xml</p>
<p>you can nowÂ modify the timeout value</p>
<pre class="brush: groovy; gutter: true">&lt;session-config&gt;
    &lt;session-timeout&gt;180&lt;/session-timeout&gt;
 &lt;/session-config&gt;
</pre>
<h3>Custom Domain Classes</h3>
<p>Update your domain class templates to <strong>reduce</strong> having to <strong>type</strong> in <strong>your companyÂ </strong><strong>standards</strong> for every domain class. One of the environments I worked in had a databaseÂ standard that required us to labelÂ Primary Key column name(PK_column_name) and use oracle&#8217;s generator for ids. I addressed this by creating a private company &#8220;db standards&#8221; Grails plugin.</p>
<p>First I updated the</p>
<p><strong>templates-&gt; artifacts -&gt;DomainClass.groovy file</strong></p>
<pre class="brush: groovy; gutter: true">@artifact.package@class @artifact.name@ {
    Date lastUpdated
    Date dateCreated
    String createdBy
    String updatedBy

    static constraints = {

    }
    static mapping={
        id generator: &#039;sequence&#039;, params: [sequence: &#039;@artifact.name.uppercase@_SEQ&#039;]
        columns { id column: &#039;PK_@artifact.name.uppercase@_ID&#039; }//prod/test
    }
}</pre>
<p><script src="https://gist.github.com/javazquez/06b70ac01890bbdc912c.js"></script>I then copied and modified a core grails script(see comments in code) that creates domain classes and renamed it <b>create-my-domain</b>(well it was better names then this&#8230; but you get the gist :D). See below.<script src="https://gist.github.com/javazquez/ab61a129425763c15796.js"></script><br />
Then I can run</p>
<pre class="brush: groovy; gutter: true">&gt;create-my-domain Book</pre>
<p>The following concrete domain class is generated(notice the sequence,id, and generator are all there).</p>
<pre class="brush: groovy; gutter: true">class Book{

  Date lastUpdated
  Date dateCreated
  String createdBy
  String updatedBy
  static mapping = {
    id generator: &#039;sequence&#039;, params: [sequence: &#039;BOOK_SEQ&#039;]
    columns { id column: &#039;PK_BOOK_ID&#039; }
}
</pre>
<h2>DataSource(s)</h2>
<p>There are times when I need to query a database that I don&#8217;t need/want a Domain Class for. Â I tend to create a <strong>datasource</strong> and <strong>inject it</strong> into a service that will be handling the connection/query with <strong>groovySql</strong><code><br />
</code></p>
<p>Here is an example datasource in the DataSource.groovy file.</p>
<pre class="brush: groovy; gutter: true">dataSource_salesInfo {
  driverClassName = &quot;oracle.jdbc.driver.OracleDriver&quot;
  url = &quot;&quot;//more on how to configure this later in this blog entry
  username = &quot;&quot;

  password = &quot;&quot;
  dialect = &quot;org.hibernate.dialect.Oracle10gDialect&quot;
  hibernate {
    cache {
      use_second_level_cache = false
      use_query_cache = false
    }
  }
}</pre>
<p>Example service that uses the <strong>defined datasource entry.</strong></p>
<pre class="brush: groovy; gutter: true">class AwesomeService{

  def dataSource_salesInfo //Inject it

  def queryDB(){
  def sql = new Sql(dataSource_salesInfo)
  String myQuery =&#039;..&#039;
  sql.rows(myQuery).each { resultSet -&gt; /*do something*/}
  }
}</pre>
<h3>Externalize Datasources</h3>
<p>One way to externalize your jdbc connection url is to use an system environment variable. Another is to have your operations team generate a <strong>properties</strong> file based on the tnsnames.ora file and read it into your grails application. I will describe how the properties file based solution would work.<br />
An Example <strong>tnsnames.properties </strong>entry might look like the following.<code><br />
</code></p>
<pre class="brush: groovy; gutter: true">DATAWAREHOUSE=jdbc:oracle:thin:@xyaeyp49:1521:DATAWAREHOUSE</pre>
<p>in datasource.groovy file, I add the following to the top of the file.<code><br />
</code></p>
<pre class="brush: groovy; gutter: true">def props = new Properties()
new File(&#039;pathToTNS.properties&#039;).withInputStream { stream -&gt; 
props.load(stream) }</pre>
<p>then IÂ reference the property in the URL entryÂ for the datasource I am working withÂ <code><br />
</code></p>
<pre class="brush: groovy; gutter: false">username=&#039;javazquez&#039;
url = props.get(&quot;DATAWAREHOUSE&quot;)
...
</pre>
<p>&nbsp;</p>
<p>Most of my day is spent with Oracle databases. The validation query that I use is</p>
<p>&nbsp;</p>
<pre class="brush: groovy; gutter: true">validationQuery = &quot;SELECT sysdate from dual&quot;</pre>
<p>here is a complete example.</p>
<pre class="brush: groovy; gutter: true">production {
  dataSource {
    url = props.get(&quot;DATAWAREHOUSE&quot;)
    username = &quot;&quot;
    password = &quot;&quot;
    properties {
      maxActive = -1
      minEvictableIdleTimeMillis = 1800000
      timeBetweenEvictionRunsMillis = 1800000
      numTestsPerEvictionRun = 3
      testOnBorrow = true
      testWhileIdle = true
      testOnReturn = true
      validationQuery = &quot;SELECT sysdate from dual&quot;
    }
  }
}</pre>
<p>&nbsp;</p>
<p><code>Here are the lines that actually allow you to externalize your config/datasources(<strong>Thanks to <a title="Burt Beckwith" href="http://burtbeckwith.com/blog/" target="_blank">Burt Beckwith</a>Â and his <a title="Programming Grails" href="http://shop.oreilly.com/product/0636920024750.do" target="_blank">book</a></strong>Â )</code></p>
<p>&nbsp;</p>
<pre class="brush: groovy; gutter: true">production {
grails.config.locations = [
&quot;file:path_2_external_config.properties&quot; //NOTE: donâ€<img src="https://s.w.org/images/core/emoji/14.0.0/72x72/2122.png" alt="™" class="wp-smiley" style="height: 1em; max-height: 1em;" />t leave spaces
]
}</pre>
<p><strong>I like to have the following in my path</strong></p>
<pre class="brush: groovy; gutter: true">grails.config.locations = [
 &quot;file:path_${appName}/${appName}_${grails.util.Environment.current.name}_config.groovy&quot;,
]</pre>
<p>This forces the file name to haveÂ <strong>development || production || testÂ </strong>and the application name in the configuration file to prevent copy and paste errors(<strong>you would never do that right <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> )</strong></p>
<h2>SQL Logging</h2>
<p>There are a couple of ways to see what is going on under the hood when your application is querying the database.</p>
<p>The easiest is to add the <strong>logSql = trueÂ </strong>to your datasource</p>
<pre class="brush: groovy; gutter: true">development {
  dataSource {
    url = props.get(&quot;DATAWAREHOUSE&quot;)
    logSql = true
    ...
    }
  }
}</pre>
<p>If you need more information, Â <strong>Burt Beckwith</strong> has the following <a title="Logging Hibernate SQL" href="https://burtbeckwith.com/blog/?p=1604">Logging Hibernate SQL</a> post that you should read. He shows howÂ adding the following lines to yourÂ <strong>log4j</strong> closure will help with understanding what is happening under the hood.</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td class="code">
<div class="container">
<div class="line number1 index0 alt2"><code class="java plain">log4j = {</code></div>
<div class="line number2 index1 alt1"><code class="java spaces">Â Â Â </code><code class="java plain">...</code></div>
<div class="line number3 index2 alt2"><code class="java spaces">Â Â Â </code><code class="java plain">debug </code><code class="java string">'org.hibernate.SQL'</code></div>
<div class="line number4 index3 alt1"><code class="java spaces">Â Â Â </code><code class="java plain">trace </code><code class="java string">'org.hibernate.type.descriptor.sql.BasicBinder'</code></div>
<div class="line number5 index4 alt2"><code class="java plain">}</code></div>
</div>
</td>
</tr>
</tbody>
</table>
<h2>Misc</h2>
<h4>A log pattern that works with tomcat(YMMV)</h4>
<pre class="brush: groovy; gutter: true">appenders {
console name: &#039;stdout&#039;, threshold: org.apache.log4j.Level.INFO
rollingFile name: &#039;MyLogs&#039;, file: &#039;logs/MyLog.log&#039;, maxSize: 104576, threshold: org.apache.log4j.Level.INFO ,
layout:pattern(conversionPattern: &quot;%d{yyyy-MM-dd HH:mm:ss} [%t] %p %c - %m%n&quot;)

}

</pre>
<h4><code>Have your war tell you what environment you are deploying to<br />
</code></h4>
<pre class="brush: groovy; gutter: true">grails.project.war.file = &quot;target/${appName}-${appVersion}-${System.getProperty(&#039;grails.env&#039;)[0..3]}.war&quot;</pre>
<h3><code>Websites and links to check out</code></h3>
<ul>
<li><a title="Groovy Weekly" href="http://glaforge.appspot.com/" target="_blank">Groovy Weekly</a></li>
<li><a title="Burt Beckwith" href="http://burtbeckwith.com/blog/" target="_blank">An Army of Solipsists</a>Â &#8211; Burt Beckwith</li>
<li><a title="Mr Haki" href="http://mrhaki.blogspot.com/" target="_blank">http://mrhaki.blogspot.com/</a></li>
<li><a href="http://melix.github.io/blog">CÃ©dric Champeau&#8217;s blog</a></li>
<li><a title="Andres Almiray's blog" href="http://www.jroller.com/aalmiray/" target="_blank">Andres Almiray&#8217;s blog</a></li>
</ul>
<p>&nbsp;</p>
<p>Many of the things I have learned have come from the above links and people. A big <strong>Thank</strong>Â <strong>You</strong> to the gr8 community for all the help over the years.</p>
<p>&nbsp;</p>
<p>-Juan</p>
]]></content:encoded>
					
					<wfw:commentRss>https://javazquez.com/juan/2015/01/06/grails-starter-kit/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Grails  ldap integration with Active Directory via spring-security-ldap</title>
		<link>https://javazquez.com/juan/2013/08/10/grails-ldap-integration-with-active-directory-via-spring-security-ldap/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=grails-ldap-integration-with-active-directory-via-spring-security-ldap</link>
					<comments>https://javazquez.com/juan/2013/08/10/grails-ldap-integration-with-active-directory-via-spring-security-ldap/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sun, 11 Aug 2013 00:22:59 +0000</pubDate>
				<category><![CDATA[Administration]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[Grails]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[jvm]]></category>
		<category><![CDATA[Active Directory]]></category>
		<category><![CDATA[configuration]]></category>
		<category><![CDATA[fun]]></category>
		<category><![CDATA[Howto]]></category>
		<category><![CDATA[LDAP]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Security]]></category>
		<guid isPermaLink="false">http://javazquez.com/juan/?p=348</guid>

					<description><![CDATA[When I was tasked with integrating our grails apps with Active Directory I remember there being a scarcity of examples.. so I hope this code will save you some time ]]></description>
										<content:encoded><![CDATA[<p>The <a href="http://grails.org/plugin/spring-security-ldap" title="spring-security-ldap" target="_blank">spring-security-ldap</a> has great documentation. <a href="https://github.com/javazquez/Grails-Active-Directory-LDAP-example" title="I put together a working example" target="_blank">I put together a working example</a> (at least in my environment) to complement the docs. When I was tasked with integrating our grails apps with Active Directory I remember there being a scarcity of examples.. so I hope <a href="https://github.com/javazquez/Grails-Active-Directory-LDAP-example" title="github ldap code" target="_blank">this code</a> will save you some time in getting ldap working with Active Directory in your grails environment. </p>
<p>Important files </p>
<p><a href='https://github.com/javazquez/Grails-Active-Directory-LDAP-example/blob/master/grails-app/conf/Config.groovy' target='_blank' >grails-app/conf/Config.groovy</a> <br />
<a href='https://github.com/javazquez/Grails-Active-Directory-LDAP-example/blob/master/src/groovy/com/javazquez/ldapexample/MyUserDetailsContextMapper.groovy' target='_blank'>src/groovy/com/javazquez/ldapexample/MyUserDetailsContextMapper.groovy</a><br />
<a href='https://github.com/javazquez/Grails-Active-Directory-LDAP-example/blob/master/src/groovy/com/javazquez/ldapexample/MyUserDetails.groovy' target='_blank'>src/groovy/com/javazquez/ldapexample/MyUserDetails.groovy</a><br />
<a href='https://github.com/javazquez/Grails-Active-Directory-LDAP-example/blob/master/grails-app/conf/spring/resources.groovy' target='_blank'>grails-app/conf/spring/resources.groovy</a></p>
<p>once you have your Active Directory configurations entered (grails-app/conf/Config.groovy), fire up your app and<br />
test it out by logging in via the login controller.</p>
<p>Notes</p>
<ul>
<li> You may have to update <strong>MyUserDetailsContextMapper.groovy</strong> as my Active Directory environment may differ from yours. </li>
<li> You may also want to update <strong>MyUserDetails.groovy</strong> to hold more or less info than my config. </li>
</ul>
<p>-JV</p>
]]></content:encoded>
					
					<wfw:commentRss>https://javazquez.com/juan/2013/08/10/grails-ldap-integration-with-active-directory-via-spring-security-ldap/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Add Map, Reduce, and Filter to Groovy with an Extension Module</title>
		<link>https://javazquez.com/juan/2013/02/05/add-map-reduce-and-filter-to-groovy-with-groovy-extension-modules/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=add-map-reduce-and-filter-to-groovy-with-groovy-extension-modules</link>
					<comments>https://javazquez.com/juan/2013/02/05/add-map-reduce-and-filter-to-groovy-with-groovy-extension-modules/#comments</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Wed, 06 Feb 2013 01:50:45 +0000</pubDate>
				<category><![CDATA[code]]></category>
		<category><![CDATA[Gradle]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[jvm]]></category>
		<category><![CDATA[fun]]></category>
		<category><![CDATA[functional]]></category>
		<category><![CDATA[Howto]]></category>
		<category><![CDATA[Programming]]></category>
		<guid isPermaLink="false">http://javazquez.com/juan/?p=476</guid>

					<description><![CDATA[To solidify my new understanding of Groovy's Extension Modules, I decided that I needed to write some code. The example I came up with was to have the functional names (map, reduce, filter ) that I had come familiar with in using Clojure added to Groovy. These "extended methods" are using Groovy's built-in collect, inject, and grep under the hood.
]]></description>
										<content:encoded><![CDATA[<p>Having just read <a href="http://mally.pl/working-with-legacy-code-is-fun-now/" target="_blank"><span> MichaÅ‚ Mally&#8217;s blog</span></a> that was posted on <a title="Groovy+" href="https://plus.google.com/communities/105160926044623621768" target="_blank">Google+</a>,<br />
I was intrigued with two benefits listed in the blog:</p>
<ul>
<li>The idea of being able to augment Groovy with changes that would behave as &#8220;if they were a part of original GDK&#8221;</li>
<li>support from your IDE like code completion shall be available out-of-the-box</li>
</ul>
<p>In order to get my head around how Extension modules worked, I used the following as references<br />
<a href="http://docs.codehaus.org/display/GROOVY/Creating+an+extension+module" target="_blank">Creating an extension module</a><br />
<a href="http://mrhaki.blogspot.com/2013/01/groovy-goodness-adding-extra-methods.html" target="_blank">Groovy Goodness: Adding Extra Methods Using Extension Modules </a><br />
<a href="http://blog.andresteingress.com/2012/09/07/groovy-extension-modules/" target="_blank">Groovy Extension Modules</a></p>
<p><a href="https://plus.google.com/116089789718222474948/posts" target="_blank">CÃ©dric Champeau </a> had this to say after I asked about the benefits of Extension Modules over using MetaClass/Expando/Category</p>
<blockquote><p>@Juan: extension modules are automatically loaded and made available globally. You don&#8217;t have to bother with metaclasses (and potential issues with external changes). As well, categories are lexically scoped, although extension modules are global (meaning that they can be used anywhere in the code as long as the extension module is found on classpath).</p>
<p>Last but not least, extension modules are compatible with type checking and static compilation <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p></blockquote>
<p>To solidify my new understanding of Groovy&#8217;s Extension Modules, I decided that I needed to write some code. The example I came up with was to have the functional names (map, reduce, filter ) that I had come familiar with in using <a href="http://clojure.org/" target="_blank">Clojure</a> added to Groovy. These &#8220;extended methods&#8221; are using Groovy&#8217;s built-in collect, inject, and grep under the hood.</p>
<p>Source code can be found <a href="https://github.com/javazquez/Groovy/tree/master/FuncProgExtensionModule" target="_blank">here</a></p>
<p>Here is the code for the new aliases found in the <a href="https://github.com/javazquez/Groovy/blob/master/FuncProgExtensionModule/src/main/groovy/com/javazquez/FuncProgUtilExtension.groovy" title="FuncProgExtensionModule" target="_blank"><strong>FuncProgUtilExtension.groovy</strong></a> class</p>
<pre class="brush: groovy; gutter: true">package com.javazquez;

public class FuncProgUtilExtension {
    public static Collection filter(Collection self, Closure clozure) {
	   return self.grep(clozure)
   }
   public static Collection map(Collection self, Closure clozure) {
	   return self.collect(clozure)
   }
   public static Object reduce(Collection self, Closure clozure) {
	   return self.inject(clozure)
   }
   public static Object reduce(Collection self, String operator) {
	   switch(operator){
		   case &#039;+&#039; :
		      self.inject({acc, val -&gt; acc + val})
			  break
		   case &#039;-&#039; :
			   self.inject({acc, val -&gt; acc - val})
			   break
		   case&#039;*&#039; :
			   self.inject({acc, val -&gt; acc * val})
			   break
		   case &#039;/&#039;:
		   	   self.inject({acc, val -&gt; acc / val})
			   break
		   case&#039;**&#039;:
		   	   self.inject({acc, val -&gt; Math.pow(acc, val)})
			   break
		   default:
			   throw new IllegalArgumentException()
			   break
	   }
   }
}</pre>
<p>In a file named &#8216;org.codehaus.groovy.runtime.ExtensionModule&#8217; located in <a href="https://github.com/javazquez/Groovy/blob/master/FuncProgExtensionModule/src/main/resources/META-INF/services/org.codehaus.groovy.runtime.ExtensionModule" target="_blank">&#8216;src/main/resources/META-INF/services/&#8217;</a></p>
<p>I have the following<br />
<code><br />
moduleName=<span>JavazquezFuncProgTest<br />
moduleVersion=1.0<br />
extensionClasses=com.javazquez.FuncProgUtilExtention<br />
</span></code></p>
<p><span>Using <span>spock</span>, I wrote the following </span><a href="https://github.com/javazquez/Groovy/blob/master/FuncProgExtensionModule/src/test/groovy/com/javazquez/FuncProgUtilSpec.groovy" target="_blank">tests</a> :</p>
<pre class="brush: groovy; gutter: true">package com.javazquez

import spock.lang.Specification

class FuncProgUtilSpec extends Specification{

	def &quot;test map&quot;(){
		expect:
			[ 1 ,2 ,3 ,4].map{it*2} == 	[ 1 ,2 ,3 ,4].collect{ it*2 } 	
	}	
	def &quot;test reduce &quot;(){
		expect:
			[ 1 ,2 ,3].reduce(&#039;*&#039;) == 6
			[ 1 ,2 ,3,4].reduce(&#039;+&#039;) == 10
			[ &#039;1&#039; ,&#039;2&#039; ,&#039;3&#039;,&#039;4&#039;].reduce(&#039;+&#039;) == &#039;1234&#039;
			[ 1 ,2 ,3].reduce(&#039;-&#039;) == -4
			[ 2, 2 ,2].reduce(&#039;**&#039;) == 16
			[ 1 ,2 ,3].reduce({acc, val -&gt; acc + val}) ==[ 1 ,2 ,3].inject { acc, val -&gt; acc + val}
	}
	def &quot;test invalid argument&quot;(){
	 	when:
	 		[ 1 ,2 ,3,4].reduce(&#039;%&#039;)
		then:
			thrown(IllegalArgumentException)
	}
	def &quot;test filter&quot;(){
		expect:
			[1,2,3,4,5,6,7,8,9].filter { it % 2 ==0 } == [2,4,6,8]
			[1,2,3,4,5,6,7,8,9].filter { it &gt; 2 } == [3,4,5,6,7,8,9]
			&quot;Juan Vazquez&quot;.toList().filter { it ==~ /[aeiou]/} == [&#039;u&#039;,&#039;a&#039;,&#039;a&#039;,&#039;u&#039;,&#039;e&#039;]
	}
}</pre>
<p>My biggest obstacle was getting the directory structure correct. It is amazing how little code was required to accomplish my goal. I hope my example project and listed references will help in your understanding of this powerful feature. My next step with this project going to be to make evaluation lazy.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://javazquez.com/juan/2013/02/05/add-map-reduce-and-filter-to-groovy-with-groovy-extension-modules/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Groovy Invoke Dynamic Support</title>
		<link>https://javazquez.com/juan/2013/01/26/groovy-invoke-dynamic-support/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=groovy-invoke-dynamic-support</link>
					<comments>https://javazquez.com/juan/2013/01/26/groovy-invoke-dynamic-support/#comments</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sun, 27 Jan 2013 02:41:44 +0000</pubDate>
				<category><![CDATA[code]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jvm]]></category>
		<category><![CDATA[configuration]]></category>
		<category><![CDATA[Linux]]></category>
		<guid isPermaLink="false">http://javazquez.com/juan/?p=463</guid>

					<description><![CDATA[In order to get things working, I read that I needed to get the "indy" jar on my classpath. I added the following to my .bash_profile and restarted my terminal and the error cleared up]]></description>
										<content:encoded><![CDATA[<p>The release of Groovy 2.1 comes with <a title="" href="http://groovy.codehaus.org/Groovy+2.1+release+notes?nc#Groovy21releasenotes-Fullinvokedynamicsupport" target="_blank">full Invoke Dynamic Support</a>. Initially I had issues with trying to get a working example up and running as seen by the following message.</p>
<p><strong>&gt;groovy &#8211;indy mergesort.groovy</strong><br />
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:<br />
General error during class generation: Cannot use invokedynamic, indy module was excluded from this build.</p>
<p>I checked the groovy version to make sure that I had Java 7 loaded as seen here<br />
<strong>groovy -version</strong><br />
Groovy Version: 2.1.0 JVM: 1.7.0_11 Vendor: Oracle Corporation OS: Mac OS X</p>
<p>In order to get things working, I read that <a title="" href="http://derjan.io/blog/2012/08/08/first-steps-with-groovys-invokedynamic-support/" target="_blank">I needed to get the &#8220;indy&#8221; jar on my classpath</a>. I added the following to my .bash_profile and restarted my terminal and the error cleared up</p>
<p><strong>export CLASSPATH=$HOME/.gvm/groovy/current/indy/groovy-2.1.0-indy.jar</strong></p>
<p>Hope this helps and a huge thanks to the Groovy Core Team for this latest update!</p>
<p>-Juan</p>
]]></content:encoded>
					
					<wfw:commentRss>https://javazquez.com/juan/2013/01/26/groovy-invoke-dynamic-support/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Using Groovy closures to fake Python generators</title>
		<link>https://javazquez.com/juan/2012/09/08/using-groovy-closures-to-fake-python-generators/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-groovy-closures-to-fake-python-generators</link>
					<comments>https://javazquez.com/juan/2012/09/08/using-groovy-closures-to-fake-python-generators/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 08 Sep 2012 20:10:53 +0000</pubDate>
				<category><![CDATA[Groovy]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[closure]]></category>
		<category><![CDATA[fibonacci]]></category>
		<category><![CDATA[Generator]]></category>
		<guid isPermaLink="false">http://javazquez.com/juan/?p=368</guid>

					<description><![CDATA[Here is a quick example of faking python generators with Groovy. Please update the comments if you have a better approach. def (a,b,sent,acc) = [0,1,null,0] def fib={ (a,b) = [b,a+=b] a } while(true){ currFibValue = fib() if( currFibValue &#62; 4000000) break else if( currFibValue % 2 ==0) acc += currFibValue } println acc]]></description>
										<content:encoded><![CDATA[<p>Here is a quick example of faking python generators with Groovy. Please update the comments if you have a better approach. </p>
<pre class="brush: groovy; gutter: true; first-line: 1; highlight: []; html-script: false">
def (a,b,sent,acc) = [0,1,null,0]
def fib={
    (a,b) = [b,a+=b]
    a
}

while(true){
    currFibValue = fib()
    if( currFibValue &gt; 4000000) break
    else if( currFibValue % 2 ==0) acc += currFibValue
}
println acc
</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://javazquez.com/juan/2012/09/08/using-groovy-closures-to-fake-python-generators/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Clojure Soundex</title>
		<link>https://javazquez.com/juan/2012/08/28/clojure-soundex/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=clojure-soundex</link>
					<comments>https://javazquez.com/juan/2012/08/28/clojure-soundex/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Wed, 29 Aug 2012 03:57:50 +0000</pubDate>
				<category><![CDATA[Clojure]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[jvm]]></category>
		<category><![CDATA[fun]]></category>
		<category><![CDATA[Howto]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[soundex]]></category>
		<guid isPermaLink="false">http://javazquez.com/juan/?p=343</guid>

					<description><![CDATA[In need of a quick program to force myself to dive in to clojure, I chose to implement a soundex program that I at one time had written in C++. It was a fun exercise to step back and look at how my thought process changed based on the language I used. Hope you find &#8230; <a href="https://javazquez.com/juan/2012/08/28/clojure-soundex/" class="more-link">Continue reading <span class="screen-reader-text">Clojure Soundex</span> <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>In need of a quick program to force myself to dive in to clojure, I chose to implement a <a title="Soundex wiki" href="http://en.wikipedia.org/wiki/Soundex" target="_blank">soundex </a>program that I at one time had written in C++. It was a fun exercise to step back and look at how my thought process changed based on the language I used. Hope you find this useful.</p>
<p>&nbsp;</p>
<pre>;steps
;1 keep first letter
;2 replace consonants
;3 remove w and h
;4 two adjacent are same, letters with h or w separating are also the same
;5 remove vowels
;6 continue until 1 letter 3 nums</pre>
<pre class="brush: groovy; gutter: true">(use &#039;clojure.contrib.str-utils)

(defn trnsfrm[ word]
  (-&gt;&gt;
    (re-gsub #&quot;(?i)[fbvp]&quot; &quot;1&quot; word)
    (re-gsub #&quot;(?i)[cgjkqsxz]&quot; &quot;2&quot; ,,) 
    (re-gsub #&quot;(?i)[dt]&quot; &quot;3&quot; ,,) 
    (re-gsub #&quot;(?i)[l]&quot; &quot;4&quot; ,,)
    (re-gsub #&quot;(?i)[mn]&quot; &quot;5&quot; ,,)
    (re-gsub #&quot;(?i)[r]&quot; &quot;6&quot; ,,)))

(defn replace-adjacent [word] 
  (-&gt;&gt; (re-gsub  #&quot;(?i)[wh]&quot; &quot;&quot; word ) 
  	trnsfrm 
  	(re-gsub #&quot;(?i)([a-z0-9])\1+&quot; &quot;$1&quot; )))  	

(defn pad [word](subs (str word &quot;0000&quot;) 0 4))  	

(defn do-soundex [word]
    (pad ( str (first word)(re-gsub #&quot;[aeiouy]&quot;  &quot;&quot; (subs (replace-adjacent word) 1)))))</pre>
<p><strong>Update Refactored version</strong><br />
Not quite happy with the above example, I decided to see if I could refactor my code. Below is what I came up with(4 less lines code).</p>
<pre class="brush: groovy; gutter: true">(use &#039;clojure.contrib.str-utils)

(def re-map{ #&quot;(?i)[fbvp]&quot; &quot;1&quot;,#&quot;(?i)[cgjkqsxz]&quot; &quot;2&quot;,#&quot;(?i)[dt]&quot; &quot;3&quot;,#&quot;(?i)[l]&quot; &quot;4&quot;,#&quot;(?i)[mn]&quot; &quot;5&quot;,#&quot;(?i)[r]&quot; &quot;6&quot; })

(defn trns [word] (map #(re-gsub (key %1) (val %1) word) re-map))

(defn pad [word](subs (str word &quot;0000&quot;) 0 4))

(defn rm1 [word] (apply str(drop 1 word)))

(defn do-soundex [word]
    (pad(str (first word) (-&gt;&gt;
        (re-gsub #&quot;(?i)[^aeiou\d]&quot; &quot;&quot; (apply str (apply interleave (trns word ))))
        (re-gsub #&quot;(?i)([a-z\d])\1+&quot; &quot;$1&quot; )
        rm1
        (re-gsub #&quot;(?i)[a-z]&quot; &quot;&quot; )))))</pre>
<p>&nbsp;</p>
<p><strong>UPDATE 2:Always one to go back to my previous works, I thought I would try a different approach.Â </strong><br />
<script src="https://gist.github.com/javazquez/00319b7e412c72263867.js"></script><br />
<strong>Now for the test cases</strong></p>
<pre class="brush: groovy; gutter: true">;;;Start test
(=(do-soundex  &quot;Ashcroft&quot;) &quot;A261&quot;)
(=(do-soundex  &quot;Ashcraft&quot;) &quot;A261&quot;)
(=(do-soundex  &quot;Tymczak&quot;) &quot;T522&quot;)
(=(do-soundex  &quot;Pfister&quot;) &quot;P236&quot;)
(=(do-soundex&quot;lukaskiewicz&quot;)&quot;l222&quot;)
(=(do-soundex&quot;Rubin&quot;)&quot;R150&quot;)
(=(do-soundex&quot;Rupert&quot;)&quot;R163&quot;)
(=(do-soundex&quot;Robert&quot;)&quot;R163&quot;)
(=(do-soundex &quot;Vazquez&quot;)&quot;V220&quot;)

;;;end test</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://javazquez.com/juan/2012/08/28/clojure-soundex/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Simple Groovy project using Gradle</title>
		<link>https://javazquez.com/juan/2011/11/15/simple-groovy-project-using-gradle/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=simple-groovy-project-using-gradle</link>
					<comments>https://javazquez.com/juan/2011/11/15/simple-groovy-project-using-gradle/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Wed, 16 Nov 2011 02:40:23 +0000</pubDate>
				<category><![CDATA[code]]></category>
		<category><![CDATA[Gradle]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jvm]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[build]]></category>
		<category><![CDATA[configuration]]></category>
		<category><![CDATA[fun]]></category>
		<category><![CDATA[Howto]]></category>
		<category><![CDATA[Programming]]></category>
		<guid isPermaLink="false">http://javazquez.com/juan/?p=378</guid>

					<description><![CDATA[Gradle is a fantastic tool and I hope this article helps show the ease of getting a project set up.]]></description>
										<content:encoded><![CDATA[<p>Hello fellow Groovyists <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>I have been kicking the tires on using Gradle for my Groovy projects. I had a few stumbles along the way and wanted to share what I came up with for getting a very simple example working.</p>
<p>build.gradle<br />
<code><br />
apply plugin: 'groovy'<br />
version = "1.0-${new Date().format('yyyyMMdd')}"</p>
<p>manifest.mainAttributes("Main-Class" : "com.javazquez.HelloThere")</p>
<p>repositories {<br />
    mavenCentral()<br />
	mavenRepo urls: "http://groovypp.artifactoryonline.com/groovypp/libs-releases-local"<br />
}<br />
dependencies {<br />
	groovy group: 'org.codehaus.groovy', name: 'groovy-all', version: '1.8.4'<br />
	groovy group: 'org.mongodb', name: 'mongo-java-driver', version: '2.6.5'<br />
	groovy group: 'com.gmongo', name: 'gmongo', version: '0.9.1'<br />
	testCompile "org.spockframework:spock-core:0.5-groovy-1.8"<br />
}</p>
<p>jar {<br />
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }<br />
}<br />
</code></p>
<p>below is the the HelloThere.groovy file located src/main/groovy/com/javazquez/HelloThere<br />
<code><br />
package com.javazquez<br />
public class HelloThere {</p>
<p>    public static void main(String []args) {<br />
        println "Hello coders!"</p>
<p>    }    </p>
<p>}<br />
</code></p>
<p>after running <strong>gradle build</strong>, I can navigate to the build/libs directory and run <strong>java -jar HelloThere-1.0-20111115.jar </strong> and get the following ouptut</p>
<p>Hello coders!</p>
<p>Gradle is a fantastic tool and I hope this article helps show the ease of getting a project set up.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://javazquez.com/juan/2011/11/15/simple-groovy-project-using-gradle/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Activiti GET/POST REST requests with Groovy</title>
		<link>https://javazquez.com/juan/2011/10/12/activiti-getpost-rest-requests-with-groovy/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=activiti-getpost-rest-requests-with-groovy</link>
					<comments>https://javazquez.com/juan/2011/10/12/activiti-getpost-rest-requests-with-groovy/#comments</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Thu, 13 Oct 2011 00:30:06 +0000</pubDate>
				<category><![CDATA[Groovy]]></category>
		<category><![CDATA[activiti]]></category>
		<category><![CDATA[Authentication]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[GET]]></category>
		<category><![CDATA[Howto]]></category>
		<category><![CDATA[POST]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[Security]]></category>
		<guid isPermaLink="false">http://javazquez.com/juan/?p=371</guid>

					<description><![CDATA[I have been working with <a href="http://activiti.org/index.html" title="Activiti " target="_blank">Activiti</a> lately and needed to test the Rest API included with the demo. Below are the GET and POST requests I whipped up using Groovy.]]></description>
										<content:encoded><![CDATA[<p>I have been working with <a href="http://activiti.org/index.html" title="Activiti " target="_blank">Activiti</a> lately and needed to test the REST API included with the demo. Below are the GET and POST requests I whipped up using Groovy. Hope you find this useful <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<pre><code>
//---Get Request
@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.0' )
import groovyx.net.http.RESTClient

def client = new RESTClient('http://localhost:8080/activiti-rest/service/process-engine')
println client.get(headers:[Authorization:"Basic ${'kermit:kermit'.bytes.encodeBase64()}"]).data

// output
[name:default, exception:null, version:5.7, resourceUrl:jar:file:/Users/juanvazquez/Documents/activiti-5.7/apps/apache-tomcat-6.0.32/webapps/activiti-rest/WEB-INF/lib/activiti-cfg.jar!/activiti.cfg.xml]


// POST request
@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.0' )
import static groovyx.net.http.ContentType.JSON

def jsonObj = new groovy.json.JsonBuilder()
jsonObj{
  userId 'kermit'
  password 'kermit'
}
def client = new groovyx.net.http.RESTClient('http://localhost:8080/activiti-rest/service/login')
def response = client.post(contentType: JSON, body:jsonObj.toString() )

println response.data           

//output
[success:true]
</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://javazquez.com/juan/2011/10/12/activiti-getpost-rest-requests-with-groovy/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>POP3 Gmail access with Clojure and JavaMail</title>
		<link>https://javazquez.com/juan/2011/05/25/pop3-gmail-access-with-clojure-and-javamail/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=pop3-gmail-access-with-clojure-and-javamail</link>
					<comments>https://javazquez.com/juan/2011/05/25/pop3-gmail-access-with-clojure-and-javamail/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Wed, 25 May 2011 22:44:04 +0000</pubDate>
				<category><![CDATA[Administration]]></category>
		<category><![CDATA[Clojure]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jvm]]></category>
		<category><![CDATA[gmail]]></category>
		<category><![CDATA[google api]]></category>
		<category><![CDATA[Howto]]></category>
		<category><![CDATA[javamail]]></category>
		<category><![CDATA[pop3]]></category>
		<category><![CDATA[Programming]]></category>
		<guid isPermaLink="false">http://javazquez.com/juan/?p=357</guid>

					<description><![CDATA[I recently had the need to access gmail using Clojure. I used JavaMail to accomplish this via pop3. Below is some code that I wrote to help me get emails. Hope you find it useful Enjoy 🙂 (use '[clojure.contrib.duck-streams]) (def props (System/getProperties)) ; Get the default Session object. (def session (javax.mail.Session/getDefaultInstance props)) ; Get a &#8230; <a href="https://javazquez.com/juan/2011/05/25/pop3-gmail-access-with-clojure-and-javamail/" class="more-link">Continue reading <span class="screen-reader-text">POP3 Gmail access with Clojure and JavaMail</span> <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>I recently had the need to access gmail using Clojure. I used JavaMail to accomplish this via pop3. Below is some code that I wrote to help me get emails. Hope you find it useful  Enjoy <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p><code><br />
(use '[clojure.contrib.duck-streams])<br />
(def props (System/getProperties))<br />
  ; Get the default Session object.<br />
  (def session (javax.mail.Session/getDefaultInstance props))</p>
<p>  ; Get a Store object that implements the specified protocol.<br />
  (def store (.getStore session "pop3s"))</p>
<p>  ;Connect to the current host using the specified username and password.<br />
  (.connect store "pop.gmail.com" "username@gmail.com" "password")</p>
<p>  ;Create a Folder object corresponding to the given name.<br />
  (def folder (. store getFolder "inbox"))</p>
<p>  ; Open the Folder.<br />
(.open folder (javax.mail.Folder/READ_ONLY ))<br />
  ; Get the messages from the server<br />
  (def messages (.getMessages folder))</p>
<p>   (defn getFrom [message](javax.mail.internet.InternetAddress/toString (.getFrom message)))<br />
   (defn getReplyTo [message] (javax.mail.internet.InternetAddress/toString (.getReplyTo message)) )<br />
   (defn getSubject [message] (.getSubject message))</p>
<p>   ;print out the body of the message<br />
      (for [m messages] (read-lines(.getInputStream m)) )</p>
<p>;;;;;code for sending an email</p>
<p>(def props (System/getProperties))<br />
(. props put "mail.smtp.host", "smtp.gmail.com")<br />
(. props put "mail.smtp.port", "465")<br />
(. props put "mail.smtp.auth", "true")<br />
(. props put "mail.transport.protocol", "smtps")</p>
<p>(def session (javax.mail.Session/getDefaultInstance props nil))<br />
(def msg (javax.mail.internet.MimeMessage. session))<br />
(. msg setFrom (javax.mail.internet.InternetAddress. "sender@gmail.com"))<br />
(. msg addRecipients javax.mail.Message$RecipientType/TO<br />
   "receiver@gmail.com") </p>
<p>(. msg  setSubject "i am the subject")<br />
(. msg setText "I am the body!!!")</p>
<p>(. msg setHeader "X-Mailer", "msgsend")<br />
(. msg setSentDate (java.util.Date.))</p>
<p>    ; send the email<br />
(def transport (. session getTransport))<br />
(. transport connect "smtp.gmail.com" 465 "sender@gmail.com" "password")<br />
(. transport sendMessage msg (. msg getRecipients javax.mail.Message$RecipientType/TO))<br />
(. transport close)<br />
</code></p>
]]></content:encoded>
					
					<wfw:commentRss>https://javazquez.com/juan/2011/05/25/pop3-gmail-access-with-clojure-and-javamail/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
