I'm using jQuery DataTables in a Java Spring Boot project. When using DataTables's server-side processing, it sends AJAX request with request parameters like:
?columns[0][data]=0
&columns[0][name]=name
&columns[0][searchable]=true
&columns[0][orderable]=true
&columns[0][search][value]=Tom
&columns[0][search][regex]=false
&columns[1][data]=1
&columns[1][name]=address
&columns[1][searchable]=true
&columns[1][orderable]=true
&columns[1][search][value]=
&columns[1][search][regex]=false
to my server.
How can I convert these request parameters to a Java object for processing? The tutorial simply states that
In most modern server-side scripting environments this data will automatically be available to you as an array.
but I cannot find any way to do this in Java, particularly using Spring Boot's #RequestParameter.
Thank you for your help!
Create the following classes, ignore the package names
//DataTableRequest.java
package com.employee.app.model;
import java.util.*;
import com.fasterxml.jackson.annotation.*;
public class DataTableRequest {
private String draw;
private List<Column> columns;
private List<Order> order;
private String start;
private String length;
private Search search;
private String empty;
#JsonProperty("draw")
public String getDraw() { return draw; }
#JsonProperty("draw")
public void setDraw(String value) { this.draw = value; }
#JsonProperty("columns")
public List<Column> getColumns() { return columns; }
#JsonProperty("columns")
public void setColumns(List<Column> value) { this.columns = value; }
#JsonProperty("order")
public List<Order> getOrder() { return order; }
#JsonProperty("order")
public void setOrder(List<Order> value) { this.order = value; }
#JsonProperty("start")
public String getStart() { return start; }
#JsonProperty("start")
public void setStart(String value) { this.start = value; }
#JsonProperty("length")
public String getLength() { return length; }
#JsonProperty("length")
public void setLength(String value) { this.length = value; }
#JsonProperty("search")
public Search getSearch() { return search; }
#JsonProperty("search")
public void setSearch(Search value) { this.search = value; }
#JsonProperty("_")
public String getEmpty() { return empty; }
#JsonProperty("_")
public void setEmpty(String value) { this.empty = value; }
}
// Column.java
package com.employee.app.model;
import java.util.*;
import com.fasterxml.jackson.annotation.*;
public class Column {
private String data;
private String name;
private String searchable;
private String orderable;
private Search search;
#JsonProperty("data")
public String getData() { return data; }
#JsonProperty("data")
public void setData(String value) { this.data = value; }
#JsonProperty("name")
public String getName() { return name; }
#JsonProperty("name")
public void setName(String value) { this.name = value; }
#JsonProperty("searchable")
public String getSearchable() { return searchable; }
#JsonProperty("searchable")
public void setSearchable(String value) { this.searchable = value; }
#JsonProperty("orderable")
public String getOrderable() { return orderable; }
#JsonProperty("orderable")
public void setOrderable(String value) { this.orderable = value; }
#JsonProperty("search")
public Search getSearch() { return search; }
#JsonProperty("search")
public void setSearch(Search value) { this.search = value; }
}
// Search.java
package com.employee.app.model;
import java.util.*;
import com.fasterxml.jackson.annotation.*;
public class Search {
private String value;
private String regex;
#JsonProperty("value")
public String getValue() { return value; }
#JsonProperty("value")
public void setValue(String value) { this.value = value; }
#JsonProperty("regex")
public String getRegex() { return regex; }
#JsonProperty("regex")
public void setRegex(String value) { this.regex = value; }
}
// Order.java
package com.employee.app.model;
import java.util.*;
import com.fasterxml.jackson.annotation.*;
public class Order {
private String column;
private String dir;
#JsonProperty("column")
public String getColumn() { return column; }
#JsonProperty("column")
public void setColumn(String value) { this.column = value; }
#JsonProperty("dir")
public String getDir() { return dir; }
#JsonProperty("dir")
public void setDir(String value) { this.dir = value; }
}
DataTables by default sends requests as FormData, to make it send that request as Json, do the following.
$(document).ready(function() {
$('#datatableId').DataTable( {
"processing": true,
"serverSide": true,
"ajax":{
url: "your_processing_endpoint",
type:"POST",
contentType:"application/json",
data:function(d){
return JSON.stringify(d)
}
},
//include other options
} );
} );
And then in the controller action, assuming your are using Spring boot, do the following
#RequestMapping(value="your_processing_endpoint",method="RequestMethod.POST")
public ResponseEntity<?> processDataTableRequest(#RequestBody DataTableRequest
datatableRequest){
//you can add your logic here
}
Related
This json occurs when a destination or origin is outside of the uk, therefore not giving me any results! I need to check for this for a null check so i dont receive null pointer exception
JSON RESULT:
{
"destination_addresses" : [ "Durham, NC, USA" ],
"origin_addresses" : [ "Lancashire, UK" ],
"rows" : [
{
"elements" : [
{
"status" : "ZERO_RESULTS"
}
]
}
],
"status" : "OK"
}
Code:
public static void extractJsonFromRequest(GoogleResponsePojo response) {
String destinationAddress =
response.getDestination_addresses().get(0);
String timeTaken =
response.getRows().get(0).getElements().get(0).getDuration().getText();
String originAddress = response.getOrigin_addresses().get(0);
System.out.println("It will take ** "+ timeTaken + " ** to walk
from " + originAddress + " to " + destinationAddress);
}
Google Reponse POJO which is structure of json:
public class GoogleResponsePojo {
private List<String> destination_addresses;
private List<String> origin_addresses;
private List<Rows> rows;
public List<String> getDestination_addresses() {
return destination_addresses;
}
public void setDestination_addresses(List<String> destination_addresses) {
this.destination_addresses = destination_addresses;
}
public List<String> getOrigin_addresses() {
return origin_addresses;
}
public void setOrigin_addresses(List<String> origin_addresses) {
this.origin_addresses = origin_addresses;
}
public List<Rows> getRows() {
return rows;
}
public void setRows(List<Rows> rows) {
this.rows = rows;
}
}
class Rows {
private List<Element> elements;
public List<Element> getElements() {
return elements;
}
public void setElements(List<Element> elements) {
this.elements = elements;
}
}
class Element {
private TextValue distance;
private TextValue duration;
public TextValue getDistance() {
return distance;
}
public void setDistance(TextValue distance) {
this.distance = distance;
}
public TextValue getDuration() {
return duration;
}
public void setDuration(TextValue duration) {
this.duration = duration;
}
}
class TextValue {
private String text;
private String value;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
I essentially need to just parse the json below so that i can say (if status != ZERO_RESULTS ) save the response else throw an exception! Probably easy but im struggling! Thanks so much!
Change GoogleResponsePojo to:
public class GoogleResponsePojo {
private List<String> destination_addresses;
private List<String> origin_addresses;
private List<Rows> rows;
public void setDestination_addresses(List<String> destination_addresses) {
this.destination_addresses = destination_addresses;
}
public void setOrigin_addresses(List<String> origin_addresses) {
this.origin_addresses = origin_addresses;
}
public void setRows(List<Rows> rows) {
this.rows = rows;
}
//getters
}
private static class Rows{
private List<Element> elements;
public void setElements(List<Element> elements) {
this.elements = elements;
}
//getters
}
private static class Element{
private TextValue distance;
private TextValue duration;
public void setDistance(TextValue distance) {
this.distance = distance;
}
public void setDuration(TextValue duration) {
this.duration = duration;
}
//getters
}
private static class TextValue{
private String text;
private String value;
public void setText(String text) {
this.text = text;
}
public void setValue(String value) {
this.value = value;
}
//getters
}
You can take duration as following:
GoogleResponsePojo name = gson.fromJson(response.toString(),GoogleResponsePojo.class);
name.getRows().get(0).getDuration().getText();
And I recommend use http-request built on apache http api. Its simple to use:
public static final String BASE_URL = "https://maps.googleapis.com/maps/api/distancematrix/json";
private static final HttpRequest<GoogleResponsePojo> HTTP_REQUEST =
HttpRequestBuilder.createGet(BASE_URL, GoogleResponsePojo.class)
.addDefaultRequestParameter("origins", "Seattle")
.addDefaultRequestParameter("destinations", "San+Francisco")
.addDefaultRequestParameter("key", "***")
.build();
#GET
#Produces(MediaType.APPLICATION_JSON)
public static void updateTestExecutionDetails() throws IOException {
ResponseHandler<GoogleResponsePojo> responseHandler = HTTP_REQUEST.execute();
GoogleResponsePojo name = responseHandler.orElseThrow(); // throws ResponseException when status code != 200
System.out.println(name.getDestination_addresses().get(0));
System.out.println(name.getRows().get(0).getElements().get(0).getDuration().getText());
System.out.println(name.getOrigin_addresses().get(0));
}
I'm trying to store a coordnates (array of double) using Realm-java,but I'm not able to do it.
Here is an example of json that I'm trying to parse:
{"_id":"597cd98b3af0b6315576d717",
"comarca":"string",
"font":null,
"imatge":"string",
"location":{
"coordinates":[41.64642,1.1393],
"type":"Point"
},
"marca":"string",
"municipi":"string",
"publisher":"string",
"recursurl":"string",
"tematica":"string",
"titol":"string"
}
My global object code is like that
public class Images extends RealmObject implements Serializable {
#PrimaryKey
private String _id;
private String recursurl;
private String titol;
private String municipi;
private String comarca;
private String marca;
private String imatge;
#Nullable
private Location location;
private String tematica;
private String font;
private String parentRoute;
public Location getLocation() {return location;}
public void setLocation(Location location) {this.location = location;}
public String getParentRoute() {
return parentRoute;
}
public void setParentRoute(String parentRoute) {
this.parentRoute = parentRoute;
}
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getFont() {
return font;
}
public void setFont(String font) {
this.font = font;
}
public String getRecursurl() {
return recursurl;
}
public void setRecursurl(String recursurl) {
this.recursurl = recursurl;
}
public String getTitol() {
return titol;
}
public void setTitol(String titol) {
this.titol = titol;
}
public String getMunicipi() {
return municipi;
}
public void setMunicipi(String municipi) {
this.municipi = municipi;
}
public String getComarca() {
return comarca;
}
public void setComarca(String comarca) {
this.comarca = comarca;
}
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public String getImatge() {
return imatge;
}
public void setImatge(String imatge) {
this.imatge = imatge;
}
public String getTematica() {
return tematica;
}
public void setTematica(String tematica) {
this.tematica = tematica;
}
And Location is a composite of type and a realmlist
Location.java
public class Location extends RealmObject implements Serializable {
private String type;
private RealmList<RealmDoubleObject> coordinates;
public Location() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public RealmList<RealmDoubleObject> getCoordinates() {
return coordinates;
}
public void setCoordinates(RealmList<RealmDoubleObject> coordinates) {
this.coordinates = coordinates;
}
}
RealmDoubleObject.java
public class RealmDoubleObject extends RealmObject implements Serializable{
private Double value;
public RealmDoubleObject() {
}
public Double getDoublevalue() {
return value;
}
public void setDoublevalue(Double value) {
this.value = value;
}
}
The error is com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was NUMBER at path $[0].location.coordinates[0] but I'm not able to figure out why this number is not "fitting" by RealmDoubleObject.
For those that not familiar with realm RealmList doesn't work and you have to build your own realm object.
Thank you. I hope to find some Realm experts here!
SOLVED:
using Gson deserializer it can be done
First we have to initialize the gson object like this
Gson gson = new GsonBuilder()
.setExclusionStrategies(new ExclusionStrategy() {
#Override
public boolean shouldSkipField(FieldAttributes f) {
return f.getDeclaringClass().equals(RealmObject.class);
}
#Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
})
.registerTypeAdapter(new TypeToken<RealmList<RealmDoubleObject>>() {}.getType(), new TypeAdapter<RealmList<RealmDoubleObject>>() {
#Override
public void write(JsonWriter out, RealmList<RealmDoubleObject> value) throws IOException {
// Ignore
}
#Override
public RealmList<RealmDoubleObject> read(JsonReader in) throws IOException {
RealmList<RealmDoubleObject> list = new RealmList<RealmDoubleObject>();
in.beginArray();
while (in.hasNext()) {
Double valor = in.nextDouble();
list.add(new RealmDoubleObject(valor));
}
in.endArray();
return list;
}
})
.create();
And then we have to put some other constructor method
public RealmDoubleObject(double v) {
this.value = v;
}
and this is all.
Thanks for the help #EpicPandaForce
In JSON Response there is key "Value" but its response have multiple forms like String and Array with same key "Value".
So how to make Retrofit model class to maintain String and Array with same key "Value".
{
"RespCode":"SUCCESS",
"RespText":"Transaction Details",
"Data":{
"Record":[
{
"group_title":"Seller Information",
"group_values":[
{
"key":"Listing Agent",
"value":[
{
"key":"Agent First Name",
"value":"Myks"
},
{
"key":"Agent Last Name",
"value":"Joe"
},
{
"key":"Company",
"value":"bdfjdlfdf"
},
{
"key":"Phone",
"value":"712.336.4967"
},
{
"key":"Email",
"value":"abc#gmail.com"
}
]
},
{
"key":"Cell Phone",
"value":"012.345.6789"
},
{
"key":"Email",
"value":"balt#gmail.com.com"
},
{
"key":"Preferred Contact Method",
"value":"Phone"
}
]
},
]
}
}
Just use an arraylist that contains multiple hashmaps maybe? Or... You have to define a pojo that has list of arrays with type map or something to that effect
Check this:
public class ModelBean {
private String RespCode;
private String RespText;
private DataBean Data;
public String getRespCode() {
return RespCode;
}
public void setRespCode(String RespCode) {
this.RespCode = RespCode;
}
public String getRespText() {
return RespText;
}
public void setRespText(String RespText) {
this.RespText = RespText;
}
public DataBean getData() {
return Data;
}
public void setData(DataBean Data) {
this.Data = Data;
}
public static class DataBean {
private List<RecordBean> Record;
public List<RecordBean> getRecord() {
return Record;
}
public void setRecord(List<RecordBean> Record) {
this.Record = Record;
}
public static class RecordBean {
private String group_title;
private List<GroupValuesBean> group_values;
public String getGroup_title() {
return group_title;
}
public void setGroup_title(String group_title) {
this.group_title = group_title;
}
public List<GroupValuesBean> getGroup_values() {
return group_values;
}
public void setGroup_values(List<GroupValuesBean> group_values) {
this.group_values = group_values;
}
public static class GroupValuesBean {
private String key;
private List<ValueBean> value;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public List<ValueBean> getValue() {
return value;
}
public void setValue(List<ValueBean> value) {
this.value = value;
}
public static class ValueBean {
private String key;
private String value;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
}
}
}
}
I am trying to assign the value returned by some function to a field in the deserialized class of json.
FileInfo.java
public class FileInfo {
#SerializedName("Name")
private String mName;
#SerializedName("Url")
private String mUri;
#SerializedName("Size")
private Integer mSize;
#SerializedName("ModTime")
private Long mModifiedTime;
private FileType mType;
#SerializedName("Children")
private ArrayList<FileInfo> mChildren = new ArrayList<>();
public ArrayList<FileInfo> getChildren() {
return mChildren;
}
public long getModifiedTime() {
return mModifiedTime;
}
public String getName() {
return mName;
}
public Integer getSize() {
return mSize;
}
public String getUrl() {
return mUri;
}
public FileType getType() {
return mType;
}
public void setChildren(ArrayList<FileInfo> mChildren) {
this.mChildren = mChildren;
}
public void setModifiedTime(long mModifiedTime) {
this.mModifiedTime = mModifiedTime;
}
public void setName(String mName) {
this.mName = mName;
}
public void setSize(Integer mSize) {
this.mSize = mSize;
}
public void setType(FileType mType) {
this.mType = mType;
}
public void setUri(String mUri) {
this.mUri = mUri;
}
#Override
public String toString() {
return FileInfo.class.toString();
}
public FileInfo() {
}
}
The mType needs to be assigned to foo(mName). I looked up custom deserializers and instance creators but none of those helped. I also thought of TypeAdapters which i feel defeats the purpose of keeping deserialization(using GSON) simple.
This is a sample JSON string that will be deserialized.
[
{
"Name":"Airport",
"Url":"http://192.168.2.2/api/sites/Baltimore%20Airport/Airport",
"Size":0,
"ModTime":"2015-12-02T14:19:17.29824-05:00",
"Children":null
}
]
P.S. I'm not sure if this should be done during deserialization but trying anyways. Also please let me know of alternative ways to achieve this.
Hello I have got a question about TableView in JavaFX and populating the table with data from an object in the model via a getter method of this object, which is part of the model .
First of all, here is my model:
package model;
import java.util.List;
public class Carmodel {
private int carmodelID;
private Cartype cartype;
private Manufacturer manufacturer;
private DrivingLicense drivingLicense;
private String label;
private int seats;
private int kw;
private String fuelType;
private double priceDay;
private double priceKM;
private int axes;
private int loadVolume;
private int loadCapacity;
private List<Equipment> equipmentList;
public Carmodel() {
}
public int getCarmodelID() {
return carmodelID;
}
public void setCarmodelID(int carmodelID) {
this.carmodelID = carmodelID;
}
public Cartype getCartype() {
return cartype;
}
public void setCartype(Cartype cartype) {
this.cartype = cartype;
}
public Manufacturer getManufacturer() {
return manufacturer;
}
public void setManufacturer(Manufacturer manufacturer) {
this.manufacturer = manufacturer;
}
public DrivingLicense getDrivingLicense() {
return drivingLicense;
}
public void setDrivingLicense(DrivingLicense drivingLicense) {
this.drivingLicense = drivingLicense;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public int getSeats() {
return seats;
}
public void setSeats(int seats) {
this.seats = seats;
}
public int getKw() {
return kw;
}
public void setKw(int kw) {
this.kw = kw;
}
public String getFuelType() {
return fuelType;
}
public void setFuelType(String fuelType) {
this.fuelType = fuelType;
}
public double getPriceDay() {
return priceDay;
}
public void setPriceDay(double priceDay) {
this.priceDay = priceDay;
}
public double getPriceKM() {
return priceKM;
}
public void setPriceKM(double priceKM) {
this.priceKM = priceKM;
}
public int getAxes() {
return axes;
}
public void setAxes(int axes) {
this.axes = axes;
}
public int getLoadVolume() {
return loadVolume;
}
public void setLoadVolume(int loadVolume) {
this.loadVolume = loadVolume;
}
public int getLoadCapacity() {
return loadCapacity;
}
public void setLoadCapacity(int loadCapacity) {
this.loadCapacity = loadCapacity;
}
public List<Equipment> getEquipmentList() {
return equipmentList;
}
public void setEquipmentList(List<Equipment> equipmentList) {
this.equipmentList = equipmentList;
}
As you can see there is a specific member (private Manufacturer manufacturer) It is an object from the type "Manufacturer". And the Manufacturer class looks like this:
public class Manufacturer {
private int manufacturerID;
private String name;
public Manufacturer() {
}
public int getManufacturerID() {
return manufacturerID;
}
public void setManufacturerID(int manufacturerID) {
this.manufacturerID = manufacturerID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
This is my controller for the JavaFX View:
public class CarmodelController implements Initializable {
CarmodelRepository carmodelRepository;
#FXML public TableView CarmodelTable;
#FXML public TableColumn<Carmodel,Integer> tableColumnID ;
#FXML public TableColumn<Carmodel,String> tableColumnLabel ;
#FXML public TableColumn<Carmodel, String> tableColumnManufacturer ;
#FXML public TableColumn<Carmodel,String> tableColumnCartype ;
public void initialize(URL location, ResourceBundle resources) {
carmodelRepository= new CarmodelRepository();
List<Carmodel> carmodelList= carmodelRepository.readAll();
ObservableList<Carmodel> carmodelObservableList = FXCollections.observableArrayList(carmodelList);
tableColumnID.setCellValueFactory(new PropertyValueFactory<Carmodel, Integer>("carmodelID"));
tableColumnLabel.setCellValueFactory(new PropertyValueFactory<Carmodel, String>("label"));
tableColumnManufacturer.setCellValueFactory(new PropertyValueFactory<Carmodel, String>("manufacturer")
And here is the problem:
Can I do here something like PropertyValueFactory("manufacturer.getName()"); This way it didn't work. It just populate the column of the table with memory adress
So my question is:
How can I get the name of the manufacturer, normally, in other code, you can do this by calling the method: "manufacturer.getName();" and it will give you the String with the name of the manufacturer, but how can I do this while I will populate the table with these specific carmodels?
And the end of the controller code ( filling the Table with values).
CarmodelTable.setItems(carmodelObservableList);
}
Thank you in advance!
You can do
tableColumnManufacturer.setCellValueFactory(cellData ->
new ReadOnlyStringWrapper(cellData.getValue().getManufacturer().getName());
The setCellValueFactory method expects a Callback<CellDataFeatures<Carmodel, String>, ObservableValue<String>> object. Hence cellData in this code is a CellDataFeatures<Carmodel, String> object, and cellData.getValue() gives the CarModel object for the row. Then cellData.getValue().getManufacturer().getName() gives the value you want; you just have to wrap it in a ReadOnlyObservableWrapper to get an ObservableValue<String> containing that value.