Call Java from Javascript with GWT JNSI - java

How do I call a Java method from Javascript? I tried the following
http://www.gwtproject.org/doc/latest/DevGuideCodingBasicsJSNI.html#calling
But it is not working. I can't put the JS into Java file because the library uses a callback. In my App.html file:
function pickerCallback(data) {
var doc = data[google.picker.Response.DOCUMENTS][0];
var name= doc[google.picker.Document.NAME];
var fileId = data.docs[0].id;
// set the path text field
//[instance-expr.]#class-name::field-name
//[instance-expr.]#class-name::method-name(param-signature)(arguments)
// Call static method
//#com.onix.sdm.client.SDM_Mailer::setSelectedFolder(Ljava/lang/String;Ljava/lang/String;)(name, fileId);
$entry(#com.onix.sdm.client.SDM_Mailer::setSelectedFolder(name, fileId));
}
In SDM_Mailer.java:
private static void setSelectedFolder(String folder, String id) {
SDM_Mailer myThis = SDM_Mailer.getInstance();
myThis.textFolder.setText(folder);
myThis.folderId = id;
}
When I load the app, in gives this error in the browser console:
Uncaught SyntaxError: Unexpected token ILLEGAL
On this line:
$entry(#com.onix.sdm.client.SDM_Mailer::setSelectedFolder(name, fileId));
I also tried the line immediately before that (commented for now), which also gave the same error.

I can't put the JS into Java file because the library uses a callback
That's by design - the purpose of this syntax is not to expose methods where they can be called by external JS, but instead to let you call it from within JSNI. This is because the JSNI can be modified to actually call the java method.
If you want to call Java/GWT methods from in plain js, you must expose them for this. You linked http://www.gwtproject.org/doc/latest/DevGuideCodingBasicsJSNI.html#calling, but didn't actually use the important part:
public static native void exportStaticMethod() /*-{
$wnd.computeLoanInterest =
$entry(#mypackage.MyUtilityClass::computeLoanInterest(IFI));
}-*/;
This is the important piece - you must expose the function to where the outside JS can call it, but you must do this exposing from within a JSNI func. Note that we are not calling the function here, just referring to it.

I think you missed the Type Parameter:
$entry(#com.onix.sdm.SDM_Mailer::setSelectedFolder(Ljava/lang/String;Ljava/lang/String;)(name, fileId));
JSNI is well explained at DevGuideCodingBasicsJSNI

Related

JNLP File App Automation using marathon java driver

I am automating a forms application using java driver marathon. I can launch the application from the automation code and navigate to following the blocked screen.
There is a table where I want to read the data, I have the decompiled java code with me.
This method returns the focused row successfully.
driver.findElement(By.name("ListView229")).getAttribute("getFocusedRow");
getFocusedRow is a java method I can call it like above.
Now I want to call the =>
public final String getCellData(int paramInt1, int paramInt2)
driver.findElement(By.name("ListView229")).getAttribute("getCellData(1,0)";
I used the above code but returns null, I can call the java methods which does not have parameters.
How I can call the java methods which have parameters?
You need to use driver.execute_script to call the getters that require parameters. The following should work:
WebElement e = driver.findElement(By.name("ListView229"));
String s = driver.executeScript("return $1.getCellData(1, 0);", e);

JavaScript scope resolve time

I'm writing an app that loads javascript dynamically using rhino(or a browser); I got 2 files:
// in a file called fooDefinition.js
var definition = {
foo: function(data){return bar(data)},
loadFile: "barLib.js"
}
now, bar() is defined like this:
// in a file called barLib.js
function bar(data){
return data + " -> bar!";
}
This is what I want to do:
load fooDefinition.js into the environment
read the value of loadFile (in this case: "barLib.js") and load the file (NOTE: load the file through external mechanism, not through javascript itself!)
call foo
external mechanism & example usage (Java pseudo code):
// assume engine is a statefull engine (rhino for example)
String str = /*content of fooDefinition.js*/;
engine.eval(str);
String fileToLoad = engine.eval("definition.loadFile");
engine.load(IOUtils.readFileToString(new File(fileToLoad)));
String result = engine.eval("definition.foo('myData')");
I've tried this in Google Chrome's JS console and no error was thrown
I wonder is this the correct way of accomplish such task?
TL;DR:
Are the attributes of an object loaded and checked when the object is defined?
If your engine is statefull that is it keeps track of defined variables, yes your approach is corrent and will work as expected
But if it is not, your way will fail, because when you call the following
String fileToLoad = engine.eval("definition.loadFile");
your engine haven't any info about definition object and as a result it return an exception (in JavaScript).
It seems your engine is statefull and all things will work correctly

Call Java From Javascript (Birt)

I want to call Java object from within javascript in my rptdesign file (which is under a report project), after i put the jar of my class in /Web-Inf/lib directory and the .class in Web-Inf/classes i tried something like this in the open event of the data set:
gsh = new Packages.de.vogella.birt.stocks.daomock.StockDaoMock();
stock = gsh.getStockValues();
de.vogella.birt.stocks.daomock is the name of a package located in a Java Project (ClassPackage) under /src
StockDaoMock is the name of the class.
getStockValues() is the method.
But I get this error:
cannot evaluate the script. data set script method fetch returned null.expected a boolean value.
What is wrong?
I tried to replace all the code in the fetch method by
"system.out.println("essai");
return true;"
and still have this error
"Data Set script method "Fetch" returned null; expected a Boolean value."
Enable logging to see the stack trace. See the wiki.
Make sure the exception is logged (the example just logs the message) :-)
"Quick and Dirty Logging" might also help.
You might also have a classloader issue. See this blog post for classloader options and how to debug bundle discovery by OSGi when using BIRT.
[EDIT] The error message means that you forgot return true; or return false; at the end of the fetch method.
The java runs on the server, and javascripts runs in the browser, so it is obvious you can't call Java from javascript directly.
There is a library called DWR (Direct Web Remoting). It can expose Java method to Javascript methods. When you call the Javascript it makes a AJAX request, then DWRServlet handles it, executes your desired Java method, and returns the method result to the browser.

How to run vbscript function from java?

From java code i am able to run the vbscript by using this code
Runtime.getRuntime().exec("wscript C:\\ppt\\test1.vbs ");
But want to know how to call the method of vbscript from java..for example in test1.vbs
Set objPPT = CreateObject("PowerPoint.Application")
objPPT.Visible = True
Set objPresentation = objPPT.Presentations.Open("C:\ppt\Labo.ppt")
Set objSlideShow = objPresentation.SlideShowSettings.Run.View
sub ssn1()
objPPT.Run "C:\ppt\Labo.ppt!.SSN"
End sub
how to call only ssn1() method from java.Otherwise can we run the macro of a power point from java code..kindly help!!
This should make you happy :) Go to the WScript section : http://technet.microsoft.com/library/ee156618.aspx
Here's my idea... in your vbscript file, make your script listen to a command line parameter that would specify which method to call. Then, in Java, you could only have to use this parameter whenever you want to call a specific method in the file.
Otherwise, if you want to access powerpoint in java, you will need to access its API like you did in vbscript, which is possible if vbscript can do it but the approach / syntax may change.
I'm not so much into the visual basic script side, but if you can expose your visual basic script as a COM object, the you can access the methods of it from java by usage of frameworks such as for example com4j:
http://com4j.java.net/
The PowerPoint application object's .Run method lets you call any public subroutine or function in any open presentation or loaded add-in
This post answers the OP's question:
Otherwise can we run the macro of a power point from java code..kindly help!!
(but does not address the original vbscript question)
There's the JACOB library, which stands for Java COM Bridge, you can find here: http://sourceforge.net/projects/jacob-project/?source=directory
With it you can invoke Excel, Word, Outlook, PowerPoint application object model methods.
I've tried this with Excel but not PowerPoint. (This is just some sample code, one might want to make it more object oriented.)
public class Excel {
private static ActiveXComponent xl = null;
public static Init() {
try {
ComThread.InitSTA();
xl = ActiveXComponent.connectToActiveInstance("Excel.Application.14");
// 14 is Office 2010, if you don't know what version you can do "Excel.Application"
if (xl==null) {
// code to launch Excel if not running:
xl = new ActiveXComponent("Excel.Application");
Dispatch.put(xl, "Visible", Constants.kTrue);
}
}
catch (Exception e) {
ComThread.Release();
}
}
public static String Run(String vbName) {
// Variant v = Dispatch.call(xl, "Run", vbName); // using string name lookup
Variant v = Dispatch.call(xl, 0x103, vbName); // using COM offset
// return Dispatch.get(this, "Name").getString();
return v.getString();
}
public static Variant Run1p(String vbName, Object param) {
// Variant v = Dispatch.call(xl, "Run", vbName, param);
return Dispatch.call(xl, 0x103, vbName, param);
// return Dispatch.get(this, "Name").getString();
}
public static Worksheet GetActiveWorksheet () {
// Dispatch d = xl.getProperty("ActiveSheet").toDispatch();
Dispatch d = Dispatch.get(xl, 0x133).toDispatch ();
return d; // you may want to put a wrapper around this...
}
}
Notes:
For Excel, at least, to get Run to invoke a VBA macro/subroutine several things have to be true:
The Excel workbook containing the macro must be "Active" (i.e. must
be the ActiveWorkbook) otherwise Run will not find the VBA subroutine. (However the workbook does not have to be
screen visible!! This means you can call a VBA Macro that is in an add-in!).
You can then pass the name of the macro using the following syntax as a string literal:
VBAProjectName.VBAModuleName.SubroutineName
For COM object invocations, you can use the name lookup version or the id number version. The id numbers come from the published COM interfaces (which you can find in C++ header files, or possibly have JACOB look them up for you).
If you successfully did the connection to Excel, be sure to call ComThread.Release() when you're done. Put it in some appropriately surrounding finally. If the process of your Java code terminates without calling it, the COM reference count on Excel will be wrong, and the Excel process will never terminate, even after you exit the Excel application. Once that happens, needless to say, Excel starts to behave screwy then (when you try to use it next, it runs but will fail to load any plug-ins/add-ons). If that happens (as it can during debugging esp. if you are bypassing finally's for better debugging) you have to use the task manager to kill the Excel process.

Passing a Javascript Variable to Android Activity?

Basically I want get data I already have accessed from javascript and passing it to Java/Android so that I can work with it there.
/* An instance of this class will be registered as a JavaScript interface */
class MyJavaScriptInterface {
#SuppressWarnings("unused")
public void setX(String html){
Activity.this.x = html;
Toast.makeText(myApp, Activity.this.x, Toast.LENGTH_LONG).show();
}
}
this works but I want to be able to call the same Toast line anywhere and get the same result. Currently it only returns null/empty when not called through loading through webview.loadUrl("Javascript:"...
Any tips?
You can not access stored javascript variables, you must do it through a function call.
You have to call it from javascript in your html page, for example:
TheNameOfYourInterface.setX('value');
TheNameOfYourInterface will be a javascript object when you add the interface to the webview via
YourWebView.addJavascriptInterface(new MyJavaScriptInterface(),"TheNameOfYourInterface");
so you can do the logic on your webview and call the interface when you set the data so the method in the Java side will be called.
I found a different solution to what I need, and I feel like it works for all who do not need get a value calc'd by javascript. My solution to my need was to HTTP GET the html/javascript and then parse it as a string. It saves me some time by not needing to load X WebViews and then (re)creating all my functions in the JavaScript Interface.
I think it will be a good idea to store the HTML in Shared Preferences ,which is a form of persistent storage.This way you will be able to access it from anywhere.
//------get sharedPreferences
SharedPreferences pref = context.getSharedPreferences("PREF_NAME", Context.MODE_PRIVATE);
//--------modify the value
pref.edit().putString("ToastString", html).commit();
//-------get a value from this from anywhere
String toastValue=pref.getString("ToastString", "");

Categories

Resources