Retrieve javascript object in java with rhino - javascript

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

Related

how to return js object to unity

I'm using the Google Draco decoder to decode mesh the following.
var dracoGeometry;
dracoGeometry = new decoderModule.Mesh();
decodingStatus = decoder.DecodeBufferToMesh(buffer, dracoGeometry);
when I check the type of the draceGeometrytry:
console.log( typeof dracoGeometry);
I get the
"object" type.
Now my problem is "how can I return this object to unity". What return type supported in C# to accept js object?
You can send strings or numbers, so what I would do is create a js object that has the data you need then call JSON.stringify on it to convert it to a string then send that over using unityInstance.SendMessage:
function sendToUnity(obj) {
unityInstance.SendMessage('MyGameObject', 'MyMethod', JSON.stringify(obj));
}
// in a script attached to a gameobject named "MyGameObject"
void MyMethod(string s)
{
Debug.Log(s);
// decode from json, do stuff with result etc
}
As for what you can do with that data while it is in JSON string form, you can use a variety of solutions to decode the JSON string once you have it in Unity. See Serialize and Deserialize Json and Json Array in Unity for more information.
So if your js looks like this:
function sendToUnity(obj) {
unityInstance.SendMessage('MyGameObject', 'MyMethod', JSON.stringify(obj));
}
sendToUnity({
playerId: "8484239823",
playerLoc: "Powai",
playerNick:"Random Nick"
});
You could do something like this in Unity:
[Serializable]
public class Player
{
public string playerId;
public string playerLoc;
public string playerNick;
}
...
void MyMethod(string s)
{
Player player = JsonUtility.FromJson<Player>(s);
Debug.Log(player.playerLoc);
}
Source: Programmer's answer
There are some methods available, but it doesn't seem possible at the moment to send a mesh from js to unity. If you are working with google draco, I recommend you to follow this fork

Variable used to store data from Excel file broken? JavaScript

I am currently developing a Keyword driven framework using JavaScript / TestComplete and have an Excel file which contains a step number, Description, Keyword, Locator and Data.
I am currently reading the data from the Excel file (.xlsx) and storing the data (in this case the locator) in a variable..
I am storing the String Browsers.Item(btlExplorer,"",Browsers.pX64 in a variable called locator. When I then attempt this: locator.Run(https://www.google.ie/?gws_rd=ssl#spf=1); I receive this error: JavaScript runtime error. TypeError. getLocator(...).Run is not a function.
This is my getLocator function:
function getLocator(x){
var driver;
var value;
driver = DDT.ExcelDriver("C:\\Users\\Username\\Desktop\\Automation Framework.xlsx", "Sheet1", false);
while (! driver.EOF() && driver.Value(0) != x){
DDT.CurrentDriver.Next();
}
value = driver.Value(3);
Log.Message(value);
DDT.CloseDriver(driver.Name);
return value;
}
And here is the function I am running:
function openGoogle()
{
//Launches the specified browser and opens the specified URL in it.
getLocator(1).Run("https://www.google.ie/?gws_rd=ssl#spf=1");
}
I am new to JavaScript, if you could give me any tips / advice on what is going wrong it would be greatly appreciated.
Since the value returned by the getLocator function is a string, you can work with it as a string and it does not have the Run method.
To get the actual object with the Run method, you need to evaluate the string in this way:
function openGoogle()
{
//Launches the specified browser and opens the specified URL in it.
let brwsr = eval(getLocator(1));
brwsr.Run("https://www.google.ie/?gws_rd=ssl#spf=1");
}

Source an object from a text file in javascript?

How do you source the data of multiple objects from a text file in JavaScript? I'm creating a program that will work with employee data and each employee will be treated as an object; I want the object data to come from an external source (i.e. a text file or an Excel spreadsheet), instead of having to explicitly write out the data for each employee within the code of the program. The multiple employee objects will be pushed into an array and then I'll interact with them in various ways. In the code below, I've had to explicitly write out employee data (see below). I want to source that data from some external source instead. Thanks!
function Employee (name, roomID, email)
{
this.name = name;
this.roomID = roomID;
this.email = email;
}
function EList()
{
this.employees = [];
this.firstindex = 0;
}
var employeeList = new EList();
var employee1 = new Employee("Aman Mundra", "D3-1", "aman.s.mundra#gmail.com"); //parameters inside parenthesis
var employee2 = new Employee("John Doe", "D4-1", "john.doe#gmail.com");
var employee3 = new Employee("Jane Doe", "D4-2", "jane.doe#gmail.com");
employeeList.employees.push(employee1, employee2, employee3)
What you are talking about is JSON. Make sure you are using JSON and the functions are already written for you. See json.com and json.org.
Particularly you would use JSON.parse to parse your text file, which would come in the form of a string after you have ajaxed your file in.
Here is the documentation for JSON.parse.
You might be looking for something along these lines if you can work with a CSV file: Javascript loading CSV file into an array
Why JavaScript? What are the other moving parts?

Accessing the parsed output buffer with the binary-parser Library

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.

How to pass a "new" object in JavaScript in Socket.IO

I'm trying to pass objects from one client to another client, e.g. pieces in a multiplayer board game. I have a working solution using JSON.parser and __proto__, but I'm curious to know if there is a better way.
Client sends:
var my_piece = new BoardPiece();
// ... my_piece is assigned data, like x-y coordinates
socket.send(JSON.stringify(my_piece));
Server forwards the piece to others:
client.broadcast(piece);
Another client receives:
var your_piece = JSON.parse(json);
your_piece.__proto__ = BoardPiece.prototype; // provide access to BoardPiece's functions
It's the last step where I use __proto__ that I'm concerned I may be shooting myself in the foot. Is there a better suggestion?
// clientone.js
var piece = new BoardPiece();
// ...
socket.send(JSON.stringify(piece));
// clienttwo.js
var piece = BoardPiece.Create(JSON.parse(json));
...
// BoardPiece.js
function BoardPiece() {
}
BoardPiece.prototype.toJSON = function() {
var data = {};
data.foo = this.foo;
...
return data;
};
BoardPiece.Create = function(data) {
var piece = new BoardPiece();
piece.foo = data.foo;
...
return piece;
}
Firstly using the toJSON method on your objects allows JSON.stringify to immediatly convert your object to JSON. This is part of the JSON API. The JSON API will call the toJSON method if it exists and converts that object to JSON.
This basically allows you to serialize your object as and how you want.
The second part is adding a factory method as a property of your constructor which takes your serialized JSON data and creates a new boardpiece. It will then inject your serialized data into that boardpiece object.
So your serializing only the data you care about and then passing that data through a factory method. This is the best way to send custom objects from one client to another.
There are a bunch of object syncing projects for node that might make life easier. For starters, check out:
NowJS
node-object-sync
Re-using Backbone.js Models on the server with Node.js and Socket.io to build real-time apps
Have tou tried jQuery's $.extend() method? http://api.jquery.com/jQuery.extend/

Categories

Resources