instantiate class in via nashorn - javascript

im thinking about replacing all my xml files and builders that i use for configuration with javascript / nashorn. lets say i have a java class that is builder style configuration object
class Configuration {
String name;
Configuration withName(String name) {
this.name = name;
return this;
}
int number;
Configuration withNumber(int number) {
this.number = number;
return this;
}
}
i would like to instantiate this class directly in javascript and have nashorn return to me an instance of it. i would like to code it in javascript like
{
name: 'qwerty',
number: 42
};
and then finally read the file, pass it into the script engine, and have it evaluate the object as an instance of Configuration.
is this possible with a json like syntax?
i wouldnt have a problem using the Packages.Configuration / Java.type("Configuration"); Java.extend(), but have yet to have any success with that.
or would i have to make / use a proper reader for the returned value?

No, Nashorn won't support this from what I've seen from available docs and JSR-223. You might need to use i.e. Jackson's ObjectMapper to deserialize JSON. And this should not be a problem, because Nashorn allows you to do almost anything in JavaScript: A JavaFX Script Application Examples.
You might also want to consider Groovy which has it's own map syntax which can be used inside constructors: Groovy Goodness: Using Lists and Maps As Constructors. Groovy is often used to define configuration.

You could cheat a little by attaching a converter function to your configuration type. This could be added easily on the JS side rather than trying to make it in Java.
var ConfigClass = Java.type('Configuration');
ConfigClass.fromJsObj = function(jsObj) {
var newConfig = new ConfigClass();
foreach(var prop in jsObj) {
newConfig[prop] = jsObj[prop];
}
return newConfig;
}
var myConfig = ConfigClass.fromJsObj( { name: "qwerty", number: 42 } );

Related

Setting a member in current class using Frida

I am hooking a certain function in Frida which uses the code:
this.carrier.getId()
However, at this point in time this.carrier has not been set yet, which causes the app to crash.
So I am thinking of manually setting this member in the current function in the class. So that carrier will exist by the time the code takes place.
The problem is that I encounter a problem by doing that.
So far this is what I got:
Java.perform(function () {
var SignUpActivity = Java.use('com.app.features.authentication.SignUpActivity');
SignUpActivity.validatePhoneNumber.implementation = function() {
var Carrier = Java.use("com.app.Carrier");
this.carrier = Carrier.$new();
console.log(this.carrier) // This prints "[object Object]"
console.log(this.carrier.setId) // This prints "undefined"
this.carrier.setId(123); // crashes
};
});
Code of carrier:
package com.app;
import android.os.Parcel;
import android.os.Parcelable;
public class Carrier implements Parcelable {
private int id;
private String name;
private String officeTerminalAddress;
public Carrier() {
}
protected Carrier(Parcel parcel) {
this.id = parcel.readInt();
this.name = parcel.readString();
this.officeTerminalAddress = parcel.readString();
}
public int getId() {
return this.id;
}
public void setId(int i) {
this.id = i;
}
}
Looks like the common problem in Frida that the way to access fields is different in Frida.
Frida uses JavaScript code so it can't handle non-JavaScript objects directly.
Therefore it wraps "native" objects (Android Java objects in this case) in JavaScript objects.
If you now call in Frida this.carrier you are getting the Frida JavaScript wrapper, not the Java Carrier instance you are aiming.
Of course the Frida JavaScript wrapper does not has the methods you try to call, therefore this.carrier.setId(123); will always fail.
Accessing a Java field with Frida
To access a field you always have to call .value on it to get the actual value:
So if you want this.carrier you have to use this.carrier.value.
Furthermore it is recommended to access a field by it's name with an additional underscore in front. Otherwise in obfuscated apps it may occur that there is a field and a method of the same name. In such a case Frida doesn't know if you want to access the field carrier or the method carrier.
Conclusion if you want to access a field of an Java class instance in an Android app using Frida the recommended way is
this._carrier.value
So for writing a field value you should call
this._carrier.value = ...
And the same way for reading.
Reference to Frida help pages
This is also described on the Frida pages, e.g. here:
Note we use this.m.value = 0 instead of this.m = 0 to set the field’s value. If there is also a method in this class called m, we need to use this._m.value = 0 to set the value of field m. In general, when looking at the properties of objects it will be necessary to use .value to access the values those fields refer to.
Complete simplified code
But in your case you can simplify everything by just using a local variable:
Java.perform(function () {
var SignUpActivity = Java.use('com.app.features.authentication.SignUpActivity');
SignUpActivity.validatePhoneNumber.implementation = function() {
const Carrier = Java.use("com.app.Carrier");
const c = Carrier.$new();
c.setId(123);
this._carrier.value = c;
};
});

How to expose JS patch function of Incremental DOM library in GWT app using #JsInterop

I would like to use Incremental DOM library in my GWT app.
https://google.github.io/incremental-dom/#about
As I am coming from the Java world, I struggle with concepts of JavaScript namespaces and modules. I was able to use Closure Compiler with closure version of Incremental DOM (has to be build from sources).
It starts with the following line:
goog.module('incrementaldom');
So if I was to use it in regular JS I would type:
var patch = goog.require('incrementaldom').patch;
And then the patch function would be available in the scope of my code. But how to make it accessible from #JsInterop annotated classes?
I tried something like:
public class IncrementalDom {
#JsMethod(namespace = "incrementaldom", name = "patch")
public static native void patch(Element element, Patcher patcher);
#JsFunction
#FunctionalInterface
public interface Patcher {
void apply();
}
}
But it doesn't work. I get this error in the runtime:
(TypeError) : Cannot read property 'patch' of undefined
So I guess I have to somehow expose the incrementaldom module or at least only the patch method. But I don't know how.
After fighting for the whole day I found the solution. In the goog.module: an ES6 module like alternative to goog.provide document I found the missing information about the role of goog.scope function - required modules are visible only within the scoped call.
I created another Closure JS file named incrementaldom.js:
goog.provide('app.incrementaldom'); // assures creation of namespace
goog.require("incrementaldom");
goog.scope(function() {
var module = goog.module.get("incrementaldom");
var ns = app.incrementaldom;
app.incrementaldom.patch = module.patch;
});
goog.exportSymbol("app.incrementaldom", app.incrementaldom);
And now I can call it from Java code like this:
public class IncrementalDom {
#JsMethod(namespace = "app.incrementaldom", name = "patch")
public static native void patch(Element element, Patcher patcher);
#JsFunction
#FunctionalInterface
public interface Patcher {
void apply();
}
}
Still I have to define every object exported in original module separately in the Closure JS file. Fortunately I only need patch method. I hope one day I will find less cumbersome way for #JsInterop with goog.module :(

How to get source code of a QML method in C++?

I'm writing a serialization of objects to QML, and want to be able to get source code of functions defined in QML object. Suppose I have the following example in QML (test.qml):
import QtQml 2.2
QtObject {
function foo() {
return 42;
}
}
I created a QObject: obj from that.
Is there any way (can be hacky) to get the source code of obj's method foo without parsing the QML file obj was created from?
It's okay to use QQmlComponent obj was created from or any other Qt classes, as long as I don't have to parse it myself. Alternatively, how to get the function's source code from the test.qml file without writing my own parser? I don't want to assume anything special about test.qml (e.g. it can be different than the one above and it doesn't have to be simple enough to use a regexp or other not full-fledged QML parser).
Assuming this works like JavaScript, I tried something like:
QQmlExpression expr(engine.rootContext(), obj, "foo.toString()");
QVariant sourceCode = expr.evaluate();
However, it doesn't work.
Edit: According to http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.4.2 the toString method of a function object prototype is implementation-defined. In case of QML I get the result:
QVariant(QString, "function() { [code] }")
Since there doesn't seem to be a way to get the code by JS or C++, I'm not limiting myself to public Qt API anymore.
I think it is impossible to get a source code of a function from an already created QML object. There doesn't seem to be any C++ interface for it and JavaScript doesn't return it using toSource method either.
However, it can be retrieved using QML parser. The bad news are that QML parser is a part of Qt private API, so it might not work when using different Qt library builds.
The code to parse QML using Qt 5.3.0 private API is more or less:
.pro file:
QT += qml qml-private
cpp file:
using namespace QQmlJS::AST;
class LVisitor: public QQmlJS::AST::Visitor {
public:
LVisitor(QString code): _code(code) {}
virtual bool visit(FunctionBody *fb) {
qDebug() << "Visiting FunctionBody" <<
printable(fb->firstSourceLocation(), fb->lastSourceLocation());
return true;
}
private:
QStringRef printable(const SourceLocation &start, const SourceLocation &end) {
return QStringRef(&_code, start.offset, end.offset + end.length - start.offset);
}
private:
QString _code;
};
void testQmlParser() {
QFile file(":/test.qml");
file.open(QFile::ReadOnly);
QString code = file.readAll();
file.close();
QQmlJS::Engine engine;
QQmlJS::Lexer lexer(&engine);
lexer.setCode(code, 1, true);
QQmlJS::Parser parser(&engine);
if (!parser.parse() || !parser.diagnosticMessages().isEmpty()) {
foreach (const QQmlJS::DiagnosticMessage &m, parser.diagnosticMessages()) {
qDebug() << "Parse" << (m.isWarning() ? "warning" : "error") << m.message;
}
}
UiProgram *ast = parser.ast();
LVisitor visitor(code);
ast->accept(&visitor);
}
To get more precise information about the object where the function is defined or just get more information from the AST, implement more methods of QQmlJS::AST::Visitor.
I also didn't find any way to do so. but I found a way around to do it.
reffer this firts
Now, As you knwo we can access an QML object in C++. will do following to run the function in QML.
Item {
width: 100; height: 100
Rectangle {
property bool call:true
objectName: "rect"
onCallChanged()
{
myFunction();
}
function myFunction()
{
//your code
}
}
}
and in C++ you have to do following:
QObject *rect = object->findChild<QObject*>("rect");
if (rect)
rect->setProperty("call", !(rect->property("call").toBool()));
here we are using change event of property 'call' to call the myFunction()

What's the difference between these namespacing methods?

I'm new to JavaScript and am trying to understand how to use namespaces to avoid naming conflicts. So far, the two most popular methods I've found for creating namespaces are these:
Method 1:
var MYAPPLICATION = {
calculateVat: function (base) {
return base * 1.21;
},
product: function (price) {
this.price = price;
this.getPrice = function(){
return this.price;
};
},
doCalculations: function () {
var p = new MYAPPLICATION.product(100);
alert(this.calculateVat(p.getPrice()));
}
}
Method 2:
var DED = (function() {
var private_var;
function private_method()
{
// do stuff here
}
return {
method_1 : function()
{
// do stuff here
},
method_2 : function()
{
// do stuff here
}
};
})();
Is the difference that the second method allows you to have private methods and variables, since only what is inside of the object being returned will be globally accessible? Which of these methods is best (or is there a better way)?
If you write an API for other people, I think method two is better. Example:jQuery.
In a web page, I prefer method one. Example:stackoverflow
In method two, you can not read and write functions and variables that is private, so if there is a bug, you can not read something by developer-tools for debug.
Second method is called 'module' pattern. Makes it comfortable for developers to use your code. Self-invoking function creates scope, so you only expose methods that you want to make public by returning object that contains references to those methods (public API). Those methods can have a lot of private helper functions and variables that you keep private for your own use. Most of the libraries are written this way. It's generally good to structure your library like that.
Here's a link to the website that explains it well : http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html
First method is just the way to put all the related functions together. You can make those for personal use in your module. Example:
Calc.add(5,5), Calc.subtract(3,2), Calc.multiply(3,3);
add, subtract, multiply share same namespace because they are related.

JavaScript Module Pattern - Protected members?

Hullo! This is my first question!
I am experimenting with the module pattern promoted by Doug Crockford and others. Mostly very happy with it so far, but I am a little unsure about the best way of handling a certain inheritance pattern.
I have it boiled down to a bare bones case using cat and mammal, although my actual intention is to make objects for a tile based game in canvas.
But here is my bare bones 'animals' case using a browser alert:
var ZOO = ZOO || {};
//
ZOO.mammal = function () {
"use strict";
var voice = "squeak.mp3", // default mammal sound
utter = function () {
window.alert(this.voice);
};
//
// public interface
return {
utter: utter,
voice: voice
};
};
//
ZOO.cat = function () {
"use strict";
// hook up ancestor
var thisCat = ZOO.mammal();
thisCat.voice = "miaw.mp3";
return thisCat;
};
//
var felix = ZOO.cat();
felix.utter();
What bothers me about this approach is that I have had to make voice a public property so that cat can modify it.
What I really want is something like 'protected' visibility (from Java, ActionScript etc.), so that cat can modify voice without anyone with access to felix being able to modify it.
Is there a solution?
You can simulate protected visibility (visible to yourself, and child objects) by passing a blank object to your base "class" to serve as the repository for your protected properties. This will allow you to share properties through your inheritance chain, without making them public.
var ZOO = ZOO || {};
ZOO.mammal = function (protectedInfo) {
"use strict";
protectedInfo = protectedInfo || {};
protectedInfo.voice = "squeak.mp3";
// public interface
return {
utter: function () {
alert(protectedInfo.voice);
}
};
};
ZOO.cat = function () {
"use strict";
var protectedInfo = {};
// hook up ancestor
var thisCat = ZOO.mammal(protectedInfo);
protectedInfo.voice = "miaw.mp3";
return thisCat;
};
Here's a live demo
Sidesteping non-answer:
There are some ways to kind of get protected properties in Javascript but they aren't necessarily very idiomatic. If I were you I would first strongly consider either
Using the convention of public properties prefaced with an underscore (ex.: _voice) to denote privacy. Its very simple and is something of a standard among dynamic languages.
Seek an alternate solution without inheritance. Inheritance often complicates and couples stuff to much, hence the old "prefer composition over inheritance" mantra. Javascript has many features, like duck typing and higher order functions, that often let you avoid using inheritance in situations where you would normaly need it in Java
There is a workaround to simulate protected members, where you make public those members for a while, and then you privatise them again. I'm not a big fan of this, but it's a "solution".
I'm just quoting from this SitePoint article:
Adding Protected Members
Splitting a script into multiple modules is a common and convenient
practice. It makes a large codebase much easier to manage, and allows
for bandwidth savings to be made when modules aren’t always required.
But what if we want to share data between different modules? If we
make that data public then we’ll lose the benefits of privacy, but if
we make it private it will only be available to one module. What we
really need are shared private members, and these are known as
protected.
JavaScript doesn’t have protected members as such, but we can
effectively create them by making data temporarily public. To achieve
this, let me first introduce you to two key functions — extend and
privatise — which we’ll define as part of a utility-functions object:
var utils = {
extend : function(root, props) {
for(var key in props) {
if(props.hasOwnProperty(key)) {
root[key] = props[key];
}
} return root;
},
privatise : function(root, prop) {
var data = root[prop];
try { delete root[prop]; } catch(ex) { root[prop] = null; }
return data;
}
};
The extend function simply adds new properties to an object, while the
privatise function copies a property and then deletes the original. We
can use extend in one module to create a public reference to a private
variable, and then use privatise in another module to copy it back to
a private variable and delete the public reference.
So here’s an example of the first module which has two protected
members (including the utils object itself), and one public member. To
keep the code example short, the utility functions are just empty
shells, but they would be identical to the functions I showed you a
moment ago:
var MyModule = (function() {
var myProtectedData = 909;
var utils = {
extend : function(root, props) { },
privatise : function(root, prop) { }
};
this.myPublicData = 42;
return utils.extend(this, { myProtectedData : myProtectedData, utils : utils });
})();
You can see how we’re using a variant of the revealing module pattern,
to return not just the public members, but the protected members as
well. So at this point we have three public members:
MyModule.myProtectedData, MyModule.utils and MyModule.myPublicData.
Now here’s an example of the last module which uses the privatise
function to copy the specified public members back to private
variables, and then delete their public references:
var MyModule = (function() {
var myProtectedData = this.utils.privatise(this, 'myProtectedData');
var utils = this.utils.privatise(this, 'utils');
return this;
}).apply(MyModule);
And once that’s done the protected members are locked inside their
objects, privately available to both the modules, but no longer
available from outside them.
Note that the privatise function relies on having separate arguments
for the object and the property-key, because objects in JavaScript are
passed by reference. So root is a reference to MyModule, and when we
delete a property from it that’s specified by key, we’re deleting that
property from the referenced object.
But if it was like this:
privatise : function(root) {
var data = root;
try { delete root; } catch(ex) { root = null; } return data;
}
And called like this:
var myProtectedData = this.utils.privatise(this.myProtectedData);
Then the public members would not be deleted — the function would
simply delete the reference, not the property it refers to.
The try ... catch construct is also necessary for older IE versions,
in which delete is not supported. In that case we nullify the public
property rather than deleting it, which is obviously not the same, but
has an equivalent end result of negating the member’s public
reference.

Categories