RESTful Web Service (using JAX-RS Annoations)

Sang Shin, www.javapassion.com/webservices



Java API for RESTful Web Services is a Java programming language API that provides support in creating web services according to the Representational State Transfer (REST) architectural style. JAX-RS uses annotations, introduced in Java SE 5, to simplify the development and deployment of web service clients and endpoints.

 In this lab, you are going to build a RESTful web service using JAX-RS.

Expected duration: 120 minutes (excluding homework)



Software Needed

Before you begin, you need to install the software mentioned in the class website on your computer.  You also need download and unzip the hands-on lab zip file below (if you have not done so yet).


OS platforms you can use

Change Log


Things to be done (by Sang Shin)

 

Lab Exercises


Exercise 0: Do installation and configuration


In this exercise, you are going to make sure if RESTful Web Service plug-in is configured with your NetBeans IDE.
  1. Check if RESTful Web Service plug-in is configured with NetBeans IDE
  2. Install "Poster" plug-in to the Firefox browser
  3. Download and install "curl"

(0.1) Check if RESTful Web Service Plug-in is configured with NetBeans IDE



If you have downloaded and installed NetBeans 6.5, 6.5.1, or 6.7.1 with Java Web and EE modules, the RESTful Web services plug-in is already configured.

1. Select Tools and select Plugins.



2. Select Installed tab and make sure RESTful Web Servuces plug-in is present.  If you don't see it, you need to install it before proceeding this lab.



(0.2) Install "Poster" add-on to the Firefox browser














(0.3) Download "curl"


1. Using your browser, go to http://curl.haxx.se/.







Exercise 1: Build and run "HelloWorld" RESTful Web service


In this exercise, you are going to build, run, and test the "HelloWorld" RESTful Web service that comes with NetBeans IDE.
  1. Build and run "HelloWorld" RESTful Web service project
  2. Study the control flow
  3. Test RESTful Web service
  4. Display WADL
  5. Display the Javadoc on RESTful Web service annotations
  6. Add another class
  7. Use Firefox Poster for testing
  8. Use "curl" command-line utility for testing

(1.1) Build and run "HelloWorld" RESTful Web service project


1. Creare a new Project.
 




2. Build and run the project.



3. Enable HTTP Monitor (if you have not done so yet).




4. Run the application again.
5. Observe the request URL through HTTP Monitor.


                                                                                                                   return to top of exercise

(1.2)  Study the control flow


1. Check the relative URL of the project.  When the application is run, the request URL is set to http://localhost:8080/HelloWorld/resources/helloWorld.  This is because the Relative URL of the project is already set to /resources/helloWorld.



2. Any request path that starts with /resources/* will be handled by com.sun.jersey.spi.container.servlet.ServletContainer, which is provided by the framework.  You can see the web.xml as shown below.



<?xml version="1.0" encoding="UTF-8"?>
<!--
 DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 
 Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
 
 The contents of this file are subject to the terms of either the GNU
 General Public License Version 2 only ("GPL") or the Common
 Development and Distribution License("CDDL") (collectively, the
 "License"). You may not use this file except in compliance with the
 License. You can obtain a copy of the License at
 http://www.netbeans.org/cddl-gplv2.html
 or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
 specific language governing permissions and limitations under the
 License.  When distributing the software, include this License Header
 Notice in each file and include the License file at
 nbbuild/licenses/CDDL-GPL-2-CP.  Sun designates this
 particular file as subject to the "Classpath" exception as provided
 by Sun in the GPL Version 2 section of the License file that
 accompanied this code. If applicable, add the following below the
 License Header, with the fields enclosed by brackets [] replaced by
 your own identifying information:
 "Portions Copyrighted [year] [name of copyright owner]"
 
 Contributor(s):
 
 The Original Software is NetBeans. The Initial Developer of the Original
 Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
 Microsystems, Inc. All Rights Reserved.
 
 If you wish your version of this file to be governed by only the CDDL
 or only the GPL Version 2, indicate your decision by adding
 "[Contributor] elects to include this software in this distribution
 under the [CDDL or GPL Version 2] license." If you do not indicate a
 single choice of license, a recipient has the option to distribute
 your version of this file under either the CDDL, the GPL Version 2 or
 to extend the choice of license to its licensees as provided above.
 However, if you add GPL Version 2 code and therefore, elected the GPL
 Version 2 license, then the option applies only if the new code is
 made subject to such option by the copyright holder.
-->
<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>ServletAdaptor</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>ServletAdaptor</servlet-name>
        <url-pattern>/resources/*</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>
web.xml

3. The remaining part of the URL, helloWorld, will be handled by a method of the HelloWorldResource class.  You can open the HelloWorldResource.java under HelloWorld->Source Packages->helloworld.



/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
 *
 * The contents of this file are subject to the terms of either the GNU
 * General Public License Version 2 only ("GPL") or the Common
 * Development and Distribution License("CDDL") (collectively, the
 * "License"). You may not use this file except in compliance with the
 * License. You can obtain a copy of the License at
 * http://www.netbeans.org/cddl-gplv2.html
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
 * specific language governing permissions and limitations under the
 * License.  When distributing the software, include this License Header
 * Notice in each file and include the License file at
 * nbbuild/licenses/CDDL-GPL-2-CP.  Sun designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Sun in the GPL Version 2 section of the License file that
 * accompanied this code. If applicable, add the following below the
 * License Header, with the fields enclosed by brackets [] replaced by
 * your own identifying information:
 * "Portions Copyrighted [year] [name of copyright owner]"
 *
 * Contributor(s):
 *
 * The Original Software is NetBeans. The Initial Developer of the Original
 * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
 * Microsystems, Inc. All Rights Reserved.
 *
 * If you wish your version of this file to be governed by only the CDDL
 * or only the GPL Version 2, indicate your decision by adding
 * "[Contributor] elects to include this software in this distribution
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
 * single choice of license, a recipient has the option to distribute
 * your version of this file under either the CDDL, the GPL Version 2 or
 * to extend the choice of license to its licensees as provided above.
 * However, if you add GPL Version 2 code and therefore, elected the GPL
 * Version 2 license, then the option applies only if the new code is
 * made subject to such option by the copyright holder.
 */

package helloworld;

import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;

/**
 * REST Web Service
 *
 * @author __USER__
 */

@Path("/helloWorld")
public class HelloWorldResource {
    @Context
    private UriInfo context;
   
    /** Creates a new instance of HelloWorldResource */
    public HelloWorldResource() {
    }

    /**
     * Retrieves representation of an instance of helloworld.HelloWorldResource
     * @return an instance of java.lang.String
     */
    @GET
    @Produces("text/html")
    public String getXml() {
        return "<html><body><h1>Hello World!</body></h1></html>";
    }

    /**
     * PUT method for updating or creating an instance of HelloWorldResource
     * @param content representation for the resource
     * @return an HTTP response with content of the updated or created resource.
     */
    @PUT
    @Consumes("application/xml")
    public void putXml(String content) {
    }
}

4. Change the response as shown below - change Hello World! to Hello Egypt!, for example.



5. Run the project.



                                                                                                                   return to top of exercise


(1.3) Test RESTful Web service


1. Start the test page.




2. Test GET method.



3. Display the Sub-Resource view.



4.  Display Headers view.



5. Display Http Monitor.



                                                                                                                   return to top of exercise


(1.4) Display WADL


1. Display WADL.



                                                                                                                   return to top of exercise


(1.5) Display the Javadoc on RESTful Web service annotations


1. Perform context-sensitive Javadoc on RESTful API's (annotations.)




                                                                                                                   return to top of exercise


(1.6) Add another class


1. Create a new Java class.




2. Replace the IDE generated  MyOwnResource.java with the one below.

package helloworld;

import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;

/**
 * REST Web Service
 *
 * @author __USER__
 */

@Path("/myOwnWorld")
public class MyOwnResource {
    @Context
    private UriInfo context;
   
    /** Creates a new instance of HelloWorldResource */
    public MyOwnResource() {
    }

    /**
     * Retrieves representation of an instance of helloworld.HelloWorldResource
     * @return an instance of java.lang.String
     */
    @GET
    @Produces("text/html")
    public String getXml() {
        return "<html><body><h1>My Own World!</body></h1></html>";
    }

    /**
     * PUT method for updating or creating an instance of HelloWorldResource
     * @param content representation for the resource
     * @return an HTTP response with content of the updated or created resource.
     */
    @PUT
    @Consumes("application/xml")
    public void putXml(String content) {
    }
}

3. Deploy the application.



4. Test the RESTful web service.




                                                                                                                   return to top of exercise

(1.7) Use Firefox Poster for REST testing







                                                                                                                   return to top of exercise

(1.8) Use"curl" for REST testing




C:\download\curl>curl http://localhost:8080/HelloWorld/resources/helloWorld
<html><body><h1>Hello World!</body></h1></html>

                                                                                                                   return to top of exercise

Exercise 2: Create RESTful Web service from patterns


In this exercise, you are going to build HelloWorld RESTful Web service application from scratch.  Acknowledgment: This exercise is created based on the GlassFish:Jersey Getting Started article.
  1. Singleton pattern
  2. Container-Item pattern
  3. Client Controlled Container-Item pattern

(2.1) Singleton pattern


1. Create a Java Web project.




                                                                                    

2. Create a Singleton RESTful resource.











package hello.world;

import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Consumes;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;

/**
 * REST Web Service
 *
 * @author sang
 */

@Path("helloworld")
public class HelloworldResource {
    @Context
    private UriInfo context;

    /** Creates a new instance of HelloworldResource */
    public HelloworldResource() {
    }

    /**
     * Retrieves representation of an instance of hello.world.HelloworldResource
     * @return an instance of java.lang.String
     */
    @GET
    @Produces("text/plain")
    public String getText() {
        //TODO return proper representation object
        throw new UnsupportedOperationException();
    }

    /**
     * PUT method for updating or creating an instance of HelloworldResource
     * @param content representation for the resource
     * @return an HTTP response with content of the updated or created resource.
     */
    @PUT
    @Consumes("text/plain")
    public void putText(String content) {
    }
}

                                                                                                                 
3. Modify the code.  The modification is to return a string as a return value of the getText() method.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package hello.world;

import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Consumes;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;

/**
 * REST Web Service
 *
 * @author sang
 */

@Path("helloworld")
public class HelloworldResource {
    @Context
    private UriInfo context;

    /** Creates a new instance of HelloworldResource */
    public HelloworldResource() {
    }

    /**
     * Retrieves representation of an instance of hello.world.HelloworldResource
     * @return an instance of java.lang.String
     */
    @GET
    @Produces("text/plain")
    public String getText() {
        //TODO return proper representation object
        //throw new UnsupportedOperationException();
        return ("Hello World! Here is " + context.getAbsolutePath());
    }

    /**
     * PUT method for updating or creating an instance of HelloworldResource
     * @param content representation for the resource
     * @return an HTTP response with content of the updated or created resource.
     */
    @PUT
    @Consumes("text/plain")
    public void putText(String content) {
    }
}



  Learning points: The HelloWorldResource class is a very simple Web resource. The URI path of the resource is "/helloworld", it supports the HTTP GET method (line 35) with getText() method, which produces a textual content of the MIME media type "text/plain".

Notice the use of Java annotations to declare the URI path(@Path), the HTTP method (@GET) and the MIME type (@Produces). Also note the @Context annotation, which acts as a marker to say "Please inject an instance of the Java type, in this case UriInfo, after the class has been constructed."

                                                                                                                   return to top of exercise

4. Verify that the project is already configured with JAX-RS libraries.



                                                                                                                 

5. Deploy the application.




                                                                                                                   return to top of exercise

(2.2) Container-Item pattern


Item resources can be created and added to the container resource using the POST method on the container resource class. Note that the URI for the newly created item resource is determined by the container resource.

1. Create a Java Web project.




2. Create RESTful Web Service from Patterns.







3. Study ItemsResource.java.

package hello.world;

import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.POST;
import javax.ws.rs.Consumes;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;

@Path("/Items")
public class ItemsResource {
    @Context
    private UriInfo context;

    /** Creates a new instance of ItemsResource */
    public ItemsResource() {
    }

    /**
     * Retrieves representation of an instance of hello.world.ItemsResource
     * @return an instance of java.lang.String
     */
    @GET
    @Produces("application/xml")
    public String getXml() {
        //TODO return proper representation object
        throw new UnsupportedOperationException();
    }

    /**
     * POST method for creating an instance of ItemResource
     * @param content representation for the new resource
     * @return an HTTP response with content of the created resource
     */
    @POST
    @Consumes("application/xml")
    @Produces("application/xml")
    public Response postXml(String content) {
        //TODO
        return Response.created(context.getAbsolutePath()).build();
    }

    /**
     * Sub-resource locator method for  {id}
     */
    @Path("{id}")
    public ItemResource getItemResource() {
        return new ItemResource();
    }
}

4. Study ItemResource.java.

package hello.world;

import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.PathParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.PUT;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.DELETE;

public class ItemResource {
    @Context
    private UriInfo context;

    /** Creates a new instance of ItemResource */
    public ItemResource() {
    }

    /**
     * Retrieves representation of an instance of hello.world.ItemResource
     * @param id resource URI parameter
     * @return an instance of java.lang.String
     */
    @GET
    @Produces("application/xml")
    public String getXml(@PathParam("id")
    String id) {
        //TODO return proper representation object
        throw new UnsupportedOperationException();
    }

    /**
     * PUT method for updating or creating an instance of ItemResource
     * @param id resource URI parameter
     * @param content representation for the resource
     * @return an HTTP response with content of the updated or created resource.
     */
    @PUT
    @Consumes("application/xml")
    public void putXml(@PathParam("id")
    String id, String content) {
    }

    /**
     * DELETE method for resource ItemResource
     * @param id resource URI parameter
     */
    @DELETE
    public void delete(@PathParam("id")
    String id) {
    }
}


                                                                                                                   return to top of exercise


(2.3) Client controlled Container-Item pattern


This pattern is a slight variation of the Container-Item pattern. The difference is that there is no POST method on the container resource class for creating item resources. Instead, item resources are created using the PUT method on the item resource class. The reason this is called Client-Controlled Container-Item pattern is because the URI for the item resource is determined by the client and not the container resource.

1. Create a Java Web project.



2. Create RESTful Web Service from Patterns.







3. Study ItemsResources.java.

package hello.world;

import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;

/**
 * REST Web Service
 *
 * @author sang
 */

@Path("/Items")
public class ItemsResource {
    @Context
    private UriInfo context;

    /** Creates a new instance of ItemsResource */
    public ItemsResource() {
    }

    /**
     * Retrieves representation of an instance of hello.world.ItemsResource
     * @return an instance of java.lang.String
     */
    @GET
    @Produces("application/xml")
    public String getXml() {
        //TODO return proper representation object
        throw new UnsupportedOperationException();
    }

    /**
     * Sub-resource locator method for  {name}
     */
    @Path("{name}")
    public ItemResource getItemResource() {
        return new ItemResource();
    }
}


4. Study ItemResource.java.

package hello.world;

import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.PathParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.PUT;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.DELETE;

/**
 * REST Web Service
 *
 * @author sang
 */

public class ItemResource {
    @Context
    private UriInfo context;

    /** Creates a new instance of ItemResource */
    public ItemResource() {
    }

    /**
     * Retrieves representation of an instance of hello.world.ItemResource
     * @param name resource URI parameter
     * @return an instance of java.lang.String
     */
    @GET
    @Produces("application/xml")
    public String getXml(@PathParam("name")
    String name) {
        //TODO return proper representation object
        throw new UnsupportedOperationException();
    }

    /**
     * PUT method for updating or creating an instance of ItemResource
     * @param name resource URI parameter
     * @param content representation for the resource
     * @return an HTTP response with content of the updated or created resource.
     */
    @PUT
    @Consumes("application/xml")
    public void putXml(@PathParam("name")
    String name, String content) {
    }

    /**
     * DELETE method for resource ItemResource
     * @param name resource URI parameter
     */
    @DELETE
    public void delete(@PathParam("name")
    String name) {
    }
}


                                                                                                                   return to top of exercise



Exercise 3: Build "CustomerDB" RESTful Web service from a database table


In this exercise, you are going expose entity classes as RESTful web services.  The entity classes are created from the table called CustomerDB, which is in sample database. 

Since the GlassFish ESB 2.2 does not come with the sample database, we are going to copy the sample database from <LAB_UNZIPPED_DIRECTORY>/wsrestjaxrs/databases directory to the <GlassFishESB2.2_InstallDirectoty>/GlassFishESBv22/glassfish/databases directory.
  1. Create sample database
  2. Create a new Web application NetBeans project
  3. Create entity classes from database tables
  4. Create RESTful web services from the entity classes
  5. Test RESTful web services

(3.0) Create database


1. Copy "sample" database to the GlassFish ESB 2.2 Java DB.






2. Start Java DB server.



3. Make JDBC connection.








                                                                                                                   return to top of exercise


(3.1) Create a new Web Application NetBeans project


1. Create Web application NetBeans project called CustomerDB.







                                                                                                                  return to top of exercise

(3.2) Create Entity classes from database tables


1. Create Entity classes from database table.












                                                                                                                  return to top of exercise

(3.3) Create RESTful Web services from Entity classes














                                                                                                                  return to top of exercise

(3.4) Test RESTful Web services


1. Start testing.


2. Perform testing against customers resource.












3. Perform testing against specific customer.







4. Verify the information of the 2nd customer.





5. Perform update on the 2nd customer.



<?xml version="1.0" encoding="UTF-8"?>
   <customer uri="http://localhost:8080/CustomerDB/resources/customers/2/">
       <addressline1>9754 Main Street</addressline1>
       <addressline2>P.O. Box 567</addressline2>
       <city>Miami</city>
       <creditLimit>50000</creditLimit>
       <customerId>2</customerId>
       <discountCode uri="http://localhost:8080/CustomerDB/resources/customers/2/discountCode/"/>
       <email>www.tsoftt.com</email>
       <fax>305-456-8889</fax>
       <name>Sang Shin</name>
       <phone>305-456-8888</phone>
       <state>FL</state>
       <zip>33055</zip>
   </customer>








                                                                                                                  return to top of exercise

Exercise 4: Add "Google Map" Feature


This exercise is created based on the Getting Started with RESTful Web Services article.
  1. Get Google map key
  2. Modify CustomerResource.java
  3. Modify CustomerResource.java
  4. Configure Google map key
  5. Start GlassFish app server (if it has not been started already)
  6. Test the RESTful web service

(4.1) Get Google map key


1. Sign up for a Google map key at http://www.google.com/apis/maps/signup.html. The Google map key request dialog has a field for your website's URL. Type http://localhost in that field.





(4.2) Modify CustomerResource.java


1. Open customerdb.service->CustomerResource.java.



2. Add the code to the CustomerResource.java as shown below.   The code fragments that need to be added are highlighted in bold and red-colored font.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package customerdb.service;

import customerdb.Customer;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.DELETE;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.QueryParam;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import com.sun.jersey.api.core.ResourceContext;
import javax.ws.rs.WebApplicationException;
import javax.persistence.NoResultException;
import javax.persistence.EntityManager;
import customerdb.DiscountCode;
import customerdb.converter.CustomerConverter;


/**
 *
 * @author sang
 */
public class CustomerResource {

    @Context
    protected UriInfo uriInfo;
    @Context
    protected ResourceContext resourceContext;
    protected Integer id;

    /** Creates a new instance of CustomerResource */
    public CustomerResource() {
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @GET
    @Produces("text/html")
    public String getGoogleMap() {
        // Drag and drop the getGoogleMap operation here

        return null;
    }

    //Gets invoked by going to browser and accessing any customer (ie  /customers/1/googleMap)
    /**
     * Returns sub-resource.
     */
    @Path("googleMap/")
    @GET
    @Produces("text/html")
    public String getGoogleMapResource() {
        return getGoogleMap();
    }

    /**
     * Get method for retrieving an instance of Customer identified by id in XML format.
     *
     * @param id identifier for the entity
     * @return an instance of CustomerConverter
     */
    @GET
    @Produces({"application/xml", "application/json"})
    public CustomerConverter get(@QueryParam("expandLevel")
            @DefaultValue("1") int expandLevel) {
        PersistenceService persistenceSvc = PersistenceService.getInstance();
        try {
            persistenceSvc.beginTx();
            return new CustomerConverter(getEntity(), uriInfo.getAbsolutePath(), expandLevel);
        } finally {
            PersistenceService.getInstance().close();
        }
    }

 

   ...



3. Add code which invokes Google map service.








(4.3) Modify CustomerResource.java so that the address comes from the database


package customerdb.service;

import customerdb.Customer;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.DELETE;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.QueryParam;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import com.sun.jersey.api.core.ResourceContext;
import javax.ws.rs.WebApplicationException;
import javax.persistence.NoResultException;
import javax.persistence.EntityManager;
import customerdb.DiscountCode;
import customerdb.converter.CustomerConverter;
import org.netbeans.saas.google.GoogleMapService;
import org.netbeans.saas.RestResponse;

/**
 *
 * @author sang
 */
public class CustomerResource {

    @Context
    protected UriInfo uriInfo;
    @Context
    protected ResourceContext resourceContext;
    protected Integer id;

    /** Creates a new instance of CustomerResource */
    public CustomerResource() {
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @GET
    @Produces("text/html")
    public String getGoogleMap() {
        // Drag and drop the getGoogleMap operation here

        try {
            //String address = "16 Network Circle, Menlo Park";
            //java.lang.Integer zoom = 15;
            //String iframe = "false";

            //RestResponse result = GoogleMapService.getGoogleMap(address, zoom, iframe);
            Customer c = getEntity();
            String address = c.getAddressline1() + " " + c.getAddressline2() + " " +
                    c.getCity() + " " + c.getState() + " " + c.getZip();
            java.lang.Integer zoom = 15;
            String iframe = "false";

            RestResponse result = GoogleMapService.getGoogleMap(address, zoom, iframe);
            return result.getDataAsString();
        //TODO - Uncomment the print Statement below to print result.
        //System.out.println("The SaasService returned: "+result.getDataAsString());
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }

    //Gets invoked by going to browser and accessing any customer (ie  /customers/1/googleMap)
    /**
     * Returns sub-resource.
     */
    @Path("googleMap/")
    @GET
    @Produces("text/html")
    public String getGoogleMapResource() {
        return getGoogleMap();
    }
...


(4.4) Configure Google map key






(4.5) Make sure GlassFish server is up and running




(4.6) Test RESTful Web service



















Homework Exercise (for people who are taking Sang Shin's "Web Services Programming online course")


1. The homework is to create MyOwnRESTfulService project as following.
2. Send the following files to  webserviceshomework@javapassion.com with Subject as WebServices-wsrestjaxrs.

                                                                                                                    return to the top