switching bw Javascript and GWT function - javascript

I am working on a project using GWT and d3. i have used d3 in javascript files. Let me explain a bit more . i have a class name AstForm in GWT. in this class i have a function which i have called in my javascript file using following code.it the code works fine for me.
public native void PrepareFunctionsForJS() /*-{
$wnd.ExtractOFFNetWork = this.#org.valcri.asstsrchui.client.AstForm::ExtractOFFNetWork(*);
}-*/;
public void ExtractOFFNetWork(JsArrayMixed args)
{
Window.alert("thisCurrent row and Column is " +
args.getString(0) + " " + args.getString(1)+"OffenderNetwork?");
}
void testfunction ()
{
Window.alert("testfunction)
}
in java script i have used the following code
window.ExtractOFFNetWork(["GWT","JS"]);
my code works fine. i can call the ExtractOFFNetWork in javascript file. however the problem is in the ExtractOFFNetWork function when i call testfunction which is also the member function of the ASTFORM class the programe error saying testfunction is not a function. however when i changed testfunction as static than i can access this function within ExtractOFFNetWork. alternatievly i can also use the testfunction inside ExtractOFFNetWork by creating a separate object of ASTForm as
AstForm my =new AstForm();
my.testfunction();
however i do not want to use either static or separate ASTform object to access member function of ASTForm. i also used this.testfunction() within ExtractOFFNetWork but it also does not work. i would appreciate if any body can help to solve my problem i have spend full day without any success :)

already tried this when calling your PrepareFunctionsForJS(btw by java naming conventions method names start with lowercase letter..)
//assuming that you are calling the prepare function from inside the AstForm
public class AstForm() {
//...
PrepareFunctionsForJS(this);
}
public native void PrepareFunctionsForJS(AstForm instance) /*-{
$wnd.ExtractOFFNetWork = instance.#org.valcri.asstsrchui.client.AstForm::ExtractOFFNetWork(*);
}-*/;

Related

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 :(

Javascript bridge / upcall to JavaFX (via JSObject.setMember() method) breaks when distributing

The Problem
I spent several hours trying to determine why my distributed code fails and yet my source code when debugging with the IDE (NetBeans) works without issue. I have found a solution and am posting to help others that might have similar issues.
BTW: I'm a self-taught programmer and might be missing a few fundamental concepts -- feel free to educate me.
Background Information
Using a WebView control within JavaFX application I load a webpage from an html file. I want to use JavaScript to handle the HTML side of things but I also need to freely pass information between Java and JavaScript (both directions). Works great to use the WebEngine.executeScript() method for Java initiated transfers and to use JSObject.setMember() in Java to set up a way for JavaScript to initiate information transfer to Java.
Setting up the link (this way breaks later):
/*Simple example class that gives method for
JavaScript to send text to Java debugger console*/
public static class JavaLink {
public void showMsg(String msg) {
System.out.println(msg);
}
}
...
/*This can be added in the initialize() method of
the FXML controller with a reference to the WebEngine*/
public void initialize(URL url, ResourceBundle rb) {
webE = webView.getEngine();
//Retrieve a reference to the JavaScript window object
JSObject jsObj = (JSObject)webE.executeScript("window");
jsObj.setMember("javaLink", new JavaLink());
/*Now in our JavaScript code we can type javaLink.showMsg("Hello!");
which will send 'Hello!' to the debugger console*/
}
The code above will work great until distributing it and attempting to run the JAR file. After hours of searching and testing different tweaks I finally narrowed the problem down to the JavaLink object itself (I eventually learned that you can use try-catch blocks in JavaScript which enabled me to catch the error: "TypeError: showMsg is not a function...").
The Solution
I found that declaring a global variable to hold an instance of the JavaLink class and passing that as a parameter into the setMember() method fixes it so that the app now runs both in the IDE as well as a standalone JAR:
JavaLink jl;
...
jl = new JavaLink();
//replace anonymous instantiation of JavaLink with global variable
jsObj.setMember("javaLink", jl);
Why!?
I'm guessing this has to do with garbage collection and that the JVM does not keep a reference to JavaLink unless you force it to by declaring a global variable. Any other ideas?
Just to demo that the hypothesis postulated in #DatuPuti's answer appears to be correct. Here's a quick test. Pressing the HTML button increments the counter in the HTML page, and also outputs to the system console. After forcing garbage collection by pressing the "GC" button, the updates to the system console stop:
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import netscape.javascript.JSObject;
public class WebViewCallbackGCTest extends Application {
private final String HTML =
"<html>"
+ " <head>"
+ " <script>"
+ " var count = 0 ;"
+ " function doCallback() {"
+ " count++ ;"
+ " javaLink.showMsg('Hello world '+count);"
+ " document.getElementById('test').innerHTML='test '+count;"
+ " }"
+ " </script>"
+ " </head>"
+ " <body>"
+ " <div>"
+ " <button onclick='doCallback()'>Call Java</button>"
+ " </div>"
+ " <div id='test'></div>"
+ " </body>"
+ "</html>" ;
#Override
public void start(Stage primaryStage) {
WebView webView = new WebView();
webView.getEngine().loadContent(HTML);
JSObject js = (JSObject) webView.getEngine().executeScript("window");
js.setMember("javaLink", new JavaLink());
Button gc = new Button("GC");
gc.setOnAction(e -> System.gc());
BorderPane root = new BorderPane(webView);
BorderPane.setAlignment(gc, Pos.CENTER);
BorderPane.setMargin(gc, new Insets(5));
root.setBottom(gc);
primaryStage.setScene(new Scene(root, 400, 400));
primaryStage.show();
}
public static class JavaLink {
public void showMsg(String msg) {
System.out.println(msg);
}
}
public static void main(String[] args) {
launch(args);
}
}
Of course, as stated in the other answer, if you declare an instance variable
private JavaLink jl = new JavaLink();
and replace
js.setMember("javaLink", new JavaLink());
with
js.setMember("javaLink", jl);
the problem is fixed, and the updates continue to appear in the console after calling System.gc();.
The solution from #DatuPuti works fine but partially. In my case, I've got multiple nested classes in the JavaLink class. Before doing what #DatuPuti exposes all the nested classes link broke and after applying the exposed solution, only the class being called is the one that keeps the link, all the rest are still breaking. This is the model of my JavaLink class:
public class JavaLink{
public NestedClass1 ClassName1;
public NestedClass2 ClassName2;
//Constructor
public JavaLink(){
ClassName1 = new NestedClass1();
ClassName2 = new NestedClass2();
}
//Nested classes being called from Javascript
public class NestedClass1(){}
public class NestedClass2(){}
}
The link would be created like this:
JavaLink javaLink;
...
javaLink = new JavaLink();
jsObject.setMember("JavaLink", javaLink);
Then, from Javascript I call classes methods like this:
JavaLink.ClassName1.method();
JavaLink.ClassName2.method();
And here comes the probem: When the crash occurs calling ClassName1 methods, ClassName2 unlinks and it's not available anymore using Javascript. The same happens if I the crash occurs while calling ClassName2 methods.
The solution that works for me (in addition to the exposed solution):
Besides declaring JavaLink in the higher scope possible, declaring all the nested classes will make them keep the link. For example (keeping the same reference from the example
class model):
JavaLink javaLink;
JavaLink.NestedClass1 nestedClass1;
JavaLink.NestedClass2 nestedClass2;
javaLink = new JavaLink();
nestedClass1 = javaLink.new NestedClass1();
nestedClass2 = javaLink.new NestedClass2();
//Creating an Object array to store classes instances
Object[] javaLinkClasses = new Object[2];
javaLinkClasses[0] = nestedClass1;
javaLinkClasses[1] = nestedClass2;
jsObject.setMember("JavaLink", javaLinkClasses); //Setting member as an array
And then finally, in order to call methods from nested classes in Javascript, object reallocation is needed, just like this (Javascript):
JavaLink.NestedClass1 = JavaLink[0];
JavaLink.NestedClass2 = JavaLink[1];
//Now we are able to call again methods from nested classes without them unlinking
JavaLink.NestedClass1.method();
I hope this helps people facing the same issue. I'm using Java JDK 1.8 with IntelliJIDEA.

Is it possible to get the class or class name from inside a function?

I'm trying to write debugging tools and I would like to be able to get the class name of the caller. Basically, caller ID.
So if I have a method like so, I want to get the class name:
public function myExternalToTheClassFunction():void {
var objectFunction:String = argument.caller; // is functionInsideOfMyClass
var objectFunctionClass:Object = argument.caller.this;
trace(object); // [Class MyClass]
}
public class MyClass {
public function functionInsideOfMyClass {
myExternalToTheClassFunction();
}
}
Is there anything like this in JavaScript or ActionScript3? FYI AS3 is based on and in most cases interchangeable with JS.
For debugging purposes you can create an error then inspect the stack trace:
var e:Error = new Error();
trace(e.getStackTrace());
Gives you:
Error
at com.xyz::OrderEntry/retrieveData()[/src/com/xyz/OrderEntry.as:995]
at com.xyz::OrderEntry/init()[/src/com/xyz/OrderEntry.as:200]
at com.xyz::OrderEntry()[/src/com/xyz/OrderEntry.as:148]
You can parse out the "caller" method from there.
Note that in some non-debug cases getStackTrace() may return null.
Taken from the documentation:
Unlike previous versions of ActionScript, ActionScript 3.0 has no
arguments.caller property. To get a reference to the function that
called the current function, you must pass a reference to that
function as an argument. An example of this technique can be found in
the example for arguments.callee.
ActionScript 3.0 includes a new ...(rest) keyword that is recommended
instead of the arguments class.
Try to pass the Class name as argument:
Class Code:
package{
import flash.utils.getQualifiedClassName;
public class MyClass {
public function functionInsideOfMyClass {
myExternalToTheClassFunction( getQualifiedClassName(this) );
}
}
}
External Code:
public function myExternalToTheClassFunction(classname:String):void {
trace(classname); // MyClass
}

C# class attributes not accessible in Javascript

I want to make a class of mine accessible in JavaScript via a C# WebView-Control.
Therefore I am using the WebView.AddWebAllowedObject method. However if I assign an attribute, it works fine, but if I assign the whole class to get all attributes in js, all of the attributes(and methods btw) are "undefined". I tried everything I found in the www. See the attached code:
//The class I want to make accessible
[AllowForWeb, ComVisible(true)]
[MarshalingBehavior(MarshalingType.Agile)]
public class DeviceInformation
{
public string IPAdress { get; private set; }
public DeviceInformation()
{
IPAdress = GetIPAdress();
}
public string GetDeviceUUID()
{
EasClientDeviceInformation deviceinfo = new EasClientDeviceInformation();
return deviceinfo.Id.ToString();
}
public string GetIPAdress()
{
List<string> ipAddresses = new List<string>();
var hostnames = NetworkInformation.GetHostNames();
foreach (var hn in hostnames)
{
if (hn?.IPInformation != null && (hn.IPInformation.NetworkAdapter.IanaInterfaceType == 71 ||
hn.IPInformation.NetworkAdapter.IanaInterfaceType == 6))
{
string ipadress = hn.DisplayName;
return ipadress;
}
}
return string.Empty;
}
}
Here the objects are initialized.
DeviceInformation devinf = new DeviceInformation();
private void View_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
{
if (args.Uri.Host == "")
{
//win_ipadress has an ipadress as value
view.AddWebAllowedObject("win_ipadress", devinf.IPAdress);
//deviceInformation is initialized as well but I have no access to its attributes
view.AddWebAllowedObject("deviceInformation", devinf);
}
}
That's the way i call it in js:
else if ($.os.ie) {
myIpAdr = window.win_ipadress;
//Throws an exception because GetIPAdress() is "undefined"
myIpAdr = window.deviceInformation.GetIPAdress();
}
I am using this in a Windows Universal App. The Javascript and in the WebView displayed HTML-Code is already in use for Android an iOS.
I believe you need to define the method name starting with a lower case character.
For example: change GetIPAddress to getIPAddress.
I tested it on my side and found if I use the upper case name 'GetIPAddress', it won't work. But if I use getIPAddress, it works.
And after I read kangax's explanation in this thread, I think it makes sense.
[Update]
Since it still doesn't work after you make the change on method name, I think the issue should be related to how you expose the windows runtime object. I guess you simply defined the DeviceInformation class and tried to use it in the same project.
First, we need to create a separate windows universal windows runtime component project.
The c# class DeviceInformation should be put into this project. Keep the same code.
Then, in your universal app project, add reference to the windows runtime component and keep rest code to consume the windows runtime object.
[Update 2]
Just noticed an interesting behavior in VS. No matter if the Method name we defined in C# is starting with uppercase or lowercase, the visual studio intellisense shows the lowercase, so the method name will be automatically converted when we try to use it in js.

GWT + SmartGWT + Javascript: external script integration

I am building a web application using GWT and SMartGWT and I need to integrate an external script for a Photo Gallery: http://slideshow.triptracker.net/.
My current attempt is:
ScriptInjector.fromUrl("http://slideshow.triptracker.net/slide.js").setCallback(
new Callback<Void, Exception>() {
public void onFailure(Exception reason) {
Window.alert("Script load failed.");
}
public void onSuccess(Void result) {
Window.alert("Script load success.");
}
}).inject();
Afterwards, I call this method:
Code:
native static void example(String p) /*-{
$wnd.viewer = new $wnd.PhotoViewer();
$wnd.viewer.add(p)
$wnd.viewer.show(0);
}-*/;
This does not give any error, but the photogallery appears BEHIND my Entry Point Layout, so it's not possible to use it.
So, I am trying to find a workaround and I would like to refer to the main layout from Javasript, to run the script on that. Is this possible? I've tried with
foo.getElement().getId();
but it returns me something like
isc_VLayout_0_wrapper
However, Javascript doesn't like it.
Then I tried
foo.getDOM.getId();
isc_1
But the result doesn't change.
Can someone help me fix this issue?
Thank You.
I think here are two things, that are possibly wrong:
You have an onSuccess() callback you can call the jsni call from within.
//1
ScriptInjector.fromUrl("http://slideshow.triptracker.net/slide.js").setCallback(
new Callback<Void, Exception>() {
public void onFailure(Exception reason) {
//3a
}
public void onSuccess(Void result) {
example("works");
//3b
}
}).inject();
//2
example("not loaded");
You may also try to call .setWindow(ScriptInjector.TOP_WINDOW) before calling .inject()

Categories