Requested unknown parameter '2' from datatable - java

I am using Jquery Datatable with server side processing in order to process all my data. My parameter '2' is a date, which I enter in as a String, convert to a Date to add to the database, however, use a String again to display to the webpage. This works fine for 'GetData' process. However, when I enter in a new dataset using 'AddData', I get the error in the title. It seems that only the two columns that deal with Date are throwing this error, the rest of the row gets written. As soon as I refresh the page, everything does back to normal.
This is my datatable script:
var i = 0;
$(document).ready(function(){
oTable = $("#datatables").dataTable({
"aoColumns" : [
{ "sName" : attendingPhysician" },
{ "sName" : "physicianName" },
{ "sName" : "dateStart" },
{ "sName" : "dateEnd" },
{ "sName" : "teamNumber" }
],
"sAjaxSource" : 'teamassignmentdata',
"sServerMethod": "GET",
"fnDrawCallback" : function(oSettings) {
//The call to makeEditable is set here to make sure all the data are loaded
i++;
if(i == 1) {
this.makeEditable({
sUpdateURL : 'UpdateTeamAssignmentData',
sAddNewRowFormId: "formAddNewRow",
sAddNewRowButtonId: "btnAddNewRow",
sAddNewRowOkButtonId: "btnAddNewRowOk",
sAddNewRowCancelButtonId: "btnAddNewRowCancel",
sAddURL: "AddTeamAssignmentData",
sAddHttpMethod: "POST",
aoColumns : [
{}, //physician number; default editing
{}, //physician name; default editing
{ //date start; datepicker
type : 'datepicker',
datepicker : {
dateFormat : 'yy-mm-dd'
}
},
{
type : 'datepicker',
datepicker : {
dateFormat : 'yy-mm-dd'
}
}, //date end; datepicker
{ //team number; no editing
indicator: 'Saving...',
tooltip: 'Click to edit team number',
loadtext: 'loading...',
type: 'select',
onblur: 'submit',
data: "{'5':'5','6':'6','7':'7','8':'8','9':'9'}"
}
],
height : "20px"
});
}
}
});
});
And this is the method that is actually entering the data into the database, and outputting it to the datatable.
String physician = request.getParameter("physician");
String physicianname = request.getParameter("physicianname");
String datestart = request.getParameter("datestart");
String dateend = request.getParameter("dateend");
String team = request.getParameter("team");
boolean addSuccess = true;
PhysicianTeamData physicianTeamData = new PhysicianTeamData();
String sql = "INSERT INTO " + TABLE_NAME + " " +
"(team_attendingPhysician, team_physicianName, team_dateStart, " +
"team_dateEnd, team_teamNumber) VALUES (?,?,?,?,?);";
int returnId = 0;
try {
dateStart = dateFormat.parse(datestart);
dateEnd = dateFormat.parse(dateend);
sqlDateStart = new java.sql.Date(dateStart.getTime());
sqlDateEnd = new java.sql.Date(dateEnd.getTime());
ps = con.prepareStatement(sql);
ps.setInt(1, Integer.parseInt(physician));
ps.setString(2, physicianname);
ps.setDate(3, sqlDateStart);
ps.setDate(4, sqlDateEnd);
ps.setString(5, team);
returnId = ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
addSuccess = false;
}
PrintWriter out = response.getWriter();
if(addSuccess) {
PhysicianTeam pt = new PhysicianTeam();
pt.setRecordNumber(returnId);
pt.setAttendingPhysician(Integer.parseInt(physician));
pt.setPhysicianName(physicianname);
pt.setDateStart(datestart.toString());
pt.setdateEnd(dateend.toString());
pt.setTeamNumber(Integer.parseInt(team));
physicianTeamData.addPhysicianTeamData(pt);
//out.print(returnId);
out.print(pt);
} else {
out.write("Row Add Failed!");
}
PhysicianTeamData is just an arraylist, and these are the fields in PhysicianTeam class:
private int attendingPhysician;
private String physicianName;
private String dateStart;
private String dateEnd;
private int teamNumber;
Like I mentioned, the JSON object puts dateStart as parameter '2' and dateEnd as parameter '3', both of which are throwing error, even though I am outputting them as a String.
Where am I going wrong?

Related

If string contains with get getContents (JXL)

UPDATE: POSSIBLE SOLUTION POSTED BELOW BY MYSELF
I need my program to read a cell. If it contains a specific string, lets say the name "Jacob", then it needs to execute a certain static function defined later in the code.
My IF statement will be nested in a while loop.
int currentRow = 1;
Cell cell;
Cell ncell;
while (!(cell = sheet.getCell(URL_COLUMN, currentRow)).getType().equals(CellType.EMPTY)) {
String url = cell.getContents();
System.out.println("Checking URL: " + url);
ncell = sheet.getCell(NAME_COLUMN, currentRow);
ncell.getContents();
ncell.toString();
if (ncell.contains("Jacob")) {
String FAV = JacobFavFood(url); // A static function will be defined later for this
System.out.println("Jacob's favorite food is " + name);
Label cellWithFAV = new Label(FAV_COLUMN, currentRow, FAV);
sheet.addCell(cellWithFAV);
}
currentRow++;
}
workbook.write();
workbook.close();
UPDATE: POSSIBLE SOLUTION POSTED BELOW BY MYSELF
int currentRow = 1;
Cell cell;
Cell ncell;
while (!(cell = sheet.getCell(URL_COLUMN, currentRow)).getType().equals(CellType.EMPTY)) {
String url = cell.getContents();
String NAME = ncell.getcontents();
System.out.println("Checking URL: " + url);
ncell = sheet.getCell(NAME_COLUMN, currentRow);
if (NAME.contains("Jacob")) {
String FAV = JacobFavFood(url); // A static function will be defined later for this
System.out.println("Jacob's favorite food is " + name);
Label cellWithFAV = new Label(FAV_COLUMN, currentRow, FAV);
sheet.addCell(cellWithFAV);
}
currentRow++;
}
workbook.write();
workbook.close();
I forgot I can define the string as was done with the url. This does work, and it is able to call on a static function. I am still wondering why .toString() didn't work, though.

Split string from time

I am getting time as like follow.
" Time : 06:00:00 AM "
I have used split method as follows, split(":"). Then it split time from all the ":" in string.
I want to separate time just after first ":" and remove the "AM" fraction from then time.
Please can anybody help me with this code.
I have build this simple sample as follows. My effort to split data after ":". Above problem occurs when it is come to split time.
import java.util.ArrayList;
import java.util.List;
public class StringBuilderSample {
public static void main(String []arg) {
List<Object> dataList = new ArrayList<Object>();
Object[] dataArr = {
"Serial no : 10",
"Supplier ID : 1",
"Supplier Name : Md40",
"GRN no : 20555",
"Bag ID : 10",
"Weight : 500",
"Date : 09-10-2017",
"Time : 16:09 PM",
"User ID : 204"
};
for(int j=0;j<dataArr.length;j++) {
String arrayData = dataArr[j].toString();
Object[] fraction = arrayData.split(":");
if(fraction.length>2) {
StringBuilder strBuilder = new StringBuilder();
for(int i=1; i<fraction.length;i++) {
strBuilder.append(fraction[i]);
}
String newString = strBuilder.toString();
dataList.add(newString);
}else {
dataList.add(fraction[1]);
}
}
for(Object data : dataList) {
System.out.println(data);
}
}
}
You could use the limit parameter of split method:
Object[] fraction = arrayData.split(":", 2);
this will give:
fraction[0] --> Time
fraction[1] --> 16:09 PM
If your problem is to split the string "Serial no : 10" to "10" for all the objects and the time has ":" and which is causing you trouble then you can try the below code
for(int j=0;j<dataArr.length;j++) {
String arrayData = dataArr[j].toString();
String fraction = arrayData.substring(arrayData.indexOf(":") + 1);
dataList.add(fraction);
}
for(Object data : dataList) {
System.out.println(data);
}

URL is getting displayed as String in table

I wanted to display one URL in a table.
Value I had was : www.yahoo.com
I converted into format as below and returning back to table :
www.yahoo.com</font>"> Link
I want it to be displayed in URL form. But it is displaying as a string like as it is above.
Below is the method used for conversion :
private static String validateString(String header) throws Exception
{
System.out.println("&&&&&&&&&& inside validateString ");
String displayString = "";
String colorValue = "";
try
{
if((header) != null && !"null".equalsIgnoreCase(header))
{
displayString = header;
colorValue = "red";
displayString = "<font color=\""+colorValue+"\">"+displayString+"</font>";
}
}
catch(Exception e)
{
displayString = " ";
}
if(!"".equals(displayString))
{
displayString = " Link ";
}
if ("".equals(displayString))
{
displayString = " ";
}
return displayString;
}
Please let me know how to display as URL.
Thanks.
In the attribute href for the tag A, you only should use the proper URL not ant other tag. Change it to something like this:
Link

Can we do datatables server side pagination using mongodb and java?

Actually I have done client side pagination using datatables but now requirement has changed due to large number of records around 100K.
I need to implement server side pagination.
For that I used below code
GSP
$('#data-grid-table').dataTable( {
"processing" : true,
"sAjaxSource": dataUrl,
"serverSide" : true,
"sPaginationType": "full",
"iDisplayLength": 25,
"aLengthMenu": [[25, 50, 100, -1], [25, 50, 100, "All"]],
"scrollX": true,
"bFilter": false,
"columnDefs": [ {
searchable: false,
"orderable": false,
className: "view-cell",
targets: 0
}],
"aaSorting": [[1,'asc']],
"fnDrawCallback": function( oSettings ) {
var callBackFlag = $("#hidden-view-flag").val()
if(callBackFlag=="1"){
$("#hidden-view-flag").val("2")
}
if(callBackFlag == "2"){
$("#hidden-view-flag").val("3")
}
if(hideViewColumn){
$(".view-cell").hide();
}
$('.datasetTable, tbody').find('tr').each(function(){
$(this).find('th:nth-child(1)').removeClass("sorting_asc");
});
}
});
Controller
dbObjArray = new BasicDBObject[2]
dbObjArray[0]= cruxLevel
dbObjArray[1] = project
List<DBObject> pipeline = Arrays.asList(dbObjArray)
if (!datasetObject?.isFlat && jsonFor != 'collection-grid') {
output= dataSetCollection.aggregate(pipeline)
}else{
//def skipRecords = params.iDisplayStart
//def limitRecords = params.iDisplayLength
//println 'params.iDisplayStart' + params.iDisplayStart
//println 'params.iDisplayLength' + params.iDisplayLength
println 'else-====================='
DBObject limit = new BasicDBObject('$limit':10);
DBObject skip = new BasicDBObject('$skip':5);
isFlatOutput = true;
dbObjArray = new BasicDBObject[3]
dbObjArray[0]= project
dbObjArray[1]= skip
dbObjArray[2]= limit
List<DBObject> pipeline1 = Arrays.asList(dbObjArray)
AggregationOptions aggregationOptions = AggregationOptions.builder()
.batchSize(100)
.outputMode(AggregationOptions.OutputMode.CURSOR)
.allowDiskUse(true)
.build();
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date now = new Date();
println 'Start time to fetch -------------------------------------' + sdfDate.format(now)
output = dataSetCollection.aggregate(pipeline1,aggregationOptions)
Date now1 = new Date();
println 'End time to fetch-------------------------------' + sdfDate.format(now1)
}
if(isFlatOutput){
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date now2 = new Date();
println 'Start time to retrieve-------------------------------' + sdfDate.format(now2)
while(output.hasNext()) {
dataList.add(output.next());
}
Date now3 = new Date();
println 'End time to retrieve-------------------------------' + sdfDate.format(now3)
}
I was not getting how to take limit and skip so I have hard coded it.
Actual result: 10 results are displaying but next is disabled.
Expected result : 10 results should display and fetch next 10 records on click of next button.
Kindly tell me where I am going wrong.
def skipRecords
def limitRecords
if(params.iDisplayStart == null){
skipRecords = 0;
}
if(params.iDisplayLength == null){
limitRecords = 25;
}
def dbObjArrayTotal = new BasicDBObject[1]
dbObjArrayTotal[0]= project
List<DBObject> pipelineTotal = Arrays.asList(dbObjArrayTotal)
AggregationOptions aggregationOptions = AggregationOptions.builder()
.batchSize(100)
.outputMode(AggregationOptions.OutputMode.CURSOR)
.allowDiskUse(true)
.build();
def totalCount = dataSetCollection.aggregate(pipelineTotal,aggregationOptions)
totalCount = totalCount.size()
if(limitRecords == -1){
limitRecords = totalCount
}
DBObject limit = new BasicDBObject('$limit':limitRecords);
DBObject skip = new BasicDBObject('$skip':skipRecords);
dbObjArray = new BasicDBObject[3] dbObjArray[0]= project
dbObjArray[1]= skip
dbObjArray[2]= limit
List<DBObject> flatPipeline = Arrays.asList(dbObjArray)
output = dataSetCollection.aggregate(flatPipeline,aggregationOptions)
def serverData = [
"iTotalRecords" : totalCount,
"iTotalDisplayRecords" : totalCount,
"aaData": yourResult]
return serverData;
And above GSP is correct use as it is.

FullCalendar - Adding Multiple Events or Add Event Source

I have looked through the post in stackoverflow to add events into FullCalendar, however I am really new and find it really difficult to understand without an example. In short, is anyone here able to dumb it down for me, in order to add an array of objects into the FullCalendar?
I would like to add appointments that I have created Appointment(Date date, String name, String phoneNo). So they are retrieved in list:
PersistenceManager pm = PMF.get().getPersistenceManager();
String query = "select from " + Appointment.class.getName();
query += " where merchant == '" + session.getAttribute("merchant") + "'";
List<Appointment> appointment = (List<Appointment>) pm.newQuery(query).execute();
How am I able to populate the FullCalendar plugin with the list I obtained? Thanks a lot!
if anyone encounters the same problem as I do - you have a list of java objects and want it to populate FullCalendar, here's the solution:
JSP Page
$(document).ready(function() {
var calendar = $('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
selectable: true,
selectHelper: true,
select: function(start, end, allDay) {
var title = prompt('Event Title:');
if (title) {
calendar.fullCalendar('renderEvent',
{
title: title,
start: start,
end: end,
allDay: allDay
},
true // make the event "stick"
);
}
calendar.fullCalendar('unselect');
},
editable: true,
eventSources: [
{
url: '/calendarDetails',
type: 'GET',
data: {
start: 'start',
end: 'end',
id: 'id',
title: 'title',
allDay: 'allDay'
},
error: function () {
alert('there was an error while fetching events!');
}
}
]
});
});
Please take not of the URL, it is the servlet URL
Servlet
public class CalendarServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
String something = req.getSession().getAttribute("merchant").toString(); //get info from your page (e.g. name) to search in query for database
//Get the entire list of appointments available for specific merchant from database
//Convert appointment to FullCalendar (A class I created to facilitate the JSON)
List<FullCalendar> fullCalendar = new ArrayList<FullCalendar>();
for (Appointment a : appointment) {
String startDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(a.getDate());
startDate = startDate.replace(" ", "T");
//Calculate End Time
Calendar c = Calendar.getInstance();
c.setTime(a.getDate());
c.add(Calendar.MINUTE, 60);
String endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(c.getTime());
endDate = endDate.replace(" ", "T");
FullCalendar fc = new FullCalendar(startDate, endDate, a.getId(), a.getName() + " # " + a.getPhone(), false);
fullCalendar.add(fc);
}
//Convert FullCalendar from Java to JSON
Gson gson = new Gson();
String jsonAppointment = gson.toJson(fullCalendar);
//Printout the JSON
resp.setContentType("application/json");
resp.setCharacterEncoding("UTF-8");
try {
resp.getWriter().write(jsonAppointment);
} catch (IOException e) {
e.printStackTrace();
}
}
}
if you need more info on JSON or GSON, check the comments above.
Melvin you have tones of examples here in Stack, try searching for add event sources.
From my experience im fullcalendar, you can add events through JSON, well formed XML and array's and i think thats it. You can use ajax calls do retrieve does 3 types of formats.
In your server side you should create a method to return a String already with the XML/JSON/array built so you can pass to you ajax call.
take a look at https://github.com/mzararagoza/rails-fullcalendar-icecube
this is done in rails but i think what you are looking for is
dayClick: function(date, allDay, jsEvent, view) {
document.location.href=new_event_link + "?start_date=" + date;
},
full jquery
$('#calendar').fullCalendar({
dayClick: function(date, allDay, jsEvent, view) {
document.location.href=new_event_link + "?start_date=" + date;
},
header: {
left: 'prev,today,next',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
selectable: true,
selectHelper: true,
editable: false,
ignoreTimezone: false,
select: this.select,
eventClick: this.eventClick,
eventDrop: this.eventDropOrResize,
eventSources: [
{
url: '/event_instances.json',
data: {
custom_param1: 'something',
custom_param2: 'somethingelse'
},
error: function() {
alert('there was an error while fetching events!');
}
}
],
eventResize: this.eventDropOrResize
});

Categories