Standalone client with Glassfish V3

November 4, 2009 Carlos 3 comments

I’m kind of excited with all the functionality packed in JEE6. As you know, Glassfish v3 will be the reference implementation for JEE6 so I wanted to give it a try with the current project I working on. This project is currently being developed using Glassfish v2. It is the typical client-server architecture using a swing standalone client as the front-end.

If you have search for some examples on how to get an standalone client running with Glassfish v3, you should have probably already noticed that there is not such an example. Everywhere you look, you will find examples using JSF2, Servlets or other web based front-ends.

I tried to search for help via Google and all I found was this post at java.net. I think, that post is the main cause of the confusion, at least for me. On the post it is said that you should use the appserv-rt.jar from Glassfish V2 since back then that jar wasn’t provided with Glassfish v3. Additionally, the post says you should use the gf-client.jar shipped with Glassfish v3 because the required jndi.properties file was inside that jar. It was a lot of confusion because 1) back then (Glassfish v3 b55 I think), well, the gf-client.jar wasn’t shipped with any jndi.properties and 2) it wasn’t clear how using a jar from Glassfish v2 should work fine with a jar from Glassfish v3.

So, I installed Glassfish v3 and tried to work around those problems without success. A couple of weeks ago I noticed that the appser-rt.jar was shipped with the new build from Glassfish v3. I thought then that the standalone client was going to work. I was wrong. I got several kinds of exceptions: NamingExceptions, Corba related Exceptions, ClassNotFoundExceptions, etc etc. Until now.

As for Glassfish v3 build 71 I have successfully run an standalone client and I want to share it with you.

Actually, the post at java.net wasn’t all that wrong. All you have to do is put the appserv-rt.jar and gf-client.jar on the classpath of you client and that’s it. Fortunately this time, both jars are shipped with Glassfish v3. I tested it with a client running on the same host as the server, so I didn’t have to configure anything in the jndi properties.

You should find the appserv-rt.jar under {yourGlassfishV3Dir}/glassfish/lib and the gf-client.jar under {yourGlassfishV3Dir}/glassfish/modules

Getting the context is as straightforward as:

InitialContext ctx=new InitialContext();

Then just do the lookup:

MyRemoteInterface myInterface=(MyRemoteInterface) ctx.lookup("com.test.MyRemoteInterface");

And that’s it.

Now, if you want to try some new JEE6 features with your EJB, you will have to add javax.ejb.jar to your classpath in order to be able to use annotations such as @Singleton. The javax.ejb.jar is also to be found under {yourGlassfishV3Dir}/glassfish/modules

I would also like to test brand new features like CDI aka JSR-299 and Bean Validation. I haven’t figured out which jars I should add to the classpath but stay tuned for the next posts.

I hope this information is helpful for you. If you have any suggestion or question, please leave a comment.

Categories: Java Tags:

Jar Hunting

November 19, 2008 Carlos Leave a comment

Probably many of you have done “jar hunting” without even noticing it. So I define Jar Hunting as follows:

Jar Hunting is the continuously search for jars due to the great number of dependencies a project, a class or a framework has.

In my case, it was related to the astonishing (sarcasm of course) Weblogic Server 10.

It turns out that for you to be able to generate the required artifacts for a Webservice, you need to run an ant-task. The infamous: jwsc from the class: weblogic.wsee.tools.anttasks.JwscTask.

It is incredible (this is not sarcasm) how many dependencies this task has. If you have your development environment independent from Weblogic (Weblogic provides “tools”, which are an installation of Eclipse + some plug-ins), then you are out of luck to deal with those dependencies. But even if you use the development environment of Weblogic things are not easier.

The big problem is that you cannot find anywhere (at least I couldn’t) any documentation about which jars are necessary for the Ant-task to run. So, you have to run the Ant-Task and wait for the ClassNotFoundException, then look for that class in all the jars that come with Weblogic (they are more than 80 jars). When you find the class, you add it to your lib / classpaht, you run the task again and the story repeats again and again. At the beginning I thought it was just a matter of 3 or 4 jars. It turns out it is about 20 jars. I searched for the first 5 classes manually (internet, Weblogic environment, etc.) but then I got desperate.

So, without further introduction: the JarHunter ™. It is a simple python script that searches for a class within a directory full of jars when it finds the class it tells you in which jar it is.

Please notice that I am not proficient in python. Feel free to make suggestions

import zipfile
import sys
import os

if len(sys.argv)==1 or len(sys.argv)==2:
    print "Usage: JarHunter dirToSearch fileToSearch"
    sys.exit(0)

if  not os.path.isdir(sys.argv[1]):
    print sys.argv[1] + " is not a directory. The search will be performed in the current directory"
    dirToSearch =os.getcwd()
else:
    dirToSearch=sys.argv[1]

fileToSearch=sys.argv[2]

print "Searching for: " + fileToSearch + " in dir: " + dirToSearch
files=sorted([ f for f in  os.listdir(dirToSearch) if os.path.isfile(dirToSearch + os.path.sep + f)])
for file in files:
    if file.find(".jar") > -1:
        absolutePath=os.path.join(dirToSearch, file)
        print "Searching in " + absolutePath
        z=zipfile.ZipFile(absolutePath,"r")
        for filename in z.namelist():
            if filename.find(fileToSearch) > -1:
                print "found Woohooo\n"
                print "It is here: " + absolutePath
                sys.exit(0)
print "Sorry, nothing found. Now, who would like a cookie?"

If you are wondering which jars they are, here, you can take a look:

jardependencies

Nevertheless I haven’t been able to deploy a working Webservice on Weblogic at the moment. If someone has done it successfully please tell me HOW!!!

Categories: python Tags:

Old technology, new technology

October 1, 2008 Carlos Leave a comment

I have worked on a couple of Java projects that have been around for almost 10 years! When you thing about it, 10 years ago there were no EJB, Java EE, JSF, Struts, Hibernate or anything like that (No Wikipedia either). Those were the days where a developer had to fight “naked” against the problems he faced back then.

If you wanted to map the results from the database to an object! Well, you had to do it with your bare hands. Today, it is as simple as to annotate a class and you don’t even have to worry about transactions. If you wanted to access a remote object, you had to use plain old CORBA. Today, well, you just simply annotate a class (or JNDI look up in the worst scenario). The point is, the frameworks and technologies have evolved to the point that we take many things for granted and that’s good because that allows the developer to focus on the functionality of the system he is working on.

Nevertheless, there were many companies developing interesting projects back then and those companies had to come up with their own technologies in order to make the developers’ lives a little bit easier. That’s the case of the customer I’m working with.

I think what my customer did is really amazing. They developed their own kind-of-application-server using tomcat as the core and everything is there: transactions, thread-pooling, messaging and ORM! and all of these before those techologies went mainstream. I mean, to have such technologies in 1999 seamleasly functioning in your system was a real accomplishment. Of course they didn’t have those technologies available from the very beginning but were developed gradually.

As for today they have nice things too even compared with current technolgies. Since the system is the typical server-client application they have also a framework to implement user interfaces. They have a nice binding framework and some Swing components that really ease the user interface development process. They even developed some eclipse plug-ins to increase productivity and make the development less error prone and the architecture of the client framework is really well thought (i.e. the managing of events and communication between components, the later is performed with almost zero coupling through DI).

I can only imagine the big investment both intellectual and monetary they have made in their framework. Several technolgies implemented in the framework are the results of doctorate’s thesises (that’s quite common in Germany even in very small companies so far I know).

However, as many things in life, there are some drawbacks and I’m not talking about bugs – well there are a couple of bugs right now that make want to punch the monitor once a week.

As I mentioned, they have implemented very good technology that wasn’t available at the end of the 90s. The problem is: we are not in 1999 anymore. I don’t quite understand how the people responsible for the architecture of the framework had just overlook some good things like well designed ORM Frameworks, Spring or more up-to-date technologies like EJB.

I don’t think they just ignored those technolgies. I can be sure they are really aware of them. Then why don’t they use them? I don’t mean they have to throw everything they had done away. I’m quite sure they could have probably integrated many of the current frameworks with their own framework. Actually, they have already done it. As I said earlier, they use dependency injection to avoid coupling among components in the UI. In the backend, however, it’s like if time had remained still. It just hurts to see how complicated is to retrieve information from the database and pass it all the way up through the layers and now that they want to do everything SOA like all is turning gradually into a mess.

I really don’t know why the things are like this in the backend. May be they have very valid reasons I’m not aware of. The weirdest thing of all is that they use Java 6 to compile and run everything but the code is written JDK 1.4 style – there are no annotations, no generics, no autoboxing, etc. They even have their own versions of Collections that check the class type of the elements “automatically” like rudimentary generics. Not to mention they have their own versions of Integer and Date (ok, java.util.Date is justifiable, for me java.util.Date is a long decorator ;-) ).

Anyway, everytime I have to do something in the backend I feel like I’m back in time and you thought a time machine couldn’t be invented.

Categories: Java, software design

Model Instances

September 29, 2008 Carlos Leave a comment

When writing applications you usually have the model, the business logic and some kind of views for the user to interact with your application. So you have the venerable MVC pattern and everything is perfect.

You have your model that can be accessed by the views to be displayed. You have the controller that manages the views and dispatches/delegates business logic.

But that is just too abstract. Everything looks fine when it is abstract. You first encounter the problem when you face the details.

One of these “problems” is as simple as the instantiation of the model’s object. Not the instantiation per se but WHERE the instances are created.

I will explain myself further with the following example.

Suppose you write an online store application in Java. You will probably use JSF/Struts for the View and JPA/Hibernate for the model. In the business layer there are much more options depending on the size and/or requirements of the application. But let’s say we use EJB 3.0

As you may guess, you have a class Product which misteriously represents a… product.

So, where do you create an instance of the class product? In the view? the view being a managed bean in JSF. Through a EJB? Or you have a centralized way to do that, like a Factory.

Let’s explore the three options a little bit.

Instantiation in the View

Yes, you don’t need nothing but a simple call like: “new Product();” in order to create a new Product. You first need and instance of it, so that you can later populate it with data. So it seems it makes sense to just create the instance in the managed bean, populate it with data using some binding and then just give the instance to an EJB in order to save it.

To be honest, although it is very straightforward, I don’t feel well about it. I feel as if I were violating some indisputable principle here. So, the other possible solution would be:

Let’s the business logic create the model

That is, an EJB creates the instance and returns it to the view. Like a kind of pimped factory and it just fits very well if you need some business logic to create an instance of a Product. Mmmh, but then I think, a call to an EJB just to create a simple and plain instance? Ok, may be it is not too bad, since both the Managed bean and the EJB are on the same server. But what if later on we decide to write a remote client?

A factory could do that

So we arrive at the conclusion that a normal factory, without the EJB stuff, would suffice. But then you have may be 15 or 20 objects that represent your model. The factory would be kind of big to say the less.

What about a sophisticated over-engineered solution like DI to create and assign a simple instance? Not that DI is an over-engineered solution, but you would have to wire everything up in order to assign the instance of the model to the instance of your managed bean.

At the end, I think the answer is the typical: it depends! It depends on how big your application will be. If the application will grow into a clustered environment or if your application is just a simple web app that requires some EJB-stuff (like transaction management).

Anyway, I am a little bit wary about the direct instantiation in the view related objects. I don’t know. I just have a bad feeling about it. Like you know it is wrong, but you do it anyway. The main problem with this is that you, more often than not, do not know how big the application will be. If you do the instantiation in the view and your application grows and it grows fast, then you will have a mess there with instance everywhere and it will be difficult to change the implementation of one of the model’s classes without doing a lot of refactoring. Although, you normally wont’ change the implementation of a domain object. Unitl now I have never done that in any of my projects. By changing the implementation I mean replacing the class with a new one.

So you see, it is not as easy as one could think. We are now living an era of converting anti-patterns into patterns and viceversa.

Anyway I think a centralized factory would be good from the beginning for a mid-size project. It could also help when testing the app. You should must avoid EJBs as a factories otherwise you will be locked to one technology. What happens if you must use Spring instead of EJB later as a requirement? Well, what it will happen is, that you will have to refactor your app in every place you get a new instance of the model.

If you still require an EJB to instantiate an object (may be you need more information to create an instance and this information must be fetched from the database which are normally accessed by an EJB through the EntityManager) then retrieve first all the information you need through the EJB and then pass that information to the factory.

Ah and believe me, I have seen the four scenarios described above and the worst of all is that they were used in the wrong way.

Categories: Java, software design

Amateurish software design

September 29, 2008 Carlos Leave a comment

This is my first blog’s post. I just want to point out an error I have seen in some of the projects I have worked on.

The Singleton that is not a Singleton

Well, what can you expect when you see a class that is supposed to be a Singleton and the class is declared as follows?:

public class MySingleton
{

    private static MySingleton INSTANCE;

    public static MySingleton getInstance()
    {
    if(INSTANCE==null)
    {
        INSTANCE=new MySingleton();
    }
    return INSTANCE;
    }
}

As you can see, there are two serious problems with the above implementation:

  1. The class does not have a private constructor, which means, anyone can create an instance just by calling “new MySingleton();”
  2. This is a classic one: The creation of the “single” instance in the getInstance method. It is not ensured that it will create one and only one instance of the object.

The first problem is trivial to solve. Just add a private constructor:

private MySingleton() { }

The second problem could be more tricky. One of the possible attempts could be to do the following:

public static synchronized MySingleton getInstance() {
    if(INSTANCE==null) {
        INSTANCE=new MySingleton();
    }
    return INSTANCE;
}

The synchronized keyword can actually solve the problem of having two threads creating 2 instances. However, it comes with a little penalty in performance. If the getInstance method is called frequently the performance could suffer.

But then things get worse, when someone comes up with the following solution:

public static MySingleton getInstance() {
    if (INSTANCE == null) {
        synchronized (INSTANCE) {
        INSTANCE = new MySingleton();
        }
    }
    return INSTANCE;
 }

What we have here is the typical double-checked locking. While it will ensure that there is only one instance of the class, it could lead to another problems caused by improper initialization. As the wikipedia link states, in Java 5 that can be addressed by adding the volatile keyword to the field declaration. So you have:

public class MySingleton
{
    private static volatile MySingleton INSTANCE;

    private MySingleton(){}

    public static MySingleton getInstance() {
    if (INSTANCE == null) {
        synchronized (INSTANCE) {
        INSTANCE = new MySingleton();
        }
    }
    return INSTANCE;
    }
}

So far, it seems that a lot of work must be done to write a Singleton. BUT there is a simple way. Just do the following:

public class MySingleton {
private static final  MySingleton INSTANCE=new MySingleton();
private MySingleton(){}
public static MySingleton getInstance() {
return INSTANCE;
}
}

Yes! That’s all you have to do. No syncrhonization is necessary and it is done with less lines of code. The seasoned Java developer will know that the latest solution is actually a recommendation made by Joshua Bloch

You think that’s a novice error but, as I mentioned at the beginning of this post, I have seen those kind of errors in the projects I have worked on and the people who wrote those classes weren’t beginners. More surprising is that when I found the mistake and then told to one of the developers that the class was wrong, he neither could see where the error was nor cared about it.

Now I can understand why my boss always complains about how hard it is to find good developers.

Categories: Design Patterns, Java