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 21, 2009

Concerned about JBoss Seam? Don't worry, it will be better

I am a big fun of Java EE. Don't ask me why, if it's not obvious I will explain in another post. Even of the fact that I like Java EE that much, that does not mean I consider it perfect. In fact is not perfect at all.
There is place for a lot of improvements, a lot of them are on the road to be included in the next versions of standards, others not yet. So, working with Java EE alone, sometimes could be a pain. That's why I put in place Seam Framework. Seam Framework is a perfect match for Java EE on server side. It gives you a lot of things which the standard has not. You have Seam components and Seam contexts, which is a big progress. I don't mention the whole features of Seam here, even those have a great weight. If you want to see details on that you can see on http://seamframework.org/. I worked with Seam on three medium/big applications and had a lot of reasons to be happy.
But in these days I had some black thoughts on that. I was wondering what will happen with Seam. You could honestly ask yourself why, if everything was so fine? Just because of WebBeans, the new standard. Here is the story.
O lot of good people of JBoss and Seam were working on the new proposals from JSR. They provided a lot of work and results for EJB3 and JPA. Now they are ready to publish the new JSR-299 Java Context and Dependency Injection ( aka. WebBeans ). That is a great JSR and I am waiting to work with. The WebBeans comes to provide a standard for the main lack of Java EE applications. The poor integration between EJB components and JSF components ( aka. managed beans ). That was the core job of Seam Framework. Now WebBeans put these two layers together, by allowing EJB components to act as JSF components. We will have more multiuser secured acces and transactions on the components beneath JSF, and that's really cool. In fact WebBeans have knowledge from Seam Framework, Struts Shale, Oracle ADF and Google Guice inside.
So what will happen with Seam in this context? The JBoss will renounce at Seam in favor of WebBeans? I was thinking on that until I read a very clear statement from JBoss. You can find it here. It explains how Seam Framework relates with WebBeans.
WebBeans implementation form JBoss will be the core on which Seam will be based. All the good things from Seam related to components and contexts will be based on that and that. Seam Framework continues, it will be alive. And most probably, it will give you in the future also, a lot of reasons to stay sticked your business and use EJB in a painless way.
The good thing here is that we could use WebBeans implementations from another providers together with Seam Framework, it's a standard, isn't it?
If you didn't give a try to Seam Framework, you should start to do it right now. EJB and Seam is a winner bet. Thanks to all guys who works on that.

August 17, 2009

NetBeans 6.7.1 with JavaFX

NetBeans soon after 6.7 had launched another version of its IDE. That's 6.7.1 with JavaFX. As its name states, this version is an update version of the previous one containing few adiitional things:
  • Support for JavaFX 1.2
  • Update of GlassFish v3 Prelude
  • Important bux fixes requested by users
You should give it a try, even if you don't use actually JavaFX. Bring it from here and have fun.

Slow death by technical debt

Did you here the words "can't have time now, implement that quickly" or "we need a.s.a.p. that for a presentation"? If you did that, you should know that you are in the middle of the battle. Invisible bullets go near your ears and you and your team are living on the edge. That's not bad in itself, but can became as bad as can be soon, if you can't handle. I'll explain why.

When you have to implement something, either is a new feature or a solution for a bug, you face one common problem. You can take main scenario, fix what it should do and go further. That's called quick and dirt. That is because the code resulted from that is really dirt. The second and best approach is to face to problem for today and tomorrow. Think hard and implement the optimum solution, use a good design. As I said, there are times when quick and dirt saves you from something. Is like in management, the difference between important and urgent. The urgent sometimes is more useful than important. But this has a trade off.

Ward Cunningham invented a metaphor for that, which fits well in understanding the implications. This metaphor is called Technical Debt. Technical debt is similar to financial debt. When your business needs something urgent and you don't have enough money, you borrow some from the bank and do your job. After that you have to pay interests and principal to return the debt. Same in software, but here you deal with quality in place of money. Sometimes to get a good deal, to touch a milestone or to give something with few resources you can accept quick and dirty. After the deal is done you can decide if you live with that or you refactor it, using a good design this time.But you must have always in mind the working on poor code means paying more interests. And if you pay too more interests your deals could became a bad one. So, for your health, refactor as soon as possible. That is called paying the principal and eliminate the technical debt.

Quality in software means resources. You have to spent more resources to have better quality. As Martin Fowler said here, technical debts hurts performance. And the performance is almost unmeasurable in software. You have to manage a proper balance in your technical debts. If you hear the magical words which leads to quick and dirty, open your ears. If you don't hear soon about refactoring tasks, you should put your questions. If these things come again and again then you could go into a swamp with your projects. Everything begins with parts of code which is considered ugly and unmanageable. These become to stink. The project can go to the slowly path of death by technical debt suffocation.

How to handle technical debts?

There no standardized solutions. That's because is hard to measure and because managers like Excel too much. They like to see numbers, that give them the sensation of control. But numbers are not so bad. They really don't show the things how they are (don't let the managers know that!), but the process of getting these numbers enforce some processes which could help in handling technical debts.

A good individual exercise which I practice is using of IDE meta comments like TODO, FIXME or somebody else from the family. When I begun to implement something which is complex somehow I use TODO comments. I use them as bookmarks to remind me that I should complete something. These marks will be removed until I submit. So they exists only to remind to my poor memory that I did not finished the job. Before submit I check to see if everything is like I want by verifying and removing these comments.I call them Transient Technical Debts. Transient because these technical debts are not persisted into version control system.

A similar approach could be followed for the persistent technical debts or the normal technical debts. You can you a marker like FIXME. Maybe a FIXME and a date. Better is to have also a system for controlling them. A good approach is to put an effort in the next iteration of your software and eliminate them. So all the technical debts you accumulated on the current iteration will be paid in the next one. Just to keep things in control.

Another approach is to keep that ledger in the bug and task tracking management system. You can have some attributes on tasks and bugs which tells us if the job was done quick and dirty or not. If we have to spent more effort to put a good implementation in place of a poor one. A mixing solution is to have code comments linked to that kind of a system.

These kinds of ledgers are good because they can give you numbers also. It forces you to have a health quality of the software and keeps you manages happy. They have the input for nice charts and reasons for raise your salary. Anyway, keep your ears tuned and don't go int the technical debts swamp.

Java EE is just Java

I write Java EE applications for about some years. During those years I learn some things and give some cents to others. But most productive things which were happen were the discussions on that topic. When you talk with somebody on a subject where both have some knowledge, you find usually nice points of view. Also I noticed that in the same the same time, the same problems are bypassed.

A lot of discussions on this subject happens having in mind that Java Enterprise applications are applications made from distributed components. That's true. Java Enterprise applications some standard services provided by EJB and web container. That is also true. Java Enterprise are build only from EJB layers ( entity beans - now JPA, session beans, message beans, etc) and presentation layers. That is not true. There is something missing here. Java Enterprise applications are still Java applications. What is the meaning of this note? The fact that Java Enterprise applications are still Java applications is an aspect which is often forgotten or simply not took into consideration. When you build a Java Enterprise application you don't loose the possibility to do the same things as you would do in a normal Java application.

When you debug a Java Enterprise application, as a matter of fact you debug a Java application. The debugging feature is something which happen on the virtual machine and class loader level (more on that on a future article). You debug in the same way a Java EE application as you would do with a desktop application, even local or remote, even through shared memory or TCP port.

You can have static or singletons or factories as would you have with normal Java application. I remember a discussion on a forum when somebody put the following problem. Every client is represented by a stateful session bean. How you would implement a communication between those clients? A saw a lot of responses, more that 15 on that topic. All of them stating more or less that you cannot avoid to use persistence layer to store information to be used by different clients. Nobody thought at a simple solution. A singleton which would hold information send by every client and requested by others (was a IM problem). Don't say that the singleton is the best solution. I state only that developing Java EE solutions sometime makes you think that the only things that you can do are EJB components. That's not true. You can however do everything you want.

The only differences between a Java application and a Java Enterprise are:

  • The Java Enterprise application is loaded and started by a special piece of code called container (EJB/web), the normal Java application does not need to be started by something else, could have it's own main entry point
  • Java Enterprise applications are packaged in a specific way to achieve the third difference, while normal Java applications don't have this constraint
  • Java Enterprise applications can use services provided by EJB and web container, while normal Java applications can't (only if you you an embedded environment)

An that's all. In every other aspect these applications are the same: Java applications.

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!

NetBeans 6.7 was launched, what brings with him?




NetBeans 6.7
On June 2009 Netbeans released the final version of 6.7. You can find more about here, on their release page. You can download it here.
From the beginning I must say that I am a big fun of NetBeans. I used since it was named Forte for Java version 2. I appreciate also Eclipse, but don't start here a flame on why I consider Netbeans superior.
From the release page we can see major topics on the improvements of new features brought to us by this version. You can read yourself about them. Here is my only humble opinion on this release.
Overview. The first impression is that is faster than its predecessors. The difference is visible in usage. Also, they added a feature to enable/disable features with you don't work.
Other languages than Java. Since I don't work too much with either of them I can't provide a full coverage. Still I am happy that I can have in the same IDE some tools for managing this kind of projects. That's cool. I tried PHP support, which I found quite good. Comparing with dedicated tools on that, it manages good. I found it fine for may needs. All that languages were supported before. Thought new valuable features were added for all of them. I would call here the sql editing and PHPUnit in php scripts, remote debugging for Ruby, code complettion on Groovy, profiling and QT libraries support for C/C++. Just to name few of them which are really consistent.
GlassFish. Nice that v3 is supported now. You have code completion, there is also a nice plug-in called GlassFish v3 enabler, quite usefull. You have also v2 version support.
Maven. That's really a very good thing. Maven support is much better now. You have a viewer for dependency graphs, you can configure a lot of your settings through UI. Also, you have archetypes for Java EE projects. The most appealing thing on that is that you can easily use your NetBeans project in another IDE. Practically nothing need to be done to do that. That's impressive. For the ones who want to know more on Maven they should take a look here.
Kenai. The most appealing to me. Kenai is a community similar to sourceforge, I think. But the best thing is that is fully integrated with NetBeans. For start up project is increddible. You have almost everything you can wish: bug tracking, wiki, dedicated place for a site, IM chats, etc. Take a loot at kenai.com. It worths the effort.
Conclusion. This release means "get into community" to my. Kenai is very apealing. In the same time they did not lost focus on continuous improvements. I believe everybody can found a new good reason to use NetBeans.
PS: for Eclipse developers now there's a button called "Synchronize editor with views" ;)

Interface vs Annotations

When I think about OOP languages, my 2 cents goes into choosing a good contract between the components of your code. I never liked "smart" solutions which tries to steal a little time from here, a little from there and so on. Don't say that there are no good solutions of that type. When you accommodate a generic solution to a specific problem, you might be find that your code is much better. But, to be in that position, you have to have first the best design possible. That gives good solutions in every day practice. And a good OOP design implies healthy contracts between components.

Interfaces apart from classes can define a contract without implementation. Interfaces exists only as pure contracts. And interfaces are firm contracts. If a class implements an interface you can be sure that it will respond to you on the contract terms. Of course, nobody saves you from a bad implementation behind, we should live with that possibility.

Interfaces solves somehow the multiple inheritance problem. Can't agree on that

When we think a contract we have in mind classes which consume services stated by interface and other classes, behind interface, who provide the service. In this way interface acts as an indirection between two classes. You can change always the consumer or the provider of that service, things will go on. There was said that interfaces solves somehow the multiple inheritance problem. Can't agree on that. Interfaces does not provides behavior. The classes which implements multiple interfaces provides the behavior. Still, the implementation classes can't be considered as multiroot inherited. The main difference is that the class which implements multiple interfaces doesn't inherit behavior. And that is the main purpose of multiple inheritance.

Multiple inheritance is a bit clumsy and error prone

I always considered multiple inheritance as a bit clumsy and error prone. When a class inherits two behaviors we live on the edge. If the behaviors are small than there is a possibility to handle things in a logical way. If the behaviors are rich in features, that we are already doomed. That is the worst form of dependency. But even if we are in the best situation possible that an be on short term only. In time things can roll on in a bad way. Considering that the maintenance of the code is the biggest stage of a software component, there will be usually a lot of occasions or opportunities to "improve" and "enrich" the behavior of a component. If a class inherits multiple behavior, these kind of improvements is a curse.

Thanks to James Gosling and others that they don't allowed that in Java. But there are problems which still need to be solved.

Interfaces define how a component should look to be albe to be used by others

Interfaces can define the form of a class. That's why they are called interfaces, right? The interface defines how a component should look to be albe to be used by others. We can have marker interfaces or interfaces with content. Our clases can be less or more polluted by methods implemented from many interfaces. For that we allways have the addapter solution. When we have a class which needs to address many targets we always can split the class in many pieces. The main piece will retain the original goal of the class. The other classes will adapt the main class to othe target, of course, by providing appropriate interface implementations. That address well the mltiple inheritance gap. But can be better, and here comes annotations.

Annotations don't enforce types, don't enforce method signatures or exceptions, like interface does

Annotations are like interfaces, but there are suble differences.Interfaces defines a contract on a whole class. Annotations defines contracts for a class, method, field and others. Like interfaces annotations does not provide behavior. Still, the interfaces defines the form of a possible behavior in a complete way. Annotations don't imply these kind of restrictions. The consumer of annotations will have to handle evenrithing in a more generic manner. Annotations don't enforce types, don't enforce method signatures or exceptions, like interface does. That's way provider classes should alter their code to include the contract of it's implemented interfaces. Annotations don't pollute business code. Don't pollute contract of a class. They just decorate the class.

Annotations can be considered more like a part of the consumer which relies on the provider

Let's take the simplest case for the moment. The marker interfaces. A marker interface is an interface which don't have a body. The are used only to "mark" a component. Just to know at runtime that a class "is a" kind of something. You can't use a marker interface to call methods. A classic example of marker interface is java.io.Serializable. When a class implements Serializable, we know that this class is allowed to be persisted. The interface is only a semantic to serialization. The same effect could be achieved using an annotation on class level. We know that on serialization problem, because of the fact that annotations were not invented at that time. Considering that, the interface solution is a normal solution. Still, if we had to design serialization now, when we have all, what should we choose? I would still choose interface. Both annotations and interfaces are ment to adapt a class to a specific usage. Thought, the interfaces are more a part of a class, more dependent to a class than annotations. Annotations can be considered more like a part of the consumer which relies on the provider. That's why they are more dependent of consumer class than interfaces. If on marker interface teh case is not very clear, we go further.

The only discriminator to choose interface or annotations is the degree of business cognation or similarity

When we want that a consumer class to use another one we usually need that the provider class to tell somethings about that. We can do that using an interface to be implemented by provider class or by using annotations. When we provide information to the consumer we have to fight against code pollution. Even if the provided information is in small or big quantity the problem is still there. The only discriminator to choose interface or annotations is the degree of business cognation or similarity. If we want our class to provide a functionality closer to its bussiness purpose, the most appropriate is interface. If we want our class to be used in a completely different way, apart from it's original scope we should use annotations. Finally, if both ways conduct to a lot of work to adapt, we are probably on a wrong way. We should give a call to adapter or it's cousins to help us because in most of the cases our problem can't be handled by our class. We take a look on two examples for clarifying purpose.

We have a BusinessProcess class which handles information about a process of our business. This class is a java bean, so all properties have setters and getters. Nice simple class. This class provides some methods to run a process, to stop it while is runnings and to collect output data as results.

We have to implement a GUI interface which shows us a log with running events, when tasks have started or stopped. A simple GUI list and that's all. We decide that the model behind the GUI to be a class which handle running business execution events. Because announcing when a process has started or stopped fits very well with our class, we can define an interface for Observer pattern. That interface can have as a sample onStart and onStop methods, with process name as a parameter. So our GUI model will implement our ProcessNotifierListener interface. Our BusinessProcess class will have methods to add or remove listeners of that type, and will call them when any event appeared.

Our classes should not be aware of the problems which don't relates to it's business

Second task is to provide a way to specify the level of logging information for each type of process. The purpose is to show full logs for processes related to security transactions. The other type of processes will have only regular logs saved. We can do that by enforcing and interface with a method. But more appropriate is to use a custom annotation with a property defined. Like @LogLevel(LogLevel.FULL). At runtime we can read the annotation and action appropriate. Why is better to use annotations in this case? Because the logging activity is not even a secondary business purpose of our class. Our classes should not be aware of the problems which don't relates to it's business.

The discussion is never ending. For sure there are not rule appliable everywhere. And you always should reevaluate the case on using interface or annotations. That's whay good programmers are valuable. Thought, at least some of the questions, if not answers, will raise in your mind after reading that. Happy choosing!

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!

Java Myths

I spent some years coding in this language and that gave me the opportunity to hear a lot of stupid things about Java. Some bigger than others. There are a lot of hilarious beliefs but I will count here only the most hilarious ones, which I heard myself in the past:

Java is lazy, a hundred times more than C++

False. It is true that Java uses a virtual machine to run, and that can hurts performance. But the differences are now very small. Years ago I read an article exposing a comparison analysis on math computations, which gives almost identical result. Thanks to JIT. Yes, I know that this not cover everything, but gives us a clear hint on that.

This mass rumours smell like Microsoft Good Guys propaganda. On that time they gives us COM and COM+ as being the most advanced way to integrate applications. Maybe just because tehy received a slap over their hands when they tried to modify Java in their own way. Maybe not. But that was the most presius slogan everywhere: virtual machine is bad, binary code integration is the way. Of course, they "forgot" when they put on the table .Net.

Java is not well suited for writing serious applications

There are some important hackers which still believe that Java is a too higher level language to write serious applications. We hear everytime that great hackers use C. And it is said that there are no great programmers which prefers Java.

So I should think that Josh Bloch, Geir Magnusson or Gavin King are some script kiddies, or that Geronimo, JBoss AS or Sun Application Server are some pitty tools on which you can play tetris, at most?

In Java you can write anything, don't have to know anything else

Here we meet other kind of fanatics, the ones which don't like the prevoius point. In my opinion, anybody with medium experience in programming understands that a technology (programming language, library, paradigm, standard) looks at a problem from its own point of view. Here we found Pareto. 80% of the things are done easily, the rest of 20% are possible to be done. Java is no exception, even if nobody had ever count the numbers.

Swing is slow

Is true that Swing is slower than any other native GUI. But when comes to graphic interfaces this is the less critical aspect. The most important thing is how good is the model behind UI. In practice an excelent model underneath the GUI is better native controls which implies a lot of tricky things when writing code. From this point of view, Swing is probably the best.

Who don't believe I invite him to try to implement a rich form with some validation inside in Visual Basic. Or to try to implement a frame with hundreds of controls. Wish him luck.

Java is better/worse than PHP/C#/C/C++/VisualBasic

Finally we meet the last category of fanatics. That kind of comparisons are often unappropriate moslty because are too general or too specific. As a sample comparing Java and PHP is a nonsense. PHP is a rich set of tools which helps creating web applications, so you can compare that with JSP, JSF or something like that.

As a clue for all kind of extremists, there are no programming languages or technologies which solves all the problems. Even if they do, they solves well only some of them. Also, often the reasons behind choosing something or other are far away from classifications and personal affections.

"A fanatic is one who can't change his mind and won't change the subject" -- Winston Churchil

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.