How To Make A Custom Window Title With Android

When you start making Android apps that ship to clients and paying customers, chances are you will find the default Android window title lacking. The default title displays the name of your app on top of a very neutral-looking grey background.

The default Android window title

While OK for experimental and side projects the stock grey colour will likely not mix well with the colour theme of your app, especially if you are using colours other than black, white and grey.

Here is how you make a custom window title. First you need to create a layout XML file and put in the res/layout directory of your Android project:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""

  		android:text="My Custom Title Here"

Now you have to tell Android to apply the custom title layout that you have created. In order to do that you need to request that your activity be given the FEATURE_CUSTOM_TITLE window feature:

    public void onCreate(Bundle savedInstanceState) {

        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_bar_example);

Make sure that the call to setContentView() occurs after requestWindowFeature() and before setFetureInt()

You would think that this is enough, however when you run the code you will see that there is still a remnant of the old stock background still lurking underneath our fresh new custom title. Still no go!

Custom Android title step 1: pesky grey still remains

In order to get rid of the last remaining traces of the stock grey we need to resort to a bit of Android wizzardy:

int titleContainerId = (Integer) Class.forName(

ViewGroup vg = ((ViewGroup) getWindow().findViewById(titleContainerId));
if(vg != null){
	vg.setPadding(0, 0, 0, 0);

The trick here is to get a runtime reference to the title_container in a way that doesn’t break between Android releases and to set its padding to 0. And here is the final result:

android, title

Your custom Android title is now complete

And from here you can go ahead and add whatever other images and controls you need by adding them by adding them to the layout file.


Told you so: RIM, Apple, Google Tied In Smartphone Race

Back in mid-2008 the smartphone race was rapidly heating up. The App Store had just come out and experts were trying to predict who is going to be the winner in the space. While journalists, bloggers and pundits were pondering whether the iPhone will be the one to win it all,  I stuck my head out and called a “no winner” scenario.

Recent research from the Nielsen Group suggests that we currently have exactly that, with all 3 major smartphone platforms – RIM, Apple and Google, tied for 27% market share or a little less than 1/3 of the total market.  Here is the link to the original post.

It should be noted that the data in the article is from the US and excludes the remaining 6+ billion people in the world, many of which don’t have the same buying patterns or consumer preferences as their American counterparts.

Still, it is one tied race with no clear dominant winner. And it will likely stay that way for a while, especially with Microsoft joining in the race (never underestimate what the giant from Redmond can bring to the table) and Nokia taking the plunge.

They Should Rename BusinessWeek To GovernmentWeek

So I am reading along the latest issue of BusinessWeek and I can’t help but notice that at the heart of of every second article sits the government in some form, be it through action or inaction, past, present or rumoured to be in the works.

“The Side Effects Of Finance Reform” details the side-effects of a yet-to-be-made clear drive by “lawmakers and regulators” to reform the world of finance. How? When? Nobody really knows, but apparently rumours abound, with each plan having more profound implications than the other.

A three page article deals with the U.S. Chamber of Commerce fight against a feared carbon bill, with a lobbyist-by-lobbyist map of the subject matter.

“Washington Revives the Mortgage Cramdown” zooms in on individual’s congressman’s inclination to punt the mortgage mess to the courts – or not. An article on health care warns of what might be if Congress doesn’t act. High youth unemployment? Let’s examine what the governments in the world have done about that.

After I put down the magazine my ears were ringing with words like “legislation”, “lawmakers”, “commission”, “lobbyist” and “lawmaker”.

Are we now living in an age where half the newsworthy business events originate out of Washington?

Secure FTP On GoDaddy Shared Hosting Accounts

For a long time GoDaddy kept frustrating many of its customers with the lack of an option to securely  access files over FTP on shared hosting accounts. FTP is inherently insecure as it transmits the authentication credentials in plain text.  For anyone taking security of their hosting account even half-seriously, a better option is clearly desirable.

The frustrating wait for better security on GoDaddy is now over (well, sort of). GoDaddy is now offering FTP-SSL access to their shared hosting accounts. This option is however not turned on by default and anyone interested in taking advantage of it must explicitly request it.

The move to enable  FTP-SSL also enables SSH access – another nice-to-have. On the downside though the switch can cause potentially crippling downtime of 24hrs+ for anyone who is running a database-driven site such as an ecommerce site or even a WordPress blog (more on this later).

Now, a world of clarification. The world of FTP security is plagued by an alphabet soup of potentially misleading acronyms that deserves an explanation.  FTP-SSL (which is what GoDaddy offers) is also known as FTP Secure or SFTP. It is an extension to the FTP protocol that provides support for TLS and SSL.

FTP-SSL should not be confused with other popular methods of securing FTP such as SSH File Transfer Protocol  (aka SFTP), as well as Secure FTP. The latter is essentially a mechanism of tunneling FTP over SSH.

Confusingly, Secure FTP and FTP Secure are totally different things. GoDaddy only offers the latter.

For people like me the subtle difference between similarly-sounding acronyms is largely irrelevant.  All I really care for is that there be a way to securely transfer files back and forth using a popular client like FileZilla.

Now, let me tell you why I didn’t make the switch to GoDaddy’s FTP-SSL. Reading the fine print towards the end of the how-to revealed the following:

“it may take 24-72 hours for SSH to be enabled for your account.”

After repeatedly talking to customer support it also became clear that databases (like MySQL) are problematic in the transition process. It turned out that all existing database instances need to be deleted prior to starting the internal move to the secured hosting space!

After the move is complete those databases will need to be re-created from a backup, which isn’t that hard. However the entire migration process can take up to 72 hours during which time the MySQL databases will effectively be non-existent.

In essence, the FTP-SSL transition will cause your database-driven functionality to be down anywhere between 24 and 72 hours! For me, this amount of downtime is clearly unacceptable.

So if you have a database-driven site on GoDaddy, you should probably proceed with extreme caution in your switch to enable SSH and FTP-SSL. In fact, with the excessive downtime quoted it is probably not worth it (moving to a hosting provider who offers painless SSH access may be a better move).

For those just starting out with GoDaddy, requesting the FTP-SSL/SSH switch early on would  probably be a good idea. One day you will be glad that you have it turned on, because once your site starts generating reasonable traffic you will likely balk at the 24-72 hour potential downtime. I sure did!

Lies, damned lies and statistics

By now I should be used to all kinds of sponsored market research, shameless product propaganda and PR hype that knows no moral boundaries. I am in fact part of the most oversold to population in the history of humanity.

Yet when something so obnoxiously manipulated and clearly intended to misguide and distort the truth innocently presents itself as actual market research something inside me wants to scream. just published some respectable-looking survey backed by some respectable-sounding company to the effect that the iPhone somehow managed to become the most satisfying business smartphone, by a wide margin.

The survey seems to give the venerable device what looks like a nearly perfect 778/800: if God himself were to do it, the subconscious message seems to be saying, he clearly wouldn’t be able to make things much better. And oh look how far ahead of the also-rans the iPhone is, compared to BlackBerry (703/800), Samsung (701/800) and the puny Palm.

I say seems of course because when you look closer to the axis and scale of the survey you start noticing things. Like how the visual axis scales from 600 to 800, and the small print says 1000 point scale. Ah, clever! Nearly got me there, appleinsider. If ever there was a visual way to make something that scored 70/1000 less points look half as good and what scored 15% less look as nearly pathetic by comparison, you have nailed it.

But that’s not what bothered me about this survey. True, I find it hard to believe that somehow the iPhone has become the most satisfying smartphone for business users by a wide margin, but I am used to listening to all kinds of iPhone-will-take-over-the-world-just-you-wait talk from pretty-looking websites that my brain has subconsciously stopped paying attention to “research” like this anymore.

Don’t get me wrong, I actually like the iPhone. It is a pretty damn amazing device. As a mobile enterpreneur I also like it in a vested interest sort of way: a rising tide lifts all boats and if all my clients came to me and asked me to port all the enterprise-targeted BlackBerry apps I made for them to the iPhone, that will be good for the consulting line of my business.

I like the iPhone so much that even on occasion I entertain the intellectual thoughts of pundits and journalists (largely the latter) who speculate of the place of the iPhone in the corporate world (none) and when it will start to get adopted by enterprise users (never). I would explain, but then I would have to get into things like security, end-to-end encryption, IT policies, Sarbanes-Oxley, push email, the importance of battery life and seamless intranet access, and I just don’t want to get all technical here.

But what bothers me about this survey is Samsung’s place. Within rounding error from BlackBerry?? You surely must be kidding me.

I am sorry but I have a hard time taking this kind of bullshit seriously. The BlackBerry world has all those sites like,,, to name just a few, where avid BlackBerry fans from around the world, corporate and consumer alike, convene to rave about their devices and drool over what’s to come. What does Samsung have in terms of user fan base? I only hear the sound of crickets.

Companies tend to be fairly rational when it comes to making their purchasing decisions, and if they were almost equally satisfied with the Samsung’s offering as they are with RIM’s, they would be buying roughly equal parts of both, right?

Except that the business crowd has been buying BlackBerries left, right and center. Of course they have, why else would the BlackBerry become the de facto pop culture symbol of modern day corporate affiliation? You don’t hear people talking about CrackJacks, do you?

How Samsung can “catch up” as a satisfying business device to BlackBerry is clearly beyond my comprehension. It certainly has nothing to do with the reality that I am seeing around me. Especially since Samsung’s devices largely run on Windows Mobile, an OS so despicably horrendous and notoriously buggy that reviews like this one are not at all uncommon (the review is for a non-Samsung device, but you get the point).

And I have not even gotten to things like security, end-to-end encryption, IT policies, Sarbanes-Oxley, push email, the importance of battery life and seamless intranet access.

I know, I know, the state of the economy is tough for everyone. iPhone sales have been sagging and with the major customers of market research firms either bankrupt, bailed out or about to go bankrupt and get bailed out, you must do research to whoever pays the bills. And should the outcome from the research be what your clients wanted you to prove in the first place, hey, let’s call this a lucky coincidence, shall we? I get it.

But please can we at least have some semblance of integrity? And please don’t try to brainwash me with your fake data and sponsored research. I am having none of it.

The Wall Street Journal for the BlackBerry: One Cool Mobile App

The Wall Street Journal recently released their new mobile reader for the BlackBerry. It is completely free and offers content from the Wall Street Journal network like and among others in a number of configurable category-like tabs (News, Tech, Opinion, etc). Some screenshots available at blackberrycool.

I have been using the BlackBerry reader for the past week or so and have been quite impressed by it. It does a lot of neat things, makes use of clever constructs in unobtrusive ways that will no doubt make it a solid hit with BlackBerry users and maybe even give us all a glimpse of where the future for many mobile software applications may lie.

Here are some of the things that impressed me:

  • Slick and very responsive UI. Going down the news feed and flipping between panels was blazing fast, something that isn’t as easily done on a mobile device as it can be on a desktop computer. The UI was looking pretty styling in my opinion too.
  • Clever, intuitive navigation. Flipping between tabs is also so intuitive and quick you barely notice it. I also like how the app visually distinguishes between an article that hasn’t been read (the title appears darker) and one that hasn’t been scanned (red star next to title). This creates an instant awareness of your reading or scanning progress down the news feed.
  • Customizable news criteria. Each one of the tabs is further customizable to include part or all of a number of sub-categories and geographical regions. My favorite is the My Keywords tab where you get to enter a bunch of keywords and all recent articles that match the criteria come up.
  • Headlines that appear in full. By using a normal (i.e. not bold) font the application can show a longer string of text per line (surprisingly, I didn’t find things any less readable as a consequence). If need be, the title continues on a second line, thus never cutting off a headline halfway through. I hate it when similar applications like Viigo cut off the article title and put ‘…’ in the end, sometimes leaving you cueless as to what the article is actually about.

The Wall Street Journal has a very ‘straight goods’ approach to news coverage, so going down the article feed feels something like a twitter feed of world events (well, world events from a capitalist point of view, I guess). Pretty neat nevertheless.

  • BlackBerry integration. Being a native application and not a web-based one has the added benefit of integrating with standard BlackBerry applications like the Address Book. I like spamming my friends with WSJ articles I find interesting, so this feature comes in handy. Sending the article to Facebook and is also available for every article, by the way.
  • Free. Did I mention this thing is free of charge? Now, when something of like Wall Street Journal content is offered for free, people naturally wonder for how long. While it’s true that the WSJ guys may be just releasing it out for free to test the waters, a case can be made that the app will probably stay free for a long time time. There are 15 million BlackBerry subscribers worldwide and the rate is growing at double digits year over year – much better than WSJ’s numbers. This fact is probably not lost on the WSJ folks. And with a whole line-up of obvious advertiser choices like the various online brokerages and wealth management firms this thing might prove profitable and in the process might even give the mobile advertising space a bit of an adrenaline shot.

Now, it’s not like the Wall Street Journal has suddenly jumped in the business of BlackBerry software development. They have chosen, and quite wisely, somebody else to do it. So all the development credits here go to the smart folks at Freerange.

Some things could use improvement though and there were minor annoyances as well:

  • Buggy My Keywords tab that just wouldn’t accept a ticker symbol as a valid keyword and throwing a nasty error 999.
  • Advertising banner a bit too large. I know, people need to make money off these things, but having the banner consume 1/3 of the screen feels a bit too much at times. Add to that the space required for the tab navigation and the header (the latter can be set to not show up via the settings) and you get about 1/2 of the screen taken by “administrative” stuff. I think that with a little bit of cleverness the banner can be reduced to at most 20% without any loss of visibility.
  • Where is the Digg button??
  • ‘Dumb’ keywords – entering “BlackBerry” in the My Keywords tab settings brought up an article on the Dying Art of Harvesting BlackBerries and putting Amazon brought articles on deforestation in Brazil. Yeah, I know, reading people’s minds is tough, but the ability to combine keywords in a meaningful Google-like search and apply it to the incoming article feed would be pretty cool thing to have in the next version.

But overall a very well-designed and pretty useful BlackBerry application that is definitely worth a try.  Cudos to the guys at Freerange. And hey, if you are reading this and work for their UI team, give me a call. Lunch is on me 🙂

Another Reason To Launch Your Start-Up Now: Inflation

They say a recession is a good time to launch a startup. It seems a bit counter-intuitive at first, but on second thoughts it makes sense. For one, economic downturns don’t last forever, so by the time things pick up the startup will hopefully be off the ground and be ready to reap in the rewards of the better times ahead. Also historically, new paradigms in technology have been introduced during downturns – think Web 2.0 and the 2001-2003 malaise. Melissa Chang at The Industry Standard lists 5 great reasons why recessions are a good time to start a company.

Naturally, making it so that your venture makes it through the rough times and lasts until the going gets better is crucial. This is where inflation can throw a big monkey wrench in your startup’s financial planning.

When a startup launches with a pool of funds, right off the gate the funds are good for, say X months. Then inflation roars along, forcing that estimate to go down to X-1, X-2 months, etc. And inflation has been roaring along: it recently inched to a 17-year high in the US, an all-time record in the EU and Canada, and emerging economies like China and India have been breaking records of their own (here and here).

So if you have an idea and some money set aside, either from saving or pledges from friends and relatives, launch that startup and launch it now. Don’t wait, because in a few months from now that amount of money may not get you as far as it would today.

The extent to which the current inflationary environment affects different startups can vary. Launching a software-based startup can be done on a shoestring these days with the relatively inexpensive cost of hosting, basic hardware and various startup support services (like SimpleDB, EC2) etc.

The relatively low “price of entry” for a software startup shouldn’t cause complacency to the threat of inflation though. Often times the largest expense category of startups, especially smaller ones and micro ISVs, is the cost of living of the founding members, some outsourced work here and there (e.g. graphic design) and maybe some travel (maybe a bit more travel if you are launching an enterprise software startup, actually). Unfortunately the expenses associated with these categories have been rising much faster than many other items that the official inflation figure tracks.

Don’t expect much of a break when it comes to hiring help either – tech workers are still in high demand, their salaries in emerging economies like India have been catching up as this story from Bangalore indicates and even reputedly not-so-great economies like Germany have now an official shortage of engineers.

There is little sign of inflationary pressures dissipating any time soon. If anything, they might only get worse. Inflation-stoking events are everywhere, from government-sponsored bailouts of bankrupt institutions (Northern Rock in the UK, Bear Stearns in the US) to economy ‘stimulus’ packages (e.g. the one in Spain), from Central Banks worldwide pumping ‘liquidity’ into markets and keeping interest rates below inflation rates.

For example, in the US the Federal Reserve rate is 2.00% or 2.25% through its discount window. These rates are available for select privileged institutions (i.e. not you and me). With inflation officially at 5% and unofficially much higher, these select privileged institutions that get access to this sweet deal are effectively being *paid* to take the money. And thus money is created out of nothing and down the inflationary spiral we go.

A surprisingly large number of developed and developing countries in the world have their Central Bank rates close to or below inflation, so the difference here is mostly about the *extent* of the creative ways in which new money is pumped into the system.

The official response on inflation so far has been mostly “yeah, it’s bad, we know it, we are just gonna look at it some more and hope it goes away on its own. Hey, how ’bout another multi-billion dollar bailout?”.

Now, I am not an economist and maybe this is the correct course of action given the circumstances. What I do know though is that things are unlikely to change in the upcoming few months while my startup ramps up, and I am planning accordingly.

Inflation is real, inflation is here and ignoring it can be detrimental to the health of your startup, present or future. Plan now, act now.

BlackBerry vs. iPhone: What If There Is No Winner?

There has been a lot of excitement in the mobile space lately. The release of the 3G iPhone has made many mark July 11th on their calendars and got many an Apple fan buzzing. BlackBerry is making headlines too with the upcoming BlackBerry Bold. And of course not to be forgotten are the ‘Google phones’, the release of which is said to be on target though likely to arrive a bit later than previously rumoured.

All this has got people wondering who will be the winner in the mobile space. Is Apple going to dominate the space with the slick iPhone design and even slicker marketing, or is the headstart enjoyed by BlackBerry devices combined with their strong grip on the enterprise market enough for them to clinch the top spot? Or could Google come out of left field with whatever it is going to come out of left field with and crush both RIM and Apple into oblivion?

But lets pause here for a second and ask ourselves, what if there is no clear winner at the end of the day? In other words, what if the smartphone market is simply not a winner-take-all industry?

For one, customer needs in the space may be too diverse for a single player to successfully satisfy them all. Early signs are starting to develop that this might be the case. Both the iPhone and the BlackBerry have successfully captured a core market, and users in either ‘core’ have little reason to switch at present. The 300-emails-a-day corporate user who wants mobile access to his company’s CRM system will probably continue being a BlackBerry customer, and the cool kid with voracious appetite for web content and YouTube videos will likely stick to his iPhone.  When I was thinking of which platform to launch my startup on, BlackBerry was the natural choice just because my app requires certain amount of typing and BlackBerries are considered to be more typing-friendly.

Another argument against the winner-take-all scenario is that the smartphone market may be growing too fast for any single company to be able to successfully dominate. BlackBerries are selling at a blistering rate: Research in Motion sold 9.4mln devices so far in FY 2008 compared with 4.4mln in the same period FY 2007 for an annualized growth rate of 114% (link to quarterly financial statement here). And judging from all the excitement around the 3G iPhone, it will probably sell many millions in less the time it takes to say “I’ll have the chicken, please”. Over at Sprint, the new Samsung Instinct touchscreen smartphones are flying off the shelves like crazy too.

Dominating an industry that is growing at a break-neck speed may be tough to achieve, even for great companies like RIM and Apple.

So the BlackBerry is popular in the segment that it targets, and the iPhone is popular in the segment that it targets. In fact, it is easy to imagine a few more segments developing in the smartphone space over the next little while as the industry expands and evolves. This will give the opportunity for new players to step in and make a lasting impression or for the existing ones to capture more market share.

Here are a few segments that will likely develop:

1.The smart phone under $50 (but without a plan). Smart phones are currently too pricey for mass adoption, especially in emerging markets. Fifty dollars sounds on the low side these days, but just like a lot of other things in technology, if it looks impossible now, just give it a couple of years. Intel is already stacking its chips accordingly and making a heavy investment in a super-small and cheap mobile processors. Nokia has done well in the lower price points in the cellphone market for years and they are making their move in this space too with the release of the E71 (Boy Genius Report on the E71 here). Price is not there yet, but just give it time, just give it time…

2. The smartphone – extension to the user’s computer(s). The ability for users to have transparent and seamless access to the same information at home or at work as they have on their mobile devices without having to initiate some sort of a manual sync would be killer feature. And the rapid emergence of clouds can be a major catalyst here – mobile syncs to cloud, cloud syncs to PC, etc. MobileMe looks like the first crack at this, but at $99/year it will likely not be massively adopted overnight.

Humm, can anyone think of a large company with massive cloud infrastructure and growing mobile aspirations?

Honorable mentions in this category here goes to Windows Mobile devices for enabling users to view their MS Office files on the go. While viewing spreadsheets on your mobile device may not overly excite many, Microsoft has recently unveiled their Mesh project, which aims to give users the ability to sync files across devices. Could it be that MS Mesh evolves into a MobileMe for the enterprise?

3. The app phone. No, it ain’t going to be the iPhone. A large amount of software is bought by companies and they are going to choke at Steve Job’s 30% cut. Do you see Microsoft giving 30% to Apple for each download of Word Mobile? I don’t think so either.

The BlackBerry’s platform is developer-friendly (kind of), but the absence of an App Marketplace is a set-back. The title in this category is pretty much out for grabs. A glimpse of an Android demo showed an icon labeled “Market” which got people speculating.

Oh it looks like it is going to be an interesting year in the mobile space!

The Future of Enterprise Software: I Am So Scared, I Am So Excited

It is not very often that one gets to hear about events that can dramatically change an industry. And yet there it is, right in front of us in the form of a lawsuit filed by Waste Management against super-large software vendor SAP. The lawsuit allegedly exposes some of the ugliest and most dishonest practices in enterprise software sales and the court’s reaction to it has the potential to dramatically transform the industry as we know it.

Basically Waste Management spent $100mln on a system that it claims was of little use after delivery. But instead of just swallowing it like many other purchasers of ill-fated software products, they decided to sue. And sue big.

The court materials are actually a pretty interesting read. In it, Waste Management alleges that the software it bought from SAP was “utterly incapable of running the operations of an American waste and recycling company” despite SAP presenting it is “out-of-the-box,”, “integrated end-to-end solution”. Another quote from the court materials that I found intriguing:

As part of its fraud, SAP presented Waste Management with a series of pre-contract product demonstrations consisting of what SAP represented was the actual Waste and Recycling Software. Yet Waste Management has discovered – and, in internal documents, SAP has admitted – that the pre-contract demonstrations were in fact nothing more than fake, mock-up simulations that did not use the software ultimately licensed to Waste Management

The full text for the court filing can be found here. Now, I Am Not A Lawyer and am the last one to know which direction this lawsuit will go. Moreover, this is the story from Waste Management side only and I am sure SAP has something to say as well.

However, the implications of this lawsuit and the attention it drew can be profound and go much further than toxic publicity for SAP. Rest assured, the business community at large is taking note of these developments. If the courts rule in favour of Waste Management in any of the counts, the salesmen at your enterprise software company might be in for a completely different experience next time they try to make a sale. Maybe at the next product demo given to a customer, instead of just people from IT and the potential users there will be also a couple of people from the legal team in the audience. Oh, and the microphone is on ‘record’, by the way. And how much of this demo is fake anyways?

Whichever way you look at it, the implications for the reputation of the large software vendors are not positive. Popular articles like this don’t help either. And all this is happening while in a report by William Snyder from Gartner comes out basically saying that enterprise software licensing model is in for a radical change (original can be purchased from here, discussion of the report can be found here) .  One of his reasons? The existing sales and licensing models just won’t fly in the emerging markets.

It looks to me like the big enterprise software vendors may be headed for a period of soul searching over the next few years as their sales and licensing models become increasingly under scrutiny and more and more customers balk at the existing practices. The good ole days of fat profit margins may be coming to an end, a sentiment echoed by Snyder as well.

But in every crisis there is opportunity, and there are plenty of opportunities in this one. The opportunities are there for enterprise software companies that maintain good, healthy relationships with their clients and don’t turn their potential users into irate and vociferous litigators. And the opportunities are there for companies that invest the time and effort on building new products and technologies that innovatively solve customer’s problems instead of relying on sales prowess alone. Given the potential PR damage and legal costs from this highly public lawsuit, I wonder if SAP now wishes they had spent more R&D time and effort on designing and implementing software that better meets their customer’s expectations.

More so than ever, the time is coming for companies that build it right and do it right to prosper while the ones that exclusively focus on just selling it right and who-cares-what-happens-after-the-deal-closes to stare at a lacklustre or flat  revenue curve. Because you really can’t fool all the people all the time.

Dependency Injection in JBoss 4.2: Hold Your Excitement

For the last little while I have been pushing my company to migrate our Enterprise Beans to EJB3 (most of our beans are of the 2.1 variety) and Dependency Injection (DI) has been one of the EJB3 features that I have been very excited to see getting used throughout our middle tier.

DI is a great new addition to the EJB spec which gives the ability to ‘inject’ an EJB reference in another bean simply by using the @EJB annotation:

MyBeanInterface myBeanReference;

At run-time, the container populates the field with the appropriate bean reference, thus saving the developer some manual JNDI lookup code. For a more thorough discussion of DI, check out Debu Panda’s article.

The biggest selling point for us was that EJB references can also be injected with a bean setter methods, e.g.

void setMyBean(MyBeanInterface myBean){
this.myBean = myBean;

which can make a bean easily unit-testable with the setter used to pass in a mock object during the test set up.

However when we started using DI with the latest stable version of JBoss (4.2.2) we found that DI of EJB references has limited support. Namely it is only supported for objects inside the EJB container. This means that while beans can refer to each other with the @EJB annotation, other managed objects like servlets and non-EJB web services must still use JNDI lookup to access any Enterprise Beans.

To quote from the JBoss docs:

“JBoss Application Server 4.2.2 implemented EJB3 functionality by way of an EJB MBean container running as a plugin in the JBoss Application Server. This had certain implications for application development. The EJB3 plugin injects references to an EntityManager and @EJB references from one EJB object to another. However this support is limited to the EJB3 MBean and the JAR files it manages. Any JAR files which are loaded from a WAR (such as Servlets, JSF backing beans, and so forth) do not undergo this processing”

So even though the JEE 5 specification stipulates a wider scope of the @EJB annotation, JBoss 4.2.2 doesn’t support it. In fact JBoss 4.2.2 is a ‘bridge’ version that doesn’t claim full JEE 5 compliance. And while I am grateful for the many other JEE 5 features JBoss currently does provide, I hope this post saves people out there the time and effort of trying in vain to make @EJB references work for servlets, web services or other WAR components.