No Relation To Blog
Subscribe to the personal musing of Emmanuel Bernard
Remotely send and consume messages with JMS in JBoss AS 5.0
This tutorial will show you how to create a queue in JBoss AS 5 (which uses JBoss Messaging 1.4.1), send a message to a remote queue and listen to the queue using a Message Driven Bean.
I have been playing with JMS queues and MDBs in JBoss AS 5 today to complete the clustering chapter of Hibernate Search in Action and went through more bumps than I should have. Let me share what I've learnt. Disclaimer, I am a JMS noob: this tutorial will go only over the basic concepts. In particular, I will not cover subjects like security, message persistence and so on. This tutorial can be partly reused by Hibernate Search users using clustering (just ignore the part when we send and consume messages as Hibernate Search does that under the hood).
First of all, get a fresh version of JBoss AS 5.0 (currently in Release Candidate 1) here. We will launch two instances of JBoss AS in parallel. If you are lucky enough, run them in two different machines (virtual image or not). If you are not, you will have to remap a few ports to avoid any conflict and this is what I will just describe now.
Go to JBOSS_HOME/server and copy the default directory as master.
cp -r default master
We now have two versions of the JBoss configuration. default will contain our slave instance configuration and master will contain our master instance configuration. Let's now change the default ports on the master configuration. In the master directory, open each file described and change the following ports
- conf/jboss-service.xml from port 1099 to 1199 (JNDI)
- conf/jboss-service.xml from port 8083 to 8084 (WebServices)
- conf/jboss-service.xml from port 1098 to 1097 (RMI)
- conf/jboss-service.xml from port 4446 to 4447 (Remoting)
- deploy/ejb3-connectors-service.xml from port 3873 to 3874
- deploy/jbossweb.sar/server.xml from 8080 to 8081 (HTTP)
- deploy/jbossweb.sar/server.xml from 8009 to 8010 (Apache connector)
- deploy/http-invoker.sar/META-INF/jboss-service.xml from port 8080 to 8081
- deploy/jmx-remoting.sar/META-INF/jboss-service.xml from port 1090 to 1091
- deploy/messaging/remoting-bisocket-service.xml from port 4457 to 4458
- deploy/remoting-service.xml from port 4444 to 4443
- deploy/remoting-service.xml from port 4445 to 4442
This step is only required if you use the same server to run both instances. There is an alternative and more elegant approach described here (thanks Julien for tweeting me the answer after I did all the hard work :) )
You need to make sure JBoss Messaging has a different ServerPeerID between different instances. Update deploy/messaging/messaging-service.xml, and set ServerPeerID to 1 (the default configuration uses 0)
We will now create the queue in the master instance. Open deploy/messaging/destinations-service.xml, and add the following fragment
<mbean code="org.jboss.jms.server.destination.QueueService"
name="jboss.messaging.destination:service=Queue,name=hibernatesearch"
xmbean-dd="xmdesc/Queue-xmbean.xml">
<depends optional-attribute-name="ServerPeer">jboss.messaging:service=ServerPeer</depends>
<depends>jboss.messaging:service=PostOffice</depends>
</mbean>
A queue is an MBean object, you can refine it's configuration as explained in the JBoss Messaging documentation. As a start, you can simply copy the fragment and replace hibernatesearch by the name of your queue. The queue will be available in JNDI under queue/hibernatesearch (this can be overridden if needed). If you start the master instance of JBoss AS (go to JBOSS_HOME/bin and launch ./run.sh -c master), you should see the following lines in the console
The next step is to publish a message from the default JBoss AS instance into the queue. Here is a simple servlet doing so:19:27:46,403 INFO [QueueService] Queue[/queue/hibernatesearch] started, fullSize=200000, pageSize=2000, downCacheSize=2000
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
QueueConnectionFactory factory;
Queue queue;
try {
Properties jndiProps = new Properties();
jndiProps.setProperty("java.naming.provider.url", "jnp://localhost:1199")
InitialContext initialContext = new InitialContext( jndiProps );
factory = (QueueConnectionFactory) initialContext.lookup( "/ConnectionFactory" );
queue = (Queue) initialContext.lookup( "queue/hibernatesearch" );
}
catch (NamingException e) {
throw new Exception( "Unable to lookup queue", e );
}
QueueConnection cnn;
QueueSender sender;
QueueSession session;
try {
cnn = factory.createQueueConnection();
session = cnn.createQueueSession( false, QueueSession.AUTO_ACKNOWLEDGE );
TextMessage message = session.createTextMessage();
message.setText("Pass it along");
sender = session.createSender( queue );
sender.send( message );
session.close();
}
catch (JMSException e) {
throw new Exception( "Unable to send message to JMS queue", e );
}
finally {
try {
if (cnn != null) cnn.close();
}
catch ( JMSException e ) {
log.warn( "Unable to close JMS connection", e );
}
}
}
A few things are noticeable here:
- we override the JNDI URL to point to the master JNDI host and port: if you run the master instance on a different machine (without remapping ports), the URL will look like jnp://master.host:1099.
- to look up the factory we use /ConnectionFactory. Do not use java:/ConnectionFactory as this value points to your local instance (I lost a few hours here, thanks Clebert for the hand!). If you want to change this name, open deploy/messaging/connection-factories-service.xml and add a new binding under the JNDIBindings attribute.
- always close your connection in a finally block to avoid connection leaks
On the master side, you can deploy a MDB (a trivial task with EJB 3 as no deployment descriptor is needed).
@MessageDriven(activationConfig = {
@ActivationConfigProperty(propertyName="destinationType", propertyValue="javax.jms.Queue"),
@ActivationConfigProperty(propertyName="destination", propertyValue="queue/hibernatesearch"),
@ActivationConfigProperty(propertyName="DLQMaxResent", propertyValue="1")
} )
public class MDBPassOnController implements MessageListener {
private final Logger log = LoggerFactory.getLogger( MDBPassOnController.class );
public void onMessage(Message message) {
if ( !( message instanceof TextMessage ) ) {
log.error( "Incorrect message type: {}", message.getClass() );
return;
}
TextMessage textMessage = (TextMessage) message;
System.out.println( textMessage.getText() );
}
}
The new embedded console (to come with JBoss AS 5 final) based on a stripped down version of JBoss ON will make some of these steps much easier but now that you have gone the roots way, don't you feel stronger? :)
*Breaking* news: Apple Inc acquires Twitter...
... and uses it as their iTunes Store infrastructure. Now it's broke!
I updated my iPhone firmware this morning *as requested by Apple* and the process is hung because the iTunes Store is down. I now have a totally bricked legit iPhone: no call, no text. Great!
Apple, I am very angry at you. Why are you penalizing your legit customers by not allowing the phone to be activated without your blessing. People who want, will jailbreak it anyway. Please this is the 21st century, be smarter.
PS: sorry Twitter to pick on you. I love your service, and it helped me to discover I was not stuck alone in this madness. Summize is a totally awesome pulse checker.
Two third of Hibernate Search in Action out!
We have just pushed another set of chapters for Hibernate Search in Action and reached the symbolic limit of 2/3. Yoohoo! We have also enhanced some of the existing chapters based on the feedbacks we received and the perseverance of our editor. They have just shipped as part of the early access program available in ebook format. I am very happy with the new chapters especially the description of analyzers in chapter 5.
I describe the use of Hibernate Search and the new Solr integration (coming up in Hibernate Search 3.1) to enable synonym, phonetic, n-gram and snowball search. Snowball is an algorithm that deduces the root of a word enabling searches for words of the same family: work, working, worker will all be reduced to the same root (called stemmer). The chapter both aims at demystifying analyzers and providing a concrete approach on how to use them. I really enjoyed writing it, I hope you will like reading it.
Beyond analyzers, here is a small list of the subjects I am personally happy with in the book:
- the introduction gives you a nice picture of what search is, why it matters nowadays and how it can be implemented in todays applications
- custom bridges: chapter 4 gives some nice examples of custom bridges including how to write one for composite identifiers
- mapping associations has always been a confusing subject for beginners. Chapter 4 comes with some nice diagrams that should clarify this topic
- chapter 5 explores when and how to use synchronous indexing, asynchronous indexing and clustered indexing (through JMS) and describes what is going on under the hood
We (and by we, I mean John) also have finished the Lucene dedicated content. While Hibernate Search hides the gory details of indexing and searching, its let you use all the flexibility of Lucene queries. Understanding Lucene is key and we have added the necessary knowledge you need for your daily work with Hibernate Search.
Let us know what you think and, of course, go buy the e-book :)
JSR 303 interviews
I have been talking, writing, preaching Bean Validation in the past six months.
A few interesting links came up recently:
- The list of blog entries I wrote. Probably the most palatable content but long.
- An interview with Dick Wall and Carl Quinn from the Javaposse I did at Javapolis 07 (newly renamed Javoxx) . I hated to listen to myself, hopefully you won't. The interview also covers Hibernate Search, Seam and Web Beans.
- An article published by InfoQ that goes beyond the standard set of questions on JSR 303
Free bonus: a very interesting talk about free time and participation in a post TV-only age. No relation to Java, not by me, so surely very interesting :o)
TimeMachine backs up too much?
I just discovered the reason why TimeMachine was backing up so much data. I forgot to exclude my Maven and Ivy repositories :o)
Here is a good tip to discover which files are backed up. You need to have the Developer Tools installed.
When TimeMachine backs up
- Launch /Developer/Applications/Instruments
- Select File Activity
- Open the default target combo box and attach the backupd process.
- Start recording
- Enjoy the list.
I wish there were a less geeky solution.
Why would you pay for JBoss products?
Andy posted some of the reasons why you would want to use the JBoss subscription based platforms rather than the .org projects. During this exercise, he hinted some of the reasons why JBoss moved from a model where the community version was supported to a model where an enterprise platform is supported. He did not go far enough in his explication for my taste.
One of the fundamental reason (other than the financial one) for such a split is that supporting all the community releases do not work in the long run. Some customers want 5+ years of support on a product line and it is simply impossible to support every single community release for 5 years.
There are two main strategies from here:
- slow down the release cycle and freeze innovation to match the 5 years customers
- leave the community projects release early, release often, innovate like crazy and fork them to do an Enterprise pace version
In the second model, an enterprise version is created every n community versions. This is where the support, packaging, service and advanced QA is provided. Packaging and QA are the ice on the cake, the five year support is really the meat (assuming a meat cake with ice is good :) )
Speaking of QA, yes deep internal QA is important and leverage bugs upfront but I trust the community QA more than any internal QA (more hands, more eyes, more time). I wish good luck to MySQL on their enterprise only features (semi-closed or closed source) but I think that will lower the quality of these particular features (less eyes, less hands, less time): my bet would simply to use the MySQL Enterprise version but not the "select" features. As Sacha like to say, in the JBoss Entreprise versions we remove features, we don't add them: unstable or experimental features are removed from the enterprise version. It's about less not more.
Generally speaking the support problem is interesting and usually kicks a company around its 5th birthday. The wannabee Platform as a Service contenders will face the same problem... in 5 years. "What do you mean the cloud where my data lives is too old??? Which version of the Cloud are you at?"
Productivity tools
With my regular job(s), the Hibernate Search book and a life going on at the same time, I had to find ways to boost my productivity.
Here is a list of some tools I am using in no particular order:
- ThinkingRock (ad the GTD methodology): I am reading Getting Things Done by David Allen and ThinkingRock is the best tool I have found to help you follow the methodology. GTD is all about putting all your thoughts somewhere, organize them and decide what will be the next action on each of them. Some sort of superpower todo list, but one you actually use.
- FreeMind: it's a software implementing the concept of Mind Mapping. It's a fantastic tool to organize your ideas on a given subject. Despite it's clumsy interface, I use it extensively to organize each chapter of the book. I also use it to build presentations.
- OmniOutliner: a fantastic outliner tool. It somewhat competes with FreeMind but keep things a bit more organized and the interface is very efficient.
- OmniGraffle: every diagram in the book is done with OmniGraffle. Fantastic tool, very productive and makes very nice diagrams without effort. Microsoft Visio but done well.
- IntelliJ IDEA: I switched from Eclipse back in the dark days of annotations. I tried to come abck a couple of times, but I am too much of a happy user to jump back.
- Keynote: Powerpoint without the useful features and annoying glitches.
- no email: I try to avoid unread emails, when I open my inbox, I process all emails and put some todos if needed in ThinkingRock. If I read an email and keep it unread, I will process it over and over. annoying
- KeepassX: Some people keep all your passwords in a text file. This is efficient and cross-platform. I keep mine in KeepassX: it's a bit more secure, it has a search box and open the websites for you. There is a Windows version as well (the original version indeed). The file is readable by both versions AFAIR.
- Mac OS X: a ton of tiny little details
- Time Machine + Time Capsule: A software + hardware solution to seamlessly backup your data on a Mac. Not so much a productivity tool as no major catastrophe has happened so far but that's the first time I do backup my data consistently. I don't even have to think about it.
- XMLEditor XMLMind: my part of the book is written in docbook as I find it more productive and easier to focus on the content rather than the style. XMLMind is the best Wysiwyg editor for Docbook (could be better but the best I've found so far). I use the pro version simply because it has on the fly autocorrect feature. It's expensive for a tiny little feature but it is worth the time it saves me.
- Hg (Mercurial): I am not using this tool yet but I am very curious about Distributed SCM. I wonder if it would help me integrate patches quicker and make the contributor's life easier (it's for another post I guess)
- No TV: pretty obvious. I check the news on Google News and Le Monde ; I rent DVDs when I feel like it.
- Google Reader: I don't run after the tech news, they are waiting for me on Google Reader. so when I have some spare time, I go read a couple of entries.
Mac OS X Leopard and internet downloads
If Leopard asks you if "you are sure you want to open this application which was downloaded from the web" every single time, read further.
I installed Mac OS X Leopard yesterday. Leopard started to warn me about applications downloaded from the Internet. Every single time I open them (not only the first time) I have to confirm it's a safe app.
I first thought Apple believed I was both stupid (can't take care of my security) and with huge memory issues (yes I am trying to open this troyan app 8 times in a row, thank you for reminding me I forgot).
Apparently, this is a small bug. If you download an application with one user account but do not open it with the same account, the security flag is never lift up. To work around that, log on your original account, open all you downloaded apps (27 for me, the dock was a nice christmas tree :) ), accept the security warning for all of them. Next time you open one of them, the security warning will not appear, pfffeu!
Another tip for free. If, like me, you want your old iLife applications back after a clean OS install, go download Pacifist, extract the iThing packages from the Tiger CDs and install them.
It was nevertheless the smoothest clean reinstall experience I've ever had (Carbon Copy Cloner and the Migration Assistant are fantastic).
Philly's search
I will be at the Philadelphia's Emerging Technologies for the Enterprise conference speaking about Hibernate Search on March 27th (Thursday).
The conference has some interesting talks around the new wave of development frameworks (Seam, Rails and so on). There is even a Battle of the frameworks! a Rountable Debate which sounds very promising. I will definitely try to sneak into it ;)
Come by and say hi. If people are interested we could have a chat about the future of Hibernate Search as we are shaping it as we speak (or you can show up on the hibernate dev list if you don't like Philly ;) ).
Hibernate Annotations and EntityManager fix-athlon
Hibernate Annotations 3.3.1.CR1 and Hibernate EntityManager 3.3.2.CR1 are available for download here. I have done a fix-athlon in the last few days to ready them for JBoss AS 5.
There is a ton of bug fixes especially in the Java Persistence scanning area and in edge mapping supports.
Some minor new features have been added as well (transparent integration with the latest Hibernate Search collection events, @Any, @NaturalId).
Check the changelogs here and here.
Unless huge bugs are discovered, these versions will be embedded in the next JBoss AS 5 release.
Go try them.