tag:blogger.com,1999:blog-60128182604273706082024-02-07T11:01:01.923-08:00edglogYAJB - yet another java blogUnknownnoreply@blogger.comBlogger17125tag:blogger.com,1999:blog-6012818260427370608.post-84143277643074704532012-11-04T23:58:00.002-08:002012-11-05T01:58:45.433-08:00Testing time-sensitive logic in Java<br />
<div>
<span style="background-color: white; color: #333333; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;"><i>It's astounding. Time is... fleeting (</i></span><i style="color: #333333; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;">The Rocky Horror Picture Show)</i></div>
<div>
<br /></div>
<div>
<div style="text-align: justify;">
<span style="background-color: white; color: #333333; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;">Testing time-sensitive business logic is essentially about being able to change the current time in our tests - somehow - and then checking how this affects the behaviour of the domain object being tested.</span></div>
</div>
<div>
<div style="text-align: justify;">
<span style="background-color: white; color: #333333; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;"><br /></span></div>
</div>
<div>
<div style="text-align: justify;">
<span style="background-color: white; color: #333333; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;">The primitive and brute-force way to do this is to manipulate the computer system clock by manually changing the current time prior to each test... Crucially this approach does not lend itself to running as part of an automated test suite, for obvious reasons.</span></div>
<div style="text-align: justify;">
<span style="background-color: white; color: #333333; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;"><br /></span></div>
</div>
<div>
<div style="text-align: justify;">
<span style="color: #333333; font-family: Arial, Helvetica, sans-serif; font-size: 12.727272033691406px; line-height: 17.999998092651367px;">The other (better) way is use two different clocks: the production code can rely on the system clock while the tests code will depend on a custom clock, i.e is a clock which can be setup to return any particular time as the current time. Usually this custom clock will expose methods to advance/rewind the clock to specific points in time. </span></div>
<div style="text-align: justify;">
<br />
<br /></div>
<div>
<pre class="prettyprint">interface clock{
public DateTime now();
}
class SystemClock implements Clock{
public DateTime now(){
return new DateTime();
}
}
class CustomClock implements Clock{
private DateTime now;
public CustomClock(DateTime now){
this.now = now;
}
public DateTime now(){
return now;
}
public void tick(){
now = now.plusDays(1);
}
}</pre>
<span style="color: #333333; font-family: Arial, Helvetica, sans-serif; font-size: 12.727272033691406px; line-height: 17.999998092651367px; text-align: justify; white-space: normal;"><br /></span>
<span style="color: #333333; font-family: Arial, Helvetica, sans-serif; font-size: 12.727272033691406px; line-height: 17.999998092651367px; text-align: justify;">Both clocks realize the "now()" method defined in the Clock interface. The difference being that the now() method from SystemClock is a simple wrapper around a new instance of a Joda dateTime instance, while the now() method from the CustomClock returns a dateTime attribute which can be modified through the tick() method to make time pass faster :)</span><br />
<span style="color: #333333; font-family: Arial, Helvetica, sans-serif; font-size: 12.727272033691406px; line-height: 17.999998092651367px; text-align: justify; white-space: normal;"><br /></span>
<span style="color: #333333; font-family: Arial, Helvetica, sans-serif; font-size: 12.727272033691406px; line-height: 17.999998092651367px; text-align: justify; white-space: normal;">The custom clock will be injected as a dependency of the testing code and the system clock as a dependency of the production code. </span><span style="color: #333333; font-family: Arial, Helvetica, sans-serif; font-size: 12.727272033691406px; line-height: 17.999998092651367px;">For a (somewhat contrived) example of how this plays out check out:</span> <span style="background-color: white; color: #333333; font-family: Arial, Helvetica, sans-serif; font-size: 12.727272033691406px; line-height: 17.999998092651367px;"><a href="https://github.com/eleco/customclock">https://github.com/eleco/customclock</a></span></div>
<div>
<br /></div>
</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-6012818260427370608.post-86704722572467536262012-10-23T08:45:00.001-07:002012-10-23T08:47:51.733-07:00First steps with... Cucumber JVM<div style="text-align: justify;">
<a href="http://cukes.info/">Cucumber</a> is a tool used to support behaviour driven development. Originally written in Ruby there is now a JVM version, called, quite logically, <a href="https://github.com/cucumber/cucumber-jvm">Cucumber-JVM</a>. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
The basic idea (very summarized...) is to write acceptance tests for a new feature, together with the product owner, before the code is written. Then run the tests, see the tests fail, implement the missing behaviour, re-run the tests etc.. until the tests pass. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
The key objective here is to involve the product owners as much as possible in writing the tests, which from experience can be tricky as they do not generally have a technical background. So it's important for an acceptance tests framework to generate tests with a syntax which is a close as possible to a natural language. </div>
<div style="text-align: justify;">
<br /></div>
Cucumber achieves this quite well, see below for an example Cucumber script (click to zoom in)<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgqsylulSlOr3UnxzIAG1xnYg6RF6tBwIUtMzN2gNayiwr3MWi5vCuLaCAenb4XT3PbbUYKB75GT3joQFSklse18MggCe0NZ8j8Z6xBp9D5JZYj75Kazr6i3sPUagrBPA4jI4nJORniyQw/s1600/Cucumber_scripts.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="268" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgqsylulSlOr3UnxzIAG1xnYg6RF6tBwIUtMzN2gNayiwr3MWi5vCuLaCAenb4XT3PbbUYKB75GT3joQFSklse18MggCe0NZ8j8Z6xBp9D5JZYj75Kazr6i3sPUagrBPA4jI4nJORniyQw/s400/Cucumber_scripts.png" width="400" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<br /></div>
<div style="text-align: justify;">
The right panel defines the tests scripts to execute, easily understandable by non-technical people. No messing around with HTML either, a big win compared with alternative frameworks such as Fitnesse or Concordion.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
The left panel maps the tests scripts to their associated junit tests. Full code source for this example is at: <a href="https://github.com/eleco/bdd">https://github.com/eleco/bdd</a></div>
<br />
<br />
Cucumber outputs the tests results in a nicely-formatted page like so.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhL5MqNrItNFK-sF8txmENJIvZ5q1miGUSyLUvgvjkkCnvtqQhP0xiUu9YmQfpemSbxAaVCoV5vF3-ltG98E3wL_J0cr7YH5iCq4ZBuELMaeQmCwdPhC6X2JxMFqAzRhPq3z6IqS9Ogdlc/s1600/Cucumber_report.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="130" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhL5MqNrItNFK-sF8txmENJIvZ5q1miGUSyLUvgvjkkCnvtqQhP0xiUu9YmQfpemSbxAaVCoV5vF3-ltG98E3wL_J0cr7YH5iCq4ZBuELMaeQmCwdPhC6X2JxMFqAzRhPq3z6IqS9Ogdlc/s400/Cucumber_report.png" width="400" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi9u-t2kvn3tbniBnxVWqFf9zrmi34-J8nQVXVmYchrDVoKTe24M4zNqcnci7H-n5lj7Q_ZWQ7daOoV-VHtIenayrWnq7nyvM4V_Y_vtBtWvKPZM3g1f5mMQv-0lOeSVBvKR0Ud7NcSU8k/s1600/Cucumber_test_results_ko.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="129" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi9u-t2kvn3tbniBnxVWqFf9zrmi34-J8nQVXVmYchrDVoKTe24M4zNqcnci7H-n5lj7Q_ZWQ7daOoV-VHtIenayrWnq7nyvM4V_Y_vtBtWvKPZM3g1f5mMQv-0lOeSVBvKR0Ud7NcSU8k/s400/Cucumber_test_results_ko.png" width="400" /></a></div>
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<br />
<br />Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-6012818260427370608.post-59920522968436428682012-07-10T13:31:00.001-07:002012-11-03T17:05:24.258-07:00Deserializing/serializing JSON with GWTA fairly typical use case: a GWT server-side component serializes java objects into Json, to be consumed by GWT clients.<br />
<br />
Server-side serialization is actually very easy thanks to the <a href="http://code.google.com/p/google-gson/">google-gson</a> library.
It's literally a one-liner:<br />
<pre class="prettyprint">String json =new Gson().toJson(myObject);
</pre>
<br />
On the client side things are a little bit more complicated. Gson (or any other library with features which are not supported on a GWT client such as reflection, dynamic class-loading, multithreading... ) cannot be used.<br />
<br />
One possible alternative is to use <a href="http://code.google.com/p/google-web-toolkit/wiki/AutoBean">autobeans</a><br />
<br />
To deserialize a Person class<br />
<pre class="prettyprint">class Person {
private String name;
public String getName();
public void setName(String s);
}
</pre>
<br />
1. define an interface for the class to deserialize<br />
<pre class="prettyprint lang-java">interface IPerson {
public String getName();
public void setName(String s);
]
</pre>
<br />
2. Mark the class to deserialize as implementing the above interface<br />
<pre class="prettyprint">class Person implements IPerson {...}
</pre>
<br />
3. Define the interface extending AutoBeanFactory
<br />
<pre class="prettyprint">interface Beanery extends AutoBeanFactory{
AutoBean <IPerson> createBean();
}
</pre>
<br />
4. Instantiate the bean factory and deserialize
<pre class="prettyprint">
Beanery beanFactory = GWT.create(Beanery.class);
IPerson person = AutoBeanCodex.decode(beanFactory, IPerson.class, json).as();
</pre>
<br />
<br />Unknownnoreply@blogger.com3tag:blogger.com,1999:blog-6012818260427370608.post-25410437021441276242012-06-29T09:30:00.000-07:002012-06-29T09:30:51.543-07:00Infinite scroll with GWT<div style="text-align: justify;">
The classical pagination pattern leads the user to click on numbered icons to navigate in a long list, each icon being associated with a different page in the list. This is how you browse google search results for instance. This is optimal when moving from page 1 to page 999, but not so much when moving from page to page in sequential order, which is the most frequent use case.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
The alternative is the "infinite scroll" technique. Here the application detects when the user scrolls down to the bottom of the list, and automatically adds the result of the next page to the list. Scrolling can go on this way for as long as results are available to be added to the list, hence the term "infinite scroll". Obviously it's infinite in theory only... but I guess "very long scroll" doesnt have quite the same ring to it.</div>
<div style="text-align: justify;">
<span style="font-size: x-small;"><br /></span></div>
<div style="text-align: justify;">
<span style="font-size: small;">Building an infinite scroll component withb GWT is easy.... because it's already been done. Check out the<a href="http://gwt.google.com/samples/Showcase/Showcase.html#%21CwCellList"> GWT showcase </a><a href="http://gwt.google.com/samples/Showcase/Showcase.html#%21CwCellList"></a></span><span style="font-size: x-small;"><span style="font-size: small;">for an example. Or have a look at my side-project <a href="http://javadevjobs.com/">javadevjobs.com</a> .</span></span></div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<span style="font-size: x-small;"><span style="font-size: small;">The key is in the ShowMorePagerPanel class (source code available from the showcase page) which listens for scroll events and increases the display range when the it detects that the scrollbar has nearly reached its bottom position. This triggers in turn a rangeChangeEvent which acts as cue for the dataProvider to go and fetch more records from the database.</span></span></div>
<div style="text-align: justify;">
<span style="font-size: x-small;"><br /></span></div>
<br />
<span style="font-size: x-small;"><br /></span><br />
<br /><br />
<br />
<br />
<br />
<br />
<br />Unknownnoreply@blogger.com2tag:blogger.com,1999:blog-6012818260427370608.post-72132939661972040522012-06-25T12:14:00.001-07:002012-06-25T12:16:10.875-07:00volatile piggybacking<br />
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<div style="text-align: justify;">
Volatilty piggybacking is the (dubious ?) technique which attributes volatile-like semantics to<u> </u>non-volatile variables.</div>
</div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<div style="text-align: justify;">
<br /></div>
</div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<div style="text-align: justify;">
The <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4">new memory model</a> , from java 5, states that "a<i> write to a volatile field (ยง8.3.1.4) happens-before every subsequent read of that field".</i></div>
</div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<u></u></div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<div style="text-align: justify;">
<br /></div>
</div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<div style="text-align: justify;">
i.e writing to a volatile field creates a memory fence, which will flush the data held in memory cache, so that<i> anything</i> visible to the thread writing to a volatile field becomes visible to any other thread reading that same field. </div>
</div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<u></u></div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<div style="text-align: justify;">
<br /></div>
</div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<div style="text-align: justify;">
The "anything" in the sentence above might be a non-volatile variable - which will end up being visible to all threads in the same way the volatile which initially triggered the memory fence is. Thus the former piggybacks on the memory flush triggered by the later.</div>
</div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<div style="text-align: justify;">
<br /></div>
</div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<div style="text-align: justify;">
<br /></div>
</div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<div style="text-align: justify;">
Examples of this technique in core jdk classes are hard to come by (ie. I havent found any...) . Possibly a reflection on how fragile that technique is. </div>
</div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<div style="text-align: justify;">
<br /></div>
</div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<u></u></div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<div style="text-align: justify;">
<br /></div>
</div>Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-6012818260427370608.post-16314550751125080042012-06-09T07:02:00.000-07:002012-07-02T11:52:04.329-07:00First steps with GWT Bootstrap<br />
<div style="text-align: justify;">
Gwt-Bootstrap is the port for Gwt of the Twitter Bootstrap framework. <a href="http://twitter.github.com/bootstrap/">Twitter Bootstrap</a> defines a set of javascript and css components which are used to kickstart the development of websites (at least on the client-side).<br />
<br />
The idea is to make it easy to develop a reasonably-good looking website without too much effort. Although of course a truly polished result will require additional customisation work on top of the framework. Twitter bootstrap also provides advanced features out-of-the-box, eg. responsive design (the components size is automatically adjusted function of the resolution of the device they're being drawn on to). </div>
<br />
<br />
<u><b>How to use.</b></u><br />
<br />
The best way to learn is to download the <a href="https://github.com/gwtbootstrap/gwt-bootstrap">Gwt-bootstrap sources from Github</a> and study the examples provided... but to sum up:<br />
<br />
- Grab the <a href="https://github.com/downloads/gwtbootstrap/gwt-bootstrap/gwt-bootstrap-2.0.3.0-SNAPSHOT.jar">GWT-bootstrap jar</a> , version 2.0.3.0-SNAPSHOT at the time of writing. <br />
<br />
- Add the jar to your project build path (menu File->Properties->Java Build Path in Eclipse)<br />
<br />
- In the gwt.xml config file add a reference to the gwt-bootstrap library.<br />
<pre class="prettyprint"> <inherits name ="com.github.gwtbootstrap.Bootstrap"/>
</pre>
<br />
<div class="p1">
<span class="s2">- Assuming you're using UI binder then add the following namespace to the </span><span class="s1"><</span>ui:UiBinder> element.</div>
<pre class="prettyprint">xmlns:b="urn:import:com.github.gwtbootstrap.client.ui"</pre>
<br />
<div class="p1">
- the bootstrap components are now ready to be used:</div>
<div class="p1">
</div>
<pre class="prettyprint"><b:heading size="2">Hello World</b:heading></pre>
<div class="p2">
</div>
<div class="p2">
<br /></div>
<div class="p2" style="text-align: justify;">
<u><b>Downsides.</b></u></div>
<div class="p2" style="text-align: justify;">
<br /></div>
<div class="p2" style="text-align: justify;">
- Gwt-Bootstrap it's still a work in progress. Not all Gwt widgets have been ported yet, eg.CellTable is missing at the time of writing.</div>
<div class="p2" style="text-align: justify;">
<br /></div>
<div class="p2" style="text-align: justify;">
- Most sites built with bootstrap tend to look a little bit similar. Greyish tones, the top navigation bar and the <a href="http://stackoverflow.com/questions/10867137/twitter-bootstrap-what-is-the-meaning-of-hero">"Hero"</a> unit underneath are the usual dead giveaways.</div>
<div class="p2" style="text-align: justify;">
<br /></div>
<div class="p2">
<br /></div>
<div class="p2">
<u><b>Examples.</b></u><br />
<br /></div>
<div class="p2">
<a href="http://builtwithbootstrap.com/">Builtwithbootstrap</a> has an extensive collection of websites leveraging Twitter bootstrap.</div>
<div class="p2">
<br /></div>
<div class="p2">
For Gwt-bootstrap specific websites - the main reference is the <a href="http://gwtbootstrap.github.com/">gwt-bootstrap showcase</a>.<br />
<br />
<br />
<b>Edit 1</b>: my <a href="http://www.javadevjobs.com/">side-project</a> also runs gwt-bootstrap. Check it out.</div>
<div class="p2">
<br />
<b>Edit 2</b>: one of the GWT-bootstrap committer <a href="http://caarlos0.github.com/code/2012/06/26/getting-started-with-gwt-bootstrap" rel="nofollow">copies most of the above post</a>, without attribution. Now - as the saying goes imitation is the most sincere form of flattery but still that's another point in the downsides section - dubious ethics from (some) of the developers on this project.</div>
<div class="p2">
<br /></div>
<br />
<br />
<div class="p1">
<span class="s2"><br /></span></div>
<div class="p1">
<br /></div>Unknownnoreply@blogger.com3tag:blogger.com,1999:blog-6012818260427370608.post-23235706919639014062012-05-25T14:14:00.002-07:002012-06-10T02:15:26.851-07:00Comparing csv files with the linux shell<br />
My heart sinks whenever I witness people resorting to Excel to compare large files. It's kind of ok when the files to be compared are below 10K rows in size... anything bigger than that and the time it takes to select the rows to compare (and the comparison in itself) becomes too much of a frustration.<br />
<br />
The alternative is to use the command line of course.<br />
<br />
To compare two csv files file1.csv and file2.csv, columns to columns, on a Linux operating system.<br />
<br />
step 1. copy all lines containing the string to search from the first input file<br />
<pre class="prettyprint">grep 'searchString' file1.csv > f1.csv
</pre>
<br />
step 2. extract the relevant columns (here columns 3,4 and 5)<br />
<pre class="prettyprint">cut -d',' -f3,4,5 f1.csv > cols_f1.csv
</pre>
<br />
step 3. sort on the 2nd column (for example)<br />
<pre class="prettyprint">sort -k2 -t"," cols_f1.csv > sorted_f1.csv
</pre>
<br />
step 4. remove duplicates<br />
<pre class="prettyprint">uniq sorted_f1.csv > uniq_f1.csv
</pre>
<br />
<br />
<br />
Quite a bit of typing here... and that's only to extract the columns from the first file. Fortunately all of these commands can be piped.<br />
<br />
steps 1,2,3 and 4 for the second file.<br />
<br />
<pre class="prettyprint">grep 'searchString' file2.csv | cut -d',' -f3,4,5 | sort -k2 -t"," | uniq > uniq_f2.csv
</pre>
<br />
<br />
And finally the last step. Show all lines unique to file1, all lines unique to file2 and all lines common to both files, arranged in a 3-columns output<br />
<br />
<pre class="prettyprint">comm uniq_f1.csv uniq_f2.csv
</pre>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-6012818260427370608.post-87933416207742830302012-05-08T11:05:00.001-07:002012-05-08T11:06:17.500-07:00The Guava Joiner - an example<br />
<a href="http://code.google.com/p/guava-libraries">Google Guava</a> ships a nice utility to transform a list of strings into a single string, with invidual elements separated by a separator character.<br />
<br />
<pre class="prettyprint">import com.google.common.base.Joiner;
List<string> words = newArrayList("abc","def","ghj");</string>
System.out.println(Joiner.on(",").join(words));
</pre>
<br />
is a replacement for the rather verbose:<br />
<br />
<pre class="prettyprint">List<string> words = newArrayList("abc","def","ghj");</string>
StringBuilder sb = new StringBuilder();
Iterator iterator = words.iterator();
if (iterator.hasNext()) {
sb.append(iterator.next());
while (iterator.hasNext()) {
sb.append(",");
sb.append(iterator.next());
}
}
System.out.println(sb);
</pre>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-6012818260427370608.post-21619021563200733372012-05-01T13:36:00.000-07:002012-05-02T13:00:06.354-07:00Unsprung! moving away from Spring DI<br />
Advantages of Spring (when used for dependency injection):<br />
<br />
- separates configuration from the code. Thus the wiring of the application can be modified without recompiling, in theory. Not sure how often this happens in practice.<br />
<br />
... and the cons:<br />
<br />
<div style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<u></u>-<span style="font-family: 'Times New Roman'; font-size: 7pt;"> </span>Xml config files are easy to get wrong (no compile time checks obviously)<br />
- Annotations spread through out the code are not terribly visible<u></u><u></u><br />
- Error messages thrown by the framework can be cryptic at times<br />
<br /></div>
There is a simpler alternative. Do away with the Spring container and inject the dependencies manually. All that is needed is a class to inject the dependency, a context which creates the appropriate dependency, and a bit of application code to wire the two together.<br />
<br />
<br />
A DbReader uses a constructor-injected datasource to retrieve database results.<br />
<pre class="prettyprint">class DbReader{
DataSource dataSource;
DbReader (DataSource dataSource){
this.dataSource= dataSource;
}
public Object fetch(){
//use the data source to execute a database query
}</pre>
<br />
A Context holds a reference to a data source (mock or real)<br />
<pre class="prettyprint">class Context {
DataSource dataSource;
static Context liveContext(){
//get production db data source
DataSource dataSource = ...;
return new Context(dataSource);
}
static Context mockContext(){
// get in memory test db data source (or mock)
DataSource dataSource = ...;
return new Context(dataSource);
}
Context(DataSource dataSource){
this.dataSource = dataSource;
}
DataSource getDataSource(){
return dataSource;
}
}
</pre>
<div>
<br />
Project classes inject the datasource associated with a live context in the DbReader constructor.</div>
<br />
<pre class="prettyprint"> public static void main(String args[]){
Context ctx = Context.liveContext();
//fetch data from a prod database
Object result = new DbReader(ctx.getDataSource()).fetch();
}
</pre>
<br />
while integration tests inject a mock datasource from a mock context.:<br />
<br />
<pre class="prettyprint"> @Test
public void Test(){
Context ctx = Context.mockContext();
//fetch data from a mock or in-memory db
Object result = new DbReader(ctx.getDataSource()).fetch();
//assert that result is as expected...
}
</pre>
<br />
Simple, easy to understand (and to debug), compile-time checks in place, no messing around with xml configuration files (or annotations).<br />
<br />
...and it's even simpler with the <a href="http://code.google.com/p/unsprung/">Unsprung project</a> which can help generate the Context class above from a Spring configuration file.Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-6012818260427370608.post-50818598101100124282012-04-22T14:08:00.000-07:002012-05-04T02:49:11.279-07:00Test infrastructure, part 3 - Matching with HamcrestA word on <a href="http://code.google.com/p/hamcrest/">Hamcrest</a>, a library which integrates with JUnit to improve test readability.
<br />
<br />
When checking if two objects obj1 and obj2 are equals, the "classic" JUnit way is to write something like:<br />
<br />
<pre class="prettyprint">import org.junit.Test;
class Test
@Test
public void equalsTest(){
assertEquals(ob1, obj2);
//is obj1 the expected or actual result ?
//not clear without resorting to the javadoc
}
}
</pre>
<br />
with Hamcrest - the test reads (almost) like plain ordinary english and it is easier to see that obj1 is the actual result and obj2 is the expected result:<br />
<br />
<pre class="prettyprint">import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
class Test{
@Test
public void equalsTest(){
//asserts that the actual result is what's expected.
assertThat (obj1, is(obj2));
}
}
</pre>
<br />
<br />
The above illustrates the use of the is() matcher, there are many other matchers to choose from... Just to name a few:
<br />
<br />
<pre class="prettyprint">//hasEntry matcher
Map aMap = new HashMap ();
amap.put("test",123);
assertThat (aMap, hasEntry("test",123);
//greaterThan matcher
assertThat(stuff.size(), greaterThan(0));
//combining is and not matchers
assertThat (stuff.size(), is(not(0)))x
//assert that an array contains certain elements
String [] array1 =....;
assertThat (array1, allOf(hasItemInArray("element1"), hasItemInArray("element2")));
</pre>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-6012818260427370608.post-68008223137089141092012-04-12T14:06:00.001-07:002012-04-19T06:33:42.309-07:00Test infrastructure, part 2 - randomizing dataThe builder created in <a href="http://edglog.blogspot.co.uk/2012/04/building-test-infrastructure-part-1.html">part 1</a> initialises the domain object under test with predefined values:<br />
<br />
id {123} and name {defaultName}
<br />
<br />
<pre class="prettyprint">public class DomainObjectBuilder{
private Integer id="123";
private String name="defaultName";
public DomainObject build(){
return new CustomObject(id,name);
}
....
}
</pre>
<br />
The objects thus constructed by the builder are then used in tests. So far so good. Sometimes though we want these tests to work a little harder, and prove that they can run ok with different input values. The methods below can be used to that end, building on the RandomStringUtils and RandomUtils methods from Apache Commons.<br />
<br />
eg. to randomise a string by adding a 2 digits to the end of it.
<br />
<pre class="prettyprint">public String randomizedString(String aString){
return aString+RandomStringUtils.randomAlphaNumeric(2);
}
</pre>
and the builder becomes (assuming the randomizedString method is statically imported)
<br />
<pre class="prettyprint">public class DomainObjectBuilder{
private Integer id=randomizedString("123");
private String name=randomizedString("defaultName");
public DomainObject build(){
return new CustomObject(id,name);
}
....
}
</pre>
Each invocation of the DomainOBjectBuilder.build() method will now return domain objects with slightly different values.
Of course it's not only strings which can be randomized. The same principles applies to enums:
<br />
<pre class="prettyprint">public static <T extends Enum> T randomizedEnum (class <T> enumClass){
T[] enumConstants = enumClass.getEnumConstants();
return enumConstants[RandomUtils.nextInt(enumConstants.length);
}
</pre>
... and to lists.
<br />
<pre class="prettyprint">public static <T> T randomElementFromList(List<t> aList){
return aList.get(RandomUtils.nextInt(aList.size()));
}
</t></pre>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-6012818260427370608.post-6948562668995821252012-04-07T02:41:00.000-07:002012-04-19T06:33:04.989-07:00Test infrastructure, part 1 - building the buildersThe basic brick of a test infrastructure is the ability to easily instantiate and set properties on the domain object under test.
This can be achieved with a builder object, as per below. This builder exposes a fluent interface (in the chaining of methods withId and withName) to improve readibility.
<br />
<br />
<br />
Given a domain object such as<br />
<br />
<pre class="prettyprint">public class DomainObject{
public DomainObject (Integer id, String name){
this.id = id;
this.name = name;
}
public Object doSomething(){
...
}
}
</pre>
<br />
then the associate builder will be:<br />
<pre class="prettyprint">public class DomainObjectBuilder{
private Integer id="123";
private String name="defaultName";
public DomainObject build(){
return new CustomObject(id,name);
}
public DomainObjectBuilder withId(Integer anId){
this.id = anId;
return this;
}
public DomainObjectBuilder withName(String name){
this.name = name;
return name;
}
}
</pre>
and a test for a DomainObject will look like:
<br />
<br />
<pre class="prettyprint">DomainObject anObject = new DomainObjectBuilder()
.withId("345").withName("someTest").build();
assertThat (anObject.doSomething, is(anExpectedResult));
</pre>
<br />
An alternative approach would be to do without a builder and simply add setters on the domain object, setters which would be invoked during the tests. The major drawback of this technique is that adding setters breaks immutability.Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-6012818260427370608.post-19385298869079133072012-01-07T09:20:00.000-08:002012-04-12T14:12:39.828-07:00Why I (finally) moved from Eclipse to Intellij<br />
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<br />
I had to keep both Eclipse and Intellij running side-by-side for a while, because I could not peel away from Eclipse, my editor of choice for years. A few days later and Intellij has eclipsed Eclipse (pardon the pun). Here' s a few reasons why:</div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<br /></div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<br /></div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
- I't s easy to switch between implementation and test (CTRL+shift+T) in Intellij, there's no equivalent in Eclipse.</div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<br /></div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
- When searching for the usages of a variable/method/class Intellij scopes the search by test files, production files (or both). In Eclipse you would have to manually specify the full path to search in each case.</div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<br /></div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
- In general Intellij is pretty smart when it comes to refactoring. for instance when renaming a class attribute the name of the getter method for that class attribute will be renamed accordingly. </div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<br />
- Smart code completion: Intellij will make much better suggestions as to what expression type is expected based on the context than Eclipse.<br />
<br />
<div class="MsoNormal">
- automatically resolution of import static.</div>
<div class="MsoNormal">
<u></u></div>
<div class="MsoNormal">
</div>
<div class="MsoNormal">
<u></u></div>
<div class="MsoNormal">
- Paste from history<u></u><u></u></div>
<div class="MsoNormal">
<br /></div>
<div class="MsoNormal">
- Use regex in search<br />
<br />
- On the downside Intellij is a tad slower than Eclipse and tends to lock up for 30 secs or so once or twice a day.</div>
</div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<br /></div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
So overall there's no major functionality or killer feature offered by Intellij that Eclipse cannot replicate. But the difference is in the many little details which are often better thought out in Intellij, resulting in a better experience (and increased productivity).<br />
<br />
<br /></div>Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-6012818260427370608.post-80599438820023526042012-01-05T13:26:00.000-08:002012-04-02T12:43:53.356-07:00Regexp use for text transformation with Intellij<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
Given a snippet of code such as:</div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<b style="text-align: center;">put("item123", x);</b><br />
<b style="text-align: center;">put("item456", x);</b><br />
<b style="text-align: center;">....</b><br />
<b style="text-align: center;">put("item888", x);</b></div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small; text-align: center;">
<b><br /></b><br />
<b> </b></div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
To retrieve the content in between quotes:<u></u><u></u></div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<b>item123</b></div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<b>item456</b></div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<b>...</b></div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<b>item888</b></div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<b><br /></b></div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<br /></div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
Then this can be achieved using the in-place find and replace functionality offered by Intellij.<u></u></div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
(obviously a manual edit would also work, but might not be as efficient <u></u><u></u>if the block of code is repeated 1000 times).</div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<br />
<br /></div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
1. search for the regex <u></u><b>put\("</b><br />
<br />
<br />
2. replace the selection with an empty field, this yields:</div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<br />
<div class="MsoNormal">
<b style="text-align: center;">item123", x);</b><br />
<b style="text-align: center;">item456", x);</b><br />
<b style="text-align: center;">....</b><br />
<b style="text-align: center;">item888", x);</b></div>
<div class="MsoNormal" style="text-align: center;">
</div>
</div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<br />
<br /></div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
3. search for the <u></u><u></u>regex <b>\".+ </b> (select everything extending from the first quote to the end of the line)<br />
<br />
<br />
4.replace the selection with an empty string yields: </div>
<div class="MsoNormal" style="background-color: rgba(255, 255, 255, 0.917969); font-family: Arial; font-size: small;">
<br />
<b style="text-align: center;">item123</b><br />
<b style="text-align: center;">item456</b><br />
<b style="text-align: center;">....</b><br />
<b style="text-align: center;">item888</b><br />
</div>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-6012818260427370608.post-36460235681951192722011-09-13T12:56:00.000-07:002011-09-13T12:56:31.498-07:00GC Tuning: NewRatioWhen it comes to garbage collection tuning the first setting to be adjusted is often the heap size. This is not always the optimal choice though. If only because a bigger heap size will tend to mechanically lengthen the duration of GC pauses.<br />
<br />
Instead of increasing the heap size it can pay to increase the size of the young generation relative to the old. That's where the NewRatio setting (i.e ratio of the old gen space to the young gen space) comes in.<br />
<br />
The screenshots below illustrate how GC activity differs when an application producing short-lived objects at a high frequency runs with NewRatio=2 and when it runs with NewRatio=1. Collections in the old gen disappear provided there's enough size in the young space to accomodate all the short lived objects.<br />
<br />
<br />
NewRatio =2 (default setting on Windows 64 bits).<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgeSZsuo39bIzirGhzH0U0vMecNdpa8GNsxmyzOWBqjifetsJlXkgMRUouPRUF-Lgn4U3PEt3sBewFeIZ30uUeaRLHz-ecd7PtzSeJZxzNjcF3OqNDEPvdcs9G4zq-A17FBkZyj77BFq-s/s1600/newratio22_2.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="382" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgeSZsuo39bIzirGhzH0U0vMecNdpa8GNsxmyzOWBqjifetsJlXkgMRUouPRUF-Lgn4U3PEt3sBewFeIZ30uUeaRLHz-ecd7PtzSeJZxzNjcF3OqNDEPvdcs9G4zq-A17FBkZyj77BFq-s/s640/newratio22_2.PNG" width="640" /></a></div>
<br />
<br />
<br />
<br />
NewRatio =1<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhUmM5obCt_Ue4fzi8INy5cgwR1WHsK9gLipPgG_h4tUcVbE6ElrskKRXEz3nLZdvxFmSNaz-blz1GZX_v2DLPqh8ttN9VyUtee4aSM87FzVT-rZSl1GHJtc7uUSQvhmGKvA4wsWs69swU/s1600/newratio11_1.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="377" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhUmM5obCt_Ue4fzi8INy5cgwR1WHsK9gLipPgG_h4tUcVbE6ElrskKRXEz3nLZdvxFmSNaz-blz1GZX_v2DLPqh8ttN9VyUtee4aSM87FzVT-rZSl1GHJtc7uUSQvhmGKvA4wsWs69swU/s640/newratio11_1.PNG" width="640" /></a></div>
<br />Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-6012818260427370608.post-67097056638593171732011-09-01T14:30:00.000-07:002012-01-05T11:53:14.437-08:00How to measure swap usage on Linux<div class="separator" style="clear: both; text-align: center;"></div><br />
On Linux (since version 2.6.14):<br />
<br />
1- find out the pid of a process <br />
2- navigate to /proc/<i>pid</i><br />
3- edit the smaps file, and sum the swap value for each of the process mappings.<br />
<br />
... or use the script found <a href="http://northernmost.org/blog/find-out-what-is-using-your-swap/">here</a> to get the swap usage for each running process. The display below has been obtained by running that script on a Ubuntu guest OS (using Virtualbox on Windows) with base memory set at 128M. <br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg1kLwPXXPshNpWfcm77NhzKiSrmAIWd56753fDOZhJPMadDjq0a28Bet4dweZDWAv_l436NB1WIj8Eh_NoN1Cwm8xD-t7HPY8dFnJee3Y2Ldd9kqcan73ISWnPveLGuBKNQFwq84bxbyw/s1600/capture_smaps.PNG" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" height="236" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg1kLwPXXPshNpWfcm77NhzKiSrmAIWd56753fDOZhJPMadDjq0a28Bet4dweZDWAv_l436NB1WIj8Eh_NoN1Cwm8xD-t7HPY8dFnJee3Y2Ldd9kqcan73ISWnPveLGuBKNQFwq84bxbyw/s320/capture_smaps.PNG" width="320" /></a></div><br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
All swaps values in kilobytes.Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-6012818260427370608.post-35935103071486739392011-05-10T12:31:00.001-07:002012-01-05T12:22:02.604-08:00How to extract specific files from an RPM (Linux)As an alternative to installing the entirety of an RPM when you're only interested into some of the files it contains...<br />
<br />
<span class="Apple-style-span" style="border-collapse: collapse; font-family: arial, sans-serif; font-size: 13px;"><i>rpm2cpio myrpm | cpio -idv *myfilename*</i></span><span class="Apple-style-span" style="border-collapse: collapse; font-family: arial, sans-serif; font-size: 13px;"><br />
</span><span class="Apple-style-span" style="border-collapse: collapse; font-family: arial, sans-serif; font-size: 13px;"></span><span class="Apple-style-span" style="border-collapse: collapse; font-family: arial, sans-serif; font-size: 13px;"><br />
</span><br />
<span class="Apple-style-span" style="border-collapse: collapse; font-family: arial, sans-serif; font-size: 13px;"><i>rpm2cpio</i> converts the rpm "<i>myrpm</i>" into a<i> cpio</i> archive, which is then passed a</span><span class="Apple-style-span" style="border-collapse: collapse; font-family: arial, sans-serif; font-size: 13px;">s a parameter of the cpio command, with arguments:</span><br />
<span class="Apple-style-span" style="border-collapse: collapse; font-family: arial, sans-serif; font-size: 13px;"></span><span class="Apple-style-span" style="border-collapse: collapse; font-family: arial, sans-serif; font-size: 13px;"><br />
</span><i><span class="Apple-style-span" style="border-collapse: collapse; font-family: arial, sans-serif; font-size: 13px;">-i : extracts</span><span class="Apple-style-span" style="border-collapse: collapse; font-family: arial, sans-serif; font-size: 13px;"><br />
</span><span class="Apple-style-span" style="border-collapse: collapse; font-family: arial, sans-serif; font-size: 13px;">-d : creates directories as needed</span><span class="Apple-style-span" style="border-collapse: collapse; font-family: arial, sans-serif; font-size: 13px;"><br />
</span><span class="Apple-style-span" style="border-collapse: collapse; font-family: arial, sans-serif; font-size: 13px;">-v : verbose</span></i><br />
<i><span class="Apple-style-span" style="border-collapse: collapse; font-family: arial, sans-serif; font-size: 13px;"><br />
</span></i><br />
<span class="Apple-style-span" style="border-collapse: collapse; font-family: arial, sans-serif; font-size: 13px;"><span class="Apple-style-span" style="border-collapse: collapse; font-family: arial, sans-serif; font-size: 13px;">Only the files with names matching "<i>myfilename</i>" will be extracted.</span></span>Unknownnoreply@blogger.com0