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
});
Related
I have list and return from controller and i'm trying to show in a mvc view using jquery each loop function.I can get to list and send to view but when jquery loop start i cannot get index and value.I checked Console and Sources,values are there.
This is my controller codes
public JsonResult electric()
{
int id = Convert.ToInt32(Session["id"]);
string cs = "data source=LNPC;initial catalog=db;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework";
SqlConnection connection = new SqlConnection(cs);
SqlCommand command = new SqlCommand("electrcic_bills", connection);
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Parameters.AddWithValue("#id", id);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
List<analiz> TestList = new List<analiz>();
analiz electric;
while (reader.Read())
{
electric= new analiz();
electric.jan= Convert.ToDouble(reader["jan"].ToString());
electric.feb= Convert.ToDouble(reader["feb"].ToString());
electric.march= Convert.ToDouble(reader["march"].ToString());
electric.april = Convert.ToDouble(reader["april"].ToString());
TestList.Add(electric);
}
return Json(new { List = TestList }, JsonRequestBehavior.AllowGet);
}
Jquery codes
$("#electric").click(function () {
$("canvas#myCharts").remove();
$("#canvas1").append('<canvas id="myCharts" width="200" height="200"></canvas>');
$.ajax({
type: "GET",
url: "/MainController/electric",
dataType: "json",
success: function (List) {
var data = List.List;
$.each(data, function (index, value) {
alert(data);
});
},
});
});
With this method i cannot get value but when i write electric.push(List.List[0].jan._bills_electric) like this i can get value manualy perfctly.
This my Source codes from browser
Local List:List: Array(1)
0:
jan_bills: null
jan_bills_electric: 135
dec_bills: null
dec_bills_electric: 60
You are using List word in your return Json() statement. This may be ambiguous for Java.
Try using another name with camel case typography to solve the problem.
In your Javascript, try to use
var data = List["List"];
instead of
var data = List.List;
Okey i found my answer and where l am wrong.
First- there is nothing wrong in my controller
Second- in each loop function,my array not only array,it is array in OBJECT.I've found this link and try each loop in a each loop and i got my items from jquery loop.
var json = [
{ 'red': '#f00' },
{ 'green': '#0f0' },
{ 'blue': '#00f' }
];
$.each(json, function () {
$.each(this, function (name, value) {
console.log(name + '=' + value);
});
});
I want to look up a user in my Cognito user pool by their sub, which as far as I can tell, is just their UUID. I would like to do this in Java within a Lambda function but cannot find how to do this in AWS's documenation. Any thoughts?
Now it works.
http://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListUsers.html
"sub" in list of supported attributes.
Example for JavaScript:
var cog = new AWS.CognitoIdentityServiceProvider();
var filter = "sub = \"" + userSub + "\"";
var req = {
"Filter": filter,
"UserPoolId": "your pool id" // looks like us-east-9_KDFn1cvys
};
cog.listUsers(req, function(err, data) {
if (err) {
console.log(err);
}
else {
if (data.Users.length === 1){ //as far as we search by sub, should be only one user.
var user = data.Users[0];
var attributes = data.Users[0].Attributes;
} else {
console.log("Something wrong.");
}
}
});
As of today this is not possible with Cognito User Pools.
Users can only be looked up using their username or aliases. ListUsers API also allows users to be searched by providing search filters on some standard attributes but sub is not one of them.
// class var
protected final AWSCognitoIdentityProviderClient identityUserPoolProviderClient;
// initialize the Cognito Provider client. This is used to talk to the user pool
identityUserPoolProviderClient = new AWSCognitoIdentityProviderClient(new BasicAWSCredentials(AWS_ACCESS_KEY, AWS_SECRET_KEY));
identityUserPoolProviderClient.setRegion(RegionUtils.getRegion(USER_POOL_REGION));
// ...some init code omitted
// build the request
AdminGetUserRequest idRequest = new AdminGetUserRequest();
idRequest.withUserPoolId(USER_POOL_ID);
idRequest.withUsername(username);
// call cognito for the result
AdminGetUserResult result = identityUserPoolProviderClient.adminGetUser(idRequest);
// loop through results
List<UserType> userTypeList = result.getUsers();
// loop through them
for (UserType userType : userTypeList) {
List<AttributeType> attributeList = userType.getAttributes();
for (AttributeType attribute : attributeList) {
String attName = attribute.getName();
String attValue = attribute.getValue();
System.out.println(attName + ": " + attValue);
}
}
Old question, but you the username parameter is overloaded in Cognito's adminGetUser method. It is, unfortunately, not documented: adminGetUser SDK
Here's a snippet:
const params = {
UserPoolId: 'someUserPoolId'
Username: 'random-string-sub-uuid',
};
CognitoService.adminGetUser(params,(err, data) => {
console.log(data);
})
Returns:
{ Username: 'random-string-sub-uuid',
UserAttributes:
[ { Name: 'sub', Value: 'random-string-sub-uuid' },
{ Name: 'custom:attributeName', Value: 'someValue' },
{ Name: 'email_verified', Value: 'false' },
{ Name: 'name', Value: 'nameValue' },
{ Name: 'email', Value: 'user#stackoverflow.com' } ],
UserCreateDate: 2018-10-12T14:04:04.357Z,
UserLastModifiedDate: 2018-10-12T14:05:03.843Z,
Enabled: true,
UserStatus: 'CONFIRMED' }
I am starting out on Elasticsearch. The scalability and performance is awesome, but I'm having trouble with the java API. Given some profile data where the id is a username and the profile contains attributes and scores (eg strength : 30, dexterity : 72, magic : 48) I want to get the top profiles for a particular combination of attributes eg strength + dexterity, or strength + magic etc.
Here is a query that I've used in Sense, which does exactly what I need:
GET_search{
"size": 0,
"aggs": {
"group by profile": {
"terms": {
"field": "profileId",
"order": {
"score_return": "desc"
}
},
"aggs": {
"score_return": {
"sum": {
"script": "doc['strength'].value + doc['dexterity'].value"
}
}
}
}
}
}
So now I want to port this query into my Java code. I managed to get it working, but it feels like it's extremely ugly - is there a better way of querying this data, or perhaps some library out there with a nice API, that can bind results to fields with annotations etc? Any suggestions welcome. This is what I have so far (it works, I just don't like the look of the code):
private void run() throws UnknownHostException {
InetAddress inetAddress = InetAddress.getByName(HOST_IP);
InetSocketTransportAddress transportAddress = new InetSocketTransportAddress(inetAddress, HOST_PORT);
Client client = TransportClient.builder().build().addTransportAddress(transportAddress);
String queryString = "{ \"aggs\": { \"group by profile\": { \"terms\": { \"field\": \"profileId\", \"order\": { \"score_return\": \"desc\" } }, \"aggs\": { \"score_return\": { \"sum\": { \"script\": \"doc['dexterity'].value + doc['strength'].value\" } } } } } }";
//Sample Query - JSONObject
//We convert the raw query string to JSONObject to avoid query parser error in Elasticsearch
JSONObject queryStringObject = new JSONObject(queryString);
//Elasticsearch Response
SearchResponse response = client.prepareSearch("profiles").setTypes("profile").setSource(queryStringObject.toString()).execute().actionGet();
//Elasticsearch Response Hits
SearchHits hits = response.getHits();
Aggregations aggregations = response.getAggregations();
Map<String, Aggregation> aggsMap = aggregations.asMap();
Aggregation groupBy = aggsMap.get("group by profile");
System.out.println(groupBy);
StringTerms st = ((StringTerms)groupBy);
System.out.println(st);
List<Bucket> buckets = st.getBuckets();
for(Bucket bucket : buckets) {
System.out.println(bucket.getKeyAsString());
Aggregation score = bucket.getAggregations().get("score_return");
String value = ((InternalSum)score).getValueAsString();
System.out.println(value);
}
client.close();
}
The servlet which receives request --
Gson gson = new Gson();
JsonObject myObj = new JsonObject();
LoginBean loginInfo = getInfo(userId,userPwd);
//System.out.println("00000000-----------"+loginInfo.userId);
JsonElement loginObj = gson.toJsonTree(loginInfo);
if(loginInfo.getUserId() == "GUEST!"){
myObj.addProperty("success", false);
}
else {
myObj.addProperty("success", true);
}
myObj.add("login", loginObj);
System.out.println(":::::"+myObj.get("success"));
out.println(myObj.toString());
out.close();
Here is the js file -----
function loadScript(url, callback)
{
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.onreadystatechange = callback;
script.onload = callback;
head.appendChild(script);
}
loadScript("js/json2.js", myJSCode);
var myJSCode = $(document).ready(function() {
$("#loginForm").submit(function(e){
e.preventDefault();
});
$("#login").click(function(e){
dataString = $("#loginForm").serialize();
var id = $("input#id").val();
var pwd = $("input#pwd").val();
dataString = "id=" + id + "&pwd="+pwd;
$.ajax({
type: "POST",
url: "login",
data: {
id : id,
pwd : pwd
},
dataType: "json",
success: function( data, textStatus, jqXHR) {
if(data.success){
$("#ajaxResponse").html("");
$("#ajaxResponse").append("<b>Welcome</b> " + data.login.id + "<br>");
//alert("#ajaxResponse" + data.login.id);
alert(data['id']);
alert(data['pwd']);
}
else {
$("#ajaxResponse").html("<div><b>Login Credentials are invalid!</b></div>");
}
}
});
I am getting the ajaxResponse if I am going with 1 element i.e 'id' but when I tried to get both the response I am getting value as undefined. I have tried with data.login.id & data[id] but unable to get desired output. Any help will be appreciated. Even I have tried with JSON.Stringify().
$.ajax({
type: "POST",
url: "login",
data: {
id : id,
pwd : pwd
},
...
This has data passed to ajax is not the same as the data in
success: function( data, textStatus, jqXHR) {
if(data.success){
...
In this success callback data is response from the server and it has a different (or same structure) based on data that server returns to you.
if you want to print the value from ajax call, you need to use just id
$("#ajaxResponse").append("<b>Welcome</b> " + id + "<br>");
I see you are trying to use "data.login.id" can you check what is real structure of data in response? add console.log(data) or put breakpoint that callback, or simple add debugger; code, it will stop code in that line for you without adding breakpoint.
Thanks Alex. I will give you +1 for the line
$("#ajaxResponse").append("<b>Welcome</b> " + id + "<br>");
Though it is working when I use:
data: {
id: $('#id').val(),
pwd: $('#pwd').val()
},
Without changing my code to this one the line was not working. Thanks for the suggestion.
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?