<?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>karanar</title>
	<atom:link href="http://karanar.net/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://karanar.net</link>
	<description>java, android, ruby, rails, grails...</description>
	<lastBuildDate>Sun, 29 Aug 2010 08:36:34 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Installing redmine 1.0.1 on jruby and glassfish</title>
		<link>http://karanar.net/?p=265</link>
		<comments>http://karanar.net/?p=265#comments</comments>
		<pubDate>Fri, 27 Aug 2010 14:52:28 +0000</pubDate>
		<dc:creator>karanar</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Server]]></category>
		<category><![CDATA[glassfish]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[jruby]]></category>
		<category><![CDATA[redmine]]></category>

		<guid isPermaLink="false">http://karanar.net/?p=265</guid>
		<description><![CDATA[<p>I just completed the installation of redmine using jruby &#38; glassfish on a redhat server. It took me a couple of hours to get it working correctly.</p>
General Informations

For the installation, when you run any ruby programs you better do it with jruby -S &#60;program&#62; to avoid conflicts between ruby and jruby
if you download a redmine release, <span style="color:#777"> . . . &#8594; Read More: <a href="http://karanar.net/?p=265">Installing redmine 1.0.1 on jruby and glassfish</a></span>]]></description>
			<content:encoded><![CDATA[<p>I just completed the installation of <strong>redmine</strong> using jruby &amp; glassfish on a redhat server. It took me a couple of hours to get it working correctly.</p>
<h2>General Informations</h2>
<ul>
<li>For the installation, when you run any <code>ruby</code> programs you better do it with <code>jruby -S &lt;program&gt;<!--formatted--></code> to avoid conflicts between ruby and jruby</li>
<li>if you download a <strong>redmine </strong>release, rails and gems are already included in the vendor&#8217;s folder so you don&#8217;t need to install them</li>
<li>If you have already installed<strong> redmine</strong> on jruby with some other help and you are having problems (like missing gems or some weird mysql exception), look below the <code>database.yml</code> file and the<code> warble.rb</code> changes, that might fix your problems!</li>
</ul>
<p>I used the following versions of the different components :</p>
<ol>
<li><a href="http://rubyforge.org/frs/?group_id=1850">redmine 1.0.1</a></li>
<li><a title="jruby" href="http://jruby.org/download" target="_blank">jruby 1.5.2</a></li>
<li><a title="mysql" href="http://www.mysql.com/downloads/mysql/" target="_blank">mysql 5.0.77</a></li>
<li><a title="glassfish" href="https://glassfish.dev.java.net/public/downloadsindex.html#top" target="_blank">glassfish 3.0.1</a> (build 22)</li>
<li><a title="mysqlconnector" href="http://www.mysql.com/downloads/connector/j/" target="_blank">mysql-connector-java-5.1.12</a></li>
</ol>
<p>But hopefully any other combination should work as well&#8230;</p>
<h2>Prerequisites</h2>
<ul>
<li>download and untar  all the above software if it&#8217;s not done yet, install mysql &amp; glassfish.</li>
<li>add jruby to your PATH variable</li>
<li>make sure you have access to  mysql with an admin account (root) to create new databases, mysqld (daemon) needs to be running.</li>
<li>make sure your glassfish installation is working (you can try to login as admin on <em>http://&lt;host&gt;:4848</em>)</li>
<li>Also in glassfish, configure the <code>Ruby container </code>to point to your jruby installation path</li>
</ul>
<h2>Installation steps</h2>
<h3>Download gems</h3>
<p>Download and install the gems that <strong>redmine</strong> needs (warble is used to pack <strong>redmine </strong>rails application as a war file to be deployed on a JEE container, see below):</p>
<pre class="brush:shell">jruby -S gem install jruby-openssl activerecord-jdbcmysql-adapter warbler</pre>
<h3>Database setup</h3>
<ul>
<li>Log on as root and create the redmine database</li>
<pre class="brush:sql">create database redmine character set utf8;</pre>
<li>create the redmine user account ( change pwd to your own password)</li>
<pre class="brush:sql">create user 'redmine'@'localhost' identified by 'pwd';</pre>
<li>grant privileges</li>
<pre class="brush:sql">grant all privileges on redmine.* to 'redmine'@'localhost';</pre>
</ul>
<h3>mysql-connector configuration</h3>
<ul>
<li>copy the <code>mysql-connector.jar</code> file to your glassfish installation lib folder</li>
<li>in the glassfish bin folder use the asadmin tool to create a connection jdbc pool:</li>
</ul>
<pre class="brush:shell">asadmin create-jdbc-connection-pool --datasourceclassname com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource \
--restype javax.sql.DataSource --property "User=redmine:Password=pwd:URL=jdbc\:mysql\://localhost\:3306/redmine" \
jdbc/RedminePool</pre>
<p>and</p>
<pre class="brush:shell">asadmin create-jdbc-resource --connectionpoolid jdbc/RedminePool jdbc/Redmine</pre>
<p>Those steps can also be done in the web administration console of glassfish.</p>
<h3>redmine configuration</h3>
<ul>
<li>in the redmine config/environments folder copy <code>production.rb </code>to <code>production_setup.rb</code></li>
<li>in the redmine config/ folder copy <code>database.yml.example </code>to <code>database.yml</code></li>
<li>modify the<code> config/database.yml</code> file and make sure you have the following with your password:</li>
</ul>
<pre class="brush:text"># MySQL (default setup).

production:
adapter: jdbc
jndi: jdbc/Redmine
driver: com.mysql.jdbc.Driver

production_setup:
adapter: jdbcmysql
database: redmine
host: localhost
username: redmine
password: pwd
encoding: utf8
</pre>
<h3>Create schema and populate default data</h3>
<p>In the <strong>redmine folder </strong>, start the following commands to create the database schema and enter the default data (roles, &#8230;) :</p>
<pre class="brush:shell">jruby -S rake db:migrate RAILS_ENV=production</pre>
<p>and</p>
<pre class="brush:shell">jruby -S rake redmine:load_default_data RAILS_ENV=production</pre>
<h3>Prepare for deployment</h3>
<p>Now we need to prepare the war file that will be deployed to the JEE container. For this step, we use warble.</p>
<ul>
<li>first, we need a warble config file. So, in the redmine folder, issue the command</li>
<pre class="brush:shell">jruby -S warble config</pre>
<p>(that generates config/warble.rb file)</p>
<li>Open config/warble.rb in your preferred editor and modify the line config.dirs so that it contains :</li>
</ul>
<pre class="brush:ruby">config.dirs = %w(app config lib log vendor tmp extra files lang)</pre>
<ul>
<li> in the same file add the line
<pre class="brush:ruby">config.gems["rack"] = "1.0.1"</pre>
<p>and make sure the line</p>
<pre class="brush:ruby">config.gems += ["activerecord-jdbcmysql-adapter", "jruby-openssl"]</pre>
<p>is not commented out.</li>
<li>issue the command
<pre class="brush:shell"> jruby -S warble.</pre>
</li>
<li>That should create a <code>war</code> file that you can deploy to your glassfish server.</li>
<li>An easy way to deploy it to glassfish:
<pre class="brush:shell"> cp &lt;redmine.war&gt; &lt;glassfishinstallation&gt;/domains/&lt;domainname&gt;/autodeploy/</pre>
</li>
<li>and then stop/restart glassfish:</li>
<pre class="brush:shell"> &lt;glassfishinstallation/bin/asadmin stop-domain &lt;domainname&gt;
&lt;glassfishinstallation/bin/asadmin start-domain &lt;domainname&gt;</pre>
</ul>
<p><strong>Now, redmine should be working!</strong></p>
<p><strong><br />
</strong></p>
<h2>Start enjoying redmine</h2>
<p>Log on to redmin as administrator with admin/admin.</p>
<h2>Useful links</h2>
<p><a href="http://www.redmine.org/wiki/redmine/RedmineInstall" target="_blank">redmine installation</a></p>
<p><a href="http://musingsofaprogrammingaddict.blogspot.com/2008/11/redmine-on-jruby-and-glassfish.html" target="_blank">redmine on jruby</a></p>
<p><a href="http://blogs.sun.com/arungupta/entry/totd_9_using_jdbc_connection" target="_blank">jdbc connection poll, jndi, rails</a></p>
]]></content:encoded>
			<wfw:commentRss>http://karanar.net/?feed=rss2&amp;p=265</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Modify Heap Memory for Tomcat Server</title>
		<link>http://karanar.net/?p=253</link>
		<comments>http://karanar.net/?p=253#comments</comments>
		<pubDate>Wed, 25 Aug 2010 11:43:14 +0000</pubDate>
		<dc:creator>karanar</dc:creator>
				<category><![CDATA[Tomcat]]></category>
		<category><![CDATA[heap]]></category>
		<category><![CDATA[memory]]></category>
		<category><![CDATA[tomcat]]></category>
		<category><![CDATA[tuning]]></category>

		<guid isPermaLink="false">http://karanar.net/?p=253</guid>
		<description><![CDATA[To increase the heap memory of a tomcat server (I had to do it make a grails application run smoothly) do the following:
<p>In the installation folder of tomcat, go to the subfolder /bin and add somewhere at the beginning of the startup script catalina.sh the line
JAVA_OPTS=&#039;-Xms8192M -Xmx8192&#039; for respectively 8GB of memory in <span style="color:#777"> . . . &#8594; Read More: <a href="http://karanar.net/?p=253">Modify Heap Memory for Tomcat Server</a></span>]]></description>
			<content:encoded><![CDATA[<h4><strong>To increase the heap memory of a tomcat server (I had to do it make a grails application run smoothly) do the following:</strong></h4>
<p>In the installation folder of tomcat, go to the subfolder /bin and add somewhere at the beginning of the startup script <code>catalina.sh</code> the line<br />
<code>JAVA_OPTS=&#039;-Xms8192M -Xmx8192&#039;</code> for respectively 8GB of memory in this case.</p>
]]></content:encoded>
			<wfw:commentRss>http://karanar.net/?feed=rss2&amp;p=253</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Verifying a checksum on a Mac</title>
		<link>http://karanar.net/?p=247</link>
		<comments>http://karanar.net/?p=247#comments</comments>
		<pubDate>Fri, 11 Jun 2010 13:54:41 +0000</pubDate>
		<dc:creator>karanar</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://karanar.net/?p=247</guid>
		<description><![CDATA[<p>I just downloaded Filezilla for my mac. I thought I should verify the checksum before installing the soft.
That&#8217;s how I did it :

openssl dgst -sha512 FileZilla_xxx.tar.bz2

and I compared the output with the corresponding hash in the checksum file.
&#8230; I guess this post is for my own reference <span style="color:#777"> . . . &#8594; Read More: <a href="http://karanar.net/?p=247">Verifying a checksum on a Mac</a></span>]]></description>
			<content:encoded><![CDATA[<p>I just downloaded <a href="http://filezilla-project.org/index.php">Filezilla</a> for my mac. I thought I should verify the checksum before installing the soft.<br />
That&#8217;s how I did it :<br />
<code><br />
openssl dgst -sha512 FileZilla_xxx.tar.bz2<br />
</code><br />
and I compared the output with the corresponding hash in the checksum file.<br />
&#8230; I guess this post is for my own reference <img src='http://karanar.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://karanar.net/?feed=rss2&amp;p=247</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>New Accelerometer Values Android application</title>
		<link>http://karanar.net/?p=239</link>
		<comments>http://karanar.net/?p=239#comments</comments>
		<pubDate>Mon, 05 Apr 2010 23:20:07 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[accelerometer]]></category>
		<category><![CDATA[sensor]]></category>

		<guid isPermaLink="false">http://karanar.net/?p=239</guid>
		<description><![CDATA[<p>I have deployed a new version of the Accelerometer Values application on the Android market. I left the previous app as I have changed a lot of things in the code and in the package organization. However, I will remove the old one soon, once everybody is happy with the new one  </p>
<p>Now, you can <span style="color:#777"> . . . &#8594; Read More: <a href="http://karanar.net/?p=239">New Accelerometer Values Android application</a></span>]]></description>
			<content:encoded><![CDATA[<p>I have deployed a new version of the Accelerometer Values application on the Android market. I left the previous app as I have changed a lot of things in the code and in the package organization. However, I will remove the old one soon, once everybody is happy with the new one <img src='http://karanar.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>Now, you can log the values of the accelerometer to a file on the sdcard (many people requested this feature). You can also change the colors (background and x,y,z values) and you can decide how often the application should catch the sensor values. However, depending on the phone, if you choose to catch the values too fast (like every 10 ms) and at the same time log the values to a file, the app or even the phone might get frozen for a couple of seconds (eventually, you might need to kill the activity).</p>
<p>I hope you will find the logging feature useful, let me know if you are fine with how the data are stored in the file.</p>
]]></content:encoded>
			<wfw:commentRss>http://karanar.net/?feed=rss2&amp;p=239</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Grails many-to-many &amp; Join table</title>
		<link>http://karanar.net/?p=217</link>
		<comments>http://karanar.net/?p=217#comments</comments>
		<pubDate>Mon, 29 Mar 2010 22:04:37 +0000</pubDate>
		<dc:creator>karanar</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[many-to-many]]></category>

		<guid isPermaLink="false">http://karanar.net/?p=217</guid>
		<description><![CDATA[<p>What I enjoy with frameworks like Grails or Rails is that they are taking care of all the object relational mapping for me. So, I can really concentrate on the domain object model and the framework will care about the underlying work. Fortunately, when needed, I can still &#8220;talk&#8221; to the database directly. Also, with the <span style="color:#777"> . . . &#8594; Read More: <a href="http://karanar.net/?p=217">Grails many-to-many &#038; Join table</a></span>]]></description>
			<content:encoded><![CDATA[<p>What I enjoy with frameworks like Grails or Rails is that they are taking care of all the object relational mapping for me. So, I can really concentrate on the domain object model and the framework will care about the underlying work. Fortunately, when needed, I can still &#8220;talk&#8221; to the database directly. Also, with the scaffolding I can quickly get a feeling for the application and see if the domain model makes any sense.</p>
<p>The <strong>many-to-many</strong> relationship and how Grails treats it is kind of interesting.</p>
<p>Let&#8217;s take an example. In a project, I have two domain classes that are connected with a many-to-many relationship, <span style="color: #000080;">ExpDesign</span>, <span style="color: #000080;">ExpConditionValue</span>. ExpDesign represents an experimental design, <span style="color: #000080;">ExpConditionValue</span> represents a value for a condition in a design. So an experimental design (<span style="color: #000080;">ExpDesign</span>) can have multiple condition values (<span style="color: #000080;">ExpConditionValue</span>) and those can belong to many <span style="color: #000080;">ExpDesign</span>. So, that is clearly a many-to-many relationship which needs a join table and Grails knows it.<br />
This is how we tell Grails (with <span style="color: #800000;">hasMany</span>) about the many-to-many relationship:</p>
<pre class="brush:groovy">class ExpDesign {
    static hasMany = [expConditionValues: ExpConditionValue]
    ...
}
class ExpConditionValue {
    static hasMany = [expDesigns: ExpDesign]
    ...
}
</pre>
<p>But actually, that&#8217;s not enough. We also need to tell Grails (with <span style="color: #800000;">belongsTo</span>) which class is the owner of the other (more about belongsTo later) :</p>
<pre class="brush:groovy">class ExpConditionValue {
    static hasMany = [expDesigns: ExpDesign]
    static belongsTo = [ExpConditionType]
}
</pre>
<p>It&#8217;s clear that <span style="color: #000080;">ExpDesign</span> owns <span style="color: #000080;">ExpConditionValue</span>, therefore I put the <span style="color: #800000;">belongsTo</span> in <span style="color: #000080;">ExpConditionValue</span>.</p>
<p>Before I run the code, I want to modify it to specify the names of the mapping tables for my two classes. My convention is to add underscores before upper case letters and pluralize the domain name to define the table name.  So here, the tables would be called <span style="color: #000080;">EXP_DESIGNS</span> and <span style="color: #000080;">EXP_CONDITION_VALUES</span>. To define the join table name, Grails appends both names with an underscore, so here it would be <span style="color: #000080;">EXP_DESIGNS_EXP_CONDITION_VALUES</span>. However, as I use Oracle, it will not work because of the length of the table name. I figured this out running <span style="color: #008000;">describe all_tab_columns</span> (did you know that Oracle limits table name length to 30 characters?). So, I want to specify not only the tables names but also the join table name.</p>
<p>The modified code:</p>
<pre class="brush:groovy">class ExpDesign {
    static mapping = {
        table 'EXP_DESIGNS'
        expConditionValues joinTable: 'EXP_COND_VALS_DESIGNS'
    }

    static hasMany = [expConditionValues: ExpConditionValue]
    ...
}
class ExpConditionValue {
    static mapping = {
        table ' EXP_COND_VALUES'
        expDesigns joinTable: 'EXP_COND_VALS_DESIGNS'
    }
    static hasMany = [expDesigns: ExpDesign]
    static belongsTo = [ExpDesign]
    ...
}
</pre>
<p>With that I let Grails take care about the relationship, I just enforced the names of the domain tables and the join table.</p>
<h3>belongsTo</h3>
<p><span style="color: #800000;">belongsTo</span> tells grails that the other class is the owning class in the relationship. In my case, <span style="color: #000080;">ExpDesign</span> owns (many) <span style="color: #000080;">ExpConditionValue</span>. The first consequence is that <span style="color: #000080;">ExpDesign</span> deletes will be cascaded to <span style="color: #000080;">ExpConditionValues</span>. Whenever a ExpDesign will be deleted all its associated <span style="color: #000080;">ExpConditionValues</span> will be deleted as well, without the <span style="color: #800000;">belongsTo</span> they would not.<br />
In the case above, I have used the unidirectional <span style="color: #800000;">belongsTo</span> clause but a bidirectional version exists as well (e.g. <span style="color: #008000;">static belongsTo = [expD : ExpDesign]</span>) which would enable to navigate from the object to its owning object.</p>
<p>What is interesting as well is that <span style="color: #800000;">belongsTo</span> combined to <span style="color: #800000;">hasMany</span> tell Grails enough about our model that it will be able to add up some dynamic methods like <span style="color: #008000;">exp.addToExpConditionValues(val1)</span> that will automatically persist objects to the DB.</p>
<p>Thanks to grails, a lot of the magic happens in the background and for us much less tedious code to write!</p>
]]></content:encoded>
			<wfw:commentRss>http://karanar.net/?feed=rss2&amp;p=217</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>createCriteria() &amp; withCriteria()</title>
		<link>http://karanar.net/?p=194</link>
		<comments>http://karanar.net/?p=194#comments</comments>
		<pubDate>Thu, 18 Mar 2010 17:53:37 +0000</pubDate>
		<dc:creator>karanar</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[createCriteria]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[withCriteria]]></category>

		<guid isPermaLink="false">http://karanar.net/?p=194</guid>
		<description><![CDATA[<p>Grails has an incredible amount of  very useful features, amongst those the dynamic methods on domain objects. When we generate the scaffolding for a controller for a domain object we get the default list method in the controller which uses the list method on the domain object. The list method takes params as argument containing max, <span style="color:#777"> . . . &#8594; Read More: <a href="http://karanar.net/?p=194">createCriteria() &#038; withCriteria()</a></span>]]></description>
			<content:encoded><![CDATA[<p>Grails has an incredible amount of  very useful features, amongst those the dynamic methods on domain objects. When we generate the scaffolding for a controller for a domain object we get the default list method in the controller which uses the list method on the domain object. The list method takes <em>params</em> as argument containing max, offset, order and sort. With this method we can already <em>paginate</em> through a collection of the domain objects. That&#8217;s what the scaffolding gives us for free.</p>
<p>But that&#8217;s not always enough. In the current system I&#8217;m working on I decided to add a boolean flag <strong>deleted</strong> on some domain objects. The reason is that I cannot allow normal users to really delete the objects from the db, so when a user deletes an object I just flag the object as being deleted, thus I can always recover it. However, I don&#8217;t want this object to appear anymore in the list. So, an easy way to achieve that is <strong><span style="color: #0000ff;">withCriteria</span></strong>. If you wonder what the difference is between <strong><span style="color: #0000ff;">withCriteria</span></strong> and <span style="color: #0000ff;"><strong>createCriteria</strong></span>, from what I understood <span style="color: #0000ff;"><strong>withCriteria</strong></span> is just a shorter form of <span style="color: #0000ff;"><strong>createCriteria</strong></span>.</p>
<p>First, the default <strong>list</strong> method in the <strong>controller</strong> is generated by the scaffolding:</p>
<pre><span style="color: #008000;">def list = {
  params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
  [ dataTypeInstanceList: DataType.list( params ), dataTypeInstanceTotal: DataType.count() ]
}</span></pre>
<p>And that the method I first added to my <strong>domain</strong> object DataType using <strong><span style="color: #0000ff;">createCriteria</span></strong>:</p>
<pre class="brush:groovy">static notDeleted(params) {
  createCriteria().list(max: params.max, offset: params.offset, sort: params.sort, order: params.order) {
     and {
              eq('deleted', false)
           }
   }
}
</pre>
<p>There should be a shorter version with <strong><span style="color: #0000ff;">withCriteria </span></strong><span style="color: #000000;">which should work as good as the previous one from what I have read. I tried something like the following but the pagination didn&#8217;t work.</span>:</p>
<pre class="brush:groovy">
static notDeleted(params) {
    withCriteria {
        eq('deleted', false)
    }
}
</pre>
<p>It looks pretty simple but it&#8217;s pretty powerful as you can combine a lot of <a title="operators" href="http://www.grails.org/doc/1.0.3/ref/Domain%20Classes/createCriteria.html" target="_blank">operator</a>.</p>
<p>And below my modified list method in the <span style="color: #0000ff;"><strong>controller</strong></span> with a modified <strong>count</strong>:</p>
<pre><span style="color: #008000;">def list = {
  params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
  [ valueInstanceList: Value.notDeleted( params ), valueInstanceTotal: Value.countByDeleted(false) ]
}
</span></pre>
]]></content:encoded>
			<wfw:commentRss>http://karanar.net/?feed=rss2&amp;p=194</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Replacing strings in a database using Groovy</title>
		<link>http://karanar.net/?p=176</link>
		<comments>http://karanar.net/?p=176#comments</comments>
		<pubDate>Mon, 15 Mar 2010 17:04:08 +0000</pubDate>
		<dc:creator>karanar</dc:creator>
				<category><![CDATA[Groovy]]></category>
		<category><![CDATA[scripting]]></category>
		<category><![CDATA[database]]></category>

		<guid isPermaLink="false">http://karanar.net/?p=176</guid>
		<description><![CDATA[<p>First my use case. A user inserted a couple of thousands records into a database describing animal samples for a transcriptomics study. In this table there is a column &#8216;description&#8217; which is for free text. The user made a mistake: among other information in this description column he put &#8216;rat&#8217; instead of &#8216;mouse&#8217;. So now, how <span style="color:#777"> . . . &#8594; Read More: <a href="http://karanar.net/?p=176">Replacing strings in a database using Groovy</a></span>]]></description>
			<content:encoded><![CDATA[<p>First my use case. A user inserted a couple of thousands records into a database describing animal samples for a transcriptomics study. In this table there is a column &#8216;description&#8217; which is for free text. The user made a mistake: among other information in this description column he put &#8216;rat&#8217; instead of &#8216;mouse&#8217;. So now, how to keep the text just replacing &#8216;rat&#8217; by &#8216;mouse&#8217;? Groovy to our rescue!</p>
<pre class="brush:groovy">def sql = groovy.sql.Sql.newInstance("jdbc:oracle:thin:@server.domain:1521:database", "user", "password", "driver")

sql.eachRow("select * from database.table where table_column_ = 'xxxx") {
newDescription = (it.description =~ /Rat/).replaceAll('Mouse')
id = it.id
updateCall = "update database.table set description = '$newDescription' where id = $id"
sql.executeUpdate(updateCall)
}
</pre>
<ul>
<li>Line 1 creates a sql connection to the database</li>
<li>Line 3 iterates through the results of the passed select statement (each row will be in the <strong>it</strong> and fields can be accessed by their name)</li>
<li>Line 4 does the regular expression find&amp;replace in the description string
<ul>
<li>=~ looks if there is a match (takes it.description as argument)</li>
<li>The <strong>slash</strong> defines the RegEx. So in our case we are looking for <em>Rat</em> (<strong>/Rat/</strong>, for first letter lower and upper case we could have put <strong>/[R|r]at/</strong>)</li>
<li>and finally <strong>.replaceAll(&#8216;Mouse&#8217;)</strong> to replace what was found with the regular expression</li>
</ul>
</li>
<li>Line 6 &amp; 7 to build and call the update</li>
</ul>
<p>Scripting languages like groovy can sometimes be very painful but luckily more often they are just great!</p>
]]></content:encoded>
			<wfw:commentRss>http://karanar.net/?feed=rss2&amp;p=176</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Accelerometer Values</title>
		<link>http://karanar.net/?p=131</link>
		<comments>http://karanar.net/?p=131#comments</comments>
		<pubDate>Tue, 16 Feb 2010 21:59:16 +0000</pubDate>
		<dc:creator>karanar</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[android java]]></category>

		<guid isPermaLink="false">http://karanar.net/?p=131</guid>
		<description><![CDATA[<p>Here is the code of the accelerometer values application for Android. I did this application in a couple of hours to test the Android platform so the features are very basic. I&#8217;m currently working on a new version that will include logging of the values and a few other things.
However, here is the code of the <span style="color:#777"> . . . &#8594; Read More: <a href="http://karanar.net/?p=131">Accelerometer Values</a></span>]]></description>
			<content:encoded><![CDATA[<p>Here is the code of the accelerometer values application for Android. I did this application in a couple of hours to test the Android platform so the features are very basic. I&#8217;m currently working on a new version that will include logging of the values and a few other things.<br />
However, here is the code of the two main classes of the application. It will compile with recent versions of the Android SDK even though some methods have been deprecated meanwhile.</p>
<pre class="brush:java">
package com.arak.sensor.accele;

import android.view.View;
import android.hardware.SensorManager;
import android.hardware.SensorListener;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.Paint;
import android.graphics.Color;

import java.util.LinkedList;
import java.text.DecimalFormat;

public class AcceleView extends View implements SensorListener {

    public final static int MAX_VALUES = 200;
    public final static int SCALING = 3; // for G to graphic
    public final static int GSCALING = 2; // for panels
    public final static int MARGIN_TOP = 15;
    public final static int SEPARATION = 20;
    public final static int MARGIN_LEFT = 10;

    private long timekeeper;

    private final LinkedList&#60;float[]&#62; fifo;
    private float height;
    private float width;
    private float halfRectHeight;

    private float xYLine;
    private float yYLine;
    private float zYLine;
    private float pX;
    private float pY;
    private float pZ;
    private float minX;
    private float minY;
    private float minZ;
    private float maxX;
    private float maxY;
    private float maxZ;

    public AcceleView(Context context, SensorManager sma) {
        super(context);
        timekeeper = android.os.SystemClock.uptimeMillis();
        fifo = new LinkedList&#60;float[]&#62;();
        int mask = 0;
        mask |= SensorManager.SENSOR_ORIENTATION;
        mask |= SensorManager.SENSOR_ACCELEROMETER;
        sma.registerListener(this, mask, SensorManager.SENSOR_DELAY_FASTEST);
        pX = 0f;
        pY = 0f;
        pZ = 0f;
        minX = 0f;
        minY = 0f;
        minZ = 0f;
        maxX = 0f;
        maxY = 0f;
        maxZ = 0f;
    }

    protected void onDraw(Canvas canvas) {
        height = canvas.getHeight();
        width = canvas.getWidth();
        halfRectHeight = SCALING * 10 *GSCALING;
        xYLine = MARGIN_TOP + SCALING * 10 *GSCALING;
        yYLine = xYLine + halfRectHeight * 2 + SEPARATION;
        zYLine = yYLine + halfRectHeight * 2 + SEPARATION;

        clear(canvas);
        drawGridAndLastValues(canvas);
        drawValues(canvas);
    }

    public void onSensorChanged(int sensor, float[] values) {
        if (android.os.SystemClock.uptimeMillis() < timekeeper + 20) return;
        timekeeper = android.os.SystemClock.uptimeMillis();
        final float[] val = new float[]{values[0], values[1], values[2]}; // defensive copy because keeps the same object

        if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
            if (fifo.size() > MAX_VALUES) fifo.poll();
            fifo.add(val);
            minX = Math.min(minX, val[0]);
            minY = Math.min(minY, val[1]);
            minZ = Math.min(minZ, val[2]);
            maxX = Math.max(maxX, val[0]);
            maxY = Math.max(maxY, val[1]);
            maxZ = Math.max(maxZ, val[2]);
            invalidate();
        }

    }

    public void onAccuracyChanged(int i, int i1) {
        /* @todo implement method */
    }

    private void clear(Canvas canvas) {
        Rect rect = new Rect();
        rect.set(0, 0, canvas.getWidth(), canvas.getHeight());
        Paint p = new Paint();
        p.setStyle(Paint.Style.FILL);
        p.setColor(Color.WHITE);
        canvas.drawRect(rect, p);
    }

    private void drawGridAndLastValues(Canvas canvas) {
        Paint p = new Paint();

        // print measured values
        DecimalFormat df = new DecimalFormat("##.#");
        String xStringVal = df.format(pX);
        String yStringVal = df.format(pY);
        String zStringVal = df.format(pZ);
        String xMinStringVal = df.format(minX);
        String yMinStringVal = df.format(minY);
        String zMinStringVal = df.format(minZ);
        String xMaxStringVal = df.format(maxX);
        String yMaxStringVal = df.format(maxY);
        String zMaxStringVal = df.format(maxZ);

        //x
        String xText = "X values [last: " + xStringVal + " - min:" + xMinStringVal + " - max:" + xMaxStringVal + "]";
        p.setColor(Color.LTGRAY);
        canvas.drawRect(MARGIN_LEFT, xYLine - halfRectHeight, width - MARGIN_LEFT, xYLine + halfRectHeight, p);
        p.setColor(Color.BLACK);
        canvas.drawLine(MARGIN_LEFT, xYLine, width - MARGIN_LEFT, xYLine, p);
        canvas.drawText(xText, MARGIN_LEFT + width / 6, xYLine - halfRectHeight - 2, p);
        canvas.drawText("+2G", MARGIN_LEFT, xYLine - halfRectHeight + 10, p);
        canvas.drawText("-2G", MARGIN_LEFT, xYLine + halfRectHeight, p);

        //y
        String yText = "Y values [last: " + yStringVal + " - min:" + yMinStringVal + " - max:" + yMaxStringVal + "]";
        p.setColor(Color.LTGRAY);
        canvas.drawRect(MARGIN_LEFT, yYLine - halfRectHeight, width - MARGIN_LEFT, yYLine + halfRectHeight, p);
        p.setColor(Color.BLACK);
        canvas.drawLine(MARGIN_LEFT, yYLine, width - MARGIN_LEFT, yYLine, p);
        canvas.drawText(yText, MARGIN_LEFT + width / 6, yYLine - halfRectHeight - 2, p);
        canvas.drawText("+2G", MARGIN_LEFT, yYLine - halfRectHeight + 10, p);
        canvas.drawText("-2G", MARGIN_LEFT, yYLine + halfRectHeight, p);

        //z
        String zText = "Z values [last:" + zStringVal + " - min:" + zMinStringVal + " - max:" + zMaxStringVal + "]";
        p.setColor(Color.LTGRAY);
        canvas.drawRect(MARGIN_LEFT, zYLine - halfRectHeight, width - MARGIN_LEFT, zYLine + halfRectHeight, p);
        p.setColor(Color.BLACK);
        canvas.drawLine(MARGIN_LEFT, zYLine, width - MARGIN_LEFT, zYLine, p);
        canvas.drawText(zText, MARGIN_LEFT + width / 6, zYLine - halfRectHeight - 2, p);
        canvas.drawText("+2G", MARGIN_LEFT, zYLine - halfRectHeight + 10, p);
        canvas.drawText("-2G", MARGIN_LEFT, zYLine + halfRectHeight, p);

    }

    private void drawValues(Canvas canvas) {
        float len = (width - MARGIN_LEFT * 2) / MAX_VALUES;
        Paint p = new Paint();

        float xVal = MARGIN_LEFT;

        boolean first = true;

        for (float[] f : fifo) {
            float x = f[0];
            float y = f[1];
            float z = f[2];
            if (first) {
                pX = x;
                pY = y;
                pZ = z;
                first = false;
            }
            p.setColor(Color.GREEN);
            canvas.drawLine(xVal, xYLine - pX * SCALING, xVal + len, xYLine - x * SCALING, p);
            p.setColor(Color.RED);
            canvas.drawLine(xVal, yYLine - pY * SCALING, xVal + len, yYLine - y * SCALING, p);
            p.setColor(Color.BLUE);
            canvas.drawLine(xVal, zYLine - pZ * SCALING, xVal + len, zYLine - z * SCALING, p);
            xVal += len;
            pX = x;
            pY = y;
            pZ = z;
        }
    }
}// END

package com.arak.sensor.accele;

import android.app.Activity;
import android.os.Bundle;
import android.hardware.SensorManager;
import android.content.Context;

public class ShowSensor extends Activity {

    private AcceleView av;

    @Override
    public void onCreate(Bundle args) {
        super.onCreate(args);
        av = new AcceleView(this, (SensorManager) getSystemService(Context.SENSOR_SERVICE));
        setTitle("Show Sensor Values");
        setContentView(av);
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://karanar.net/?feed=rss2&amp;p=131</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>How can we run code on an object instance before construction?</title>
		<link>http://karanar.net/?p=118</link>
		<comments>http://karanar.net/?p=118#comments</comments>
		<pubDate>Wed, 10 Feb 2010 18:09:46 +0000</pubDate>
		<dc:creator>karanar</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://karanar.net/?p=118</guid>
		<description><![CDATA[<p>We can do it with initialization blocks. I find it actually a very interesting feature of java even though I would recommend to be very careful when using it. Indeed, initialization blocks might confuse people looking at your code especially if there is not only one and if it&#8217;s not placed close to the constructor.
So an <span style="color:#777"> . . . &#8594; Read More: <a href="http://karanar.net/?p=118">How can we run code on an object instance before construction?</a></span>]]></description>
			<content:encoded><![CDATA[<p>We can do it with initialization blocks. I find it actually a very interesting feature of java even though I would recommend to be very careful when using it. Indeed, initialization blocks might confuse people looking at your code especially if there is not only one and if it&#8217;s not placed close to the constructor.<br />
So an initialization block looks like that:  </p>
<pre class="brush:java">
{
list = new ArrayList()
}</pre>
<p>Assuming the <em>list</em> member has been defined, this code will be executed just as it would have been inserted at the very beginning of the constructor.<br />
And if there would be many of them, they would all be called in the order they appear in the class (ok, that&#8217;s even more dangerous !). Initialization blocks can also throw exceptions, as long as the constructor throws the same exceptions as well.<br />
Now the question is: why would you use an initialization block instead of putting everything in the constructor or in a init() method like we always do. I guess, it depends. For sure, init() cannot set final members, initialization blocks can.<br />
Also, in an anonymous inner classes, we cannot define constructors, a initialization block can play the constructor role. Code generators can also take advantage of initialization blocks, UI builders for instance.<br />
Here is a little examples of a class with two initialization blocks and random exception.</p>
<pre class="brush:java">
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class TryItOut {

    private List list;

    {
        System.out.println("calling Hello()");
        hello();
    }

    {
        System.out.println("adding element to list");
        list.add("blabla");
        if (new Random().nextBoolean())throw new Exception("exception!");
    }

    public TryItOut() throws Exception {
        System.out.println("starting constructor, how many elements? ");
        System.out.println(list.size());
    }

    public void hello() {
        System.out.print("hello");
        list = new ArrayList();
        for (int i = 0; i < 10; i++) list.add("hello" + i);
        System.out.println(" world " + list.size());
    }

    public final static void main(String[] args) {
        try {
            new TryItOut();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
</pre>
<p>Interesting, isn't it??</pre>
]]></content:encoded>
			<wfw:commentRss>http://karanar.net/?feed=rss2&amp;p=118</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Exporting a database to XML with Groovy</title>
		<link>http://karanar.net/?p=93</link>
		<comments>http://karanar.net/?p=93#comments</comments>
		<pubDate>Fri, 29 Jan 2010 18:26:33 +0000</pubDate>
		<dc:creator>karanar</dc:creator>
				<category><![CDATA[Groovy]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://karanar.net/?p=93</guid>
		<description><![CDATA[<p>I&#8217;m currently working on refactoring an UI/ORM application and the database it connects to. I need to change a lot of things in the db design so I was looking for a simple java tool that would allow me to easily export tables from the database to a defined XML format.
A tool that would produce something <span style="color:#777"> . . . &#8594; Read More: <a href="http://karanar.net/?p=93">Exporting a database to XML with Groovy</a></span>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m currently working on refactoring an UI/ORM application and the database it connects to. I need to change a lot of things in the db design so I was looking for a simple java tool that would allow me to easily export tables from the database to a defined XML format.<br />
A tool that would produce something like that:</p>
<pre class="brush:xml">
<table_entries>
<entry>
<column1>value_col1</column1>
<column2>value_val2</column2>
</entry>
<entry>
<column1>value_col1</column1>
<column2>value_val2</column2>
</entry>
</table_entries>
</pre>
<p>I briefly googled but I couldn&#8217;t find anything free and easy to use. I know there must be! Anyway, I found an elegant way to do it with Groovy and wanted to share it.</p>
<pre class="brush:groovy">
def sql = groovy.sql.Sql.newInstance("connectionString", "user", "password", "db_driver")

def fileOut = new FileWriter("/path/to/out/put/file.xml")

def xml = new groovy.xml.MarkupBuilder(fileOut)
xml.table_entries {
  sql.eachRow("select * from schema.table") {row ->
    entry {
      column1(row.column1)
      column2(row.column2)
      ...
    }
  }
}
</pre>
<p>1 minute to write the code to export one table, isn&#8217;t Groovy great?</p>
]]></content:encoded>
			<wfw:commentRss>http://karanar.net/?feed=rss2&amp;p=93</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
