Building and Running the calculator Application
with Ant
- Open a terminal prompt and navigate to <swdp.tutorial.home>/examples/rest/calculator.
- 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 apt tool. These warnings can safely be ignored.
- Enter ant deploy and press Enter.
This will deploy calculator.war to Application Server 9.1.
- 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 Return class defines resource methods to create, update, and delete attendees.
@UriTemplate("/responses/{rsvpId}")
public class Return {
@Resource
HttpContext context;
private static final Logger logger = Logger.getLogger("Return REST service");
/** Creates a new instance of Return */
public Return() {
}
@HttpMethod("GET")
@ProduceMime("text/html")
public Representation<String> returnStatusAsHtml(@UriParam("rsvpId") int id) {
Attendee attendee;
try {
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);
}
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 new StringRepresentation(status, "text/html");
}
@HttpMethod("GET")
@ProduceMime("text/plain")
public Representation<String> returnStatusAsPlainText(@UriParam("rsvpId") int id) {
Attendee attendee;
try {
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);
}
String status = new String(attendee.getFirstName() +
" " + attendee.getLastName() + "'s status is: " +
attendee.getStatus() + ".");
return new StringRepresentation(status);
}
@HttpMethod("POST")
@ConsumeMime("application/x-www-form-urlencoded")
@ProduceMime("text/html")
public Representation<String> createAttendee(Representation<FormURLEncodedProperties>
formData) {
Map<String,String> formDataContent = formData.getContent();
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 new StringRepresentation(response.toString(), "text/html");
}
@HttpMethod("DELETE")
@ProduceMime("text/html")
public Representation<String> removeInvitee(@UriParam("rsvpId") int id) {
logger.info("Received DELETE request for attendee ID " + id + ".");
StringBuffer response = new StringBuffer();
Attendee attendee;
try {
attendee = this.lookupAttendee(id);
if (attendee == null) {
logger.warning("Attendee " + id + " not found.");
return new StringRepresentation("<p>Attendee " + id + " not found.</p>", "text/html");
}
this.delete(attendee);
logger.info("Deleted attendee " + id);
response.append("<p>Removed attendee " + id + "</p>");
} catch (Exception e) {
response.append("<p>An error occurred when attempting " +
"to delete attendee ID " + id + ".");
logger.log(Level.SEVERE,"exception caught", e);
throw new RuntimeException(e);
}
return new StringRepresentation(response.toString(), "text/html");
}
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 Return there are two resource methods that respond to HTTP GET requests, returnStatusAsHtml and returnStatusAsPlainText. These methods extract the ID of the attendee from the URI Template specified by the @UriTemplate annotation. 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 single HTTP POST method, createAttendee, is used to create a new attendee. The @ConsumeMime("application/x-www-form-urlencoded") annotation is used to specify that the createAttendee method accepts input from URL encoded form data. The input parameter for createAttendee is a Representation<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 StringRepresentation object is then returned to the client with an HTML page showing the attendee's name, status, and ID.
The removeAttendee method responds to HTTP DELETE requests and is used to delete an attendee. The removeAttendee 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
- Select File→Open Project in NetBeans IDE 5.5.1.
- Navigate to <swdp.tutorial.home>/examples/rest, select rsvp, and click OK.
- 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.
- 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.
- (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
- Make sure your JavaDB instance is running.
- Open a terminal prompt and navigate to <swdp.tutorial.home>/examples/rest/rsvp.
- 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.
- 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.
- In a web browser navigate to:
http://<server>:<server port>/rsvp/
This page has an HTML form for creating attendees.
- 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.
- (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