Just view first few minutes of Soble's interview with Jonathan Schwartz. Pretty cool!


powered by performancing firefox

I have this on my Things To Do In Some Distant FutureTM list but today I have spotted one person who actually was looking for such article -- so I have finally wrote a small how-to develop Netbeans modules within Eclipse IDE.

To provide a custom component docked into statusbar of NetBeans platform/IDE ( actually I'm using it only as a platform :>) ) just create class implementing org.openide.awt.StatusLineElementProvider. It is a simple one-method interface:

public abstract interface StatusLineElementProvider {
  
  public abstract Component getStatusLineElement();
}
And return your custom component there. Just make sure you are returning always the same component, because this method is called at last twice on NetBeans start ( at last it was for me ).
When you are done, make NetBeans know about it by writting it's fully qualified name into /META-INF/services/org.openide.awt.StatusLineElementProvider file.

( for source code samples look at ProblemsVisualizerProvider in org.netbeans.modules.autoupdate package in NetBeans Platform source tree. )

For a while I was playing with J2SE5.0 APT tool (Brian Oxley have written how to create annotation processor for APT) -- this tool mimics behaviour of javac adding additional annotation processing abilities. I was wondering how could I run it to allow multiple passes of different annotation processors (with few ant tasks launched sequentially or something like that), but in mean time I have found JAM. It is Annogen component and it abstracts JSR175 and XDoclet annotations and provide single layer for processing them in a easy way:


 
public static void main (String[] args ) throws IOException {

   
JamServiceFactory factory = JamServiceFactory.getInstance ();
    JamServiceParams params = factory.createServiceParams
();

   
// search in source files.
   
params.includeSourcePattern (new File[] { new File (
       
"src/sandbox/jam/test/" ) }, "*.java" );

    JamService service = factory.createService
(params );

    JamClassIterator jClassIter = service.getClasses
();
   
while (jClassIter.hasNext ()) {
     
JClass elem = (JClass ) jClassIter.next ();
      System.out.println
("Class name:" + elem.getSimpleName ());
      JAnnotation
[] annotations = elem.getAnnotations ();
      dumpAnnotations
(annotations );

     
for (JField field : elem.getFields ()) {
       
System.out.println (" f> " + field.getSimpleName () + ":"
           
+ field.getType ().getSimpleName ());
        annotations = field.getAnnotations
();
        dumpAnnotations
(annotations );
     
}

     
for (JMethod method : elem.getMethods ()) {
       
System.out.println (" m> " + method.getSimpleName ());
        annotations = method.getAnnotations
();
        dumpAnnotations
(annotations );
     
}
    }
  }

 
private static void dumpAnnotations (JAnnotation[] annotations ) {
   
for (JAnnotation ann : annotations ) {
     
System.out.println ("    a> " + ann.getSimpleName ());
     
for (JAnnotationValue annVal : ann.getValues ()) {
       
System.out.println ("       v> " + annVal.getName () + ":"
           
+ annVal.asString ());
     
}
    }
  }

I'll stick with JAM for a while /images/emoticons/wink.gif Maybe it is not a complete tool like APT but I think it gives more power and is XDoclet annotations 'backward-compatible'.

Above code with simple annotated class can be downloaded here as Eclipse compressed project (just import it into workspace; Eclipse 3.1M4 is required and you'll need to fix path for tools.jar pointing to your JDK's copy).

update:
  • 01-jan: colorized source code with java2html.

jCoverage/djUnit users should check Cobertura project on SourceForge. Basically it is "just a fork" but it seems it'll be more actively developed than original jcoverage.

We all know this principle and we all know how hard is code defensively to keep it.
But it is a little easier now /images/emoticons/wink.gif Today AJDT team released developement version 2005012444759 of their Eclipse plugin, providing latest AspectJ5 capabilities to compile and wave J2SE 5.0 code with support to pointcuts matching annotated elements (there is no parameter and package annotations support right now).
Using annotations and one simple aspect we can check all calls to chosen methods and throw IllegalArgumentsExceptions whenever null value is passed to them. Here is how to do it:

  • First, create marker kind annotation (let's name it a "GoodCitizen") which we would use to mark methods which calls should be "null parameter" free.
    package sandbox.nullchecks;
    
    import java.lang.annotation.*;
    
    /**
     * Indicates methods which should behave as "Good Citizen".
     * In conjunction with GoodCitizenAspect all such methods
     * should throw IllegalArgumentException when there is 
     * null value passed to them or they return null value. 
     */
    @Retention(RetentionPolicy.CLASS)
    @Target( {ElementType.METHOD} )
    @Documented
    public @interface GoodCitizen {
    
    }
    
  • Then create aspect which will do the hard work:
    package sandbox.nullchecks;
    
    public aspect GoodCitizenAspect {
      
      // it will match any method call to annotated method with any
      // signature.
      pointcut goodCitizenMethodCall() : 
         call (@sandbox.nullchecks.GoodCitizen * *(..));
    
      before() : goodCitizenMethodCall() {
        Object[] methodArgs = thisJoinPoint.getArgs();
        for (int t = 0; t < methodArgs.length; t++) {
          if ( null == methodArgs[t] ) {
            throw (new IllegalArgumentException("Parameter " + (t + 1)
                + " of " + methodArgs.length + " in call to "
                + thisJoinPoint.getSignature()
                + " was NULL, but method is annotated as GoodCitizen."));
          }
        }
      }
    }
    
  • Now just try it! /images/emoticons/happy.gif
    package sandbox.nullchecks;
    
    
    public class GoodCitizenExample1 {
    
      @GoodCitizen
      public void citizenTest(String str, int prim, Object obj) {
        System.out.println(str+":"+prim+":"+obj);
      }
      
      public static void main(String[] args) {
        GoodCitizenExample1 ex = new GoodCitizenExample1();
        // it should yell about null as third parameter when executed.
        ex.citizenTest("str", 9, null);
      }
    }
    
Running it produces this result:
Exception in thread "main" java.lang.IllegalArgumentException:
 Parameter 3 of 3 in call to 
 void sandbox.nullchecks.GoodCitizenExample1.citizenTest(String,
 int, Object) was NULL, but method is annotated as GoodCitizen.

  at sandbox.nullchecks.aspects.GoodCitizenAspect.ajc$before
 $sandbox_nullchecks_aspects_GoodCitizenAspect$1$38402fab
   (GoodCitizenAspect.aj:23)
  at sandbox.nullchecks.GoodCitizenExample1.main
   (GoodCitizenExample1.java:13)

Also note we could check method calls to all methods enclosed within annotated classes (link to sample source code is available on bottom of this post) but it requires runtime checks and it would be rather inefficient.

As for "never return null" part I couldn't find a nice way of checking whenever method returned null or it's return type is void (after() returning(Object obj) advice threats void return type the same as when null is being returned). A little hackich way is to parse thisJointPoint.getSignature().toLongString() or create two annotations -- one for parameters checks and another one for return value checks and use them when apropriate.

  • 26-jan: update:
Matthew Webster pointed me that I could define another pointcut like this:
  pointcut NonVoidGoodCitizenMethodCall() : goodCitizenMethodCall() 
    && call(!void *(..));
and then create after() returning advice which would catch all those non-void methods:
  after () returning(Object retValue) : NonVoidGoodCitizenMethodCall() {
    if (null == retValue) {
      throw (new IllegalArgumentException("Method "
        + thisJoinPoint.getSignature()
        + " returned NULL but it is marked as GoodCitizen."));
     }
  }

Now it is a little easier to trace all those NullPointerExceptions out there. Happy hacking /images/emoticons/wink.gif

As always compressed Eclipse project is available to download. Eclipse 3.1M4 and latest developement snapshot of AJDT are required.

If you use Swing in your applications then make sure to check out Romain Guy's Weblog. He has very useful tips for Swing users. My personall favourite is "wait with style" (just check this webstartable demo). I hope He will create a full WaveLaF someday because it LooksSoCool(tm) /images/emoticons/wink.gif

As far as I know there is no simple way to use PicoContainer (tiny IoC framework) in servlet container environment for filters, servlets and so on... (this is also true for any managed object in non-IoC aware container)

The problem is that we cannot control instantiation of such objects -- it is hard coded into servlet engine. But we can of course execute dependecy lookup code in contructor itself (loosing any IoC abilities :/), or we can use AspectJ (or any other AOP framework) to decouple dependency lookup code from constructor. going futher we can use setter injection on our already instantiated object.

It sounds simple and (probably) logical but PicoContainer desn't support injection in already instantiated object 'out of the box' (or at last I couldn't find it). I have achieved this by hacking around SetterInjectionComponentAdapter and creating my own InstanceSetterInjectionAdapter. Resolving dependencies is now as easy as creating one simple aspect:

  pointcut ReferenceServiceInitialization () : execution (public ReferenceService.new ());
 
  after
(): ReferenceServiceInitialization () {
   
MutablePicoContainer picoContainer = getPicoContainer ();
    PicoUtils.resolveDependencies
(picoContainer, thisJoinPoint.getThis ());
 
}

It will be more easier when AspectJ will have full support for J2SE5.0 features. Then it will be possible to write our classes as:

   @injectDeps (container="root") public class SomeFilter implements ServletFilter {
   
...
  
}

and leave rest to our little aspect /images/emoticons/wink.gif

An example is available as compressed eclipse project, just import it into your workspace and take a look. It doesn't depend on servlet/or-something container it is just uses this IoC hack to show this basic idea. (you must have AJDT installed because it is AspectJ project)

update:
  • 01-jan: colorized source code with java2html.

Probably You have heard this a while before but just for reference: Here you can download Sun Studio Creator 2 if you are a Sun Developers Network member (registration is free AFAIR).
Personally I just wonder if they fixed the unability to compile with "-source 1.5" which was a major PITA in EA1/EA2 releases? (still downloading on my 256/128kbps adsl connection).

If you doesn't know it already here it is: Hibernate 3.0 Tools for Eclipse and it looks very promising! It is designed for Eclipse 3.1M4 and the download is approx. 8Mb.

There are: JDeveloper 10g (free of charge for all developers), Eclipse 3.1, preview version of Exadel Studio 3.0 and final version of jsr 181 (metadata for web services).

And all in one day, huh! :-)

From thursday I'm lying in bed feeling very sick so I have time to play with latest snapshots of maven2, its plugins and eclipse plugin for it. So far I can tell that I'm impressed, just invoking mvn clean install deploy:deploy and viola! Everything is simple and almost works. I ran upon some difficulties at the beginning:

  • MavenIde for Eclipse didn't show precise error messages from default maven compiler, eg. like it doesn't like generics when not set to 1.5 source compatibility (but aspectj compiler plugin does).
  • it also somewhat fails to integrate nicely with latest WTP releases -- maven dependencies aren't copied to .deployment/app/WEB-/INF/lib/ directory upon build.
  • Aspectj and cobertura plugins are accessible from mojo sandbox subversion repository but as source code and I didn't find a way for maven to auto download them (other than deploying them to my own private repository).
I didn't find a workaround only for second point (probably I didn't try enough, because it probably should work) and after resolving the two others I can say that maven2 rocks!

For all jython users (if you didn't already know it) -- there is a nice interactive console avaliable (with autocompletion and command history). You can get it from http://dev.artenum.com/projects/jyconsole.
It would be nice to have similar functionality included in pyDev Eclipse plugin :-)

Today I have stumbled upon a blog post titled "… And what about SealedObject and GuardedObject?" and as a quick exercise I have implemented spoken feature in AspectJ. I didn't write an annotation processor because it was quicker (for me) to go with AspectJ and besides APT builder for Eclipse 3.1.2 is not working for me at the moment. So I'm leaving implementation of a real AnnotationProcessor to orginal author of the idea.
You can try it for yourself by downloading archived project [12kb], and importing it to your workspace. To build it you'll need Eclipse 3.1 and AJDT plugin.

When looking for a game for New Year's Day (see last post ;-))
I stumbled on continuation of RoboCode -- RoboCodeNG.
The first thought I got when I first saw robot team API was: "Wow! How much neater could computer science laboratories be if we could implement byzantene agreement solutions in RoboCode instead of PVM!" ;-)

Some details about this game: It is Java based, you write robot code in pure Java ( you can use Eclipse/NetBeans/IDEA/... for it ) and it is somewhat similar to corewars -- you have an arena where robots makes fights. As very nice addition you can have teams of robots cooperating with each other.

In last week eclipse team released version 3.1M4 of their IDE which (almost) fully supports new J2SE 5.0 features. There was also release of Eclipse WebTools Milestone 2 which of course works with Eclipse 3.1M4 :-) (there is also a small tutorial available)

I highly recommends playing with those -- annotations, generics, enums and others are just addictive :-> (I just can't wait for AJDT J2SE5.0 support; annotations and AOP are IMHO just a killer combination for medium/large projects)

One small tip for WebTools -- don't use spaces in your application server name; and if you share a project with others make sure they have configured J2EE runtime libraries with the same name. (or they will see a nice NPE after importing that project into workspace).


PS. I'm actually trying to create custom annotation processors for APT and I just can't see how apt could use multiple annotation processor services distributed in separete jar archives. Maybe someone know how to do it?