Tuesday, May 8, 2012

JSF 2 + Twitter Bootstrap

I really like JSF 2, especially when integrated in the whole J2EE stack, but component libraries like RichFaces or PrimeFaces can be somewhat heavy on the front end. 

So, I decided to try out Twitter's Bootstrap UI library with just plain JSF 2, without any component libraries. For testing purposes, I modified JBoss 7 skeleton maven archetype project to use Twitter Bootstrap, and the two seem to be getting along nicely together. 

This could be a nice alternative for building lightweight JSF 2 web applications, especially if you would build a good base of common composite components.

One of the advantages of Twitter Bootstrap is that it comes pre-optimized for mobile devices:

You can check out the source code for this on my GitHub: https://github.com/rkovacevic/JSFBootstrap

Wednesday, January 18, 2012

Layout manager for iOS

I made a simple layout manager for iOS (tested on iPhone and iPad 4.0+). It lets you easily arrange views in horizontal or vertical stack, or in a grid. Check it out on my GitHub:

Monday, November 28, 2011

Beware: NSBundle's pathForResource won't fail fast

One of the base ideas of lean software development is the concept of failing fast. This means that once a software element has determined that it cannot do it's job correctly, given the input it has, it should fail immediately and loudly. This will force the user to check the input and fix his mistake.

Apple's Foundation.framework's NSBundle class has a nice example of how to do completely ignore this concept. For example, consider this code:
    NSLog(@"Path with real file name: %@", [[NSBundle mainBundle] pathForResource:@"test" ofType:@"png"]);
    NSLog(@"Path with nil file name: %@", [[NSBundle mainBundle] pathForResource:nil ofType:@"png"]);
What do you except it to print in the log, assuming the bundle contains the file 'test.png'? Nil string? Some kind of exception or error?

Actually, it prints this:
2011-11-28 10:32:42.733 Test[666:40b] Path with real file name: /Users/rkovacevic/Library/Application Support/iPhone Simulator/5.0/Applications/B12B5FC0-6DDA-4908-AB05-1B07A74341E7/Test.app/test.png
2011-11-28 10:32:42.735 Test[666:40b] Path with nil file name: /Users/rkovacevic/Library/Application Support/iPhone Simulator/5.0/Applications/B12B5FC0-6DDA-4908-AB05-1B07A74341E7/Test.app/test.png
If you pass a 'nil' string to 'pathForResource' it will just find the first file of the given type, and pass it's path to you. Beware of this, or you will spend hours looking for a bug, assuming that it can't possibly be that the NSString you passed to 'pathForResource' is 'nil', because it wouldn't just make up a path and return it to you. Well, actually, it would, and it does. With Apple - assume nothing.

Friday, October 21, 2011

Setting up a VPN PPTP client on Ubuntu 10.04

Today I needed an external IP for a server deep inside corporate network, so the simplest solution for me was to purchase a cheap VPN service. I used StrongVPN, since it was the first I could find. This is a quick and dirty guide how to get it up and running on Ubuntu 10.04 server:

Install the PPTP client:
sudo apt-get install pptp-linux
Add a line like this to /etc/ppp/chap-secrets file:
Create a file /etc/ppp/peers/NAME_OF_YOUR_CONNECTION:
pty "pptp VPN_SERVER_URL --nolaunchpppd"
remotename PPTP
file /etc/ppp/options.pptp
Create a script /etc/ppp/ip-up.d/route-traffic:
route add -net dev ppp0
 Make the script executable:
sudo chmod +x /etc/ppp/ip-up.d/route-traffic
 Establish the connection:
sudo /usr/sbin/pppd call NAME_OF_YOUR_CONNECTION
 That should be it. Check /var/log/messages to see if everything went OK, and if you have curl installed, run this to see if you got your new external IP:
curl ifconfig.me

Sunday, February 20, 2011

Unit testing EJBs with Mockito

There's a lot of hype over in-container EJB testing frameworks, like Arquillian, that JBoss is trying to push. However, as even Arquillian's front page will tell you, this is integration testing, not unit testing. For actual unit tests, a module should be detached from everything else, especially the container.

Fortunately, thanks to EJBs being just plain Java objects with annotations, they can be unit tested just like any other object, by mocking the dependencies.

I created a small demo application to show how to test EJBs with Mockito, a mocking framework that makes mocking things like an EntityManager much easier. The application has a servlet, that when invoked, records the visit time to the database and returns a list of all visits in the HTTP response. Recording and reading the list of visits is handled by this EJB:

public class VisitsBean {

 EntityManager entityManager;
 public void recordVisit() {
  Visit visit = new Visit();
  visit.setVisitTime(new Date());
 public List getVisits() {
  return entityManager.createNamedQuery(Visit.ALL).getResultList();

To test this EJB, we obviously need to create an EntityManager and test to see if correct methods are called on it, with correct parameters. This is how I did it with JUnit4 and Mockito:

public class VisitsBeanTest {
 private VisitsBean visitsBean = new VisitsBean();
 public void injectMockEntityManager() {
  EntityManager entityManager = mock(EntityManager.class);
  visitsBean.entityManager = entityManager;
 public void testRecordVisit() {
  ArgumentCaptor persistedVisit = ArgumentCaptor.forClass(Visit.class);
  verify(visitsBean.entityManager, atLeastOnce())
  long visitTimeInMillis = persistedVisit.getValue().getVisitTime().getTime();
  assertTrue("Visit time not set correctly", 
    System.currentTimeMillis() - visitTimeInMillis < TimeUnit.SECONDS.toMillis(1));

 public void testGetVisits() {
  List visitList = VisitRecorderTestUtil.createTestVisitList();
  Query mockQuery = getQueryThatReturnsList(visitList);
  assertEquals(visitList, visitsBean.getVisits());

 private Query getQueryThatReturnsList(List list) {
  Query mockQuery = mock(Query.class);
  return mockQuery;

Before every test, we call the injectMockEntityManager() method, that uses Mockito to create a mock EntityManager and injects it into the EJB.

The testRecordVisit() method checks that perisit() is called on the EntityManager, with correct time set for the Visit, and testGetVisits() will check that correct named query is invoked to retrieve the list of Visits from the database and that results are returned.

As we can see here, we achieved 100% test coverage, according to EclEmma:

However, there are some problems with this approach:
  • test are pretty brittle, if we would, for example, change the getVisits() method to use Criteria queries, instead of invoking the named query,  the test would break
  • we are not testing things like transaction handling, but it could be argued that this is the container's responsebillity, so we're not supposed to test them
  • you really can't test entity beans this way, without a JPA provider, you can only test getters, setters and hashCode - equals contract
With that said, I do think that this is a good technique for crating fast and autonomous EJB unit tests. I'll try to use it in a more real world project and report how it turns out.

You can check out the full code for the demo project on my GitHub:
(I tested it on JBoss AS 6.0, but you can probably deploy it to Glassfish too, without much problems)

Tuesday, February 8, 2011

Easy singletons in Java

Singleton is a design pattern used when only one instance of a given class can exist in an application. Although some argue it to be an anti-pattern, it remains one of the most used idioms, so I'm not going to go into if you should use it or not, rather I'll try to show you how to use it properly, if you do decide to use it.

First, here are some things we want in any singleton:
  • It should not be possible to create more than one instance of it per application
  • It should be thread safe
  • Since it will be used all over the application, getting the singleton instance should be as fast as possible
Ok, so how do we do it? Most people would probably start with something like this:
// Wrong way to do a singleton
public class NaiveSingleton {

    private static NaiveSingleton instance;
    private NaiveSingleton() {
        // Initialize
    public static NaiveSingleton getInstance() {
        if (instance == null) {
            instance = new NaiveSingleton();
        return instance;
There are more than few problems with this singleton. Most obvious problem is that the getInstance method is not synchronized, so if two threads enter it around the same time, they could get two different instances, thus breaking our only-one-instance-per-application rule. If we synchronize getInstance, we run into a performance problem, now threads have to wait for each other. But even if we get around this problem with some clever hacks, we still need to worry about overriding the clone method, to prevent another instance to be created that way, and all kind of other issues.

Fortunately, there is a much easier and more robust solution to crate a singleton. Ready? Here it comes:
public enum ProperSingleton {
    public static ProperSingleton getInstance() {
        return ProperSingleton.INSTANCE;
Since enum constants are guaranteed to have only one instance by the JVM, we don't need to worry about anything, it's all handled for us, and in an optimized way.

This solution comes from Joshua Bloch's excellent book "Effective Java". It's one of the most elegant and beautiful idioms for a common Java problem that I've ever seen. When you see it once, there is really no way you will ever write another singleton any other way.

Friday, February 4, 2011

JBoss webinar on Maven

There's a bunch of JBoss developers webinars on Vimeo. You can check them out here:

Unfortunately, most of them have horrible, barely audible sound. There's some really interesting stuff there, so it's a shame JBoss couldn't invest in a decent microphone.

One of the usable ones is the one about setting up a Nexus Maven repository. It starts with a general introduction on repository handling in Maven and then gives some pretty useful tips that they learned in JBoss's recent switch to Nexus.

Maven Repository Magic from JBoss Developer on Vimeo.