Wednesday, September 11, 2013

JAX-RS 1.x Tip of the Day: Using POST with JAX-RS

http://commons.wikimedia.org
I was looking over some more unpublished code, and found a simple gem that demonstrates how to use a HTTP POST with JAX-RS and a @Singleton.

The code was originally developed with JAX-RS 1.0, but I went back and retrofitted it to work on JAX-RS 1.1. The code has a @Singleton that manages the "Widgets" that are created using the HTTP POST. It is a simple and fun example of what you can do with JAX-RS.

It is a simple application that creates "Widget" objects and returns JSON with the widget data.

The code for the project can be found here: jersey-post-example

Note: This example application needs to be run on GlassFish 3.1.2+ because of an issue with Guava GlassFish 4.

JSON Response


WidgetSingleton.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
package com.bluelotussoftware.jersey.cdi;
 
import com.bluelotussoftware.jersey.misc.Widget;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.inject.Named;
import javax.inject.Singleton;
 
/**
 *
 * @author John Yeary
 */
@Named
@Singleton
public class WidgetSingleton implements Serializable {
 
    private static final long serialVersionUID = 939286339566082006L;
    private static final List<widget> widgets = new ArrayList<widget>();
 
    public WidgetSingleton() {
    }
 
    public List<widget> getWidgets() {
        return Collections.unmodifiableList(widgets);
    }
 
    public boolean add(Widget widget) {
        return widgets.add(widget);
    }
 
    public boolean remove(Widget widget) {
        return widgets.remove(widget);
    }
}

ExampleResource.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
package com.bluelotussoftware.jersey.cdi.resources;
 
import com.bluelotussoftware.jersey.cdi.WidgetSingleton;
import com.bluelotussoftware.jersey.misc.Widget;
import java.io.Serializable;
import java.util.List;
import java.util.ListIterator;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import org.apache.commons.codec.binary.Hex;
 
/**
 * REST Web Service
 *
 * @author John Yeary
 */
@Path("example")
@RequestScoped
public class ExampleResource implements Serializable {
 
    private static final long serialVersionUID = -8883891023988941637L;
    @Inject
    WidgetSingleton ws;
    @Context
    private UriInfo uriInfo;
 
    public ExampleResource() {
    }
 
    @GET
    @Produces({MediaType.APPLICATION_JSON})
    public GenericEntity<List<widget>> get() {
        return new GenericEntity<List<widget>>(ws.getWidgets()) {
        };
    }
 
    @GET
    @Path("{index}")
    @Produces({MediaType.APPLICATION_JSON})
    public Widget get(@PathParam("index") int index) {
        return ws.getWidgets().get(index);
    }
 
    /**
     * PUT method for updating or creating an instance of ExampleResource
     *
     * @param widget representation for the resource
     * @return an HTTP response with content of the updated or created resource.
     */
    @PUT
    @Consumes({MediaType.APPLICATION_JSON})
    @Produces({MediaType.APPLICATION_JSON})
    public Response put(Widget widget) {
        ListIterator<widget> iterator = ws.getWidgets().listIterator();
        boolean found = false;
        for (Widget w : ws.getWidgets()) {
            if (w.getName() != null && w.getName().equals(widget.getName())) {
                found = true;
                ws.remove(w);
                ws.add(widget);
            }
        }
 
        // This is not idempotent!
        if (!found) {
            ws.add(widget);
            UriBuilder uriBuilder = UriBuilder.fromUri(uriInfo.getRequestUri());
            uriBuilder.path("{index}");
            String index = String.valueOf(ws.getWidgets().lastIndexOf(widget));
            return Response.created(uriBuilder.build(index)).entity(widget).build();
        }
 
        return Response.ok(widget).build();
    }
 
    @POST
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    @Produces({MediaType.APPLICATION_JSON})
    public Response post(@FormParam("name") String name, @FormParam("value") String value) {
        Widget widget = new Widget(name, value);
        ws.add(widget);
        int index = ws.getWidgets().indexOf(widget);
        UriBuilder uriBuilder = UriBuilder.fromUri(uriInfo.getRequestUri());
        uriBuilder.path("{index}");
        EntityTag etag = new EntityTag(Hex.encodeHexString(widget.toString().getBytes()));
        return Response.created(uriBuilder.build(index)).
                tag(etag).
                entity(widget).
                type(MediaType.APPLICATION_JSON).
                build();
    }
}

Widget.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
package com.bluelotussoftware.jersey.misc;
 
import java.io.Serializable;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
 
/**
 *
 * @author John Yeary
 */
public class Widget implements Serializable {
 
    private static final long serialVersionUID = 679964674798270082L;
    private String name;
    private String value;
 
    public Widget() {
    }
 
    public Widget(String name, String value) {
        this.name = name;
        this.value = value;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getValue() {
        return value;
    }
 
    public void setValue(String value) {
        this.value = value;
    }
 
    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Widget other = (Widget) obj;
        if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
            return false;
        }
        if ((this.value == null) ? (other.value != null) : !this.value.equals(other.value)) {
            return false;
        }
        return true;
    }
 
    @Override
    public int hashCode() {
        int hash = 7;
        hash = 79 * hash + (this.name != null ? this.name.hashCode() : 0);
        hash = 79 * hash + (this.value != null ? this.value.hashCode() : 0);
        return hash;
    }
 
    @Override
    public String toString() {
        JSONObject jsono = new JSONObject(); // Quick way to return JSON.
        try {
            jsono.put("name", name);
            jsono.put("value", value);
 
        } catch (JSONException ignored) {
        }
        return jsono.toString();
    }
}

0 comments :

Popular Posts