JAVA- generate scheduled JSON - java

I started with this :http://examples.javacodegeeks.com/enterprise-java/rest/jersey/json-example-with-jersey-jackson/
and created a JSON on localhost:8080...
I am not sure if there is any way to generate new Json every 3 or 5 second. for example just add one digit to new JSON every 3 sec.
#Path("/LNU.se")
public class EntryPoint {
#GET
#Path("get")
#Produces(MediaType.TEXT_PLAIN)
public String test() {
return "mahdi Test";
}
#POST
#Path("post")
#Consumes(MediaType.TEXT_PLAIN)
public Response postTest(Track track){
String resault = " the track is saved mahdi: "+ track;
return Response.status(201).entity(resault).build();
}
}
and another class:
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
public class App {
public static void main(String[] args) {
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
Server jettyServer = new Server(8080);
jettyServer.setHandler(context);
ServletHolder jerseyServlet = context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0);
jerseyServlet.setInitParameter( "jersey.config.server.provider.classnames", EntryPoint.class.getCanonicalName());
try {
jettyServer.start();
System.out.println(" open your browser on http://localhost:8080/LNU.se/get");
jettyServer.join();
} catch (Exception e)
{
e.printStackTrace();
} finally {
jettyServer.destroy();
}
}
}
======================
UPDATE: -->
My server is:
package rest;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
public class RestServer {
public static void main(String[] args) throws Exception {
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
Server jettyServer = new Server(8080);
jettyServer.setHandler(context);
ServletHolder jerseyServlet = context.addServlet(
org.glassfish.jersey.servlet.ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0);
jerseyServlet.setInitParameter("jersey.config.server.provider.classnames",
Calculator.class.getCanonicalName());
try {
jettyServer.start();
System.out.println(" open the browser on http://localhost:8080/calculator/squareRoot?input=16");
jettyServer.join();
} finally {
jettyServer.destroy();
}
}
}
and this class:
package rest;
import java.awt.event.ItemEvent;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
#Path("calculator")
public class Calculator {
Result ress = new Result("mahdi84");
public static String resul1;
#GET
#Path("mahdi")
#Produces(MediaType.APPLICATION_JSON)
public Result mahdi(){
JSONObject json = new JSONObject();
json.put("validTime", "2016-02-24T11:00:00Z");
JSONArray jsonArray = new JSONArray();
JSONObject obj = new JSONObject();
obj.put("mcc", resul1);
obj.put("temprature", resul1+1);
obj.put("Humidity", resul1+10);
jsonArray.add(obj);
json.put("\n JSONdata --> ", jsonArray);
ress.setInput(Double.parseDouble(resul1));
ress.setOutput(Double.parseDouble(resul1));
ress.setTestVar(resul1);
ress.setTestVar2(json);
return ress;
}
#POST
#Path("/post")
#Consumes(MediaType.APPLICATION_JSON)
public Response createDataInJSON(String data) {
resul1= data;
return Response.status(201).entity(result).build();
}
static class Result{
double input;
double output;
String action;
Object testVar;
JSONObject testVar2;
public Result(){}
public JSONObject getTestVar2() {
return testVar2;
}
public void setTestVar2(JSONObject testVar2) {
this.testVar2 = testVar2;
}
public Object getTestVar() {
return testVar;
}
public void setTestVar(Object testVar) {
this.testVar = testVar;
}
public Result(String action) {
this.action = action;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public double getInput() {
return input;
}
public void setInput(double input) {
this.input = input;
}
public double getOutput() {
return output;
}
public void setOutput(double output) {
this.output = output;
}
}
}
and my client is:
import java.util.Timer;
import java.util.TimerTask;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class JerseyClientPost extends TimerTask{
public int cuntr = 0;
public static void main(String[] args) {
TimerTask mytask = new JerseyClientPost();
Timer timer = new Timer();
timer.schedule(mytask, 1000, 1000);
}
#Override
public void run() {
try {
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/calculator/post");
String input = Integer.toString(cuntr++);
ClientResponse response = webResource.type("application/json").post(ClientResponse.class, input);
if (response.getStatus() != 201) {
throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus());
}
String output = response.getEntity(String.class);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
the client will post to the server every 1 sec and the server will generate new JSON on "http://localhost:8080/calculator/mahdi"
when i try to read from "http://localhost:8080/calculator/mahdi" by apache http1.1 in another program :
package HttpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
public class MyHttpClient {
public static void main(String[] args) throws Exception{
HttpGet requset = new HttpGet("http://localhost:8080/calculator/mahdi");
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(requset);
HttpEntity entity = response.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
System.out.println("Reading began ... ");
while (true) {
String line = br.readLine();
if (line != null && !line.isEmpty()) {
System.out.println(line);
}
}
}
}
edit:
thank you I did that by using TImeTask class
it only print the first JSON! but when I refresh the weblink, it is updating on browser.
would you please correct me if I am wrong? I want to see the stream of JSON on MyHttpClient, but it only shows the first JSON!

I think you are mixing things. The server should only be a server, and not extend TimerTask. The client should call the server at a specific intervall
Do the follwing:
Test your server in a web-browser. Make sure that it will respond.
Write a client either in Java or javascript If you are using Java
the client should have a http-client.
The client should hava a timertask calling the the server at a specific intervall

Related

Send file using POST from a Java

I am trying to send file using java, i have a existing python which is working which needs to be converted to java.
Below is my python code,
with io.open('test.text', 'rb') as f:
r = requests.request("POST",'http://my_url/post', data=f)
My java code
HttpURLConnection httpUrlConnection = null;
URL url = new URL("http://my_url/post");
httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setRequestMethod("POST");
Now i am not sure how to pass the file to the post request
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
public class PostFile {
public static void main(String[] aaa) throws URISyntaxException{
final URI uri = new URIBuilder("http://httpbin.org/post")
.build();
HttpPost request = new HttpPost(uri);
File f = new File("file.txt");
request.setEntity(new FileEntity(f));
CloseableHttpAsyncClient client = HttpAsyncClients.custom().build();
client.start();
client.execute(request, new FutureCallback<HttpResponse>() {
#Override
public void completed(HttpResponse httpResponse) {
System.out.println("completed: " + httpResponse);
}
#Override
public void failed(Exception e) {
System.out.println("failed");
}
#Override
public void cancelled() {
System.out.println("cancelled");
}
});
}
}
Try this

How to make my restful server enable to support websocket client request (switchable)

The HTTP clients can fetch request from my restful API, but websocket clients getting error that my server cant switch the protocol.
I am newbie in protocols coding, how can I make my server support (and switch protocol) websocket client requests.
My jetty restful code:
import java.awt.List;
import java.awt.event.ItemEvent;
import java.security.PublicKey;
import java.util.ArrayList;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
#Path("lnu")
public class Generator {
Result ress = new Result("mahdi84");
public static String resul1;
public static ArrayList<Result> lst = new ArrayList<Result>();
public String txt = "TEXT";
#GET
#Path("mahdi")
#Produces(MediaType.APPLICATION_JSON)
public Result mahdi(){
JSONObject json = new JSONObject();
json.put("validTime", "2016-02-24T11:00:00Z");
JSONArray jsonArray = new JSONArray();
JSONObject obj = new JSONObject();
obj.put("mcc", resul1);
obj.put("temprature", resul1+1);
obj.put("Humidity", resul1+10);
jsonArray.add(obj);
json.put("\n JSONdata --> ", jsonArray);
ress.setInput(Double.parseDouble(resul1));
ress.setOutput(Double.parseDouble(resul1));
ress.setTestVar(resul1);
ress.setTestVar(txt);
ress.setTestVar2(json);
lst.add(ress);
return ress;
}
#POST
#Path("/post")
#Consumes(MediaType.APPLICATION_JSON)
public Response createDataInJSON(String data) {
String result = "---------> "+data;
resul1= data;
return Response.status(201).entity(result).build();
}
static class Result{
double input;
double output;
String action;
Object testVar;
Object testvar3;
JSONObject testVar2;
public Result(){}
public Object getTestvar3() {
return testvar3;
}
public void setTestvar3(Object testvar3) {
this.testvar3 = testvar3;
}
public JSONObject getTestVar2() {
return testVar2;
}
public void setTestVar2(JSONObject testVar2) {
this.testVar2 = testVar2;
}
public Object getTestVar() {
return testVar;
}
public void setTestVar(Object testVar) {
this.testVar = testVar;
}
public Result(String action) {
this.action = action;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public double getInput() {
return input;
}
public void setInput(double input) {
this.input = input;
}
public double getOutput() {
return output;
}
public void setOutput(double output) {
this.output = output;
}
}
}
And:
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
public class RestServer {
public static void main(String[] args) throws Exception {
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
Server jettyServer = new Server(8080);
jettyServer.setHandler(context);
ServletHolder jerseyServlet = context.addServlet(
org.glassfish.jersey.servlet.ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0);
jerseyServlet.setInitParameter("jersey.config.server.provider.classnames",
Generator.class.getCanonicalName());
try {
jettyServer.start();
System.out.println(" open the browser on http://localhost:8080/lnu/mahdi");
jettyServer.join();
} finally {
jettyServer.destroy();
}
}
}

Fast and asynchronous way of making multiple http requests in JAVA

I have a program that should make really fast http requests. Requests should be made asynchronously so that it won't block the main thread.
So I have created a queue which is observed by 10 separate threads that make http requests. If something is inserted in the queue then the first thread that gets the data will make the requests and process the result.
The queue gets filled with thousands of items so multithreading is really neccessary to get the response as fast as possible.
Since I have alot of code I'll give a short example.
main class
package fasthttp;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
public class FastHTTP {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
LinkedBlockingQueue queue = new LinkedBlockingQueue();
queue.add("http://www.lennar.eu/ip.php");//for example
executor.execute(new HTTPworker(queue));
}
}
}
FastHTTP class
package fasthttp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.LinkedBlockingQueue;
public class HTTPworker implements Runnable {
private final LinkedBlockingQueue queue;
public HTTPworker(LinkedBlockingQueue queue) {
this.queue = queue;
}
private String getResponse(String url) throws IOException {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
StringBuilder response;
try (BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
String inputLine;
response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}
return response.toString();
}
#Override
public void run() {
while (true) {
try {
String data = (String) queue.take();
String response = getResponse(data);
//Do something with response
System.out.println(response);
} catch (InterruptedException | IOException ex) {
//Handle exception
}
}
}
}
Is there a better or faster way to make thousands of http requests response processing asynchronously? Speed and performance is what I'm after.
Answering my own question. Tried Apaches asynchronous http client but after a while I started using Ning's async client and I am happy with it.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import org.apache.http.client.methods.HttpGet;
import java.util.Iterator;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
public class RestService {
private final static Executor executor = Executors.newCachedThreadPool();
private final static CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();
public static String sendSyncGet(final String url) {
return sendAsyncGet(List.of(url)).get(0);
}
public static List<String> sendAsyncGet(final List<String> urls){
List<GetRequestTask> tasks = urls.stream().map(url -> new GetRequestTask(url, executor)).collect(Collectors.toList());
List<String> responses = new ArrayList<>();
while(!tasks.isEmpty()) {
for(Iterator<GetRequestTask> it = tasks.iterator(); it.hasNext();) {
final GetRequestTask task = it.next();
if(task.isDone()) {
responses.add(task.getResponse());
it.remove();
}
}
//if(!tasks.isEmpty()) Thread.sleep(100); //avoid tight loop in "main" thread
}
return responses;
}
private static class GetRequestTask {
private final FutureTask<String> task;
public GetRequestTask(String url, Executor executor) {
GetRequestWork work = new GetRequestWork(url);
this.task = new FutureTask<>(work);
executor.execute(this.task);
}
public boolean isDone() {
return this.task.isDone();
}
public String getResponse() {
try {
return this.task.get();
} catch(Exception e) {
throw new RuntimeException(e);
}
}
}
private static class GetRequestWork implements Callable<String> {
private final String url;
public GetRequestWork(String url) {
this.url = url;
}
public String getUrl() {
return this.url;
}
public String call() throws Exception {
return closeableHttpClient.execute(new HttpGet(getUrl()), new BasicResponseHandler());
}
}
}

Different Result on DBPedia Spotlight by using the code and DBPedia Spotlight endpoint

This is the main class in which query is being fired
package extractKeyword;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.methods.GetMethod;
import org.dbpedia.spotlight.exceptions.AnnotationException;
import org.dbpedia.spotlight.model.DBpediaResource;
import org.dbpedia.spotlight.model.Text;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.LinkedList;
import java.util.List;
public class db extends AnnotationClient {
//private final static String API_URL = "http://jodaiber.dyndns.org:2222/";
private static String API_URL = "http://spotlight.dbpedia.org/";
private static double CONFIDENCE = 0.0;
private static int SUPPORT = 0;
// private static String powered_by ="non";
// private static String spotter ="CoOccurrenceBasedSelector";//"LingPipeSpotter"=Annotate all spots
//AtLeastOneNounSelector"=No verbs and adjs.
//"CoOccurrenceBasedSelector" =No 'common words'
//"NESpotter"=Only Per.,Org.,Loc.
//private static String disambiguator ="Default";//Default ;Occurrences=Occurrence-centric;Document=Document-centric
//private static String showScores ="yes";
#SuppressWarnings("static-access")
public void configiration(double CONFIDENCE,int SUPPORT)
//, String powered_by,String spotter,String disambiguator,String showScores)
{
this.CONFIDENCE=CONFIDENCE;
this.SUPPORT=SUPPORT;
// this.powered_by=powered_by;
//this.spotter=spotter;
//this.disambiguator=disambiguator;
//showScores=showScores;
}
public List<DBpediaResource> extract(Text text) throws AnnotationException {
// LOG.info("Querying API.");
String spotlightResponse;
try {
String Query=API_URL + "rest/annotate/?" +
"confidence=" + CONFIDENCE
+ "&support=" + SUPPORT
// + "&spotter=" + spotter
// + "&disambiguator=" + disambiguator
// + "&showScores=" + showScores
// + "&powered_by=" + powered_by
+ "&text=" + URLEncoder.encode(text.text(), "utf-8");
//LOG.info(Query);
GetMethod getMethod = new GetMethod(Query);
getMethod.addRequestHeader(new Header("Accept", "application/json"));
spotlightResponse = request(getMethod);
} catch (UnsupportedEncodingException e) {
throw new AnnotationException("Could not encode text.", e);
}
assert spotlightResponse != null;
JSONObject resultJSON = null;
JSONArray entities = null;
try {
resultJSON = new JSONObject(spotlightResponse);
entities = resultJSON.getJSONArray("Resources");
} catch (JSONException e) {
//throw new AnnotationException("Received invalid response from DBpedia Spotlight API.");
}
LinkedList<DBpediaResource> resources = new LinkedList<DBpediaResource>();
if(entities!=null)
for(int i = 0; i < entities.length(); i++) {
try {
JSONObject entity = entities.getJSONObject(i);
resources.add(
new DBpediaResource(entity.getString("#URI"),
Integer.parseInt(entity.getString("#support"))));
} catch (JSONException e) {
//((Object) LOG).error("JSON exception "+e);
}
}
return resources;
}
}
The extended class
package extractKeyword;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.dbpedia.spotlight.exceptions.AnnotationException;
import org.dbpedia.spotlight.model.DBpediaResource;
import org.dbpedia.spotlight.model.Text;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;
import javax.ws.rs.HttpMethod;
/**
* #author pablomendes
*/
public abstract class AnnotationClient {
//public Logger LOG = Logger.getLogger(this.getClass());
private List<String> RES = new ArrayList<String>();
// Create an instance of HttpClient.
private static HttpClient client = new HttpClient();
public List<String> getResu(){
return RES;
}
public String request(GetMethod getMethod) throws AnnotationException {
String response = null;
// Provide custom retry handler is necessary
( getMethod).getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
try {
// Execute the method.
int statusCode = client.executeMethod((org.apache.commons.httpclient.HttpMethod) getMethod);
if (statusCode != HttpStatus.SC_OK) {
// LOG.error("Method failed: " + ((HttpMethodBase) method).getStatusLine());
}
// Read the response body.
byte[] responseBody = ((HttpMethodBase) getMethod).getResponseBody(); //TODO Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
response = new String(responseBody);
} catch (HttpException e) {
// LOG.error("Fatal protocol violation: " + e.getMessage());
throw new AnnotationException("Protocol error executing HTTP request.",e);
} catch (IOException e) {
//((Object) LOG).error("Fatal transport error: " + e.getMessage());
//((Object) LOG).error(((HttpMethodBase) method).getQueryString());
throw new AnnotationException("Transport error executing HTTP request.",e);
} finally {
// Release the connection.
((HttpMethodBase) getMethod).releaseConnection();
}
return response;
}
protected static String readFileAsString(String filePath) throws java.io.IOException{
return readFileAsString(new File(filePath));
}
protected static String readFileAsString(File file) throws IOException {
byte[] buffer = new byte[(int) file.length()];
#SuppressWarnings("resource")
BufferedInputStream f = new BufferedInputStream(new FileInputStream(file));
f.read(buffer);
return new String(buffer);
}
static abstract class LineParser {
public abstract String parse(String s) throws ParseException;
static class ManualDatasetLineParser extends LineParser {
public String parse(String s) throws ParseException {
return s.trim();
}
}
static class OccTSVLineParser extends LineParser {
public String parse(String s) throws ParseException {
String result = s;
try {
result = s.trim().split("\t")[3];
} catch (ArrayIndexOutOfBoundsException e) {
throw new ParseException(e.getMessage(), 3);
}
return result;
}
}
}
public void saveExtractedEntitiesSet(String Question, LineParser parser, int restartFrom) throws Exception {
String text = Question;
int i=0;
//int correct =0 ; int error = 0;int sum = 0;
for (String snippet: text.split("\n")) {
String s = parser.parse(snippet);
if (s!= null && !s.equals("")) {
i++;
if (i<restartFrom) continue;
List<DBpediaResource> entities = new ArrayList<DBpediaResource>();
try {
entities = extract(new Text(snippet.replaceAll("\\s+"," ")));
System.out.println(entities.get(0).getFullUri());
} catch (AnnotationException e) {
// error++;
//LOG.error(e);
e.printStackTrace();
}
for (DBpediaResource e: entities) {
RES.add(e.uri());
}
}
}
}
public abstract List<DBpediaResource> extract(Text text) throws AnnotationException;
public void evaluate(String Question) throws Exception {
evaluateManual(Question,0);
}
public void evaluateManual(String Question, int restartFrom) throws Exception {
saveExtractedEntitiesSet(Question,new LineParser.ManualDatasetLineParser(), restartFrom);
}
}
The Main Class
package extractKeyword;
public class startAnnonation {
public static void main(String[] args) throws Exception {
String question = "What is the winning chances of BJP in New Delhi elections?";
db c = new db ();
c.configiration(0.25,0);
//, 0, "non", "AtLeastOneNounSelector", "Default", "yes");
c.evaluate(question);
System.out.println("resource : "+c.getResu());
}
}
The main problem is here when I am using DBPedia spotlight using spotlight jar (above code)then i am getting different result as compared to the dbpedia spotlight endpoint(dbpedia-spotlight.github.io/demo/)
Result using the above code:-
Text :-What is the winning chances of BJP in New Delhi elections?
Confidence level:-0.35
resource : [Election]
Result on DBPedia Spotlight endpoint(//dbpedia-spotlight.github.io/demo/)
Text:-What is the winning chances of BJP in New Delhi elections?
Confidence level:-0.35
resource : [Bharatiya_Janata_Party, New_Delhi, Election]
Why also the spotlight now don't have support as a parameter?

Internal Server Error when trying to send pojo class object in response on rest using jersey

I have a ResponseModel class, I want to send it's object in response to rest. But I am getting this error: A message body writer for Java class com.tcs.srl.message.model.ResponseModel, and Java type class com.tcs.srl.message.model.ResponseModel, and MIME media type application/json was not found
package com.tcs.DataShare.WebService;
import java.io.InputStream;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.*;
import javax.ws.rs.core.Response.ResponseBuilder;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.tcs.DataShare.Client.DataShareServiceClient;
import com.tcs.DataShare.Client.GetFilesOnLocal;
import com.tcs.DataShare.Constants.DataShareConstants;
import com.tcs.srl.message.model.ResponseModel;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
#Path("/ConfigureAndrew")
public class ConfigureAndrew {
private static final Logger LOGGER = LoggerFactory
.getLogger(ConfigureAndrew.class);
private ClientResponse response;
#Path("/configureAndrew")
#POST
//#Produces("application/octet-stream")
// #Produces("application/xml")
#Produces(MediaType.APPLICATION_JSON)
public Response configureAndrew(#Context HttpServletRequest requestObj,
String serviceData) {
System.out.println("methods");
LOGGER.debug("Inside Configure Andrew web service: ");
JSONParser parser = new JSONParser();
ResponseModel result = new ResponseModel();
// JSONObject result=null;
String isSuccess = "false";
try {
String headerString = requestObj.getHeader("header");
JSONObject serviceJSON = (JSONObject) parser.parse(serviceData);
String datashareURL = (String) serviceJSON
.get(DataShareConstants.DATASHARE_URL);
String datasharePort = (String) serviceJSON
.get(DataShareConstants.DATASHARE_PORT);
System.out.println("datasharePort: " + datasharePort);
String servicename = (String) serviceJSON
.get(DataShareConstants.SERVICE_NAME);
String appname = (String) serviceJSON
.get(DataShareConstants.APP_NAME);
String version = (String) serviceJSON
.get(DataShareConstants.APP_VERSION);
String path = (String) serviceJSON.get(DataShareConstants.APP_PATH);
DataShareServiceClient dataShareServiceClient = new DataShareServiceClient(
datashareURL, datasharePort, servicename);
InputStream inputStream = dataShareServiceClient
.zipFolderWithSubsequestFolder(path);
if (inputStream.available() != 0) {
System.out.println("In the input stream");
GetFilesOnLocal getFilesOnLocal = new GetFilesOnLocal();
result = getFilesOnLocal.getFiles(inputStream, result);
LOGGER.debug("Input stream contains data");
} else {
LOGGER.error("Input stream is empty");
System.out.println("error in input stream");
}
LOGGER.debug("DatashareServices :completed configure Andrew");
isSuccess = "true";
result.setSuccess("true");
result.setErrors(null);
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("DatashareServices :configureAndrew service failed "
+ e);
isSuccess = "false";
result.getErrors().add("Error in configureAndrew method");
}
return Response.status(200).entity(result).build();
}
}
Response Model POJO class::
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class ResponseModel implements Serializable{
String success;
List errors;
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
public List getErrors() {
return errors;
}
public void setErrors(List errors) {
this.errors = errors;
}
public List getWarnings() {
return warnings;
}
public void setWarnings(List warnings) {
this.warnings = warnings;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
List warnings;
Object data;
String transactionId;
public String getTransactionId() {
return transactionId;
}
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}

Categories