« Archives in July, 2010

Sardine powered webdav client?

Extra Sardines on my pizza please

A few days ago I came across the need for an easy to use webdav client. Currently we’re using jakarta slide, which as it turns out is a project that was discontinued (as of fall 2007!), and whose code base as of this writing is practically 10 years old. Who wants those jars collecting dust in their lib directories? Sure it works, but hey, I’m trying to keep up with the Jones’ here, I’d like an up-to-date library that hasn’t been discontinued.

Dismayed, I took a look a the replacement suggested by the jakarta site – the Jackrabbit project which is a java based content repository API implementation (JCR, as outlined in JSR 170 and 283). Uh.. I’m not really looking to integrate a full fledged content repository into my project just so I can access some files on a webdav server. If I was building a CMS though, I’d be way more interested. All I was looking for was an easy way to access files on a webdav server.

Next I found Apache’s commons-vfs project but I was disappointed to find this note regarding webdav: “.. We can’t release WebDAV as we depend on an snapshot, thus it is in our sandbox.” (full page here, skip to “Things from the sandbox” ). Dammit! Guess I’ll have to keep looking..

Finally, I stumbled across Google’s Sardine project, an oasis in a desert of mismatched suitors. I practically feel guilty about rehashing whats already well documented, but I am compelled if only to underscore the ease of use.

Classpath Dependacies

At the minimum you’ll need commons-logging.jar, commons-codec.jar, httpcore-4.0.1.jar and httpclient-4.0.1.jar if you’re on Java6+. If you’re on Java5 you’ll need JAXB 2.1 and any dependancies. Luckily for you, the authors have included links to the JAXB jars and have included the other jars in the Sardine distribution so you can easily add them to your classpath.

Code Examples

Using Sardine is really simple, and pretty self explanatory. You must first call SardineFactory.begin() to initiate the webdav session. If you don’t have authentication enabled, you don’t need to provide the username/password parameters.

public List<DavResource> listFiles() throws SardineException {

	log.debug("fetching webdav directory");

	Sardine sardine = SardineFactory.begin("username", "password");
	List<DavResource> resources = sardine.getResources("http://webdav/dir/");

	return resources;

This List of DavResource objects is essentially meta data about the webdav files, which you can then use to perform whatever tasks you need.

Grabbing the contents of a file is just as easy:

	public InputStream getFile(String fullURL) throws SardineException {

		log.info("fetching webdav file");

		Sardine sardine = SardineFactory.begin("username", "password");
		return sardine.getInputStream("http://webdav/dir/file.txt");

as is saving a file:

	public void storeFile(String filePath) throws IOException {
		Sardine sardine = SardineFactory.begin("username", "password");
		byte[] data = FileUtils.readFileToByteArray(new File(filePath));
		sardine.put("http://webdav/dir/filename.jpg", data);

checking if a file exists:

	public boolean fileExists(String filePath) throws IOException {
		Sardine sardine = SardineFactory.begin();
		if (sardine.exists("http://webdav/dir/filename.jpg")) {
			return true;

		return false;

Other code examples can be found for deleting, moving files from one place to another, copying files so you end up with two, and creating directories in the user guide in the Sardine project page.

Overall, Sardine is simple, elegant, easy to use and pretty darned sexy, so check it out. I guess it’s time to update all that jakarta API related code…

Sending Attachments with the Javamail 1.4.x API

Make your emails interesting with attachments!

Not that your emails aren’t already interesting – if you have some kind of regular job running and you want to produce a results bound file sent to your recipients as an attachment, this code example can illustrate one way it can be done. It’s pretty much the same thing as sending a regular email except that it uses multipart attachments as the body content of the message:

package com.faceroller.mail;

public class Mailer {
	private static final Log log = LogFactory.getLog(Mailer.class);

	public static void send(Email email)
			throws MessagingException, NamingException, IOException {

		 * prefer the jndi lookup in your container, but when debugging
		 * manually setting properties explicitly will do

		// InitialContext ictx = new InitialContext();
		// Session session = (Session) ictx.lookup("java:/Mail");

		Properties props = (Properties) System.getProperties().clone();
		props.put("mail.transport.protocol", "smtp");
		props.put("mail.smtp.host", host);
		props.put("mail.smtp.port", port);
		props.put("mail.debug", "true");

		 * create the session and message
		Session session = Session.getInstance(props, null);

		 * set the message basics
		MimeMessage message = new MimeMessage(session);
		Message.setFrom(InternetAddress.parse(email.getFrom(), false)[0]);
			InternetAddress.parse(email.getTo(), false)

		 * multipart attachments here, part one is the message text, 
		 * the other is the actual file. notice the explicit mime type 
		 * declarations
		Multipart multiPart = new MimeMultipart();

		MimeBodyPart messageText = new MimeBodyPart();
		messageText.setContent(email.getBodyAsText(), "text/plain");

		MimeBodyPart report = new MimeBodyPart();
		report.setContent(email.getAttachmentAsText(), "text/xml");

		MimeBodyPart rarAttachment = new MimeBodyPart();
		FileDataSource rarFile = new FileDataSource("C:/my-file.rar");
		rarAttachment.setDataHandler(new DataHandler(rarFile));

		 * set the message's content as the multipart obj

		 * do the actual sending here
		Transport transport = session.getTransport("smtp");

		try {

			transport.connect(username, password);
			transport.sendMessage(message, message.getAllRecipients());

			log.warn("Email message sent");

		} finally {

You’ll notice the first multipart’s content is a String with the mime type “text/plain”, this is what will render this part as the message’s body. You can set as many parts as you want, each one defined as a separate attachment. If you want to attach rar or zipped up archive, you can use the activation libraries to include them in as one of the parts. The MimeBodyPart will automatically detect and fill in the mime type for the file – it’s provided by FileDataSource. In JBoss if you’re using the container’s mail service, you can configure the mail server properties in the deploy/mail-service.xml file, and then you can use the initial context to get a handle on that configured mail server.

Get the jars and supporting docs from the Javamail site here: http://java.sun.com/products/javamail

The Deploy vs Deployers directory, JBoss v5.x

Tae Bo for JBoss!

JBoss ships with a few configurations that are meant to provide examples of how JBoss can be configured for your environment. It’s recommend you take the “default” configuration (or “all” if you require clustering), and then slim it down by removing the various mbean components found in the “jboss/server/<configured instance>/deployers” and “jboss/server/<configured instance>/deploy” folders until only your minimum requirements are met. If you deploy JBoss with everything as it is, you’re going to end up wasting system resources on services that your application is going to use. For example, if your application doesn’t make any use of ejb2, then theres no reason to enable ejb2 implementation services or deployers in your instance. By removing these unnecessary pieces you’ll end up with a more optimized configuration, and you’ll end up getting the most bang for the buck from your installation. You’ll want to become familiar with each of the items in the deploy and deployers folders so that you can remove the services that would otherwise eat your cpu cycles while not providing any benefit.

The deploy directory

This deploy folder houses deployable services or applications meant to be run by the JBoss instance. To squeeze absolutely the most out of your installation you’ll want to be picky when deciding which services you end up leaving in. It should be noted that even though the JBoss instance is capable of hot deployments, its generally a bad idea to use Hot deploy in a production environment, its bound to cause wierd problems over time – items in memory might not be completely unallocated and may end up causing unexpected behavior in the long run. It’s also a good idea NOT to use HypersonicSQL as the defaultDS provider for your application. You probably do NOT want to queue up a massive 300k message queue into HSQL via the defaultDS, you might want to use something a little more enterprise level. Replace the defaultDS provider with your own vendor.

Here is an breif explanation of the items found in those directories:

  • deploy/admin-console.war – this is a useful utility you can use to inspect jboss and start/stop and administer your application and/or services. Not required to run your application but if you run into trouble, it can be handy for debugging or performance tuning
  • deploy/http-invoker.sar – this service allows you to invoke ejbs and make jndi calls through the http protocol. Calls are made in a similar way to: http://<hostname>:8080/invoker/EJBInvokerServlet. If you dont use this service, you can take this out.
  • deploy/jbossweb.sar – this is the tomcat integration service. If your application doesn’t have a web interface, then you can remove this safely.
  • deploy/jbossws.sar – this is the web service implementation. If your application does not use web services, or you choose to implement your own, you can safely remove this.
  • deploy/jmx-console – this is an application similar to the admin-console.war where you can go and inspect the server’s individual mbeans, view the jndi namespace (bound services, ejbs etc) view stack traces for active threads and other useful things like that. This is not required to run your app in a production environment but it can be extremely useful for debugging or performance tuning.
  • deploy/jmx-remoting.sar – this allows rmi access to jmx in jboss. Even if you remove this you’ll still have access to jmx if you haven’t removed jmx-console.war.
  • deploy/management/console-mgr.sar – this is supposed to provide a gui interface for managing the jboss application server. Haven’t used it much, so I cant say if its any good or not. This can be safely removed if you don’t intend to administer the server via a web gui.
  • deploy/messaging – the set of files in this directory are used for jms. Out of the box, its wired to use the hsql db that jboss comes with. If your application uses jms, you’ll want to remove hsqldb-persistence-service.xml and use the proper service.xml file that goes with your vendor. The right file can be found here: jboss-5.1.0.GA/docs/examples/jms. So if you use postgres you would use postgresql-persistence-service instead of hsqldb-persistence-service.xml. There are other places where you would need to update to completely remove the hsql dependency, but this particular fileset speaks to the jms implementation
  • deploy/profileservice-secured.jar – documentation says it allows web access to the profile service. I think this section allows you to administer the individual profiles, but I’m not completely sure it saves the configurations to disk, although I could be wrong.
  • deploy/ROOT.war – this is the default context application that comes with JBoss. I usually remove this completely so that I’m free to use the root context for my own application since there can be only one is use.
  • deploy/security – this is used for configuring security policies for the server
  • deploy/uuid-key-generator.sar – this service is a uuid generators, it is used by things like entity primary key sequence generators in ejb3 etc. If you change the DefaultDS name to something else, theres the META-INF/jboss-service.xml file has a reference you’ll need to change.
  • deploy/xnio-provider.jar – default configuration for some kind of remote jboss connector
  • deploy/cache-invalidation-service.xml – this is a service that allows you to invalide the ejb cache through jms, this is disabled by default so it can safely be removed without problem
  • deploy/ejb2-container-jboss-beans.xml, deploy/ejb2-timer-service.xml – these are used to support ejb 2.x in jboss. Remove if yor app doesn’t use ejb 2.x
  • deploy/ejb3-connectors-jboss-beans.xml, deploy/ejb3-container-jboss-beans.xml, deploy/ejb3-interceptors-aop.xml, deploy/ejb3-timerservice-jboss-beans.xml – these descriptors directly support ejb3 functionality in jboss, remove if your application doesn’t use ejb3
  • deploy/hdscanner-jboss-beans.xml – hot deploy support for jboss. Hot deployments are usually a bad idea for production environments, so take this out and save yourself the trouble
  • deploy/hsqldb-ds.xml – the hsql ds file, remove this and wire the DefaultDS jndi resource to your one production environment database
  • deploy/jboss-local-jdbc.rar – this is the JCA adaptor that implements the jboss datasource. Remove this if your application doesn’t use the DS files. Use
  • deploy/jboss-xa-jdbc.rar – this is the JCA adaptor that is required to support distributed transaction management (XA) datasource
  • deploy/jca-jboss-beans.xml – the jboss JCA spec implementation, this allows JCA adaptors like jboss-xa-jdbc.rar to function (enabling transaction aware jdbc calls)
  • deploy/jms-ra.rar – jms resource adaptor
  • deploy/jmx-invoker-service.xml – mbean service that configures remote access to jmx via rmi. You probably don’t need this unless your application requires remote jmx management
  • deploy/jsr88-service.xml – mbean descriptor for the jsr-88 remote deploy spec. This can be safely removed if your application does not use any jsr-88 spec deployments. More info on the spec can be found here.
  • deploy/legacy-invokers-service.xml – mbean descriptors for legacy remote jms invokers
  • deploy/mail-ra.rar – resource adapters for javamail. You can safely remove this if your app doesn’t make use of javamail.
  • deploy/mail-service.xml – mbean dessriptor for the localized jboss javamail configuration. Use this file to configure the mail server settings for receiving, sending, etc
  • deploy/monitoring-service.xml – mbean descriptors for jmx based server monitoring services, like the jmx-console.
  • deploy/profileservice-jboss-beans.xml – mbean descriptor that supports the jboss profile service. You probably don’t want to get rid of this since this piece should help configure your instance’s bootstrap and port settings.
  • deploy/properties-service.xml – mbean descriptors for the jboss properties services, allowing system properties to be loaded externally or remotely. You should be able to remove this safely if you don’t use the profile service in your application and don’t mind the default system properties
  • deploy/quartz-ra.rar – the quartz resource adapter. Remove if your application doesn’t make any use of quartz
  • deploy/remoting-jboss-beans.xml – mbean descriptors that support the jboss remoting project. More on this can be found here. You can remove this if your application doesn’t make use of any jboss remoting code.
  • deploy/schedule-manager-service.xml – mbean descriptors for the Java5 scheduler services. This can be configured for older pooled jmx based timers. I think this might be required for ejb3 timer support.
  • deploy/scheduler-service.xml – additional mbean descriptors for Java5 timers. I’m not convinced ejb3 timers require this to work, but if you’re not using ejb3 timer or the scheduling service you can safely remove this.
  • deploy/sqlexception-service.xml – mbean descriptor for handling vendor specific sql exceptions.
  • deploy/transaction-jboss-beans.xml – mbean descriptors enabling JTA transactions. This is required for ejbs transaction management. More info on the JTA spec can be found here.
  • deploy/transaction-service.xml – mbean descriptors for a jmx service that handles the jboss UserTransaction implementation for client applications
  • deploy/vfs-jboss-beans.xml – mbean descriptors for virtual file caching, used by the server for deployments. Probably a good idea to leave this in.

The deployers directory

The items in the deployers directory are used to aid jboss in its deploy capability. The ear, ejb, and seam deployers are examples of the types of artifacts jboss can deploy, and each one of these types need deployer descriptors configurations to enable their deployment capabilities. Remove some of these, and jboss will not deploy artifacts of the corresponding type. Chances are it’s OK with leaving most of these in. You’ll want to remove and leave the obvious ones and experiment with the ones you’re not sure about if you want to achieve the most bare boned and streamlined JBoss configuration. Here’s a brief rundown of these deployers:

  • deployers/bsh.deployer – enables bean shell script deployments. Remove if your application does not use beanshell scripts
  • deployers/ejb3.deployer – enables ejb3 deployers, remove if your application doesn’t use any ejb3.
  • deployers/jboss-aop-jboss5.deployer – enables the jboss 5 base aspects.
  • deployers/jboss-jca.deployer – enables JCA deployments. Keep this if your app makes use of JCA adapters like jboss-local-jdbc.rar
  • deployers/jbossweb.deployer – deploys web components like servlets and jsps
  • deployers/jbossws.deployer – deploys web service related endpoint components
  • deployers/seam.deployer – provides integration support for jboss seam
  • deployers/alias-deployers-jboss-beans.xml – supports alias deployment descriptors that install once the original is deployed
  • deployers/clustering-deployer-jboss-beans.xml – supports deployments for jboss clusters, you don’t need this if you’re not running in a clustered environment
  • deployers/dependency-deployers-jboss-beans.xml – adds support for dependency deployments like aliases
  • deployers/directory-deployer-jboss-beans.xml – legacy support for embedded deployable artifacts in folder deployments like embedded lib directories
  • deployers/ear-deployer-jboss-beans.xml – adds support for ear deployments
  • deployers/ejb-deployer-jboss-beans.xml – supports java 1.4 ejb deployments
  • deployers/hibernate-deployer-jboss-beans.xml – adds support for hibernate deployment descriptors and artifacts
  • deployers/jsr77-deployers-jboss-beans.xml – support for the JSR 77 spec, standard j2ee deployments. See more here
  • deployers/metadata-deployer-jboss-beans.xml – add support for reading in and deploying metadata in the form of annotations or xml metadata
  • deployers/security-deployer-jboss-beans.xml – supports deployment of security related configuration

Feeling 10 lbs lighter!

As you can see, JBoss is highly configurable and is therefore extremely flexible – try to leave in only what you need to get the most out of your install. Sure, you can just use the default install as it is out of the box, but you’ll be bloating your server with unnecessary services as well as possibly providing security holes that the savvy intruder might be able to exploit. Specifically, the admin-console/jmx-console store usernames and password defaults in a properties file – if you leave those alone, and don’t update or change them, you’ll be vulnerable to anyone who happens to be familiar with these defaults and how to access either console.

Jboss documentation on the “Default” configuration
JBoss 5.x Tuning/Slimming

Jars and Class Loading, Jboss v5.x

So where do I put all my jars?

As you write your applications you’re bound to leverage third party libraries to cut down on the amount of work; lets face it no one wants to reinvent the wheel. A downside is sometimes these third party libraries might not be the most mature or stable releases to date. As your product grows and matures, or you expand your client base or number of implementations, you’re bound to come across multiple third party library dependencies, even ones across the same library but different versions, what a headache! How can we organize these libraries in JBoss? Luckly we are provided with a few directories where you can stick library jars for use in your own application, here is a quick rundown:

  • jboss/client – this folder contains all the jar files used by any client application for jboss, for example a swing application that needs to commnicarte with a remote JBoss instance would need to have the jar files in this directory in its classpath or it will not be able to communicate correctly. Generally, you don’t stick third party libraries used by your application here unless you’re writing some kind of jboss client application and you’re extending the server’s functionality in some way.
  • jboss/common/lib – this folder is meant to hold jar files that should be made available to all JBoss instances. Jar files global to all applications go here.
  • jboss/lib – this folder holds all the jar files used in order for the server to run correctly. You don’t stick your libraries in this directory unless you’re extending or adding functionality to the JBoss server itself.
  • jboss/lib/endorsed – this folder holds all the endorsed libs that jboss uses where other implementations can be used to override. Xalan implementations other than the default go here if you want to override with a newer version. Since JBoss relies on these libraries also, be mindful that you might find xml parsing issues if you use an older xalan library (jboss uses many xml files for configuration)
  • jboss/server/<configured instance>/lib – this is where you put any instance specific jar files

So for the most part, unless you’re going to be tinkering with extending or modifying the JBoss server itself, you’ll want to stick to one of thee locations, the server global lib, the instance global lib, or the lib in your deployable artifact.

Possible scenarios

Ultimately, you’re going to need to make a decision on how you’re manage your third party libraries, and its all based on your particular setup and installed application base. The JBoss loaders can do teasingly mysterious things, as the order of precedence might not be completely obvious. The most easy pitfalls include more than one library being loaded, but of a different version. Which one gets loaded if there is more than one? The answer depends on the strategy you used in your setup, and figuring out the best strategy for your particular application(s) is paramount to minimizing this risk. First, lets look at the viable options:

If you want to make your application portable and completely self contained – you’ll want to package all your third party libraries in the right lib directory for your war or ear file. The benefits include more complete portability by becoming completely self contained deployable artifacts, and therefore minimizing immediate class loading problems. The downside to packaging everything into your deployable artifact is that your instance startup times inflate. A full complement of third party libraries in a huge ear file containing multiple war files could end up taking minutes to deploy because each artifact deploys its own libraries; and if there are common libraries throughout, each one can be loaded separately if they’re not organized to minimize this inefficiency.

The converse of removing all the third party libraries and sticking them into the instance library (jboss/server/<configured instance>/lib). The instance libraries load up orders of magnitude more quickly than the prepackaged third party library strategy, but the downside is your deployable artifact is no longer completely self contained. This might not necessarily be a bad thing at the end of the day however, as long as your third party libraries can be easily managed in whatever application server you use. JBoss allows you to use an instance specific library folder, and it turns out to be a neat alternative to self contained libraries, especially when there is more than one deployed application, and they share a few common libraries.

If you want to go a step more global than an instance specific common library, you could use the jboss/common/lib directory. This location will be loaded before the instance specific library and provides a baseline for all available instances. Any libraries that are super global should be placed here.

What the.. ?

So what happens if you have more than one library, say one in your war file, and another one in the instance lib, which one gets used by your code? It turns out that the order in which the classes are loaded matters and is the determining factor. The server global directory loads before the instance specific lib, and the instance specific lib loads before your deployable artifacts and their libraries. So basically, the more global libraries will outweigh the artifact local libraries.

Now what if you want your deployable artifact to override global libraries? Luckily, JBoss provides a way to scope the deployment. Scoping the deployment here means you’re making the libraries used by your deployment localized, superseding the global libraries with whats packaged in the artifact.

For War files you will need to add an entry to your jboss-web.xml file:

   <class-loading java2ClassLoadingCompliance="false">

and for Ear files you’ll need to make your jboss-app.xml look like this:


Where com.example is the package name for the specific class package (third party library) you want to override, and unique-archive-name.xxx is the name of the deployable artifact for which you want to localize the classes loading. Note that these descriptors only work for jboss and will not be honored by other vendors. Also worthy of mention is that for your deployable artifacts, the most global artifact’s deployment scope will be honored, so if you have an ear file, the jboss-app.xml in the ear file will override and cause any jboss-web.xml scoping configurations in any embedded war files to be ignored. java2ParentDelegation is supposed to be disabled by default, but its a good idea to explicitly set it to false anyway just to be on the safe side – enabling it to true will cause the classes referenced in this scope configuration to be loaded by the next most global scope (moving the loaded classes to the instance/lib if its in an ear or war, and to the most global jboss/common/lib if its in the instance specific lib).

It’s also a good practice to make sure your war files don’t start with the same first few letters as other deployed war files in the same instance. In JBoss 4.x it was possible to collide class loading when 2 or more war files started with the first few letters and the packaged class files in the WEB-INF directory shared a similar code base (ex: my_war.war vs my_warfile.war). The fix was to change the names of the war files so they were totally different. Whoever loaded first would be linked in the JBoss class loaders. If you run into a situation where old code keeps getting reloaded, keep this in mind.

JBoss wiki on Class Loading
Jboss Wiki on Class Loading use cases