Calling a javascript function out of java - java

Im trying to call a javascript function out of my Vaadin Portlet.
lets say I have an HTML file witch is located in my project ;
homepage.html
<html>
...
<script type="text/javascript">
...
function foo(String msg)
{
alert(msg);
}
...
</script>
...
</html>
the page in Embedded in my Portlet via the Vaadin Embedded Browser
how do I call the function foo(String msg) out of my java application
do i need to import/read the homepage.html file and just call it or is it something else I have to do ?

firstly you need to get the script body;
then you can user javax.script.ScriptEngineManager to solve your problem javax.script.*
pseudo code
import javax.script.*;
ScriptEngine engine =
new ScriptEngineManager().getEngineByName("javascript");
String script = getScript(path_to_html);
engine.eval(script);

The simplest way to include an external javascript file into a Vaadin application is to override the Application#writeAjaxPageHtmlVaadinScripts method.
To call a javascript function from the Vaadin server-side code, you call Window#executeJavascript
#Override
protected void writeAjaxPageHtmlVaadinScripts(Window window,
String themeName, Application application, BufferedWriter page,
String appUrl, String themeUri, String appId,
HttpServletRequest request) throws ServletException, IOException {
page.write("<script type=\"text/javascript\">\n");
page.write("//<![CDATA[\n");
page.write("document.write(\"<script language='javascript' src='" + appUrl + "/VAADIN/scripts/example.js'><\\/script>\");\n");
page.write("//]]>\n</script>\n");
super.writeAjaxPageHtmlVaadinScripts(window, themeName, application,
page, appUrl, themeUri, appId, request);
}
NB : I have never used Vaadin as a Portlet, but a quick look suggests that this should work OK.
However, this approach is rather rudimentary, and only suitable for a quick hack/proof-of-concept: if you want to so anything more sophisticated, then developing your own Vaadin widget is correct approach. It gives you the power of GWT and JSNI, and gives you a much finer grain of control : See The Book Of Vaadin for more details.

Refer to following links, these provides API for doing what you want to do,
http://www.ibm.com/developerworks/java/library/j-5things9/index.html
http://metoojava.wordpress.com/2010/06/20/execute-javascript-from-java/

Related

Input to JavaFX from JSP

I want to give dynamic input to Java FX application from a JSP page. I am not able to find any suitable way.
Dynamic in the sense that I want to give input to JavaFX application based on user input in a JSP page. I am embedding the same Java FX application in the same JSP page.
Any help is welcome regarding the same.
I want to give input to Java FX application when it is running through JSP page.
See the JavaFX deployment topic: Accessing a JavaFX Application from a Web Page.
The JavaScript => JavaFX interface in JavaFX is the same as that used for a traditional Java applet - it makes use of a technology known as LiveConnect. Further documentation on using LiveConnect is in the LiveConnect documentation topic: Calling from JavaScript to Java.
The JavaFX documentation provides the following sample code:
Java Code
package testapp;
public class MapApp extends Application {
public static int ZOOM_STREET = 10;
public static class City {
public City(String name) {...}
...
}
public int currentZipCode;
public void navigateTo(City location, int zoomLevel) {...}
....
}
JavaScript Code
function navigateTo(cityName) {
//Assumes that the Ant task uses "myMapApp" as id for this application
var mapApp = document.getElementById("myMapApp");
if (mapApp != null) {
//City is nested class. Therefore classname uses $ char
var city = new mapApp.Packages.testapp.MapApp$City(cityName);
mapApp.navigateTo(city, mapApp.Packages.testapp.MapApp.ZOOM_STREET);
return mapApp.currentZipCode;
}
return "unknown";
}
window.alert("Area zip: " + navigateTo("San Francisco"));
Note the important comment in the JavaScript code "Assumes that the Ant task uses "myMapApp" as id for this application". The id referred to is the placeholderid parameter of the fx:deploy task.
Now, because you are using a JSP, presumably the html page containing the application is dynamically generated by the JSP processor. So, what you may want to do is make use of the fx:template task to generate modified jsp source which invokes the dtjava deployment script to embed your target JavaFX application.
I'm not sure, but try: HostServices.getWebContext

Call java method in javascript without html firebug extension

I'm trying to develop an extension for firebug. I want to call a java method in this extension but there is no html in it so I can't use the applet-html solution.
Here is my java Applet :
import java.applet.Applet;
import javax.swing.JOptionPane;
public class MyApplet extends Applet {
public void init() {
super.init();
System.out.println("init something");
}
public String jsCall(String hello) {
System.out.println("this method is called by a js function and say :"
+ hello);
Thread t = new Thread(new Runnable(){
public void run(){
JOptionPane jop1 = new JOptionPane();
jop1.showMessageDialog(null, "Message informatif", "Information", JOptionPane.INFORMATION_MESSAGE);
}
});
t.start();
return "lala";
}
}
I try this:
var applet = document.createElement("applet");
applet.setAttribute("code","file:///home/dacostam/z_test/firebug-extension-examples-0bdcf15/helloamd#janodvarko.cz/chrome/content/MyApplet.class");
applet.setAttribute("id","javaToJavascriptApplet");
applet.setAttribute("mayscript","true");
applet.jsCall("HelloWorld"); //jsCall not a function
And this:
var dom = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', null);
dom.appendChild(applet);
dom.javaToJavascriptApplet.jsCall("HelloWorld"); //jsCall not a function
The document is not like usual there is no body or html in it.
Is there an other way to call java in javascript instead of the applet-html solution?
Or is there a way to do it with this method but otherwise?
If you need more information, I'm here.
Thanks.
Edit:
It would be to long to explain you what the program do, just keep in mind that it's inevitably in java, I just need to call a method which take a parameter string and return a string or eventually void.
Edit2:
Sorry I have not thought of that, java needs to run on the client.
If your requirement is to make a call from JavaScript to your Java application, you need to clarify where does your Java app needs to run.
If Java needs to run on the client (same machine as your Firebug), it looks like you are either stuck with an applet or you need to be building a tiny webservice in your Java so you can talk to it through a web API on localhost.
If your Java can sit on a server somewhere, you could talk to your Java application through a web API (similarly to the second option above).

How to execute JavaScript on Android?

I have code which uses ScriptEngineManager, ScriptEngine class for executing JavaScript code using Java. But it works fine in Java SE, and doesn't work in Android - SDK show error of missing classes. Is it possible to execute JS code in Android? Thank you.
AndroidJSCore is a great one. And here is another little library I wrote for evaluating JavaScript:
https://github.com/evgenyneu/js-evaluator-for-android
jsEvaluator.evaluate("function hello(){ return 'Hello world!'; } hello();", new JsCallback() {
#Override
public void onResult(final String result) {
// get result here (optional)
}
});
It creates a WebView behind the scenes. Works on Android version 3 and newer.
You can use Webview which inherits View class. Make an XML tag and use findViewById() function to use in the activity. But to use the JavaScript, you can make a HTML file containing the JavaScript code. The example blelow might help.
Webview browser=(Webview) findViewById(R.main.browser); //if you gave the id as browser
browser.getSettings().setJavaScriptEnabled(true); //Yes you have to do it
browser.loadUrl("file:///android_asset/JsPage.html"); //If you put the HTML file in asset folder of android
Remember that the JS will run on WebView, not in native environment, thus you might experience a lag or slow FPS in emulator. However when using on an actual phone, the code may run fast, depending on how fast is your phone.
http://divineprogrammer.blogspot.com/2009/11/javascript-rhino-on-android.html will get you started. ScriptEngine is a java thing. Android doesn't have a JVM but a DalvikVM which is not identical but similar.
UPDATE 2018: AndroidJSCore has been superseded by LiquidCore, which is based on V8. Not only does it include the V8 engine, but all of Node.js is available as well.
Original answer:
AndroidJSCore is an Android Java JNI wrapper around Webkit's JavaScriptCore C library. It is inspired by the Objective-C JavaScriptCore Framework included natively in iOS 7. Being able to natively use JavaScript in an app without requiring the use of JavaScript injection on a bloated, slow, security-constrained WebView is very useful for many types of apps, such as games or platforms that support plugins. However, its use is artificially limited because the framework is only supported on iOS. Most developers want to use technologies that will scale across both major mobile operating systems. AndroidJSCore was designed to support that requirement.
For example, you can share Java objects and make async calls:
public interface IAsyncObj {
public void callMeMaybe(Integer ms, JSValue callback) throws JSException;
}
public class AsyncObj extends JSObject implements IAsyncObj {
public AsyncObj(JSContext ctx) throws JSException { super(ctx,IAsyncObj.class); }
#Override
public void callMeMaybe(Integer ms, JSValue callback) throws JSException {
new CallMeLater(ms).execute(callback.toObject());
}
private class CallMeLater extends AsyncTask<JSObject, Void, JSObject> {
public CallMeLater(Integer ms) {
this.ms = ms;
}
private final Integer ms;
#Override
protected JSObject doInBackground(JSObject... params) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.interrupted();
}
return params[0];
}
#Override
protected void onPostExecute(JSObject callback) {
JSValue args [] = { new JSValue(context,
"This is a delayed message from Java!") };
try {
callback.callAsFunction(null, args);
} catch (JSException e) {
System.out.println(e);
}
}
}
}
public void run() throws JSException {
AsyncObj async = new AsyncObj(context);
context.property("async",async);
context.evaluateScript(
"log('Please call me back in 5 seconds');\n" +
"async.callMeMaybe(5000, function(msg) {\n" +
" alert(msg);\n" +
" log('Whoomp. There it is.');\n" +
"});\n" +
"log('async.callMeMaybe() has returned, but wait for it ...');\n"
);
}
I was also looking for a way to run javascript on Android and came across j2v8 library. This is a java wrapper for Google's v8 engine.
To use it add a dependency:
compile 'com.eclipsesource.j2v8:j2v8_android:3.0.5#aar'
It has pretty simple api, but I haven't found any docs online apart from javadoc in maven repository. The articles on their blog are also useful.
Code sample from this article:
public static void main(String[] args) {
V8 runtime = V8.createV8Runtime();
int result = runtime.executeIntegerScript(""
+ "var hello = 'hello, ';\n"
+ "var world = 'world!';\n"
+ "hello.concat(world).length;\n");
System.out.println(result);
runtime.release();
}
The javax.script package is not part of the Android SDK. You can execute JavaScript in a WebView, as described here. You perhaps can use Rhino, as described here. You might also take a look at the Scripting Layer for Android project.
You can use Rhino library to execute JavaScript without WebView.
Download Rhino first, unzip it, put the js.jar file under libs folder. It is very small, so you don't need to worry your apk file will be ridiculously large because of this one external jar.
Here is some simple code to execute JavaScript code.
Object[] params = new Object[] { "javaScriptParam" };
// Every Rhino VM begins with the enter()
// This Context is not Android's Context
Context rhino = Context.enter();
// Turn off optimization to make Rhino Android compatible
rhino.setOptimizationLevel(-1);
try {
Scriptable scope = rhino.initStandardObjects();
// Note the forth argument is 1, which means the JavaScript source has
// been compressed to only one line using something like YUI
rhino.evaluateString(scope, javaScriptCode, "JavaScript", 1, null);
// Get the functionName defined in JavaScriptCode
Object obj = scope.get(functionNameInJavaScriptCode, scope);
if (obj instanceof Function) {
Function jsFunction = (Function) obj;
// Call the function with params
Object jsResult = jsFunction.call(rhino, scope, scope, params);
// Parse the jsResult object to a String
String result = Context.toString(jsResult);
}
} finally {
Context.exit();
}
You can see more details at my post.
Given that ScriptEngineManager and ScriptEngine are part of the JDK and Android SDK is not the same thing as the JDK I would say that you can't use these classes to work with JavaScript under Android.
You can check the Android SDK's reference documentation/package index to see what classes are included (what can you work on Android out of the box) and which of them are missing.
I just found the App JavaScript for Android, which is the Rhino JavaScript engine for Java. It can use all Java-classes, so it has BIG potential. The problem is it might be slow, since it is not really optimized (heavy CPU load). There is another JavaScript engine named Nashorn, but that unfortunately doesn't works on Google's DalvikVM Java engine (does not support the optimizations of Oracle Java engine). I hope Google keeps up with that, I would just love it!
If you want to run some javascript code on chrome browser as per the question copy this code and paste it into address bar:
data:text/html, <html contenteditable> <title> Notepad </title> <script> alert('Abhasker Alert Test on Mobile'); </script> </html>

How to call jquery trigger from gwt?

public static native void doConnect() /*-{
$wnd.jQuery(document).trigger('connect',
{
jid: 'sss',
password: 'sss'
}
);
}-*/;
i tried the above ,but there is no error in firebug or gwt hosted mode
console(so i cannot know whether the code is success or not). may i know is this the correct way to call jquery trigger? but when i put alert() in bind('connect'), it was not called
inside .js file
$(document).bind('connect', function (ev, data) {
alert('not call.....at all');
var conn = new Strophe.Connection(
"http://bosh/xmpp-httpbind");
conn.connect(data.jid, data.password, function (status) {
if (status === Strophe.Status.CONNECTED) {
$(document).trigger('connected');
} else if (status === Strophe.Status.DISCONNECTED) {
$(document).trigger('disconnected');
}
});
Hello.connection = conn;
});
I had similar issues when using jQuery UI with GWT - no errors in console/dev mode, yet the code did not behave like I wanted. The reason was that jQuery (and such frameworks) extend/change many core elements of JavaScript and expect it to stay that way - however, GWT code (meaning, also JSNI stuff) is executed from a "clean" iframe (so that no external frameworks can mess with the language and cause some weird errors in GWT, that's why you have to reference to the main window via $wnd).
I'd suggest moving your doConnect function to the host page (or external js file linked to the host page) and instead just call that function from your JSNI stub:
public static native void doConnect() /*-{
$wnd._doConnect('sss','sss'); //_doConnect defined in the host page
}-*/;
Or provide helper functions that will return Arrays, etc, from the host page, so that they include all the changes that jQuery made and expects.
It's a bit late for this answer, but your original code did not work due to a simple mistake: You have properly used $win instead of window but a few characters later you have used document instead of $doc :)
public static native void doConnect() /*-{
$wnd.jQuery($doc).trigger($wnd.jQuery.Event('connect', {
jid: 'sss',
password: 'sss'
}));
}-*/;

How can I fill out an online form with Java?

My cell phone provider offers a limited number of free text messages on their website. I frequently use the service although I hate constantly having a tab open in my browser.
Does anyone know/point me in the right direction of how I could create a jar file/command line utility so I can fill out the appropriate forms on the site. I've always wanted to code up a project like this in Java, just in case anyone asks why I'm not using something else.
Kind Regards,
Lar
Try with Webdriver from Google or Selenium.
Sounds like you need a framework designed for doing functional testing. These act as browsers and can navigate web sites for testing and automation. You don't need the testing functionality, but it would still serve your needs.
Try HtmlUnit, or LiFT, which is a higher-level abstraction built on HtmlUnit.
Use Watij with the Eclipse IDE. When your done, compile as an .exe or run with a batch file.
Here is some sample code I wrote for filling in fields for a Google search, which can be adjusted for the web form you want to control :
package goog;
import junit.framework.TestCase;
import watij.runtime.ie.IE;
import static watij.finders.SymbolFactory.*;
public class GTestCases extends TestCase {
private static watij.runtime.ie.IE activeIE_m;
public static IE attachToIE(String url) throws Exception {
if (activeIE_m==null)
{
activeIE_m = new IE();
activeIE_m.start(url);
} else {
activeIE_m.goTo(url);
}
activeIE_m.bringToFront();
return (activeIE_m);
}
public static String getActiveUrl () throws Exception {
String currUrl = activeIE_m.url().toString();
return currUrl;
}
public void testGoogleLogin() throws Exception {
IE ie = attachToIE("http://google.com");
if ( ie.containsText("/Sign in/") ) {
ie.div(id,"guser").link(0).click();
if ( ie.containsText("Sign in with your") ||
ie.containsText("Sign in to iGoogle with your")) {
ie.textField(name,"Email").set("test#gmail.com");
ie.textField(name,"Passwd").set("test");
if ( ie.checkbox(name,"PersistentCookie").checked() ){
ie.checkbox(name,"PersistentCookie").click();
}
ie.button(name,"signIn").click();
}
}
System.out.println("Login finished.");
}
public void testGoogleSearch() throws Exception {
//IE ie = attachToIE( getActiveUrl() );
IE ie = attachToIE( "http://www.google.com/advanced_search?hl=en" );
ie.div(id,"opt-handle").click();
ie.textField(name,"as_q").set("Watij");
ie.selectList(name,"lr").select("English");
ie.button(value,"Advanced Search").click();
System.out.println("Search finished.");
}
public void testGoogleResult() throws Exception {
IE ie = attachToIE( getActiveUrl() );
ie.link(href,"http://groups.google.com/group/watij").click();
System.out.println("Followed link.");
}
}
It depends on how they are sending the form information.
If they are using a simple GET request, all you need to do is fill in the appropriate url parameters.
Otherwise you will need to post the form information to the target page.
You could use Watij, which provides a Java/COM interface onto Internet Explorer. Then write a small amount of Java code to navigate the form, insert values and submit.
Alternatively, if it's simple, then check out HttpClient, which is a simple Java HTTP client API.
Whatever you do, watch out that you don't contravene your terms of service (easy during testing - perhaps you should work against a mock interface initially?)
WebTest is yet another webapp testing framework that may be easier to use than the alternatives cited by others.
Check out the Apache Commons Net Package. There you can send a POSt request to a page. This is quite low level but may do what you want (if not you might check out the functional testing suites but it is probably not as easy to dig into).
As jjnguy says, you'll need to dissect the form to find out all the parameters.
With them you can form your own request using Apache's HTTP Client and fire it off.

Categories