JAX-RS consume a resource object - java

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.

Related

Why there is Internal server error , Unable to create node at /bin/searchServlet

I'm trying to create a servlet in AEM which uses the parameter from ajax and sends the response from URL back to ajax request
but when I hit button its throws an internal server error along with unable to create a node at /bin/searchServlet.
response from URL is in json format
here is my servlet
package com.community.aem.core.servlets;
import org.osgi.framework.Constants;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.HttpConstants;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.HttpResponse;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.sling.jcr.api.SlingRepository;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.rmi.ServerException;
import java.util.Base64;
import java.io.IOException;
import javax.servlet.Servlet;
import com.google.gson.Gson;
import com.google.gson.*;
#Component(service=Servlet.class,
property={
Constants.SERVICE_DESCRIPTION + "=Simple Demo Servlet",
"sling.servlet.methods=" + HttpConstants.METHOD_POST,
"sling.servlet.paths="+ "/bin/searchServlet"
})
public class slingdemo2 extends
org.apache.sling.api.servlets.SlingAllMethodsServlet {
private static final long serialVersionUID = 2598426539166789515L;
private SlingRepository repository;
#Reference
public void bindRepository(SlingRepository repository){
this.repository = repository;
}
public void unbindRepository(SlingRepository repository) {
this.repository = repository;
}
#Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
throws ServerException, IOException {
try
{
// Get the submitted form data that is sent from the
String query = request.getParameter("query");
//sending HTTP request and reading content using buffered reader
HttpResponse response1 = httpClient.execute(getRequest);
BufferedReader br = new BufferedReader(new InputStreamReader((response1.getEntity().getContent())));
String output;
String myJson = " ";
while ((output = br.readLine()) != null) {
myJson = myJson + output;
}
Gson gson = new Gson();
String jsonArray = gson.toJson(myJson);
response.getWriter().write(jsonArray);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
and here is my ajax query
$(document).ready(function(){
$('body').hide().fadeIn(1000);
$('#submit').click(function() {
var query= $('query').val() ;
$.ajax({
type: 'POST',
url:'/bin/searchServlet',
data:query,
success: function(responseText){
$('#result').val(responseText);
}
});
});
});
Maybe it would help if your Post(!) servlet would have code for post requests and not only for get requests.

JPOS Restful API send and receive data

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:

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

Testing Jersey resourse with parameters

I'm using Jersey resourse in my project, like:
#Path("/api")
public class MyResource {
#Path("/create")
#POST
#Consumes(MediaType.APPLICATION_XML)
#Produces(MediaType.APPLICATION_XML)
public Response handle(final String xml, #Context final HttpServletRequest request) {
.....
}
and I'm trying to test it:
public class MobipayResourceTest extends JerseyTest {
private MockHttpServletRequest servletRequest;
#Override
#Before
public void setUp() throws Exception {
servletRequest = new MockHttpServletRequest();
servletRequest.setMethod("POST");
}
public MobipayResourceTest() throws TestContainerException {
super("ua.privatbank.mobipay.api.resource");
}
#Test
public void testRes(){
WebResource webResource = resource();
webResource.path("/api/create").post(???); // I need to pass 2 parameters in the request - xml (in the body of post) and HttpServletRequest
}
How can I pass 2 my parameters (String xml and HttpServletRequest) to the resourse in test?
You don't need to pass the HttpServletRequest, I believe.
As to the xml parameter, I think you should have a parameter
of some other class there, not just of type String. For example
Item, Customer, Order, i.e. any business object (bean, POJO).
The way you've done it now, you'd better declare
#Consumes(MediaType.TEXT_PLAIN) because you declare that
you expect just a String in your method. Normally when
you expect XML, this XML value is unmarshalled into
an object of some type (usually a bean, POJO, etc). You
get this on the fly and you can just work with the object.
Here is some sample code of a sample Java client.
package com.company.api.test;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import com.google.gson.Gson;
import com.sun.jersey.api.client.Client;
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.client.filter.LoggingFilter;
import com.company.common.DateUtil;
import com.company.api.input.ItemOperation;
import com.company.api.input.ItemOperationData;
import com.company.api.result.ItemResult;
public class JavaClientREST {
public static void main(String[] args) throws Exception {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
client.addFilter(new LoggingFilter());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
WebResource service = client.resource(getBaseURI());
ItemOperation op1 = new ItemOperation();
op1.setItemID("447");
Date d1 = DateUtil.getDate(2013, Calendar.DECEMBER, 20);
System.out.println("DT1 = " + sdf.format(d1));
op1.setDate(d1);
op1.setOperation("pause");
String res = service.path("Item")
.entity(op1, MediaType.APPLICATION_XML)
.accept(MediaType.APPLICATION_JSON)
.post(String.class);
Gson gson = new Gson();
ItemResult result = gson.fromJson(res, ItemResult.class);
System.out.println("ID = [" + result.getId() + "]");
System.out.println("Error = [" + result.getError() + "]");
System.out.println("DONE!");
}
private static URI getBaseURI() {
return UriBuilder.fromUri("http://localhost:8080/api/service").build();
}
}

Categories