Can we instantiate Java Objects in Javascript? - javascript

I know we can do this via DWR library to work with Java objects in Javascript.
But I would like to know if we can actually instantiate Java Objects in Javascript, using plain Javascript objects?
I searched on the internet and found this link and this link which speaks about Packages object in Javascript. I even read that this object is a part of JS since JS 1.1, is that true?
But when I actually used var myClass = new Packages.myPackage.myClass(); , it says, Packages is not defined, obviously I am missing out something here.
For my use case I have to instantiate a Java Pojo in JS.
Any clue folks on how to achieve this?

This feature depends on the JavaScript engine (i.e. the interpreter which runs the JavaScript). I haven't tried to do this in a browser but it might be possible when the Java plugin is enabled (which you shouldn't do for security reasons, at least not unconditionally).
The special object Packages is a feature of the Rhino engine, for example, which is a JavaScript interpreter that runs in a Java VM. The Packages has overloaded the accessor methods so when you write Packages.com.pany.Foo, it will internally look up the class and return something that wired the Java and the JavaScript worlds in a useful way.
You can find a tutorial here: https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Rhino/Scripting_Java

You can create a Java object and assign it to a variable in JavaScript with the help of the new
keyword. When you create an instance of a Java class, JavaScript automatically creates a JavaObject
object. For example, you can instantiate a Java String from JavaScript and assign it to a variable.
Then you can use the dot operator to access the object’s length()
var myString=new java.lang.String("Test String");
alert(myString.length()); //prints 11
You can follow this link for more information http://www.sitepoint.com/connect-java-to-javascript-with-liveconnect/

Related

How does RegExp access the string it operates on?

I was wondering how accessing to strings is done. The String object exposes methods such as char(Code)At for public access, but doesn't use them itself as part of its other methods, for example indexOf, but instead accesses the string through an internal structure. However, when using a RegExp, I assume it can't use String's private properties, so it has to call the public API as any other class. I wrote a short test to see that, but it doesn't seem that's what happens: https://jsfiddle.net/n5pxe94L/
String.prototype[Symbol.iterator]=function*()
{
console.log("My custom iterator!");
yield "t";
};
const originalFunc=String.prototype.charCodeAt;
String.prototype.charCodeAt=function(index)
{
console.log("Used!");
return originalFunc.call(this,index);
}
new RegExp("a").test("Lalalala");
When I run this test, it doesn't print anything, which indicates the functions I overrode aren't used! So how does RegExp access the string it analyzes?
It's all done in the JavaScript engine however that engine sees fit to do it. Each JavaScript implementation may take a different approach, but they all have direct, very low-level access to the string's content. For performance reasons I'd expect these access methods to be highly optimized and direct, not allowing for overrides like you've attempted here as that would slow things down in the 99.9999% of cases where no such override exists.
JavaScript is not stuck using functions exposed in the API, it may have many others that are hidden from developers and for internal use only.
If you're writing JavaScript code you're stuck using the features available to you. If you're writing a JavaScript runtime you can do whatever you want.
Originally I wanted to simply answer along the lines of RegExp accesses the underlying string structure in C but I got curious so started digging into the source code of various javascript engines.
All the javascript engines commonly in use (which are V8 for Chrome and node.js, Chakra for Edge and JavascriptCore for Safari) implement regexp processing in C++. I couldn't find the exact regexp processing functions in Chakra and JavascriptCore but I'm sure if I spend a few days reading the code I'll find it.
For Chakra you will see that most of the Regexp methods in C++ accept an argument called input which is defined as Char*. I'm not sure if input is the string or the regexp pattern but I'm guessing it's the string. But note that it is Char not char so it is probably a custom class in the project. You can start by looking at the Chakra RegexpRuntime implementation here: https://github.com/microsoft/ChakraCore/blob/master/lib/Parser/RegexRuntime.cpp
For JavascriptCore best I can tell is that they pass the C++ JSString object to the regexp function. This is as close as to actually using the actual String prototype in js but it probably has methods not available to js: https://github.com/WebKit/webkit/blob/master/Source/JavaScriptCore/runtime/RegExpObject.cpp
I got the furthest with V8 in the last 15 minutes. V8 passes a parameter called subject as the string to regexp functions. This is a String object which is then converted to String::FlatContent. Now what is FlatContent? It is an array-like object (see the Vector class) of either 8 bit or 16 bit values that you can access using the [] operator in C++. This allows them to loop through the string using regular array indexing. You can start by checking out regexp.cc: https://github.com/v8/v8/blob/master/src/regexp/regexp.cc
As you can see, none of them access strings via Javascript's String object as is. The closest that works kind of how you expected them to behave is Apple's JavascriptCore in Safari but even then it's not using merely APIs exposed via javascript.

How to launch shell command and generate JSON after Cplex OPL model runs?

I have an OPL model which solves an ILP.
Currently it writes the solution to a txt file.
I want to launch something on the completion of the model to nicely display the solution, so I need to run a shell command.
How can I launch an arbitrary shell command on completion of the OPL run?
Can I call a JavaScript file in the same project from the OPL run to process the data? (NOTE: I see I can do this with includeScript(...))
Could I launch an arbitrary shell command within a JavaScript file?
I want to format the results as JSON. However the usual "JSON" object is not available within the Javascript context. Can I create an object in Javascript then "stringify" it as JSON?
(NOTE on (4) - the documentation claims that the JavaScript implementation is compliant with ECMA-262:
https://www.ibm.com/support/knowledgecenter/SSSA5P_12.4.0/ilog.odms.ide.help/refjsopl/html/intro.html#1037020
However the ECMA-262 definition does include the JSON.Stringify function:
https://www.ecma-international.org/ecma-262/5.1/#sec-15.12
Why is it not then available in OPL?)
Just some personal experience, OPLScript is incomplete if you treat it as a JavaScript variant - very incomplete. Every time I try to use some old-style JavaScript code in OPLScript, I re-learn this lesson.
At the very basic level, many standard array and object methods are missing. For example, you can't even use the [] syntax to create a JavaScript array or access the property of an object. You can't list the keys of an object, etc. ...
It's probably better to use another language such as Java or Python for any complex data structure (without re-inventing all the common facilities).
This could be part of a new version if you re patient enough. But with 12.7.1 you could either use an external Java call from scripting or modify the example at CPLEX_Studio1271\opl\examples\opl_interfaces\java\oplrunsample in order to do what you need.
Yes through includes
Not in version 12.7.1
OPLscript is a subset of ECMA and not all functions are inside but you could manage with IloOplOutputFile See https://www.ibm.com/developerworks/community/forums/html/topic?id=a7738eaf-f053-4fa8-83dc-5886bc381244&ps=25

Call JS function from QML when JS code is not known at app build time (hat tip SpiderMonkey)

I am interested in the possibilities of calling JavaScript from C++ in QML. The problem that I see is that JavaScript functions need to be compiled with the application before I can invoke them. Rather, I would like to dynamically read the code for a JavaScript function from a file and have it interpreted on demand like I can do with Mozilla's SpiderMonkey.
Is this possible with Qt?
There are two ways to do that:
Use the "evil" eval() to return a function object from a string
Use Qt.createQmlObject() to create a QML object from a string that has the function as a member
Then you can pass the function to C++ as a QJSValue which you can call(QJSValueList &args).

"Some JS files act more like libraries - they [...] never manipulate QML component instances directly" - middle ground?

Quote from Defining JavaScript Resources In QML:
Some JavaScript files act more like libraries - they provide a set of helper functions that take input and compute output, but never manipulate QML component instances directly.
What if I want a JS file that both:
manipulates QML component instances (that are passed to it as arguments)
doesn't get a copy of its code and data stored for every QML component instance that imports it?
I could get the "no data stored on every instance" part by, well, not putting global variables in the JS file. But, for some strange reason, a copy of the "code" part seems to be stored for every instance as well. I don't get why this is but I want to know whether I can circumvent it, and at what cost.
I think that the line you quoted from the documentation is incorrect, or at least very poorly worded; you can still have a JS file with .pragma library in it and manipulate QML objects that are passed in as arguments to its functions. The sentence was probably referring to the previous section.
To share data across qml files, consider using a qml Singleton.
For data sharing purpose, I would not suggest using .pragma library (#Mitch) for following reasons.
.pragma library js provides limited functionality in qml object manipulation. While simple qml object manipulation (like property reading/writing) could be done with a .pragma library js, it does NOT allow creating/deleting qml objects (as you can in regular non-library js). It will suck when your application becomes dynamic.
.pragma library creating only one instance is merely an optimization in Qt implementation. It's never guaranteed that Qt creates exactly one instance, nor that your data would actually be shared.
Well, .pragma library is not designed to do data sharing work from the very beginning. Just, don't try to do it this way.

Parse javascript function name from js file using javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Return all of the functions that are defined in a Javascript file
OK so i have a JS file in which i have a number of JavaScript functions defined.Is there any way to parse out the name of all function in that particular JS file using JavaScript.Any guidance or link to achieve this will be appreciated
If you are not generating the js file dynamically, the easiest and safest option is to keep a hard-coded list of function names.
All other parsing methods are risky because
String parsing of the code is not safe, since you will have to cater
too many cases
There are options to get all global functions. But they are browser
dependent. like looping through all window objects for objects with typeof window[x] === 'function'
If it's just for development purposes then use an IDE. The IDE will depend on your environment. For example, you might you IntelliJ if your server side code is Java or Visual Studio's if you are a .NET shop.
If you really need to use javascript to dynamically go through the list of functions I suggest rethinking why you need to do it. If it turns out usefull you could namespace your functions and then just iterate over the namespace functions. See this answer for how to namespace https://stackoverflow.com/a/5947280/695461. Then iterate over the "public" functions.
Again, if it's just for development ease of use, use an IDE. They have whole teams of people writing parsers and syntax highlighters and structure diagrams for you.

Categories