tag:blogger.com,1999:blog-65621291888345892842024-02-07T14:00:12.461+01:00Java PeanutsAmicofragilehttp://www.blogger.com/profile/03798843481140367818noreply@blogger.comBlogger34125tag:blogger.com,1999:blog-6562129188834589284.post-5279853328368248372021-01-03T12:43:00.002+01:002021-01-03T12:43:14.565+01:00JavaPeanuts reloaded - #askpietro<p style="text-align: justify;">So, nine years later, here we are: a few of published posts, many periods of silence - the longest one of more than three years!! - and many ideas for incoming posts and content.</p><p style="text-align: justify;">But the "Java" prefix no longer matches my professional life, I moved a long time ago to other technologies - .Net and NodeJs above all - and my professional interests range now from DevOps to distributed systems, from backend to frontend, from Kotlin to C# 9 to TypeScript... and - last but not least - this Blogger-powered blog shows a bunch of limits for code formatting and layout customization, which are starting to bother me... so... I decided to move to another technology stack, based on</p><p style="text-align: justify;"></p><ul><li><a href="https://hexo.io/">hexo</a> blog framework</li><li><a href="http://gitlab.com/">GitLab</a> pages</li><li>GitHub flawored <a href="https://en.wikipedia.org/wiki/Markdown">Markdown</a> </li></ul><div>and switched to a less language-specific blog name: now you can find my (restyled!) old posts - and soon a series of new ones - on <a href="http://askpietro.amicofragile.org" target="_blank">#askpietro</a>: keep in touch!</div><p></p><div id="gtx-trans" style="left: 223px; position: absolute; top: 208px;"><div class="gtx-trans-icon"></div></div>Amicofragilehttp://www.blogger.com/profile/03798843481140367818noreply@blogger.com0tag:blogger.com,1999:blog-6562129188834589284.post-16787609982101719322020-12-23T21:27:00.000+01:002020-12-23T21:27:40.965+01:00Functional shell: a minimal toolbox<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>functional-shell-minimal-toolbox</title>
<link rel="stylesheet" href="https://stackedit.io/style.css" />
</head>
<body class="stackedit">
<div class="stackedit__html"><p>I already wrote <a href="https://javapeanuts.blogspot.com/2020/12/functions-as-first-class-citizens-shell.html">a post</a> about adopting a <em>functional</em> programming style in Bash scripts. Here I want to explore how to build a minimal, reusable functional toolbox for my bash scripts, avoiding redefinition of base <em>functional bricks</em> whenever I need them.</p>
<p>So, in short: I wish I could write a scripts (say <code>use-functional-bricks.sh</code>) like the following</p>
<pre class=" language-bash"><code class="prism language-bash"><span class="token shebang important">#!/bin/bash</span>
double <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
<span class="token function">expr</span> <span class="token variable">$1</span> <span class="token string">'*'</span> 2
<span class="token punctuation">}</span>
square <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
<span class="token function">expr</span> <span class="token variable">$1</span> <span class="token string">'*'</span> <span class="token variable">$1</span>
<span class="token punctuation">}</span>
input<span class="token operator">=</span><span class="token variable"><span class="token variable">$(</span><span class="token function">seq</span> 1 6<span class="token variable">)</span></span>
square_after_double_output<span class="token operator">=</span><span class="token punctuation">$(</span>map <span class="token string">"square"</span> <span class="token punctuation">$(</span>map <span class="token string">"double"</span> <span class="token variable">$input</span><span class="token punctuation">))</span>
<span class="token keyword">echo</span> <span class="token string">"square_after_double_output <span class="token variable">$square_after_double_output</span>"</span>
sum<span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
<span class="token function">expr</span> <span class="token variable">$1</span> <span class="token string">'+'</span> <span class="token variable">$2</span>
<span class="token punctuation">}</span>
sum<span class="token operator">=</span><span class="token punctuation">$(</span>reduce 0 <span class="token string">"sum"</span> <span class="token variable">$input</span><span class="token punctuation">)</span>
<span class="token keyword">echo</span> <span class="token string">"The sum is <span class="token variable">$sum</span>"</span>
</code></pre>
<p>referring to “globally” available functions <code>map</code> and <code>reduce</code>(and maybe others, too) without to re-write them everywhere they are needed and without to be bound to external scripts invocation.</p>
<p>The way I think we can solve the problem refers to three interesting features available in <a href="https://www.gnu.org/software/bash/">bash</a>:</p>
<ul>
<li>export functions from scripts (through <code>export -f</code>)</li>
<li>execute scripts <em>in the current shell’s environment</em>, through <a href="https://ss64.com/bash/source.html"><code>source</code></a> command</li>
<li>execute scripts when bash starts</li>
</ul>
<p>So I wrote the following script (say <code>functional-bricks.sh</code>):</p>
<pre class=" language-bash"><code class="prism language-bash"><span class="token shebang important">#!/bin/bash</span>
map <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
f<span class="token operator">=</span><span class="token variable">$1</span>
<span class="token function">shift</span>
<span class="token keyword">for</span> x
<span class="token keyword">do</span>
<span class="token variable">$f</span> <span class="token variable">$x</span>
<span class="token keyword">done</span>
<span class="token punctuation">}</span>
<span class="token function">export</span> -f map
reduce <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
acc<span class="token operator">=</span><span class="token variable">$1</span>
f<span class="token operator">=</span><span class="token variable">$2</span>
<span class="token function">shift</span>
<span class="token function">shift</span>
<span class="token keyword">for</span> curr
<span class="token keyword">do</span>
acc<span class="token operator">=</span><span class="token variable"><span class="token variable">$(</span>$f $acc $curr<span class="token variable">)</span></span>
<span class="token keyword">done</span>
<span class="token keyword">echo</span> <span class="token variable">$acc</span>
<span class="token punctuation">}</span>
<span class="token function">export</span> -f reduce
</code></pre>
<p>and added the following line at the end of my user’s <code>~/.bashrc</code> file:</p>
<pre><code>. ~/common/functional-bricks.sh
</code></pre>
<p>and… voila!: now <code>map</code> and <code>reduce</code> implemented in <code>functional-bricks.sh</code> are available in all my bash sessions - so I can use them in all my scripts!<br>
And because seeing is beleiving… if I launch the script <code>use-functional-bricks.sh</code>defined above, I get the following output:</p>
<pre><code>square_after_double_output 4
16
36
64
100
144
The sum is 21
</code></pre>
</div>
</body>
</html>
Amicofragilehttp://www.blogger.com/profile/03798843481140367818noreply@blogger.com0tag:blogger.com,1999:blog-6562129188834589284.post-23304004453812363662020-12-20T12:38:00.006+01:002020-12-20T15:34:58.720+01:00Functional way of thinking: higher order functions and polymorphism<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>functional-way-of-thinking</title>
<link rel="stylesheet" href="https://stackedit.io/style.css" />
</head>
<body class="stackedit">
<div class="stackedit__html"><p>I think <a href="https://en.wikipedia.org/wiki/Higher-order_function"><em>higher order functions</em></a> are the functional way to <a href="https://en.wikipedia.org/wiki/Polymorphism_(computer_science)"><em>polymorphism</em></a>: the same way you can write a generic algorithm in an OO language <strong>referring to an interface</strong>, which you can plug specific behaviour into the generic algorithm through, you can follow <strong>the same</strong> “<em>plug something specific into something generic</em>” advice writing a high order function <strong>referring to a function signature</strong>.</p>
<p>Put it another way, function signatures are the functional counterpart for OO interfaces.</p>
<p>This is a very simple concept having big implications about you can design and organize your code. So, I think the best way to metabolize this concept is to get your hands dirty with higher order functions, in order to become faimilar with thinking in terms of <em>functions that consume and return (other) functions</em>.</p>
<p>For example, you can try to reimplement simple higher order functions from some library like <a href="https://lodash.com/">lodash</a>, <a href="https://ramdajs.com/">ramdajs</a> or similar. What about implementing an <code>after</code>function that receives an integer <code>n</code> and another function <code>f</code> and returns a new function that invokes <code>f</code> when it is invoked for the <code>n</code>-th time?</p>
<pre class=" language-javascript"><code class="prism language-javascript"><span class="token keyword">function</span> <span class="token function">after</span><span class="token punctuation">(</span>n<span class="token punctuation">,</span> f<span class="token punctuation">)</span> <span class="token punctuation">{</span>
<span class="token keyword">return</span> <span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
n<span class="token operator">--</span>
<span class="token keyword">if</span><span class="token punctuation">(</span>n <span class="token operator">===</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
<span class="token function">f</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
<p>You can use like this:</p>
<pre class=" language-javascript"><code class="prism language-javascript"><span class="token keyword">const</span> counter <span class="token operator">=</span> <span class="token function">after</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'5!'</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token function">counter</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token function">counter</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token function">counter</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token function">counter</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token function">counter</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment">// Writes '5!' to the console</span>
</code></pre>
<p>So you have a simple <em>tool</em> for <em>count</em> events, reacting to the <code>n</code>-th occurrence (and you honored the <a href="https://en.wikipedia.org/wiki/Single-responsibility_principle">Single Responsibility Principly</a>, too, separating <em>counting</em> responsibility from business behavior implemented by <code>f</code>). Each invocation of <code>after</code> creates a <em>scope</em> (more *technically: a <a href="https://en.wikipedia.org/wiki/Closure_(computer_programming)"><em>closure</em></a> for subsequent executions os the returned function - the value of <code>n</code> or of variables defined in the lexical scope of <code>after</code>'s invocation are nothing different from the instance fields you can use in your class implementing an interface.<br>
Generalizing this approach, you can implement subtle variation of the <code>after</code> function: you can for example write an <code>every</code> function that returns a function that call the <code>f</code> parameter of the <code>every</code> invocation every <code>n</code> times</p>
<pre class=" language-javascript"><code class="prism language-javascript"><span class="token keyword">function</span> <span class="token function">every</span><span class="token punctuation">(</span>n<span class="token punctuation">,</span> f<span class="token punctuation">)</span> <span class="token punctuation">{</span>
<span class="token keyword">let</span> m <span class="token operator">=</span> n
<span class="token keyword">return</span> <span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
m<span class="token operator">--</span>
<span class="token keyword">if</span><span class="token punctuation">(</span>m <span class="token operator">===</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
m <span class="token operator">=</span> n
<span class="token function">f</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
<p>This is my way to see functional composition through higher order functions: another way to plug my specific, business-related behavior into e generic - higher order - <em>piece of code</em>, without reimplement the generic algorithm the latter implements.</p>
<p><em><strong>Bonus track</strong></em>: what is the higher order behaviour implemented by the following function?</p>
<pre class=" language-javascript"><code class="prism language-javascript"><span class="token keyword">function</span> <span class="token function">canYouGuessMyName</span> <span class="token punctuation">(</span>items<span class="token punctuation">,</span> f<span class="token punctuation">)</span> <span class="token punctuation">{</span>
<span class="token keyword">return</span> items<span class="token punctuation">.</span><span class="token function">reduce</span><span class="token punctuation">(</span><span class="token punctuation">(</span>acc<span class="token punctuation">,</span> curr<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">(</span><span class="token punctuation">{</span> <span class="token operator">...</span>acc<span class="token punctuation">,</span> <span class="token punctuation">[</span><span class="token function">f</span><span class="token punctuation">(</span>curr<span class="token punctuation">)</span><span class="token punctuation">]</span><span class="token punctuation">:</span> <span class="token punctuation">(</span>acc<span class="token punctuation">[</span><span class="token function">f</span><span class="token punctuation">(</span>curr<span class="token punctuation">)</span><span class="token punctuation">]</span> <span class="token operator">||</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">concat</span><span class="token punctuation">(</span><span class="token punctuation">[</span>curr<span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
</code></pre>
<blockquote>
<p>Written with <a href="https://stackedit.io/">StackEdit</a>.</p>
</blockquote>
</div>
</body>
</html>
Amicofragilehttp://www.blogger.com/profile/03798843481140367818noreply@blogger.com0tag:blogger.com,1999:blog-6562129188834589284.post-53638547380702231352020-12-12T19:31:00.003+01:002020-12-13T10:03:30.033+01:00Functions as first-class citizens: the shell-ish version<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>functional-bash</title>
<link rel="stylesheet" href="https://stackedit.io/style.css" />
</head>
<body class="stackedit">
<div class="stackedit__html"><p>The idea to compose multiple functions together, passing one or more of them to another as parameters, generally referred to as <em>using higher order functions</em> is a pattern which I’m very comfortable with, since I read about ten years ago the very enlighting book <a href="https://www.blogger.com/blog/post/edit/6562129188834589284/5363854738070223135?hl=en#">Functional Thinking: Paradigm Over Syntax</a> by Neal Ford. The main idea behind this book is that you can adopt a functional mindset programming in any language, wheter it supports <em>function as first-class citizens</em> or not. The examples in that book are mostly written in Java (version 5 o 6), a language that supports (something similar to) <em>functions as first-class citizens</em> only from version 8. As I said, it’s more a matter of mindset than anything else.</p>
<p>So: a few days ago, during a lab of Operating System course, waiting for the solutions written by the students I was wondering If it is possible to take a <em>functional</em> approach composing functions (or something similar…) in a (bash) shell script.</p>
<p><em>(More in detail: the problem triggering my thinking about this topic was "how to reuse a (not so much) complicated piece of code involving searching files and iterating over them in two different use cases, that differed only in the action applied to each file)</em></p>
<p>My answer was <em>Probably yes!</em>, so I tried to write some code and ended up with the solution above.</p>
<p><strong>The main point</strong> is - imho - that as in a language supporting <em>functions as first class citizens</em> the bricks to be put together are <em>functions</em>, in (bash) script the minimal bricks are <em>commands</em>: generally speaking, a command can be a binary, or a <em>script</em> - but <em>functions</em> defined in (bash) scripts can be used as <em>commands</em>, too. After making this mental switch, it’s not particularly difficult to find a (simple) solution:</p>
<p><strong><code>action0.sh</code></strong> - An action to be applied to each element of a list</p>
<pre><code>#!/bin/bash
echo "0 Processing $1"
</code></pre>
<p><strong><code>action1.sh</code></strong> - This first action to be applied to each element of a list</p>
<pre><code>#!/bin/bash
echo "1 Processing $1"
</code></pre>
<p><strong><code>foreach.sh</code></strong> - Something similar to <a href="https://www.blogger.com/blog/post/edit/6562129188834589284/5363854738070223135?hl=en#"><code>List<T>.ForEach(Action<T>)</code></a> extension method of .Net standard library(it’s actually a <em>high order program</em>)</p>
<pre><code>#!/bin/bash
action=$1
shift
for x
do
$action $x
done
</code></pre>
<p><strong><code>main.sh</code></strong> - The main program, reusing <em>foreach</em>’s logic in more cases, passing to the <em>high order program</em> different <em>actions</em></p>
<pre><code>#!/bin/bash
./foreach.sh ./action0.sh $(seq 1 6)
./foreach.sh ./action1.sh $(seq 1 6)
./foreach.sh ./action0.sh {A,B,C,D,E}19
./foreach.sh ./action1.sh {A,B,C,D,E}19
</code></pre>
<p>Following this approach, you can apply different actions to a bunch of files, without duplicating the code that finds them… and you do so applying a functional mindset to bash scripting!</p>
<p>In the same way it is possible to implement something like the classic map <em>higher order function</em> using functions in a bash script:</p>
<pre><code>double () {
expr $1 '*' 2
}
square () {
expr $1 '*' $1
}
map () {
f=$1
shift
for x
do
echo $($f $x)
done
}
input=$(seq 1 6)
double_output=$(map "double" $input)
echo "double_output --> $double_output"
square_output=$(map "square" $input)
echo "square_output --> $square_output"
square_after_double_output=$(map "square" $(map "double" $input))
echo "square_after_double_output --> $square_after_double_output"
</code></pre>
<p><code>square_after_double_output</code>, as expected, contains values 4, 16, 36, 64, 100, 144.</p>
<p>In conclusion… no matter what language you are using: using it functionally, composing bricks and higher order bricks together, it’s just a matter of mindset!</p>
<blockquote>
<p>Written with <a href="https://stackedit.io/">StackEdit</a>.</p>
</blockquote>
</div>
</body>
</html>
Amicofragilehttp://www.blogger.com/profile/03798843481140367818noreply@blogger.com0tag:blogger.com,1999:blog-6562129188834589284.post-82453430064150680112019-07-01T17:16:00.002+02:002019-07-01T17:16:56.915+02:00Singleton is an anti-pattern<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtHDwwPPJNW6r5TbcpY3T523yhACyu4RPddiQpptpfmeWsWkaBNYWzMp5Xy3BcHqLNi7b0WqTZGDQ4uc_NlxJyrKsxq_dUDhXS7OFNZnNb-wOGRESeZeO2dCKNLgne8GLZxRHfql34h_A/s1600/singleton.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="365" data-original-width="683" height="340" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtHDwwPPJNW6r5TbcpY3T523yhACyu4RPddiQpptpfmeWsWkaBNYWzMp5Xy3BcHqLNi7b0WqTZGDQ4uc_NlxJyrKsxq_dUDhXS7OFNZnNb-wOGRESeZeO2dCKNLgne8GLZxRHfql34h_A/s640/singleton.jpg" width="640" /></a></div>
<br />Amicofragilehttp://www.blogger.com/profile/03798843481140367818noreply@blogger.com0tag:blogger.com,1999:blog-6562129188834589284.post-6438581114303695982019-02-19T08:51:00.000+01:002019-02-19T16:39:58.802+01:00Set Of Responsability and IOC<span lang="EN-US" style="font-family: inherit; text-align: justify;"><span style="font-family: inherit;">I recently</span> read this </span><span style="font-family: inherit; text-align: justify;">Pietro’s </span><span style="font-family: inherit; text-align: justify;"><a href="https://javapeanuts.blogspot.com/2018/10/set-of-responsibility.html" target="_blank"><span style="color: blue;">post</span></a> about a possible </span><span style="background: rgb(255 , 255 , 255); font-family: inherit; text-align: justify;">adaptation</span><span style="font-family: inherit; text-align: justify;"> of the “Chain of responsability” pattern: the “<b>Set of responsability</b>”. This is very similar to its "father" because each
</span><span style="font-family: "courier new" , "courier" , monospace; text-align: justify;">Handler</span><span style="font-family: inherit; text-align: justify;"> handles the responsibility of a </span><span style="font-family: "courier new" , "courier" , monospace; text-align: justify;">Request</span><span style="font-family: inherit; text-align: justify;"> but </span><span style="background-color: white; font-family: inherit; text-align: justify;">in this case</span><span style="font-family: inherit; text-align: justify;"><span style="background-color: white;"> i</span>t doesn’t propagate
the check of responsibility to other handlers. There is a responsibility without chain!</span><br />
<div>
<div class="MsoNormal">
<div style="text-align: justify;">
<span style="font-family: inherit;"><br /></span></div>
</div>
<div class="MsoNormal">
<div style="text-align: justify;">
<span lang="EN-US" style="font-family: inherit;">In this article I’d like to present the usage
of this pattern in an <b>IOC Container, </b>where the Handlers aren’t added to the </span><span lang="EN-US" style="font-family: "courier new" , "courier" , monospace;">HandlerSet</span><span lang="EN-US" style="font-family: inherit;">
list but provided from the container. In this way you can add new responsibility
to the system simply adding a new </span><span lang="EN-US" style="font-family: "courier new" , "courier" , monospace;">Handler</span><span lang="EN-US" style="font-family: inherit;"> in the container without changing other
parts of </span>implemented <span lang="EN-US" style="font-family: inherit;">code (es. the </span><span lang="EN-US" style="font-family: "courier new" , "courier" , monospace;">HandlerSet</span><span lang="EN-US" style="font-family: inherit;">), in full compliance with
the <a href="https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle">Open closed principle</a>. <span style="mso-spacerun: yes;"> </span></span><br />
<br /></div>
</div>
<div class="MsoNormal">
<div style="text-align: justify;">
<span lang="EN-US"><span style="font-family: inherit;">For coding I’ll use the <b>Spring Framework (JAVA)</b> because
it has a good IOC Container and provides a set of classes to manage with that. Inversion of control principle and the Dependency Injection are first class citizens in the <a href="https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/beans.html" target="_blank"><span style="color: blue;">SpringFramework</span></a>.</span></span><br />
<span lang="EN-US"><span style="font-family: inherit;"><br /></span></span>
Here is the UML class diagram with 3 responsabilities X,Y,Z and a brief description of the solution adopted.<br />
<div class="mxgraph" data-mxgraph="{"highlight":"#0000ff","nav":true,"resize":true,"toolbar":"zoom layers lightbox","edit":"_blank","xml":"<mxfile modified=\"2019-02-15T16:59:06.600Z\" host=\"www.draw.io\" agent=\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36\" etag=\"vC99h6XJ_uoP2ivh8IDi\" version=\"10.2.2\" type=\"google\"><diagram name=\"Page-1\" id=\"c4acf3e9-155e-7222-9cf6-157b1a14988f\">7V1rc5u4Gv41nul+cAZxs/2xdnrZmXS20+ye0/bLGcXINluMXCwnTn/9SiABumATG2xylk6mQS+vhJCe9yqhDJzZev8hgZvVJxygaGBbwX7g3A5sG1iORX8xynNGccd2RlgmYcCZCsJ9+AuJmpy6CwO0lRgJxhEJNzJxjuMYzYlEg0mCn2S2BY7kp27gEmmE+zmMdOp/w4CsMurYswr6RxQuV+LJwOJ3HuD8xzLBu5g/b2A7i/RfdnsNRVucf7uCAX4qkZx3A2eWYEyyq/V+hiI2tmLYsnrvK+7m/U5QTOpU8AIbTLyHYGwFcAEAGNo+7xh5FoOBAjo2vIgTssJLHMPoXUGdpi+MWJMWLa3IOqKXgF4GcLtK6awQwQcUTfMBmuEIJ/RWjGPWxpbAhLwPo4i3guLgLZtJ9tANijOKfJ/jBrDiAsfkPVyHEUPcf1ASwBhycplNHx8BL5gsEakYFDDKmNhIlGrxIf2A8BqR5JkyJCiCJHyUUQQ5GJc5H69K3w8+lxg2OIzJVp6vz4xGebho+S4HDhcsRwBPtLHFu2SOeK2iIXpR6mhBSuFQExpgnD3qEUY7JODtR3TQphsJMf7PHcPvdE3HNKQz95betTZ7+n86A1ZGHxK8ye65pXsE7ckQRuGS15vTiUJJ0Sa9WvLf6ZPDEgGuNwxmeul31sYCzlFOlqtILdJxCdWnPCQaRRA+wjiI0h6K2g8qL6VtVNoqYUMmFJ94O1D9oicNcYQWpDTGetuMdw7j7CXefEE/d2hLfsuqPFCNi2BsGgNWbWWq8wVtd5Tb+OKKWnlECQmpyn2bTfZtCocpn/rbrOdTTLkWUaoFFqnsSxJtq4L/EUWPiLUqqyFZP+U6lxXmeB3O+fUxBZXgH0gQB0z02L/8jjAU7IGsryVObgIOqB82GGh/ULfwu7Yja4CJc+NlhKfCUoEJZ1qVrNTYqtZHkp54iVKwvd5e6JrSu7C9MBsLZ6QYC1dxBo7xW5aCjawH5tq2Z37aJUyTPWoShWgfkq+l62+M5Wbk/R8B1O0GQG0FMiPvMEAVftc9C6D8aRcB6PjfqSazIa0aFKuTKHQnR9Skyu+/BIXO2Fw7724muO2gcNKj8FIoPDrxnt3axN9OntCvP38uyYfdl9n8+8f/ocX90G/UU6NDnDx/zaeLFjIr6Yni7b588/a5XPqMkpC+Dkp0OHDAyHD4GxHyzGca7ghmgUHe3TvMAoe0U8aJPIoI42gZrKiZ71yw1PW8D/Wyj8jLETmPSF9xRB7gewaQVRgv3xgDa/3t+1B7YAq1tbjaoA0qQ23XdiWNXT/UHk1aEnhbE3g6rZGu2E32tTyVku02qvVCk3+TFHmFWuchE68mgiZ+XVRiBVHnNG1dmZY8rqrNk12eS+GLnWvqfdnUg5qhsNaQqzRk1/QZXu4Ce3JodNgD9sDkALvsADflvjga8rme/6qhf/sUriOYapJUhfE7oKTzuBFzpmbVOF+FUXAHn/GOAYp6r/MfojRd4ST8RZuFQmZS55YLl+1LHPesJod7gphx+SzQDRTSJ7iXGO/gluSKM4rgZhs+5K+RGZMpJgSvJWk6T98pHqptAV3d+QZ159ktqTvf4N8cMZAKFpj3olkUbmbKpoOTFJtoRsd2A+f0yXcpz61bUL7wIXFlc7oKgyBVwgkmkMBsGtmccbGkHfWm9IeO7IwpUI92fEbLoCjTH8aekBmO6bvAMJ1RRDHyxFydmtNfLVg6JgQG/HoQEHyNQ2BUJffferlvTO5tWe5F+Wpyb1pp7OW+WbkfdVvuJ1Vy/72X+5bsveM7V5Z7sf+nF/wWBX/SbcH3G01SdzG1WDe36Jsnqt3VEH8MZGfg0BpbU8GdWHhuODedF+rmpl8vVsZdwIpYGavevWYf4m8JW6DH1nnYAlYXwOVadvtgEWMiOSCqu7mCG3a5SfBjSEHC/NIwQUGxpiEhRrgUdyzl/RlvQxJi5lo8cG8ucxIy2qQhz84fyWMHRqbUtW0y6w1sEjOnGfQE3tds22Hvzzc068Ctkb8zLle0NuluhT9/fM/pwHb4ov7RzaZ9BPDSlN/Lc34m2LhuW7DxNNh863VFu7rClPO7rK6oSvb3uuKqusLruK7QFwi+97qiVV1hzBNeVldULRD0uuKquuLlawoX1RWuyR3tXq7x1L2Vg+ZyAy6X8MNfEVwl6TSRlRHgMUaraQGvnRySdWNZvjzHwHOPZpJexw5aE4QOBInX2kLrdVIFND4PjW9nB8rWNGes7HlsaGvaxPyYdlPGDWPi1K3yHcVSHZk+d+3qPDuv5xr1YKD7WVxleb4DSdyRPrB/bfVA6/Ttx+LLyxvLkb6+HBzaSMwKukEsbCxwyoI3pBQaP5xgZBsUJJEYPXUNuI1Ny8pnbfbJm5bVbaRqQy1/6DTSvfxGQVoXBpeZNeU4AEeV/VNnTWuo7VnTc77tqJayWhHu9smqRXXfbX9ybc1S+3OIilXdC6gWRz2K4mSQqg21DdL+CBzzEThRgJJPMIbLV30STo0jbfov7y7x5Z0jvlTncu4D6+qf3omGS7I/I3t+/FOO/X7JoSEAjCUAuCNQGwBtBT/C1miLDv0iQqPfJbx8f/JFFxHEQvnrTBg2ngd0gS9JqjdWNobX9u3EoUSFzr+obzd2ujivpWDD9fKsBQs2wI0Fco4rBRtii+bx7cnnbiE9T2Svu6tz2FRC0LXkz7Q9X1eGF80HjvVUC8OBbS0SOgi29fsfs0F6Si+hFsLgHjVxTsFIOqjgmETUB/9JS598ooa0W0DZvzw89GXNuQG2SMzm7pJ9mhJ2lK0edQ8pevnRhEqHDx0hoNUeytGB2ke8WGxROzaii/F/6eAb5fDV1xN/D7maSIWQcd2ThDqwne93FgBQiZhlnRcfJx7vfnu92YreJG+ybvzWtVRFA6bQVw5zdD1jgGj6cnHSmjXUMwQJIrsk1sba4EiIYc8dCN02SsawMJSpV2jMbtviMJ6K5HZhRH2Q562zqqXM9pV8y9quZSO7kDQbMwYywLS8Ql2TOnKONNSQSR25slUEwKk2qccNIi0Wf4YgYy/+1oPz7h8=</diagram></mxfile>"}" style="border: 1px solid transparent; max-width: 100%;">
<br /></div>
<script src="https://www.draw.io/js/viewer.min.js" type="text/javascript"></script>
</div>
</div>
</div>
<div class="MsoNormal">
<pre style="background-color: #eeeeee; color: #222222;"><span style="font-size: 13.2px;">@Component
public class XHandler implements Handler {
@Override
public Result handle(Request request) {
return ((RequestX) request).doSomething();
}
@Override
public boolean canHandle(Request request) {
return request instanceof RequestX;
}
}</span> </pre>
<div style="text-align: justify;">
<span style="font-family: "courier new" , "courier" , monospace;">@Component</span> annotation on <span style="font-family: "courier new" , "courier" , monospace;">XHandler</span> tells to Spring to instantiate an object of this type in the IOC container.
</div>
<pre style="background-color: #eeeeee; color: #222222; font-size: 13.2px;">public interface HandlerManager {
Result handle(Request request) throws NoHandlerException;
}
</pre>
<pre style="background-color: #eeeeee; color: #222222; font-size: 13.2px;">@Service
public class CtxHandlerManager implements HandlerManager {
private ApplicationContext applicationContext;
@Value("${base.package}")
private String basePakage;
@Autowired
public CtxHandlerManager(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Override
public Result handle(Request request) throws NoHandlerException {
Optional<handler> handlerOpt = findHandler(request);
if ( !handlerOpt.isPresent() ) {
throw new NoHandlerException();
}
Handler handler = handlerOpt.get();
return handler.handle(request);
}
private Optional<Handler><handler> findHandler(Request request) {
ClassPathScanningCandidateComponentProvider provider = createComponentScanner();
for (BeanDefinition beanDef : provider.findCandidateComponents(basePakage)) {
try {
Class clazz = Class.forName(beanDef.getBeanClassName());
Handler handler = (Handler) this.applicationContext.getBean(clazz);
//find responsible handler for the request
if (handler.canHandle(request)) {
return Optional.ofNullable(handler);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return Optional.empty();
}
private ClassPathScanningCandidateComponentProvider createComponentScanner() {
ClassPathScanningCandidateComponentProvider provider
= new ClassPathScanningCandidateComponentProvider(false);
provider.addIncludeFilter(new AssignableTypeFilter(Handler.class));
return provider;
}
}
</handler></handler></pre>
</div>
<div style="text-align: justify;">
<span style="font-family: inherit;"><span style="font-family: "courier new" , "courier" , monospace;">CtxHandlerManager</span> works like an Handler dispatcher. </span><span style="font-family: inherit;"><span style="font-family: inherit;"> The </span><span style="font-family: "courier new" , "courier" , monospace;">handle</span><span style="font-family: inherit;"> method finds the Handler and calls its </span><span style="font-family: "courier new" , "courier" , monospace;">handle</span><span style="font-family: inherit;"> method which invokes the </span><span style="font-family: "courier new" , "courier" , monospace;">doSomething</span><span style="font-family: inherit;"> method of the </span><span style="font-family: "courier new" , "courier" , monospace;">Request</span><span style="font-family: inherit;">.</span></span><br />
<br />
<span style="font-family: inherit;">In the <span style="background-color: white; font-family: "courier new" , "courier" , monospace;">findHandler </span></span><span style="font-family: inherit;"><span style="text-align: justify;"><span style="font-family: inherit;">method I use the Spring </span></span></span><span style="background-color: white; color: #222222;"><span style="font-family: "courier new" , "courier" , monospace;"><a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/ClassPathScanningCandidateComponentProvider.html" target="_blank">ClassPathScanningCandidateComponentProvider</a> </span></span><span style="text-align: justify;">object with an <span style="font-family: "courier new" , "courier" , monospace;">AssignableTypeFiler</span> to the <span style="font-family: "courier new" , "courier" , monospace;">Handler</span> class. I call the <span style="font-family: "courier new" , "courier" , monospace;">findCandidateComponent</span> on a <span style="font-family: "courier new" , "courier" , monospace;">basePackage</span> (the value is set by <span style="font-family: "courier new" , "courier" , monospace;">@Value</span><span style="color: blue;"> <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/annotation/Value.html" target="_blank"><span style="color: blue;">Spring annotation</span></a></span>) and for each candidate the <span style="font-family: "courier new" , "courier" , monospace;">canHandle</span> method check the responsability. And that's all!</span><br />
<span style="text-align: justify;"><br /></span></div>
<span style="font-family: inherit; text-align: justify;">In </span><span style="font-family: "courier new" , "courier" , monospace; text-align: justify;">Sender</span><span style="font-family: inherit; text-align: justify;"> class the </span><span style="font-family: "courier new" , "courier" , monospace; text-align: justify;">HandlerProvider</span><span style="font-family: inherit; text-align: justify;"> implementation (</span><span style="font-family: "courier new" , "courier" , monospace; text-align: justify;">CtxHandlerManager)</span><span style="font-family: inherit; text-align: justify;">is injected by Spring IOC by "Autowiring":</span>
<br />
<span style="font-family: inherit; text-align: justify;"><br /></span>
<br />
<div style="text-align: justify;">
<pre style="background-color: #eeeeee; color: #222222; font-size: 13.2px;">
@Service
public class Sender {
@Autowired
private HandlerManager handlerProvider;
public void callX() throws NoHandlerException {
Request requestX = new RequestX();
Result result = handlerProvider.handle(requestX);
...
}
</pre>
<br /></div>
<div style="text-align: justify;">
<span style="font-family: inherit;">T</span><span style="font-family: inherit;">his solution let you to add new responsibility simply creating new </span><span style="font-family: "courier new" , "courier" , monospace;">Request</span><span style="font-family: inherit;"> implementation and a new </span><span style="font-family: "courier new" , "courier" , monospace;">Handler</span><span style="font-family: inherit;"> implementation to manage it. By applying </span><span style="font-family: "courier new" , "courier" , monospace;">@Component</span><span style="font-family: inherit;"> annotation on the </span><span style="font-family: "courier new" , "courier" , monospace;">Handler</span><span style="font-family: inherit;"> you allow Spring to autodetect the class for dependency injection when annotation-based configuration and classpath scanning is used. On application reboot, this class can be provided by the IOC Container and instantiated simply invoking the </span><span style="font-family: "courier new" , "courier" , monospace;">HandlerManager</span><span style="font-family: inherit;">.</span></div>
<div style="text-align: start;">
<div style="text-align: justify;">
<br /></div>
</div>
<div style="text-align: start;">
<div style="text-align: justify;">
<span style="font-family: inherit;">In the next post I’d like present a possible implementation of a Component Factory using the "Set of responsability" pattern in conjunction with another interesting pattern, the "Builder pattern".</span></div>
</div>
<div style="text-align: start;">
<div style="text-align: justify;">
<span style="font-family: inherit;"><br /></span></div>
</div>
<div style="text-align: justify;">
<span lang="EN-US" style="font-family: inherit;"><span style="mso-spacerun: yes;"></span></span><br /></div>
<div style="text-align: justify;">
<span lang="EN-US"><span style="font-family: inherit;"><span style="mso-spacerun: yes;"><span style="font-family: inherit;">Happy coding</span> </span><span style="mso-spacerun: yes;"> </span><span style="mso-spacerun: yes;"> </span></span></span></div>
<div style="text-align: start;">
<div style="text-align: justify;">
Mauro</div>
</div>
Mauro Pelizzarihttp://www.blogger.com/profile/04222329532644062323noreply@blogger.com0tag:blogger.com,1999:blog-6562129188834589284.post-33053516330962907012018-10-11T18:14:00.001+02:002018-10-12T09:00:38.530+02:00Set of responsibility<div style="text-align: justify;">
<div style="text-align: left;">
So, three and a half years later... I'm back.</div>
</div>
<div style="text-align: justify;">
<div style="text-align: left;">
<br /></div>
</div>
<div style="text-align: justify;">
<div style="text-align: left;">
According to <a href="https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern">wikipedia</a>, <i>the chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects.[1] Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain</i>.</div>
</div>
<div style="text-align: justify;">
<div style="text-align: left;">
<br /></div>
</div>
<div style="text-align: justify;">
<div style="text-align: left;">
In some cases, I will benefit from flexibility allowed by this pattern, without being tied to the <i>chain-based</i> structure, e.g. when there is an IoC container involved: <span style="font-family: "courier new" , "courier" , monospace;">Handler</span>s in the pattern all have the same interface, so it's difficult to leave their instantiation to the IoC container.</div>
</div>
<div style="text-align: justify;">
<div style="text-align: left;">
<br /></div>
</div>
<div style="text-align: justify;">
<div style="text-align: left;">
In such scenario I use a variation of the classic <i>chain of responsibility</i>: there are still <i>responsibilities</i>, off course, but there is no <i>chain</i> out there.</div>
</div>
<div style="text-align: justify;">
<div style="text-align: left;">
<br /></div>
</div>
<div style="text-align: justify;">
<div style="text-align: left;">
I like to call my variation set of responsibility (or list of responsibility, see above for discussion about this) - the structure is the one that follows (C# code):
</div>
</div>
<div style="text-align: justify;">
<div style="text-align: left;">
<br /></div>
</div>
<pre style="background-color: #eeeeee;">interface Handler {
Result Handle(Request request);
bool CanHandle(Request request);
}
class HandlerSet {
IEnumerable<handler> handlers;
HandlerSet(IEnumerable < handler > handlers) {
this.handlers = handlers;
}
Result Handle(Request request) {
return this.handlers.Single(h => h.CanHandle(request)).Handle(request);
}
}
class Sender {
HandlerSet handler;
Sender(HandlerSet handler) {
this.handler = handler;
}
void FooBar() {
Request request = ...;
var result = this.handler.Handle(request);
}
}</handler></pre>
<div style="text-align: justify;">
<div style="text-align: left;">
<br /></div>
</div>
<div style="text-align: justify;">
<div style="text-align: left;">
One interesting scenario which I've applied this pattern in is the case in which the <span style="font-family: "courier new" , "courier" , monospace;">Handler</span>s' input type Request hides a hierarchy of different subclasses and each Handler implementation is able to deal with a specific Request subclass: when use polymorphism is not a viable way, e.g. because those classes comes from an external library and are not under our control, we can use set of responsibility in order to cleanup the horrible code that follows:</div>
</div>
<div style="text-align: justify;">
<div style="text-align: left;">
<br /></div>
</div>
<div style="text-align: justify;">
<div style="text-align: left;">
<br /></div>
</div>
<pre>class RequestX : Request {}
class RequestY : Request {}
class RequestZ : Request {}
class Sender {
var result = null;
void FooBar() {
Request request = ...;
if(request is RequestX) {
result = HandleX((RequestX)request);
} else if (request is RequestY) {
result = HandleY((RequestY)request)
} else if (request is RequestZ) {
result = HandleZ((RequestZ)request)
}
}
}
</pre>
<div style="text-align: justify;">
<div style="text-align: left;">
<br /></div>
</div>
<div style="text-align: justify;">
<div style="text-align: left;">
We can't avoid is and () operators usage, but we can hide them behind a polymorphic interface, adopting a design than conform to <a href="https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle">open-closed principle</a>:
</div>
</div>
<div style="text-align: justify;">
<div style="text-align: left;">
<br /></div>
</div>
<pre>class Sender {
HandlerSet handler;
Sender(HandlerSet handler) {
this.handler = handler;
}
void FooBar() {
Request request = ...;
var result = this.handler.Handle(request);
}
}
class HandlerX : Handler {
bool CanHandle(Request request) => request is RequestX;
Result Handle(Request request) {
HandleX((RequestX)request);
}
}
class HandlerY : Handler {
bool CanHandle(Request request) => request is RequestY;
Result Handle(Request request) {
HandleY((RequestY)request);
}
}
class HandlerZ : Handler {
bool CanHandle(Request request) => request is RequestZ;
Result Handle(Request request) {
HandleZ((RequestZ)request);
}
}
</pre>
<div style="text-align: justify;">
<div style="text-align: left;">
<br /></div>
</div>
<div style="text-align: justify;">
<div style="text-align: left;">
Adding a new <span style="font-family: "courier new" , "courier" , monospace;">Request</span> subclass case is now only a matter of adding a new <span style="font-family: "courier new" , "courier" , monospace;">HandlerAA</span> implemementation of <span style="font-family: "courier new" , "courier" , monospace;">Handler</span> interface, without the need to touch existing code.</div>
</div>
<div style="text-align: justify;">
<div style="text-align: left;">
<br /></div>
</div>
<div style="text-align: justify;">
<div style="text-align: left;">
I use in cases like the explained one the name of <i><b>set of responsibility</b></i> to stress the idea that only one handler of the set can handle a single, specific request (I use <span style="font-family: "courier new" , "courier" , monospace;">_handlers.Single(...)</span> method in HandlerSet implementation, too).</div>
</div>
<div style="text-align: justify;">
<div style="text-align: left;">
<br /></div>
</div>
<div style="text-align: justify;">
<div style="text-align: left;">
When the <b>order</b> in which the handlers are tested matters, we can adopt a different <span style="font-family: "courier new" , "courier" , monospace;">_handlers.Single(...)</span> strategy: in this case I like to call the pattern variation <b><i>list of responsibility</i></b>.</div>
</div>
<div style="text-align: justify;">
<div style="text-align: left;">
<br /></div>
</div>
<div style="text-align: justify;">
<div style="text-align: left;">
When more than one handler can handle a specific request we can think to variations of this pattern that select all applyable handlers (i.e. those handlers whose <span style="font-family: "courier new" , "courier" , monospace;">CanHandle</span> method returns true for the current <span style="font-family: "courier new" , "courier" , monospace;">request</span>) and apply them to the incoming <span style="font-family: "courier new" , "courier" , monospace;">request</span>.</div>
</div>
Amicofragilehttp://www.blogger.com/profile/03798843481140367818noreply@blogger.com1tag:blogger.com,1999:blog-6562129188834589284.post-65418492790110007022015-08-12T13:59:00.001+02:002015-08-12T13:59:23.957+02:00Embrace change<div style="text-align: justify;">
So it is: three months ago I joined a new job position, switching from a big company to a little, agile one, after more than eight years of distinguished service :-).</div>
<div style="text-align: justify;">
Furthermore: I switched from a Java and JEE - centric technological environment to a more rich and various one - yet .NET and C# oriented.</div>
<div style="text-align: justify;">
So, my Java Peanuts will maybe become in the future C# Peanuts (or Node.js Peanuts, who knows...) or, more generally, Programming Peanuts: for the moment I'm still planning a little post series about my way from Java to .NET, so... if you are interested... stay tuned!</div>
Amicofragilehttp://www.blogger.com/profile/03798843481140367818noreply@blogger.com0tag:blogger.com,1999:blog-6562129188834589284.post-72694069156349500622014-07-22T16:20:00.000+02:002015-03-24T12:45:24.882+01:00Seven things I really hate in database design<ol>
<li>Common prexif in all table names</li>
<ol>
<li>es: <span style="font-family: "Courier New",Courier,monospace;">TXXX, TYYY, TZZZ, VAAA, VBBB</span> - T stays for <span style="font-family: "Courier New",Courier,monospace;">Table</span>, V stays for <span style="font-family: "Courier New",Courier,monospace;">View</span></li>
<li>es: <span style="font-family: "Courier New",Courier,monospace;">APPXXX, APPYYY, APPZZZ</span> - APP is an <i>application name</i></li>
</ol>
<li> Common prefix in all field names in every table<br /> es: <span style="font-family: "Courier New",Courier,monospace;">APPXXX.XXX_FIELD_A, APPXXX.XXX_FIELD_B, APPXXX.XXX_FIELD_C</span></li>
<li>Fields with the same meaning and different names (in different tables)<br /> es: <span style="font-family: "Courier New",Courier,monospace;">TABLE_A.<b>BANK_ID</b>, TABLE_B.<b>BK_CODE</b></span></li>
<li>Fields with the same logical type and different physical types<br /> es: <span style="font-family: "Courier New",Courier,monospace;">TABLE_A.MONEY_AMOUNT NUMBER(20,2)</span><br /> <span style="font-family: "Courier New",Courier,monospace;">TABLE_B.MONEY_AMOUNT NUMBER(20,0) -- value * 100</span><br /> <span style="font-family: "Courier New",Courier,monospace;">TABLE_B.MONEY_AMOUNT VARCHAR(20) --value * 100 as char</span></li>
<li>No foreign-keys nor integrity constraints at all - by <i>design</i></li>
<li>Date (or generally structured data type) representation with generic and not specific types</li>
<ol>
<li>es: <span style="font-family: "Courier New",Courier,monospace;">TABLE_A.START_DATE NUMBER(8,0) -- yyyyddmm as int</span></li>
<li>es: <span style="font-family: "Courier New",Courier,monospace;">TABLE_B.START_DATE VARCHAR(8) -- yyyyddmm as char</span></li>
</ol>
<li> (possible only in presenceof 6.) <i>Special</i> values for semantic corner-cases which are <span class="short_text" id="result_box" lang="en"><span class="hps"><i>syntactically</i> invalid</span></span><span class="short_text" id="result_box" lang="en"><span class="hps"><br /> es: <span style="font-family: "Courier New",Courier,monospace;">EXPIRY_DATE = 99999999 -- represents "<i>never expires case</i>", <br /> but... IT'S NOT A VALID DATE!!! - why not 99991231??</span></span></span></li>
</ol>
Amicofragilehttp://www.blogger.com/profile/03798843481140367818noreply@blogger.com0Brescia BS, Italia45.5415526 10.21180189999995545.4525846 10.050440399999955 45.630520600000004 10.373163399999955tag:blogger.com,1999:blog-6562129188834589284.post-45513952810911334152013-10-04T14:48:00.000+02:002013-10-04T14:49:53.128+02:00slf4j - based debug template for Eclipse 'surround-with' feature<script src="https://gist.github.com/pietrom/6825410.js"></script>Amicofragilehttp://www.blogger.com/profile/03798843481140367818noreply@blogger.com0tag:blogger.com,1999:blog-6562129188834589284.post-84800665675623992672013-09-25T09:16:00.000+02:002013-09-25T09:16:11.296+02:00slf4j - based logger template for Eclipse auto-completion<script src="https://gist.github.com/pietrom/6682982.js"></script>Amicofragilehttp://www.blogger.com/profile/03798843481140367818noreply@blogger.com0tag:blogger.com,1999:blog-6562129188834589284.post-72670275254944571662012-10-29T09:47:00.001+01:002012-10-29T09:47:35.091+01:00Automate JavaScript testing<div style="text-align: justify;">
I like TDD and testing automation and I'm used to consider essential a toolset providing automation for unit, integration, system tests and for code coverage analysis.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Switching from Java to JavaScript development, I tried to put together a Maven-based toolset that resembles the classic automation tools for Java: a <i>testing framework</i> (with a runner which I can run through <span style="font-family: "Courier New",Courier,monospace;"><span style="background-color: #eeeeee;">mvn clean test</span></span>) and a <i>code coverage tool</i> (which I can for example run through <span style="background-color: #eeeeee;"><span style="font-family: "Courier New",Courier,monospace;">mvn verify</span></span>, obtaining a graphical coverage report).</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
The result is <a href="https://bitbucket.org/amicofragile/javascript-library-test">this small example of JavaScript library</a>, whose Maven-based automation is achieved through a number of excellent frameworks (<a href="http://pivotal.github.com/jasmine/">Jasmine</a>) and Maven plugins (<a href="http://searls.github.com/jasmine-maven-plugin">Jasmine Maven Plugin</a>, <a href="http://timurstrekalov.github.com/saga">Saga</a> JS coverage plugin).</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Feel free to checkout <a href="https://bitbucket.org/amicofragile/javascript-library-test">my sample</a> and to adjust it to your needs!</div>
Amicofragilehttp://www.blogger.com/profile/03798843481140367818noreply@blogger.com1Brescia BS, Italia45.5411875 10.219443745.452217 10.061515199999999 45.630158 10.3773722tag:blogger.com,1999:blog-6562129188834589284.post-84114456543357537022012-05-29T07:30:00.000+02:002012-08-27T21:29:53.602+02:00Mocking static methods and the Gateway pattern<div style="text-align: justify;">
A year ago I started to use <i><b>mocking libraries</b></i> (e.g., <a class="external text" href="http://mockito.org/" rel="nofollow" title="http://mockito.org/">Mockito</a>, <a class="external text" href="http://www.easymock.org/" rel="nofollow" title="http://www.easymock.org">EasyMock</a>, ...), both for learning something new and for testing purpose in hopeless cases<i>.</i>
</div>
<div style="text-align: justify;">
<i><b>Briefly</b></i>: such a library makes it possible to
dynamically redefine the behaviour (return value, thrown exceptions) of
the methods of the class under test, in order to run tests in a
controlled environment. It makes it possible even to check behavioural
expectations for <i>mock objects</i>, in order to test the Class Under Test's interactions with its collaborators.
</div>
<div style="text-align: justify;">
A few weeks ago a <a class="external text" href="http://it.linkedin.com/in/sammyrulez" rel="nofollow" title="http://it.linkedin.com/in/sammyrulez">colleague</a> asked me: "<i>[How] can I <b>mock a static method</b>, eventually using a mock library?</i>".
</div>
<div style="text-align: justify;">
In detail, he was looking for a way to test a class whose code was using a static <tt>CustomerLoginFacade.login(String username, String password)</tt> method provided by an external API (an authentication custom API by a customer enterprise).
</div>
<div style="text-align: justify;">
His code looked as follows:</div>
<br />
<pre style="background-color: #eeeeee;">public class ClassUnderTest {
...
public void methodUnderTest(...) {
...
// check authentication
if(<b>CustomerLoginFacade.login(...)</b>) {
...
} else {
...
}
}
}</pre>
<pre></pre>
<div style="text-align: justify;">
but customer's authentication provider was not accessible from test environment: so the main (but not the only: test isolation, performances, ...) reason to mock the static <tt>login</tt> method.
</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
A quick search in the magic mocking libraries world revealed that:
</div>
<ul style="text-align: justify;">
<li> <a class="external text" href="http://www.easymock.org/" rel="nofollow" title="http://www.easymock.org">EasyMock</a> supports static methods mocking using extensions (e.g, <i><a class="external text" href="http://www.easymock.org/EasyMock2_4_ClassExtension_Documentation.html" rel="nofollow" title="http://www.easymock.org/EasyMock2_4_ClassExtension_Documentation.html">Class Extension</a></i>, <i><a class="external text" href="http://code.google.com/p/powermock/" rel="nofollow" title="http://code.google.com/p/powermock/">PowerMock</a>)</i>
</li>
<li> <a class="external text" href="http://www.jmock.org/" rel="nofollow" title="http://www.jmock.org">JMock</a> doesn't support static method mocking
</li>
<li> <a class="external text" href="http://mockito.org/" rel="nofollow" title="http://mockito.org">Mockito</a> (my preferred [<a class="external text" href="http://java.sun.com/" rel="nofollow" title="http://java.sun.com">Java</a>] mocking library at the moment) doesn't support static method mocking, because <i>Mockito prefers object orientation and dependency injection over static, procedural code that is hard to understand & change</i> (see <a class="external text" href="http://code.google.com/p/mockito/wiki/FAQ" rel="nofollow" title="http://code.google.com/p/mockito/wiki/FAQ">official FAQ</a>). The same position appears even in a JMock-related <a class="external text" href="http://old.nabble.com/Mocking-Static-Methods-td13482266.html" rel="nofollow" title="http://old.nabble.com/Mocking-Static-Methods-td13482266.html">discussion</a>. PowerMock provides a <a href="http://code.google.com/p/powermock/wiki/MockitoUsage">Mockito extension</a> that supports static methods mocking.</li>
</ul>
<div style="text-align: justify;">
So, thanks to my colleague, I will analize the more general question "<i>Ho can I handle external / </i>legacy<i> API </i>(e.g., static methods acting as service facade)<i> for testing purposes?</i>".
I can identify three different approaches:
</div>
<ul>
<li style="text-align: justify;"> <i><b>mocking by library</b></i>: we can use a mocking library supporting external / <i>legacy</i> API mocking (e.g, class' mocking, static methods' mocking), as discussed earlier
</li>
<li style="text-align: justify;"> <i><b>mocking by language</b></i>: we can refer to the features of a dynamically typed programming language to dynamically change external / <i>legacy</i>
API implementation / behaviour. E.g., the login problem discussed
earlier can be solved in Groovy style, using the features of a language
fully integrated with the Java runtime: </li>
</ul>
<pre style="background-color: #eeeeee;"><span style="background-color: #eeeeee;">CustomerLoginFacade.metaClass.'static'.login = {
return true;
};</span> </pre>
<br />
Such an approach can be successfully used when <span style="font-family: "Courier New",Courier,monospace;">CustomerLoginFacade.login</span>'s client code is Groovy code, not for <i>old</i> Java client code.<br />
<ul style="text-align: justify;">
<li><i>Architectural</i> approach: <i><b>mocking by design</b></i>. This approach refers to a general principle: <i>hide every external (concrete) API behind an interface</i> (i.e.: <i>coding on interfaces, not on concrete implementation</i>). This principle is commonly knows as <a href="http://en.wikipedia.org/wiki/Dependency_inversion_principle"><i>dependency inversion</i> principle</a>.
</li>
</ul>
<div style="text-align: justify;">
So, we can solve my colleague's problem this way: first, we define a login <tt>interface</tt>:</div>
<br />
<div style="background-color: #eeeeee;">
</div>
<div style="background-color: #eeeeee;">
<span style="background-color: #eeeeee;">
</span></div>
<pre><span style="background-color: #eeeeee;">public interface MyLoginService {
public abstract boolean login(final String username, final String password);
}</span>
</pre>
<div style="text-align: justify;">
Then, we refactor the original <tt>methodUnderTest</tt> code to use the <tt>interface</tt>:</div>
<br />
<pre style="background-color: #eeeeee;">public class ClassUnderTest {
private <b>MyLoginService loginService</b>;
// Collaborator provided by <i>Constructor injection</i> (see <a class="external text" href="http://misko.hevery.com/2009/02/19/constructor-injection-vs-setter-injection/" rel="nofollow" title="http://misko.hevery.com/2009/02/19/constructor-injection-vs-setter-injection/">here</a> for
// a discussion about injection styles)
public ClassUnderTest(final LoginService loginService) {
this.loginService = loginService;
}
...
public void methodUnderTest(...) {
...
// check authentication
if(<b>loginService.login(...)</b>) {
...
} else {
...
}
}
}</pre>
<pre></pre>
<br />
So, for testing pourposes, we can simply <i>inject</i> a <i>fake</i> implementation of the <tt>MyLoginService</tt> interface:<br />
<br />
<pre style="background-color: #eeeeee;">public void myTest() {
final ClassUnderTest cut = new ClassUnderTest(new FakeLoginService());
cut.methodUnderTest(..., ...);
...
}</pre>
<pre></pre>
<br />
where <tt>FakeLoginService</tt> is simply
<br />
<br />
<pre style="background-color: #eeeeee;">public class FakeLoginService implements MyLoginService {
public boolean login(final String username, final String password) {
return true;
}
}</pre>
<pre></pre>
and the real, pruduction implementation of the interface looks simply like this:<br />
<br />
<pre style="background-color: #eeeeee;">public class RealLoginService implements MyLoginService {
public boolean login(final String username, final String password) {
return CustomerLoginFacade.login(username, password);
}
}</pre>
<pre></pre>
<div style="text-align: justify;">
<br />
Ultimately, the interface defines an abstract <i><a class="external text" href="http://martinfowler.com/eaaCatalog/gateway.html" rel="nofollow" title="http://martinfowler.com/eaaCatalog/gateway.html">gateway</a></i> to the external authentication API: changing the <i>gateway</i> implementation, we can set up a testing environment fully decoupled from real customer' authentication provider<br />
.
</div>
<div style="text-align: justify;">
IMHO, i prefer the last mocking approach: it's more <i>object oriented</i>, and after all... my colleague called me once <i>the more OO person I know</i> :-).
I find this approach more clean and elegant: it's built only upon
common features of programming languages and doesn't refer to external
libraries nor testing-oriented dynamic languafe features.<br />
In terms of design, too, I
think it's a more readable and more reusable solution to the problem,
which allows a clearer identification of responsibilities of the various
pieces of code: <tt>MyLoginService</tt> defines an interface, and every implementation represents a way to implement it (a <i>real-life</i> (i.e.: <i>production</i>) implementation <i>versus</i> the <i>fake</i> one).</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
However, method mocking (by library or by language, doesn't matter) is in
certain, specific situations a very useful technique, too, especially when code that suffers static dependencies (<span style="font-family: "Courier New",Courier,monospace;">ClassUnderTest</span> in our example) is an example of <i>legacy code</i>, designed with no testing in mind, and is eventually out of developer control.</div>
<div style="text-align: justify;">
[Incidentally: the solution adopted by my <a class="external text" href="http://it.linkedin.com/in/sammyrulez" rel="nofollow" title="http://it.linkedin.com/in/sammyrulez">colleague</a> was just that I have proposed (i.e., <i>mocking by design</i>)]</div>
<div style="text-align: justify;">
</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<b>Credits</b>: thanks to <a class="external text" href="http://it.linkedin.com/in/sammyrulez" rel="nofollow" title="http://it.linkedin.com/in/sammyrulez">Samuele</a>
for giving me cause to analyze such a problem (and for our frequent and
ever interesting design-related discussion). Thanks to my wife for hers
valuable support in writing in <i>pseudo-</i>English
</div>
Amicofragilehttp://www.blogger.com/profile/03798843481140367818noreply@blogger.com1Brescia BS, Italia45.5398382 10.222956245.4508662 10.0650277 45.6288102 10.380884700000001tag:blogger.com,1999:blog-6562129188834589284.post-54762108909194136032012-05-24T07:30:00.001+02:002012-05-24T07:30:01.469+02:00Eloquent JavaScript - An opinionate guide to programming<div style="text-align: justify;">
<i><a href="http://www.anobii.com/books/Eloquent_JavaScript/9781593272821/0117dd8d3ff7acb0d3/">Eloquent JavaScript</a> - An opinionate guide to programming - </i>Marijn Haverbeke, 2011</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Interesting and useful guide to Javascript, whose "opinionate" approach
can reconcile with this loved-heated language. I found extremely interesting
the sections about functional programming and object oriented
programming: finally I've found a systematic presentation of OOP in
Javascript!</div>Amicofragilehttp://www.blogger.com/profile/03798843481140367818noreply@blogger.com0Verona VR, Italia45.4383395 10.991727745.2600775 10.6758707 45.616601499999994 11.3075847tag:blogger.com,1999:blog-6562129188834589284.post-59455687077211957862012-05-21T17:09:00.004+02:002014-04-10T10:52:48.556+02:00How to automatically test Java Console<div style="text-align: justify;">
Some weeks ago, during a workroom lesson in University, I've faced a typical <i>TDD-addicted</i> dilemma: how can I test driven develop a console-based Java application?</div>
<div style="text-align: justify;">
The main problem is clearly how to automatically interact with the application, which relies to <span style="font-family: "Courier New",Courier,monospace;">System.in</span> for user input and to <span style="font-family: "Courier New",Courier,monospace;">System.out</span> for user output.</div>
<div style="text-align: justify;">
You can use <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/System.html#setIn%28java.io.InputStream%29"><span style="font-family: "Courier New",Courier,monospace;">System.setIn</span></a> and <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/System.html#setOut%28java.io.PrintStream%29" style="font-family: "Courier New",Courier,monospace;">System.setOut</a> methods, of course: but this is IMHO a dirty solution to the console-interaction testability problem, which can be resolved in a cleaner way referring to the <a href="http://en.wikipedia.org/wiki/Dependency_inversion_principle"><i>dependency inversion</i> principle</a>, ubiquitous in test driven design: rather than directly referring to concrete <span style="font-family: "Courier New",Courier,monospace;">System.in</span> and <span style="font-family: "Courier New",Courier,monospace;">System.out</span> streams (this reference is <i>concrete </i>because it's direct, not because it points to a concrete class: <a href="http://docs.oracle.com/javase/6/docs/api/java/io/InputStream.html"><span style="font-family: "Courier New",Courier,monospace;">InputStream</span></a> is really an <span style="font-family: "Courier New",Courier,monospace;">abstract</span> class), the console-based application should reference to some abstraction that encapsulates standard I/O streams dependency - for example to <a href="http://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html"><span style="font-family: "Courier New",Courier,monospace;">Scanner</span></a> (for user input) and <a href="http://docs.oracle.com/javase/6/docs/api/java/io/PrintStream.html"><span style="font-family: Courier New, Courier, monospace;">PrintStream</span></a> (for user ouput: again, direct reference to <span style="font-family: "Courier New",Courier,monospace;">System.out</span> is <i>concrete</i> because it's direct, not because it points to something concrete).</div>
<div style="text-align: justify;">
So, application behaviour can be encapsulated into a classe having a constructor like this:</div>
<div style="text-align: justify;">
<pre><span class="kd"> </span></pre>
<pre style="background-color: #eeeeee;"><span class="kd">public</span> <span class="nf">HelloApp</span><span class="o">(</span><span class="n">Scanner</span> <span class="n">scanner</span><span class="o">,</span> <span class="n">PrintStream</span> <span class="n">out</span><span class="o">)</span></pre>
</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
The application main method instances such a class and invokes a method thar triggers application logic execution, simply providing Scanner and PrintStream that wrap standard I/O streams:</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<pre style="background-color: #eeeeee;"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-29"></a> <span class="n">Scanner</span> <span class="n">scanner</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Scanner</span><span class="o">(</span><span class="n">System</span><span class="o">.</span><span class="na">in</span><span class="o">);</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-30"></a> <span class="n">scanner</span><span class="o">.</span><span class="na">useDelimiter</span><span class="o">(</span><span class="n">System</span><span class="o">.</span><span class="na">getProperty</span><span class="o">(</span><span class="s">"line.separator"</span><span class="o">));</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-31"></a>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-32"></a> HelloApp app = new HelloApp(scanner, System.out);
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-33"></a> <span class="n">app</span><span class="o">.</span><span class="na">run</span><span class="o">();</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-34"></a><span class="o">}</span></pre>
<pre><span class="o">
</span></pre>
</div>
<div style="text-align: justify;">
Testing code, however, can provide to <span style="font-family: "Courier New",Courier,monospace;">HelloApp</span> testing oriented instances of <span style="font-family: "Courier New",Courier,monospace;">Scanner</span> and <span style="font-family: "Courier New",Courier,monospace;">PrintStream</span>: </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<pre style="background-color: #eeeeee;"><span class="kd">final</span> <span class="n">Scanner</span> <span class="n">scanner</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Scanner</span><span class="o">(</span><span class="s">"Duke y Goofy y Donald n"</span><span class="o">);</span>
<span class="n">scanner</span><span class="o">.</span><span class="na">useDelimiter</span><span class="o">(</span><span class="s">" "</span><span class="o">);</span> </pre>
<pre style="background-color: #eeeeee;"><a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-40"></a><a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-41"></a><span class="n"> </span></pre>
<pre style="background-color: #eeeeee;"><span style="background-color: transparent;">ByteArrayOutputStream outputBuffer = new ByteArrayOutputStream();
PrintStream out = new PrintStream(outputBuffer);</span> </pre>
<pre style="background-color: #eeeeee;"> </pre>
<pre style="background-color: #eeeeee;"><a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-44"></a><span class="kd">final</span> <span class="n">HelloApp</span> <span class="n">app</span> <span class="o">=</span> <span class="k">new</span> <span class="n">HelloApp</span><span class="o">(</span><span class="n">scanner</span><span class="o">,</span> <span class="n">out</span><span class="o">);</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-45"></a><span class="n">app</span><span class="o">.</span><span class="na">run</span><span class="o">();</span></pre>
<pre style="background-color: #eeeeee;"><span class="o"> </span></pre>
<pre style="background-color: #eeeeee;"><span class="kd">final</span> <span class="n">String</span> <span class="n">output</span> <span class="o">=</span> <span class="n">outputBuffer</span><span class="o">.</span><span class="na">toString</span><span class="o">();</span> </pre>
<pre style="background-color: #eeeeee;"><span class="o">// Assertions about outputBuffer content:</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-47"></a><span class="n">assertTrue</span><span class="o">(</span><span class="n">output</span><span class="o">.</span><span class="na">startsWith</span><span class="o">(</span><span class="s">"Welcome to HelloApp!"</span><span class="o">));</span><span class="o"> </span></pre>
</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
So, we have gracefully decoupled application logic from console-based user interactions, providing a solid framework for automated application testing and, even more satisfying for TDD addicted, for Test Driven Development.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
A complete example can be found here: <a href="https://bitbucket.org/pietrom/automatically-testing-the-console">https://bitbucket.org/pietrom/automatically-testing-the-console</a></div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Code repository can be cloned using <a href="http://git-scm.com/">git</a>:</div>
<div style="text-align: justify;">
<pre id="clone-url-https">git clone https://bitbucket.org/pietrom/automatically-testing-the-console.git</pre>
</div>
Amicofragilehttp://www.blogger.com/profile/03798843481140367818noreply@blogger.com0Brescia BS, Italia45.5398382 10.222956245.4508662 10.0650277 45.6288102 10.380884700000001tag:blogger.com,1999:blog-6562129188834589284.post-33042596490861415422012-05-16T09:41:00.004+02:002012-05-16T09:41:55.283+02:00JNDI name duplication problem chez WebSphere<div style="text-align: justify;">
Yesterday a colleague and I have faced a subtle problem deploying a suite of enterprise applications on WebSphere Application Server - version 6.1.</div>
<div style="text-align: justify;">
The problem manifested itself with a marshalling error when a webapp called a service exposed as an EJB <b>in the same enterprise application</b>: this was very annoying due to two main aspects:</div>
<ol style="text-align: justify;">
<li>there was no duplication, between webapp and EJB module, fot the classes involved in the call</li>
<li>the issue seemed to occur randomly: not for all calls (and never for some), not always for the same call (apparently depending to application restart)</li>
</ol>
<div style="text-align: justify;">
After a few hours of <i>stop-and-start-and-read-the-log</i> nightmare, we discovered that at the root of the problem was a JNDI name duplication between EJBs published by two different applications of the suite: these applications are based on the same infrastructural framework, and the framework published some <i>framework services</i> using a fixed JNDI name. This was clearly an error in suite packaging, but... WebSphere did not report in any way this name collision, deployed without errors nor warnings both the applications, and the duplicated JNDI name was associated with an implementation of the service or with the other, depending to starting order of the apps. So:</div>
<ol>
<li>the marshalling problem appeared when the webapp from an EAR called the service published by the other application</li>
<li>the issue occurred only for the EJB with the duplicated name, not for the others; and coccurred or did not depending to the starting order</li>
</ol>
The solution was quite simple: changing the JNDI name of one of the twins services.<br />
But... why the application server did not give any error when deploying an EJB using an already-in-use JNDI name, as do for example JBoss and BEA Weblogic application servers?<br />
<br />
Definitely something to remember!Amicofragilehttp://www.blogger.com/profile/03798843481140367818noreply@blogger.com0Brescia BS, Italia45.5398382 10.222956245.4508662 10.0650277 45.6288102 10.380884700000001tag:blogger.com,1999:blog-6562129188834589284.post-82979646997434716382012-04-17T09:18:00.001+02:002012-04-17T09:19:07.843+02:00Quick trick: solving an MDB deploy problem on WebLogic<div style="text-align: justify;">
Quick trick about a problem I've faced deploying a Message Driven Bean on BEA WebLogic: MDB's configuration in ejb-jar.xml contained this snippet:</div>
<div style="text-align: justify;">
<br /></div>
<div style="background-color: white;">
</div>
<div style="background-color: white;">
</div>
<div style="background-color: #eeeeee;">
<span style="font-family: "Courier New",Courier,monospace;"><message-driven></span><br />
<span style="font-family: "Courier New",Courier,monospace;"> <ejb-name>MyEjb</ejb-name></span><br />
<span style="font-family: "Courier New",Courier,monospace;"> <ejb-class>com.my.domain.MyEjbBean</ejb-class></span><br />
<span style="font-family: "Courier New",Courier,monospace;"> <b><transaction-type>Container</transaction-type></b></span><br />
<span style="font-family: "Courier New",Courier,monospace;"> <message-driven-destination></span><br />
<span style="font-family: "Courier New",Courier,monospace;"> <destination-type>javax.jms.Queue</destination-type></span><br />
<span style="font-family: "Courier New",Courier,monospace;"> </message-driven-destination> </span><br />
<span style="font-family: "Courier New",Courier,monospace;"> <b><acknowledge-mode>auto_acknowledge</acknowledge-mode></b></span><br />
<span style="font-family: "Courier New",Courier,monospace;"></message-driven></span></div>
<br />
<br />
<div style="text-align: justify;">
This configuration worked well on JBoss 4, but causes causes an exception during deployment phase on BEA WebLogic 10:</div>
<br />
<br />
<div style="background-color: #eeeeee;">
</div>
<div style="background-color: #eeeeee;">
Caused By: </div>
<div style="background-color: #eeeeee;">
<span style="background-color: #eeeeee;">org.hibernate.HibernateException: The chosen transaction strategy requires access to the JTA TransactionManager</span></div>
<div style="background-color: #eeeeee;">
<span style="background-color: #eeeeee;"> at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:371)</span></div>
<div style="background-color: #eeeeee;">
<span style="background-color: #eeeeee;"> at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1341)</span></div>
<div style="background-color: #eeeeee;">
<span style="background-color: #eeeeee;"> at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:867)</span></div>
<div style="background-color: #eeeeee;">
<span style="background-color: #eeeeee;"> at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:669)</span></div>
<div style="background-color: #eeeeee;">
<span style="background-color: #eeeeee;"> at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:132)</span></div>
<div style="background-color: #eeeeee;">
<span style="background-color: #eeeeee;"> at weblogic.deployment.PersistenceUnitInfoImpl.createEntityManagerFactory(PersistenceUnitInfoImpl.java:355)</span></div>
<div style="background-color: #eeeeee;">
<span style="background-color: #eeeeee;"> at weblogic.deployment.PersistenceUnitInfoImpl.createEntityManagerFactory(PersistenceUnitInfoImpl.java:333)</span></div>
<div style="background-color: #eeeeee;">
<span style="background-color: #eeeeee;"> at weblogic.deployment.PersistenceUnitInfoImpl.<init>(PersistenceUnitInfoImpl.java:135)</span></div>
<div style="background-color: #eeeeee;">
<span style="background-color: #eeeeee;"> at weblogic.deployment.AbstractPersistenceUnitRegistry.storeDescriptors(AbstractPersistenceUnitRegistry.java:336)</span></div>
<div style="background-color: #eeeeee;">
<span style="background-color: #eeeeee;"> at weblogic.deployment.EarPersistenceUnitRegistry.initialize(EarPersistenceUnitRegistry.java:77)</span></div>
<div style="background-color: #eeeeee;">
<span style="background-color: #eeeeee;"> at weblogic.application.internal.flow.InitJpaFlow.prepare(InitJpaFlow.java:38)</span></div>
<div style="background-color: #eeeeee;">
<span style="background-color: #eeeeee;"> at weblogic.application.internal.BaseDeployment$1.next(BaseDeployment.java:1223)</span></div>
<div style="background-color: #eeeeee;">
<span style="background-color: #eeeeee;"> at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:41)</span></div>
<div style="background-color: #eeeeee;">
<span style="background-color: #eeeeee;"> at weblogic.application.internal.BaseDeployment.prepare(BaseDeployment.java:367)</span></div>
<div style="background-color: #eeeeee;">
<span style="background-color: #eeeeee;"> at weblogic.application.internal.EarDeployment.prepare(EarDeployment.java:58)</span></div>
<div style="background-color: #eeeeee;">
<span style="background-color: #eeeeee;"> at weblogic.application.internal.DeploymentStateChecker.prepare(DeploymentStateChecker.java:154)</span></div>
<div style="background-color: #eeeeee;">
<span style="background-color: #eeeeee;"> at weblogic.deploy.internal.targetserver.AppContainerInvoker.prepare(AppContainerInvoker.java:60)</span></div>
<div style="background-color: #eeeeee;">
<span style="background-color: #eeeeee;"> at weblogic.deploy.internal.targetserver.operations.ActivateOperation.createAndPrepareContainer(ActivateOperation.java:208)</span></div>
<div style="background-color: #eeeeee;">
<span style="background-color: #eeeeee;"> at weblogic.deploy.internal.targetserver.operations.ActivateOperation.doPrepare(ActivateOperation.java:98)</span></div>
<div style="background-color: #eeeeee;">
<span style="background-color: #eeeeee;"> at weblogic.deploy.internal.targetserver.operations.AbstractOperation.prepare(AbstractOperation.java:217)</span></div>
<div style="background-color: #eeeeee;">
<span style="background-color: #eeeeee;"> at weblogic.deploy.internal.targetserver.DeploymentManager.handleDeploymentPrepare(DeploymentManager.java:749)</span></div>
<div style="background-color: #eeeeee;">
<span style="background-color: #eeeeee;"> at weblogic.deploy.internal.targetserver.DeploymentManager.prepareDeploymentList(DeploymentManager.java:1216)</span></div>
<div style="background-color: #eeeeee;">
<span style="background-color: #eeeeee;"> at weblogic.deploy.internal.targetserver.DeploymentManager.handlePrepare(DeploymentManager.java:250)</span></div>
<div style="background-color: #eeeeee;">
<span style="background-color: #eeeeee;"> at weblogic.deploy.internal.targetserver.DeploymentServiceDispatcher.prepare(DeploymentServiceDispatcher.java:160)</span></div>
<div style="background-color: #eeeeee;">
<span style="background-color: #eeeeee;"> at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.doPrepareCallback(DeploymentReceiverCallbackDeliverer.java:171)</span></div>
<div style="background-color: #eeeeee;">
<span style="background-color: #eeeeee;"> at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.access$000(DeploymentReceiverCallbackDeliverer.java:13)</span></div>
<div style="background-color: #eeeeee;">
<span style="background-color: #eeeeee;"> at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer$1.run(DeploymentReceiverCallbackDeliverer.java:47)</span></div>
<div style="background-color: #eeeeee;">
<span style="background-color: #eeeeee;"> at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:528)</span></div>
<div style="background-color: #eeeeee;">
<span style="background-color: #eeeeee;"> at weblogic.work.ExecuteThread.execute(ExecuteThread.java:201)</span></div>
<div style="background-color: #eeeeee;">
<span style="background-color: #eeeeee;"> at weblogic.work.ExecuteThread.run(ExecuteThread.java:173)</span></div>
<br />
<br />
<div style="text-align: justify;">
The problem was the presence of <span style="font-family: "Courier New",Courier,monospace;"><acknowledge-mode></span> tag: this has no effect when <span style="font-family: "Courier New",Courier,monospace;"><transaction-type></span> is <span style="font-family: "Courier New",Courier,monospace;">Container</span> (in this case messages ACK coincides with transaction commit). On JBoss the <span style="font-family: "Courier New",Courier,monospace;"><acknowledge-mode></span> tag is ignored, but WebLogic validate configuration and raises an Exception when its presence is meaningless.</div>
<div style="text-align: justify;">
Removing the tag solved the problem.</div>
<br />Amicofragilehttp://www.blogger.com/profile/03798843481140367818noreply@blogger.com0Brescia BS, Italia45.5398382 10.222956245.4508662 10.0650277 45.6288102 10.380884700000001tag:blogger.com,1999:blog-6562129188834589284.post-21499790006668320422012-04-13T08:51:00.000+02:002015-01-26T09:59:46.428+01:00How-to find a class in a JAR directory using shell scripting<div style="text-align: justify;">
The biggest problems in J2EE applications deployment come often from classloader hierarchies and potential overlapping between server-provided and application-specific libraries. So, searching classes through collection of JARs is oftwen the main activity in order to identifiy and fix classloader issues.</div>
<div style="text-align: justify;">
<span class="short_text" id="result_box" lang="en"><span class="hps">This</span> <span class="hps">is surely</span> <span class="hps">a tedious</span> <span class="hps">and repetitive task: so,</span></span> here's a shell script you can use to automate JAR collection traversing and tar command's output analysis to search a pattern, which is provided as script parameter.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<i>Credits</i>: Thanks to <i><a href="http://sirowain.com/">sirowain</a></i> for parameter check and return code related contributions.</div>
<br />
<pre style="background-color: #eeeeee;"><span class="c">#!/bin/bash</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-2"></a><span class="c"># Commonly available under GPL 3 license</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-3"></a><span class="c"># Copyleft Pietro Martinelli - javapeanuts.blogspot.com</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-4"></a><span class="k">if</span> <span class="o">[</span> -z <span class="nv">$1</span> <span class="o">]</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-5"></a><span class="k">then</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-6"></a><span class="k"> </span><span class="nb">echo</span> <span class="s2">"Usage: $0 <pattern>"</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-7"></a><a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284#allposts/postNum=2" name="cl-6"></a><span class="k"> </span>echo "tar xf's output will be tested against provided <pattern> in order\
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-7"></a> <a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-7"></a> <span class="nb"></span>to select matching JARs"
<span class="nb">exit </span>1
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-8"></a><span class="k">else</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-9"></a><span class="k"> </span><span class="nv">jarsFound</span><span class="o">=</span><span class="s2">""</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-10"></a> <span class="k">for </span>file in <span class="k">$(</span>find . -name <span class="s2">"*.jar"</span><span class="k">)</span>; <span class="k">do</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-11"></a><span class="k"> </span><span class="nb">echo</span> <span class="s2">"Processing file ${file} ..."</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-12"></a> <span class="nv">out</span><span class="o">=</span><span class="k">$(</span>jar tf <span class="k">${</span><span class="nv">file</span><span class="k">}</span> | grep <span class="k">${</span><span class="nv">1</span><span class="k">})</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-13"></a> <span class="k">if</span> <span class="o">[</span> <span class="s2">"${out}"</span> !<span class="o">=</span> <span class="s2">""</span> <span class="o">]</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-14"></a> <span class="k">then</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-15"></a><span class="k"> </span><span class="nb">echo</span> <span class="s2">" Found '${1}' in JAR file ${file}"</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-16"></a> <span class="nv">jarsFound</span><span class="o">=</span><span class="s2">"${jarsFound} ${file}"</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-17"></a> <span class="k">fi</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-18"></a><span class="k"> done</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-19"></a><span class="k"> </span><span class="nb">echo</span> <span class="s2">"${jarsFound}"</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-20"></a>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-21"></a> <span class="nb">echo</span> <span class="s2">""</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-22"></a> <span class="nb">echo</span> <span class="s2">"Search result:"</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-23"></a> <span class="nb">echo</span> <span class="s2">""</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-24"></a>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-25"></a> <span class="k">if</span> <span class="o">[</span> <span class="s2">"${jarsFound}"</span> !<span class="o">=</span> <span class="s2">""</span> <span class="o">]</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-26"></a> <span class="k">then</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-27"></a><span class="k"> </span><span class="nb">echo</span> <span class="s2">"${1} found in"</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-28"></a> <span class="k">for </span>file in <span class="k">${</span><span class="nv">jarsFound</span><span class="k">}</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-29"></a> <span class="k">do</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-30"></a><span class="k"> </span><span class="nb">echo</span> <span class="s2">"- ${file}"</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-31"></a> <span class="k">done</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-32"></a><span class="k"> else</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-33"></a><span class="k"> </span><span class="nb">echo</span> <span class="s2">"${1} not found"</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-34"></a> <span class="k">fi</span>
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-35"></a><span class="k"> </span><span class="nb">exit </span>0
<a href="http://www.blogger.com/blogger.g?blogID=6562129188834589284" name="cl-36"></a><span class="k">fi</span></pre>
<br />
<div style="text-align: justify;">
This script is available on <a href="http://github.com/">github.com</a>:</div>
<div style="text-align: justify;">
<a href="https://github.com/pietrom/javapeanuts-shell-utils/blob/master/find-jar.sh">https://github.com/pietrom/javapeanuts-shell-utils/blob/master/find-jar.sh</a></div>
Amicofragilehttp://www.blogger.com/profile/03798843481140367818noreply@blogger.com4Brescia BS, Italia45.5398382 10.222956245.4508662 10.0650277 45.6288102 10.380884700000001tag:blogger.com,1999:blog-6562129188834589284.post-74433728439713894212012-04-12T10:12:00.000+02:002012-08-27T21:56:47.076+02:00grepcode!<a href="http://grepcode.com/"><span style="font-family: "Courier New",Courier,monospace;">grepcode</span></a> is a very useful web site that allows opensource code reading and navigation in user <i>friendly fashion</i>: it's e.g. very convenient to compare different version of an opensource class to investigate about bugs and their resolution, but to simply navigate through code when no sources' jars in maven repositories are available, too.<br />
And... the search engine look for classes, by name, across all the available packages...<br />
<br />
I like it!Amicofragilehttp://www.blogger.com/profile/03798843481140367818noreply@blogger.com0Brescia BS, Italia45.5398382 10.222956245.4508662 10.0650277 45.6288102 10.380884700000001tag:blogger.com,1999:blog-6562129188834589284.post-72081691597039798362012-03-12T09:45:00.000+01:002012-08-29T11:33:05.055+02:00How to clean-up JBoss temporary directories using bash scriptingRepetitive and annoying file system tasks are the natural field of automation through shell scripting - so, here's a script that can be used to clean up temporary directories created by JBoss Application Server.<br />
<br />
You can provide as parameter the name of the node that you want clean up - if launched without parameters, the script cleans up temporary directories in each node under current installation.<br />
<br />
Tested on JBoss 4.0.5.GA and JBoss 5.1.0.GA installations.<br />
<br />
<div style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;">
</div>
<div style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;">
#!/bin/bash</div>
<div style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;">
# Commonly available under <a href="http://www.gnu.org/licenses/gpl-3.0.html">GPL 3</a> license</div>
<div style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;">
# Copyleft Pietro Martinelli - javapeanuts.blogspot.com<br />
<br />
function <b>cleanTmpDir</b> {<br />
echo " Cleaning ${1}/${2}"<br />
rm -rf "${1}/${2}"<br />
<br />
}<br />
<br />
function <b>cleanNode</b> {<br />
echo "Cleaning \"${1}\" jboss node"<br />
for tmpDir in <b>data log tmp work</b><br />
do<br />
cleanTmpDir ${1} ${tmpDir}<br />
done<br />
}<br />
<br />
<br />
if [ $# -eq 0 ]<br />
then<br />
for dir in $(find server -maxdepth 1 -mindepth 1 -type d)<br />
do<br />
cleanNode ${dir}<br />
done<br />
else<br />
if [ -e "server/${1}" ]<br />
then<br />
cleanNode "server/${1}"<br />
else<br />
echo "${1} is not a subdir of server dir"<br />
fi<br />
fi</div>
<br />
Updated: this script is now available on <a href="http://bitbucket.org/">bitbucket.org</a>:<br />
<a href="https://bitbucket.org/thecleancoder/javapeanuts-shell-utils/src">https://bitbucket.org/thecleancoder/javapeanuts-shell-utils/src</a>Amicofragilehttp://www.blogger.com/profile/03798843481140367818noreply@blogger.com1Brescia BS, Italia45.5398382 10.222956245.4508662 10.0650277 45.6288102 10.380884700000001tag:blogger.com,1999:blog-6562129188834589284.post-29061894937782553592012-02-28T09:04:00.001+01:002012-02-28T09:04:39.375+01:00Never executed - never tested!<div style="text-align: justify;">
Code samples I'll publish in this post are not fakes: they come from real code, released into production.</div>
<div style="text-align: justify;">
And they are not only brilliant samples of never tested code: they are samples of <b>never executed code</b>!!! Indeed there are in these code snippets execution path which ever - ever! - fail. Read to believe...</div>
<div style="text-align: justify;">
<br style="background-color: white;" /></div>
<div style="text-align: justify;">
<b>Sample #1</b> - <i><span style="font-family: "Courier New",Courier,monospace;">NullPointerException</span> at each <span style="font-family: "Courier New",Courier,monospace;">catch</span> execution</i></div>
<div style="background-color: white; text-align: justify;">
<br /></div>
<div style="background-color: white; text-align: justify;">
<span style="font-family: "Courier New",Courier,monospace;"></span></div>
<div style="background-color: #eeeeee; color: black; text-align: justify;">
<span style="font-family: "Courier New",Courier,monospace;">MyClass result = null;</span><br style="font-family: "Courier New",Courier,monospace;" /><span style="font-family: "Courier New",Courier,monospace;">try {</span><br style="font-family: "Courier New",Courier,monospace;" /><span style="font-family: "Courier New",Courier,monospace;"> result = callMethod(...);</span></div>
<div style="background-color: #eeeeee; color: black; text-align: justify;">
<span style="font-family: "Courier New",Courier,monospace;">} catch(Exception e) {</span><span style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;"> // throws ever NullPointerException...</span><br style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;" /><span style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;"> result.registerException(e);</span><br style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;" /><span style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;">}</span><br style="font-family: "Courier New",Courier,monospace;" /><span style="font-family: "Courier New",Courier,monospace;"></span></div>
<div style="text-align: justify;">
<span style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;"></span><span style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;"></span><br style="background-color: white;" /><b>Sample #2</b>: <i><span style="font-family: "Courier New",Courier,monospace;">ArrayIndexOutOfBoundException</span> at each <span style="font-family: "Courier New",Courier,monospace;">catch</span> execution</i><br style="background-color: white;" /><span style="background-color: white;"></span><br style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;" /><span style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;"></span></div>
<div style="background-color: #eeeeee; color: black; text-align: justify;">
<span style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;">try {</span><br style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;" /><span style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;"> result = callSomeMethod(...);</span><br style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;" /><span style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;">} catch(Exception e) {</span><br style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;" /><span style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;"> String[] messages = new String[3];</span><br style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;" /><span style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;"> messages[0] = ... ;</span><br style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;" /><span style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;"> messages[1] = ... ;</span><br style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;" /><span style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;"> messages[2] = ... ;</span><span style="font-family: "Courier New",Courier,monospace;"> </span></div>
<div style="background-color: #eeeeee; color: black; text-align: justify;">
<span style="font-family: "Courier New",Courier,monospace;"> // throws ever ArrayIndexOutOfBoundException</span><span style="font-family: "Courier New",Courier,monospace;"> ...</span></div>
<div style="background-color: #eeeeee; color: black; text-align: justify;">
<span style="font-family: "Courier New",Courier,monospace;"> </span><span style="font-family: "Courier New",Courier,monospace;">messages[3] = ... ; </span></div>
<div style="background-color: #eeeeee; color: black; text-align: justify;">
<span style="font-family: "Courier New",Courier,monospace;"></span><span style="font-family: "Courier New",Courier,monospace;"> throw new CustomException(messages);</span><br style="font-family: "Courier New",Courier,monospace;" /><span style="font-family: "Courier New",Courier,monospace;">}</span></div>
<div style="text-align: justify;">
<br style="font-family: "Courier New",Courier,monospace;" /></div>
<div style="text-align: justify;">
<b>Sample #3</b>: <i><span style="font-family: "Courier New",Courier,monospace;">ClassCastException</span> whenever <span style="font-family: "Courier New",Courier,monospace;">if</span> condition is verified</i></div>
<div style="text-align: justify;">
<br /></div>
<div style="background-color: #eeeeee; text-align: justify;">
<span style="color: black; font-family: "Courier New",Courier,monospace;">public class AClass {</span></div>
<div style="background-color: #eeeeee; text-align: justify;">
<span style="color: black; font-family: "Courier New",Courier,monospace;"> ...</span></div>
<div style="background-color: #eeeeee; text-align: justify;">
<span style="color: black; font-family: "Courier New",Courier,monospace;"> </span><span style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;">public void aMethod(final Object obj) {</span><br style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;" /><span style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;"> ...</span><br style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;" /><span style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;"> if(!obj instanceof InterfaceXYZ) {</span><br style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;" /><span style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;"> final InterfaceXYZ xyz = (InterfaceXYZ)obj;</span><br style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;" /><span style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;"> ...</span><br style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;" /><span style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;"> }</span><br style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;" /><span style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;"> ...</span><br style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;" /><span style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;"> </span><span style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace;">}</span><br style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;" /><span style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace;">}</span><span style="color: black; font-family: "Courier New",Courier,monospace;"> </span></div>
<div style="text-align: justify;">
<span style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;"></span><span style="background-color: #eeeeee; color: black; font-family: "Courier New",Courier,monospace;"></span></div>Amicofragilehttp://www.blogger.com/profile/03798843481140367818noreply@blogger.com1tag:blogger.com,1999:blog-6562129188834589284.post-85283673660251943372012-02-23T14:58:00.004+01:002012-02-23T14:58:44.937+01:00Exception management antipatterns - Episode I<div style="text-align: justify;">
Exception management is a tricky skill, and perhaps the most misunderstood topic of Java - and I think not only Java - programming. So, I will try to collect a series of posts about <i>antipatterns</i> in exception management: to provide a reference to anyone interested in the topic, of course, but also to analyze and deepen the issue myself.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
My first post on the subject concerns a number of <i><b>basic</b> antipatterns</i>:</div>
<ul style="text-align: justify;">
<li><b><i>Throw all away</i></b></li>
<li><b><i>Empty catch</i></b></li>
<li><b><i>Re-throw without cause</i></b></li>
<li><b><i>Log and rethrow</i></b></li>
</ul>
<div style="text-align: justify;">
<span style="font-size: large;"><b>Throw all away</b></span></div>
<div style="text-align: justify;">
This is the simplest exception management antipattern we can (and shouldn't!) use, and is the tipical approach used when studying a new language: <i>no exception management</i>! While this can be a legitimate approach in <b>training contexts</b> - I'm learning Java IO API and will initially concentrate on the <i>sunny day path</i>, not on exception management - or in <b>testing contexts</b> - I'm writing a test that doesn't cover exception handling: another test will cover it! - it's not admittable in normal, production code... simply because without exception management one exception causes program termination.</div>
<div style="text-align: justify;">
<br /></div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
</div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
public void aMethod() <b>throws Exception</b> {</div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
doSomething(); </div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
}</div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
<br /></div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
public void callerMethod() <b>throws Exception</b> {</div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
aMethod(); </div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
}</div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
<br /></div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
public void callersCallerMethod() <b>throws Exception</b> {</div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
callerMethod() </div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
}</div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
<br /></div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
...</div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
<br /></div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
public static void main(String[] args) <b>throws Exception</b> {</div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
callersCallerscallersCallers...CallerMethod();</div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
}</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
etc. etc. etc. ... when <span style="font-family: "Courier New",Courier,monospace;">doSomething</span> method raises an exception, it goes up through the entire stacktrace and causes program termination. Oh!</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<b><span style="font-size: large;">Empty catch</span></b></div>
<div style="text-align: justify;">
T<span class="" id="result_box" lang="en"><span class="hps">his is the</span> <span class="hps">antipattern</span> <span class="hps">which causes more</span> <span class="hps">headaches,</span> as<span class="hps"> it</span> <span class="hps">hides</span> <span class="hps">exceptions instead of really managing them: unlike the previous antipattern, <i><b>Empty catch</b></i> makes very difficult bug finding and fixing, since it gives no information about the exception taht has occurred: the exception simple <i>disappears</i>, </span></span><span class="" id="result_box" lang="en"><span class="hps">the current operation</span> <span class="hps">is not completed</span> <span class="hps">successfully, </span></span><span class="short_text" id="result_box" lang="en"><span class="hps">the user</span> <span class="hps">is not given</span> <span class="hps">any warning</span> <span class="hps">about the unespected application behaviour, and </span></span><span class="" id="result_box" lang="en"><span class="hps">the developer</span> <span class="hps">has no </span></span><span class="" id="result_box" lang="en"><span class="hps">useful </span></span><span class="" id="result_box" lang="en"><span class="hps">information</span> <span class="hps">for analyzing</span> <span class="hps">the issue: <b><i>great</i></b>!</span></span></div>
<div style="text-align: justify;">
<span class="" id="result_box" lang="en"><span class="hps"><br /></span></span></div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
public void aMethod() {</div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
try {</div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
doSomething(); </div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
}</div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
<b>catch(Exception e) {</b></div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
<b> }</b></div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
}</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<span style="font-size: large;"><b>Re-throw without <i>cause</i></b></span></div>
<div style="text-align: justify;">
Another exception management antipattern I've often seen at work is the <i><b>Re-throw without cause</b></i> one: exceptions are catched, exception handling code constructs another, tipically custom, exception and throw it... <i>without reference to the initial exception</i>.</div>
<div style="text-align: justify;">
This can be useful in some specific contexts, such as code in layers that are called using a remote protocol: <span class="short_text" id="result_box" lang="en"><span class="hps">if you do not</span> <span class="hps">want to expose your <i>internal</i> exception through some type of serialization mechanism (RMI, SOAP, ...), you can throw another <i>interface</i> (known to the client)<i> exception</i>: this newly created exception exposes the problem in the client language.</span></span></div>
<div style="text-align: justify;">
<span class="short_text" id="result_box" lang="en"><span class="hps">In regular code, however, creating and throwing and exception without reference to the cause exception is something like <b><i>Empty catch</i></b>: it hides the <i>real</i> problem and causes headaches, both to users and debuggers, since it </span></span><span class="" id="result_box" lang="en"><span class="hps">does not give</span> <span class="hps">sufficient</span> <span class="hps">information to analyze</span> <span class="hps">the problem.</span></span></div>
<div style="text-align: justify;">
<br /></div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
public void aMethod() throws ABCException {</div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
try {</div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
doSomething(); </div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
}</div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
<b>catch(XYZException e) {</b></div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
<b> throw new ABCException("Error!"); </b></div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
<b> }</b></div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
}</div>
<div style="text-align: justify;">
<span class="short_text" id="result_box" lang="en"><span class="hps"><br /></span></span></div>
<div style="text-align: justify;">
<span style="font-size: large;"><b><span class="short_text" id="result_box" lang="en"><span class="hps">Log and rethrow</span></span></b></span></div>
<div style="text-align: justify;">
<span class="short_text" id="result_box" lang="en"><span class="hps">This antipattern refers to both exception and logging management: it consists in catching an exception for the only purpose of logging it, and then rethrow it (possibly wrapped in another). This is an antipattern because it causes a stack-trace pollution in log file, wich makes more difficult to read and interpret it. Try to search debugging information in logs of an application which common exception management approach is <i><b>Log and rethrow</b></i>: you'll find a series of repeated stacktraces, one for each exception; look for significant informations in such a mess is more and more difficult than look for them in a repetition-free log file. Such an approach increases log size without adding significant information, </span></span><span class="" id="result_box" lang="en"><span class="hps">with</span> <span class="hps">the effect of diluting</span> <span class="hps">thesignificant content.</span></span><br />
<span class="" id="result_box" lang="en"><span class="hps"><br /></span></span><br />
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace;">
<span class="" id="result_box" lang="en"><span class="hps">public void aMethod() throws AnException {</span></span></div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace;">
<span class="" id="result_box" lang="en"><span class="hps"> try {</span></span></div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace;">
<span class="" id="result_box" lang="en"><span class="hps"> doSomething();</span></span></div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace;">
<span class="" id="result_box" lang="en"><span class="hps"> } catch(AnException e) {</span></span></div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace;">
<span class="" id="result_box" lang="en"><span class="hps"> logger.log("Error!", e);</span></span></div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace;">
<span class="" id="result_box" lang="en"><span class="hps"> throw e;</span></span></div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace;">
<span class="" id="result_box" lang="en"><span class="hps"> }</span></span></div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace;">
<span class="" id="result_box" lang="en"><span class="hps">}</span></span></div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace;">
<span class="" id="result_box" lang="en"><span class="hps"><br /></span></span></div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace;">
<span class="" id="result_box" lang="en"><span class="hps">public void bMethod() throws AnException {</span></span></div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace;">
<span class="" id="result_box" lang="en"><span class="hps"> try {</span></span></div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace;">
<span class="" id="result_box" lang="en"><span class="hps"> aMethod();</span></span></div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace;">
<span class="" id="result_box" lang="en"><span class="hps"> } catch(AnException e) {</span></span></div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace;">
<span class="" id="result_box" lang="en"><span class="hps"> logger.log("Error!", e);</span></span></div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace;">
<span class="" id="result_box" lang="en"><span class="hps"> </span></span><span class="" id="result_box" lang="en"><span class="hps">throw e;<br />
</span></span>
</div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace;">
<span class="" id="result_box" lang="en"><span class="hps"> }</span></span><span class="" id="result_box" lang="en" style="background-color: #eeeeee;"><span class="hps"> </span></span></div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace;">
<span class="" id="result_box" lang="en" style="background-color: #eeeeee;"><span class="hps">}</span></span></div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace;">
<span class="" id="result_box" lang="en" style="background-color: #eeeeee;"><span class="hps"></span></span><span class="" id="result_box" lang="en"><span class="hps"></span></span>public <span class="" id="result_box" lang="en"><span class="hps">void cMethod() throws AnException {</span></span></div>
</div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
<span class="" id="result_box" lang="en"><span class="hps"> try {</span></span><br />
<span class="" id="result_box" lang="en"><span class="hps"> bMethod();</span></span><br />
<span class="" id="result_box" lang="en"><span class="hps"> } catch(AnException e) {</span></span><br />
<span class="" id="result_box" lang="en"><span class="hps"> logger.log("Error!", e);</span></span><br />
<span class="" id="result_box" lang="en"><span class="hps"> throw e;<br />
</span></span><br />
<span class="" id="result_box" lang="en"><span class="hps"> }<br />
</span></span><br />
<span class="" id="result_box" lang="en"><span class="hps">}</span></span></div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
<span class="" id="result_box" lang="en"><span class="hps"> </span></span></div>
<div style="background-color: #eeeeee; font-family: "Courier New",Courier,monospace; text-align: justify;">
<span class="" id="result_box" lang="en"><span class="hps">public void dMethod() throws AnException {</span></span><br />
<span class="" id="result_box" lang="en"><span class="hps"> try {</span></span><br />
<span class="" id="result_box" lang="en"><span class="hps"> cMethod();</span></span><br />
<span class="" id="result_box" lang="en"><span class="hps"> } catch(AnException e) {</span></span><br />
<span class="" id="result_box" lang="en"><span class="hps"> logger.log("Error!", e);</span></span><br />
<span class="" id="result_box" lang="en"><span class="hps"> handleException(e);<br />
</span></span><br />
<span class="" id="result_box" lang="en"><span class="hps"> }<br />
</span></span><br />
<span class="" id="result_box" lang="en"><span class="hps">}</span></span></div>
<div style="text-align: justify;">
<span class="" id="result_box" lang="en"><span class="hps"> </span></span></div>
<div style="text-align: justify;">
<span class="" id="result_box" lang="en"><span class="hps">In this example the <span style="font-family: "Courier New",Courier,monospace;">AnException</span> is <b>logged four times</b> before it is actually handled, and the log is <b>four times more verbose</b> than necessary - and <b>four time less readable</b>...</span></span><span class="" id="result_box" lang="en"></span></div>
<div style="text-align: justify;">
<span class="" id="result_box" lang="en"></span></div>
<div style="text-align: justify;">
<span class="" id="result_box" lang="en"><span class="hps"></span></span><span class="" id="result_box" lang="en"><span class="hps"> </span></span></div>
<ul style="text-align: justify;">
</ul>Amicofragilehttp://www.blogger.com/profile/03798843481140367818noreply@blogger.com4Brescia BS, Italia45.5398382 10.222956245.4508662 10.0650277 45.6288102 10.380884700000001tag:blogger.com,1999:blog-6562129188834589284.post-41279593453769313242012-02-21T11:20:00.001+01:002012-02-24T08:20:04.670+01:00Book review: Extreme Programming Explained, by Kent Beck<div style="text-align: justify;">
<a href="http://www.anobii.com/books/Extreme_Programming_Explained/9780201616415/001398793d78756729/"><i>Extreme Programming Explained</i></a>, Kent Beck, 1999</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Complete and easy to read introduction to <b>values</b>, <b>principles</b> and
<b>practices</b> which Extreme Programming is based on, wrote by the "father"
of XP. A book every modern <i>software engineer</i> should read. </div>Amicofragilehttp://www.blogger.com/profile/03798843481140367818noreply@blogger.com0Brescia BS, Italia45.5398382 10.222956245.4508662 10.0650277 45.6288102 10.380884700000001tag:blogger.com,1999:blog-6562129188834589284.post-50499304959802726982012-02-21T11:11:00.000+01:002012-02-21T11:11:00.611+01:00Empty JSP template<span style="font-family: inherit;">Here an empty JSP template, providing basic</span><span style="font-family: inherit;"> settings for UTF-8 character encoding </span><span style="font-family: inherit;">configuration.</span><br />
<span style="font-family: inherit;"> </span>
<br />
<pre><%@page <b>contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"</b> %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "<a class="external free" href="http://www.w3.org/TR/html4/strict.dtd" rel="nofollow" title="http://www.w3.org/TR/html4/strict.dtd">http://www.w3.org/TR/html4/strict.dtd</a>">
<html>
<head>
<title><b>Your page title here!</b></title>
<b><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></b>
</head>
<body><b>Your markup here!</b></body>
</html></pre>Amicofragilehttp://www.blogger.com/profile/03798843481140367818noreply@blogger.com0Brescia BS, Italia45.5398382 10.222956245.4508662 10.0650277 45.6288102 10.380884700000001tag:blogger.com,1999:blog-6562129188834589284.post-57031310405587978982012-02-17T14:55:00.000+01:002012-02-17T14:55:16.211+01:00Reinventing the wheel: Collection.size()<pre style="font-family: inherit;"> Original way to <i><b>reinvent the wheel</b></i> - by an examination of "Programming Fundamentals"</pre>
<pre style="font-family: inherit;"> </pre>
<pre style="background-color: #eeeeee;">public class MyContainer {
private final Collection myBag;
public int getBagSize() {
int <b>j = 0</b>;
for(int i = 0; <b>i < this.myBag.size()</b>; i++) {
<b>j++;</b>
}
<b> return j</b>;
}
}</pre>Amicofragilehttp://www.blogger.com/profile/03798843481140367818noreply@blogger.com1Brescia BS, Italia45.5398382 10.222956245.4508662 10.0650277 45.6288102 10.380884700000001