Search This Blog

Monday 30 September 2013

Passing & Consuming JsonObject in a Jersey Exposed REST Services


---------------Part:1 ## passing JSON-Obj via a HttpPost Request---------------------

NOTE :: ## Include (json-lib-2.2.jar) for Creating a JsonObject ,etc..

private void callRestServices_JSON_Request(JSONObject jsonObj) {

    String RestURL = "http://localhost:4040/RestServicesExample2/rest/JSONRequest/";
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response;
HttpPost httpPost;
StringEntity entity;
List<NameValuePair> regParams =  new ArrayList<NameValuePair>();
try {
httpPost = new HttpPost(RestURL);
httpPost.setHeader("Accept", "application/json"); //Note this Step
httpPost.setHeader("Content-Type", "application/json"); //Note this Step
httpPost.setEntity(new StringEntity(jsonObj.toString())); //Note this Step

response = client.execute(httpPost);
               BufferedReader br = new BufferedReader(new                                                  InputStreamReader(response.getEntity().getContent()));
String res = "";
while((res=br.readLine())!=null){
System.out.println( "response  >>> "+response);
}

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}catch(URISyntaxException e){
e.printStackTrace();
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}

------------------Part:2 ## Consuming JSON-Obj via a HttpPost Request----------------

NOTE :: ##  Do Include the requisite jar(json-simple-1.1.1.jar) for creating JsonObject & JsonParser ..

@POST
@Path("/JSONRequest")
@Consumes(javax.ws.rs.core.MediaType.APPLICATION_JSON) //Note this Step
public String receiveJSONobject_Testing(String requestParam){

String name = "";
String phone = "";
String email = "";

org.json.simple.JSONParser jsonParser = new JSONParser();

org.json.simple.JSONObject jsonObj = new JSONObject();
try {
jsonObj = (JSONObject) jsonParser.parse(requestParam);
name = jsonObj.get("name").toString();
phone = jsonObj.get("phone").toString();
email = jsonObj.get("email").toString();

} catch (ParseException e) {
e.printStackTrace();
}

String response = ("Response from RestService >>> name recevd = "+name +"phone recevd >>                                            "+phone +" email recevd >> "+ email);

return response ;
}

-------------------------------------------------------------------------------------------------


Thursday 26 September 2013

java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to net.sf.json.JSONObject


Sep 27, 2013 11:42:56 AM com.sun.jersey.spi.container.ContainerResponse mapMappableContainerExceptionSEVERE: The RuntimeException could not be mapped to a response, re-throwing to the HTTP containerjava.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to net.sf.json.JSONObject

 The Exception is very clear ..
org.json.simple.JSONObject cannot be cast to net.sf.json.JSONObject
since ,  we are using making use of two diff libs here ..

 The problem here is that the "jsonParser.parse("-string-");" will return a org.json.simple.JSONObject (json-simple-1.1.1.jar) && we are trying to store in into a JsonObject vreated via net.sf.json.JSONObject (json-lib-2.2.jar)

 Solution -simply remove the use of "net.sf.json.JSONObject" to create a JsonObject & INSTEAD use org.json.simple.JSONObject create a JsonObject.


 Hence, your code will also be slightly modified given the way you extract key-values going further..

 BEFORE-- 

  //## here the requisite jar(json-simple-1.1.1.jar) for JsonParser is included in the jersey bundle itself..
org.json.simple.parser.JSONParser jsonParser = new JSONParser();

// ## Included json-lib-2.2.jar for using JsonObject ,etc..
net.sf.json.JSONObject jsonObj;
try {
jsonObj = (JSONObject) jsonParser.parse(requestParam);
name = jsonObj.getString("name");
phone = jsonObj.getString("phone");
email = jsonObj.getString("email");

} catch (ParseException e) {
e.printStackTrace();
}

AFTER --

//## here the requisite jar(json-simple-x.x.jar) for JsonParser is included in the jersey bundle itself..
org.json.simple.parser.JSONParser jsonParser = new JSONParser();

// ## Included json-lib-2.2.jar for using JsonObject ,etc..
org.json.simple.JSONObject jsonObj = new JSONObject();
try {
jsonObj = (JSONObject) jsonParser.parse(requestParam);
name = jsonObj.get("name").toString();
phone = jsonObj.get("phone").toString();
email = jsonObj.get("email").toString();

/*phone = jsonObj.getString("phone");
email = jsonObj.getString("email");*/

} catch (ParseException e) {
e.printStackTrace();
}

Creating Render & Action URLs in Liferay

    
Creating A RENDER URL :

Using tags:    (preferred in JSP's)
<portlet:renderURL var="assignAgentTargetURL">
        <portlet:param name="agentId" value="<%= String.valueOf(AgentListBean.get_agentId())%>" />
        <portlet:param name="jspPage" value="/html/crm/team/assignAgentTarget.jsp" />
 </portlet:renderURL> 

Otherwise: (often used in case you wanna redirect to outside of current Portlet)
ie this type of URL creation is often helpful in case you are in (Portlet A) and wanna redirect to some jsp in(Portlet B).
Note: in such a case you must specify the portletId.portlet-name (refer below : plid) of the target Portlet.

long plid1 = PortalUtil.getPlidFromPortletId(themeDisplay.getScopeGroupId(), com.prabhakar.portal.product.util.Constants.PRODUCT_PORTLET_NAME);

 LiferayPortletURL url = PortletURLFactoryUtil.create(actionRequest, com.prabhakar.portal.product.util.Constants.PRODUCT_PORTLET_NAME,  plid1, PortletRequest.RENDER_PHASE);

---------------------------------------------------------------------------------------------------------------------------------------------------

Creating A ACTION URL:

Using tags: (preferred in JSP's)

    <portlet:renderURL name="assignAgentTarget" var="assignAgentTargetURL">
        <portlet:param name="agentId" value="<%= String.valueOf(AgentListBean.get_agentId())%>" />
    </portlet:renderURL> 

Otherwise: (often used in case you wanna redirect to outside of current Portlet)
ie this type of URL creation is often helpful in case you are in (Portlet A) and wanna redirect to some jsp in(Portlet B).
Note: in such a case you must specify the portletId.portlet-name (refer below : plid) of the target Portlet.

long plid1 = PortalUtil.getPlidFromPortletId(themeDisplay.getScopeGroupId(), com.prabhakar.portal.product.util.Constants.PRODUCT_PORTLET_NAME);

 LiferayPortletURL url = PortletURLFactoryUtil.create(actionRequest, com.prabhakar.portal.product.util.Constants.PRODUCT_PORTLET_NAME,  plid1, PortletRequest.ACTION_PHASE);