Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

NbBundle on Steroids Using Annotation Processors

DZone's Guide to

NbBundle on Steroids Using Annotation Processors

· Java Zone
Free Resource

Learn how to troubleshoot and diagnose some of the most common performance issues in Java today. Brought to you in partnership with AppDynamics.

The NetBeans Platform has great support for i18n through the Bundle.properties/NbBundle. In it’s simplest form you basically create a Bundle.properties file with your key/values, and access them in your code like this:

NbBundle.getBundle(ClassInPackage.class).getString("yourKey");
This works great, but if “yourKey” doesn’t exist, you get an exception at runtime. You want to catch these errors at compile time or directly when coding in your IDE. I came across Jaroslav Tulach’s fancy LiveDB a while back, and I’ve been aching to use this brilliant approach in other situations. I believe NbBundle is the perfect candidate to enhance with an annotation processor. My solution lets you write this instead:
Bundle.yourKey;

You get code completion and even automatic value lookup if your IDE is any good :) Also, you get compile time checking, you will be notified if a value is deleted from your Bundle.properties but still referenced in your code, and you can easily spot entries in Bundle.properties that are not used anywhere.

To get started, include my StaticBundle.java annotation and my StaticBundleProcessor.java in your classpath (see below), preferably in a “wrapper” module, not the module where you will be using the annotation. (This avoids some chicken/egg situations).

In the package you have your Bundle.properties, create a file called package-info.java:

@StaticBundle
package com.yourcompany.yourpackage;

import no.tornado.netbeans.tools.StaticBundle;

Next, register the annotation processor as a service in META-INF/services/javax.annotation.processing.Processor:

no.tornado.netbeans.tools.StaticBundleProcessor

Now, compile your project, and a Bundle.class will magically appear with static public fields for all keys in your Bundle.properties. This also works without modification to your build process for maven projects as well. If you use IntelliJ, you have to register the annotation processor and also add the generated-sources folder as a source-folder in your project, since IntelliJ doesn’t use the target/output folder for content assist etc.

This is the StaticBundle.java annotation:

package no.tornado.netbeans.tools;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.PACKAGE)
@Retention(RetentionPolicy.SOURCE)
public @interface StaticBundle {
}

This is the StaticBundleProcessor.java:

package no.tornado.netbeans.tools;

import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.tools.FileObject;
import javax.tools.JavaFileObject;
import javax.tools.StandardLocation;
import java.io.Writer;
import java.util.Properties;
import java.util.Set;

@SupportedAnnotationTypes("no.tornado.netbeans.tools.StaticBundle")
@SupportedSourceVersion(SourceVersion.RELEASE_6)
public final class StaticBundleProcessor extends AbstractProcessor {
    public boolean process(Set<!--? extends TypeElement--> annotations, RoundEnvironment roundEnv) {
        for (Element e : roundEnv.getElementsAnnotatedWith(StaticBundle.class)) {
            PackageElement pe = (PackageElement) e;
            String clsName = pe.getQualifiedName() + ".Bundle";
            try {
                Filer filer = processingEnv.getFiler();
                FileObject bundleFO = filer.getResource(StandardLocation.CLASS_OUTPUT, pe.getQualifiedName().toString(), "Bundle.properties");
                Properties bundleProps = new Properties();
                bundleProps.load(bundleFO.openInputStream());
                JavaFileObject src = filer.createSourceFile(clsName, pe);
                Writer w = src.openWriter();
                w.append("package ").append(pe.getQualifiedName().toString()).append(";\n\n");
                w.append("import org.openide.util.NbBundle;\n");
                w.append("import java.util.ResourceBundle;\n\n");
                w.append("public class Bundle {\n");
                w.append("\tprivate static final ResourceBundle bundle = NbBundle.getBundle(Bundle.class);\n\n");
                for (Object key : bundleProps.keySet())
                    w.append("\tpublic static final String ").append(String.valueOf(key)).append(" = bundle.getString(\"").append(String.valueOf(key)).append("\");\n");
                w.append("}");
                w.close();
            } catch (Exception ex) {
                throw new IllegalStateException(ex);
            }
        }
        return true;
    }
}

The generated Bundle.java will look like this:

package com.yourcompany.yourpackage;

import org.openide.util.NbBundle;
import java.util.ResourceBundle;

public class Bundle {
	private static final ResourceBundle bundle = NbBundle.getBundle(Bundle.class);

	public static final String myKey = bundle.getString("myKey");
}

I have no prior experience with annotation processors so I’m sure my approach isn’t optimal, but I think you’ll agree that this can save you a lot of time and make your code safer and look nicer!

From http://blog.syse.no/edvin/nbbundle-on-steroids-using-annotationprocessors/

Understand the needs and benefits around implementing the right monitoring solution for a growing containerized market. Brought to you in partnership with AppDynamics.

Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}