How to send date with gremlin javascript - javascript

I think I'm missing something about the new javascript gremlin client.
I can't find any way to send any kind onf date from my script to the database.
Code example :
import { P } from 'gremlin/lib/process/traversal':
import g from '../path/to/my/gremlin/client';
const myFunction = id => g.V(id).has('some_date', P.gte(new Date())
In this code example I send a javascript date object. I tried a formated string, a timetamp, a stringified timestamp, and one exotical things.
And I always end up wwith an error like this one :
Error: Server error: java.lang.String cannot be cast to java.util.Date (500)
Or this one when I try with a number
Error: Server error: java.lang.Integer cannot be cast to java.util.Date (500)
Is there anything I can do ?
Regards,
F.

I'd suggest storing your Date as a String in your graph using ISO-8601 format. Then you should have no type transformation problems from Javascript as you'll just be sending strings in your Gremlin.
You have to be somewhat aware of the data types you have in your graph versus the ones you have in the target programming language you're using. Unfortunately, there aren't always one-to-one mappings to all the possible types that can be stored in a Java-based graph database (e.g. javax.time.*). For the most portable code and data, try to stick to the primitive types.

Related

Datetime seems to break Google Apps Script client-side deserialization

I've uncovered an odd bug with Google Apps Script's web interface that it can't seem to transport datetime values from the server side to the client.
// Code.gs
function fetchData(){
var spreadsheet = SpreadsheetApp.openByUrl(SHEET_URL)
var sheet = spreadsheet.getSheetByName("My sheet")
var values = sheet.getDataRange().getValues()
Logger.log(values)
return values
}
// javascript.html
<script>
$(function() {
google.script.run.withSuccessHandler(console.log).fetchData()
})
</script>
If I run the above without any dates in the "My sheet" spreadsheet, it works as expected, with the server side Logger.log and the client side console.log showing the same data. But if I input a date type value into the spreadsheet, the Logger.log will still show everything as expected, but the console.log will simply log null.
I checked the XHR and it appears that the data is in fact making it to the browser, but it looks like something about the de-serialization is breaking. If the date is listed as 7/7/21 in the spreadsheet, it is coming across as Wed Jul 07 00:00:00 PDT 2021 in the XHR.
Any ideas about how to fix are much appreciated! Thank you!
You are describing the documented behavior of google.script.run:
Requests fail if you attempt to pass a Date, Function, DOM element besides a form, or other prohibited type, including prohibited types inside objects or arrays. Objects that create circular references will also fail, and undefined fields within arrays become null.
See the reference given by #Cooper.
To pass datetime values between the client and the server, serialize before sending them across. The easiest way is usually to use date.getTime() and pass as integer. Try this:
const values = sheet.getDataRange().getValues().map(value => {
(Object.prototype.toString.call(value) === '[object Date]')
? value.getTime()
: value
});
On the receiving side, use const date = new Date().setTime(value) to convert the integer back to a Date object.
If you do not know the locations of dates in the spreadsheet, but need to detect them in data, you may want to use a magic prefix like 'date:' + value.getTime().

Convert a JSON to TW Object of type ANY

Using IBM BPM 8.6
I have a JSON as follows:
tw.local.person = "{\"firstName\":\"Ahmed\",\"job\":\"Doctor\"}";
I am using the BPM helper toolkit to convert the json to TW Object
tw.local.outputObject = BPMJSON.convertJSONToTw(tw.local.person);
RESULTS:
If the outputObject is of type Person (with the attributes firstName and job), it works and the object is created.
If the outputObject is of type any, it doesn't work
How can I get the output in an any object?
Any workaround or a a tweak in the BPM-JSON-Utils.js or json2.js files?
The first thing I would note that in my 8.6 install, calling JSON.parse() just works, so you don't need the community toolkit. That being noted, that approach seems to encounter what is likely the same bug as you are seeing when you try to do it using ANY or Record.
Based on the error it seems that the underlying TWObject won't let you reference member fields that are not explicitly declared. In my tests, using the JSON String -
var json='{ "name" : "Andrew", "value" : "42"}';
I tried -
tw.local.myNvp = JSON.parse(json);
tw.local.myAny = JSON.parse(json);
The first one which was parsing into a variable of type "NameValuePair" from the system data toolkit worked. The 2nd which was trying to parse into an "ANY" failed. I also tried with Record to see if we could get there, but that failed as well.
My suggestion would be to return the raw JSON to the caller and have them invoke the parse line above. I'm assuming the caller is expecting a specific type back, which means the variable isn't an Abstract type, so the parse call should work.
-Andrew Paier

In NodeRed, how can I separate values from JSON data sent by the Watson IoT Platform

How can I get the distance value and how to assign it to another variable.
I get that data from bluemix (Watson IoT Platform) to node-red
{distance:"45.9"};
I tried like
var data=msg.distance;
Use Json.parse to convert the string to an array.Now you can access the elements of the array.
If you include the JSON node it will convert your JS Object to JSON. But maybe you have messed with the quotes and actually have json; by default you would.
I would add a Debug node to your IoT-In node. Check what exactly you receive. And then it is usually easy to parse like (it depends on what you send):
var distance = msg.payload.d.distance
var distance = msg.payload.distance
You might want to edit your Question to include exactly what you receive in the Debug node and need to parse.
Also be aware that your value for distance is a string, you'll probably want to convert it to a number at somepoint. If it is in your control, it would be better practice to send it as a number to start with.

Extracting SSH public key from message with libssh

I am using node-libssh as a nice binding to libssh in my node application and can simulate an ssh server quite easily. However I need to extract the public key from an incoming SSH session. I need a stringified version of the key for later usage in a db query and it must match the same format as you would find in id_rsa.pub file.
I have been able to narrow it down to needing a way to convert between a libssh ssh_key to a char array.
Its simple enough to use ssh_key pubKey = ssh_message_auth_pubkey(message); to get a ssh_key version of the pubkey, however there appear to be no methods within libssh to convert from an ssh_key into any other format which can be passed back to my nodejs process. I forsee something like this being the solution:
ssh_key authKey = ssh_message_auth_pubkey(m->message);
const char *pubKey = ssh_key_to_char(authKey);
if (pubKey)
instance->Set(NanSymbol("pubKey"), v8::String::New(pubKey));
But naturally it's not that simple as no method ssh_key_to_char exists, I would really appreciate any pointers here.
After digging for quite a while I was able to find this method which I was able to use to build this functionality:
ssh_pki_export_pubkey_base64(ssh_key, char*)
This converts an ssh_key into its base64 equivalent.

How I handle JSON dates returned by ASP.NET AJAX?

The problem of how to handle dates in JSON is one of the more troublesome issues that may arise when directly calling ASP.NET AJAX web services and page methods.
Unlike every other data type in the language, JavaScript offers no declarative method for expressing a Date. Consequently, embedding them within JSON requires a bit of fancy footwork.
I will attempt to explain what exactly the problem is with dates in JSON.
What’s the problem?
The fundamental problem is that JavaScript does not provide a way to declaratively express Date objects. You may previously have seen this described as (the lack of) a Date literal.
What are literals? To illustrate, these are literals for several other data types:
// String
'foo';
// Number
3.14;
// Boolean
true;
// Array
[1, 2, 3, 5, 7];
// Object
{ pi: 3.14, phi: 1.62 };
Unfortunately, when it comes to dates, the lack of a literal means that the only way to create one is by explicitly initializing a Date object:
// Correct.
new Date('4/26/09');
// Correct (the month is 0 indexed, hence the 3).
new Date(2009, 3, 26);
// Incorrect. This is a string, not a Date.
'4/26/09';
While this limitation is fine when writing client-side JavaScript code, it leaves us without a good way to transmit dates within JSON objects.
lack of a date literal is a problem, Can Somebody Suggest a Solution.
Consider why you want to send a DateTime to the client-side to begin with. Most often, you’re displaying a string representation of it and have no need for the proper JavaScript Date object.
What’s more, if you end up with a JavaScript Date object, you’ll probably use additional code or a JavaScript library to display it in a user-friendly format.
As much as I appreciate a clever workaround, I’d much rather avoid the problem completely. Rather than jump through all of these hoops to instantiate a JavaScript Date object on the client-side and then format it, I suggest simply returning a formatted string.
For example,
[System.Web.Script.Services.ScriptService]
public class DateService : System.Web.Services.WebService
{
[WebMethod]
public string GetDate()
{
return new DateTime(2009, 4, 26).ToLongDateString();
}
}
Now, calling the service will return this JSON:
{"d":"Sunday, April 26, 2009"}
No more regular expressions. No more JavaScript Date objects. No more worrying about formatting the data on the client-side.
Even better, no functionality is lost. If we need to instantiate Dates, we still can.
I recently wrote a blog post about this sort of thing here... it's a minefield! At work, we've decided to transmit DateTimes and DateTimeOffsets from our MVC3 service as strings, using variations on a W3C format found here. For DateTime, we use YYYY-MM-DDThh:mm:ss, for DateTimeOffsets, YYYY-MM-DDThh:mm:ss+TZD (these format specifiers are W3C, not .NET).
But the answer to this question really does depend on what you want to do with the dates. As another reply suggests, you might be able to get away with simply sending a human readable string across the wire if all you want to do is display it to an end user.
I use two ways, one is to make it Date.UTC() and the other to make it as Ticks. Both they work.
The function that convert it to Json Ticks
private static readonly long UnixEpochTicks = (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).Ticks;
  public static long cOnlyDate(long Ticks)
  {
    return (864000000000 * (Ticks / 864000000000));
  }
public static long ToJsonTicks(DateTime value)
{
return (cOnlyDate(value.ToUniversalTime().Ticks) - UnixEpochTicks) / 10000;
}
The results will be like {dt : 28839281}
and how I convert it to Date
public static string ToJsonDate(DateTime value)
{
return string.Format("Date.UTC({0}, {1}, {2})", value.Year, value.Month-1, value.Day);
}
The results will be like {d : Date.UTC(2012, 2, 11)}
ps, I just test now the solution of the "Unknow" and not work on my code.

Categories

Resources