Jersey webservice returning a null JSON - java

I want to get the data of a database table to the client end. I'm sending the data via a JSON. When I print the output result in the client end it gives the following result.
{"pricing":null}
When I print return statement in the server end, it outputs the following
[Connection.Pricing#3d5bae2]
There are no errors. What have I done wrong?
Here is my Client Side Code
public String loadTable(String tablename) throws ClientProtocolException, IOException {
pathParams.add("tablename", tablename);
ClientResponse response = service.path("access").path("loadtable").queryParams(pathParams).type(MediaType.APPLICATION_JSON).get(ClientResponse.class);
String responseString = response.getEntity(String.class);
return responseString;
This is my Server End
#Path("/loadtable")
#GET
#Produces(MediaType.APPLICATION_JSON)
public List<Pricing> loadTable(#QueryParam("tablename") String tablename) throws Exception {
List<Pricing> pricing = new ArrayList<Pricing>();
try {
query = c.prepareStatement("select * from " + tablename);
ResultSet ets_rs = query.executeQuery();
while (ets_rs.next()) {
pricing.add(new Pricing(ets_rs.getString(1), ets_rs.getString(2), ets_rs.getString(3), ets_rs.getString(4), ets_rs.getString(5), ets_rs.getString(6)));
}
query.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (c != null) {
c.close();
}
}
return pricing;
Here is my POJO class in the server end
#XmlRootElement
class Pricing {
String category;
String lower_limit;
String class_no;
String value;
String employee;
String upper_limit;
public Pricing() {
}
Pricing(String a, String b, String c, String d, String e, String f) {
category = a;
lower_limit = b;
upper_limit = c;
class_no = d;
value = e;
employee = f;
}
//getters
}

You need to override toString method in your Pricing class to print the object in a beautiful way. The default toString() method shows the object class and its hash code separated by # character and hence you see this
Pricing#3d5bae2
Here is one implmentation of toString method for Pricing class:
#Override
public String toString() {
return "Pricing [category=" + category + ", lower_limit=" + lower_limit
+ ", class_no=" + class_no + ", value=" + value + ", employee="
+ employee + ", upper_limit=" + upper_limit + "]";
}

Related

After adding #Around advice for all of my REST Controller methods request don't return any JSON data

I've implemented REST Controller methods and they work fine when there is no aspects implemented.
After I implement aspects, controller methods still execute fine in background(i.e DELETE request actually deletes entries), but when i'm testing responses with Postman, i don't get any responses. Aspects do work, and txt file gets updated when methods get invoked.
#RestController
public class MovieScreeningREST {
#Autowired
private MovieScreeningService movieScreeningService;
#GetMapping("/movies")
public List<MovieScreening> findAll(){
return movieScreeningService.findAll();
}
#GetMapping("/movies/genre={movieGenre}")
public List<MovieScreening> findAllByMovieGenre(#PathVariable String movieGenre){
return movieScreeningService.findAllByMovieGenre(movieGenre);
}
#GetMapping("/movies/minimum-tickets={amount}")
public List<MovieScreening> findAllByTicketsSoldGreaterThanEqual(#PathVariable int amount){
return movieScreeningService.findAllByTicketsSoldGreaterThanEqual(amount);
}
#GetMapping("/movies/maximum-screenings={amount}")
public List<MovieScreening> findAllByScreeningsNumberLessThanEqual(#PathVariable int amount){
return movieScreeningService.findAllByScreeningsNumberLessThanEqual(amount);
}
#GetMapping("/movies/id={id}")
public MovieScreening findById(#PathVariable int id){
return movieScreeningService.findById(id);
}
#PostMapping("/movies")
public MovieScreening addMovieScreening(#RequestBody MovieScreening movieScreening){
return movieScreeningService.save(movieScreening);
}
#PutMapping("/movies")
public MovieScreening editMovieScreening(#RequestBody MovieScreening movieScreening){
return movieScreeningService.save(movieScreening);
}
#DeleteMapping("/movies/id={id}")
public String deleteMovieScreening(#PathVariable int id){
return movieScreeningService.deleteById(id);
}
}
Aspect class
#EnableAspectJAutoProxy
#Aspect
#Component
public class Logger {
#Pointcut("execution(* asss.pj.projekat_bioskop.controller.*.*(..))")
public void allRESTMethods(){};
#Around("allRESTMethods()")
public void blabla(ProceedingJoinPoint pjp) {
//#Before
String methodName = pjp.getSignature().getName();
String before = "*** Attempting " + methodName + " method ***";
writeLog(before);
try {
//#AfterReturning
pjp.proceed();
String success = "\n*** Method " + methodName + " has succeeded";
writeLog(success);
} catch (Throwable throwable){
//#AfterThrowing
String failed = "\n*** Method " + methodName
+ " has failed. " + throwable.getMessage() + " .***";
writeLog(failed);
}
//#After
String after = "\n";
writeLog(after);
}
public void writeLog(String log){
File file = new File("filmovi_izvestaj.txt");
try (Writer wr = new FileWriter(file, true)){
wr.write(log);
} catch(FileNotFoundException fe){
fe.printStackTrace();
} catch(IOException ioe){
ioe.printStackTrace();
}
}
}
Postman
#Around Advice
The value returned by the around advice is the return value seen by
the caller of the method.
Your advice is not returning anything which prevents the calling method to get the actual return value. Modify your around advice method to return Object to complete the flow correctly.
Example
#Around("allRESTMethods()")
public Object blabla(ProceedingJoinPoint pjp) {
//#Before
String methodName = pjp.getSignature().getName();
String before = "*** Attempting " + methodName + " method ***";
writeLog(before);
Object retVal = null;
try {
//#AfterReturning
retVal = pjp.proceed();
String success = "\n*** Method " + methodName + " has succeeded";
writeLog(success);
} catch (Throwable throwable){
//#AfterThrowing
String failed = "\n*** Method " + methodName
+ " has failed. " + throwable.getMessage() + " .***";
writeLog(failed);
}
//#After
String after = "\n";
writeLog(after);
return retVal;
}

How to parse a JSONString and turn its values into an Array?

How to parse a JSONString, from a once JSONString.stringify simple array that now "appears flattened" inside, and turn its values back into a Java List or Java Array? (Using Jersey 1.x & Java) ? Array originally started as [1,2,3] before it was stringify-ed.
items = (3) [" To", "8357", "30028"] --> JSON.stringify(items) sent through rest call
Chrome Dev Tools's Request Payload after rest call:
items=%5B%22%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0To%22%2C%228357%22%2C%2230028%22%5D
/*inside (Jersey) Rest Resource
#POST
#Path("/...")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response receive(#Context SecurityContext securityContext, #Context
HttpServletRequest srequest, String jsonString) throws URISyntaxException,
JSONException ...
/*eclipse watch on jsonString inside (Jersey) Rest Resource
items=%5B%22%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0To%22%2C%228357%22%2C%2230028%22%5D
*/[enter image description here][2]
NOTE: There is no name value. There is no entity.
There's only a very simple string of IDs because that's all I need. (Is that supported by Jersey 1.X or JAX-RS 1.X?)
JSONArray jSONArray = new JSONArray(java.util.Arrays.asList(jsonString));
Eclipse jSONArray Expression: jSONArray
--myArrayList
----elementData
------[0] "items=%5B%22%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0To%22%2C%228357%22%2C%2230028%22%5D"
----------value
------------[0..99]
---------------[0] i
---------------1 t
---------------[2] e
---------------[3] m
---------------[4] s
---------------[5] =
---------------[6] %
---------------[7] 5
---------------[8] B ....
I cannot understand exactly your original question, but one of the way is:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.JFileChooser;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JsonParser {
JFileChooser chooser = new JFileChooser();
File f;
static String fn = "";
static String js1 = "{\"name\": \"LALA\", \"email\": \"tst#tst.com\"}";
String name = "name";
String email = "email";
String fName = "firsName";
String city = "city";
// ... other needed fields
User u1 = null;
public JsonParser() {
parseFile();
System.out.println("\n" + u1.toShortString());
}
private String openFchooser() throws FileNotFoundException, IOException, InterruptedException, Exception {
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
f = chooser.getSelectedFile();
}
return f.getAbsolutePath();
}
// To parse JSON files with data
//===========================================
public void parseFile() {
JSONParser parser = new JSONParser();
try {
// To parse obj 1
Object obj1 = parser.parse(js1);
System.out.println("User 1: " + obj1.toString());
System.out.println();
JSONObject jobj1 = (JSONObject) obj1;
String from_name = jobj1.get(name).toString();
String from_email = jobj1.get(email).toString();
// String from_fName = jobj1.get(fName).toString();
// String from_city = jobj1.get(city).toString();
u1 = new User(from_name, from_email, null, null);
// System.out.println(u1.toString() + "\n");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new JsonParser();
}
class User {
String name = null;
String email = null;
String fName = null;
String city = null;
public User(String n, String e, String f, String c) {
this.name = n;
this.email = e;
this.fName = f;
this.city = c;
}
public String getFirsName() {
return this.name;
}
public String setFirsName(String s) {
return this.name = s;
}
public String getEmail() {
return this.email;
}
public String setEmail(String s) {
return this.email = s;
}
public String toString() {
return "{\"name\":" + this.name + ", "
+ "\"email\":" + this.email + ", "
+ "\"firsName\":" + this.fName + ", "
+ "\"city\":" + this.city + "\"}";
}
public String toShortString() {
return "{\"name\": \"" + this.name + "\", "
+ "\"email\": \"" + this.email + "\"}";
}
};
}
OUTPUT:
User 1: {"name":"LALA","email":"tst#tst.com"}
{"name": "LALA", "email": "tst#tst.com"}
Thanks guys. I managed to find an alternative send & receive:
now sending array without stringify-ing it first
receiving with:
public Response archiveSelectedApplicants(#Context SecurityContext securityContext, #Context HttpServletRequest srequest,
#FormParam("items[]") List items) throws URISyntaxException

Gson not deserializing JSON data

I am trying to get some weather information from Yahoo APIs. This is my JSON:
JSON
This is my DTO:
public class forecast implements Serializable {
private static final long serialVersionUID = -520652416977871134L;
private String text;
private String high;
private String day;
private String code;
private String low;
private String date;
public forecast() {
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getHigh() {
return high;
}
public void setHigh(String high) {
this.high = high;
}
public String getDay() {
return day;
}
public void setDay(String day) {
this.day = day;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getLow() {
return low;
}
public void setLow(String low) {
this.low = low;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
#Override
public String toString() {
return "ClassPojo [text = " + text + ", high = " + high + ", day = "
+ day + ", code = " + code + ", low = " + low + ", date = "
+ date + "]";
}
}
I am only interested for the forecast element.
When I try to read the data de-serialized into my DTO all of them are null. I sense that I have not formatted my DTO properly.
Also, what Is the right way to map JSON to POJOs?
EDIT: this is my code for deserializing
String endpoint = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20"
+ "where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22Rhodes%2C%20Gr%22)&"
+ "format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
try {
URL endpointURL = new URL(endpoint);
HttpURLConnection connection = (HttpURLConnection) endpointURL
.openConnection();
connection.connect();
InputStream input = connection.getInputStream();
JsonReader reader = new JsonReader(new InputStreamReader(input));
reader.setLenient(true);
forecast response = new Gson().fromJson(reader,
forecast.class);
Log.d("forecast", response.toString());//override toString() to return all the values of the object
} catch (IOException e) {
e.printStackTrace();
}
Your JSON (which you get from Yahoo) is very complex. So it can not be easily mapped to simple POJO (but you still can write huge POJO that contains fields for all corresponding nested JSON elements).
But it is possible to parse and extract specific elements from JSON.
The code:
public static void main(String[] args) {
String endpoint = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20"
+ "where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22Rhodes%2C%20Gr%22)&"
+ "format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
try {
URL endpointURL = new URL(endpoint);
HttpURLConnection connection = (HttpURLConnection) endpointURL
.openConnection();
connection.connect();
InputStream input = connection.getInputStream();
JsonReader reader = new JsonReader(new InputStreamReader(input));
reader.setLenient(true);
JsonElement forecastSubObject = new JsonParser().parse(reader).
getAsJsonObject().get("query").
getAsJsonObject().get("results").
getAsJsonObject().get("channel").
getAsJsonObject().get("item").
getAsJsonObject().get("forecast");
System.out.println(forecastSubObject.toString());
List<forecast> forecasts = (List<forecast>)new Gson().fromJson(forecastSubObject, List.class);
System.out.println("forecast : " + forecasts);
System.out.println("first forecast: " + forecasts.get(0));
} catch (IOException e) {
e.printStackTrace();
}
}
Using JsonParser you can walk through elements (by theirs names). When 'forecast' element is reached corresponding string is extracted. Then it parsed as usual object and mapped to list of your forecast POJO.
Generally speaking mapping to/from JSON is very wide sphere. Different libraries provide different ways for achieving this (from simple and dirty to complex but reliable).

ClassNotFoundException with readObject() method

I'm trying to read objects from a file in the Internet. I have been given the object class, which is this:
import java.io.Serializable;
public class Sulearvuti extends Arvuti implements Serializable {
private static final long serialVersionUID = 1L;
//isendiväli
private int aku;
//konstruktor
public Sulearvuti(String tootja, String mudel, String lisainfo,
int järjekorraNumber, int raskusaste, boolean kiirtellimus, int aku)
throws ValeRaskusAsteErind {
super(tootja, mudel, lisainfo, järjekorraNumber, raskusaste,
kiirtellimus);
this.aku = aku;
}
// meetod toString, kasutama ülemklassi meetodit
public String toString() {
return "Sülearvuti [aku=" + aku + ", " + super.toString() + "]";
}
// meetodi ülekatmine
double parandamiseAeg(){
return this.getRaskusaste()*2;
}
}
Now when I'm trying to read the objects (Sulearvuti), I get ClassNotFoundException. This is the piece of code :
ObjectInputStream ois =
new ObjectInputStream (
new URL("http://www.ut.ee/~marinai/sulearvutid.dat")
.openConnection()
.getInputStream());
int arv=ois.readInt();
Sulearvuti sülearvuti=(Sulearvuti)ois.readObject();
There's no problem with the Integer, but it won't recognize the class. I've been desperate for the past hour or so...
Also here's the code for the superclass "Arvuti":
import java.io.Serializable;
public class Arvuti implements Serializable, Comparable<Arvuti> {
private String tootja;
private String mudel;
private String lisainfo;
private int jrnumber;
private int vea_raskusaste;
private boolean kiirtellimus;
String getTootja() {
return tootja;
}
String getMudel() {
return mudel;
}
String getLisainfo() {
return lisainfo;
}
int getJrnumber() {
return jrnumber;
}
int getVea_raskusaste() {
return vea_raskusaste;
}
boolean isKiirtellimus() {
return kiirtellimus;
}
void setTootja(String tootja) {
this.tootja = tootja;
}
void setMudel(String mudel) {
this.mudel = mudel;
}
void setLisainfo(String lisainfo)throws WindowsXPErind {
this.lisainfo = lisainfo;
if(lisainfo.contains("WindowsXP"))throw new WindowsXPErind();
}
void setJrnumber(int jrnumber) {
this.jrnumber = jrnumber;
}
void setVea_raskusaste(int vea_raskusaste)throws ValeRaskusAsteErind {
if(vea_raskusaste<1 || vea_raskusaste>10) throw new ValeRaskusAsteErind();
this.vea_raskusaste = vea_raskusaste;
}
void setKiirtellimus(boolean kiirtellimus) {
this.kiirtellimus = kiirtellimus;
}
Arvuti(String tootja, String mudel, String lisainfo, int jrnumber,
int vea_raskusaste, boolean kiirtellimus)throws ValeRaskusAsteErind {
try{
setTootja( tootja);
setMudel(mudel);
setJrnumber(jrnumber);
setVea_raskusaste(vea_raskusaste);
setKiirtellimus(kiirtellimus);
setLisainfo(lisainfo);
}
catch (WindowsXPErind e){
System.out.println("WindowsXPErind");
setVea_raskusaste(vea_raskusaste+2);
}
}
double parandamiseAeg(){
return getVea_raskusaste()*1.5;
}
public String toString() {
return "Arvuti [tootja=" + tootja + ", mudel=" + mudel + ", lisainfo="
+ lisainfo + ", järjekorranumber=" + jrnumber + ", vea raskusaste="
+ vea_raskusaste + ", kiirtellimus=" + kiirtellimus
+ ", parandamise aeg=" + parandamiseAeg() + "]";
}
public int compareTo(Arvuti arvuti){
if(this.isKiirtellimus()==true && arvuti.isKiirtellimus()==false) return -1;
else if(this.isKiirtellimus()==false && arvuti.isKiirtellimus()==true) return 1;
else{
if(this.getJrnumber()<arvuti.getJrnumber())return -1;
else if(this.getJrnumber()>arvuti.getJrnumber())return 1;
else return 0;
}
}
}
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type ClassNotFoundException
at Peaklass.main(Peaklass.java:36)
You are missing some classes contained in the .dat file. Lookout for the classname shown in the classnotfound exception.
It is not sufficient to have the "Sulearvuti", you also need "Arvuti" (superclass) and "ValeRaskusAsteErind" (Exception) in your classpath.
BTW the language looks very funny to me, what language is this ?
Is "Sulearvuti" class on the classpath of the application trying to deserialize the object?

asynccallback failures

In my app I need to add string vallues to the file(.property file, if it is important). and user enter this values in gwt GUI. Here is it's important part:
final Button submit = new Button("Submit");
addButton(submit);
submit.addSelectionListener(new SelectionListener<ButtonEvent>() {
#Override
public void componentSelected(ButtonEvent ce) {
keyWord.selectAll();
regexp.selectAll();
if (keyWord.getValue() != null){
setKeyWord(customerId, keyWord.getValue());
keyWord.setValue("");
}
if (regexp.getValue() != null){
setRegExp(customerId, regexp.getValue());
regexp.setValue("");
}
}
});
}
private void setKeyWord(final String customerId, final String keyword){
final AsyncCallback<String> callbackItems = new AsyncCallback<String>() {
public void onFailure(final Throwable caught) {
Window.alert("unable to add " + caught.toString());
}
public void onSuccess(final String x) {
Window.alert(x);
}
};
serverManagementSvc.setKeyWords(customerId, keyword, callbackItems);
}
private void setRegExp(final String customerId, final String regexp){
final AsyncCallback<String> calbackItems = new AsyncCallback<String>() {
#Override
public void onFailure(Throwable throwable) {
Window.alert("unable to add " + throwable.toString());
}
#Override
public void onSuccess(String s) {
Window.alert(s);
}
};
serverManagementSvc.setRegExp(customerId, regexp, calbackItems);
}
So I need to use Asunccallback to call methods which are in the "server part".
here are these methods:
//adds a new keyword to customers properties
public String setKeyWords(String customer, String word){
try{
PropertiesConfiguration props = new PropertiesConfiguration("/home/mikhail/bzrrep/DLP/DLPServer/src/main/resources/rules.properties");
String newKeyWord = new String(props.getString("users." + customer + ".keywords" + "," + word));
props.setProperty("users." + customer + ".keywords", newKeyWord);
props.save();
}catch (ConfigurationException e){
e.printStackTrace();
}
return "keyword " + word + " added";
}
// adds a new regexp to customer properties
public String setRegExp(String customer, String regexp){
try {
PropertiesConfiguration props = new PropertiesConfiguration("/home/mikhail/bzrrep/DLP/DLPServer/src/main/resources/rules.properties");
String newRegValue = new String(props.getString("users." + customer + ".regexps" + "," + regexp));
props.setProperty("users." + customer + ".regexps", newRegValue);
props.save();
} catch (ConfigurationException e){
e.printStackTrace();
}
return "regexp " + regexp + " added to " + customer + "'s config";
}
all interfaces are present.
when I run my code And press "submit" button in gui I see that both asynccallback failured(Window.alert, as you can see, shows "null pointer exception" despite of the fact that values which I send to methods are not null). why can it be? can you suggest me something?
UPD here is error which is shown by firebug:
uncaught exception: java.lang.ClassCastException
function W8(){try{null.a()}catch(a){return a}}
the problem is solved: there were a simple mistake in the code. I've closed brackets at the wrong place:
//adds a new keyword to customers properties
public String setKeyWords(String customer, String word){
try{
PropertiesConfiguration props = new PropertiesConfiguration("/home/mikhail/bzrrep/DLP/DLPServer/src/main/resources/rules.properties");
String newKeyWord = new String(props.getString("users." + customer + ".keywords") + "," + word);
props.setProperty("users." + customer + ".keywords", newKeyWord);
props.save();
}catch (ConfigurationException e){
e.printStackTrace();
}
return "keyword " + word + " added";
}
// adds a new regexp to customer properties
public String setRegExp(String customer, String regexp){
try {
PropertiesConfiguration props = new PropertiesConfiguration("/home/mikhail/bzrrep/DLP/DLPServer/src/main/resources/rules.properties");
String newRegValue = new String(props.getString("users." + customer + ".regexps") + "," + regexp);
props.setProperty("users." + customer + ".regexps", newRegValue);
props.save();
} catch (ConfigurationException e){
e.printStackTrace();
}
return "regexp " + regexp + " added to " + customer + "'s config";
}
I recommend that you recompile the GWT code using
-style PRETTY
and then check that firebug output again; it may give you a better clue, compared to your updated uncaught exception.
Next, I suggest you run it in the eclipse debugger, and set breakpoints in both the client and server code, and then you can inspect the variables and step through the code.

Categories

Resources