Restlet implementing post with json receive and response –Best Practice

Here is one example forRestlet implementing post with json receive and response

1) Add maven dependency

<dependency>
<groupId>org.restlet.jse</groupId>
<artifactId>org.restlet.ext.json</artifactId>
<version>2.1-M1</version>
</dependency>
<dependency>
<groupId>org.restlet.jse</groupId>
<artifactId>org.restlet</artifactId>
<version>2.1-M1</version>
</dependency>
<dependency>
<groupId>org.restlet.jse</groupId>
<artifactId>org.restlet.lib.org.json</artifactId>
<version>2.0</version>
</dependency>

<dependency> <groupId>org.restlet.jse</groupId> <artifactId>org.restlet.ext.json</artifactId> <version>2.1-M1</version> </dependency> <dependency> <groupId>org.restlet.jse</groupId> <artifactId>org.restlet</artifactId> <version>2.1-M1</version> </dependency> <dependency> <groupId>org.restlet.jse</groupId> <artifactId>org.restlet.lib.org.json</artifactId> <version>2.0</version> </dependency>

2) implement server side resource

import org.json.JSONException;

import org.json.JSONObject;

import org.json.JSONStringer;

import org.restlet.data.Status;

import org.restlet.ext.json.JsonRepresentation;

import org.restlet.representation.Representation;

import org.restlet.resource.Post;

import org.restlet.resource.ResourceException;

import org.restlet.resource.ServerResource;

public class PrefPushResource extends ServerResource {

@Post(“json:json”)

public Representation acceptJson(JsonRepresentation represent)

throws ResourceException {

Representation rep = null;

try {

// Representation entity = getRequestEntity();

// JsonRepresentation represent = new JsonRepresentation(entity);

JSONObject jsonobject = represent.getJsonObject();

String requestString = jsonobject.getString(“request”);

JSONObject json = new JSONObject(requestString);

String user = json.getString(“user_email”);

String itemUrl = json.getString(“item_url”);

String source = json.getString(“source”);

String action = json.getString(“action”);

double score = json.getDouble(“score”);

//getResponse().setStatus(Status.SUCCESS_ACCEPTED);

getResponse().setStatus(Status.SUCCESS_ACCEPTED);

JSONStringer jsReply = new JSONStringer();

jsReply.object();

jsReply.key(“CODE”).value(“SUCCESS”);

jsReply.key(“DESC”).value(“Process Sucessfully”);

jsReply.endObject();

rep = new JsonRepresentation(jsReply);

getResponse().setStatus(Status.SUCCESS_OK);

} catch (Exception e) {

e.printStackTrace();

JSONStringer jsReply = new JSONStringer();

try {

jsReply.object();

jsReply.key(“CODE”).value(“Error”);

jsReply.key(“DESC”).value(e.getMessage());

jsReply.endObject();

} catch (JSONException e1) {

e1.printStackTrace();

}

getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);

}

return rep;

}

}

3) implement server side application

import org.restlet.Application;

import org.restlet.Component;

import org.restlet.Restlet;

import org.restlet.data.Protocol;

import org.restlet.routing.Router;

import org.restlet.service.MetadataService;

public class DiscoveryApplication  extends Application{

/**

* Creates a root Restlet that will receive all incoming calls.

*/

@Override

public synchronized Restlet createInboundRoot() {

// Create a router Restlet that routes each call to a new instance of HelloWorldResource.

Router router = new Router(getContext());

// Defines only one route

router.attach(“/pref/push”, PrefPushResource.class);

return router;

}

public static void main(String[] args) throws Exception {

MetadataService media = new MetadataService();

media.getAllMediaTypes(null);

// Create a new Component.

Component component = new Component();

// Add a new HTTP server listening on port 8182.

component.getServers().add(Protocol.HTTP, 8182);

// Attach the sample application.

component.getDefaultHost().attach(“/discovery”,

new DiscoveryApplication());

// Start the component.

component.start();

}

}

4) implement client test application
import java.io.IOException;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;
import org.restlet.data.MediaType;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;
public class PrefPushResourceClient {
public static void main(String[] argv) throws JSONException, IOException {
JSONStringer jsRequest = new JSONStringer();
JSONStringer js = new JSONStringer();
try {
js.object();
jsRequest.object();
jsRequest.key(“user_email”).value(“hhuiwen@cn.ibm.com”);
jsRequest.key(“item_url”).value(“http://thoughtclicks.com/status”);
jsRequest.key(“source”).value(“tap”);
jsRequest.key(“action”).value(“try”);
jsRequest.key(“score”).value(2.0);
jsRequest.endObject();
js.key(“request”).value(jsRequest);
js.endObject();
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println(jsRequest.toString());
System.out.println(js.toString());
ClientResource requestResource = new ClientResource(
“http://localhost:8182/discovery/pref/push”);
Representation rep;
rep = new JsonRepresentation(js);
rep.setMediaType(MediaType.APPLICATION_JSON);
Representation reply = requestResource.post(rep);
String replyText = reply.getText();
System.out.println(“Reply Text:” + replyText);
System.out.println(“Reply Media Type:” + reply.getMediaType());
reply.write(System.out);
if (reply.getMediaType().equals(new MediaType(“application/json”))) {
JSONObject jsObj = new JSONObject(replyText);
String code = jsObj.getString(“CODE”);
String desc = jsObj.getString(“DESC”);
System.out.println(“Code:” + code + “,DESC:” + desc);
}
reply.release();
}
}
Some notes:
1) Post annonation,
a) your method must have one input parameter. if the method has no parameter ,it will return a HTTP 415 not supported media type error
@Documented
@Retention(value=RUNTIME)
@Target(value=METHOD)
public @interface Post

Annotation for methods that accept submitted representations. Its semantics is equivalent to an HTTP POST method. Note that your method must have one input parameter if you want it to be selected for requests containing an entity.

Example:

 @Post
 public MyOutputBean accept(MyInputBean input);

 @Post("json")
 public String acceptJson(String value);

 @Post("xml|json:xml|json")
 public Representation accept(Representation xmlValue);
b) Specifies the media type of the request and response entities as
 extensions. If only one extension is provided, the extension applies to
 both request and response entities. If two extensions are provided,
 separated by a colon, then the first one is for the request entity and
 the second one for the response entity.
public abstract String value
Specifies the media type of the request and response entities as extensions.
If only one extension is provided, the extension applies to both request and response entities.
If two extensions are provided, separated by a colon,
then the first one is for the request entity and the second one for the response entity.
If several media types are supported, their extension can be specified
separated by "|" characters. Note that this isn't the full MIME type
value, just the extension name declared in MetadataService. For a list of all predefined extensions,
please check MetadataService.addCommonExtensions().
New extension can be registered using
MetadataService.addExtension(String, org.restlet.data.Metadata) method.
Returns:
The media types of request and/or response entities.
Default:
""
Detail please please see :http://www.restlet.org/documentation/2.0/jse/api/org/restlet/resource/Post.html

some reference:
http://stackoverflow.com/questions/1352202/restlet-implementing-post-with-json-receive-and-response
http://www.restlet.org/documentation/2.0/jse/api/org/restlet/resource/Post.html
http://wiki.restlet.org/docs_2.1/13-restlet/21-restlet/318-restlet/303-restlet.html
http://wiki.restlet.org/docs_2.1/13-restlet/21-restlet/378-restlet.html
http://stackoverflow.com/questions/1255948/post-data-in-json-format-with-javascript