Showing posts with label Reviews. Show all posts
Showing posts with label Reviews. Show all posts

March 8, 2010

Five things I like most at NetBeans Platform 6.8

NetBeans 6.8 is there since December 2009. It did not look like a very important upgrade at first. At least not very important for Platform developers. But using the new version of platform, some things which may appear small at first, has been visibly improved. The most important improvements are listed here (according to my personal feelings). For a complete overview of changes in platform API you can take a look here.

Wrapped libraries
That was one of the major headaches source. Developing modules for NetBeans (as for other platforms) requires sometimes links to other libraries. Third-party libraries, other than the modules provided by the platform, needs to be linked and wrapped in your custom pluggins or platform-based applications.

Wrapping libraries was done in the past in two ways. By creating a module library wrapper plugin for every library which need to be imported. But when you have to link a bigger library, which have a lot of jars, that was a pain. Because a module library wrapper could be created only for one jar. You can end up with easy to have twenty-thirty libraries only to link to something like apache logging libraries or Seam or similar.


The second approach was to create a big jar with all jars from library. For this operation, NetBeans is helpfull, but you have other two problem to solve. First is that the new jar will have it's own manifest. That means that if there is information in manifest files of every jar, that information is lost or not complete. If that information is important, you have a nice problem to solve. The second is that you can loose control over which libraries you have, which versions. Become very difficult in time to maintain the upgrades.

Solution is the new wrapped libraries feature. Now each plugin module in NetBeans can have it's own dependencies on external libraries. For configuration, you have a new tab panel to add as much as needed libraries. The cool thing is that you can specify also the source code and javadocs for every wrapped jar. That was not possible in the old versions.

ActionListeners are everywhere

That could not look as important as it is. In the old versions you could use ActionListeners only for always enabled type of actions. Not you can use the same interface also for context aware and callback action types. That is really cool, even it does not sounds like that at first. A main aspect here is that it is used a "well known" interface.

The first consequence is that if you want to migrate a swing-based app on NetBeans platform, is easier because you just have to pipe your actions. The second consequence is that you don't have to use specific platform interfaces like cookies. I don't say that cookies were bad, but they are old and there is better and much usable alternative.



Declarative Asynchronous actions

That's small, but makes code cleaner and flexible. Also throws away the need to manage yourself the asynchronous behavior of your actions. Nice done.

Enhanced IO API


We already had colors and links. And it was very useful. But now is even more flexible.

You can color the output as you like because you can output with IOColorPrint.print. So you can made your output lines from peaces colored independently. You can also put more hypelinks on the same line. You can, again, add an importance marker, which improves readability on verbose outputs. Finally, you can specify the parent of an IOTab and set its icon and tooltip message. All of them are small things, but used together can be very helpful on creating really effective and friendly output for your application. I appreciate very much an application which let you know what is going on.

Annotations

That's not a specific point. There are some very useful annotations added. The point is, thought, not the specific annotations added. But the trend to use as much as possible annotations. I hope that this trend will continue. I already used @OptionsPanelController.SubRegistration and @ConvertAsJavaBean. But there are more, take a look.

August 31, 2009

Powered by Service Provider Interface

In my previous post I used an annotation processor to enrich the usage of annotations. I stated that to configure an annotation processor you should use a compiler time parameter. In Java 6 you can do more. You have Service Provider Interface API which lets you configure the same processor in a more elegant manner. But what is SPI (Service Provider Interface)?

Brief on SPI

The official java doc is here. A service is an interface or abstract class which defines a contract for a specific functionality. A service provider is an implementation of that service. Java 6 provides a loader for services based on a provider-configuration file. Just as simple.

Steps to put on jobs
  1. You define an interface or use an existing one which defines the contract of your service.
  2. You define and implement one or more implementing classes. This classes should have an empty constructor, that is the only requirement.
  3. You create META-INF/services folder in you jar archive. In that folder you create a file named with the canonical class name of the interface. (as a sample: your.packages.MyInterface). That is the provider-configuration file.
  4. In the new created file you insert the canonical names of the implementing classes. These classes are the service providers. If you have more implementations, you put them on separate lines. The syntax of this file is the syntax of properties file (put comments prefixed with # for clarity).
That's all. The runtime will parse the provider-configuration files and provides service loaders for these services, which you can use.

What are the usages?

Insert providers for existent services

JDK provides some usefull SPIs already, which you can use them. Going back to the beggining of my article, the java annotation processor is such a SPI service. So, in place of putting "-processor org.aap.processor.AAPProcessor" as a compiler option, we can skip that. Instead, we create META-INF/services folder. In that folder we create a file called "javax.annotation.processing.Processor". In that provider-configuration file we put "org.aap.processor.AAPProcessor". Now it works. For the article go here. Simply by providing this, the runtime at the moment of loading the jar library, will parse providers and use them. Nice and clean.

Obviously we can provide implementation services for other SPIs as well. I mention here just a few like: LoginModule for authentication, sound sample API or better here, java text spi API (by the way, nice feature), and others.

Usage of service providers in an Observer Pattern manner
Implement your own interface for observable (eventually by extending java.util.Observer). Don't need to handle yourself contributions, service loader is here for that. And can handle contributions from the whole class path.

Usage of service providers in a Factory pattern manner
Implement an interface with a getter to discriminate between implementations. On execution time, use service loader to iterate through implementations and find which provider to use.

Conclusion
That's only a starting point for service provider. I found a nice feature brought by Java 6. In fact not only nice, but almost fabulous. An option to extending platform.

August 27, 2009

Annotation checking at compile time with Java Annotation Processor

Some weeks ago I implemented a feature which collects some information on runtime from some classes. I preferred using annotations against interfaces for flexibility. Practically the task could be described like: decorate with meta information some classes, parse annotations and get information to be stored.

As a sample a had a annotation like:
@Retention( RetentionPolicy.RUNTIME )
@Target( ElementType.METHOD )
public @interface Description
{
}

As you can see, annotation syntax allows me to specify to store for runtime the annotation and that the annotation to be used for methods. That was frustrating for my job, because I would expect to have more flexibility on that. In my specific case, I would like to allow the meta decoration only on methods which returns strings.

I was thinking to document the annotation and specify that if the annotation is not on a method which returns string, the annotation will be ignored. Said and done. But there is a better and fairly simple method to do the task. This is Java Annotation Processor. This feature is documented in JSR 269: Pluggable Annotation Processing API.

The code I wrote is more complex, but for this post I wrote a sample to show the usage of this API.

The JSR 269 states that you can implement a plug-in for the compiler which can handle the annotations. This plug-in can be given as parameter at compile time, so your code will be called when one of your annotation appears in source code.

First step is to create a annotation processor. This can be done by implementing interface javax.annotation.processing.Processor or by extending the class AbstractProcessor from the same package. I used the second way being much easier.
@SupportedAnnotationTypes(value = {"mypackage.LiveDescription"})
@SupportedSourceVersion(SourceVersion.RELEASE_5)
public class AAPProcessor extends AbstractProcessor {

@Override
public boolean process(Set annotations, RoundEnvironment roundEnv)
{
for (TypeElement typeElement : annotations)
{
Set elements = roundEnv.getElementsAnnotatedWith(typeElement);
for (Element element : elements)
{
// we have only one annotation on methods
processElement((ExecutableElement) element);
}
}
return true;
}

private void processElement(ExecutableElement element)
{
String elementTypeStr = element.getReturnType().toString();
if (!"java.lang.String".equals(elementTypeStr))
{
processingEnv.getMessager().printMessage(
Kind.ERROR,
"Method does not return a String",
element);
}
}
}
Some things need to be explained:
  • SupportedAnnotationTypes specify one specific annotation. You can use * and package names also.
  • SupportedSourceVersion specify the Java version. That's OK because we did not had annotations on prior versions of Java language.
  • the process method iterates though annotations and for every one give the code elements annotated with (in my case only methods); after that calls processElement for any annotated element.
  • processElement  verify get the returned type of the method; if the returned type is not java.lang.String that use the message service to signal a syntax error
That's all about processor. As you can see, is quite obvious and simple to implement that. Of course, your implementation will be more flexible (not harcoded) and complicated.

The final step is to give that to the compiler. I used NetBeans (my beloved IDE) for that, but is simple enough in any IDE. You have only to give the compiler a hint about your plug-in. For that you have to:
  • put on compiler options "-processor org.aap.processor.AAPProcessor", aka the -processor option with the fully qualified name of your class. In NetBeans you go on Project Properties->Build->Compiling and put that in "Addidtional Compiler Options" text box.
  • put the class on compiler class path; as I created a jar file containing my annotation processor, you have only to add that to the compiler path. In NetBeans is also trivial. You have to go to Project Properties->Libraries->Compile and add your jar there
That's all. The tested code was:

public class AnnotatedTest {

@Description
public String getName() {
return "String";
}

@Description
public int getAge() {
return 10;
}
}
I bet that the second method will fail at compile time. Do you?

August 17, 2009

Scannotation - java annotation scanner

Bill Burke a JBoss old timer, Red Hatter, and successful open source entrepreneur, as he calls himself here is one of the good people I read. He created in the past a very interesting and useful small tool. That tool is called Scannotation. You can find more on that from it's own place on web in the big house of sourceforge at this address http://scannotation.sourceforge.net/. The idea at least, if not the final code, which started Scannotation was the fact that Bill worked on JBoss EJB container and needed to know more about the annotated code.

There are two often seen scenarios on annotation usage. You can have classes or instances loaded by class loaders and you want to know which annotations provides these classes. That's the first scenario. The second one is when you want to know annotations used by classes before the class loader loads the definition of classes. Scannotation give you the second scenario.

You can have jars on classpath or even the bits of a class from a stream and you can use Scannotation to load annotations. You can also find annotations from a war type archive (Java EE web application module). The trick is that you don't need to load and spent a lot of processing time and memory to load classes just to know what annotations have. Scannotation parse the bits from the class definition and gives you annotations.

After you know what to parse you can parse and store annotation usages into a AnnotationDB object. That is not a real database. It contains only two maps. The first one gives you each class which have annotations and for each one the used ones. The second map gives you all annotations, and for each one the classes which uses them. You refine the class search by adding ignored packages. There are already some ignored packages by default, also. You can refine the search by setting to collect only some specific annotation place like annotations on classes, methods, parameters or fields.

The usage is really simple, and for that I will give you an excerpt from their own tests:

          URL url = ClasspathUrlFinder.findClassBase(TestSmoke.class);
AnnotationDB db = new AnnotationDB();
db.scanArchives(url);

Map<String, Set<String>> annotationIndex = db.getAnnotationIndex();
Set<String> simpleClasses = annotationIndex.get(
SimpleAnnotation.class.getName());
Assert.assertTrue(simpleClasses.contains(
ClassWithFieldAnnotation.class.getName()));
Assert.assertTrue(simpleClasses.contains(
InterfaceWithParameterAnnotations.class.getName()));

Set<String> simpleAnnotations = db.getClassIndex().get(
ClassWithFieldAnnotation.class.getName());
Assert.assertTrue(simpleAnnotations.contains(
SimpleAnnotation.class.getName()));
simpleAnnotations = db.getClassIndex().get(
InterfaceWithParameterAnnotations.class.getName());
Assert.assertTrue(simpleAnnotations.contains(
SimpleAnnotation.class.getName()));

As you can see you feed the AnnoationDB instances with URLs. These URLs can be obtained using Scannotation tools. After that you use the two provided indexes.

Scannotation is small, fast and if you like, you can modify for you needs it it does not fit well. It's Open Source licensed with Apache License v2.0.

JarSearch.com

JarSearch.com is the tool of choice for software developers and software engineers searching for the jar file of a missing class. This is the first sentence which tells everything you need to know about that tool.

During time spent with Java programming there are a lot of cases when a class or more are missing from the path. The worst situation is when you don't even know where the class is defined. I mean which jar contains the class definition.

This site helps you with identifing that jars. It gives you all possible jars (most of the possible solutions, or course). It gives you also the jar version.

I found useful sometimes, so hope you will have too. Enjoy it!

How to debug Java EE on JBossAS

A week ago I noticed a problem with a strange behavior of an EJB component.

Source code inspecting was not enough to understand what was happening. So I had to debug the component. In that moment I remembered what I felt the first time when I had to do a debug on such kind of application. I supposed that should be a complicated process behind, that I was needed some sophisticated tool for that. In reality the task is very easy to accomplish. Even the title of this article is misleading. You will understand why.

Java virtual machine gives us the everything to do a remote debug on any kind of Java application. Simply, as long as we have the source code, we can debug anything on the local computer or on the network. JBossAS is a Java application itself, like any other. Ok, not like any other, but from this point of view there is not difference.

Taking thisn into consideration, all we have to do is to configure the virtual machine on which the JBossAS is running. We have to enable a TCP connection for remote debugging, to enable the required port in firewall and to connect our IDE to that port. We need to have an IDE which is able to do a remote debugging, but virtually all the IDEs on the market implement that feature.

Configuring JBossAS

JBossAS make things simpler, from this point of view. If you use Linux, you should modify run.conf, if on Windows, you should modify directly run.bat (don't have any clue why on Windows they don't use run.conf). Here are the lines which should be modified.

# Sample JPDA settings for remote socket debuging
#JAVA_OPTS="$JAVA_OPTS -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n"

If have only to remove the comment sign on the second line. We can change the port as we wish (TCP is used). Default value for that is 8787. The suspend deserves a closer look. If we change the value to y, that, the debugged process will wait for the client to make a remote connection and after that will continue to run. This is very useful if we have to debug something in the initializing code of the target application. Now is not useful.

I repeat, this kind of debugging can be enabled on any Java process. In that case this options are give in the command line to the java runtime.

Network configuration

If the target process is executed on another computer we should be able to connect on that machine. In order to be able to do this the specified port should not be blocked by firewall, if we have something like this enable. If the target system is not in our network or we don't have direct acces on that, than we have to create a path to that port. We do that using routing and port forwarding. Eventually from computer to computer until we found one which we can connect to.

Starting a remote debug session from Eclipse

In Ecplise we use menu item Run -> Debug Configurations .. It will open a dialog box with execution configuration. We create a configuration for Remote Java Application. There we specify the project which contains the sources we want to debug, the host name or ip of the target system and the port, also.

Eventually we configure the breakpoints we want and .. happy debugging!

Two ways to start with Seam Framework

Seam is an Open Source framework for building Web Java EE.

Main functionalities includes:

  • building managed beans on the fly for web modules
  • building EJB components in contexts richer that the three standard contexts for web apps (application, session and request)
  • useful JSF elements
  • many many other functionalities, but I wil not still from you the pleasure to discover these reading the official reference guide, which worths every minute spent

When we want to create a project structure for a Seam Java EE application we have two options: generate application using seam-gen or create that using JBossTools, an Eclipse plugin published by JBoss. I will not introduce you to the details of these processes, but I will insist on the consequences and what you can expect.

Create application with JBossTools

JBossTools is an Eclipse plug-in dedicated to manage this kind of application. More precisely, it offers a wizard which can be used to generate Seam Web applications. In the dialog boxes of this wizard you should specify all the start up information, including project names and modules, package names and persistence configuration. Using dialog boxes the process of creating the application becomes almost trivial.

JBossTools also offers a lot of functionalities which can be used after the project generation. It contains complex editors for web pages and for specific configuration files. In the same time, using additional wizards, we can add new components to the application. Yopu can generate entities from relational databases, creating web pages for generated entities, add new EJB or client modules and many others.

Generate application using seam-gen

Seam Framework contains in its distribution a tool to generate Seam Java EE projects. Unlike JBossTools, this is a command line tool. It is based on Ant, so is executed in a similar way like a regular Ant taks. In order to generate the application, seam-gen needs also some information. They are the almost the same as in the case of JBossTools.

After you configure and execute seam-gen tool, the result will be produced in the form of a folder in which you will find everything required to build a Seam Web application. seam-gen will generate projects for Eclipse and NetBeans.

Strong/weak points

The two folder structures are not identical at all. JBossTools uses a project for every module of the Java EE application. seam-gen, on the contrary, uses a single project, containing a folder structure having everything you need to build and deploy all the application mdoules. JBossTools has an advantage on that, having a separate structure for every module helps to have an image about the project more closer to the final product.

JBossTool allows fast project configurations, using dialog boxes to set up every property of the projects. On the other hand, seam-gen uses for building and deploying an Ant build script. Using the Ant script is, of course, more harder to manage than a dialog box. Still, the build script is more flexible, practically we can take and implement any decision we like. For begginers the Ant script can seem intimidant, first choise would be JBossTools way. For the advanced ones, the complete control and flexibility makes the seam-gen variant be the first choice. If we count also the possibility of finding bugs in JBossTools (experience confirmed me that), the configuration can become a real nightmare.

The possibility to add with ease new modules brings again JBossTools in front. Modules having separate projects and the UI manipulation of settings is a real advantage. Although, the more experienced programmers know that the structure of a Java EE aplication module is very clear and easy to build. That's why the building of these modules using Ant script is realy easy after you understand basics.

JBossTools is integrated in Eclipse. It uses a lot from Web Tools Platform, a functionality set for Java EE. The advanced editors are often very useful. I name here the JBossTools editor for facelets web pages, which have an autocomplet feature for Seam EL and page preview. If you want another IDE or deploy to another kind of server, other than JBoss (Glassfish), than seam-gen is your choice. You have a generated project ready for NetBeans, but, because we have a project based on An, practically you can use the project with any other IDE. In the same time, using seam-gen you can choose to use various techonlogies for generating web pages (Apache Wicket, just to name one).

Conclusion

For the beginners in working with Seam Web Java EE, probably JBossTools fits well. The more advanced users will apreciate the flexibility and portability of the structure generated by seam-gen, and also the control offered by Ant build script. Even for beginners, learning Ant (not complicated at all) will give good thing on long term. We should not forget the advanced features offered by JBossTools.

My proposal is a simple one. Use the best things from both. Use seam-gen for generating the project structure. In time you can manipulate Ant build scriptwithout difficulties. In the same time, use Eclipse and JBossTools for editing web resources, is priceles very often.