The customer Example Application - The Java EE 6 Tutorial (original) (raw)
2. Using the Tutorial Examples
3. Getting Started with Web Applications
4. JavaServer Faces Technology
7. Using JavaServer Faces Technology in Web Pages
8. Using Converters, Listeners, and Validators
9. Developing with JavaServer Faces Technology
10. JavaServer Faces Technology: Advanced Concepts
11. Using Ajax with JavaServer Faces Technology
12. Composite Components: Advanced Topics and Example
13. Creating Custom UI Components and Other Custom Objects
14. Configuring JavaServer Faces Applications
16. Uploading Files with Java Servlet Technology
17. Internationalizing and Localizing Web Applications
18. Introduction to Web Services
19. Building Web Services with JAX-WS
20. Building RESTful Web Services with JAX-RS
21. JAX-RS: Advanced Topics and Example
Annotations for Field and Bean Properties of Resource Classes
Extracting the Java Type of a Request or Response
Subresources and Runtime Resource Resolution
Integrating JAX-RS with EJB Technology and CDI
Using Java Objects to Model Your Data
Starting from an Existing XML Schema Definition
Using JSON with JAX-RS and JAXB
23. Getting Started with Enterprise Beans
24. Running the Enterprise Bean Examples
25. A Message-Driven Bean Example
26. Using the Embedded Enterprise Bean Container
27. Using Asynchronous Method Invocation in Session Beans
Part V Contexts and Dependency Injection for the Java EE Platform
28. Introduction to Contexts and Dependency Injection for the Java EE Platform
29. Running the Basic Contexts and Dependency Injection Examples
30. Contexts and Dependency Injection for the Java EE Platform: Advanced Topics
31. Running the Advanced Contexts and Dependency Injection Examples
32. Introduction to the Java Persistence API
33. Running the Persistence Examples
34. The Java Persistence Query Language
35. Using the Criteria API to Create Queries
36. Creating and Using String-Based Criteria Queries
37. Controlling Concurrent Access to Entity Data with Locking
38. Using a Second-Level Cache with Java Persistence API Applications
39. Introduction to Security in the Java EE Platform
40. Getting Started Securing Web Applications
41. Getting Started Securing Enterprise Applications
42. Java EE Security: Advanced Topics
Part VIII Java EE Supporting Technologies
43. Introduction to Java EE Supporting Technologies
45. Resources and Resource Adapters
46. The Resource Adapter Example
47. Java Message Service Concepts
48. Java Message Service Examples
49. Bean Validation: Advanced Topics
50. Using Java EE Interceptors
51. Duke's Bookstore Case Study Example
52. Duke's Tutoring Case Study Example
53. Duke's Forest Case Study Example
This section describes how to build and run the customer sample application. This example application is a RESTful web service that uses JAXB to perform the Create, Read, Update, Delete (CRUD) operations for a specific entity.
The customer sample application is in the tut-install/examples/jaxrs/customer/ directory. See Chapter 2, Using the Tutorial Examples for basic information on building and running sample applications.
Overview of the customer Example Application
The source files of this application are at tut-install/examples/jaxrs/customer/src/java/. The application has three parts:
- The Customer and Address entity classes. These classes model the data of the application and contain JAXB annotations. See The Customer and Address Entity Classes for details.
- The CustomerService resource class. This class contains JAX-RS resource methods that perform operations on Customer instances represented as XML or JSON data using JAXB. See The CustomerService Class for details.
- The CustomerClientXML and CustomerClientJSON client classes. These classes test the resource methods of the web service using XML and JSON representations of Customer instances. See The CustomerClientXML and CustomerClientJSON Classes for details.
The customer sample application shows you how to model your data entities as Java classes with JAXB annotations. The JAXB schema generator produces an equivalent XML schema definition file (.xsd) for your entity classes. The resulting schema is used to automatically marshal and unmarshal entity instances to and from XML or JSON in the JAX-RS resource methods.
In some cases you may already have an XML schema definition for your entities. See Modifying the Example to Generate Entity Classes from an Existing Schema for instructions on how to modify the customer example to model your data starting from an .xsd file and using JAXB to generate the equivalent Java classes.
The Customer and Address Entity Classes
The following class represents a customer’s address:
@XmlRootElement(name="address") @XmlAccessorType(XmlAccessType.FIELD) public class Address {
@XmlElement(required=true)
protected int number;
@XmlElement(required=true)
protected String street;
@XmlElement(required=true)
protected String city;
@XmlElement(required=true)
protected String state;
@XmlElement(required=true)
protected String zip;
@XmlElement(required=true)
protected String country;
public Address() { }
// Getter and setter methods
// ...
}
The @XmlRootElement(name="address") annotation maps this class to the address XML element. The @XmlAccessorType(XmlAccessType.FIELD)annotation specifies that all the fields of this class are bound to XML by default. The @XmlElement(required=true) annotation specifies that an element must be present in the XML representation.
The following class represents a customer:
@XmlRootElement(name="customer") @XmlAccessorType(XmlAccessType.FIELD) public class Customer {
@XmlAttribute(required=true)
protected int id;
@XmlElement(required=true)
protected String firstname;
@XmlElement(required=true)
protected String lastname;
@XmlElement(required=true)
protected Address address;
@XmlElement(required=true)
protected String email;
@XmlElement (required=true)
protected String phone;
public Customer() { }
// Getter and setter methods
// ...
}
The Customer class contains the same JAXB annotations as the previous class, except for the @XmlAttribute(required=true) annotation, which maps a property to an attribute of the XML element representing the class.
The Customer class contains a property whose type is another entity, the Addressclass. This mechanism allows you to define in Java code the hierarchical relationships between entities without having to write an .xsd file yourself.
JAXB generates the following XML schema definition for the two classes above:
<xs:schema version="1.0" xmlns:xs="" title="undefined" rel="noopener noreferrer">http://www.w3.org/2001/XMLSchema">
<xs:element name="address" type="address"/> <xs:element name="customer" type="customer"/>
<xs:complexType name="address"> xs:sequence <xs:element name="number" type="xs:int"/> <xs:element name="street" type="xs:string"/> <xs:element name="city" type="xs:string"/> <xs:element name="state" type="xs:string"/> <xs:element name="zip" type="xs:string"/> <xs:element name="country" type="xs:string"/>
<xs:complexType name="customer"> xs:sequence <xs:element name="firstname" type="xs:string"/> <xs:element name="lastname" type="xs:string"/> <xs:element ref="address"/> <xs:element name="email" type="xs:string"/> <xs:element name="phone" type="xs:string"/> <xs:attribute name="id" type="xs:int" use="required"/>
The file sample-input.xml in the top-level directory of the project contains an example of an XML representation of a customer:
Duke OfJava 1 Duke's Way JavaTown JA 12345 USA duke@example.com 123-456-7890The file sample-input.json contains an example of a JSON representation of a customer:
{ "@id": "1", "firstname": "Duke", "lastname": "OfJava", "address": { "number": 1, "street": "Duke's Way", "city": "JavaTown", "state": "JA", "zip": "12345", "country": "USA" }, "email": "duke@example.com", "phone": "123-456-7890" }
The CustomerService Class
The CustomerService class has a createCustomer method that creates a customer resource based on the Customer class and returns a URI for the new resource. The persist method emulates the behavior of the JPA entity manager. This example uses a java.util.Properties file to store data. If you are using the default configuration of GlassFish Server, the properties file is at domain-dir/CustomerDATA.txt.
@Path("/Customer") public class CustomerService { public static final String DATA_STORE = "CustomerDATA.txt"; public static final Logger logger = Logger.getLogger(CustomerService.class.getCanonicalName()); ...
@POST
@Consumes({"application/xml", "application/json"})
public Response createCustomer(Customer customer) {
try {
long customerId = persist(customer);
return Response.created(URI.create("/" + customerId)).build();
} catch (Exception e) {
throw new WebApplicationException(e,
Response.Status.INTERNAL_SERVER_ERROR);
}
}
...
private long persist(Customer customer) throws IOException {
File dataFile = new File(DATA_STORE);
if (!dataFile.exists()) {
dataFile.createNewFile();
}
long customerId = customer.getId();
Address address = customer.getAddress();
Properties properties = new Properties();
properties.load(new FileInputStream(dataFile));
properties.setProperty(String.valueOf(customerId),
customer.getFirstname() + ","
+ customer.getLastname() + ","
+ address.getNumber() + ","
+ address.getStreet() + ","
+ address.getCity() + ","
+ address.getState() + ","
+ address.getZip() + ","
+ address.getCountry() + ","
+ customer.getEmail() + ","
+ customer.getPhone());
properties.store(new FileOutputStream(DATA_STORE),null);
return customerId;
}
...
}
The response returned to the client has a URI to the newly created resource. The return type is an entity body mapped from the property of the response with the status code specified by the status property of the response. The WebApplicationException is a RuntimeException that is used to wrap the appropriate HTTP error status code, such as 404, 406, 415, or 500.
The @Consumes({"application/xml","application/json"}) and @Produces({"application/xml","application/json"}) annotations set the request and response media types to use the appropriate MIME client. These annotations can be applied to a resource method, a resource class, or even an entity provider. If you do not use these annotations, JAX-RS allows the use of any media type ("*/*").
The following code snippet shows the implementation of the getCustomer and findbyIdmethods. The getCustomer method uses the @Produces annotation and returns a Customer object, which is converted to an XML or JSON representation depending on the Accept:header specified by the client.
@GET @Path("{id}") @Produces({"application/xml", "application/json"}) public Customer getCustomer(@PathParam("id") String customerId) { Customer customer = null;
try {
customer = findById(customerId);
} catch (Exception ex) {
logger.log(Level.SEVERE,
"Error calling searchCustomer() for customerId {0}. {1}",
new Object[]{customerId, ex.getMessage()});
}
return customer;
}
private Customer findById(String customerId) throws IOException { properties properties = new Properties(); properties.load(new FileInputStream(DATA_STORE)); String rawData = properties.getProperty(customerId);
if (rawData != null) {
final String[] field = rawData.split(",");
Address address = new Address();
Customer customer = new Customer();
customer.setId(Integer.parseInt(customerId));
customer.setAddress(address);
customer.setFirstname(field[0]);
customer.setLastname(field[1]);
address.setNumber(Integer.parseInt(field[2]));
address.setStreet(field[3]);
address.setCity(field[4]);
address.setState(field[5]);
address.setZip(field[6]);
address.setCountry(field[7]);
customer.setEmail(field[8]);
customer.setPhone(field[9]);
return customer;
}
return null;
}
The CustomerClientXML and CustomerClientJSON Classes
Jersey is the reference implementation of JAX-RS (JSR 311). You can use the Jersey client API to write a test client for the customer example application. You can find the Jersey APIs at http://jersey.java.net/nonav/apidocs/latest/jersey/.
The CustomerClientXML class calls Jersey APIs to test the CustomerService web service:
package customer.rest.client;
import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import customer.data.Address; import customer.data.Customer; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.core.MediaType;
public class CustomerClientXML { public static final Logger logger = Logger.getLogger(CustomerClientXML.class.getCanonicalName());
public static void main(String[] args) {
Client client = Client.create();
// Define the URL for testing the example application
WebResource webResource =
client.resource("http://localhost:8080/customer/rest/Customer");
// Test the POST method
Customer customer = new Customer();
Address address = new Address();
customer.setAddress(address);
customer.setId(1);
customer.setFirstname("Duke");
customer.setLastname("OfJava");
address.setNumber(1);
address.setStreet("Duke's Drive");
address.setCity("JavaTown");
address.setZip("1234");
address.setState("JA");
address.setCountry("USA");
customer.setEmail("duke@java.net");
customer.setPhone("12341234");
ClientResponse response =
webResource.type("application/xml").post(ClientResponse.class,
customer);
logger.info("POST status: {0}" + response.getStatus());
if (response.getStatus() == 201) {
logger.info("POST succeeded");
} else {
logger.info("POST failed");
}
// Test the GET method using content negotiation
response = webResource.path("1").accept(MediaType.APPLICATION_XML)
.get(ClientResponse.class);
Customer entity = response.getEntity(Customer.class);
logger.log(Level.INFO, "GET status: {0}", response.getStatus());
if (response.getStatus() == 200) {
logger.log(Level.INFO, "GET succeeded, city is {0}",
entity.getAddress().getCity());
} else {
logger.info("GET failed");
}
// Test the DELETE method
response = webResource.path("1").delete(ClientResponse.class);
logger.log(Level.INFO, "DELETE status: {0}", response.getStatus());
if (response.getStatus() == 204) {
logger.info("DELETE succeeded (no content)");
} else {
logger.info("DELETE failed");
}
response = webResource.path("1").accept(MediaType.APPLICATION_XML)
.get(ClientResponse.class);
logger.log(Level.INFO, "GET status: {0}", response.getStatus());
if (response.getStatus() == 204) {
logger.info("After DELETE, the GET request returned no content.");
} else {
logger.info("Failed, after DELETE, GET returned a response.");
}
}
}
This Jersey client tests the POST, GET, and DELETE methods using XML representations.
All of these HTTP status codes indicate success: 201 for POST, 200 for GET, and 204 for DELETE. For details about the meanings of HTTP status codes, see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
The CustomerClientJSON class is similar to CustomerClientXML but it uses JSON representations to test the web service. In the CustomerClientJSON class "application/xml" is replaced by"application/json", and MediaType.APPLICATION_XML is replaced by MediaType.APPLICATION_JSON.
Modifying the Example to Generate Entity Classes from an Existing Schema
This section describes how you can modify the customer example if you provide an XML schema definition file for your entities instead of providing Java classes. In this case JAXB generates the equivalent Java entity classes from the schema definition.
For the customer example you provide the following .xsd file:
<xs:schema targetNamespace="http://xml.customer" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" xmlns:ora="" title="undefined" rel="noopener noreferrer">http://xml.customer">
<xs:element name="customer" type="ora:Customer"/>
<xs:complexType name="Address"> xs:sequence <xs:element name="number" type="xs:int"/> <xs:element name="street" type="xs:string"/> <xs:element name="city" type="xs:string"/> <xs:element name="state" type="xs:string"/> <xs:element name="zip" type="xs:string"/> <xs:element name="country" type="xs:string"/>
<xs:complexType name="Customer"> xs:sequence <xs:element name="firstname" type="xs:string"/> <xs:element name="lastname" type="xs:string"/> <xs:element name="address" type="ora:Address"/> <xs:element name="email" type="xs:string"/> <xs:element name="phone" type="xs:string"/> <xs:attribute name="id" type="xs:int" use="required"/>
You can modify the customer example as follows:
To Modify the customer Example to Generate Java Entity Classes from an Existing XML Schema Definition
- Create a JAXB binding to generate the entity Java classes from the schema definition. For example, in NetBeans IDE, follow these steps:
- Right click on the customer project and select New > Other...
- Under the XML folder, select JAXB Binding and click Next.
- In the Binding Name field, type CustomerBinding.
- Click Browse and choose the .xsd file from your file system.
- In the Package Name field, type customer.xml.
- Click Finish.
This procedure creates the Customer class, the Address class, and some JAXB auxiliary classes in the package customer.xml.
- Modify the CustomerService class as follows:
- Replace the customer.data.* imports with customer.xml.* imports and import the JAXBElement andObjectFactory classes:
import customer.xml.Customer;
import customer.xml.Address;
import customer.xml.ObjectFactory;
import javax.xml.bind.JAXBElement; - Replace the return type of the getCustomer method:
public JAXBElement getCustomer(
@PathParam("id") String customerId) {
...
return new ObjectFactory().createCustomer(customer);
}
- Replace the customer.data.* imports with customer.xml.* imports and import the JAXBElement andObjectFactory classes:
- Modify the CustomerClientXML and CustomerClientJSON classes as follows:
- Replace the customer.data.* imports with customer.xml.* imports and import the JAXBElement andObjectFactory classes:
import customer.xml.Address;
import customer.xml.Customer;
import customer.xml.ObjectFactory;
import javax.xml.bind.JAXBElement; - Create an ObjectFactory instance and a JAXBElement instance at the beginning of the main method:
public static void main(String[] args) {
Client client = Client.create();
ObjectFactory factory = new ObjectFactory();
WebResource webResource = ...;
...
customer.setPhone("12341234");
JAXBElement customerJAXB = factory.createCustomer(customer);
ClientResponse response = webResource.type("application/xml")
.post(ClientResponse.class, customerJAXB);
...
} - Modify the GET request after testing the DELETE method:
response = webResource.path("1").accept(MediaType.APPLICATION_XML)
.get(ClientResponse.class);
entity = response.getEntity(Customer.class);
logger.log(Level.INFO, "GET status: {0}", response.getStatus());
try {
logger.info(entity.getAddress().getCity());
} catch (NullPointerException ne) {
// null after deleting the only customer
logger.log(Level.INFO, "After DELETE, city is: {0}", ne.getCause());
}
The instructions for building, deploying, and running the example are the same for the original customer example and for the modified version using this procedure. - Replace the customer.data.* imports with customer.xml.* imports and import the JAXBElement andObjectFactory classes:
Running the customer Example
You can use either NetBeans IDE or Ant to build, package, deploy, and run the customer application.
To Build, Package, and Deploy the customer Example Using NetBeans IDE
This procedure builds the application into the tut-install/examples/jax-rs/customer/build/web/ directory. The contents of this directory are deployed to the GlassFish Server.
- From the File menu, choose Open Project.
- In the Open Project dialog, navigate to:
tut-install/examples/jaxrs/ - Select the customer folder.
- Select the Open as Main Project check box.
- Click Open Project.
It may appear that there are errors in the source files, because the files refer to JAXB classes that will be generated when you build the application. You can ignore these errors. - In the Projects tab, right-click the customer project and select Deploy.
To Build, Package, and Deploy the customer Example Using Ant
- In a terminal window, go to:
tut-install/examples/jaxrs/customer/ - Type the following command:
ant
This command calls the default target, which builds and packages the application into a WAR file, customer.war, located in the dist directory. - Type the following command:
ant deploy
Typing this command deploys customer.war to the GlassFish Server.
To Run the customer Example Using the Jersey Client
- In NetBeans IDE, expand the Source Packages node.
- Expand the customer.rest.client node.
- Right-click the CustomerClientXML.java file and select Run File.
The output of the client looks like this:
run:
Jun 12, 2012 2:40:20 PM customer.rest.client.CustomerClientXML main
INFO: POST status: 201
Jun 12, 2012 2:40:20 PM customer.rest.client.CustomerClientXML main
INFO: POST succeeded
Jun 12, 2012 2:40:20 PM customer.rest.client.CustomerClientXML main
INFO: GET status: 200
Jun 12, 2012 2:40:20 PM customer.rest.client.CustomerClientXML main
INFO: GET succeeded, city is JavaTown
Jun 12, 2012 2:40:20 PM customer.rest.client.CustomerClientXML main
INFO: DELETE status: 204
Jun 12, 2012 2:40:20 PM customer.rest.client.CustomerClientXML main
INFO: DELETE succeeded (no content)
Jun 12, 2012 2:40:20 PM customer.rest.client.CustomerClientXML main
INFO: GET status: 204
Jun 12, 2012 2:40:20 PM customer.rest.client.CustomerClientXML main
INFO: After DELETE, the GET request returned no content.
BUILD SUCCESSFUL (total time: 5 seconds)
The output is slightly different for the modified customer example:
run:
Jun 12, 2012 2:40:20 PM customer.rest.client.CustomerClientXML main
INFO: POST status: 201
[...]
Jun 12, 2012 2:40:20 PM customer.rest.client.CustomerClientXML main
INFO: DELETE succeeded (no content)
Jun 12, 2012 2:40:20 PM customer.rest.client.CustomerClientXML main
INFO: GET status: 200
Jun 12, 2012 2:40:20 PM customer.rest.client.CustomerClientXML main
INFO: After DELETE, city is: null
BUILD SUCCESSFUL (total time: 5 seconds)
To Run the customer Example Using the Web Services Tester
- In NetBeans IDE, right-click the customer node and select Test RESTful Web Services.
Note - The Web Services Tester works only with the modified version of the customerexample.
- In the Configure REST Test Client dialog, select Web Test Client in Project and click Browse.
- In the Select Project dialog, choose the customer project and click OK.
- In the Configure REST Test Client dialog, click OK.
- When the test client appears in the browser, select the Customer resource node in the left pane.
- Paste the following XML code into the Content text area, replacing “Insert content here”: Duke OfJava 1 Duke's Way JavaTown JA 12345 USA duke@example.com 123-456-7890 You can find the code in the file customer/sample-input.xml.
- Click Test.
The following message appears in the window below:
Status: 201 (Created) - Expand the Customer node and click {id}.
- Type 1 in the id field and click Test to test the GET method.
The following status message appears:
Status: 200 (OK)
The XML output for the resource appears in the Response window: Duke OfJava 1 Duke's Way JavaTown JA 12345 USA duke@example.com 123-456-7890 A GET for a nonexistent ID also returns a 200 (OK) status, but the output in the Response window shows no content: You can test other methods as follows: * Select PUT, type the input for an existing customer, modify any content except the id value, and click Test to update the customer fields. A successful update returns the following status message: Status: 303 (See Other) * Select DELETE, type the ID for an existing customer, and click Test to remove the customer. A successful delete returns the following status message: Status: 204 (See Other)
Using Curl to Run the customer Example Application
Curl is a command-line tool you can use to run the customerapplication on UNIX platforms. You can download Curl from http://curl.haxx.se or add it to a Cygwin installation.
Run the following commands in the directory tut-install/examples/jaxrs/customer/ after deploying the application.
To add a new customer and test the POST method using XML data, use the following command:
curl -i --data @sample-input.xml
--header Content-type:application/xml
http://localhost:8080/customer/rest/Customer
To add a new customer using JSON data instead, use the following command:
curl -i --data @sample-input.json
--header Content-type:application/json
http://localhost:8080/customer/rest/Customer
A successful POST returns HTTP Status: 201 (Created).
To retrieve the details of the customer whose ID is 1, use the following command:
curl -i -X GET http://localhost:8080/customer/rest/Customer/1
To retrieve the details of the same customer represented as JSON data, use the following command:
curl -i --header Accept:application/json -X GET http://localhost:8080/customer/rest/Customer/1
A successful GET returns HTTP Status: 200 (OK).
To delete a customer record, use the following command:
curl -i -X DELETE http://localhost:8080/customer/rest/Customer/1
A successful DELETE returns HTTP Status: 204.
The customer example and the modified version respond differently to a GET request for a customer ID that does not exist. The original customer example returns HTTP Status: 204 (No content), whereas the modified version returns HTTP Status: 200 (OK) with a response that contains the XML header but no customer data.
Copyright © 2013, Oracle and/or its affiliates. All rights reserved. Legal Notices