Wednesday, May 14, 2008

NetBeans plugin: Special copy/paste

The very little I've had to paste code into this fairly new blog, was enough to give me the idea of creating an extension to NetBeans which would help to remedy this formatting nightmare. Now, in my world, there's approximately a 100:1 ratio between idea and actual realization, so I'd have to salute the awesome OpenIDE API's for making this possible spending just a few late nights and taking just 200 lines of code. Without further ado, I present, my first NetBeans plugin.


Special copy/paste
The plugin will add a couple of new actions to the context-sensitive popup-menu of the source editor, which will allow you to copy the selected text as preformatted HTML, as well as a CSS version which will preserve the formatting used in NetBeans.



Using the "Copy as HTML and CSS" menu as in the above screen dump will result in you being able to paste it directly into a website/wiki/blog and have it display like this:


/**
* @param args the command line arguments
*/

public static void main(String[] args) {
// TODO code application logic here
}



For a larger example of what the output of the plugin looks like, take a look at the plugin's own source code.

It's supposed to be language agnostic, in that it should work with all types of sources NetBeans is able to tokenize. The plugin will try to mimic the formatting of the tokens in regard to font family, keyword and literal colors. It will however *not* be able to show member-wide variables in green as NetBeans does nor show method and class decelerations in bold. This is a limitation caused by the fact that I am only using the NetBeans lexer API rather than doing any kind of semantic analysis or parsing.

If you want to give the plugin a try, download it from NetBean's Plugin Portal. Source code is available here.


Update:
It has been made clear to me through the comments, that NetBeans already contains functionality to extract source code as HTML. You can find the feature in the "File" menu under the ill named item "Print to HTML". Since it would appear other people than just me did not associate "print" with that of exporting HTML content, I have filed an issue for the relocation and/or renaming of this.

Friday, May 9, 2008

Keurig Platinum B70

Time to try to live more up to the name of this blog. As most developers, I have a passion for coffee and coke and consume it in quantities which are probably not on the healthy side. Anyway, when I saw the Keurig Platinum B70 coffee maker in action, I absolutely had to own one. Why? Take a look below.



Yup, it takes 45 sec. for it to brew a large cup (4 sizes to choose from) of fresh programmer oil, has a very gadgety blue light and is ready to serve its master 24/7. It probably isn't the most economical way to get your caffeine dose, but it does allow for a small filter so that you can use normal coffee beans rather than the convenient K-cups. Also, it came with samples of Van Houtte's Kenyan Kilimandjaro roast, so now I know why Stephen Colebourne named his OpenJDK sandbox Kijaro. ;)

Wednesday, May 7, 2008

Type registry strategy pattern

One pattern that I have often seen applied in Java, is the one where you plug-in and register a handler for a given type of object to thereby supply a specific behavior for it. For instance, this is often used in order to render, edit and validate elements of various visual components in Swing, such as the JTable. I am unaware of any official name for this mechanism, but it appears to be a combination of Martin Fowlers Registry Pattern and the GoF Strategy pattern so I like to think of it as the Type registry strategy pattern.

Legacy example
Conditional behavior is encapsulated by some common interface, which provides the mechanism for dispatching to elsewhere, responsible for applying a concrete strategy. An example is this format handler, which allows an object to be formatted as a String:


1 interface Handler
2 {
3 String format(Object object);
4 }


And an API, capable of associating handlers for various Object types registered and dispatching to these:


5 class SomeAPI
6 {
7 Map handlers = new HashMap();
8
9 public void installHandler(Class clazz, Handler handler)
10 {
11 handlers.put(clazz, handler);
12 }
13
14 public String format(Object obj)
15 {
16 Handler handler = (Handler)handlers.get( obj.getClass() );
17 if(handler != null)
18 return handlers.format( obj );
19 else
20 return obj.toString();
19 }
20 }



This way, we can supply an API with an implementation (in the following example, an anonymous inner class) of formatting behavior for a given Object type, i.e. a Date:


21 someApiInstance.installHandler(Date.class, new Handler(){
22 public String format(Object obj)
23 {
24 Date date = (Date)obj;
25 return SimpleDateFormat.getInstance().format(date);
26 }
27 });



This works fine, but it's a little verbose and not particular type-safe. I wondered if I could device a generified version which improved on this. After all, we KNOW that the object passed is an instance of Date, we just need to convince Java of this as well.

Generified type strategy
Like many others in the Java space, I am not super comfortable nor experienced with generifying methods and dealing with use-site covariance. So in order to work out the following, I got some much appreciated help from the usenet group comp.lang.java.help.

Take one
First things first, the required changes to the callback interface is pretty obvious. We now simply declare our Handler to be of the type T, for which it has a format method accepting an instance of this type:


28 interface Handler<T>
29 {
30 String format(T object);
31 }



Now comes the tricky part. We need to have the compiler able to infer the type we provide, that is, apply some wildcard capturing magic. Our map now maps unknown Class types to an unknown Handler type. The installHandler method makes use of this, and associates an unknown Class type with a Handler of type T. We capture the type of the Handler in the format method, by casting to any type that is a super type of T:


32 class SomeAPI
33 {
34 Map<Class<?>, Handler<?>> handlers = new HashMap<Class<?>, Handler<?>>();
35
36 public <T> void installHandler(Class clazz<?>, Handler<T> handler>)
37 {
38 handlers.put(clazz, handler);
39 }
40
41 public <T> String format(T obj)
42 {
43 Handler handler<? super T> = getHandler(obj);
44 if(handler != null)
45 return handler.format( obj );
46 else
47 return obj.toString();
48 }
49
50 @SuppressWarnings("unchecked")
51 private <t> Handler<? super T> getHandler(T obj)
52 {
53 return (Handler<? super T>) handlers.get(obj.getClass());
54 }
55 }



This allows the type to flow all the way out through the callback, such that we may implement it as follows:


56 someApiInstance.installHandler(Date.class, new Handler<Date>(){
57 public String format(Date obj){
58 return SimpleDateFormat.getInstance().format(obj);
59 }
60 }



Voila, no more casting needed. :)

Take two
Now, the observant reader will notice that while we got rid of the casts, we still need to supply the type twice, once as class literal (the key of the internal map) and secondly as the type of the Handler (the value of the map). I was not sure if this could be done, given Java's generics by erasure. But it turns out that the type information actually is saved as meta-data, in order for reflection to still be possible:


61 public <T> void installHandler(Handler<T> handler)
62 {
63 callbacks.put(extractGenericType(handler), handler);
64 }
65
66 private <T> Class<T> extractGenericType(Handler<T> handler)
67 {
68 Type[] interfaces = handler.getClass().getGenericInterfaces();
69
70 for(Type type:interfaces)
71 if(type instanceof ParameterizedType)
72 return (Class<T>)
((ParameterizedType)type).getActualTypeArguments()[0];
73
74 throw new IllegalArgumentException ("You must supply a generified Handler
with a single parameterized type");
77 }



It's not pretty and generally makes everything a bit more fragile, but it sure makes for a nice public API for your consumers:


78 someApiInstance.installHandler(new Handler<Date>(){
79 public String format(Date obj){
80 return SimpleDateFormat.getInstance().format(obj);
81 }
82 }



The issue of erasure
While the parameterized type of the Handler can be uptained through reflection, as shown in the previous example, it isn't actually available at the core of the type system. For a demonstration of this, imagine your consumer of SomeAPI tries to implement several formatters:


83 public class Formatter implements Handler<Date>, Handler<Calendar>
84 {
85 public String format(Date obj){
86 return SimpleDateFormat.getInstance().format(obj);
87 }
88
89 public String format(Calendar obj){
90 return SimpleDateFormat.getInstance().format(obj.getTime());
91 }
92 ...



This code won't compile, for the simple reason that during compilation, the parameterized types with Date and Calendar are lost and both resolve to the same Handler interface, and you are of course not allowed to implement the same interface twice (one of the reasons for why delegates exists in C#, but that's another story).

I'll try to make more use of this type-safe way of applying composition to factor away centralized conditional complexity. And it should be interesting having it work together with the service provider pattern.


Update
It turns out there's a trick to get rid of the unchecked cast in the SomeAPI class. The trick is to use a dynamic cast to make up for a limitation in the Java type system and is mentioned in Joshua Bloch's Effective Java Second Edition, item 29.

Friday, May 2, 2008

@SuppressWarnings values

Meta-data and how to associate it has always been a bit of a confusing topic in Java. For instance, the transient modifier is really a kind of marker annotation, as is the @deprecated javadoc tag compilers are also required to process, as is the marker interface Serializable. Then in JDK 1.5, a dedicated annotation facility was added, probably in light of the success of C#'s attributes. One of the first practical uses of annotations appears to be as a way to suppress compiler warnings.

@SuppressWarnings
This build-in annotation allows the developer to signal a respecting compiler that it should forgo a particular warning. It can be applied in front of a type, a field, a method, a parameter, a constructor as well as a local variable. It is up to the compiler to make sense of whatever you put inside the String, the only value mandated by the JLS is the "unchecked". Compilers as well as IDE's will typically implement each their own set of warning types, the Eclipse IDE defines far more of these than NetBeans does for instance.
Here I will only cover the ones supported by the SUN compiler. To see the supported types, issue a "javac -X" command. On my JDK1.6.0_03 system I get:



-Xlint:{all,cast,deprecation,divzero,empty,unchecked,
fallthrough,path,serial,finally,overrides}




Of those ones, "all", "empty", "path" and "overrides" doesn't seem to have any effect when using the SUN compiler or when used inside NetBeans. The following lists the remaining ones and how to use them.

@SuppressWarnings("deprecation")
Use this when you are deliberately using a deprecated method, realizing full well that your code might one day break, but you do not wish to be notified of this. In the following example, we use getYear of java.util.Date which has been deprecated:


   @SuppressWarnings("deprecation")
   
public void suppressWarningsTest()
   
{
       
Date date = new Date();
       
int year = date.getYear();
    }



Without suppressing the warning, the compiler (if invoked with -Xlint:deprecation) would've complained:


warning: [deprecation] getYear() in java.util.Date has been deprecated
int year = date.getYear();



@SuppressWarnings("unchecked")
Java 1.5 brought a crippled, but mostly working generics facility into play. This of course vastly improves type-safety. However, you often need to mix non-generic and generic types and this usually provoked the compiler into complaining. Take the following example:



   @SuppressWarnings("unchecked")
   
public void uncheckedTest()
   
{
       
List nonGenericStringList = new ArrayList();
       
nonGenericStringList.add("Some string");
       
List<String> genericStringList = (List<String>)nonGenericStringList;
   
}



Without suppresssing the warning, the compiler (if invoked with -Xlint:unchecked) will complain with something like:



warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.List
nonGenericStringList.add("Some string");
warning: [unchecked] unchecked cast
found : java.util.List
required: java.util.List
List genericStringList = (List)nonGenericStringList;




@SuppressWarnings("fallthrough")
Java has always followed the C-style of switch statements, where you need to explicititly break out of a switch unless you wish to simply fall through and execute the code in the case below. This can be dangerous of cousee and errors of this kind can be very hard to track down. In the following example, case 1 lacks a break:



    @SuppressWarnings("fallthrough")
   
public void fallthroughTest(int i)
   
{
       
switch (i)
       
{
           
case 1:
               
// Execute both 1 and 2
           case 2:
               
// Execute only 1
       }
   
}



Without suppresssing the warning, the compiler (if invoked with -Xlint:fallthrough) will complain with something like:



warning: [fallthrough] possible fall-through into case
case 2:




@SuppressWarnings("serial")
To ensure a serialized class is consistent with how the Java runtime perceives this object (based on its class definition), it is important that serialVersionUID be present. In practice, most people rely on the compiler to insert an appropriate UID:



    @SuppressWarnings("serial")
   
class Serialest implements Serializable
   
{
   
}



Without suppressing this warning, the compiler (if invoked with -Xlint:serial) will complain with something along the following lines:



warning: [serial] serializable class SerTest has no definition of serialVersionUID
class SerTest implements Serializable




@SuppressWarnings("finally")
Since try-finally blocks are really glorified goto instructions, the compiler can be instructed to complain if it sees a violation of "good practice" when it comes to execution flow. In the following example we issue a return from within a finally. The compiler allows this, since the JLS specifies a finally clause will always get executed, but realize that any exception thrown in the try may be completely disregarded:



    @SuppressWarnings("finally")
   
public String finallyTest(String str)
   
{
       
try
       
{
           
str+=".";
       
}
       
finally
       
{
           
return str.toUpperCase();
       
}
   
}




Without suppressing this warning, the compiler (if invoked with -Xlint:finally) will complain with something along the following lines:



warning: [finally] finally clause cannot complete normally




@SuppressWarnings("divzero")
This can be used to catch explicit integer division by 0. It should be default in my opinion, since the compiler KNOWS that executing the code will always result in a a java.langArithmeticException. The annotation has no effect on double's or float's, since these can represent infinity:



    @SuppressWarnings("divzero")
   
public void divzeroTest()
   
{
       
long l = 12l/0;
   
}



Without suppressing this warning, the compiler (if invoked with -Xlint:divzero) will complain with:



warning: [divzero] division by zero
long l = 12l/0;




IDE's
I reckon most people do not mess with the compiler and supply -Xlint flags, but use the facilities of their IDE. NetBeans allows you to see all (+more) warnings as hints in the gutter section of the editor. You can tweak this to your liking, by going in the options.




NetBeans supports a few more values, namely "empty-statement" and "cast". But that's nothing compared to Eclipse, which supports "unused", "empty", "UnusedAssignment", "UnusedDeclaration", WeakerAccess", "autoboxing" and many more.

Update
Should you be using NetBeans 6.1 or later, I have created a small plugin to assist in the code completion and documentation of these values. You can read more about that here.