Accessing the parsed output buffer with the binary-parser Library - javascript

https://github.com/keichi/binary-parser
Does the binary-parser library for Node allow you to access the variables that have been parsed from your input buffer? The Quick-Start instructions state "Parsed result will be returned as an object.".
I can't see a mechanism to reference a constructor function, outlined in the Create API method.
"create(constructorFunction)
Set the constructor function that should be called to create the object returned from the parse method."
How can I access the data that was parsed? For the GitHub example, tcp.js, the values from the example tcp.js (shown below):
https://github.com/keichi/binary-parser/tree/master/example
var Parser = require('../lib/binary_parser').Parser;
var tcpHeader = new Parser()
.endianess('big')
.uint16('srcPort')
.uint16('dstPort')
.uint32('seq')
.uint32('ack')
.bit4('dataOffset')
.bit6('reserved')
.nest('flags', {
type: new Parser()
.bit1('urg')
.bit1('ack')
.bit1('psh')
.bit1('rst')
.bit1('syn')
.bit1('fin')
})
.uint16('windowSize')
.uint16('checksum')
.uint16('urgentPointer');
var buf = new Buffer('e8a203e108e177e13d20756b801829d3004100000101080a2ea486ba793310bc', 'hex');
console.log(tcpHeader.parse(buf));
binary-parser Output using parse(buf)
*{ srcPort: 59554,
dstPort: 993,
seq: 148994017,
ack: 1025537387,
flags: { urg: 0, ack: 1, psh: 1, rst: 0, syn: 0, fin: 0 },
dataOffset: 8,
reserved: 0,
windowSize: 10707,
checksum: 65,
urgentPointer: 0 }*
What if I wanted to access the dstPort 993 value - does binary-parser allow me to do this in Node.js?
In other words, how do I use the values from the parse operation? In my current limited knowledge of Node.js, I believe according to the documentation that I should be able to pick-off the values of the parse individually? Am I misinterpreting binary-parser's ability to assign variables name with types to variable that can be used in a user program? My goal is to access these variables whether in an array or other data structure in a later part of my program.

I'm not sure what your skill level is with JS, but you might try var dstPort = tcpHeader.parse(buf).dstPort; console.log(dstPort) and see if it says 993. That output looks like a JavaScript object--I don't know why you have asterisks around it. The parse function gives you a basic JavaScript Object the way you set it up, not anything particular to binary-parser.

Related

How to pass array of transferable objects i.e. buffer along with non transferable object i.e. json obj via web worker in JavaScript - postMessage()?

So, here is what I am trying to achieve:
Call a specific function onMessage() in main thread from web-worker.
Passing an array of transferable objects i.e. Uint16Array buffer, Float32Array buffer etc.
Along with all of above, I want to pass a simple boolean object or an integer or a string value while posting message.
For example:
const cornersArray = new Uint16Array(5000), // should go as Transferable object
trailsArray = new Float32Array(7000); // should go as Transferable object
const state = 1, // integer
quality = 'High', // string
isTracking = true; // boolean
this.Worker.postMessage({
event: 'ShowTrails',
data: {
cornersArray: cornersArray,
trailsArray: trailsArray,
state: state,
quality: quality,
isTracking: isTracking
}
}, [cornersArray.buffer, trailsArray.buffer]);
So, onMessage() at main thread, this should call ShowTrails() and data should be passed as a parameter. But this is throwing error that objects passed are not detachable, failing in postMessage().
I am very noob in this, first time using web workers, please help me how to make this happen. I must be doing something wrong here while passing data.
Thanks!
You are not passing the transferrable buffer correctly. Try this:
this.Worker.postMessage({
event: 'ShowTrails',
data: {
cornersArray: cornersArray.buffer,
trailsArray: trailsArray.buffer,
state: state,
quality: quality,
isTracking: isTracking
}
}, [cornersArray.buffer, trailsArray.buffer]);

Retrieve javascript object in java with rhino

I want to get a javascript object from a javascript file, that only constists of this one big object.
For example:
var cars = {
mercedes: {
colour: 'silver',
drivemode: 'alldrive'
},
audi: {
size: '4x2x1,5m'
speed: '220 kmph'
}
};
For the javapart I am using rhino to get that object. For now I have coded:
Context context = context.enter();
context.setOptimizationLevel(9);
context.setLangaugeVersion(170);
context.getWrapFactory().setJavaPrimitiveWrap(false);
Scriptable defaultScope = context.initSafeStandardObjects();
So now i should have the possibility to be able to retrieve the javascript object. But how?
Script function = context.compileString("Any javascriptfunction as String", "javaScriptFile.js", 1, null);
function.exec(context, defaultScope);
But what would that javascript function look like to get that object as JSON (something like cars.stringify() )? And further more is that the right approach in using this function?
And finally how and where to i save the object in a java Object?
i have already checked this post and this post also this post but all dont fit my criteria or are missing out on a code example for clarification
Edit:
I have found another approach in calling/writing a javascript function in java as a string like:
Scriptable scriptObject;
private String functionAsString = "function getAsJson() {var objectString = { colour: \"silver\", drivemode: \"alldrive\" };return JSON.stringify(objectString);}";
Function fct = context.compileFunction(defaultScope, functionAsString, "AnyName", 1, null);
Object result = fct.call(context, defaultScope, scriptObject, null);
The only problem still standing is how do it get "objectString" to contain my cars.js? There somehow has to be a possibility to load that object in this variable
probably something like:
String functionAsString2 = "get cars() {return this.cars;}";
But how/and where do i specify the file in which to use this function?
I have found a way to retrieve the object by using the ScriptEngine from Rhino
private ScriptEngineManager manager = new ScriptEngineManager();
private ScriptEngine engine = manager.getEngineByName("JavaScript");
engine.eval(Files.newBufferReader("PATH TO THE JAVASCRIPT FILE", StandardCharsets.UTF_8));
Object result = engine.get("cars"); //Variable in the javascript File
if(result instanceof Map){
result = (Map<String,Object>) result;
}
so the object is retrieved and can be accessed and casted as a Map> and recursively accesed to in the end having a java Object of the JavaScript Object.
No need to use functions

How to initialize z object to use z.JSON.parse function in a code Zap?

I'm developing a Zapier zap. The source is Google calendar. I collect the event description. It is a json string. I want to turn it into an object to process it in a Zap code (in JavaScript). The doc recommends to use the z.JSON.parse() function. I do it but at run time the error z is not initialized is sent. How to JSON parse a string to make an object ?
I tried to add z = new Z(), but it didn't work.
var eventDescriptorString = {
codeEvt: 'ID-LGC-02/21/2019-testoon_mail',
appCible: 'SIB',
action: 'testoon_mail',
parametre: 'ID-LGC-02/21/2019-testoon_mail-presents'
}
var eventDescriptorObject = z.JSON.parse(inputData.eventDescriptorString);
console.log('action', eventDescriptorObject.action);
output = [{
'action': eventDescriptorObject.action
}];
I expect action to equal 'testoon_mail'
David here, from the Zapier Platform team.
The docs you found are probably for the app scripting environment. While similar, it's got access to a separate set of functions (and the z object itself). Code steps (which is what you're using here) are "plain" javascript environments.
If you change z.JSON.parse -> JSON.parse it should work as expected.

Need Help to implement Tincan Javascript API

I'm working on tincan JavaScript API. The issue my data format is total change and TinCan have specified a why to pass data along with call. Help me to adjust my data in TinCan Api format. Here is sample data one of my call.
var data = {
"groupId": "groupId",
"groupName": "gNameEncrypt",
"tutorNames": "tutorNames",
"actorNames": "actorNames",
"otherNames": "otherNames"
};
Current what i do i simply decode this data and send it like this.
var actionList = new TinCan(
{
recordStores: [{
endpoint: "http://example.com",
username: username,
password: password,
allowFail: false
}]
});
var action = new TinCan.Agent({
"name": "insert"
});
actionList.getStatements({
'params': {
'agent': action,
'verb': {
'id': $.base64.encode(data)
}
},
'callback': function (err, data) {
console.info(data.more);
var urlref = "http://<?php echo $_SERVER['SERVER_NAME'] . ":" . $_SERVER['SERVER_PORT'] . $uriParts[0] . "?" ?>t=" + data.more.TutorToken;
window.location.href = urlref;
}
});
crypt.finish();
});
There are really two parts here:
need to get data into an xAPI (formerly Tin Can) format, and
the code itself.
In depth,
I think you need to take another look at how xAPI is used in general. Data is stored a JSON "Statement" object that has 3 required properties and various other optional ones. These properties often contain complex objects that are very extensible. It is hard to tell from what you've shown what you are really trying to capture and what the best approach would be. I suggest reading some material about the xAPI statement format. http://experienceapi.com/statements-101/ is a good starting point, and to get at least some coverage of all the possibilities continue with http://experienceapi.com/statements/ .
The code you've listed is attempting to get already stored statements based on two parameters rather than trying to store a statement. The two parameters being "agent" and "verb". In this case We can't tell what the verb is supposed to be since we don't know what data contains, I suspect this isn't going to make sense as a verb which is intended to be the action of a statement. Having said that the fact that the "actor" has a value of action is questionable, as that really sounds more like what a "verb" should contain. Getting the statements right as part of #1 should make obvious how you would retrieve those statements. As far as storing those statements, if you're using the TinCan interface object you would need to use the sendStatement method of that object. But this interface is no longer recommended, the recommended practice is to construct a TinCan.LRS object and interact directly with it, in which case you'd be using the saveStatement method.
I would recommend looking at the "Basic Usage" section of the project home page here: http://rusticisoftware.github.io/TinCanJS/ for more specifics look at the API doc: http://rusticisoftware.github.io/TinCanJS/doc/api/latest/

Passing objects from NodeJS to client and then into KnockoutJS viewmodel

So thanks to SO I can pass an object from node to the client, but then getting it into a knockout view model is a bit awkward. These are the steps I have so far (I've included links to the relevant lines as they appear in my github project. Thought the context might help.):
Apply JSON.stringify and pass to the jade file
recipeJSON: JSON.stringify(recipe);
Wrap this in a function in a header script that just parses the JSON and returns the result
script
function getRecipeObject() {
var r = '!{recipeJSON}';
return JSON.parse(r);
}
Call this function and pass the result to a view model constructor
self.recipe = ko.observable(new Recipe(getRecipeObject()));
This works but is there a better way?
Question clarification (Edit): I feel step 2 shouldn't be necessary. Is there a way to directly pass the JSON from node to the Recipe() constructor, without the getRecipeObject() acting as an intermediate step? I tried passing recipeJSON in directly like so
self.recipe = ko.observable(JSON.parse('!{recipeJSON}'));
That doesn't work I think because its not a jade template and has no access to the variable.
According to the answer to this question rendering data into scripts is bad practice and I should instead make an XHR call on page load instead.
Edit
I just saw you linked a github repo! So you're already familiar with most of this...you even have an endpoint set up at /recipe/:id/view, so now I'm really confused...what isn't working out for you? Just the last step of deserialization using ko.utils.*?
Sorry about all the exposition -- I thought this was way more rudimentary than it actually was; I hope no offense taken there!
You really don't want to return a script to execute -- instead, treat this as a DTO: an object that just stores data (no behaviors). An example would be:
{
recipeID: 12,
reviewIDs: [42, 12, 55, 31],
rating: 4.2
recipeName: "A super tasty pie!"
}
This object (representation) is a projection -- a simplified version of the full data stored in the database.
The next step is to create an endpoint to access that data on the server. Let's assume you're using Express:
var app = express();
app.get('/recipes/:recipeID', function(req, res) {
var recipeID = req.params.recipeID;
// It would be cool if this existed, huh?
getRecipeAsync(recipeID, function(recipe) {
res.status(200).json(recipe);
});
});
If you send a GET request to your (hypothetical) application (let's say it's https://localhost:8080/recipes/12), you'll get json representing the (admittedly imaginary) recipe with ID 12.
You can accomplish getting the JSON with jQuery (or any other library that makes XHR nice and pretty)
var recipeID = 12;
$.ajax({
url: "/recipes/" + recipeID,
type: "GET"
}).then(function(recipe) {
console.log("Hey! I got the recipe: %O", recipe);
// Note: you might need to use ko.utils.fromJS(recipe) if the returned
// data is JSON that ISN'T deserialized into an object
var recipeObservable = ko.utils.fromJS(recipe);
});
That's about everything you need to know. Obviously, the devil's in the details, but that's basic idea; let me know if that helps!

Categories

Resources