Saturday, December 31, 2011

JAX-RS Tip of the Day: Using YUI2 and YUI3 DataTables with Jersey and jQuery

This is a great example (if I do say so myself) that demonstrates some really cool capabilities of Jersey combined with Yahoo User Interface versions 2 and 3 combined with jQuery to demonstrate interoperability of multiple technologies.

The example code that I have included uses GlassFish 3.1.1 with Jersey 1.11 and was developed using NetBeans 7.1 RC2. The data is from the default sample database included in NetBeans. Here is the code: jsonp-database.zip

The YUI2, YUI3, and jQuery libraries are provided by Yahoo and Google CDN. This is a further example of a truly RESTful application where the application is provided as a mashup of multiple web resources.

Yahoo User Interface (YUI) is an incredibly well developed UI framework for the web. The DataSource implementation is easy to use and is extremely adaptable. It is also very stable, and Yahoo eats its own dogfood like Google so it is battle tested. YUI3 is the next generation code, and the DataTable implementation includes a number of new features.

jQuery is an extremely popular Javascript framework with great AJAX functionality. I have included two examples (YUI2/YUI3) in which jQuery provides JSON data to the Yahoo DataSource.

Jersey provides the heavy lifting. In all of the examples I provide the data in a variety of formats, but I focus on providing both JSON and JSONP. JSONP allows us to use have cross-domain capabilities. The code also demonstrates how to use Jettison to encapsulate POJOs. The best part is that the data can be tested not only using your browser, but can also be tested using curl. This provides a very simple visual means of verifying data.

So what does it look like... look at the images below. The results speak for themselves.

YUI2 DataTable using JSP

YUI3 DataTable with JSONP and JAX-RS (Jersey)

Now for the most important part, how do you get here.

Technical Details

The CustomerFacadeREST class is the most interesting. The JSP and HTML pages have the details of how to use the various YUI DataSources along with jQuery. I will not print the pages out, and suggest that you simply download the code and examine it.

CustomerFacadeREST.java


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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
/*
 * Copyright 2011 Blue Lotus Software, LLC.
 * Copyright 2011 John Yeary <jyeary@bluelotussoftware.com>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bluelotussoftware.example.jaxrs.resources;
 
import com.bluelotussoftware.example.jaxrs.model.Customer;
import com.sun.jersey.api.json.JSONWithPadding;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.*;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
 
/**
 *
 * @author John Yeary <jyeary@bluelotussoftware.com>
 * @version 1.0
 */
@Stateless
@Path("customers")
public class CustomerFacadeREST extends AbstractFacade<customer> {
 
    @PersistenceContext(unitName = "demoPU")
    private EntityManager em;
 
    public CustomerFacadeREST() {
        super(Customer.class);
    }
 
    @POST
    @Override
    @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public void create(Customer entity) {
        super.create(entity);
    }
 
    @PUT
    @Override
    @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public void edit(Customer entity) {
        super.edit(entity);
    }
 
    @DELETE
    @Path("{id}")
    public void remove(@PathParam("id") Integer id) {
        super.remove(super.find(id));
    }
 
    @GET
    @Path("json/{id}")
    @Produces({MediaType.APPLICATION_JSON})
    public JSONObject findJSONObject(@PathParam("id") Integer id) {
        Customer c = super.find(id);
        JSONObject jSONObject = new JSONObject();
        try {
            jSONObject.put("customerId", c.getCustomerId());
            jSONObject.put("name", c.getName());
            jSONObject.put("addressLine1", c.getAddressline1());
            jSONObject.put("addressLine2", c.getAddressline2());
            jSONObject.put("city", c.getCity());
            jSONObject.put("state", c.getState());
            jSONObject.put("phone", c.getPhone());
            jSONObject.put("fax", c.getFax());
            jSONObject.put("email", c.getEmail());
            jSONObject.put("creditLimit", c.getCreditLimit());
        } catch (JSONException ex) {
            throw new WebApplicationException(ex, Response.Status.INTERNAL_SERVER_ERROR);
        }
        return jSONObject;
    }
 
    @GET
    @Path("{id}")
    @Produces({"application/javascript", "application/ecmascript", "application/x-ecmascript",
        "application/x-javascript"})
    public JSONWithPadding find(@PathParam("id") Integer id,
            @QueryParam(value = "callback") String callback) {
        return new JSONWithPadding(super.find(id), callback);
    }
 
    @GET
    @Produces({"application/javascript", "application/ecmascript", "application/x-ecmascript",
        "application/x-javascript"})
    public JSONWithPadding getCustomers(@QueryParam("callback") String callback) {
        return new JSONWithPadding(new GenericEntity<List<customer>>(super.findAll()) {
        }, callback);
    }
 
    @GET
    @Produces({MediaType.APPLICATION_JSON})
    @Path("json")
    public List<customer> getCustomersJSON() {
        return super.findAll();
    }
 
    @GET
    @Produces({"application/javascript", "application/ecmascript", "application/x-ecmascript",
        "application/x-javascript"})
    @Path("alternate")
    public JSONWithPadding getCustomersAlternate1(@QueryParam("callback") String callback) {
        return new JSONWithPadding(super.findAll(), callback);
    }
 
    //FIXME This returns an unexpected result of toString() on the Customer objects.
    @GET
    @Produces({"application/javascript", "application/ecmascript", "application/x-ecmascript",
        "application/x-javascript"})
    @Path("alternate2")
    public JSONWithPadding getCustomersAlternate2(@QueryParam(value = "callback") String callback) {
        JSONArray jSONArray = new JSONArray(super.findAll());
        return new JSONWithPadding(jSONArray, callback);
    }
 
    @GET
    @Path("{from}/{to}")
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public List<customer> findRange(@PathParam("from") Integer from, @PathParam("to") Integer to) {
        return super.findRange(new int[]{from, to});
    }
 
    @GET
    @Path("count")
    @Produces("text/plain")
    public String countREST() {
        return String.valueOf(super.count());
    }
 
    @java.lang.Override
    protected EntityManager getEntityManager() {
        return em;
    }
}

CODE


Here is the code: jsonp-database.zip

0 comments :

Popular Posts