Custom JSON to populate a Datatable - java

Im creating a DataTable from an Ajax json.
resultTable = $('#changeTable').DataTable({
"order": [[0, "desc"]],
"pageLength": 50,
"scrollX": true,
"lengthMenu":[[50,100,250, -1], [50, 100, 250, "All"]],
"dom":'<"toolbar">ltipr', //write ltfipr to show a search bar
"ajax":{
url:"api/changes",
"dataType":"json",
timeout:15000
}
});
The DataTables creates but it shows an error:
DataTables warning: table id=changeTable - Requested unknown parameter
'0' for row 0, column 0. For more information about this error, please
see http://datatables.net/tn/4
My JSON Looks like the following
{"data":
[
{"id":1,
"createdDate":"Apr 18, 2018 4:10:58 PM",
"source":"manual upload",
"emailId":"manual upload",
"attachmentId":"manual upload",
...,},
{next objet}]}
Such JSON object is created in my Java controller:
#RequestMapping(value = "/api/changes", method = RequestMethod.GET, produces = "application/json")
#ResponseBody
public String getChanges(){
Optional<List<PriceChange>> priceChangeList = pcService.findAllPriceChanges();
JsonObject result = new JsonObject();
if (priceChangeList.isPresent()) {
result.add("data", new Gson().toJsonTree(priceChangeList.get()));
return result.toString();
}
return null;
}
I don know how to use this information with the dataSrc property to make it work for the DataTable. Any Ideas?

You just need to define columns for the table. If you have
<table id="changeTable"></table>
add this to your DataTables options :
resultTable = $('#changeTable').DataTable({
...,
columns: [
{ data: 'id', title: 'id' },
{ data: 'createdDate', title: 'createdDate' },
{ data: 'source', title: 'source' },
{ data: 'emailId', title: 'emailId' },
{ data: 'attachmentId', title: 'attachmentId' }
]
})
If ypu have specifed a <thead> section you can skip the title's.

Related

count array object with condition in mongodb and spring-boot

I want to count the number of videos in each mediaList and then return the total number of videos in the document.
{
_id: ObjectId("5f9d8d02d7bb2c56b678614c"),
mainTopicId: "5f8066dad0b65b3b9ca67e4b",
subTopicId: "5f9d89f5d7bb2c56b678614b",
userIdLiked: [
"5fe4560f19050e372a2a17f8",
"5f8061e0d0b65b3b9ca67e49"
],
likeCount: NumberInt(2),
mediaList: [
{
url: "ad491eb8-7f28-47da-9d35-fe83bb4f8eb0.mp4",
mediaType: "VIDEO"
}
],
text: "this sample text",
title: "sample title",
created: ISODate("2020-10-31T16:12:50.615Z"),
updated: ISODate("2020-10-31T16:12:50.615Z"),
},
{
_id: ObjectId("5f9d8f95d7bb2c56b678614e"),
mainTopicId: "5f8066dad0b65b3b9ca67e4b",
subTopicId: "5f67816fb2ae8c3e1f203946",
userIdLiked: [
"5f8061e0d0b65b3b9ca67e49"
],
mediaList: [
{
url: "5633c4b2-d3aa-4d7c-8419-1403e43674b1.mp4",
mediaType: "VIDEO"
}
],
text: "sample text 2",
title: "sample title 2",
created: ISODate("2020-10-31T16:23:49.488Z"),
updated: ISODate("2020-10-31T16:23:49.488Z"),
_class: "com.example.api.pregnancy.models.Content"
}
I use this Spring-boot code for sum likeCount in document.
now i want count total mediaType when is VIDEO type
Aggregation agg = Aggregation.newAggregation(
project("subTopicId").and("likeCount").as("sumLikeCount"),
group("subTopicId").sum("sumLikeCount").as("totalCount")
);
The code
Aggregation aggregation = Aggregation.newAggregation(
p-> new Document("$project",
new Document("totalVideos",
new Document("$size",
new Document("$filter",
new Document("input","$mediaList").append("cond",
new Document("$eq",Arrays.asList("$$this.mediaType","VIDEO"))
)
)
)
)
)
).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());
Spring-data doesn't provide few operation like $addFields, $filter. So what we can do is to go with a trick using BSON
Note : This code is not tested, Hope, it would work. It was written based on working Mongo playground

How i can add my content in body of request? Groovy

I have a json request (generated with Postman app). I'm pretty sure my API is working correctly. How can I send a POST request with my content in the body using Groovy?
I run this code, but I get a 500 error. This is due to incorrect parameters in my request.
Sorry, my code look bad, because I don’t know what other methods to use and I decided to slip the line on my forehead.
The code:
def rest = new RESTClient('http://logicased-mog.service.btlab.ru/')
def response = rest.post(
path: 'alfresco/s/mog/outgoing/createOutgoing',
headers: [Authorization:"user1 user1"],
body: [fromSoo: 'true',
attachments: [],
signer: 'jfjf',
executor: 'kjdf',
isElectronicSign: 'true',
shortDescription : 'dskjh',
sheetsNumber : 3,
note: 'dshsd',
reviewList : [],
NodeRef: '',
apps : 5],
requestContentType: 'application/json' )
response.responseData
return response.contentType
JSON request (will be validated with Postman app):
{
"fromSoo": true,
"attachments": [
{
"attachmentNodeRef": "workspace://SpacesStore/2c300b5a-8646-45ea-afc4-c8a4a6a2db55",
"attachmentCategory": "1"
},
{
"attachmentNodeRef": "workspace://SpacesStore/d71d31f7-c1fe-434a-8774-6dbb77bd135b",
"attachmentCategory": "2"
},
{
"attachmentNodeRef": "workspace://SpacesStore/faf06ad7-6707-4926-8c45-0e4d1d9b482e",
"attachmentCategory": "3"
}
],
"signer": "qqqe",
"executor": "qqqw",
"isElectronicSign": true,
"shortDescription": "short",
"sheetsNumber": 3,
"copies": "4",
"responseTo": "workspace://SpacesStore/0fc89bec-7b62-4862-a90b-311bd2c0a447",
"note": "note",
"reviewList": [
{
"stageItemMember": "kol",
"decisionTime": "15:15:15",
"decisionDate": "11-12-2020"
},
{
"stageItemMember": "qqqq",
"decisionTime": "11",
"decisionDate": "13-12-2020"
},
{
"stageItemMember": "qqq7",
"decisionTime": "18",
"decisionDate": "14-12-2020"
}
],
"NodeRef": "workspace://SpacesStore/990c4554-5499-44fe-9783-e3fbdb458d31",
"apps": "5"
}
I managed to solve the problem with the code
def createUrl = new URL('http://logicased-mog.service.btlab.ru/alfresco/s')
def map = [:]
map["fromSoo"] = 'true'
map["attachments"] = attachments
map["signer"] = 'qqqe'
map["executor"] = 'qqqw'
map["isElectronicSign"] = 'true'
map["shortDescription"] = 'dskjh'
map["sheetsNumber"] = 3
map["note"] = 'dshsd'
map["reviewList"] = reviewList
map["NodeRef"] = ''
map["responseTo"] = 'workspace://SpacesStore/0fc89bec-7b62-4862-a90b-311bd2c0a447'
map["apps"] = 5
map["copies"] = 2
//create JSON
def jsonBody = new JsonBuilder(map).toString()
// build HTTP POST
def client = new RESTClient(createUrl)
client.auth.basic 'user1', 'user1' // auth
def resp = client.post(body : jsonBody, contentType: JSON)
return resp.data

How to set nested JSON data to datatables?

I have a (nested) data structure containing objects and arrays. And trying to sent datatables but only one value displaying.
JSON data:
{
"data": [{
"name": "name1",
"value": "value1",
"list": [{
"sname": "sname1",
"svalue": "svalue1"
}, {
"sname": "sname2",
"svalue": "svalue2"
}]
}]
}
JSON data getting through URL by using Java.
jQuery code:
var pk = $("#pk").val();
console.log(pk);
url = "/register/search?id=" + pk;
console.log(url);
$('#largeTable').DataTable({
"ajax": url,
"bDestroy": true,
"columns": [{
"data": "name"
},
{
"data": "value"
},
{
"data": "list.1.sname"
},
{
"data": "list.1.svalue"
},
{
"data": null,
"defaultContent": editview
}
]
});
Here it is possible to display either first or second list values by using list.1 or list.0
But I want two values at a time.
If you used render or mRender you can do what you want with the object. For example you can traverse the array like in this example.
$('#largeTable').DataTable({
"columnDefs": [
{"targets": [0], "title":"name", "data":"name"},
{"targets": [1], "title":"value", "data":"value"},
{"targets": [2], "title":"list", "data":"list", "type":"html"
"render":function(data){
var listArray = data;
var listHtml = "";
for(var i=0;i<listArray.length;i++) {
listHtml += listArray[i].sname + " " + listArray[i].svalue + "<br>";
}
return listHtml;
},
}]
});
$.ajax({
"type":"GET",
"url":url,
"success":function(data,status) {
var jsonData = $.parseJSON(data);
$('#largeTable').dataTable().fnAddData(jsonData);
}
Your list in json data structure is an array. So, you should use
list.forEach(function(element) {
//console.log(element);
});
You could create an object and build JSON dynamically and set it to "columns" array.
Here is an example:
// make an empty object
var myObject = {};
// set the "list1" property to an array of strings
myObject.list1 = ['1', '2'];
// you can also access properties by string
myObject['list2'] = [];
// accessing arrays is the same, but the keys are numbers
myObject.list2[0] = 'a';
myObject['list2'][1] = 'b';
myObject.list3 = [];
// instead of placing properties at specific indices, you
// can push them on to the end
myObject.list3.push({});
// or unshift them on to the beginning
myObject.list3.unshift({});
myObject.list3[0]['key1'] = 'value1';
myObject.list3[1]['key2'] = 'value2';
myObject.not_a_list = '11';

extjs combobox afterrender() called together leading to asynchronous ajax calls

I'm developing an application using Java Spring and ExtJS. The front end contains a panel with some fields including 3 comboboxes. To fill the comboboxes, I have defined a function which is fired on ComboBox afterRender. I have a store for each combobox (each combobox is filled from different tables).
The problem is when the page is rendered, the function is called 3 times but only the 3rd combo box is filled, or the JSON string returned contains only the value for last combo box. Actually the request for all 3 comboboxes are sent, but only the last request is processed.
Can anyone give me an idea how to handle this problem?
This is how i defied a combo box.
{
xtype: 'combobox',
x: 300,
y: 70,
store: 'TasksStr',
msgTarget: 'side',
displayField: 'label',
valueField: "value",
itemId: 'TaskRef',
fieldLabel: 'Task Ref',
name: 'taskRef'
} //Similarly 2 more combo boxes for Project and Status
This is the controller:
init: function(application) {
this.control({
"#TaskRef": {
afterrender: this.onComboboxAfterRender,
select: this.onFormBlur
},
"#ProjectRef": {
afterrender: this.onComboboxAfterRender,
select: this.onFormBlur
},
"#StatusRef": {
afterrender: this.onComboboxAfterRender,
select: this.onFormBlur
}
});
}
This is the store:
Ext.define('MainApp.store.TasksStr', {
extend: 'Ext.data.Store',
requires: [
'MainApp.model.Model'
],
constructor: function(cfg) {
var me = this;
cfg = cfg || {};
me.callParent([Ext.apply({
storeId: 'TasksStr',
model: 'MainApp.model.Model',
proxy: {
type: 'ajax',
url: 'http://localhost:8080/project/Tasks',
reader: {
type: 'json',
root: 'data',
totalProperty: 'count'
}
}
}, cfg)]);
}
});
This is the controller in java:
#RequestMapping(value="/{id}")
public String getElanLUT(#PathVariable("id") String Id, ModelMap model ){
System.out.println(Id);
try{
ABCDao.set(Id);
List<ABC> List = Dao.getABC();
model.addAttribute("data", List);
model.addAttribute("success", true);
model.addAttribute("count", List.size());
}catch(Exception e){
model.addAttribute("success", false);
e.printStackTrace();
}
return "jsonTemplate";
}
While running this code, the console for java prints all 3 Id's but the value returned is just the 3rd one.
Thanks in advance.!
You need to create store instances for all 3 combo boxes.
{
xtype: 'combobox',
x: 300,
y: 70,
store: Ext.create('MainApp.store.TasksStr'),
msgTarget: 'side',
displayField: 'label',
valueField: "value",
itemId: 'TaskRef',
fieldLabel: 'Task Ref',
name: 'taskRef'
}

How to send data from controller which is acceptable format to Highstock?

I am new to Highstock, am not able to plot the graph.
I am sending an AJAX request to get the graph data.I am returning List of X-Axis Data, and List of Y-Axis Data, I also used Map but the values are coming like {1420051860000=101}, which is not acceptable format in Highstock.
$(document).ready(function(){
$.ajax({ url: 'getData',
dataType : 'json',
type: 'GET'
success: function (data) {
var xAxisdata= data.xAxisData;
var yAxisData=data.yAxisData;
//converting two arrays to two-dimesional array, It's not working
var jarray = [];
for (var i=0; i<xAxisdata.length && i<yAxisdata.length; i++){
jarray[i] = [xAxisdata[i], [yAxisdata[i]]];
}
//Getting these values for X and Y values
var xAxisdata=[1420051860000,1420052160000,1420052460000,1420052760000,1420053060000,....];
var yAxisdata=[100,110,112,113,110,112,111,110,115,116,114,114,110,114,112,113,110,....];
//Creates chart
var chart =new Highcharts.StockChart({
chart: {
renderTo: "container",
zoomType: 'x'
},
rangeSelector : {
selected : 1,
inputEnabled: $('#container').width() > 280
},
title : {
text : 'AAPL Stock Price'
},
credits: {
enabled: false
},
xAxis: {
title: {
text: 'Time'
},
type: 'datetime',
labels:{
formatter:function(){
return Highcharts.dateFormat('%H<br/>%d<br/>%m<br/>%Y',this.value);
}
},
},
yAxis: {
title: {
text: "Stock "
},
lineWidth: 1,
min:0,
gridLineWidth: 0
},
series : [{
name : 'AAPL',
showInLegend: true,
data : jarray,
marker : {
enabled : true,
radius : 3
}
}]
});
}
});
} );
And also facing issue with Months, in javaScript the months are starting from 0 to 11, But in java starts from 1. If the month is JAN-2014, it showing FEB-2014.
Suggest me the best way to plot the graph using JSON Response.
You were very close, there's just a little issue with the format of your array you've built.
Try to use
var jarray = [];
for (var i=0; i<xAxisdata.length && i<yAxisdata.length; i++){
jarray[i] = [xAxisdata[i], yAxisdata[i]];
}
Just remove the outer square brackets on [ yAxisdata[i] ]
Like in this jsFiddle

Categories