Saturday 1 October 2011

Creating Hello World in Netbeans IDE 7.0.1 and Glassfish 3.1

A simple attempt of mine to create a HelloWorld Enterprise JavaBean (EJB) in Netbeans 7.0.1. and Glassfish 3.1.

Primary use is for me to remember how to do this, and what needs to be configured to make it work.

Creating the JEE Application

First, start up your brand new Netbeans 7.0.1. and select a new project.

Select Java Enterprise Applications.





It will start creating the new project. You will end up with three new projects.


First of the projects, HelloWorldEE is the EAR file, which is a jar-file that is to be deployed to the glassfish server. It consists of two jar-files, that are created by the other two projects.

Second is HelloWorldEE-ejb, the project that is to contain our new Enterprise Java Beans (EJB).

Third is HelloWorldEE-war, the project that is to contain all the web stuff, like jsp pages, servlets, and what have you.

Let's create our first Enterprise Java Bean.



Here I've selected a Local interface for now. You'll notice two java files are generated, one containing the local interface and one containing the implementation.

We will add a business method.




Change the helloWorld method to return the string "Hello, world.". Now, in order to test it, we are going to create a java client that connects to the bean using Corba. However, for this to work, the interfaces need to be Remote, and not Local. Change the source code accordingly.

Your source code should look something like this:

package mrbear.beans;

import javax.ejb.Remote;

/**
 * The remote interface to my bean.
 * @author Mr. Bear
 */

@Remote
public interface MyFirstBeanRemote {

    /**
     * Returns the string "Hello, world."
     * @return String with text.
     */

    public String helloWorld();
    
}
package mrbear.beans;

import javax.ejb.Stateless;

/**
 * My first enterprise java bean.
 * @author Mr. Bear
 */

@Stateless
public class MyFirstBean implements MyFirstBeanRemote {

    @Override
    public String helloWorld() {
        return "Hello, world.";
    }

}

In the war project, a jsp page is automatically generated upon creation of the project, and it will help to check if the ear file was successfully deployed.

Try and "run" the project HelloWorldEE. A GlassFish 3.1 server will be started by Netbeans, the ear file deployed, and a webpage will be visible at url http://localhost:8080/HelloWorldEE-war/. It should show "Hello world!". Now, make no mistake! This is not our bean! This is the jsp page that is generated automatically in the war project. It shows that at least the ear file was successfully deployed.

The jsp file can be found at HelloWorldEE/HelloWorldEE-war/web/index.jsp

In your output window (HelloWorldEE(run)), you should see something like this:

Starting GlassFish Server 3.x
GlassFish Server 3.x is running.
Initial deploying HelloWorldEE to /home/mrbear/NetBeansProjects/HelloWorldEE/dist/gfdeploy/HelloWorldEE
Completed initial distribution of HelloWorldEE
Initializing...
Browsing: http://localhost:8080/HelloWorldEE-war

In the GlassFish log, you should see something like this:

INFO: Portable JNDI names for EJB MyFirstBean : [java:global/HelloWorldEE/HelloWorldEE-ejb/MyFirstBean, java:global/HelloWorldEE/HelloWorldEE-ejb/MyFirstBean!mrbear.beans.MyFirstBeanRemote]
INFO: WEB0671: Loading application [HelloWorldEE#HelloWorldEE-war.war] at [HelloWorldEE-war]
INFO: HelloWorldEE was successfully deployed in 5,409 milliseconds.

Pay special attention to the JNDI names used for the EJB MyFirstBean. We'll need those to create our HelloWorld java client.

Your bean should now be alive and kicking! You can check this by browsing to the administration console of your Glassfish server at http://localhost:4848/.


Creating the Java Client

Time to create a new project. Create a new project, and select Enterprise Application Client.





You do need to add a dependency in the HelloWorldClient to the HelloWorldEE-ejb (which resides in the HelloWorldEE) by selecting "add Project" in the Compile tab of "Libraries" of the Helloworld java client project.


Your java client source code in the main method should look something like this:

package helloworldclient;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import mrbear.beans.MyFirstBeanRemote;

/**
 * The client for connecting to the MyFirstBean bean.
 * @author Mr. Bear
 */

public class Main {

    /**
     * Main method, called when executing this program.
     * @param args the command line arguments
     */

    public static void main(String[] args) {
        System.out.println("Starting...");

        System.out.println("Establishing connection to the bean...");
        MyFirstBeanRemote example;
        try {
            InitialContext initialContext = new InitialContext();

            // INFO: Portable JNDI names for EJB MyFirstBean : 
            // java:global/HelloWorldEE/HelloWorldEE-ejb/MyFirstBean
            example = (MyFirstBeanRemote) initialContext.lookup("java:global/HelloWorldEE/HelloWorldEE-ejb/MyFirstBean");
            System.out.println("Calling method on the bean...");
            System.out.println("     Result: " + example.helloWorld());
        } catch (NamingException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            System.exit(1);
        }
        System.out.println("Exiting...");

    }

}

When executing said project (remember, the Glassfish is still running), you can see the following in the log of Glassfish:

INFO: ACDEPL103: Java Web Start services started for the app client HelloWorldClient (contextRoot: /HelloWorldClient)
INFO: HelloWorldClient was successfully deployed in 85 milliseconds.

And the log of your java client, should show the following indicating success:

Copying 1 file to /home/mrbear/NetBeansProjects/HelloWorldClient/dist
Copying 2 files to /home/mrbear/NetBeansProjects/HelloWorldClient/dist/HelloWorldClientClient
Warning: /home/mrbear/NetBeansProjects/HelloWorldClient/dist/gfdeploy/HelloWorldClient does not exist.
Starting...
Establishing connection to the bean...
Calling method on the bean...
Result: Hello, world.
Exiting...

Now this is just the basics, but it is always good to start from a simple example that works, and then branch out from there. Good luck!

I plan to keep this article updated with new versions of software that are issued, and with new expansions, like adding an ORM to your little bean.

Remarks

I've chosen for Netbeans 7.0.1, as there is an issue with automatic downloading of Glassfish 3.1 in Netbeans 6.9

In order for the java client to connect to the Glassfish when the Glassfish is not conveniently started by the Netbeans on your local machine, you need to change the settings used to connect to the remote host. This can be done programmatically using a Properties java hashmap thing, or you can use the dreaded jndi.properties file. I guess that last one could use a blog entry all on its own. [1]

I've not mentioned anything about setting up Glassfish on your local machine, as Netbeans basically does all that for you. You just need to select the little checkbox with "Download Glassfish" when creating a new Java EE Application Project.

It is a pleasure to work with Netbeans and Glassfish, basically because the two are nicely intertwined and setting up the environment is almost a point-and-click experience and speedily done. It makes it possible to spend more time developing and less time battling frameworks, fixing dependencies and installing jar-files.


Update


Ever since the coming of EJB 3.1, it is no longer necessary to have a WAR archive for your web related things, a JAR archive for your Enterprise Java Beans, and an EAR archive containing these two. If you are not interested in keeping these two strictly apart (in the name of modularization), you can just toss all your EJBs into the same WAR and deploy that WAR in EJB 3.1.

It simplifies life tremendously.

References


[1] How do I access a Remote EJB component from a stand-alone java client?
http://glassfish.java.net/javaee5/ejb/EJB_FAQ.html#StandaloneRemoteEJB

6 comments:

  1. Great work, Thanks

    ReplyDelete
    Replies
    1. Thank you!

      I like to point to the Update section, as it simplified my life muchly. Who needs EARs nowadays?

      Delete
  2. Hi, I notice that there is a warning in your last window:

    Warning: /home/mrbear/NetBeansProjects/HelloWorldClient/dist/gfdeploy/HelloWorldClient does not exist.

    It seems that your program was not affected by this warning, however could please roughly explain what it means? Because I have a program has a similar warning and stops working after that...

    ReplyDelete
  3. Thanks!
    I am not sure if I understood why MyFirstBeanRemote says "Remote" when the we have selected the "Local" interface.

    ReplyDelete
    Replies
    1. That seems to be faulty on my side. It should say "Local".

      Delete
  4. Sir ! How to change JNDI and other Application specific mappings existing in ejb-jar.xml etc, if I want..?

    ReplyDelete