Thursday Feb 18, 2010

TOTD #124: Using CDI + JPA with JAX-RS and JAX-WS

This is a follow up blog to TOTD #120 and TOTD #123. These two blogs together have created a simple Java EE 6 application and showed the following features so far:

  • No-interface view for EJB
  • EJBs packaged in a WAR file
  • Optional "faces-config.xml" for Java Server Faces
  • FacesServlet registered using Servlet 3.0 programmatic registration APIs
  • Java Server Faces navigation rules using convention-over-configuration
  • Optional "web.xml" for Servlets 3.0
  • Add database access using Java Persistence API 2.0
  • Show type-safe Criteria API from JPA 2.0
  • Use Context & Dependency Injection for JSF managed beans
  • Add Ajax effects from Java Server Faces 2.0
  • Add Bean Validation to the JSF managed bean

GlassFish v3 is the Java EE 6 Reference Implementation and comes bundled with a complete SOAP Web services stack (Metro/JAX-WS) and a RESTful stack (JAX-RS/Jersey). This blog will update the previously created Maven project with:

  • A SOAP Web service using JAX-WS
  • A RESTful Web service using JAX-RS
  • Use Context & Dependency Injection with JAX-WS and JAX-RS
  • Query the database using JPA 2 based upon criteria from the Web service invocation

Lets get started!

  1. Use the Maven project from TOTD #123 and update the directory structure as follows:
    src
    src/main
    src/main/java
    src/main/java/org
    src/main/java/org/glassfish
    src/main/java/org/glassfish/samples
    src/main/java/org/glassfish/samples/ActorResource.java
    src/main/java/org/glassfish/samples/RESTApplication.java
    src/main/java/org/glassfish/samples/SakilaBean.java
    src/main/java/org/glassfish/samples/SimpleBean.java
    src/main/java/org/glassfish/samples/SimpleEJB.java
    src/main/java/org/glassfish/samples/SimpleServlet.java
    src/main/java/org/glassfish/samples/SOAPService.java
    src/main/resources
    src/main/webapp
    src/main/webapp/index.jsp
    src/main/webapp/index.xhtml
    src/main/webapp/sakila.xhtml
    src/main/webapp/show.xhtml
    src/main/webapp/WEB-INF
    src/main/webapp/WEB-INF/beans.xml
    src/main/webapp/WEB-INF/web.xml
    

    The changes are:
    • "ActorResource.java" is added for the RESTful representation of Actor table.
    • "SOAPSevice.java" is added to invoke the SOAP-based Web service.
    • "SakilaBean.java" is updated to query the database for an Actor identified by "id".
  2. The updated files are explained below.
    • A new method is added to SakilaBean.java as shown below:
       public Actor findActorById(int id) {
          EntityManager em = emf.createEntityManager();
      
          CriteriaBuilder cb = emf.getCriteriaBuilder();
          CriteriaQuery<Actor> criteria = cb.createQuery(Actor.class);
      
          // FROM clause
          Root<Actor> actor = criteria.from(Actor.class);
      
          // SELECT clause
          criteria.multiselect(actor.<Short>get("actorId"),
                               actor.<String>get("firstName"),
                               actor.<String>get("lastName"));
      
          // WHERE clause
           criteria.where(cb.equal(actor.<Short>get("actorId"), id));
      
          Query q = em.createQuery(criteria);
          ((org.eclipse.persistence.jpa.JpaQuery)q).getDatabaseQuery().dontMaintainCache();
      
          return (Actor)q.getResultList().get(0);
      }
      

      This method queries the database for an actor by his id and uses the typesafe Criteria API to achieve the purpose. The FROM, SELECT, and WHERE clause are highlighted in the code. A cast to EclipseLink specific class is required because of the bug #303205.
    • SOAPService.java
      package org.glassfish.samples;
      
      import javax.inject.Inject;
      import javax.jws.WebService;
      import sakila.Actor;
      
      @WebService
      public class SOAPService {
          @Inject SakilaBean bean;
      
          public String sayHello(int id) {
              Actor a = bean.findActorById(id);
              return "Hello " + a.getFirstName();
          }
      }
      

      The key points in the code are:
      • Standard JAX-WS annotations from "javax.jws.\*" package are used to represent the Web service.
      • The Web service has only one method "sayHello" that concatenates the string "Hello" with the first name of "Actor" identified by "id".
      • No deployment descriptor modifications are required to publish this Web service.
      • "SakilaBean" is injected using @Inject annotation and used to query the database. This allows to encapsulate all the database details in one class and injected in a typesafe manner.
    • RESTApplication.java
      package org.glassfish.samples;
      
      import javax.ws.rs.ApplicationPath;
      import javax.ws.rs.core.Application;
      
      @ApplicationPath("/sakila")
      public class RESTApplication extends Application {
      }
      

      This is a marker class to inform Jersey of the root resource to be registered. By default, all classes with @Path and @Provider annotations are included. It also specifies the base path at which all resources are accessible.

      An alternative to this class is to specify the required information in "web.xml" as:
      <servlet>
           <servlet-name>Jersey Web Application</servlet-name>
           <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
       </servlet>
      
       <servlet-mapping>
           <servlet-name>Jersey Web Application</servlet-name>
           <url-pattern>/sakila/\*</url-pattern>
       </servlet-mapping>
      

      So only one of RESTApplication.java or changes in "web.xml" are required.
    • ActorResource.java
      package org.glassfish.samples;
      
      import javax.enterprise.context.RequestScoped;
      import javax.inject.Inject;
      import javax.ws.rs.GET;
      import javax.ws.rs.Path;
      import javax.ws.rs.Produces;
      import javax.ws.rs.PathParam;
      import sakila.Actor;
      
      @Path("/actor/{id}")
      @RequestScoped
      public class ActorResource {
          @Inject SakilaBean sakila;
      
          @GET
          @Produces("application/json")
          public Actor getActor(@PathParam("id") int id) {
              return sakila.findActorById(id);
          }
      }
      
      The key points in the code are:
      • Standard JAX-RS annotations from "javax.ws.rs" package are used to represent the RESTful resource.
      • "getActor" method is invoked when the resource is accessed using HTTP GET.
      • The resource is accessible at "/actor/{id}" URL where "{id}" is mapped to the "id" parameter of "getActor" method.
      • SakilaBean is injected in a typesafe manner using @Inject annotation. This bean is then used to query the database using the "id" parameter.
      • "getActor" method produces JSON representation, as defined by the "@Produces" annotation. This is easily achieved by updating our Persistence Unit (PU) created in TOTD #122 and adding "@javax.xml.bind.annotation.XmlRootElement" as the class level annotation on "sakila.Actor" class. Make sure to install the updated PU to your local Maven repository.

Package and deploy the application as:
mvn clean package
./bin/asadmin deploy --force=true ~/samples/javaee6/simplewebapp/target/simplewebapp-1.0-SNAPSHOT.war

Now the SOAP web service is accessible at "http://localhost:8080/simplwebapp-1.0-SNAPSHOT/SOAPServiceService" and looks like:


Notice, the URL in your case may be different if the Web service class name was different. The default URL is "http://<HOST>:<PORT>/<CONTEXT ROOT><WEB SERVICE CLASS NAME>Service".

This Web service can be easily tested by using the in-built tester accessible at "http://localhost:8080/simplwebapp-1.0-SNAPSHOT/SOAPServiceService?tester" and looks like:

The WSDL describing the Web service can be seen by clicking on the "WSDL File" link. The Web service method can be invoked by entering a value ("id" of the Actor) in the text box and clicking on "sayHello" button. Here is a sample run:

Clicking on "Submit" invokes the Web service which then uses the injected "SakilaBean" to query the database using the parameter specified. The first name from the response from the database is then extracted, concatenated with the string "Hello" and returned as Web service response.

The RESTful resource is accessible at "http://localhost:8080/simplwebapp-1.0-SNAPSHOT/sakila/actor/5" and looks like:

As in the SOAP-based Web service, the "5" in the URL is mapped to a parameter in the "ActorResource.java", the injected "SakilaBean" is then used to query the database and returns the JSON representation. Specifying a different number in the URL will show the RESTful JSON representation for that particular actor.

More Java EE 6 features will be covered in subsequent blogs. Are you interested in any particular ones ?

Technorati: jaxws metro webservices jaxrs rest jersey glassfish v3 cdi jsr299 weld

Monday Feb 01, 2010

Screencast #29: Web service using NetBeans 6.8 and GlassFish v3 (Accessing database in business method)

GlassFish v3 comes bundled with Metro - a secure, reliable, transactional, and .NET interoperable Web services stack. Metro is compliant with JAX-WS and provides additional quality of service attributes that can be easily enabled using NetBeans IDE.

This blog contains a screencast that shows how to create a simple Web service using NetBeans 6.8, implement the business logic by accessing a database table using Java Persistence API, and deploy on GlassFish v3.

Please post your questions to users@glassfish.dev.java.net.

Several other screencasts on GlassFish v3and related topics are available here.

Technorati: netbeans jax-ws metro webservice glassfish jpa database

Tuesday Jan 12, 2010

TOTD #117: Invoke a JAX-WS Web service from a Rails app deployed in GlassFish

A user on GlassFish Forum tried invoking a JAX-WS Web service from a Rails application and faced some issues. This Tip Of The Day (TTOD) will discuss the different approaches and shows their current status.

A Rails app can be deployed on GlassFish in 3 different ways:

  1. Directory Deployment in GlassFish v3 Server - TOTD #72 explains how to deploy a trivial Rails application (with just a scaffold) on GlassFish v3 server. Even though the blog uses a Rails application, any Rack-based application can be deployed on the server. This server is also the Reference Implementation for Java EE 6 and can also run Grails and Django applications.
  2. Directory Deployment using light-weight GlassFish Gem - GlassFish Gem is a light-weight version of the full-blown server and is stripped to run, just like the server, any Rack-based application such as Merb, Rails, and Sinatra. TOTD #70 shows how to deploy the same application using GlassFish Gem.
  3. WAR file in GlassFish v2.x or v3 - TOTD #73 explains how to deploy a Rails application as WAR file on GlassFish v2. The JNDI connection pooling part of the blog may be skipped to simplify the steps but the concepts are still valid. TOTD #44 shows how to do JNDI connection pooling for GlassFish v3. As GlassFish v2 has in-built support for session replication, TOTD #92 demonstrate how Rails application can leverage that functionality.

Now lets get to the issue reported by the user using these 3 deployment models.

First, lets deploy a simple Web service endpoint and generate a JAR file of the client-side artifacts:

  1. This blog will use a simple Web service as defined in screencast #ws7. The Web service endpoint looks like:
    package server;
    
    import javax.jws.WebService;
    
    /\*\*
     \* @author arungupta
     \*/
    @WebService()
    public class HelloService {
     public String sayHello(String name) {
     return "Hello " + name;
     }
    }
    

  2. Generate Web service client-side artifacts as:
    ~/samples/v3/rails/webservice/tmp >wsimport -keep http://localhost:8080/HelloWebService/HelloServiceService?wsdl
    parsing WSDL...
    
    
    generating code...
    
    
    compiling code...
    
  3. Create a Web service client jar file as:
    jar cvf wsclient.jar ./server
    

Now lets write a Rails application and invoke this Web service:

  1. Create a simple Rails application as:
    jruby -S rails webservice
    

    Optionally you may specify "-d mysql" to use MySQL database. Or better un-comment the following line:
    # config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
    

    in "config/environment.rb" as no database interaction is required.
  2. Create a controller and view as:
    jruby script/generate controller home index
    
  3. Update the Controller in "app/controllers/home_controller.rb" as:
    include Java
    
    class HomeController < ApplicationController
     def index
     service = Java::server.HelloServiceService.new
     port = service.getHelloServicePort
    
     @result = port.sayHello("Duke")
     end
    
    end
    
  4. Change the View in "app/views/home/index.html.erb" as:
    <h1>Home#index</h1%gt;
    <p>Find me in app/views/home/index.html.erb</p>
    
    <%= @result %>
    

Now lets deploy this Web service using the 3 different deployment models mentioned above.

GlassFish v3 allows a directory-based deployment of Rails applications. This application needs to locate the Web service client classes. The "wsclient.jar" can be copied to the "lib" directory of Rails application ("webservice/lib" in our case), "domains/domain1/lib/ext" or "JRUBY_HOME/lib". The library can also be passed during deployment using "--libraries" switch. None of this approach seem to work correctly as explained in issue# 11408. So for now, invoking a JAX-WS Web service from a Rails application deployed directly on GlassFish v3 is not possible, at least until the bug is fixed.

In order to deploy the same application using GlassFish Gem, you can copy "wsclient.jar" to the "lib" directory of your Rails application. And also add the following line to "app/controllers/home_controller.rb":

require 'lib/wsclient.jar'

Alternatively you can copy it to "JRUBY_HOME/lib" directory if this Web service client is accessed my multiple applications. In this case there is no need to add any "require" statement to your Controller. Anyway, running the application as:

jruby -S glassfish

and accessing "http://localhost:3000/home/index" shows the following output:

And finally as explained in TOTD #73, bundle up your original Rails application as WAR and then deploy on GlassFish v3 as:

asadmin deploy webservice.war

Make sure to copy "wsclient.jar" to the "lib" directory of your Rails application and then Warbler will copy it to "WEB-INF/lib" of the generated WAR file. The output is shown as below:

So if you want to invoke a Metro/JAX-WS Web service from a Rails application, then run your Rails application using GlassFish Gem or deploying as a WAR file. It'll work on GlassFish v3 server when issue# 11408 is fixed.

Here are some additional links:

  • TOTD #104 also shows how popular Rails applications such as Redmine, Typo, and Substruct can be easily deployed on GlassFish.
  • Rails applications can be easily clustered using Apache + mod_proxy or  nginx.

A complete archive of all the TOTDs is available here.

Technorati: totd glassfish v3 jruby rails webservice jax-ws metro

Monday Aug 24, 2009

TOTD #98: Create a Metro JAX-WS Web service using GlassFish Tools Bundle for Eclipse


Now that you've installed GlassFish Tools Bundle for Eclipse 1.1, lets use this bundle to create a simple Metro/JAX-WS compliant Web service and deploy on GlassFish. These steps will work with either Eclipse 3.4.2 or 3.5 with WTP Java EE support.

  1. Lets create a simple "Dynamic Web Project" as shown below:


  2. Name the project "HelloMetro" and take all other defaults:



    Click on "Finish" to complete the project creation.
  3. Metro allows to create a Web service from a POJO class. So let's add a POJO to the project by right-clicking on the project and selecting "New", "Class" as shown below:

      

    Specify the package name as "server", class name as "HelloService" and click on "Finish".
  4. Add a simple method to the newly generated class as:

    public String sayHello(String name) {
          return "Hello " + name + "!!";
    }
  5. Expand the project, go to "HelloService.java" in "server" package, right-click, select "Web Services", "Create Web service".
  6. Click on "Web service runtime: Apache Axis" and select "Metro (JAX-WS) Runtime" as the Web service runtime as shown below:

  7. Move the slider on the left to top. This will enable testing of the deployed Web service. The completed configuration looks like:



    and click on "Next >".
  8. Select the checkbox "Copy Metro library jars to the project" to resolve the references correctly as shown below:



    and click on "Next >". This bundles the application and deploys to GlassFish and provides an option to test the deployed Web service as shown below:



    Clicking on the "Launch" button shows the following output in the browser:



    The WSDL is hosted at "http://localhost:8083/HelloMetro/HelloServiceService?wsdl".
  9. Click on "sayHello" method, click on "Add" and enter the value as "Duke" as shown below:



    Click on "Go" and the response is shown as:



    Clicking on "Source" in the response window shows the SOAP request/response messages as shown below:

  10. Alternatively, you can click on "Finish" to complete the dialog. Then click on "Run" menu item, "Launch the Web Services Explorer" to see a screen as:



    Enter the URL of the WSDL in "WSDL URL" box as "http://localhost:8083/HelloMetro/HelloServiceService?wsdl" and click on "Go". Now you are seeing the similar screen to test the Web service within the integrated browser as shown below:


A future blog will cover how to write a database-enabled application using the bundled Dali JPA Tools and MySQL pre-registered JDBC driver.

Please send your questions and comments to users@glassfishplugins.dev.java.net.
Please leave suggestions on other TOTD that you'd like to see. A complete archive of all the tips is available here.

Technorati: totd glassfish eclipse galileo webservices metro jax-ws

Wednesday Feb 18, 2009

Sun Tech Days Hyderabad 2009


India has always had the largest number of attendees of all the Tech Days, and this time is certainly no exception. 10,000+ attendees, the passion for technology, the eagerness to share their work, and everything else makes it certainly one of the most exciting venues for Tech Days.

The Hyderabad International Airport is certainly very impressive - big, clean, and very 21st centurisque with a 8-lane freeway connecting to the main city.

See a short video as the attendees were allowed to enter the Hyderabad International Convention Center (the venue for Tech Days):


I got a chance to talk to the General Manager of the convention center and very happy to know that similar convention centers are planned for Pune (1/2 the size of existing one), Mumbai (4x), and Bangalore (2x) in the near future.

As part of the opening, there was an excellent performance by an 11-year old percussionist, enjoy the video here:


Absolutely stunning performance!

It was funny, I was standing right next to the boy's parents while recording the video. Apparently the boy was allotted 10 minutes and the parents were trying their best to distract the boy right at the beginning of 11th minute :)

I presented on:
  • WSIT: Security, Reliability, Transactional, and .NET-interoperable Web services (slides). The screencast #ws7 is the demo shown during the talk.
  • GlassFish & Future of Java EE (slides)
There were 1000+ attendees in both the sessions and had some very interactive discussions post session. It was a great opportunity to meet lots of local Campus Ambassadors, students using GlassFish for their projects, engineers using GlassFish for their development/deployment, Sun colleagues and lots of other folks!

Here are some of the pictures:


And finally the evolving album:



Technorati: conf suntechdays glassfish metro wsit hyderabad

Monday Nov 10, 2008

GlassFish @ Silicon Valley Code Camp 2008 - Trip Report

CodeCamp at FootHill College. Click Here for Details and Registration 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 event had higher attendance (close to 500) than last year and certainly is a great networking event for the local community.

The venue at Foothill College is literally in foot of the hills and the campus is beautiful. The barebecue reception in the evening was certainly a pleasant relief to the attendees who did not get a pizza slice at lunch ;-)

If you could not attend any of our sessions hen you can read through the slides for GlassFish: The Best Open Source Application Server and Rails powered by GlassFish. The demos shown in the talk are available at:
Feel free to send any comments to users@glassfish.dev.java.net.

Check out some pictures:


And the complete album at:



Technorati: conf siliconvalleycodecamp glassfish netbeans rubyonrails metro webservices

Friday Oct 17, 2008

SOAP and REST - both equally important to Sun


"Sun moving away from SOAP to embrace REST" is the misleading title of an article recently published in SD Times. The article provides a good introduction to JAX-RS and Jersey. But I really wonder what motivated the author of this article to use this title. This blog, hopefully, provides a better context.

Jersey is the Reference Implementation of Java API for RESTful Web Services (JAX-RS, JSR 311) and was released earlier this week. The headline indicates that Sun is leaving SOAP and will support REST. The debate between REST and SOAP is not new and there are religious camps on both sides (even within Sun). And that's completely understandable because each technology has its own merits and demerits. But just because a new JSR aimed to make RESTful Web services easy in the Java platform is released, it does not mean Sun Microsystems is leaving existing technology in trenches.

The addition of Jersey to Sun's software portfolio makes the Web services stack from GlassFish community a more compelling and comprehensive offering. This is in contrast  to "moving away" from SOAP as indicated by the title. As a matter of fact, Jersey will be included as part of Metro soon, the Web Services stack of GlassFish. And then you can use JAX-WS (or Metro) if you like to use SOAP or JAX-RS (or Jersey) if you prefer RESTful Web services. It's all about a offering choice to the community instead of showing a direction.

Here are some data points for JAX-WS:
  • The JAX-WS 2.0 specification was released on May 11, 2006. There have been couple of maintenance releases since then and another one brewing.
  • Parts of Metro, the implementation of JAX-WS, are currently baked into GlassFish, embeddable in JBoss WS Stack, and also part of Oracle Weblogic and IBM Websphere.
  • The implementation stack is mature and used in several key customer deployments. 
  • JAX-WS is already included in Java SE 6 and hence available to a much wider audience.
  • As opposed to "moving away", JAX-WS 2.2 (currently being worked upon) will be included in Java EE 6 platform, as will Jersey be.
So I believe both SOAP and REST are here to stay, at least in the near future. And Sun Microsystems is committed to support them!

You still think Sun is moving away from SOAP ?

It seems a personal preference is interpreted as Sun's disinvestment in SOAP. It's good to have increased readership but not at the cost of misleading headlines :)

Technorati: jax-ws rest webservices metro sdtimes glassfish

Monday Aug 11, 2008

LOTD #1: Using Silverlight to access GlassFish Metro and JAX-WS Web service endpoints

Following TOTD (Tip Of The Day) pattern, I'm starting LOTD (Link Of The Day) series today. These are light-weight entries with generally a single line description and links to other blogs/articles/tips/whitepapers/screencasts/etc.

Let's start with three recent entries on MSDN that describe how to invoke Metro and JAX-WS Web service endpoints from Microsoft Silverlight and .NET:
All entries will be archived at LOTD.

Technorati: lotd webservices metro jax-ws glassfish msdn

Wednesday Jul 30, 2008

Why GlassFish Metro over Axis ?


Metro (Web services stack from GlassFish) is kicking strong these days - here are two instances!
  1. ArcGIS SOAP stack gains 90% performance improvement using Metro

    An intern in the Web services team for performance enhancement of ArcGIS SOAP SDK reported:

    "With Axis 1.x based tool kits XML parsing was identified as a bottleneck and therefore we wanted to make a switch to a tool kit that uses the Streaming API for XML Parsing (StAX). We identified that Metro (Glassfish's SOAP Stack) was the way to go and i generated the new Metro based SDK for accessing Web-Services."

    And the conclusion is ...

    "The result of this project is an increased performance of the ArcGIS Server's SOAP stack (by about 90%)."

    Pretty cool - Metro (Web services stack baked in GlassFish) gave about 90% improvement over Axis! Read more details about the study here.
  2. Change of the guard: AXIS out, JAX-WS in

    Here are some relevant points:

    "I have come to a conclusion: I no longer want to deal with the hassle that has become Apache AXIS."

    "AXIS2 is current, but has become very large, the doc is poor, the support is invisible, the generated code smells, and the seams are everywhere.  Fifty nine jar files?  Really?   Do I need this hassle?  With JAX-WS, do I need AXIS any longer? I think not."

    "But I honestly cannot believe customers will continue to put up with the furball that AXIS2 has become. And if I am in a position to make a recommendation, I will recommend JAX-WS. It works."
And you can also connect to Microsoft Exchange Server using JAX-WS.

And here are some other endorsements for Metro.

Technorati: webservices adoption glassfish metro axis

Wednesday Jul 09, 2008

Getting Started with GlassFish in IntelliJ IDEA


IntelliJ IDEA 7.0.x include plugins that provide support for configuring GlassFish. This blog provides clear instructions on how to get started by developing and deploying a JSP, Servlet and Web services using GlassFish in IntelliJ. The instructions are using IntelliJ 7.0.3 Build #7757 (with no additional plugins).
  1. Create a new project
    1. Clicking on "Create New Project" or "File", "New Project". Take the default as shown below:



      and click on "Next >".
    2. Enter the project name as "GlassFishRocks" and take all defaults as shown:



      and click on "Next >".
    3. Take another default for the source directory as shown:



      and click on "Next >".
    4. For the first time use, JDK needs to be specified. Click on "+" in top-left corner as shown here:



      Take the default option of "JSDK" and specify the Home Directory as shown:



      Click on "OK" and then click on "Next >".
    5. Let's create a Web application. Select the list of technologies as shown:



      and finally (phew!) click on "Finish". The expanded project looks like:

  2. Create a GlassFish configuration
    1. Select "Run", "Edit Configurations" as shown:


    2. Click on "+" on top-left corner and select GlassFish as shown below:


    3. Specify the location of GlassFish Application server at:



      by clicking on "Configure" button and enter the values as shown:



      and click on "OK". You can download and install GlassFish v2 UR2 from here.
    4. Enter the "Name" and select the "Server Domain" as shown:



      and click on "OK".
  3. Deploy the Web application
    1. Click on the green button in the toolbar:


    2. Click on the "Fix" button on the bottom and then click "Run". The recently created Web module is selected to be deployed as shown:

    3. This starts the GlassFish v2 UR2 Application Server and deploys the Web application showing the console as:



      and also shows the default page at "http://localhost:8080/GlassFishRocksWeb/". You can edit "index.jsp", re-deploy the Web facet and refresh the page to see the updated message.

      Notice, even though project's name is "GlassFishRocks", the application context root is "GlassFishRocksWeb".
  4. Now lets create/deploy a new Servlet.
    1. Create a new project as described above and name it "KillerServlet".
    2. Right-click on the project and select "New", "Servlet" as shown:

    3. Enter the values as shown:



      and click on "OK".
    4. The "Java EE: Structure" shows the project as:


    5. Double-click on "HelloServlet" (nested one) and add the following fragment to "doGet" method:

              java.io.PrintWriter out = response.getWriter();
              try {
                  out.println("<html>");
                  out.println("<head>");
                  out.println("<title>Servlet NewServlet</title>");
                  out.println("</head>");
                  out.println("<body>");
                  out.println("<h1>Servlet NewServlet at " + request.getContextPath () + "</h1>");
                  out.println("</body>");
                  out.println("</html>");
              } finally {
                  out.close();
              }

      NetBeans IDE auto-generates this code for a Servlet ;-) And add the following to "doPost" method:

             doGet(request, response);
    6. Double-click on "web.xml" and then select "Assembly Descriptor" tab.
    7. Click on "+" in Servlet Mappings and specify the values as:


    8. Deploy the project (as described above) and output from Servlet is displayed at "http://localhost:8080/KillerServletWeb/hello". Read more details in Creating Java EE Apps and Servlets with IntelliJ IDEA.

      Remember the weird context root, it's "KillerServletWeb" instead of "KillerServlet". Now there may be a good reason to do so but nothing obvious.
  5. Now lets create a simple Web service using the Metro Web services stack (the stack baked into GlassFish)
    1. Create a new project with name "GlassFishWS" following the instructions given above.
    2. Select the list of technologies as shown:

    3. The default generated Web service looks like:

    4. The default generated Web service uses light-weight Endpoint API to host the endpoint. Run the Web service by right-clicking in the editor pane and selecting "Run" as shown or default shortcut of Ctrl+Shift+F10:

    5. The WSDL is now available at "http://localhost:9000/HelloWorld?wsdl".
    6. Right-click on the project and select "New", "Web Service Client" as shown:



      enter the value as "WSClient" and click on "OK".
    7. In the next dialog, enter the values as shown:

    8. The generated client code has some errors as shown:



      Change the code to:

            client.HelloWorld service = new client.HelloWorldService().getHelloWorldPort();
            //invoke business method
            System.out.println(service.sayHelloWorldFrom("Duke"));

      and run WSClient.main to see the result as:



      Now you deployed a Metro Web service using light-weight Endpoint API.  The bundled plugin version is 0.9 build 2 and the steps are so much cleaner from 0.7 version of the plugin.

      Read more about Web Services support in IntelliJ IDEA.
    9. Deploying this Web service on GlassFish is really simple.
      1. Create a new GlassFish configuration as explained above.
      2. Run the project using this configuration and the Web service is now hosted at "http://localhost:8080/GlassFishWSWeb/services/HelloWorld?wsdl".
      3. Generate a client using the steps described above.
Here are few issues filed:
  • JEEAS-180 does not allow an application to be re-deployed to GlassFish and that's why the examples above use different projects.
  • JEEAS-181  asks for better integration of GlassFish logs in the IDE.
  • JEEAS-182 require support for GlassFish v3 in the GlassFish plugin. Please help by voting for this issue.
  • WSVC-61 reports the errors generated in Web services client code
So whether you are using Eclipse, IntelliJ or NetBeans - you can easily configure GlassFish and deploy your applications directly from within the IDE. Here are some related links:
However of all the IDEs, NetBeans IDE still provides the most comprehensive coverage in terms of development and deployment of Java EE applications (JSP, Servles, Java Server Faces, SOAP-based .NET 3.0-interoperable Web service, RESTful Web services, JPA, EJBs) and server plug-ins (GlassFish, Tomcat, JBoss, WebLogic, WebSphere, OC4J, SAP BusinessOne and JOnAS).


Technorati: glassfish intellij idea jsp servlets metro webservices
About

profile image
Arun Gupta is a technology enthusiast, a passionate runner, author, and a community guy who works for Oracle Corp.


Java EE 7 Samples

Stay Connected

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today