Input to JavaFX from JSP - java

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

Related

How to use processing sketch in a web app

Good day, i have a Processing sketch that i want to use in a web application
i am using jsp and servlets in my web app with tomcat as a server. I am using netbeans and i tried using < applet > tag but i can't get it to work, please help.
CODE:
import processing.core.*;
public class MyProcessingSketch extends PApplet {
public static void main(String args[]) {
PApplet.main(new String[] { "MyProcessingSketch" });
}
public void setup() {
}
#Override
public void draw() {
background (200,0,0);
}
public void settings(){
size(600,240);
}
public void mousePressed(){
exit();
}
}
Applets are not really supported anymore... But you might try p5js. Your HTML page would look like this:
<html>
<script src="http://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.6/p5.js"></script>
<script>
function setup() {
createCanvas(600, 240);
background(200,0,0);
}
function draw() {
// ...
}
</script>
Like the other answer says, applets are pretty much dead. They currently require you to have a paid signed certificate or for your users to change their security settings. And even then they show a bunch of scary warning dialogs, and it's just a pain in the neck for everybody. Chrome has dropped support for applets, and they'll be deprecated in the next version of Java.
If you're using eclipse, you've got three options:
Deploy as a runnable jar.
Deploy as a packaged executable.
Deploy using webstart.
None of these are embedding an applet in a webpage.
However, if you're using the Processing editor, you can use Processing.js to write the same Processing code but have it deployed as JavaScript, which you can embed in a webpage. Processing.js does the translation for you, so you don't have to change your code into JavaScript code.
You can also use p5.js, but that will require you to completely rewrite your syntax into JavaScript syntax.
In either case, you'll no longer be able to use Java libraries in your code. You'll have to find a JavaScript library that does the same things and use that instead. If you really need to use the Java libraries, then you have to go with deploying using one of the first three options.

JSP like templating for simple text

I've got a program that currently has a mass of code that I would like to design away. This code takes a number of text files and passes it through an interestingly written interpreter to produce a plain text file report that goes on to other systems. In theory this allows a non-programmer to be able to modify the report without having to understand the inner workings of Java and the interpreter. In practice, any minor change likely necessitates going into the interpreter and tweaking it (and the domain specific language isn't exactly friendly even to other programmers).
I would love to redesign this code. As a primarily web programmer the first thing that came to mind when thinking of "non-programmer being able to modify the report ..." I replaced report with web page and said to myself "ah ha! Jsp." This would give me a nice What You See Is Almost What You Get approach for people along with taglibs and java scriptlets (as undesirable as the later may be) rather than awkwardly written DSL statements.
While it is possible to use jspc to compile a jsp into java (another part of the application runs ejbs on a jboss server so jspc isn't too far away), the boilerplate code that it uses tries to hook up the output to the pagecontext from the servletcontext. It would involve tricking the code into thinking it was running inside a web container (not an impossibility, but a kluge) and then removing the headers.
Is there a different templateing approach (or library) for java that could be used to print to a text file? Every one that I've looked at so far appears to either be optimized for web or tightly coupled to a particular application server (and designed for web work).
So you need a slim down version of JSP.
See if this one (JSTP) works for you
http://jstp.sourceforge.net/manual.html
Give Apache Velocity a try. It is incredibly simple and does not assume it is running in the context of a web application.
This is totally subjective, but I would argue it's syntax is easier for a non-programmer to understand than JSP and tag libraries.
If you want to be a real tread setter in your company, you could create a Grails application to do it and use Groovy templating (maybe in combination with the Quartz plugin for scheduling), it might be a bit of a hard sell if there is alot of existing code to be replaced but I love it...
http://groovy.codehaus.org/Groovy+Templates
If you want the safe bet, then (the also excellent) Velocity has to be it:
http://velocity.apache.org/
Probably you want to check Rythm template engine, with good performance (2 to 3 times faster than velocity) and elegant syntax (.net Razor like) and designed specifically to Java programmer.
Template, generate a string of user names separated by "," from a list of users
#args List<User> users
#for (User user: users) {
#user.getName() #user_sep
}
Template: if-else demo
#args User user
#if (user.isAdmin()) {
<div id="admin-panel">...</div>
} else {
<div id="user-panel">...</div>
}
Invoke template using template file
// pass render args by name
Map<String, Object> renderArgs = ...
String s = Rythm.render("/path/to/my/template.txt", renderArgs);
// or pass render arguments by position
String s = Rythm.render("/path/to/my/template.txt", "arg1", 2, true, ...);
Invoke template using inline text
User user = ...;
String s = Rythm.render("#args User user;Hello #user.getName()", user);
Invoke template with String interpolation mode
User user = ...;
String s = Rythm.render("Hello #name", user.getName());
ToString mode
public class Address {
public String unitNo;
public String streetNo;
...
public String toString() {
return Rythm.toString("#_.unitNo #_.streetNo #_.street, #_.suburb, #_.state, #_.postCode", this);
}
}
Auto ToString mode (follow apache commons lang's reflectionToStringBuilder, but faster than it)
public class Address {
public String unitNo;
public String streetNo;
...
public String toString() {
return Rythm.toString(this);
}
}
Document could be found at http://www.playframework.org/modules/rythm. Full demo app running on GAE: http://play-rythm-demo.appspot.com.
Note, the demo and doc are created for play-rythm plugin for Play!Framework, but most of the content also apply to the pure rythm template engine.
Source code:
Rythm template engine: https://github.com/greenlaw110/rythm/
Play Rythm Plugin: https://github.com/greenlaw110/play-rythm

Calling a javascript function out of 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/

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