<?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>2lips.pl - pasja programowania</title>
	<atom:link href="http://2lips.pl/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://2lips.pl/blog</link>
	<description>Programowanie i nie tylko</description>
	<lastBuildDate>Sun, 15 Apr 2012 17:05:32 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Tapestry SelectModel wrapping</title>
		<link>http://2lips.pl/blog/tapestry-selectmodel-wrapping/</link>
		<comments>http://2lips.pl/blog/tapestry-selectmodel-wrapping/#comments</comments>
		<pubDate>Sun, 15 Apr 2012 11:32:59 +0000</pubDate>
		<dc:creator>bendi</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[annotation]]></category>
		<category><![CDATA[ComponentClassTransformWorker]]></category>
		<category><![CDATA[selectmodel]]></category>
		<category><![CDATA[tapestry5]]></category>

		<guid isPermaLink="false">http://2lips.pl/blog/?p=755</guid>
		<description><![CDATA[Problem description Recently I joined a project that uses tapestry5 - a very nicely organized framework for web development with its own IoC mechanisms, great error reporting and very productive. And to me it still holds closest to its goal &#8211; it should be easy to edit templates by non-programmers. Let&#8217;s get to the point &#8211; [...]]]></description>
			<content:encoded><![CDATA[<h3>Problem description</h3>
<p>Recently I joined a project that uses <a href="http://tapestry.apache.org/">tapestry5</a> - a very nicely organized framework for web development with its own IoC mechanisms, great error reporting and very productive. And to me it still holds closest to its goal &#8211; it should be easy to edit templates by non-programmers.</p>
<p>Let&#8217;s get to the point &#8211; on one of pages I needed to display a dropdown, which is quite nicely described in <a href="http://tapestry.apache.org/using-select-with-a-list.html">tapestry documentation</a> but to make things a little bit more compliated the model for the dropdown must be persistent throughout requests. At first it looked like a piece-of-cake, just add <a href="http://tapestry.apache.org/current/apidocs/org/apache/tapestry5/annotations/Persist.html">@Persist</a> annotation to the model field and that&#8217;s it. Under jetty (which is our development environment) it all looked nice but after moving to Glassfish (which is production environment) strange error apeared, stating that SelectModel cannot be stored in session since it doesn&#8217;t implement <a href="http://docs.oracle.com/javase/6/docs/api/java/io/Serializable.html">Serializable</a> interface.</p>
<p>So I asked our tapestry guru what&#8217;s going on and why can&#8217;t I store SelectModel in session and he said that Tapestry components should not be stored in session and the only thing that I should keep in session is the backing list for which model should be regenerated for each request.</p>
<p>This sounded awkward to me &#8211; because I envisioned all this repetitive code for converting Lists into SelectModels so they could be properly displayed.</p>
<p>I knew there had to be a better way&#8230;</p>
<h3>Solution description</h3>
<p>Fortunately tapestry gives you a very nice way of hooking into it&#8217;s bytecode manipulation mechanisms by implementing <a href="http://tapestry.apache.org/5.3.2/apidocs/org/apache/tapestry5/services/transform/ComponentClassTransformWorker2.html">ComponentClassTransformWorker2</a> (available since v. 5.3), so I decided on a following solution:</p>
<ul>
<li>each field that is supposed to be displayed as dropdown should be marked with some specialized annotation (say @SelectModel)</li>
<li>there should be some magical way of transforming a list into a SelectModel behind-the-scenes so view gets it with no other line of code.</li>
</ul>
<p>I started googling and I found very <a href="http://tawus.wordpress.com/2011/08/01/tapestry-mixins-classtransformations/">similar case</a> - there was a mixin, that should be added to every label. This post gave me an idea how to plug my bytecode manipulation service into tapestry plugin mechanism.</p>
<h3>Usage</h3>
<ol>
<li>As mentioned in solution plan the whole thing starts with annotating field with <a href="https://github.com/bendi/code/blob/master/tapestry_select_model/src/main/java/pl/bedkowski/code/tapestry/annotation/SelectModel.java">@SelectModel </a>annotation, which requires name of field that should be used as option label.</li>
<li>And you need to register <a href="https://github.com/bendi/code/blob/master/tapestry_select_model/src/main/java/pl/bedkowski/code/tapestry/services/SelectModelPropertyWorker.java">SelectModelPropertyWorker</a> in you <a href="https://github.com/bendi/code/blob/master/tapestry_select_model/src/main/java/pl/bedkowski/code/tapestry/services/AppModule.java">AppModule</a>.</li>
</ol>
<p>And that&#8217;s it &#8211; now you can start using your list field as SelectModel in your view under the same name.</p>
<p>As you may have noticed SelectModelPropertyWorkier injects <a href="http://tapestry.apache.org/current/apidocs/org/apache/tapestry5/services/SelectModelFactory.html">ServiceModelFactory</a> under weird name so the getter can produce you model. If you know a better way to do it &#8211; just leave a comment and I&#8217;ll definitely include it.</p>
<h3>Known limitations</h3>
<p>There are 2 things that you need to keep in mind when working with @SelectModel annotation:</p>
<ol>
<li>The field cannot have <a href="http://tapestry.apache.org/5.3.2/apidocs/org/apache/tapestry5/annotations/Property.html">@Property</a> annotation since tapestry default mechanism will try to generate getter and setter which might give weird exceptions</li>
<li>Since there cannot be getter so you cannot add it manually as well</li>
</ol>
<h3>Source code</h3>
<p>Source code available on <a href="https://github.com/bendi/code/tree/master/tapestry_select_model">github</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://2lips.pl/blog/tapestry-selectmodel-wrapping/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Seam3, richfaces4, jpa2/hibernate, tomcat 6/7 archetypes</title>
		<link>http://2lips.pl/blog/seam3-jpa2-tomcat-archetypes/</link>
		<comments>http://2lips.pl/blog/seam3-jpa2-tomcat-archetypes/#comments</comments>
		<pubDate>Sat, 31 Mar 2012 11:08:57 +0000</pubDate>
		<dc:creator>bendi</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[archetype]]></category>
		<category><![CDATA[cdi]]></category>
		<category><![CDATA[jpa2]]></category>
		<category><![CDATA[maven]]></category>
		<category><![CDATA[richfaces4]]></category>
		<category><![CDATA[seam3]]></category>
		<category><![CDATA[tomcat]]></category>
		<category><![CDATA[weld]]></category>

		<guid isPermaLink="false">http://2lips.pl/blog/?p=742</guid>
		<description><![CDATA[Introduction Here you can find some seam3 archetypes that will help you get started when generating new application for tomcat 6/7. They extend weld archetypes with some pieces extra: richfaces 4.2 JPA2/Hibernate transactional EntityManager tomcat data source pool Seam3/tomcat archetypes Because it took me a while to put all of them together, I decided to share a [...]]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>Here you can find some seam3 archetypes that will help you get started when generating new application for tomcat 6/7.</p>
<p>They extend <a href="http://seamframework.org/Documentation/CDIQuickstartForMavenUsers">weld archetypes</a> with some pieces extra:</p>
<ul>
<li>richfaces 4.2</li>
<li>JPA2/Hibernate transactional EntityManager</li>
<li>tomcat data source pool</li>
</ul>
<h3>Seam3/tomcat archetypes</h3>
<p>Because it took me a while to put all of them together, I decided to share a shortcut for those trying to use tomcat+jpa. You can use them directly from my private repository. There are two seam3 archetypes (due to <a href="https://hibernate.onjira.com/browse/HHH-7012">this bug</a>):</p>
<ul>
<li><a href="http://repo.bedkowski.pl/maven2/pl/bedkowski/archetypes/seam3-rf4-jpa2-tomcat6/">seam3-rf4-jpa2-tomcat6</a></li>
<li><a href="http://repo.bedkowski.pl/maven2/pl/bedkowski/archetypes/seam3-rf4-jpa2-tomcat7/">seam3-rf4-jpa2-tomcat7</a></li>
</ul>
<h5>Available options</h5>
<p>In order to make your work more productive I added some extra options, once you fill them, you have</p>
<table border="1" cellpadding="3">
<tbody>
<tr>
<th>name</th>
<th>required</th>
<th>default</th>
</tr>
<tr>
<td>jdbcUrl</td>
<td>required</td>
<td>-</td>
</tr>
<tr>
<td>jdbcUser</td>
<td>required</td>
<td>-</td>
</tr>
<tr>
<td>jdbcPassword</td>
<td>required</td>
<td>-</td>
</tr>
<tr>
<td>jdbcJndiName</td>
<td>false</td>
<td>jdbc/Seam3Test</td>
</tr>
<tr>
<td>jdbcDriverClassName</td>
<td>false</td>
<td>com.mysql.jdbc.Driver</td>
</tr>
<tr>
<td>hibernateDialect</td>
<td>false</td>
<td>org.hibernate.dialect.MySQL5InnoDBDialect</td>
</tr>
</tbody>
</table>
<h3>Usage</h3>
<p>So just add my public repo to your settings.xml:</p>
<pre>&lt;repository&gt;
    &lt;id&gt;repo.bedkowski.pl&lt;/id&gt;
    &lt;url&gt;http://repo.bedkowski.pl/maven2&lt;/url&gt;
&lt;/repository&gt;</pre>
<p>And for mysql you can generate project with:</p>
<pre>mvn archetype:generate \
        -DarchetypeArtifactId=seam3-rf4-jpa2-tomcat7 \
        -DarchetypeGroupId=pl.bedkowski.archetypes \
        -DarchetypeVersion=1.0 \
        -DgroupId=pl.bedkowski.code \
        -DartifactId=seam3-generated \
        -Dversion=1.0-SNAPSHOT \
        -DjdbcUser=test \
        -DjdbcPassword=test \
        -DjdbcUrl='jdbc:mysql://localhost/test?useUnicode=true&amp;characterEncoding=utf8' \
        -DinteractiveMode=false</pre>
<p>Go to your <em>seam3-generated</em> direcotry and run:</p>
<p><em>mvn clean install </em></p>
<p>And in target directory you can find 2 wars:</p>
<ul>
<li>seam3-generated.war</li>
<li>seam3-generated-nolib.war</li>
</ul>
<p>First one is obvious and second one is just a convenience in case you need to synchronize your war on external server &#8211; in which case send over libs each time is time consuming, so you can store libs on your server and just send -nolib.war and recompress the file with libs appended.</p>
<h3>Source code</h3>
<p>As usual <a title="Archetypes repository." href="https://github.com/bendi/archetypes">sources available on github</a>:</p>
<ul>
<li><a title="seam3-rf4-jpa2-tomcat6" href="https://github.com/bendi/archetypes/tree/master/seam3-rf4-jpa2-tomcat6">seam3-rf4-jpa2-tomcat6</a></li>
<li><a title="seam3-rf4-jpa2-tomcat7" href="https://github.com/bendi/archetypes/tree/master/seam3-rf4-jpa2-tomcat7">seam3-rf4-jpa2-tomcat7</a></li>
</ul>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://2lips.pl/blog/seam3-jpa2-tomcat-archetypes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>has-a vs is-a using graph drawing example</title>
		<link>http://2lips.pl/blog/hasa-isa-drawing-example/</link>
		<comments>http://2lips.pl/blog/hasa-isa-drawing-example/#comments</comments>
		<pubDate>Sun, 08 Jan 2012 12:57:00 +0000</pubDate>
		<dc:creator>bendi</dc:creator>
				<category><![CDATA[czytelny kod]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[wzorce projektowe w akcji]]></category>
		<category><![CDATA[aggregation]]></category>
		<category><![CDATA[composition]]></category>
		<category><![CDATA[has-a]]></category>
		<category><![CDATA[inheritance]]></category>
		<category><![CDATA[is-a]]></category>
		<category><![CDATA[oop]]></category>

		<guid isPermaLink="false">http://2lips.pl/blog/?p=717</guid>
		<description><![CDATA[Introduction (OOP principles) Today I&#8217;d like to present you a problem that most especially rookie developers find compelling. This is strongly connected with OOP basics, specifically with 2 fundamental truths: Use inheritance whenever possible. Prefer composition over inheritance. So at first I had problems understanding how these 2 rules are related but as the time [...]]]></description>
			<content:encoded><![CDATA[<h3>Introduction (OOP principles)</h3>
<p>Today I&#8217;d like to present you a problem that most especially rookie developers find compelling. This is strongly connected with OOP basics, specifically with 2 fundamental truths:</p>
<ol>
<li>Use inheritance whenever possible.</li>
<li>Prefer composition over inheritance.</li>
</ol>
<div>So at first I had problems understanding how these 2 rules are related but as the time passed I learned to distinguish the two and recently in one of my projects I came across piece of code that is perfect example on why object composision/aggregation might be a better solution over inheritance.</div>
<h3>Old way &#8211; using inheritance</h3>
<h5>Background &#8211; code usage</h5>
<p>To start with some background &#8211; the code referred to is part of application that displays daily trend graph of some piece of data. It&#8217;s responsible for drawing coordinate system, x-axis, y-axis, some labels, legend lines, text-labels and of course data-curves. The code is executed on client-side and one of requirements is to support ie8 &#8211; which is why there was a need to support both SVG and VML drawing formats.</p>
<h5>Classes responsibilites</h5>
<p>The old apporach used in inheritance to support both formats and below you can find class diagram for the described classes. To start from the top:</p>
<ul>
<li><em>GrapDrawer</em> is a drawing interface &#8211; it&#8217;s main goal is to provide high-level methods for drawing different parts of graph used by othere pieces of application</li>
<li><em>AbstractGraphDrawer</em> which is an interesting beast &#8211; because it provides a bridge between <em>GraphDrawer</em> interface and client-specific implementations &#8211; that is VML/SVG achieved set of <strong>abstract</strong> <strong>protected</strong> methods that encapsulate client-specific drawing API</li>
<li>SVGDrawer/VMLDrawer &#8211; these are both client-specific drawing apis.</li>
</ul>
<p><img class="alignnone" title="Initial design" src="http://yuml.me/diagram/scruffy/class/%5B%3C%3CGraphDrawer%3E%3E;+drawIconBusy();+drawLabel();+drawCoordSystem();+drawLegendAxis();+drawXAxis();+drawYAxis()%5D%5E-.-%5BAbstractGraphDrawer%7C+drawIconBusy();+drawLabel();+drawCoordSystem();+drawLegendAxis();+drawXAxis();+drawYAxis();%23drawLine();%23drawText();%23buildPanel();%23drawLetter();%23drawEllipsis();%23drawIcon()%5D,%20%5BAbstractGraphDrawer%5D%5E%5BSVGDrawer%7C%23drawLine();%23drawText();%23buildPanel();%23drawLetter();%23drawEllipsis();%23drawIcon()%5D,%5BAbstractGraphDrawer%5D%5E%5BVMLDrawer%7C%23drawLine();%23drawText();%23buildPanel();%23drawLetter();%23drawEllipsis();%23drawIcon()%5D." alt="" /></p>
<h5>Problem description</h5>
<p>You might be asking yourselves why is there any problem with this approach. It has all the good parts:</p>
<ul>
<li>there&#8217;s an interface for accessing public methods,</li>
<li>there&#8217;s an abstract method that acts as a bridge between drawer and</li>
<li>client-specific implementation.</li>
</ul>
<p>Everything is encapsulated so user has no knowledge of what&#8217;s going on behing the secenes &#8211; so what&#8217;s the big deal.</p>
<p>This is all true but due to <em>AbstractGraphDrawer</em> dual nature it&#8217;s code is really hard to maintain. Both high and low-level API collide with each other &#8211; the former changes frequently where the latter very rarely. If you look closer you can see that all protected methods are there only to be overridden by implementation and they&#8217;re completely hidden from user. While all parts of public interface are not used in any way by the implementation.</p>
<h3>New way &#8211; use object aggregation</h3>
<h5>Solution description</h5>
<p>These two worlds interact with each other only through their interfaces. So it&#8217;s a perfect candidate for split &#8211; low-level methods should be hidden behind an interface that must be implemented by client-specific code, whereas high-level methods, used by some other code go to a public class which has reference to client-specific low-level drawing api.</p>
<p>This is all presented in the diagram below, where you can find:</p>
<ul>
<li>GrapDrawer class which is used for high-level operations. Low level operations are executed by <em>graphDrawerWorker</em></li>
<li><em>GraphDrawerWorker</em> interface which defines set of required low-level operations</li>
<li>SVGDrawer/VMLDrawer classes which only implement <em>GraphDrawerWorker</em> and thus loose all coupling with high-level code</li>
</ul>
<p><img class="alignnone" title="After refactoring" src="http://yuml.me/diagram/scruffy/class/%5BGraphDrawer%7C-graphDrawerWorker%7C+drawIconBusy();+drawLabel();+drawCoordSystem();+drawLegendAxis();+drawXAxis();+drawYAxis()%5Duses++-1%5B%3C%3CGraphDrawerWorker%3E%3E;+drawText();+buildPanel();+drawLetter();+drawEllipsis();+drawIcon()%5D,%20%5B%3C%3CGraphDrawerWorker%3E%3E;+drawText();+buildPanel();+drawLetter();+drawEllipsis();+drawIcon()%5D%5E-.-%5BSVGDrawer%7C+drawText();+buildPanel();+drawLetter();+drawEllipsis();+drawIcon()%5D,%20%5B%3C%3CGraphDrawerWorker%3E%3E;+drawText();+buildPanel();+drawLetter();+drawEllipsis();+drawIcon()%5D%5E-.-%5BVMLDrawer%7C+drawText();+buildPanel();+drawLetter();+drawEllipsis();+drawIcon()%5D." alt="" /></p>
<h3>Summary</h3>
<p>There&#8217;s still at least one question that needs some attention: how did this code creep into the application? The answer is fairly simple &#8211; it was built incrementally as business needs rose and suddenly <em>AbstractGraphDrawer</em> became a beast with two heads. Unfortunately for everyone who&#8217;s been working with it for longer time it was hidden. Only when someone with fresh look apporached a project, not only could this be spotted but also addressed.</p>
<p>All of you that can spot more basic OOP principles broken in original code (or a new one <img src='http://2lips.pl/blog/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> ) please leave them in comments <img src='http://2lips.pl/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://2lips.pl/blog/hasa-isa-drawing-example/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Google collections wrappers/forwardingobjects</title>
		<link>http://2lips.pl/blog/google-collections-wrappers-forwardingobjects/</link>
		<comments>http://2lips.pl/blog/google-collections-wrappers-forwardingobjects/#comments</comments>
		<pubDate>Wed, 16 Nov 2011 21:19:21 +0000</pubDate>
		<dc:creator>bendi</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[delegate]]></category>
		<category><![CDATA[forwardingobject]]></category>
		<category><![CDATA[forwardingset]]></category>
		<category><![CDATA[google-collections]]></category>
		<category><![CDATA[proxy]]></category>

		<guid isPermaLink="false">http://2lips.pl/blog/?p=694</guid>
		<description><![CDATA[This blog is a contitunation of my previous entry (polish only sorry) in which I presented a solution for hiding certain operations on a collection using jdk&#8217;s dynamic proxy mechanism. It consited of MethodInterceptr which checked if specific method was called and in such a case it reported and error using RuntimeException. With this entry [...]]]></description>
			<content:encoded><![CDATA[<p>This blog is a contitunation of my <a href="http://2lips.pl/blog/dynamic-proxy-w-javie/">previous entry</a> (polish only sorry) in which I presented a solution for hiding certain operations on a collection using jdk&#8217;s dynamic proxy mechanism. It consited of MethodInterceptr which checked if specific method was called and in such a case it reported and error using RuntimeException.</p>
<p>With this entry I&#8217;d like to present a different approach using google collection <a href="http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/ForwardingObject.html">ForwardingObjects</a>. It&#8217;s parent for all types of wrappers &#8211; one for each collection type and the advantage of using wrapper is that hey&#8217;re all designed as abstract classes implementing interface for given type of Collection, in case of Set it&#8217;s <a href="http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/ForwardingSet.html">ForwardingSet</a> (to continue older example) and the only thing you need to do as implementor is to telli wrapper how it can find its delegate by providing a <a href="http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/ForwardingObject.html#delegate%28%29"><em>delegate</em></a> method.</p>
<p>Below you can find previous example rewritten to use ForwardingSet with disabled <em>clear</em> method. Last but not least &#8211; this version is waaay much cleaner <img src='http://2lips.pl/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  and you also let compiler do its job &#8211; if you check the previous post you&#8217;ll notice that there are two versions of this solution. The original one contained a but because I made a typo and the code checks for call to <em>clean </em>method instead of <em>clear&#8230;</em></p>
<pre class="brush: java; title: ; notranslate">
import java.util.Set;
import com.google.common.collect.ForwardingSet;

class StructElement3 {

	private class ForwardingSetNoClear extends ForwardingSet&lt;String&gt; {

		private Set&lt;String&gt; delegate;
		public ForwardingSetNoClear(Set&lt;String&gt; delegate) {
			this.delegate = delegate;
		}

		@Override
		protected Set&lt;String&gt; delegate() {
			return delegate;
		}

		@Override
		public void clear() {
			throw new UnsupportedOperationException(&quot;Cannot call clear&quot;);
		}
	}

	public StructElement3(Set&lt;String&gt; obj) {
		Set&lt;String&gt; forwardingSet =  new ForwardingSetNoClear(obj);

		// yeah yeah keep talking...
		forwardingSet.clear();
	}

}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://2lips.pl/blog/google-collections-wrappers-forwardingobjects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hibernate automated sql SUM&#8217;s retrieval</title>
		<link>http://2lips.pl/blog/hibernate-sum-pojo-entity/</link>
		<comments>http://2lips.pl/blog/hibernate-sum-pojo-entity/#comments</comments>
		<pubDate>Tue, 08 Nov 2011 21:39:16 +0000</pubDate>
		<dc:creator>bendi</dc:creator>
				<category><![CDATA[hibernate]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[column]]></category>
		<category><![CDATA[pojo]]></category>
		<category><![CDATA[sql]]></category>
		<category><![CDATA[sum]]></category>

		<guid isPermaLink="false">http://2lips.pl/blog/?p=668</guid>
		<description><![CDATA[Problem description There is a part of your application that needs to display summaries of certain piece of data stored in data base and you need to specily  certain intervals for which summaries should be retrieved. Requirements I want to have an easy way of fetching summaries for some columns in certain table for specified [...]]]></description>
			<content:encoded><![CDATA[<h3>Problem description</h3>
<p>There is a part of your application that needs to display summaries of certain piece of data stored in data base and you need to specily  certain intervals for which summaries should be retrieved.</p>
<h3>Requirements</h3>
<p>I want to have an easy way of fetching summaries for some columns in certain table for specified interval.</p>
<h3>Solution description</h3>
<h5>Plain SQL</h5>
<p>The first solution that comes into play is glue some pieces of SQL together from sum and execute it &#8211; yes it&#8217;s fast, it works but it&#8217;s ugly.</p>
<h5>Use HQL</h5>
<p>Yes in this solution we&#8217;ve got some of the job perfomed by Hibernate &#8211; we&#8217;ve got our entity defined, there&#8217;s a bridge for each sql dilatect but&#8230; we still need to explicitly state columns and add calls to sum function in order to retrieve summaries.</p>
<h5>Entity to Criteria mapping</h5>
<p>But maybe we could somehow use the same Entity object that we have already defined for this specific table and instead of performing regular fetch, generate sql based on <em>@Column</em> definitions. That way we are able to use JavaBean property name as alias for sum and use result transformer to get the data back.</p>
<p>The only portion that&#8217;s left here is adding support for omitting some properties &#8211; we don&#8217;t want to do automated retrieval of SUM&#8217;s for name or id <img src='http://2lips.pl/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h3>Source code</h3>
<p>Solution consists of 2 static methods responsible for:</p>
<ul>
<li><a href="https://github.com/bendi/code#L74">getSumarriesProjectionList </a>- getting list of projections with proper aliasing based on <em>@Column</em> annotations</li>
<li><a href="https://github.com/bendi/code#L39">getSummaries</a> &#8211; addding <a href="http://docs.jboss.org/hibernate/core/3.3/api/org/hibernate/transform/AliasToBeanResultTransformer.html">AliasToBeanResultTransformer</a>, applying interval and retrieving results. It also accepts list of excluded properties (other than date and id <img src='http://2lips.pl/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> )</li>
</ul>
<p>There&#8217;s also <a href="https://github.com/bendi/code#L54">3rd method</a> but it&#8217;s totally optional &#8211; it prevents NPE for returned values of a specifc type and it uses <a href="http://2lips.pl/blog/cglib-jdk15-generics/">cglib-jdk5</a> Enhancer, so you don&#8217;t need to do explicit casting <img src='http://2lips.pl/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>You can see full <a href="https://github.com/bendi/code/tree/master/criteria_utils">source code on github</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://2lips.pl/blog/hibernate-sum-pojo-entity/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>List onblur seam problem</title>
		<link>http://2lips.pl/blog/list-onblur-seam-problem/</link>
		<comments>http://2lips.pl/blog/list-onblur-seam-problem/#comments</comments>
		<pubDate>Sat, 05 Nov 2011 11:27:00 +0000</pubDate>
		<dc:creator>bendi</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[datatable]]></category>
		<category><![CDATA[inputtext]]></category>
		<category><![CDATA[integer]]></category>
		<category><![CDATA[jsf]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[onblur]]></category>
		<category><![CDATA[richfaces]]></category>

		<guid isPermaLink="false">http://2lips.pl/blog/?p=683</guid>
		<description><![CDATA[As you can see title of this entry is not very descriptive but the idea is to save some of you folks couple of hours (this is how I&#8217;ve been trying to find some pieces of information). So the problem is pretty well described under this entry on seam forum but just to give you [...]]]></description>
			<content:encoded><![CDATA[<p>As you can see title of this entry is not very descriptive but the idea is to save some of you folks couple of hours (this is how I&#8217;ve been trying to find some pieces of information).</p>
<p>So the problem is pretty well described under <a href="http://seamframework.org/Community/SeamComponentBindingWithPrimitiveWrapper">this entry on seam forum</a> but just to give you an idea:</p>
<ul>
<li>you have a list of integer wrappers (List&lt;Integer&gt;)</li>
<li>you pass this list to your jsf view</li>
<li>some component goes through entries in the list (<a href="http://docs.jboss.org/richfaces/latest_3_3_X/en/devguide/html/rich_dataTable.html">rich:datatable</a> in my case)</li>
<li>all entries are displayed as <a href="http://www.jsftoolbox.com/documentation/help/12-TagReference/html/h_inputText.html">h:inputText</a> and value is assigned using name given in var attribute</li>
<li>each input text has an onblur event attached that re renders the whole element (rich:datatable)</li>
</ul>
<p>The expected behaviour is that newly entered value is bound and displayed again in the form but this is not happening.</p>
<p>The solution is <a href="http://stackoverflow.com/questions/5252708/how-to-save-an-array-in-jsf-with-uirepeat-hinputtext-managed-bean">described here</a> &#8211; basically assigning value using name given in <em>var</em> attribute is not bi-directional, so you need to use <em>indexing</em> technique.</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://2lips.pl/blog/list-onblur-seam-problem/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Clownfish effect flash/as3</title>
		<link>http://2lips.pl/blog/clownfish-effect-flash-as3/</link>
		<comments>http://2lips.pl/blog/clownfish-effect-flash-as3/#comments</comments>
		<pubDate>Thu, 27 Oct 2011 20:52:26 +0000</pubDate>
		<dc:creator>bendi</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[actionscript3]]></category>
		<category><![CDATA[atan2]]></category>
		<category><![CDATA[avoid]]></category>
		<category><![CDATA[clownfish]]></category>
		<category><![CDATA[flash]]></category>
		<category><![CDATA[mouse]]></category>

		<guid isPermaLink="false">http://2lips.pl/blog/?p=672</guid>
		<description><![CDATA[Below you can find source code for effect named Clownfish. Probably some of you will scratch your heads when seeing this name but for me watching how these bubles avoid cursor is similar to how small clownfish finds shelter in stinging tentacles of the anemone. You can find it in action at this website (circles [...]]]></description>
			<content:encoded><![CDATA[<p>Below you can find source code for effect named <em>Clownfish</em>. Probably some of you will scratch your heads when seeing this name but for me watching how these bubles avoid cursor is similar to how small clownfish finds shelter in stinging tentacles of the anemone.</p>
<p>You can find it in action at <a title="Stowarzyszenie Społeczności Osiedlowej 'AURA'" href="http://stowarzyszenie-aura.org">this website</a> (circles over top menu).</p>
<pre class="brush: as3; title: ; notranslate">
/**
 * Copyright (c) 2011, Marek Bedkowski
 * All rights reserved.
 *
 * @author Marek Bedkowski
 * @package pl.bedkowski.code.clownfish
 * @license new BSD License (https://github.com/bendi/code/blob/master/zend_form_decorator_js_validation/LICENSE)
 *
 */
package pl.bedkowski.code.clownfish
{
	import flash.display.MovieClip;
	import flash.events.Event;

	public class ClowFishBall extends MovieClip
	{
		private var distance:Number,startX:Number = 0,startY:Number = 0,speed:Number = 0;

		private static var DISTANCE:Number = 3000;

		private static var FILL_COLOR:Number = 0x13698F;

		public function ClowFishBall(_x:Number, _y:Number, radius:Number)
		{
			graphics.beginFill(FILL_COLOR);
			graphics.drawCircle(0,0,radius);
			graphics.endFill();

			startX = x = _x;
			startY = y = _y;

			speed = (20/height)*height;
			addEventListener(Event.ENTER_FRAME, followMouse);
		}

		private function followMouse(e:Event):void
		{
			var xdiff:Number = MovieClip(parent).mouseX - x;
			var ydiff:Number = MovieClip(parent).mouseY - y;
			var dist:Number = Math.sqrt(xdiff * xdiff + ydiff * ydiff);
			if (dist &lt; DISTANCE)
			{
				var angle:Number = Math.atan2(ydiff,xdiff);
				var sp:Number = (speed/dist)*3;
				x = startX - Math.cos(angle) * sp;
				y = startY - Math.sin(angle) * sp;
			}
		}
	}
}
</pre>
<p>And here&#8217;s how it&#8217;s been generated:</p>
<pre class="brush: as3; title: ; notranslate">
import pl.bedkowski.code.clownfish.ClowFishBall;

var dist = 10;
for(var ii=0,j=0;ii&lt;9;ii++) {
	for(var i=15,h=1;i&lt;310;i+=dist,j++,h+=.3) {
		var mc:MovieClip =  new ClowFishBall(i, 5+dist*ii, h/2);
		addChild(mc);
	}
}
</pre>
<p>Example:<br />
<code>
    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_0" width="319" height="95">
      <param name="movie" value="http://stowarzyszenie-aura.org/clownfish-effect.swf" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://stowarzyszenie-aura.org/clownfish-effect.swf" width="319" height="95">
      <!--<![endif]-->
        
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>
</code></p>
<p><a href="https://github.com/bendi/code/blob/master/zend_form_decorator_js_validation/LICENSE">LICENSE</a></p>
]]></content:encoded>
			<wfw:commentRss>http://2lips.pl/blog/clownfish-effect-flash-as3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>cglib for java 1.5 (with generics support)</title>
		<link>http://2lips.pl/blog/cglib-jdk15-generics/</link>
		<comments>http://2lips.pl/blog/cglib-jdk15-generics/#comments</comments>
		<pubDate>Fri, 16 Sep 2011 18:46:56 +0000</pubDate>
		<dc:creator>bendi</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[cglib]]></category>
		<category><![CDATA[cglib-jdk15]]></category>
		<category><![CDATA[enhancer]]></category>
		<category><![CDATA[generics]]></category>
		<category><![CDATA[java 1.5]]></category>
		<category><![CDATA[jdk15]]></category>
		<category><![CDATA[templates]]></category>

		<guid isPermaLink="false">http://2lips.pl/blog/?p=656</guid>
		<description><![CDATA[As you probably noticed there are few entries in my blog that deal with usage of cglib. There was one thing though that kept me a bit frustrated &#8211; why wasn&#8217;t it possible to use JDK 1.5 generics when creating eg. new Ehnancer. So I decided to add generics which could also get me more [...]]]></description>
			<content:encoded><![CDATA[<p>As you probably noticed there are few entries in my blog that deal with usage of cglib. There was one thing though that kept me a bit frustrated &#8211; why wasn&#8217;t it possible to use JDK 1.5 generics when creating eg. new Ehnancer.</p>
<p>So I decided to add generics which could also get me more familiar with this library. My first step was to download source code from sourceforge and import into cglib-jdk15 repository on my github account. Afterwards I found out that <a href="https://github.com/bendi/cglib-jdk15/blob/master/cglib/src/main/java/net/sf/cglib/core/AbstractClassGenerator.java">AbstractClassGenerator</a> contains inner <em>Source</em> class which uses caching mechanism for generated classes but unfortunately it wasn&#8217;t possible to add generic WeakHashMap without altering the code. Luckily this didn&#8217;t seem that much complicated &#8211; I just split cache into two separate caches &#8211; one for classes and one for References.</p>
<p>After everything was in place I could update Junit Tests and my code snippets blog entries with no more explicit casts.</p>
<p>Than I had a look at ant build script- in order to put generics version into the repository I wanted to use maven&#8217;s <a href="http://maven.apache.org/plugins/maven-deploy-plugin/examples/deploying-with-classifiers.html"><em>classifier</em></a> but to achieve this a build script needed some more attention. It looked like its task could be replaced with maven tasks/conventions. It all worked &#8211; I could even generate &#8222;nodep&#8221; package but in this case I think that project structure still needs some attention.</p>
<p>Finally in order to build the project you can issue following command:</p>
<pre class="brush: bash; title: ; notranslate">
mvn clean install javadoc:javadoc jxr:jxr jxr:jxr-test site
</pre>
<p>As usual <a href="https://github.com/bendi/cglib-jdk15/tree/master/cglib">modfied source code</a> available on github.</p>
<p>Binaries in <a href="http://repo.bedkowski.pl/maven2/cglib/cglib/2.2.2/">my repository</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://2lips.pl/blog/cglib-jdk15-generics/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Cglib proxy conditional getter (Enhancer)</title>
		<link>http://2lips.pl/blog/conditional-getter/</link>
		<comments>http://2lips.pl/blog/conditional-getter/#comments</comments>
		<pubDate>Mon, 27 Jun 2011 18:38:56 +0000</pubDate>
		<dc:creator>bendi</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[cglib]]></category>
		<category><![CDATA[enhancer]]></category>
		<category><![CDATA[proxy]]></category>

		<guid isPermaLink="false">http://2lips.pl/blog/?p=628</guid>
		<description><![CDATA[Problem description Imagine you have a project with hierarchical data structure with 4 levels, where 1st level serves as reference data for 2nd and so on. So your task as a developer is to present this on a web form with a checkbox for each value, where &#8222;checked&#8221; means that it has its own value [...]]]></description>
			<content:encoded><![CDATA[<h3>Problem description</h3>
<p>Imagine you have a project with hierarchical data structure with 4 levels, where 1st level serves as reference data for 2nd and so on. So your task as a developer is to present this on a web form with a checkbox for each value, where &#8222;checked&#8221; means that it has its own value and &#8222;unchecked&#8221; means that value of such a field should be taken from it&#8217;s parent, with exception for 1st level, which should use only its own values. Furthermore the DTO used for form should pass its state into remote EJB.</p>
<h3>Requirements</h3>
<p>So let&#8217;s summarize it as requirements:</p>
<p><em>I want to be able to bind a command object with pair of fields &#8211; one used for remote EJB and one for determining if field is available on this level. In case field is not available remote EJB object should be passed a null value.</em></p>
<h3>Solution discussion</h3>
<h5>Simple if/else</h5>
<p>The easiest solution is to use regular if/else block and in case field is not available set null passed value otherwise, eg:</p>
<pre class="brush: java; title: ; notranslate">

if (myCommand.isFieldAvailable()) {
   myRemote.setField(myCommand.getField());
} else {
   myRemote.setField(null);
}
</pre>
<p>It does the job but it&#8217;s a bit of an overhead when you have 20 fields &#8211; all 100 lines look alike:</p>
<ul>
<li>check if field is available</li>
<li>pass its value to ejb</li>
<li>set null otherwise</li>
</ul>
<p>An experienced OOP developer, which I&#8217;m sure you are, sees a needless repetition here and it&#8217;s obvious that there&#8217;s got to be a better way.</p>
<h5>Reflection</h5>
<p>Another apporach is to use reflection with property names passed as strings and a helper method which retrieves these using reflection and applies them accrodingly, eg:</p>
<pre class="brush: java; title: ; notranslate">

fromCommandToEJB(&quot;field&quot;, command, ejb);
</pre>
<p>Internally this method will encapsulate logic for checking if <em>available</em> flag is set and reacts to it. This version is <strong>much better</strong> but it still has one flaw &#8211; property name is passed as string and compiler will not warn you when any change in the interface takes place.</p>
<h5>Delegating proxy</h5>
<p>Proxy may sound a bit intimidating but <a href="http://cglib.sourceforge.net/apidocs/net/sf/cglib/Enhancer.html">cglib&#8217;s Ehnancer</a> makes it very easy &#8211; the only requirement is that you can&#8217;t use <em>final </em>classes.</p>
<p>So the work-horse of this solution is <a href="http://cglib.sourceforge.net/apidocs/net/sf/cglib/MethodInterceptor.html">MethodInterceptor</a> that has 3 tasks:</p>
<ol>
<li>Intercept call to a method</li>
<li>Determine if call should be handled (method should be a JavaBean getter).</li>
<li>Handle supported method call (find suffixed method and execute it in order to check what value should be returned).</li>
</ol>
<p>The <strong>first</strong> point is handled by cglib internally, so we&#8217;re not going to spend any more time on it.</p>
<p><strong>Second</strong> point is the decission making part &#8211; which  is a slightly modified version of <a href="http://tutorials.jenkov.com/java-reflection/getters-setters.html">isGetter method presented by Jakob Jenkov in his article on reflection</a>. We&#8217;re going to intercept both <em>get</em> and <em>is</em> methods but exclude the ones ending with <em>Available</em> suffix and instead of returning a <em>boolean</em> our method returns a <em>String</em> where <em>null</em> means that method should not be handled.</p>
<pre class="brush: java; title: ; notranslate">
	private String getHandledPropertyName(Method method) {
		String methodName = method.getName();
		if (!(methodName.startsWith(&quot;get&quot;) ||
			(methodName.startsWith(&quot;is&quot;) &amp;&amp;
			!methodName.endsWith(suffix)))) {
			return null;
		}
		else if (method.getParameterTypes().length != 0 ||
			void.class == method.getReturnType()) {
			return null;
		}
		else if (methodName.startsWith(&quot;get&quot;)) {
			return methodName.substring(3);
		} else {
			return methodName.substring(2);
		}
	}
</pre>
<p>As you can see returned String is important so we can have decission making (get/is prefix) and propoperty name reading (everything following is/get prefix).</p>
<p>There is a small overhead &#8211; every property needs to have an <em>isAvailable</em> method, which in case of compound properties means that each call must be redirected to the &#8222;real&#8221; checker.</p>
<p>Let&#8217;s try an example here &#8211; your bean contains start/endDate method so endDate is not valid without startDate, which means that there should be a common method checking if both dates are set and only afterwards passing it for further processing but with proxy you need to have isStartDateAvailable and isEndDateAvailable which might make code analysis a bit harder, so remember to use proper comments to make others work easier.</p>
<p><strong>Third</strong> point is very simple &#8211; for given property name, find correspoint <em>isAvailable</em> method, check its return value and either call original method, passing its return value or return null.</p>
<pre class="brush: java; title: ; notranslate">
	private Object handleGetter(Method method, String propertyName) throws Throwable {
		String conditionPropertyName = StringUtils.uncapitalize(propertyName) + suffix;
		PropertyDescriptor conditionDescriptor = PropertyUtils.getPropertyDescriptor(myBean, conditionPropertyName);
		if (conditionDescriptor == null) {
			throw new NoSuchMethodException(&quot;Missing is&quot;+StringUtils.capitalize(conditionPropertyName) + &quot; method for property: &quot; + StringUtils.uncapitalize(propertyName));
		}
		Method condition = conditionDescriptor.getReadMethod();
		if (condition == null) {
			throw new NoSuchMethodException(&quot;Missing is&quot;+StringUtils.capitalize(conditionPropertyName) + &quot; method for property: &quot; + StringUtils.uncapitalize(propertyName));
		}
		if ((Boolean) condition.invoke(myBean)) {
			return method.invoke(myBean);
		}
		return null;
	}
</pre>
<p>I&#8217;ve added also a small utility static method, to make wiring the whole stuff a bit easier.</p>
<pre class="brush: java; title: ; notranslate">
	public static &lt;T&gt; T create(T myBean, String suffix) {
		return (T) Enhancer.create(myBean.getClass(), new ConditionalPropertyInterceptor&lt;T&gt;(myBean, suffix));
	}
</pre>
<p>There&#8217;s just one last thing that needs attention &#8211; how to make sure that each getter has a corresponding <em>isAvailable</em> method. Yes you can take your chances and wait until application is deployed&#8230; but it&#8217;s much better to have so me kind of automatic testing &#8211; in this case I recommend using <a href="http://dozer.sourceforge.net/">dozer library</a> exclude transient properties and after excluding transient properties all the rest should pass. </p>
<p><a href="https://github.com/bendi/code/tree/master/conditionalgetter">Sources available on github</a></p>
]]></content:encoded>
			<wfw:commentRss>http://2lips.pl/blog/conditional-getter/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Application version with MBean and JBoss (ejb3 extension)</title>
		<link>http://2lips.pl/blog/application-version-with-mbean-and-jboss-ejb3-extension/</link>
		<comments>http://2lips.pl/blog/application-version-with-mbean-and-jboss-ejb3-extension/#comments</comments>
		<pubDate>Sun, 12 Jun 2011 09:14:55 +0000</pubDate>
		<dc:creator>bendi</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[jboss]]></category>
		<category><![CDATA[maven]]></category>
		<category><![CDATA[mbean]]></category>
		<category><![CDATA[resource]]></category>
		<category><![CDATA[service]]></category>
		<category><![CDATA[version]]></category>

		<guid isPermaLink="false">http://2lips.pl/blog/?p=594</guid>
		<description><![CDATA[Problem description Let&#8217;s say that your multi-tiered application consists of numerous components: webservice server webservice client business component-logic front-end web application These components communicate with each-other through SOAP webservices and from time to time your customer is reporting an error which you know is caused by non-compatible changes done in the webservice call &#8211; which [...]]]></description>
			<content:encoded><![CDATA[<h3>Problem description</h3>
<p>Let&#8217;s say that your multi-tiered application consists of numerous components:</p>
<ul>
<li>webservice server</li>
<li>webservice client</li>
<li>business component-logic</li>
<li>front-end web application</li>
</ul>
<p>These components communicate with each-other through SOAP webservices and from time to time your customer is reporting an error which you know is caused by non-compatible changes done in the webservice call &#8211; which baiscally means that he did not do a full upgrade &#8211; one of the components is at least one version behind.</p>
<p>The project is built using maven and each release has its own version so the idea is to put this version into easily-accessible form so that each time this problem rises developers could ask customer for the version of a component and thus make sure that problem rised is not upgrade issue.</p>
<h3>Requirements</h3>
<p>So lets first specify requirements for this task:</p>
<p><em>I want to have version of each component easily accessible for users. Version should be applied automatically . After a release it should not be possible to alter version without recompiling the code.</em></p>
<h3>Solution discussion</h3>
<h5>Version should be easily accessible</h5>
<p>The first requirement is a little bit vauge <em>easily accessible</em> mitght differ from person to person but it&#8217;s also stated that person accessing it might have little or nothing to do with development or programming at all, that&#8217;s why solution with writing version of component into the log file might not be enough.</p>
<p>Probably the easiest solution is just to point user to a certain URL within application server, let him take screenshot of version and treat it as PREREQUISITE of all bug reports.</p>
<p>All application servers have managed beans and in JBoss there&#8217;s also a jmx-console where mbeans can be accessed with their properties and in case sombody still prefers command line &#8211; there&#8217;s a utility script called twiddle that can access mbeans from command-line. In order for this to work there needs to be mbean configured within JBoss application server.</p>
<h5>Version should be applied automatically</h5>
<p>Since project is built with maven this requirement is achieved easily &#8211; we just need to add resource filtering, apply version number within the resource and make it accessible to the mbean.</p>
<h5>It should not be possible to alter version without recompiling the code</h5>
<p>This requirement makes it a bit more compliated &#8211; using the previous one only, it could have been just a text file added to the jar and than loaded using Property class. Right now the only option is to have somehow java class treated as a resource, this means that first there should be resource filtering applied and java class should be placed in <em>src/main/java </em>and than everything would go as normal.</p>
<p>This makes any changes to this class a bit harder since one must know that version class is someplace else than <em>src/main/java</em> but proper comment should do the trick.</p>
<h3>Solution description</h3>
<p>Requirement analysis presented us with a view of how the solution should look like:</p>
<ul>
<li>It should be a java class</li>
<li>This java class should be filtered using maven resource filtering</li>
<li>This java class should have version property applied when doing resource filtering</li>
<li>This java class should be treated by JBoss application server as mbean</li>
<li>mbean should contain a meaningful name so it&#8217;s easy to find it in the jmx console</li>
</ul>
<p>Let&#8217;s start with creating a java class for our mbean:</p>
<pre class="brush: java; title: ; notranslate">

public class MyVersion {

  private String version = &quot;${project.version}&quot;;

  public String getVersion() {

    return version;

  }

}
</pre>
<p>As you can see in the code sample above, <em>version</em> property does have a setter &#8211; this is a way to mark it as <em>readonly</em> property in the JMX console.</p>
<p>Now maven needs to know that this class should be treated as regular resource and apply filtering &#8211; thus replacing <em>project.version </em>property with current version number.</p>
<p>So first approach would be to change <em>src/man/java</em> into something different but since it&#8217;s a strong convention this proved to be hard (if not impossible).</p>
<p>So another approach is to use special directory called <em>src/main/tpl</em> and add it as additional resource directory whose output should be placed into <em>src/main/java</em>.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;project&gt;
  ...
  &lt;build&gt;
    &lt;plugins&gt;
      &lt;plugin&gt;
        &lt;artifactId&gt;maven-resources-plugin&lt;/artifactId&gt;
        &lt;version&gt;2.5&lt;/version&gt;
        &lt;executions&gt;
          &lt;execution&gt;
            &lt;id&gt;copy-resources&lt;/id&gt;
            &lt;!-- here the phase you need --&gt;
            &lt;phase&gt;validate&lt;/phase&gt;
            &lt;goals&gt;
              &lt;goal&gt;copy-resources&lt;/goal&gt;
            &lt;/goals&gt;
            &lt;configuration&gt;
              &lt;outputDirectory&gt;${basedir}/src/main/java&lt;/outputDirectory&gt;
              &lt;resources&gt;
                &lt;resource&gt;
                  &lt;directory&gt;src/main/tpl&lt;/directory&gt;
                  &lt;filtering&gt;true&lt;/filtering&gt;
                  &lt;includes&gt;
                    &lt;include&gt;**/*.java&lt;/include&gt;
                  &lt;/includes&gt;
                &lt;/resource&gt;
              &lt;/resources&gt;
            &lt;/configuration&gt;
          &lt;/execution&gt;
        &lt;/executions&gt;
      &lt;/plugin&gt;
    &lt;/plugins&gt;
    ...
  &lt;/build&gt;
  ...
&lt;/project&gt;
</pre>
<p>The only thing that&#8217;s left is to register our mbean so it&#8217;s available through JMX console. On JBoss there&#8217;s special extension of EJB3 specification called <a href="http://docs.jboss.org/ejb3/docs/tutorial/1.0.7/html/Service_POJOs.html">POJO service</a>. It&#8217;s specific annotation that informes JBoss AS to create single instance of your class and have it registered in JNDI under specified name.</p>
<p>So let&#8217;s see how our code changes after applying it:</p>
<pre class="brush: java; title: ; notranslate">
@Service(objectName = &quot;projectName.VersionClass&quot;)
@Management(MyVersion.class)
public class MyVersionImpl implements MyVersion {

 private String version = &quot;${project.version}&quot;;

 public String getVersion() {

 return version;

 }

}
</pre>
<p>As you can see in the code above &#8211; there are two annotations @Service and @Management. The latter requires a management interface to be specified so let&#8217;s create one:</p>
<pre class="brush: java; title: ; notranslate">

public interface MyVersion {

String getVersion();

}
</pre>
<p>And that&#8217;s it &#8211; now we can always tell our client to first provide us with screenshot of a version before handling any bug reports.</p>
<p><strong>NOTE</strong>:  In case you were wondering if it&#8217;s possible to add service mbean into existing jar in your project be warned that the author of this post has tried that and JBoss AS tried to register the same mbean twice &#8211; first when loading the jar alone and second time when loading the jar as a dependency of embedded war which as you can guess resulted in Exception thrown.</p>
]]></content:encoded>
			<wfw:commentRss>http://2lips.pl/blog/application-version-with-mbean-and-jboss-ejb3-extension/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

