Miles to go …

May 21, 2008

Embeddable GlassFish in Action – Servlet in a Maven project

Filed under: web2.0 — arungupta @ 11:45 pm

Kohsuke announced the embedability of GlassFish v3 – this is really cool! Now you can run GlassFish inside an existing JVM, without the need to start it externally. The API javadocs are available here. This blog explains how to host a Servlet using these APIs and write a simple Maven test to invoke the Servlet – all within the same VM.

The blog creates a Maven project using NetBeans but Maven CLI can be used as well.

In the NetBeans IDE, if Maven plugin is not already installed, then install it using “Tools”, “Plugins”,”Available Plugins”.

  1. Create a new Maven project
    1. Create a new project in NetBeans IDE and select “Maven” types as shown below

      Click on “Next >”.

    2. Take the default “Archetype” as shown:

      Click on “Next >”.

    3. Enter the “Project Name” and “Artifact Id” as shown below:

      and click on “Finish”. The following output is shown in NetBeans Output window:

      This confirms the successful creation of the project.

      The command-line equivalent for all the above steps is:

      mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=org.glassfish.embedded.samples -DartifactId=webtier
  2. Update pom.xml with repositories & dependencies
    1. Expand “Project Files” and open “pom.xml”. Add the following repositories (right after <url>…</url> tags)

      <repositories>
          <repository>
            <id>glassfish-repository</id>
            <name>Java.net Repository for Glassfish</name>
            <url>http://download.java.net/maven/glassfish</url>
          </repository>
          <repository>
            <id>download.java.net</id>
            <name>Java.net Maven Repository</name>
            <url>http://download.java.net/maven/2</url>
          </repository>
        </repositories>
    2. Add the following fragment after “<repositories>” to set the target JDK as 1.5:
      <build>
          <plugins>
            <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-compiler-plugin</artifactId>
              <version>2.0.2</version>
              <configuration>
                <source>1.5</source>
                <target>1.5</target>
             </configuration>
           </plugin>
         </plugins>
       </build>
    3. Add the following dependencies (inside “<dependencies>” and after “</dependency>”)
      <dependency>
            <groupId>org.glassfish.distributions</groupId>
            <artifactId>web-all</artifactId>
            <version>10.0-build-20080430</version>
          </dependency>
          <dependency>
            <groupId>org.glassfish.embedded</groupId>
            <artifactId>gf-embedded-api</artifactId>
            <version>1.0-alpha-4</version>
          </dependency>
  3. Add Servlet class
    1. Right-click on “Source packages”, select “New”, “Java Class…” and enter the value as shown below

      and click on “Finish”.

    2. Replace the template class with the following Servlet
      package org.glassfish.embedded.samples.webtier;

      import java.io.IOException;
      import java.io.PrintWriter;
      import javax.servlet.ServletException;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;

      /**
       * @author Arun Gupta
       */
      public class SimpleServlet extends HttpServlet {

          @Override
          protected void doGet(HttpServletRequest request,
                  HttpServletResponse response)
                  throws ServletException, IOException {
              PrintWriter out = response.getWriter();
              out.println(“Wow, I’m embedded!”);
          }
      }

      This is a simple Servlet class.

  4. Add deployment descriptor (this step could be made optional with possibly a default mapping)
    1. In the “Files” window, expand “src”, “main”, right-click and select “New”, “Folder…” as shown below …

      and give the folder name as “resources” as shown …

      g style="width: 724px; height: 498px;" alt="" src="http://blogs.sun.com/arungupta/resource/images/embed-gf-resources-new-folder-name.png">

      … click on “Finish”.

    2. Using the same mechanism, create a new folder “WEB-INF” in “resources”. Right-click on “WEB-INF” and select “New”, “XML Document…” as shown:

    3. Enter the name as “web” as shown

    4. Click on “Next >”, take defaults and click on “Finish”. Replace the content of generated “web.xml” with the following …
      <?xml version=”1.0″ encoding=”UTF-8″?>
      <web-app version=”2.5″ xmlns=”http://java.sun.com/xml/ns/javaee” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd”>
          <servlet>
              <servlet-name>SimpleServlet</servlet-name>
              <servlet-class>org.glassfish.embedded.samples.webtier.SimpleServlet</servlet-class>
          </servlet>
          <servlet-mapping>
              <servlet-name>SimpleServlet</servlet-name>
              <url-pattern>/SimpleServlet</url-pattern>
          </servlet-mapping>
      </web-app>

  5. Add a new test to invoke the Servlet
    1. In “Projects”, expand “Test Packages” and open “org.glassfish.embedded.samples.webtier.AppTest” as shown:

    2. Add the following fragment at end of the class:
          private final String NAME = “AppTest”;

          public void testServlet() throws Exception {
              int port = 9999;
              GlassFish glassfish = newGlassFish(port);
              URL url = new URL(“http://localhost:” + port + “/” + NAME + “/SimpleServlet”);
              BufferedReader br = new BufferedReader(
                      new InputStreamReader(
                      url.openConnection().getInputStream()));
              assertEquals(“Wow, I’m embedded!”, br.readLine());
              glassfish.stop();
          }

          private GlassFish newGlassFish(int port) throws Exception {
              GlassFish glassfish = new GlassFish(port);
              ScatteredWar war = new ScatteredWar(NAME,
                      new File(“src/main/resources”),
                      new File(“src/main/resources/WEB-INF/web.xml”),
                      Collections.singleton(new File(“target/classes”).toURI().toURL()));
              glassfish.deploy(war);
              System.out.println(“Ready …”);
              return glassfish;
          }

    3. Right-click in the editor window and select “Fix Imports” as shown

    4. Take all the defaults as shown

      and click on “OK”.

    5. The complete project structure looks like:

  6. Run the Test (mvn test)
    1. In Projects window, right-click the project and select “Test” as shown:

    2. The Output window shows the result as:

      Notice how GlassFish v3 started in 598 milliseconds (around 0.5 sec) and all the tests passed.

This is a work in progress and we would like to hear your feedback at users@glassfish and GlassFish Forum.

How are you using GlassFish embeddability ?

Technorati: glassfish v3 embedded servlet netbeans

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • email
  • StumbleUpon
  • Technorati
  • Twitter
  • Slashdot
Related posts:
  1. TOTD #56: Simple RESTful Web service using Jersey and Embeddable GlassFish – Text and JSON output
  2. TOTD #99: Creating a Java EE 6 application using MySQL, JPA 2.0 and Servlet 3.0 with GlassFish Tools Bundle for Eclipse
  3. TOTD #101: Applying Servlet 3.0/Java EE 6 “web-fragment.xml” to Lift – Deploy on GlassFish v3
  4. TOTD #132: Servlets 3.0 in Embedded GlassFish Reloaded – lightweight Java EE 6
  5. TOTD #91: Retrieve JSON libraries using Maven dependency: json-lib

16 Comments »

  1. Wow! This is kinda cool!

    Comment by Jason — May 23, 2008 @ 11:10 am

  2. [Trackback] GlassFish v3 is a modular (OSGi compliant), embeddable (runs in-VM) and extensible (supports non-Java apps) Application Server. The extensible part is demonstrated by deployment of Rails and Grails applications. An example of embeddability is an in-VM…

    Comment by Arun Gupta's Blog — June 26, 2008 @ 6:17 am

  3. Really cool! Do you by chance know how to hook up a datasource to an embedded glassfish instance?

    Comment by Justin Spradlin — June 26, 2008 @ 12:50 pm

  4. [Trackback] I presented on GlassFish at Utah JUG yesterday,&nbsp;slides are available. The topic provided insight into GlassFish v2, the current production version, and GlassFish v3 – the upcoming&nbsp;modular, embeddable &amp; extensible version. There were close…

    Comment by Arun Gupta's Blog — July 18, 2008 @ 7:11 am

  5. [Trackback] Would you like to influence the quality of GlassFish ? The GlassFish Quality Group is starting Community Acceptance Testing – a community based testing of upcoming GlassFish v3. This is your chance to provide an early feedback on stability…

    Comment by Arun Gupta's Blog — August 13, 2008 @ 6:23 am

  6. great post- online forex can use it

    Comment by Forex — October 10, 2008 @ 7:34 am

  7. 2 Justin Spradlin. Yes really cool post

    Comment by scommesse sportive — October 25, 2008 @ 12:39 pm

  8. Goog article. thk

    Comment by forex forum — October 25, 2008 @ 12:44 pm

  9. Interesting. I tried the whole demo. Everything is working fine except my start up is longer than yours. I want to know if I can run the SimpleServlet as well. Let me know if I am not supposed to run the SimpleServlet directly. I tried to run it from NetBeans and here is the msg I got, any ideas. -Thanks! Doris

    Scanning for projects…
    project-execute
    [#process-resources]
    [resources:resources]
    Using default encoding to copy filtered resources.
    [#compile]
    [compiler:compile]
    Nothing to compile – all classes are up to date
    [exec:exec]
    Exception in thread "main" java.lang.NoSuchMethodError: main
    [ERROR]The following mojo encountered an error while executing:
    [ERROR]Group-Id: org.codehaus.mojo
    [ERROR]Artifact-Id: exec-maven-plugin
    [ERROR]Version: 1.1
    [ERROR]Mojo: exec
    [ERROR]brought in via: Direct invocation
    [ERROR]While building project:
    [ERROR]Group-Id: org.glassfish.embedded.samples
    [ERROR]Artifact-Id: webtier
    [ERROR]Version: 1.0-SNAPSHOT
    [ERROR]From file: /Users/dorischen/NetBeansProjects/webtier/pom.xml
    [ERROR]Reason: Result of /bin/sh -c cd /Users/dorischen/NetBeansProjects/webtier && java -classpath /Users/dorischen/NetBeansProjects/webtier/target/classes:/Users/dorischen/.m2/repository/org/glassfish/distributions/web-all/10.0-build-20080430/web-all-10.0-build-20080430.jar:/Users/dorischen/.m2/repository/org/glassfish/embedded/gf-embedded-api/1.0-alpha-4/gf-embedded-api-1.0-alpha-4.jar:/Users/dorischen/.m2/repository/org/glassfish/api/dtds/9.0.2/dtds-9.0.2-resources.jar:/Users/dorischen/.m2/repository/org/glassfish/api/schemas/9.0.2/schemas-9.0.2-resources.jar org.glassfish.embedded.samples.webtier.SimpleServlet execution is: ’1′.
    ————————————————————————
    For more information, run with the -e flag
    ————————————————————————
    BUILD FAILED
    ————————————————————————
    Total time: 1 second
    Finished at: Fri Oct 31 12:29:21 PDT 2008
    Final Memory: 63M/146M
    ————————————————————————

    Comment by Doris — October 31, 2008 @ 12:34 pm

  10. Doris,

    I tried the code listed above again and v3 started in 718 ms. It could be because of a different machine configuration. How much time is it taking on your machine ?

    SimpleServlet is run and invoked from testServlet in AppTest. If you want to show the output form SimpleServlet in a browser, then you need to add sleep() before glassfish.stop() in testServlet().

    Comment by Arun Gupta — November 4, 2008 @ 10:38 am

  11. [Trackback] GlassFish v3 Prelude is a modular and lightweight Web 2.0 development and deployment platform. It has been brewing for the past few months and is now finally available – download here! Read the official Press Release for more details….

    Comment by Arun Gupta's Blog — November 6, 2008 @ 6:36 am

  12. [Trackback] 1400 registrations, 112 sessions, free pizza, a barbecue on Saturday night, raffles and lot more – that is Silicon Valley Code Camp. Jitu, Jiandong, Jacob, and I presented on GlassFish at Silicon Valley Code Camp over the weekend. The…

    Comment by Arun Gupta's Blog — November 11, 2008 @ 4:32 am

  13. [Trackback] GlassFish v3 Prelude is now available! Some of the cool features are: Modularity using OSGi Rapid deployment using retain session data across HTTP redeploys and deploy-on-save Embeddability Dynamic languages and frameworks Faster start up time Integra…

    Comment by Arun Gupta's Blog — November 19, 2008 @ 5:41 am

  14. after adding SimpleServlet.java netbeans says package javax.servlet doesnot exists

    did i missed something or something needs to be configured?

    Comment by jim — March 2, 2009 @ 7:36 pm

  15. SimpleServlet.java netbeans says package javax.servlet doesnot exists…

    Comment by antalya escort — March 8, 2009 @ 2:26 pm

  16. jim, antalya,

    You may have to invoke mvn from CLI first so that it pulls the relevant binaries in your local repository. Then the class is resolved correctly.

    Comment by Arun Gupta — March 27, 2009 @ 3:14 pm

RSS feed for comments on this post. TrackBack URL

Leave a comment

The views expressed on this blog are my own and do not necessarily reflect the views of Oracle.
Powered by WordPress