How to properly create a JavaScript Array of Dates in Spring? - javascript

I've got a Spring Web MVC application where I need to get a JavaScript Array filled with java.util.Dates that are stored in an ArrayList accessible from the webapp with ${cust.dates}.
How do I properly initialize the array in the webapp?
Thank you.

Spring executes at server-side, and JavaScript executes at client-side. For the point of view of Spring, JavaScript is just text that must be generated. And this text must represent valid JavaScript source code.
The JavaScript source code that creates an array of dates could thus be generated like this:
var dateArray = [];
<c:forEach var="javaDate" items="${cust.dates}">
dateArray.push(new Date(${javaDate.time}));
</c:forEach>
This will generate the following JavaScript code:
var dateArray = [];
dateArray.push(new Date(65987985);
dateArray.push(new Date(98654654);
// ...
with the numeric arguments being the number of milliseconds since the epoch, which is the same in Java and JavaScript.

Related

Formatting to Export from Sheets to Firebase

I'm working on an app/sheets combination scoring system for a tournament. The current data in the Firebase database is stored under a tag like so: tag:"[\"Test\",-1,12,3]"
The data is in the form of a list containing a single string and 3 numbers. Each index in the list will be stored in consecutive cells so referencing the data is easy. The difficulty I am having is formatting the data from the sheet to write it to the database in the same format.
Using JSON.stringify doesn't quite give me what I'm looking for:
var range = sheet.getRange(22,24,4,1);
var data = JSON.stringify(range.getValues());
result:
tag:"[[\"Test1\"],[70],[0],[18]]"
This is not quite the same as the rest of the data as I'm turning the entire range to a string by using stringify, but I don't know of a way to format the data to be stored as [string, int,int,int]. I am new to app scripts and java (hence my lack of knowledge of functions) and was hoping somebody knows of another way to write the range of cells to match the data stored in the database.
First thing, Google Apps Scripts uses JavaScript, not Java.
Second thing getValues() returns a Array of Arrays where each inner Array has the values of a row from the corresponding range. In order to get what you are looking for you have to flatten the result of getValues(). One way to do this is this:
var range = sheet.getRange(22,24,4,1);
var data = JSON.stringify(range.getValues().map([value] => value));
var values = [["Test1"],[70],[0],[18]];
var data = JSON.stringify(values.map(([value]) => value));
console.info(data)

Reading JSON objects from javascript file using JINT

I've been supplied with a javascript file containing two JSON objects such as this.
var languages = {"Languages":["English","Cymraeg","Deutsch"]};
var labels = [{"$JOB":["Job","Orchwyl","Auftrag",]},{"$JOB_NO":["Job Number","Rhiforchwyl","Auftragsnummer"]}];
I need to serialise the two JSON objects into something I can manipulate within .NET. I'm using JINT to get the two values from the file like this.
Engine js = new Engine();
js.Execute(fileContents);
languages = js.GetValue("languages");
labels = js.GetValue("labels");
But I can't do anything with the two values now. I can't parse the JSON, the values just come out as a strange object array where I can't actually determine the values.
Any suggestions on how I can get access to the JSON objects?
There is no JSON here.
This is javascript code, that creates javascript objects when it's evaluated.
Now, you can convert that javascript object into a JSON string.
The simplest way I found, was to have JINT do it for me, but I'm no expert in Jint, there might be better ways.
// Run javascript, inside the interpreter, to create JSON strings
js.Execute("languages = JSON.stringify(languages)");
js.Execute("labels = JSON.stringify(labels)");
// Extract the strings from the JS environment, into your c# code as strings
// Now, you can deserialize them as normal JSON
var languagesJsonString = js.GetValue("languages").AsString();
var labelsJsonString = js.GetValue("labels").AsString();

send array of Javascript constructors from PHP to Javascript

I am trying to send an array back to Javascript from PHP. I'm using Ajax to do this. I know how to send arrays to Javascript, but this time I'm trying to send an array that contains some Javascript constructors. For example I want to be able to send this: [new Date(2017,06,03), 25, 33] Is there a way to send this array to Javascript? If so, how will Javascript be able to use this array in a way where a new Date is created in the first index of the array?
Can not you just simply send value of new Date() instead of constructor? Will be more effective i assume.
Short answer: No, there is no direct way.
Long answer: When you say that you send arrays to Javascript from PHP, you need to understand that PHP is a server side language, and Javascript is what runs in the browser.
So, in between them, u have the network layer and all the things that transfers on that layer should be serializable, usually means strings.
So the data that you pass to the browser via Ajax usually is JSON.
It can contain only primitive values, like: string, number, boolean, null.
new Date(2017,06,03) is an javascript object, that is not part of JSON spec.
You can serialize the Date with some PHP func like date, send it via Ajax, and then deserialize it on Javascript world.
Something like that:
<?php
/* your Ajax return */
echo json_encode(array(date('c', mktime(0, 0, 0, 7, 1, 2000)), 25, 33)); // will return ["2000-07-01T00:00:00-07:00",25,33]
?>
Then on the JavaScript part u can parse it with Date constructor.
// Javascript
const response = ...
const myData = new Data(response[0]); // Will be Date obj.

How to convert MySQL Timestamp to Javascript date?

I want to display a Google Chart (Line Chart) on .jsp page of my Spring MVC application. The data is retrieved from a MySQL database, so I need to convert the YYYY-MM-DD HH:MM:SS format into Javascript's Date.
The database is created by Hibernate. The Reading entity has a time field of type java.sql.Timestamp, which is stored as DATETIME in the database.
The results is an Iterable<Reading> object passed to the .jsp via controller. It is passed correctly (I am displaying the data as a table, too).
I'm trying to use the solution proposed here, but it does not work.
Here's the code I'm trying to populate the chart with:
<c:forEach items="${results}" var="reading">
var t = "${reading.time}".split(/[- :]/);
var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
data.addRow([d,${reading.temperature}]);
</c:forEach>
The chart is not displaying.
Facts:
JDBC's java.sql.Timestamp is a subclass of java.util.Date.
JSTL has a <fmt:formatDate> for converting java.util.Date to String.
JavaScript Date constructor can take a.o. a string in ISO8601 time format.
Put together:
<c:forEach items="${results}" var="reading">
<fmt:formatDate var="time" value="${reading.time}" pattern="yyyy-MM-dd'T'HH:mm:ss" timeZone="UTC" />
var d = new Date("${time}");
// ...
</c:forEach>
Alternatively, just convert results to JSON using a decent JSON formatter in the controller and print it as if it's a JS variable like so var data = ${data};. See also a.o. How to access array of user defined objects within <script> in JSP?
Unrelated to the concrete problem: make sure your model is of java.util.Date type. You shouldn't have java.sql.* typed properties in your model. If you're using plain JDBC, just upcast ResultSet#getTimestamp() to java.util.Date directly. See also a.o. Handling MySQL datetimes and timestamps in Java.

How to convert javascript array to scala List object

I have inherited some code that uses the Play! framework which has scala.html files that have javascript in them. Play! and scala are all new to me.
One of the javascript functions does a post and gets back a JSON object. It then loops through the JSON object and creates an array.
var myArray = [];
function createArray(){
$.post('/createArray', $('#arrayForm').serialize()).done(function( data ) {
var obj1 = JSON.parse(data);
$.each(obj1, function(idx, obj) {
myArray.push(obj.name);
});
});
return true;
}
It then uses this array (of strings) to create a text input field that does autocomplete using the data in the array.
I want/need to convert this text input to a select dropdown using the Play! #select but the options arg for #select wants a List object (or Map or Seq - just figured List would be easier since I already have an array of strings).
If I manually create the List object, it works fine.
#select(pForm("equipName"), options(scala.collection.immutable.List("Yes","No")))
The problem is I cannot figure out how to convert the myArray array to a List object which I can then pass to the #select options.
I have found a lot of posts that talk about converting a scala List to an array but can't find a way to go the other way. I am hoping it is an easy thing that I can't seem to figure out.
Thanks in advance for the help.
You can not do that. And more precisely - you do not want to do that.
So basically your play application run on server. In your Play application all those .scala html files are compiled to generate some functions.
Now, when a play application receives a request from a client browser, it gets mapped to some controller by by router. The controller does some processing and finally take one of these above functions ( lets say for index.scala.html we get views.html.index ) and call this function with some parameters.
These functions returns some text which is then sent to the client's browser as HTTP response with response header Content-Type:text/html; charset=utf-8 which tells the browser to treat this text as html.
Now, the browser renders the html which has embedded JavaScript and hence runs the JavaScript. So... basically your JavaScrpt code does not exist on server... for play all of it is just text.
Both of these Scala code and JavaScript code are executed at very different times, at different computers and in different environments hence you can not do whatever you are saying.

Categories

Resources