I've got the JSON data behind the scenes, that's it
[{"aid":100000,"name":"JYCM201609010250","rtsp":"947|100000|3750","statuz":"1","updateTime":"2017-05-31"},{"aid":100001,"name":"gui","rtsp":"947|100000|3750","statuz":"0","updateTime":"2017-05-31"}]
Background and foreground code are as follows
#Autowired
private MediaImpl media;
#ResponseBody
#RequestMapping(value = "/media",method = RequestMethod.GET)
public List<Media> MediaAll(){
System.out.println("------------------------------------------------------");
return media.findAll();
}
JS code is as follows
<script>
$(document).ready(function () {
$('#table_id_example').DataTable({
"iDisplayLength": 10,
"bLengthChange": false,
"ajax": {
"url": "/media",
"dataType": "json",
"success": function (json) {
console.log(json)
}
},
"columns": [
{
"data": 'aid'
},
{
"data": 'name'
},
{
"data": 'rtsp'
},
{
"data": 'statuz'
},
{
"data": 'updateTime'
}
]
});
});
html code is as follows
The console code
VM178:10 (2) [{…}, {…}]0: {aid: 100000, name: "JYCM201609010250", rtsp: "947|100000|3750", statuz: "1", updateTime: "2017-05-31"}1: {aid: 100001, name: "gui", rtsp: "947|100000|3750", statuz: "0", updateTime: "2017-05-31"}length: 2__proto__: Array(0)
There is no error in the front-end console, and no errors in the back end.But the data is not available
There are a couple of problems here. The first is that datatables expects data in a data element of the json response, such as:
{
data: [{"aid":100000,"name":"JYCM201609010250","rtsp":"947|100000|3750","statuz":"1","updateTime":"2017-05-31"},{"aid":100001,"name":"gui","rtsp":"947|100000|3750","statuz":"0","updateTime":"2017-05-31"}]
}
You should be able to use ajaxSrc: "" on your DataTable settings.
The second problem is with your ajax settings. DataTables states you can not supply the success callback in the ajax settings as it uses this internally.
Documentation on both of these issues:
https://datatables.net/reference/option/ajax
Assuming you are using DataTables 1.10.x
Related
In MVC, you would expect that controller will receive models as input and produce models as output. In Swagger, the latter is not a problem but I have troubles with former. I can't understand how to make Swagger build an input model from incoming GET parameters.
Consider:
"paths": {
"/search": {
"get": {
"consumes": [],
"produces": [
"application/json"
],
"parameters": [
// What goes here?
],
"responses": {
"200": {
"description": "Success",
"schema": {
"$ref": "#/definitions/SearchResponse"
}
},
}
}
}
}
How do I make the generated controller's method to have a signature like:
public ResponseEntity<ResultModel> controllerGet(ModelFromParameters input);
where ModelFromParameters will have several fields corresponding to different GET parameters.
Examples mostly focus either on POST requests, or GET requests where every of 20-odd parameters are stuffed in the arguments list of method, which is obviously anti-MVC.
The API in question is a complex stateless querying system with a lot of parameters.
Assumption: you want to create an object as parameter to your service method but still pass each of the fields of the object as query parameter in the actual http request and be able to document individual fields in swagger.
e.g. GET http://localhost:8080/search?parameter1=value1¶meter2=value2
Typical Service Method Definition where each query param is defined as a parameter in the actual method
#RequestMapping(method = RequestMethod.GET)
public ResponseEntity<List<String>> search(#RequestParam parameter1, #RequestParam parameter2) {
...
}
Modified service method with single parameter using Object (a.k.a Bean) annotated with #ModelAttribute. Though it is an object, as far as the REST API is concerned it is still the same as above.
#RequestMapping(method = RequestMethod.GET)
public ResponseEntity<List<String>> search(#ModelAttribute FormParam formParam) {
...
}
FormParam class. You can document each field using #ApiParam
public class FormParam {
#ApiParam(value = "parameter1 - description here", required = true)
private String parameter1;
#ApiParam(value = "parameter2 - description here", required = true)
private String parameter2;
//define getter setters below
}
This is how it appears in swagger
This is the generated swagger.json snippet
"paths": {
"/search": {
"get": {
"tags": ["search-service"],
"summary": "Search with Object as parameter",
"description": "Search with Object as parameter",
"operationId": "searchUsingGET",
"consumes": ["application/json"],
"produces": ["*/*"],
"parameters": [{
"name": "parameter1",
"in": "query",
"description": "parameter1 - description here",
"required": true,
"type": "string"
},
{
"name": "parameter2",
"in": "query",
"description": "parameter2 - description here",
"required": true,
"type": "string"
}],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
},
"401": {
"description": "Unauthorized"
},
"403": {
"description": "Forbidden"
},
"404": {
"description": "Not Found"
}
}
}
},
If you are manually creating the swagger.json the query parameters can be documented like
"parameters": [{
"name": "parameter1",
"in": "query",
"description": "parameter1 - description here",
"required": true,
"type": "string"
},
{
"name": "parameter2",
"in": "query",
"description": "parameter2 - description here",
"required": true,
"type": "string"
}],
I think you can't. I had also a similar problem, for list page + search, using GET with body. No way to make swagger represent this, also if it works in Tomcat; also Elasticsearch supports it. It looks like there is no plan to change this aspect in swagger. I resorted to split the two in swagger: list-without-search as GET and list+search as POST, just to put the page in the swagger documentation, also if the latter actually works also as GET.
I have no experience with swagger code generation but, if your configuration generates what you expect with POST but it doesn't with GET, then you are probably hitting the same limitation.
https://github.com/swagger-api/swagger-ui/issues/2867
https://github.com/swagger-api/swagger-ui/issues/2136
https://github.com/OAI/OpenAPI-Specification/blob/OpenAPI.next/versions/3.0.md#operationRequestBody
The requestBody is only supported in HTTP methods where the HTTP 1.1 specification RFC7231 has explicitly defined semantics for request bodies. In other cases where the HTTP spec is vague, requestBody SHALL be ignored by consumers.
In usual, http server(eg. tomcat, jetty) will not accept a body message within a get request. If client needs pass parameters to server by http get method, it should use query string . Last part of the url after '?' character. Query string details you can see query string
But with spring mvc help, your http request parameters in query string will be bound to your controller method parameter`s fields.So it seems like client passed a pojo parameter to server side.
Any way the parameter part should look like this:
"parameters" : [ {
"name" : "age",
"in" : "query",
"required" : false,
"type" : "integer"
}, {
"name" : "firstName",
"in" : "query",
"required" : false,
"type" : "string"
}]
Please note that "in" filed's value is "query". That means parameter is passed by query string.
I supose what you require is posting your arguments in request body, it goes like this:
...
{
"name": "files",
"in": "body",
"required": true,
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/FileRequest"
}
}
}
which translates to:
public Response storageFilePost(
#NotEmpty(message = "systemID is required!") #QueryParam("systemID") final String systemID,
#NotNull(message = "qParam is required!") #QueryParam("qParam") final Long qParam,
#NotNull(message = "files are required!") final List<FileRequest> files) {
Using swagger editor I created a post call to consume a json object that I want to simply load into a db but when I run the call I get an empty json object.
This is the parameters portion of my json swagger for the post
"parameters": [
{
"in": "body",
"name": "body",
"description": "Add question to collection",
"required": true,
"schema": { "type" : "object", "additionalProperties" : {}
}
}
],
It then creates a "Body" model, but I am not able to see the json that was part of the post:
#javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2016-01-22T20:49:03.229Z")
public class Body {
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Body body = (Body) o;
return true;
}
#Override
public int hashCode() {
return Objects.hash();
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Body {\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
If I remove the text/json from consume and generated my code again and I still see an issue with the body model and being able to pull in json.
If you look at the toString method it shows hard coded values, so I dont see how I can pull the json from the post with the post method only taking in the Body and securitycontext.
I am a little confused about the http accept, when using this swagger snippet:
"post": {
"tags": [
"AskGrey"
],
"summary": "Create new askgrey.com question",
"operationId": "postAskGrey",
"consumes": [
"application/json",
"text/json"
],
"produces": [
"application/json"
],
"parameters": [
{
"in": "body",
"name": "body",
"description": "Add question to collection",
"required": true,
"schema": { "type" : "object", "additionalProperties" : {}
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "object"
}
}
},
"deprecated": false
}
The method generated is the following:
#Override
#POST
#Consumes("application/json")
public Response postAskGrey(Body body,SecurityContext securityContext)
throws NotFoundException {
So based on all this I am not sure how to pull in the post body info, normally I would grab what I need from the http request but with swagger I cant seem to figure out how that gets used.
Before you send your data you should check HTTP ACCEPT method which you set in swagger when you send your data.
There should be Several Accept method which their behaviour distinct from each other when sending data to server.
Thus for application/JSON : Data are part of body.
form-data and x-www-form-urlencoded : Data are part of header.
I haven't adaquate Java experience to give correct code to obtain json into related jSON Object but How to convert HTTP Request Body into JSON Object in Java this answer could help.
Please Check following RFCs for further information
form-data related RFC https://www.rfc-editor.org/rfc/rfc7578
x-www-form-urlencoded related RFC https://datatracker.ietf.org/doc/html/draft-hoehrmann-urlencoded-01
application/JSON related rfc https://www.ietf.org/rfc/rfc4627.txt
UPDATED
Related curl command : I get the command from swagger live demo http://petstore.swagger.io/#/pet paste your json to it and change url, secret key give it a try!
curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{
"id": 0,
"category": {
"id": 0,
"name": "string"
},
"name": "doggie",
"photoUrls": [
"string"
],
"tags": [
{
"id": 0,
"name": "string"
}
],
"status": "available"
}' 'http://petstore.swagger.io/v2/pet?api_key=special-key'
I have requirement to handle json response and it is coming by rest service GET Method call.
I already have looked solutions from these links:-
http://www.journaldev.com/2315/java-json-processing-api-example-tutorial
http://answers.oreilly.com/topic/257-how-to-parse-json-in-java/
but it is not fulfill my requirements because it is small and static. I am keeping my json response in below:-
`<!--json response start -->
{
"HotelListResponse": {
"cachedSupplierResponse": {
"#cachedTime": "0",
"#candidatePreptime": "111",
"#matchedCurrency": "true",
"#matchedLocale": "true",
"#otherOverheadTime": "4",
"#supplierRequestNum": "211",
"#supplierResponseNum": "20",
"#supplierResponseTime": "405",
"#tpidUsed": "5001"
},
"cacheKey": "302c317:13443ffb599:-7712",
"cacheLocation": "10.186.168.61:7302",
"customerSessionId": "0ABAA83D-2C31-7913-4432-FFB599907714",
"HotelList": {
"#activePropertyCount": "237",
"#size": "1",
"HotelSummary": {
"#ubsScore": "1867",
"#order": "0",
"hotelId": 127092,
"name": "The Edgewater - A Noble House Hotel",
"address1": "Pier 67, 2411 Alaskan Way",
"city": "Seattle",
"stateProvinceCode": "WA",
"postalCode": 98121,
"countryCode": "US",
"airportCode": "SEA",
"supplierType": "E",
"propertyCategory": 1,
"hotelRating": 4,
"confidenceRating": 85,
"amenityMask": 6259019,
"tripAdvisorRating": 4,
"tripAdvisorReviewCount": 590,
"tripAdvisorRatingUrl": "http://www.tripadvisor.com/img/cdsi/img2/ratings/traveler/4.0-12345-4.gif",
"locationDescription": "Near Washington State Convention & Trade Center",
"shortDescription": "<p><b>Location. </b> <br />The Edgewater - A Noble House Hotel is a business-friendly hotel located in central Seattle, close to Odyssey - The Maritime Discovery Center, Washington State Convention &",
"highRate": 249,
"lowRate": 186.75,
"rateCurrencyCode": "USD",
"latitude": 47.61252,
"longitude": -122.35013,
"proximityDistance": 11.898841,
"proximityUnit": "MI",
"hotelInDestination": true,
"thumbNailUrl": "/hotels/1000000/20000/11200/11133/11133_73_t.jpg",
"deepLink": "http://travel.ian.com/index.jsp?pageName=hotAvail&cid=55505&hotelID=127092&mode=2&numberOfRooms=2&room-0-adult-total=1&room-0-child-total=1&room-0-child-0-age=3&room-1-adult-total=1&room-1-child-total=1&room-1-child-0-age=5&arrivalMonth=8&arrivalDay=4&departureMonth=8&departureDay=5&showInfo=true&locale=en_US¤cyCode=USD",
"RoomRateDetailsList": {
"RoomRateDetails": {
"roomTypeCode": 1160,
"rateCode": 1221260,
"maxRoomOccupancy": 2,
"quotedRoomOccupancy": 2,
"minGuestAge": 0,
"roomDescription": "City Lodge - Nonrefundable",
"promoId": 200803780,
"promoDescription": "7-Day Advance Purchase Special (Nonrefundable)",
"currentAllotment": 10,
"propertyAvailable": true,
"propertyRestricted": false,
"expediaPropertyId": 11133,
"rateKey": "f3525aff-9f4d-4d92-bc1c-144628fcaa30",
"nonRefundable": true,
"RateInfos": {
"#size": "1",
"RateInfo": {
"#rateChange": "false",
"#promo": "true",
"#priceBreakdown": "true",
"RoomGroup": {
"Room": [
{
"numberOfAdults": 1,
"numberOfChildren": 1,
"childAges": 3
},
{
"numberOfAdults": 1,
"numberOfChildren": 1,
"childAges": 5
}
]
},
"ChargeableRateInfo": {
"#commissionableUsdTotal": "373.5",
"#total": "441.74",
"#surchargeTotal": "68.24",
"#nightlyRateTotal": "373.5",
"#averageBaseRate": "249.0",
"#averageRate": "186.75",
"#maxNightlyRate": "186.75",
"#currencyCode": "USD",
"NightlyRatesPerRoom": {
"#size": "1",
"NightlyRate": {
"#promo": "true",
"#rate": "186.75",
"#baseRate": "249.0"
}
},
"Surcharges": {
"#size": "1",
"Surcharge": {
"#amount": "68.24",
"#type": "TaxAndServiceFee"
}
}
}
}
}
}
}
}
}
}
}
so here I am getting dynamic response based on my rest url call so how do I set this json response to my pojo.
any help would be appreciated.
Thank you in advance.
`
You could use a framework to handle all that for you; a great one is Spring.
Have a look here
Here is stackoverflow question to get you jump-started.
example from link above:
create a Controller to handle REST calls (changed to demonstrate json use):
#Controller
#RequestMapping("/kfc/brands")
public class JSONController {
#RequestMapping(value="{name}", method = RequestMethod.POST)
public #ResponseBody Shop getShopInJSON(#PathVariable String name, #RequestBody JsonNode json) {
// do stuff with the json request body (its is jackson)
JsonNode test= json.get("test");
Shop shop = new Shop();
shop.setName(name);
shop.setStaffName(new String[]{"mkyong1", "mkyong2"});
return shop;
}
}
// you could use jQuery to perform a REST call to your new controller:
$.ajax({
type: "POST",
url: "[your server]/kfc/brands",
data: {"test": "json value"},
success: function() {}
});
Try gson lib. It converts json to pojo and pojo to json.
If you have a schema for the JSON response then jsonschema2pojo would be a good tool to use. It works in a similar way that JAXB does for XML, in that it generates pojos at build time based on the schema, which you can then use at compile time.
If there isn't a schema but you are confident on the format, you could always generate the schema yourself.
I am new for sencha touch. I need to create, delete, update a member record throughout jersey java. Here is my code
view.js
Ext.define('bluebutton.view.BlueButton.testing', {
extend: 'Ext.form.Panel',
xtype: 'testing',
requires: [
'bluebutton.view.BlueButton.TransactionList',
'bluebutton.view.BlueButton.MemberPopUp',
'bluebutton.view.BlueButton.MemberDetail',
'bluebutton.store.BlueButton.MemberList',
],
config: {
id:'register',
items :[
{
xtype: 'textfield',
name: 'name',
label: 'Name'
},
{
xtype: 'emailfield',
name: 'email',
label: 'Email'
},
{
xtype: 'button',
text: 'Send',
handler: function(button) {
var form = Ext.getCmp('register');
values = form.getValues();
var myStore= new Ext.data.Store({
model: 'bluebutton.model.BlueButton.MemberList'
});
var newModel = Ext.ModelMgr.create({ 'memberId': 1,
'name': 2,
'imgUrl': 3
}, 'bluebutton.model.BlueButton.MemberList');
myStore.add(newModel);
myStore.sync();
}
}
],
}
});
Model.js
Ext.define('bluebutton.model.BlueButton.MemberList', {
extend: 'Ext.data.Model',
config: {
idProperty: 'memberModel',
fields: [
{ name: 'memberId' },
{ name: 'name' },
{ name: 'imgUrl' },
{ name: 'age' },
{ name: 'address' },
{ name: 'pointAvalaible' },
{ name: 'lastVisited' },
],
proxy: {
type: 'ajax',
actionMethods: {
create : 'POST',
read : 'POST', // by default GET
update : 'POST',
destroy: 'POST'
},
url: 'http://localhost:8080/RESTFulExample/rest/json/metallica/testingj'
},
}
});
Store.js
Ext.define('bluebutton.store.BlueButton.MemberList', {
extend: 'Ext.data.Store',
requires: [
'bluebutton.model.BlueButton.MemberList'
],
config: {
grouper: {
groupFn: function (record) {
return record.get('name')[0];
}
},
model :'bluebutton.model.BlueButton.MemberList',
storeId :'memberStore',
autoLoad:false,
pageSize: 5,
clearOnPageLoad: false,
data: [
]
}
});
Jersey.java
#POST
#Path("/testingj")
// #Consumes("application/x-www-form-urlencoded")
#Consumes(MediaType.APPLICATION_JSON)
public Response too(MultivaluedMap<String, String> form) {
return Response.status(201).entity(form).build();
}
But I keep getting this error
XMLHttpRequest cannot load localhost:8080/RESTFulExample/rest/json/metallica/testingj?_dc=1358408853016.
Origin localhost is not allowed by Access-Control-Allow-Origin.
Please guide me solution.
You are getting this response because of browser's security constraint for cross origin requests, which means from javascript you can call only those urls which are in same domain. Since your service is running on 8080 post so browser consider it from other domain.
There are various ways to do cross domain request, out of which you should read about:
JsonP
Enabling CORS on server
But since mobile's security constraints are different from desktop's browser constraints so the same thing might work in mobile even though it doesn't work in browser. For more details check this out : Loading store data with rest proxy from server in Sencha Touch 2
In your case I would recommend you to add JsonP support to your services and use JsonP proxy instead of AJAX & REST proxy.
Hi I'm trying to develop a UI for an oracle table which has around 40 columns/fields using jquery datatbles plugin. I'm able to display upto 18 columns, but after that it's not working. Is anyone else faced the same issue before? Please advice me on this i'm pretty new with jquery.
`Sorry for that...
when i'm trying to create a UI for my oracle table, when i configure it for 18 columns(any 18) i can see my UI is working perfectly. But if i add one more column and update the configuration my UI is not loading.
<script type="text/javascript">
$(document).ready(function () {
$("#reports").dataTable({
"bServerSide": true,
"sAjaxSource": "/databaseInterface/DataSource",
"bProcessing": true,
"sPaginationType": "full_numbers",
"bJQueryUI": true,
"aoColumns": [
{ "sName": "ID",
"bSearchable": false,
"bSortable": false,
"bVisible": false
},
{ "sName": "name" },
{ "sName": "sname" },
{ "sName": "address" },
{ "sName": "city" },
{ "sName": "post code" },
{ "sName": "age" },
{ "sName": "major" },
{ "sName": "grade" },
{ "sName": "Elect1" },
{ "sName": "Elect2" },
{ "sName": "Elect3" },
{ "sName": "Elect4" },
{ "sName": "Elect5" },
{ "sName": "Assig1" },
{ "sName": "Assig2" },
{ "sName": "Assig3" },
{ "sName": "Assig4" },
{ "sName": "Assig5" }
]
}).makeEditable({
"aoColumns": [
{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}
]
});
});
</script>
this is my sample code which is working properly, and is i add { "sName": "Status" } at the end, and update my datasource with the corresponding value it's not displaying aything in my UI.
`
jquery 1.8, java 5 and also jquery editable datable plugin
I'm trying to display my oracle table like a datatable shown in this website
datatable reference that i'm using
Very likely the problem is that your server is rejecting GET requests which have more than a certain number of characters. By default DataTables sends server-side processing requests as GET. To change to POST use the sServerMethod option - http://datatables.net/ref#sServerMethod .