sun.com docs.sun.com My Sun Worldwide Sites

  Previous Contents Next

Building and Running the calculator Application with Ant

  1. Open a terminal prompt and navigate to swdp.tutorial.home/examples/rest/calculator.
  2. Enter ant and press Enter.

    This will build and package the calculator.war web application.


    Note - You will see some warning messages in the output from the rest-generate task. These warnings can safely be ignored.


  3. Enter ant deploy and press Enter.

    This will deploy calculator.war to Application Server 9.1.

  4. In a web browser navigate to:
    http://server:server port/calculator/restbean/number1=3&number2=4

    You will see the following output in your web browser:

    7

The rsvp Application

The rsvp application is a more complicated example that shows how to use all the main HTTP methods: GET, POST, PUT, and DELETE. Attendees to an event are stored in database by using a Java Persistence API entity manager The Rsvp and RsvpContainerclasses define resource methods to create, update, and delete attendees.

The RsvpContainer class responds to the URI template /responses/.

@UriTemplate("/responses/")
public class RsvpContainer {

    private static final Logger logger = Logger.
			getLogger("RsvpContainer REST service");

    @HttpMethod
    @ConsumeMime("application/x-www-form-urlencoded")
    @ProduceMime("text/html")
    public String postCreateAttendee(FormURLEncodedProperties formDataContent) {
        String firstName = formDataContent.get("firstName");
        String lastName = formDataContent.get("lastName");
        String status = formDataContent.get("status");
        
        Attendee attendee = new Attendee(firstName,
            lastName,
            status);
        this.persist(attendee);

        StringBuffer response = new StringBuffer();
        response.append("<html><head><title>Results from creating new attendee ");
        response.append(attendee.getFirstName());
        response.append(" " + attendee.getLastName());
        response.append("</title></head><body>");
        response.append("<h1>Results from creating new attendee ");
        response.append(attendee.getFirstName());
        response.append(" " + attendee.getLastName());
        response.append("</h1>");
        response.append("<p>Created new attendee ");
        response.append(attendee.getFirstName());
        response.append(" " + attendee.getLastName());
        response.append(" with ID ");
        response.append(attendee.getId());
        response.append(" and with response ");
        response.append(attendee.getStatus());
        response.append(".</p>");
        response.append("<p><a href=\"/rsvp/remove.jsp\">Remove attendee page</a></p>");
        response.append("</body></html>");
        
        return response.toString();
    }

    @UriTemplate("{rsvpId}")
    public Rsvp getRsvpResource(@UriParam("rsvpId") int id) {
       return new Rsvp(id);
    }

    private void persist(Attendee object) {
        try {
            Context ctx = new InitialContext();
            EntityManager em = (EntityManager) 
					ctx.lookup("java:comp/env/persistence/rsvp");
            UserTransaction utx = (UserTransaction) 
					ctx.lookup("java:comp/env/UserTransaction");
            utx.begin();
            em.persist(object);
            utx.commit();
        } catch(Exception e) {
            logger.log(Level.SEVERE,"exception caught", e);;
            throw new RuntimeException(e);
        }
    }
}

The single HTTP POST method, postCreateAttendee, is used to create a new attendee. The @ConsumeMime("application/x-www-form-urlencoded") annotation is used to specify that the postCreateAttendee method accepts input from URL encoded form data. The input parameter for postCreateAttendee is a FormURLEncodedProperties object representing the form data. The content of the form data is extracted as a Map<String, String> in the formDataContent object, and the submitted first name, last name, and status is then extracted from formDataContent. This information is then used to create a new Attendee entity, which is persisted. A String object is then returned to the client with an HTML page showing the attendee's name, status, and ID.

The getRsvpResource responds to the URI template /responses/{rsvpId}, returns an Rsvp class. All the other HTTP operations are defined in the Rsvp class.

@ProduceMime("text/html")
public class Rsvp {

    @Resource
    HttpContext context;
    
    private static final Logger logger = 
			Logger.getLogger("Rsvp REST service");

    private Attendee attendee;

    Rsvp(int id) {
        try {
            this.attendee = this.lookupAttendee(id);
            if (attendee == null) {
                logger.warning("Attendee " + id + " not found.");
                throw new AttendeeNotFoundException("Attendee " + 
						id + " not found.");
            }
        } catch (Exception e) {
            logger.log(Level.SEVERE,"exception caught", e);
            throw new RuntimeException(e);
        }
    }

    @HttpMethod
    public String getStatus() {
        String status = new String("<html>" +
            "<head>" +
            "<title>Status for attendee " +
            attendee.getFirstName() +
            " " +
            attendee.getLastName() +
            "</title>" +
            "</head>" +
            "<body>" +
            "<h1>Status for attendee " +
            attendee.getFirstName() +
            " " +
            attendee.getLastName() +
            "</h1>" +
            "<p>The current response is " +
            attendee.getStatus() +
            ".</p>" +
            "</body>" +
            "</html>");
        return status;
    }

    @HttpMethod
    @ProduceMime("text/plain")
    public String getStatusAsPlainText() {
        String status = new String(attendee.getFirstName() +
            " " + attendee.getLastName() + "'s status is: " +
            attendee.getStatus() + ".");
        return status;
    }

    @HttpMethod
    public String deleteInvitee() {
        String response;
        this.delete(attendee);
        logger.info("Deleted attendee " + attendee.getId());
        response = "<p>Removed attendee " + attendee.getId() + "</p>";
        return response;
    }

    private void persist(Attendee object) {
        try {
            Context ctx = new InitialContext();
            EntityManager em = (EntityManager) 
					ctx.lookup("java:comp/env/persistence/rsvp");
            UserTransaction utx = (UserTransaction) 
					ctx.lookup("java:comp/env/UserTransaction");
            utx.begin();
            // TODO:
            em.persist(object);
            utx.commit();
        } catch(Exception e) {
            logger.log(Level.SEVERE,"exception caught", e);;
            throw new RuntimeException(e);
        }
    }
    
    private void delete(Attendee object) {
        try {
            Context ctx = new InitialContext();
            EntityManager em = (EntityManager) 
					ctx.lookup("java:comp/env/persistence/rsvp");
            UserTransaction utx = (UserTransaction) 
					ctx.lookup("java:comp/env/UserTransaction");
            utx.begin();
            em.remove(em.merge(object));
            utx.commit();
        } catch (Exception e) {
            logger.log(Level.SEVERE,"exception caught", e);
            throw new RuntimeException(e);
        }
    }

    private Attendee lookupAttendee(int id) {
        try {
            Context ctx = new InitialContext();
            EntityManager em = (EntityManager) 
					ctx.lookup("java:comp/env/persistence/rsvp");
            Attendee attendee = em.find(Attendee.class, id);
            return attendee;
        } catch (Exception e) {
            logger.log(Level.SEVERE,"exception caught", e);
            throw new RuntimeException(e);
        }
    }
}

In Rsvp there are two resource methods that respond to HTTP GET requests, getStatusAsHtml and getStatusAsPlainText. These methods extract the ID of the attendee from the URI Template specified by the @UriTemplate annotation in RsvpContainer's getRsvpResource method. They then use the ID as the primary key for looking up the Attendee persistence entity by calling the lookupAttendee convenience method. If there is no corresponding attendee in the database with the specified ID, an AttendeeNotFoundException is thrown. If the attendee exists, the current status of the attendee is returned either as HTML or plain text. The @ProduceMime annotation is used to specify the MIME type of the returned status statement.

The deleteAttendee method responds to HTTP DELETE requests and is used to delete an attendee. The deleteAttendee method extracts the ID of the specified attendee from the URI Template specified by the @UriTemplate annotation. This ID is the primary key of the corresponding Attendee entity. A lookup is performed using the ID to retrieve the Attendee entity. If the specified attendee doesn't exist in the database, an AttendeeNotFoundException is thrown. If the attendee exists, it is deleted.

The rsvp application uses a single Java Persistence API entity, Attendee:

@Entity
public class Attendee implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    
    private String firstName;
    
    private String lastName;
    
    private String status;
    
    /** Creates a new instance of Attendee */
    public Attendee() {
    }
    
    public Attendee(String firstName,
        String lastName,
        String status) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.status = status;
    }

    /**
     * Gets the id of this Attendee.
     * @return the id
     */
    public Integer getId() {
        return this.id;
    }

    /**
     * Sets the id of this Attendee to the specified value.
     * @param id the new id
     */
    public void setId(Integer id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
}
Removing Attendees

The HTTP DELETE method used to remove attendees is not supported by web browsers, so it is more difficult to create HTML forms that allow you to delete attendees. The XMLHttpRequest JavaScript object used in Ajax-enabled applications, however, can be used to send DELETE requests. The rsvp application includes a JSP page, remove.jsp, that uses XMLHttpRequest to delete attendees by their ID, which is entered into an HTML form.

The following code shows the remove.jsp file.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Delete attendee</title>
        <%@include file="/WEB-INF/jspf/header.jspf" %>
    </head>
    <body>

        <h1>Delete attendee</h1>

        <form name="deleteAttendeeForm" action="javascript:;">
            <input type="text" id="attendeeId" value="" />
            <button onclick="deleteAttendee();" value="Delete" name="deleteAttendeeButton">Delete</button>
        </form>

        <div id="deleteResponse"><p>Look for response here.</p></div>
    </body>
</html>

Note that we include a header file, header.jspf. This JSP fragment contains the JavaScript code used by the form to create the HTTP DELETE request for the specified ID. The following code shows header.jspf.

<script>
// the base of the RESTBeans resource
var baseUrl = "/rsvp/restbean/responses/";

// function called by delete form to remove attendee
function deleteAttendee () {
    var deleteMessage = document.getElementById("deleteResponse");

    function processRequest(evt) {
        if (evt.target.readyState == 4) {
            if (evt.target.status == 200) {
                deleteMessage.innerHTML = "Deleting attendee";
            } else {
                alert("Problem processing request for attendee ID " + 
						attendeeId + ".");
            }
        }
    }
        
    var xmlHttpReq;
    if (window.XMLHttpRequest) { // Mozilla, Safari, ...
        xmlHttpReq = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // IE
        xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
        
    // get the attendee ID from the text box in the form
    var attendeeId = document.getElementById("attendeeId").value;
       
    if (xmlHttpReq != null) {
        xmlHttpReq.onreadystatechange = processRequest;
        xmlHttpReq.open("DELETE", baseUrl + attendeeId, false);
        xmlHttpReq.send("");
    } else {
        alert("Problem deleting attendee ID " + attendeeId + ".");
    }
    deleteMessage.innerHTML = xmlHttpReq.responseText;
}

</script>

Building and Running the rsvp Application in NetBeans IDE 5.5.1

  1. Select File→Open Project in NetBeans IDE 5.5.1.
  2. Navigate to swdp.tutorial.home/examples/rest, select rsvp, and click OK.
  3. Right click on the rsvp application in the Projects pane and select Run Project.

    This will generate the helper classes and artifacts for your resource, compile the classes, package the files into a WAR file, deploy the WAR to your Application Server 9.1 instance, and open a web browser to the following URL:

    http://server:server port/rsvp/

    Note - You will see some warning messages in the output from the apt tool and during the deployment phase on subsequent runs of the application. These warnings can safely be ignored.


    This page has an HTML form for creating attendees.

  4. Enter the first name, last name, select the status of the attendee, and then click Submit.

    The attendee will be added to the database, and you'll see a status page with the attendee's information and newly created ID.

  5. (Optional) Remove an attendee.

    In a web browser, open the following page:

    http://server:server port/rsvp/remove.jsp

    Enter the ID of an attendee, and click Delete.

Building and Running the rsvp Application with Ant

  1. Make sure your JavaDB instance is running.
  2. Open a terminal prompt and navigate to swdp.tutorial.home/examples/rest/rsvp.
  3. Enter ant and press Enter.

    This will build and package the rsvp.war web application.


    Note - You will see some warning messages in the output from the apt tool and during the deployment phase on subsequent runs of the application. These warnings can safely be ignored.


  4. Enter ant deploy and press Enter.

    This will deploy rsvp.war to Application Server 9.1.

    On deployment, the database tables will be created in the default JavaDB database.

  5. In a web browser navigate to:
    http://server:server port/rsvp/

    This page has an HTML form for creating attendees.

  6. Enter the first name, last name, select the status of the attendee, and then click Submit.

    The attendee will be added to the database, and you'll see a status page with the attendee's information and newly created ID.

  7. (Optional) Remove an attendee.

    In a web browser, open the following page:

    http://server:server port/rsvp/remove.jsp

    Enter the ID of an attendee, and click Delete.

Previous Contents Next
Company Info Contact Terms of Use Privacy Copyright 1994-2007 Sun Microsystems, Inc.