JPOS Restful API send and receive data - java

I configure the RESTFul API in JPOS from jpos-rest.pdf.
The problem is I couldn't receive data from the client, but I can send data to the client.
In Echo.java class by below code I can send data:
package org.jpos.rest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.HashMap;
import java.util.Map;
#Path("/echo")
public class Echo {
#GET
#Produces({MediaType.APPLICATION_JSON})
public Response echoGet() {
Map<String, Object> resp = new HashMap<>();
resp.put("success", "true");
resp.put("Name", "Hamid");
resp.put("Family", "Mohammadi");
Response.ResponseBuilder rb = Response.ok(resp, MediaType.APPLICATION_JSON).status(Response.Status.OK);
return rb.build();
}
}
How can I receive data from the client? There is no request parameter to find what is the request and its data;

Thanks to #Sabir Khan
I changed the code to:
#Path("/echo")
public class Echo {
#PUT
#Produces({MediaType.APPLICATION_JSON})
#Consumes(MediaType.TEXT_PLAIN)
#Path("/{name}/{family}")
public Response echoGet(
#PathParam("name") String name,
#PathParam("family") String family,
String Desc
) {
Map<String, Object> resp = new HashMap<>();
resp.put("success", "true");
resp.put("Name", name);
resp.put("Family", family);
resp.put("Desc", Desc);
Response.ResponseBuilder rb = Response.ok(resp,
MediaType.APPLICATION_JSON).status(Response.Status.OK);
return rb.build();
}
}
and send data to RESTFul API like this:

Related

RESTFUL web services - client application not linking to web service

If this has been asked somewhere before, please let me know. The crux of the problem may be similar, I'm not sure.
I basically have two programs on Eclipse. A client and a web service with rest (I'm using REST 3.1.3 by the way). The problem, quite simply, is that my client app is not linking to the restful web service to get the request I'm asking for.
Namely, I'm trying to get a list of author channels from the web service's own database. The problem is not that the service can't retrieve the data itself, rather than that the client can't access the web service to get THAT data from it and then display in its own JSP.
Here is the method from the client app that I'm trying to use:
#SuppressWarnings("unchecked")
#Override
public List<Channel> getAllChannels() {
Client client = ClientBuilder.newClient();
System.out.println("Client created.");
WebTarget target = client.target("http://localhost:8080/RESTService/examples/channels/authorchannels");
Response response = target.request().accept(MediaType.TEXT_PLAIN, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON).get();
List<Channel> channels = null;
if (response.getStatus() != 200) {
System.out.println("Could not retrieve!" );
} else {
channels = (List<Channel>) response.getEntity();
System.out.println(response.getMediaType().toString());
System.out.println(response.readEntity(String.class));
}
return channels;
}
It belongs to the following interface and class:
class Channel.java:
package examples.pubhub.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="channels")
public class Channel implements Serializable {
#Id
#Column(name="channel_user")
private String channel_user;
#Id
#Column(name="channel_bio")
private String channel_bio;
public Channel() {
}
public Channel(String user, String bio) {
super();
this.channel_user = user;
this.channel_bio = bio;
}
interface ChannelDAO.java :
package examples.pubhub.dao;
import java.util.List;
import examples.pubhub.model.Channel;
public interface ChannelDAO {
public List<Channel> getAllChannels();
public Channel getChannelByAuthorUser(String author_user);
public void createAuthorChannel(String author_user);
}
The method would send a get request to the following method in the web service:
AuthorChannel.java (from RESTService):
#GET
#Consumes({MediaType.TEXT_PLAIN, MediaType.APPLICATION_XML,
MediaType.APPLICATION_JSON})
#Path("authorchannels")
public List<Response> getAllChannels() {
Session session = DAOUtilities.getSessionFactory().openSession();
session.beginTransaction();
Query query = session.createQuery("from Channel");
#SuppressWarnings("unchecked")
List<Object> channels = query.list();
session.getTransaction().commit();
ResponseBuilder respBuilder = null;
if (channels == null)
respBuilder = Response.status(Response.Status.NOT_FOUND);
else
respBuilder = Response.status(Response.Status.OK);
respBuilder.entity(channels);
System.out.println("Channels? " + channels);
System.out.println("Users? " + ((Channel)
channels.get(0)).getChannel_user());
System.out.println("Bios? " + ((Channel)
channels.get(0)).getChannel_bio());
return (List<Response>) respBuilder.build();
}
When I try to test this on Postman, it gives me a 404. I'm not sure what's wrong. I'm thinking the URI might be incorrect, but I'm noticing conflicting theories on how the URI should be written.
My biggest problem is mostly misinformation on this topic; any help would be appreciated. If you want to see anything else from the code, please let me know.
Controller code:
package methods;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import org.hibernate.Query;
import org.hibernate.Session;
import model.Channel;
import resources.DAOUtilities;
#Path("/channels")
public class AuthorChannel {
#POST
#Path("/{id}")
#Consumes({MediaType.TEXT_PLAIN, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public void createAuthorChannel(#PathParam("id") String user, #QueryParam("bio") String bio) {
Session session = DAOUtilities.getSessionFactory().openSession();
Channel channel = new Channel();
channel.setChannel_bio(bio);
channel.setChannel_user(user);
session.save(channel);
session.flush();
session.getTransaction().commit();
}
#GET
#Consumes({MediaType.TEXT_PLAIN, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
#Path("/authorchannels")
public List<Response> getAllChannels() {
Session session = DAOUtilities.getSessionFactory().openSession();
session.beginTransaction();
Query query = session.createQuery("from Channel");
#SuppressWarnings("unchecked")
List<Object> channels = query.list();
session.getTransaction().commit();
ResponseBuilder respBuilder = null;
if (channels == null)
respBuilder = Response.status(Response.Status.NOT_FOUND);
else
respBuilder = Response.status(Response.Status.OK);
respBuilder.entity(channels);
System.out.println("Channels? " + channels);
System.out.println("Users? " + ((Channel) channels.get(0)).getChannel_user());
System.out.println("Bios? " + ((Channel) channels.get(0)).getChannel_bio());
return (List<Response>) respBuilder.build();
}
#GET
#Path("/{id}")
#Produces({MediaType.TEXT_PLAIN, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response getChannelByAuthorUser(#PathParam("id") String channel_user) {
Session session = DAOUtilities.getSessionFactory().openSession();
Query query = session.createQuery("from Channel where channel_user = :channel_user");
query.setParameter("channel_user", channel_user);
Channel channel = (Channel) query.uniqueResult();
session.getTransaction().commit();
ResponseBuilder respBuilder = null;
if (channel == null)
respBuilder = Response.status(Response.Status.NOT_FOUND);
else
respBuilder = Response.status(Response.Status.OK);
respBuilder.entity(channel);
return respBuilder.build();
}
}

How to POST in REST Service using Hibernate and Jersey

I wasn't able to find out proper format how to send Response back to .JSP page after POST. First, how to obtain Response from Web service to Client?
Second question is how to call Client from Servlet.
Because second part is quite straightforward (create class instance in servlet in the proper doGet, doPost method), I will focus on the first question.
Snippet on the server side:
import java.math.BigInteger;
import java.util.List;
import java.util.logging.Logger;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.hibernate.SessionFactory;
// internal beans and classes
import com.deepam.util.BasicUtils;
import entities.CustomerRest;
import entities.DualInteger;
import entities.Dualloc;
import model.CustomerModel;
import model.DualModel;
import model.HibernateUtil;
#Path("/customer")
public class CustomerRestWS {
private final static Logger LOGGER = Logger.getLogger(CustomerRestWS.class.getName());
private CustomerModel cm = new CustomerModel();
private DualModel dm = new DualModel();
private final String CUSTSEQ = "customer_rest_seq";
SessionFactory sessionFactory;
/** Constructor
*/
public CustomerRestWS() {
super();
LOGGER.info("***" + LOGGER.getName());
sessionFactory = HibernateUtil.getSessionFactory();
}
...
#GET
#Path("/findcustseq")
#Produces(MediaType.APPLICATION_XML)
public DualInteger selectCustSeq() {
return cm.selectCustSeqNative(CUSTSEQ);
}
// post method how to save customer into DB
#POST
#Path("/create")
#Consumes(MediaType.APPLICATION_XML)
#Produces(MediaType.APPLICATION_JSON) // JSON is used for clearity between Consumes/Produces on the Client side
public Response create(final CustomerRest cust) throws JSONException {
Response response;
LOGGER.info("***" + LOGGER.getName() + " Insert Customer, id, name, last name: " + cust.getId() + ", " + cust.getFirstName() + ", " + cust.getLastName());
try {
cm.create(cust);
}
catch (Exception ex) {
// internal error
LOGGER.info("***" + LOGGER.getName() + " Exception: " + ex.getMessage());
response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(Response.Status.INTERNAL_SERVER_ERROR.toString()).build();
return response;
}
// created
response = Response.status(Response.Status.CREATED)
.entity(Response.Status.CREATED.toString()).build();
return response;
}
...
On the Client side:
import java.text.MessageFormat;
import java.util.logging.Logger;
import javax.ws.rs.core.MediaType;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.DefaultClientConfig;
// internal beans
import entities.Customer;
import entities.DualInteger;
import entities.ListCustomers;
public class CustomerRestfulClient {
private final static Logger LOGGER = Logger.getLogger(CustomerRestfulClient.class.getName());
private WebResource webresource;
private Client client;
private static final String BASE_URI = "http://localhost:8080/RestfulOracleServer/rest/";
public CustomerRestfulClient() {
// init client
client = Client.create(new DefaultClientConfig());
// init webresource
webresource = client.resource(BASE_URI).path("customer");
}
...
/** method getCustIdXML for obtaining unique ID (from sequence) */
public DualInteger getCustIdXML() throws UniformInterfaceException {
WebResource resource = webresource.path(MessageFormat.format("findcustseq", new Object[] {}));
return resource.accept(MediaType.APPLICATION_XML).get(DualInteger.class);
}
/** method saveCustXML call other method to obtain unique ID, than save Bean to DB */
public ClientResponse saveCustXML(String firstName, String lastName) throws UniformInterfaceException {
DualInteger custId = getCustIdXML();
LOGGER.info("Seqence number: " + (custId.getSeq()));
Customer cust = new Customer(custId.getSeq(), firstName, lastName);
ClientResponse response = webresource.path("create").
accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_XML).post(ClientResponse.class, cust);
LOGGER.info("Entity: " + response.getStatus());
return response;
}
Notice classes Response on the Server side and ClientResponse on the Client Side. Look how are treated #Consumes, #Produces annotations on server side to and accept, type methods on the Client side. There were my sources of errors.
In servlet Controller for .jsp simply create Client for WS e.g. custClient = new CustomerRestfulClient(); in constructor and use the obvious methods doGet, doPost as obvious. The Servlet has its own Request, Response different from Request, Response of WS. Be carefully in MVC model, Controller is treated by server as Singleton. In concurrent environment you must keep session continuity. (The most simple way is to use local variables in methods, when it is indicated.) Links to similar topics:
Is it ok by REST to return content after POST?
RESTful Java Client with POST method

JAX-RS consume a resource object

service with the Jersey implementation of JAX-RS. My Question is if it is possible to consume an object that is represented by an URI directly. I'm sorry if my wording is wrong but I'm a beginner when it comes to web-services, REST and Marshalling/Unmarschalling.
To illustrate my problem I've made an example web-service.
First I created a POJO that will be published and consumed by the web-service
package com.test.webapp.resources;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement
public class SomeData {
private String name;
private String id;
private String description;
public SomeData() {
}
public SomeData(String id, String name, String description) {
this.id = id;
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public String getId() {
return id;
}
public String getDescription() {
return description;
}
#Override
public String toString() {
return "SomeData [id="
+ id
+ ", name="
+ name
+ ", description="
+ description + "]";
}
}
Next the web-service that will publish the data:
package com.test.webapp.resources;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
#Path("/data")
public class DataResource {
#Context
private UriInfo uriInfo;
#Context
private Request request;
private static SomeData firstData = new SomeData("1",
"Important Data",
"First Test Data");
private static SomeData secondData = new SomeData("2",
"Very Important Data",
"Second Test Data");
private static SomeData thirdData = new SomeData("3",
"Some Data",
"Third Test Data");
private static List<SomeData> someDataList = new ArrayList<>();
static {
someDataList.add(firstData);
someDataList.add(secondData);
someDataList.add(thirdData);
}
#GET
#Path("/someData/list")
#Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public List<SomeData> getSomeData() {
return someDataList;
}
#GET
#Path("/someData/{id}")
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public SomeData getSomeDataSingle(#PathParam("id") int id) {
try {
SomeData data = someDataList.get(id);
return new SomeData(data.getId(),
data.getName(),
data.getDescription());
}
catch (IndexOutOfBoundsException e){
throw new RuntimeException("Data with id: "
+ id + " was not found");
}
}
#POST
#Path("/someSummary/create/all/uri")
#Consumes(MediaType.APPLICATION_XML)
public Response createSumaryFromUrl(String someDataResourceString) {
URI someDataResource = null;
try {
someDataResource = new URI(someDataResourceString);
}
catch (URISyntaxException e1) {
e1.printStackTrace();
}
List<SomeData> theDataList = this.comsumeData(someDataResource);
String summaryString = "";
for(SomeData data : theDataList) {
summaryString += data.getDescription() + " ";
}
return Response.status(201).entity(summaryString).build();
}
private List<SomeData> comsumeData(URI someDataResource) {
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures()
.put(JSONConfiguration.FEATURE_POJO_MAPPING,
Boolean.TRUE);
Client client = Client.create(clientConfig);
WebResource webResource = client.resource(someDataResource);
List<SomeData> dataListFromGet = webResource
.accept(MediaType.APPLICATION_JSON)
.get(new GenericType<List<SomeData>>(){});
return dataListFromGet;
}
}
Now I create a Jersey Client to do a post and create a summary.
package com.test.webapp.client;
import java.net.URI;
import javax.ws.rs.core.MediaType;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
public class JerseyClient {
public static void main(String[] args) {
try {
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
Client client = Client.create(clientConfig);
WebResource webResource = client.resource("http://localhost:8080/WebApp");
URI someDataListResource = new URI("http://localhost:8080/WebApp/data/someData/list");
ClientResponse response = webResource
.path("data/someSummary/create/all/uri")
.accept(MediaType.APPLICATION_XML)
.type(MediaType.APPLICATION_XML)
.post(ClientResponse.class, someDataListResource.toString());
if(response.getStatus() != 201) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
System.out.println(response.getEntity(String.class));
}
catch(Exception e) {
e.printStackTrace();
}
}
}
So this works all good and well. However I think this is some kind of workaround to create a client inside the web-service to consume a resource. What I would like to do is remove the client all together inside the web-service and consume the object behind a resource directly.
Something like this:
In the web-service:
#POST
#Path("/someSummary/create/all")
#Consumes(MediaType.APPLICATION_XML)
public Response createSumary(List<SomeData> someDataList) {
String summaryString = "";
for(SomeData data : someDataList) {
summaryString += data.getDescription() + " ";
}
return Response.status(201).entity(summaryString).build();
}
And in the client something like this:
URI someDataListResource = new URI("http://localhost:8080/WebApp/data/someData/list");
ClientResponse response = webResource
.path("data/someSummary/create/all/uri")
.accept(MediaType.APPLICATION_XML)
.type(MediaType.APPLICATION_XML)
.post(ClientResponse.class, someDataListResource);
Is this possible or do I get something wrong?
Sorry if this is a trivial question but I did some research and couldn't find anything probably because my search therms are wrong due to my inexperience.
Thank you for your efforts in advance.
First, yes, if you want to consume URIs, you will need to do it by hand. You could write a custom class like this:
public class SomeDataList extends ArrayList<SomeData> {
public static SomeDataList valueOf(String uri) {
// fetch the URI & create the list with the objects, return it.
}
// other methods
}
And just use this specific class in your request:
#POST
#Path("/someSummary/create/all/uri")
#Consumes(MediaType.APPLICATION_XML)
public Response createSumaryFromUrl(#QueryParam("uri") SomeDataList someDataResourceString) {
//....
}
However, it looks to me that the specific objects you want to retrieve are already in the server, so there's no need to do a round-trip over HTTP+REST - just find them directly.

Getting Unauthorized 401 error from Google Cloud Messaging and I am using Server API key with all IPs allowed

I have the following DropWizard resource which is supposed to make a Google Cloud Messaging request and return the response. I keep on getting Unauthorized 401 error.
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
#Path(value="/gcm")
#Produces(MediaType.APPLICATION_JSON)
public class GcmResource {
Client client;
public GcmResource(Client client) {
this.client = client;
}
#GET
public String sendMsg() {
WebResource r = client.resource("https://android.googleapis.com/gcm/send");
r.header("Authorization", "key=MY_SERVER_API_KEY");
r.accept(MediaType.APPLICATION_JSON);
r.type(MediaType.APPLICATION_JSON);
ClientResponse res = r.post(ClientResponse.class, "{\"registration_ids\":[\"ABC\"]}");
return res.getEntity(String.class);
}
}
I am using a valid API key.
My API key is of type "Server (with IP blocking)".
I have no IPs in the block list. So, all IPs are allowed.
I also ran the above code from my web-hosting server, there too I get the same error.
What am I doing wrong?
Finally I found the bug in the above code. I actually wrote a PHP code to dump all Http request it receives - header and body. I changed the above code to send request to my PHP code instead. That is when I noticed that none of the headers I set were being sent! Then I noticed the bug.
I had assumed that lines like r.header("Authorization", "key=MY_SERVER_API_KEY") actually modify r. I was wrong. They return a new Builder object which has those changes. So, now the below modified version works.
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
#Path(value="/gcm")
#Produces(MediaType.APPLICATION_JSON)
public class GcmResource {
Client client;
public GcmResource(Client client) {
this.client = client;
}
#GET
public String sendMsg() {
WebResource r = client.resource("https://android.googleapis.com/gcm/send");
ClientResponse res = r
.header("Authorization", "key=MY_SERVER_API_KEY")
.accept(MediaType.APPLICATION_JSON)
.type(MediaType.APPLICATION_JSON)
.post(ClientResponse.class, "{\"registration_ids\":[\"ABC\"]}");
return res.getEntity(String.class);
}
}

Passing an object to a REST Web Service using Jersey

I have a simple WS that is a #PUT and takes in an object
#Path("test")
public class Test {
#PUT
#Path("{nid}"}
#Consumes("application/xml")
#Produces({"application/xml", "application/json"})
public WolResponse callWol(#PathParam("nid") WolRequest nid) {
WolResponse response = new WolResponse();
response.setResult(result);
response.setMessage(nid.getId());
return response;
}
and my client side code is...
WebResource wr = client.resource(myurl);
WolResponse resp = wr.accept("application/xml").put(WolResponse.class, wolRequest);
I am trying to pass an instance of WolRequest into the #PUT Webservice. I am constantly getting 405 errors trying to do this..
How can I pass an object from the client to the server via Jersey ? Do I use a query param or the request ?
Both my POJOs (WolRequest and WolResponse) have the XMlRootElement tag defined so i can produce and consume xml..
I think the usage of the #PathParam is not correct here. A #PathParam is can basically be a String (see its javadoc for more info).
You can
use the #PathParam as a String parameter or
don't define WolRequest as a #PathParam.
The first approach:
#Path("test")
public class Test {
#PUT
#Path("{nid}")
#Consumes("application/xml")
#Produces({"application/xml", "application/json"})
public WolResponse callWol(#PathParam("nid") String nid) {
WolResponse response = new WolResponse();
response.setResult(result);
response.setMessage(nid);
return response;
}
This will accept urls like: "text/12", 12 will then be the String nid. It doesn't look like this will help what you are trying to do.
The second approach:
#Path("test")
public class Test {
#PUT
#Consumes("application/xml")
#Produces({"application/xml", "application/json"})
public WolResponse callWol(WolRequest nid) {
WolResponse response = new WolResponse();
response.setResult(result);
response.setMessage(nid.getId());
return response;
}
Your client code can be like you specified, only the url for PUT is: "test". Perhaps you need a combination of both one #PathParam for your id and one "normal" parameter to get your request data.
Check this link https://www.vogella.com/tutorials/REST/article.html
As per the code sample of method putTodo of class TodoResource ,
your code should be like this.
#Path("test")
public class Test{
#PUT
#Consumes("application/xml")
#Produces({"application/xml", "application/json"})
public WolResponse callWol(JAXBElement<WolRequest> nid) {
WolResponse response = new WolResponse();
response.setResult(result);
response.setMessage(nid.getValue().getId());
return response;
}
}
Hope this will solve your problem.
You can try something like this
#POST
#Path("/post")
#Consumes(MediaType.APPLICATION_XML)
#Produces(MediaType.APPLICATION_XML)
public Response callWol(WolRequest nid) {
WolResponse response = new WolResponse();
response.setResult(result);
response.setMessage(nid.getValue().getId());
return Response.status(Status.OK).entity(response).build();
}
You can try #PUT instead of #Post as well. Hope this helps
I had the same problem I solved in 3 Steps with Jackson in Netbeans/Glashfish btw.
1)Requirements :
some of the Jars I used :
commons-codec-1.10.jar
commons-logging-1.2.jar
log4j-1.2.17.jar
httpcore-4.4.4.jar
jackson-jaxrs-json-provider-2.6.4.jar
avalon-logkit-2.2.1.jar
javax.servlet-api-4.0.0-b01.jar
httpclient-4.5.1.jar
jackson-jaxrs-json-provider-2.6.4.jar
jackson-databind-2.7.0-rc1.jar
jackson-annotations-2.7.0-rc1.jar
jackson-core-2.7.0-rc1.jar
If I missed any of the jar above , you can download from Maven here http://mvnrepository.com/artifact/com.fasterxml.jackson.core
2)Java Class where you send your Post.
First ,Convert with Jackson the Entity User to Json and then send it to your Rest Class.
import com.fasterxml.jackson.databind.ObjectMapper;
import ht.gouv.mtptc.siiv.model.seguridad.Usuario;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.simple.JSONObject;
public class PostRest {
public static void main(String args[]) throws UnsupportedEncodingException, IOException {
// 1. create HttpClient
DefaultHttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost
= new HttpPost("http://localhost:8083/i360/rest/seguridad/obtenerEntidad");
String json = "";
Usuario u = new Usuario();
u.setId(99L);
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", u.getId());
// 4. convert JSONObject to JSON to String
//json = jsonObject.toString();
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
//ObjectMapper mapper = new ObjectMapper();
//json = mapper.writeValueAsString(person);
ObjectMapper mapper = new ObjectMapper();
json = mapper.writeValueAsString(u);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json,"UTF-8");
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
//inputStream = httpResponse.getEntity().getContent();
}
}
3)Java Class Rest where you want to receive the Entity JPA/Hibernate .
Here with your MediaType.APPLICATION_JSON you recieve the Entity in this way :
""id":99,"usuarioPadre":null,"nickname":null,"clave":null,"nombre":null,"apellidos":null,"isLoginWeb":null,"isLoginMovil":null,"estado":null,"correoElectronico":null,"imagePerfil":null,"perfil":null,"urlCambioClave":null,"telefono":null,"celular":null,"isFree":null,"proyectoUsuarioList":null,"cuentaActiva":null,"keyUser":null,"isCambiaPassword":null,"videoList":null,"idSocial":null,"tipoSocial":null,"idPlanActivo":null,"cantidadMbContratado":null,"cantidadMbConsumido":null,"cuotaMb":null,"fechaInicio":null,"fechaFin":null}"
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.apache.log4j.Logger;
#Path("/seguridad")
public class SeguridadRest implements Serializable {
#POST
#Path("obtenerEntidad")
#Consumes(MediaType.APPLICATION_JSON)
public JSONArray obtenerEntidad(Usuario u) {
JSONArray array = new JSONArray();
LOG.fatal(">>>Finally this is my entity(JPA/Hibernate) which
will print the ID 99 as showed above :" + u.toString());
return array;//this is empty
}
..
Some tips : If you have problem with running the web after using this code may be because of the #Consumes in XML ... you must set it as #Consumes(MediaType.APPLICATION_JSON)
Try this it will work
Server Side:
#PUT
#Consumes(MediaType.APPLICATION_XML)
#Produces(MediaType.APPLICATION_XML)
public String addRecord(CustomClass mCustomClass)
{
///
///
///
return "Added successfully : "+CustomClass.getName();
}// addRecord
Client Side:
public static void main(String[] args)
{
///
///
///
CustomClass mCustomClass = new CustomClass();
Client client = ClientBuilder.newClient();
String strResult = client.target(REST_SERVICE_URL).request(MediaType.APPLICATION_XML).put(Entity.xml(mCustomClass), String.class);
}

Categories