Skip to main content

Embeddable GlassFish in Action - Servlet in a Maven project

Posted by arungupta on May 22, 2008 at 6:15 AM PDT

Kohsuke
announced the href="http://weblogs.java.net/blog/kohsuke/archive/2008/04/glassfish_v3_ju.html">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 href="https://embedded-glassfish.dev.java.net/nonav/gf-embedded-api/apidocs/">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



      src="http://blogs.sun.com/arungupta/resource/images/embed-gf-create-maven-project.png">



      Click on "Next >".
    2. Take the default "Archetype" as shown:



      src="http://blogs.sun.com/arungupta/resource/images/embed-gf-create-maven-project-archetype.png">



      Click on "Next >".
    3. Enter the "Project Name" and "Artifact Id" as shown below:



      src="http://blogs.sun.com/arungupta/resource/images/embed-gf-create-maven-project-name-location.png">



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



      src="http://blogs.sun.com/arungupta/resource/images/embed-gf-create-maven-project-success.png">



      This confirms the successful creation of the project.



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


      cellpadding="2" cellspacing="2">
      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)


      cellpadding="2" cellspacing="2">
      <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:


      cellpadding="2" cellspacing="2">
      <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>")


      cellpadding="2" cellspacing="2">
      <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



      src="http://blogs.sun.com/arungupta/resource/images/embed-gf-servlet-create.png">



      and click on "Finish".
    2. Replace the template class with the following
      Servlet


      cellpadding="2" cellspacing="2">
      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 ...



      src="http://blogs.sun.com/arungupta/resource/images/embed-gf-resources-new-folder.png">



      and give the folder name as "resources" as shown ...



      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:



      src="http://blogs.sun.com/arungupta/resource/images/embed-gf-resources-new-xml.png">
    3. Enter the name as "web" as shown



      src="http://blogs.sun.com/arungupta/resource/images/embed-gf-resources-webxml.png">
    4. Click on "Next >", take defaults and click on
      "Finish".
      Replace the content of generated "web.xml" with the following ...


      cellpadding="2" cellspacing="2">
      <?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:



      src="http://blogs.sun.com/arungupta/resource/images/embed-gf-apptest-open.png">
    2. Add the following fragment at end of the class:


      cellpadding="2" cellspacing="2">
       
        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



      src="http://blogs.sun.com/arungupta/resource/images/embed-gf-apptest-fix-imports.png">
    4. Take all the defaults as shown



      src="http://blogs.sun.com/arungupta/resource/images/embed-gf-apptest-fix-all-imports.png">



      and click on "OK".
    5. The complete project structure looks like:



      src="http://blogs.sun.com/arungupta/resource/images/embed-gf-project-structure.png">
  6. Run the Test (mvn test)
    1. In Projects window, right-click the project and select
      "Test" as shown:



      src="http://blogs.sun.com/arungupta/resource/images/embed-gf-run-test.png">
    2. The Output window shows the result as:



      src="http://blogs.sun.com/arungupta/resource/images/embed-gf-run-test-result.png">



      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 href="mailto:users@glassfish.dev.java.net">users@glassfish
and href="http://forums.java.net/jive/forum.jspa?forumID=56&start=0">GlassFish
Forum.



How are you using GlassFish embeddability ?


Technorati: href="http://technorati.com/tag/glassfish">glassfish
v3 href="http://technorati.com/tag/embeddable">embeddable
servlet
netbeans

Related Topics >>