Local EJBs and Spring Framework’s @EJB annotation

July 23, 2008 – 9:13 am

Lately I have been working with Glassfish v2 and local EJB3. Everything worked perfectly until I have decided to leverage the Spring Framework for my web component.

Glassfish only supports @EJB annotation on limited types of classes, namely Servlets and other EJBs. Injection in POJOs are not supported:

“Injection is not supported for POJO classes, so the POJO needs to look up the local EJB reference within the private namespace (java:comp/env) of the component within whose scope it is executing”. Source: Glassfish EJB FAQ / POJOLocalEJB

So when you try to use @EJB nothing happens, you just get the dreadful NullPointerException. But according to documentation Spring supports EJBs and @EJB annotiation via CommonAnnotationBeanPostProcessor.

Finally, this post-processor also supports the EJB 3 EJB annotation, analogous to Resource as well, with the capability to specify both a local bean name and a global JNDI name for fallback retrieval. The target beans can be plain POJOs as well as EJB 3 Session Beans in this case.

This is my setup. Let’s start with Java classes:

// Local EJB
@Stateless
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
public class ForumMapperBean implements ForumMapper {
...

// Spring's Controller
public class ForumListController extends AbstractController {

    @EJB
    ForumMapper forumMapper;

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest req, ...) throws Exception {
    ...

And now application context bean needed to get @EJB going:

    

Unfortunately this setup fails on deployment due to BeanCreationException: “Error creating bean with name ‘forumListController’: Injection of resource fields failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [pl.aie.mapper.ForumMapper] is defined (…).

But why on earth is Spring trying to inject it’s bean on EJB annotation? I don’t get it. Well, ok. How do I stop it from doing so? Quick glance at the documentation on CommonAnnotationBeanPostProcessor and everything is getting clearer. Docs say that for direct JNDI access, resolving resource names as JNDI resource references within the Java EE application’s “java:comp/env/” namespace one has to use alwaysUseJndiLookup property:

The central element is the Resource annotation for annotation-driven injection of named beans, by default from the containing Spring BeanFactory, with only mappedName references resolved in JNDI. The “alwaysUseJndiLookup” flag enforces JNDI lookups equivalent to standard Java EE 5 resource injection for name references and default names as well. The target beans can be simple POJOs, with no special requirements other than the type having to match.

Okay, let’s check it out:

    
        <property name=”alwaysUseJndiLookup” value=”true” />
    

Still no good, we now get “No bean named ‘forumMapper’ is defined: not found in JNDI environment”. Okay, so it gets the wrong interface name. Let’s try forcing it to use correct one:

// Spring's Controller
public class ForumListController extends AbstractController {

    @EJB(name = "ForumMapper")
    ForumMapper forumMapper;
    ...

And voila! Everything works as it should now

Tags: , , ,

Next response to “Where did all the PHP programmers go?”

June 6, 2008 – 5:33 pm

Yesterday I have read a very interesting article touching the subject of hiring PHP programmers with a conclusion that most of the people complain about the interviewing process rather than answering questions. It’s a very interesting read, so take a moment and get back to me when you have finished - Where did all the PHP programmers go?. Now, those are very good points but I have to admit that I too have been interviewed on paper too many times. And it has some major drawbacks:

  1. Writing on paper is different than writing on screen. When it comes to programming, you can’t prepare interfaces upfront and fill in the details later just because you can’t insert new text between already written lines. And that’s a thing you do constantly while writing code. Of course it’s very easy to give your potential employees more familiar environment - you can give them at least a basic text editor (like notepad) on your laptop. It will really help (my own experience speaking)
  2. PHP is a messy language. It’s interfaces are very inconsistent so it’s very hard to memorize it all. Good IDEs (not a Dreamweaver) negate this effect. You can give your interviewees an access to the manual. When a programmer writes code he constantly uses the manual when he needs it. Why do you want to test his memory and not his skills?
  3. Programmers are used to look at a code that has syntax highlighting turned on. Looking at a plain black text is just a senseless handicap - you can’t see things you see everyday in a snap. You have to actually browse and read everything every time you have to look IN THE CODE for something you wrote earlier.
  4. PHP veterans use libraries. Standard public ones as well as their own. They seldom work with pure php function calls nowadays. Especially when it comes to database calls and some obscure mysql functions (ie. you don’t have to know the difference between mysql_fetch_assoc and mysql_fetch_array from the top of your head!).
  5. You don’t need to know sorting algorithms by heart these days - all decent languages come with sort functions already implemented in the language. What you need to know is what sort method to use in which circumstances. If quicker sort is harder to develop you use the easiest one (like easiest built in function in the language). Premature optimization is a root of all evil they say. You use better sorting solution when the easiest one is not performing well. But this is after you test the almost finished software.
  6. And last - experienced programmers will be much more handicapped by all this than novice programmers. That’s because novice programmers are learning on the very low language level (think function calls) while seasoned programmers are thinking globally on much higher level. They generally think OOP and interfaces which are de facto language independent. Not to mention they are used to their working conditions stronger and then even changing color of hightlighted variables can result in slower thinking.

So, the bottom line is - first make sure what you want to accomplish and then make your tests accordingly. Most of the interviewers are testing memory instead of programming skills. And when they do test skills they test some basic stuff rather than things which will be required on the job.

UPDATE: If you’re interested in a more practical interviewing process you may want to read Nick Jenkins’ reply to the same post here - http://blog.nickj.org/2008/06/05/response-to-where-did-all-the-php-programmers-go/.

See you next time.

Blog has moved

June 6, 2008 – 4:59 pm

This blog has recently moved to it’s new location - http://blog.aie.pl. You may have received duplicate feed items for which I’m sorry - but this also means you don’t have to update your feed bookmarks in your rss readers. I think it’s a good tradeoff.

Thanks for reading!

Tags:

Fluent interfaces and code readability

March 30, 2008 – 1:28 pm

Fluent interfaces. Sigh. They help sometimes, they really do. In fact I don’t have anything against the idea, it’s the actual use that makes me uncomfortable.

Let’s start with the example first. The nicer one, that is. And to make my case stronger, I will use an example taken directly out of the blog of Mike Naberezny - Fluent Interfaces in PHP. Mike’s a renown PHP authority, so it should make you think:

    $customer->newOrder()
        ->with(6, 'TAL')
        ->with(3, 'LGV')
        ->with(5, 'HPK')->skippable()
        ->priorityRush();

It’s clean and pretty and sexy and all that, all right. You may be even tempted to say it’s more readable, but is that so in reality? I don’t think so. The problem here is you don’t know if skippable() method returns an order object or not. It may return something radically different like a totally different object or, even worse, a boolean. Furthermore, you can’t know what type of object the priorityRush() method is executed on. And THAT makes the code much harder to read.

You still don’t believe me? Take a look at the Mike’s blog and read a comment by FGM (4 Nov 06). Maybe that will open your eyes.

When one writes software only for himself it pays to type less. Some of the time, but still. When you know your code by heart and when you maintain the software yourself then there is a fat chance you will not be hindered by this. But in a corporate environment one writes software that is mainly read. By many different people. You write the software and then there are bug fixes, additional features, upgrades, etc. A lot of people have to browse your code in order to get a grasp of what the code in fact does. And then they modify. I assure you this is far more easier to comprehend later on:

        $order = $customer->newOrder();
        $order->with(6, 'TAL');
        $order->with(3, 'LGV');
        $order->with(5, 'HPK')->skippable();
        $order->priorityRush();

See? I have even left one use of fluent interface. It’s pretty clear that skippable() is executed on the object with() method returns. And it won’t make anyone browse through the “Order” source to understand. I agree, it is a little more to type and you have to sacrifice a couple of CPU cycles. But it pays when the code is forgotten and has to be modified later on.

And now the horrific use in my eyes:

        $view = new Zend_View();
        Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer')->setView($view);
        Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer')->view->doctype('XHTML1_TRANSITIONAL');

The major problem here is that the most important stuff is far on the right, so far you can loose focus before you get there (and even have to scroll it on my blog). Basically? It’s a readability hell. Not to mention it probably takes a lot more to type (216 key strikes). Oh, now you though Copy & Paste! Please, don’t get me started on that :)

Isn’t this way more readable?

        $view = new Zend_View();
        $view->doctype('XHTML1_TRANSITIONAL');

        $renderer = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
        $renderer->setView($view);

Well? You exactly see what’s happening now and important stuff is taken to the front so it’s easier to spot. The line is shorter so you will get the meaning quicker. Oh, and it’s 169 key strikes with additional white-space making it even better.

Don’t rape the fluent interfaces from now on, please.

Whitespace and coding standards

March 18, 2008 – 9:36 pm

Today I would like to touch a subject which is often trivialized by many software craftsmen - use of white space and coding standards compliance.

I work in an environment where two (or more) subcontractors often work on the same project, many times concurrently; where coding standards and clean coding style really start to shine. Big time. And yet these companies don’t seem to see the benefit in the standards — I have to do fine grained code reviews on every delivered change because if I don’t, I get something like this:

    String configSql = "{ ? = call x_int_bit_pkg.gettpnum (?)}";
    CallableStatement cstmt = con.prepareCall(configSql);
    cstmt.registerOutParameter(1, OracleTypes.CURSOR);
    cstmt.setInt(2, sp.getObjid());
    cstmt.execute();
    ResultSet rs = ((OracleCallableStatement) cstmt).getCursor(1);
    if (rs.next()) {
        result = new CPartAttr();
        result.setXValue(rs.getString("x_value"));
    }
    rs.close();
    cstmt.close();
    return result;

What makes me wonder is that those subcontractors are big and world-class recognized companies. I’m starting to suspect it’s their companies’ policies to make software in quick-and-dirty mode and forgo all good programming habits. All in all, every modification costs more and more with such approach, since the code starts to look like a big mess after some time.

But this is only my paranoia speaking.

Why can’t they see that good practices, like placing additional white space, make code more readable? And as such easier to work with after some time. And coding standards? When there are groups of people working on the same code base it’s a lot easier and faster to get a big picture when you name your variables, methods or objects in the same way:

    String configSql = "{ ? = call x_int_bit_pkg.gettpnum (?)}";
    CallableStatement cstmt = con.prepareCall(configSql);

    cstmt.registerOutParameter(1, OracleTypes.CURSOR);
    cstmt.setInt(2, sitePart.getId());

    cstmt.execute();

    ResultSet rs = ((OracleCallableStatement) cstmt).getCursor(1);

    if (rs.next()) {
        partAttribute = new ClarifyPartAttribute();
        partAttribute.setValue(rs.getString("x_value"));
    }

    rs.close();
    cstmt.close();

    return partAttribute;

Isn’t this far more readable? Take a look at the return statement of the first and second code snippet. Which is easier to grasp? I thought so.

When you code in accordance to standards you’re making next persons life easier. And probably the most important thing to remember is that this next person could be you.

Furthermore, you have a better overall code quality and delivery times which both make the customer happier. But this, in itself, is another story…

Spring’s PropertyPlaceholderConfigurer as a PropertiesFactoryBean

March 6, 2008 – 7:45 pm

For a couple of past days I have been struggling with a problem with Spring’s PropertyPlaceholderConfigurer. I coudn’t get it to work in a way PropertiesFactoryBean is working. I wanted it to act in a similar way:

    <bean id="properties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:MaNaWa.properties" />
    </bean>

    <bean id="config" class="com.netia.manawa.Config">
        <constructor-arg ref="properties" />
    </bean>

Unfortunately this code does not work. Everything you get is just an exception saying PropertyPlaceholderConfigurer can’t be cast to java.util.Properties. So, for a good deal of time I have been doing something ugly:

    <bean id="properties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="location" value="classpath:MaNaWa.properties" />
    </bean>  

    <context:property-placeholder location="classpath:MaNaWa.properties"/>  

    <bean id="config" class="com.netia.manawa.Config">
        <constructor-arg ref="properties" />
    </bean>

Which, of course, resulted in a properties file being loaded two times.

Then, while I was sleeping, came a solution. I dreamed I could use a PropertiesFactoryBean in a PropertyPlaceholderConfigurer and guess what… it works. Just like that. See for yourselves:

    <bean id="properties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="location" value="classpath:MaNaWa.properties" />
    </bean>

    <bean id="placeholder"  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="properties" ref="properties" />
    </bean>

    <bean id="config" class="com.netia.manawa.Config">
        <constructor-arg ref="properties" />
    </bean>

Gee. Now, to think about code while sleeping? That’s geeky, isn’t it? Well, I guess I have to live with that :)

Let’s get started with this thingy

March 4, 2008 – 9:36 pm

Well, this is a strange feeling. I have always been opposed to the idea of blogging and yet here we are. On my own, more-or-less personal, blog.

I don’t really know why I have decided to open one now or if I will keep it alive for a longer period of time. But the idea is definitely there and I’ll do my best to live up to my own expectations. One thing is sure - it will be a strictly professional blog. I mean, it will or should be strictly related to programing or development in general. Well, maybe with an occasional posting concerning some current work events that have a stronger influence on me or on how I see the world.

So, welcome, my dearest reader. I can assure you you’re special - there’s a strong possibility you’re the only person (besides me) that is looking at these words :)