Having next code, which use RestEasy to get to a Twilio CALL info:
import java.util.Base64;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import com.twilio.rest.api.v2010.account.Call;
public class RestGetCallInfo1 {
public static void main(String[] args) {
try {
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget = client.target("https://api.twilio.com/2010-04-01/Accounts/AC99999999/Calls/CA77777777777.json");
String credentials = "AC99999999:888888888";
String base64encoded = Base64.getEncoder().encodeToString(credentials.getBytes());
Response response = target.request().header(HttpHeaders.AUTHORIZATION, "Basic " + base64encoded).get();
int status = response.getStatus();
if (status == 200) { //OK
Call call = response.readEntity(Call.class); //<------------- This fails!
System.out.println(call);
}
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
}
I want to ask you:
What 'Rest' libraries/tools does twilio-7.47.2-jar-with-dependencies.jar use inside (in order to use that instead of RestEasy)?
How can I get the JSON call object properly? with the actual code I get:
javax.ws.rs.ProcessingException: Unable to find a MessageBodyReader of content-type application/json and type class com.twilio.rest.api.v2010.account.Call
EDIT: I am able to get the Call info in JSon format with:
String call = response.readEntity(String.class);
Edit:
I tried to implement the suggestions of #Durgpal Singh and #Nikhil. I changed the code so it looks like this.
Client:
Client client = ClientBuilder.newClient();
WebTarget target = client
.target("http://localhost:8087/api/ls3algorithm/" + petrinets + "/" + Integer.toString(k) + "/" + Float.toString(theta));
Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON);
Response response = invocationBuilder.get();
Map<String, List<Map>> result_ = response.readEntity(new GenericType<Map<String, List<Map>>>() { });
result = (ArrayList<Map>) result_.get("data");
Server:
ArrayList<Map> result;
result = new Ls3Algorithm().execute(new File("petrinetze").getAbsolutePath(), k, theta);
Map<String, List<Map>> map = new HashMap<>();
map.put("data", result);
return Response.ok(map).build();
Unfortunately this leads to Exception in thread "main" org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyReader not found for media type=application/json, type=interface java.util.Map, genericType=java.util.Map<java.lang.String, java.util.List<java.util.Map>>.
Where do I go wrong?
-------------------------------
I'm pretty new to RESTful web services and currently writing a microservice which provides a calculating algorithm. I'm testing the service as posted below.
Workflow:
Client saves some data in a MongoDB database and sends the names of the relevant files via #PathParam as part of the GET request. The server then retrieves the files from the MongoDB, processes its algorithm and sends back the result as List<Map> packed in a Response object.
Goal:
Transfer the result (List<Map>) as JSON and print it out on the client console.
Client:
package ls3test;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Map;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.mongodb.DB;
import com.mongodb.MongoClient;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSInputFile;
public class Ls3TransmissionTest {
final static String petrinets = "eins, zwei, drei, vier";
final static int k = 3;
final static float theta = 0.9f;
public static void main(String[] args) throws IOException {
[... save all the relevant files in the MongoDB ...]
ArrayList<Map> result = new ArrayList<Map>();
Client client = ClientBuilder.newClient();
WebTarget target = client
.target("http://localhost:8087/api/ls3algorithm/" + petrinets + "/" + Integer.toString(k) + "/" + Float.toString(theta));
Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON);
Response response = invocationBuilder.get();
result = response.readEntity(new GenericType<ArrayList<Map>>() {
});
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(result);
}
}
Server:
package service;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.DB;
import com.mongodb.MongoClient;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.List;
import java.util.Map;
#SuppressWarnings("deprecation")
#Path("/ls3algorithm")
public class Resource {
// SLF4J is provided with Dropwizard
Logger log = LoggerFactory.getLogger(Resource.class);
#SuppressWarnings("rawtypes")
#GET
#Path("/{petrinets}/{k}/{theta}")
#Produces(MediaType.APPLICATION_JSON)
public Response ls3execute(#PathParam("petrinets") String petrinetNames, #PathParam("k") int k,
#PathParam("theta") float theta) {
[... get all the relevant files from the MongoDB ...]
List<Map> result;
Ls3Algorithm ls3Algorithm = new Ls3Algorithm();
result = ls3Algorithm.execute(new File("petrinetze").getAbsolutePath(), k, theta);
GenericEntity<List<Map>> entity = new GenericEntity<List<Map>>(result) {};
Response response = Response.ok(entity).build();
return response;
}
}
This is not working, the exception I get is posted below:
Exception in thread "main" org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyReader not found for media type=application/json, type=class java.util.ArrayList, genericType=java.util.ArrayList<java.util.Map>.
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:231)
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:155)
at org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:1085)
at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:874)
at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:834)
at org.glassfish.jersey.client.ClientResponse.readEntity(ClientResponse.java:368)
at org.glassfish.jersey.client.InboundJaxrsResponse$2.call(InboundJaxrsResponse.java:126)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:419)
at org.glassfish.jersey.client.InboundJaxrsResponse.runInScopeIfPossible(InboundJaxrsResponse.java:267)
at org.glassfish.jersey.client.InboundJaxrsResponse.readEntity(InboundJaxrsResponse.java:123)
at ls3test.Ls3TransmissionTest.main(Ls3TransmissionTest.java:89)
Ls3TransmissionTest.java:89 is ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
I spent plenty of time now doing research on this problem, but I cannot find an example that really fits it. What do I miss? Any help or hint is highly appreciated!
You can send a map. Like this
Map<String, Object> map = new HashMap<>();
map.put("data", entity);
Response.ok(map).build();
return Response;
Cannot see why do you need to wrap the List with GenericEntity. Something as simple as below will work:-
#SuppressWarnings("rawtypes")
#GET
#Path("/{petrinets}/{k}/{theta}")
#Produces(MediaType.APPLICATION_JSON)
public Response ls3execute(#PathParam("petrinets") String petrinetNames, #PathParam("k") int k,
#PathParam("theta") float theta) {
//[... get all the relevant files from the MongoDB ...]
List<Map> result;
Ls3Algorithm ls3Algorithm = new Ls3Algorithm();
result = ls3Algorithm.execute(new File("petrinetze").getAbsolutePath(), k, theta);
Response response = Response.ok(result).build();
return response;
}
And in the client side,
String result = response.readEntity(String.class);
return result;
I am working on restful api of spring and i am send parameters from my browser to my server(localhost). My server will call the link in world wide web and get the result. Here I am getting the exception.
Following is the original link i have to get the
https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term=science%5bjournal%5d+AND+breast+cancer+AND+2008%5bpdat%5d
THIS IS MY link i call in browser
http://localhost:8080/search?db=pubmed&term=science[journal]+AND+breast+cancer+AND+2008[pdat]
Please help me out.
package com.ncbi.team.utils;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import org.springframework.stereotype.Service;
enter code here
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
#Service
public class SearchReq {
public String browseURL(List <String> param )
throwsUnsupportedEncodingExce
ption{
StringBuffer sb = new StringBuffer();
String masterURL = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi";
System.out.println(param);
sb.append(masterURL);
for(int i=0;i<param.size();i++)
{
if(i==0){
sb.append("?");
sb.append(param.get(0));
}
else{
sb.append("&"+param.get(i));
}
}
System.out.println("URL Is :"+sb.toString());
Client c = Client.create();
String url=URLEncoder.encode(sb.toString(),"UTF-8");
// WebResource resource = c.resource(URLEncoder.encode(sb.toString(),"UTF-8"));
WebResource resource = c.resource(url);
//#SuppressWarnings("deprecation")
//WebResource resource = c.resource(sb.toString());
ClientResponse resp = resource.accept("text/html").get(ClientResponse.class);
String xml= null;
if(resp.getStatus() == 200){
xml = resp.getEntity(String.class);
}
return xml;
}
}
I was trying postman with a Java clientava client. I was getting the following output
com.squareup.okhttp.internal.http.RealResponseBody#c9673cf
the original output is
Curl -I "http://ec2-52-34-14-38.us-west-2.compute.amazonaws.com:14000/webhdfs/v1/user/ec2-user/prediction_output/part-00000?user.name=ec2-user&op=OPEN"
1234.566788
here is my java code.
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import java.io.IOException;
#Path("/hello")
public class HelloWorldService {
#GET
#Produces("application/json")
public Response getMsg() throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://ec2-52-34-14-38.us-west-2.compute.amazonaws.com:14000/webhdfs/v1/user/ec2-user/prediction_output/part-00000?user.name=ec2-user&op=OPEN")
.build();
com.squareup.okhttp.Response responses = null;
responses = client.newCall(request).execute();
System.out.println(responses);
return Response.status(200).entity(responses.body().toString()).build();
}
}
any help will be appreciated.
Use response.body().string() not toString().
Use the above also in System.out.println.
Your method getMsg() says #Produces("application/json") but your built response is text/plain.
Currently working on server sent events of html5 now. I made a servlet and set the
response.setContentType("text/event-stream");
as this. Now I get the update from this servlet on my client side and my client side code is as follows:
<script >
if(typeof(EventSource)!=="undefined")
{
var url = 'http://localhost:8080/KnockOut/DateFeed.jsp';
eventSource = new EventSource(url);
eventSource.onmessage = function (event) {
var theParagraph = document.createElement('p');
theParagraph.innerHTML = event.data.toString();
document.body.appendChild(theParagraph);
}
}
else
{
document.getElementById("result").innerHTML="Sorry, your browser does not support server-sent events...";
}
</script>
But when I change the url to call a rest full webservice written in java, it shows some error and I am note able to get the updated output.
The REST webservice code is:
#GET
public String getXml(#Context HttpHeaders header, #Context HttpServletResponse response) {
response.setHeader("cache-control", "no-cache");
response.setContentType("text/event-stream");
return "dataas: " + (new java.util.Date()).toString() + "x\n\n";
}
please help me.
Here i got the answer
import java.io.PrintWriter;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.enterprise.context.RequestScoped;
import org.glassfish.jersey.media.sse.EventOutput;
import org.glassfish.jersey.media.sse.OutboundEvent;
import org.glassfish.jersey.media.sse.SseFeature;
/**
* REST Web Service
*
* #author Irshad kk
*/
#Path("WS")
#RequestScoped
public class SSEResource {
#Context
private UriInfo context;
/**
* Creates a new instance of SSEResource
*/
public SSEResource() {
}
#GET
#Produces(SseFeature.SERVER_SENT_EVENTS)
public String getServerSentEvents() {
System.out.println("haii" + System.currentTimeMillis());
return "data: " + "irshad" + System.currentTimeMillis() + "\n\n";
}
}