jQuery and Java applets - java

I'm working on a project where we're using a Java applet for part of the UI (a map, specifically), but building the rest of the UI around the applet in HTML/JavaScript, communicating with the applet through LiveConnect/NPAPI. A little bizarre, I know, but let's presume that setup is not under discussion. I started out planning on using jQuery as my JavaScript framework, but I've run into two issues.
Issue the first:
Selecting the applet doesn't provide access to the applet's methods.
Java:
public class MyApplet extends JApplet {
// ...
public String foo() { return "foo!"; }
}
JavaScript:
var applet = $("#applet-id");
alert(applet.foo());
Running the above JavaScript results in
$("#applet-id").foo is not a function
This is in contrast to Prototype, where the analogous code does work:
var applet = $("applet-id");
alert(applet.foo());
So...where'd the applet methods go?
Issue the second:
There's a known problem with jQuery and applets in Firefox 2: http://www.pengoworks.com/workshop/jquery/bug_applet/jquery_applet_bug.htm
It's a long shot, but does anybody know of a workaround? I suspect this problem isn't fixable, which will mean switching to Prototype.
Thanks for the help!

For the first issue, how about trying
alert( $("#applet-id")[0].foo() );
For the second issue here is a thread with a possible workaround.
Quoting the workaround
// Prevent memory leaks in IE
// And prevent errors on refresh with events like mouseover in other browsers
// Window isn't included so as not to unbind existing unload events
jQuery(window).bind("unload",
function() {
jQuery("*").add(document).unbind();
});
change that code to:
// Window isn't included so as not to unbind existing unload events
jQuery(window).bind("unload",
function() {
jQuery("*:not('applet, object')").add(document).unbind();
});

Related

Javascript placement in GWT HTML

What is the difference of placing a Javascript (.js) library on before the GWT application nocache.js and after nocache.js in a GWT application which uses the JS library in JSNI methods.
Does it affect wether a JSNI method will be functional or not?
That really depends on when the JSNI method is loaded.
To be safe - always check to see if the JS lib you are using has been loaded. eg
public native static boolean isJqueryMethodLoaded(String method) /*-{
if ($wnd.jQuery && $wnd.jQuery[method]) {
return true;
} else {
return false;
}
}-*/;
(edited - thanks to the other answers for clarifying the load sequence)
Normal <script> tag are blocking, but the GWT script tag is not, since it is fetched asynchronously (i.e., non-blocking). The onModuleLoad() is called only when the body has been parsed (i.e., scripts have been fetched). Hence:
put it as the very first script in your list: you will save time;
<script> tags will always be loaded when onModuleLoad() is called.
Have a look at here.
onModuleLoad is always called at or after DOMContentLoaded, and this will always happen after your scripts have loaded (because they could do document.write()), unless you loaded them with async or defer.
So, unless you load your "other JS" with async or defer, it really shouldn't matter in which order you load them, as onModuleLoad should always be called after both are loaded.

Hard Refresh in GWT

Using Google Web Toolkit, I'd like to code the equivalent of a hard refresh (control + F5).
I don't believe (or know) if GWT's Window.Location will work.
import com.google.gwt.user.client.Window.Location;
Window.Location = currentPage; // I don't think it'll be hard refresh
For reloading the current page you need to call Window.Location.reload() method.
Reloads the current browser window. All GWT state will be lost.
Or you can even specify your own JSNI (below how todo), because by default force reload is false :
public static native void forceReload() /*-{
$wnd.location.reload(true);
}-*/;
According to https://developer.mozilla.org/en-US/docs/DOM/window.location#Methods you would need to call window.location.reload(true) to force the reload of the current page.
Unfortunately GWT wraps only the window.location.reload() via Window.Location.reload(), and it is up to the browser to retrieve the page from the cache or from another get. This is done to achieve the most cross-browser solution.
Never tried but you should be able to use the following.
public static native void reload(boolean force) /*-{
$wnd.location.reload(force);
}-*/;
For reload gwt page, you have two options:
1) Window.Location.reload();
Reloads the current browser window. All GWT state will be lost.
2) Window.Location.replace("newurl");
Replaces the current URL with a new one. All GWT state will be lost. In the browser's history, the current URL will be replaced by the new URL.

Open and maximise a browser window in OATS Java (not javascript)

I am a tester and just installed oracle application test suite to use testing eBus apps
Anyway the only language it supports for coding test scripts (I don't want to use the recorder for a number of reasons). The problem I am having is that everything I search or google is javascript not java (even googling with -script I still ended up looking at javascript. This just gets rejected by the oats editor
The only other examples I have seen, appear to be defining a variable then setting the value of that variable as the window they want to maximize. Aside from the fact that my java skills are not up to doing that - I do not need to do this for a newly opened browser window do I? (The assumption is that this will be the only browser window open (ie test is executed with browser closed)
Is there any easy way to do this?
Below is the very simple initiate of the browser which is generated from a recording plus part of the first step which loads the url the test starts at: (I realize the first step is not complete below -I didn't paste it all, just enough to hopefully allow someone to show me what I need to edit to force the browser to load maximized, or maximize it immediately after loading?
public void initialize() throws Exception {
browser.launch();
}
/**
* Add code to be executed each iteration for this virtual user.
*/
public void run() throws Exception {
beginStep("[1] Login (/RF.jsp)", 0);
{
web
.window(2,
"/web:window[#index='0' or #title='about:blank']")
.navigate(
"http://somepageiwantolaunch");
web.window(4, "/web:window[#index='0' or #title='Login']")
.waitForPage(null);
I am not sure whether you already got the answer for this.. if not this code should help you
browser.launch();
DOMBrowser currentExecutionBrowser = web.window("/web:window[#index='0' or #index='1']");
currentExecutionBrowser.maximize();
Let me know if this helps!
There is a function in the Oracle Functional Tester API Reference which has a build in function called object.WindowState It says you can get or set using this function and it has values
0 - Normal, 1- minimized and 2-maximised.
Only issue is that these examples look more like VB than Javascript but presumably there is a similar function built into to the Oracle libraries for Java.
I did a quick search for Oracle Openscript API and came up with this link which asks for the same thing. They suggest using Help->Search from within the openscript application and then searching for "openscript API" which should provide a list of the functions available.
Hope that helps.
To Maximize browser in OATS, follow the below code
Open script ha in built methods which helps coding easy
browser.launch();
web.window(12, "/web:window[#index='0' or #title='about:blank']").navigate("http://www.google.com/");
web.window(12, "/web:window[#index='0' or #title='about:blank']").maximize();
for more OATS Tips/Tricks follow here
http://www.testinghive.com/category/oracle-application-testing-suite-tips
If it is the only browser window open, you can use the below code. It must be used with caution since the code maximizes any window that is open above the browser window.
try {
Robot a = new Robot();
a.keyPress(KeyEvent.VK_ALT);
a.keyPress(KeyEvent.VK_SPACE);
a.keyRelease(KeyEvent.VK_SPACE);
a.keyRelease(KeyEvent.VK_ALT);
a.keyPress(KeyEvent.VK_X);
a.keyRelease(KeyEvent.VK_X);
} catch (AWTException e) {
}

How to embed jar in HTML

There are a lot of resources on this already but I just can't seem to get it to work. What am I doing wrong? The jar file is at:
http://www.alexandertechniqueatlantic.ca/multimedia/AT-web-presentation-imp.jar
And the code I am using to embed is:
<APPLET ARCHIVE="multimedia/AT-web-presentation-imp.jar"
CODE="ImpViewer.class"
WIDTH=100%
HEIGHT=100%>
</APPLET>
The test page I am using is at:
http://www.alexandertechniqueatlantic.ca/test.php
When I download the jar it runs fine, so I am certain the problem is only with the html embedding. Pleas help!
Also, I get the following error:
java.lang.ClassCastException: ImpViewer cannot be cast to
java.applet.Applet
java.lang.ClassCastException: ImpViewer cannot be cast to java.applet.Applet
The 'applet' is not an applet.
BTW - nice UI. Like the way the red splash fades in to the 'Welcome Introductory Workshop' page. Very smooth.
Launch it from a link using Java Web Start (& please don't try and cram such a beautiful UI into a web page).
If the client insists on the GUI being crammed into a web site then (slap them for me &) try this hack.
/*
<APPLET
ARCHIVE="AT-web-presentation-imp.jar"
CODE="ImpViewerApplet"
WIDTH=720
HEIGHT=564>
</APPLET>
*/
import java.awt.*;
import java.applet.*;
import java.util.*;
public class ImpViewerApplet extends Applet {
public void init() {
setLayout(new BorderLayout());
Window[] all = Window.getWindows();
ArrayList<Window> allList = new ArrayList<Window>();
for (Window window : all) {
allList.add(window);
}
String[] args = {};
ImpViewer iv = new ImpViewer();
iv.main(args);
all = Window.getWindows();
for (Window window : all) {
if (!allList.contains(window) && window.isVisible()) {
if (window instanceof Frame) {
Frame f = (Frame)window;
Component[] allComp = f.getComponents();
Component c = f.getComponents()[0];
f.remove(c);
f.setVisible(false);
add(c);
validate();
}
}
}
}
}
The emphasis is on the word 'hack'.
The Frame will flash onto screen before disappearing.
It will only work at 720x564 px, unlike the java.awt.Frame which was resizable to any size. But then, your '100%' width/height was being a bit optimistic anyway. Some browsers will honour those constraints, others will not.
It took a bit of effort, but your ImpViewer class has the following definition:
public class ImpViewer extends ImWindow
implements Printable, Runnable
{
[...]
ImpViewer is NOT an Applet like it needs to be, but is instead an ImWindow. It should inherit from either Applet or perhaps ImApplet.
At either rate, Andrews idea of using Java Web Start is legit. The app you have looks more like a desktop app.
An Applet is a Java component which handles the right calls to show up embedded in a web page. The product you have (the JAR file) contains everything necessary to run the program; however, it does not have the correct interface (the applet) for running that program embedded in a web page.
Talk to the author of the product (of if that author is not available, look for documentation) and see if a applet interface is available. Perhaps it is only a matter of using a different class name. If it looks like such an interface is not available, then no one has done the necessary work to make it "embeddable" in a web page. Without knowing your product in more detail, it's not easy to determine if the effort to create an Applet interface into the product is easy or not.
If you don't have the source code, then the amount of effort to develop an Applet interface to what you have is even greater than the unknown amount of effort it would have been with the source code.
There are a few products that do allow applications to be viewed and controlled from a web browser, even when the application in question wasn't designed to be embedded in a web page. These products tend to be expensive and proprietary; but, if it is truly mission-critical (and if it makes enough money) then the expense and effort might be bearable. With such a solution, the web browser actually opens a window into a configured "application server" which launches the application in full screen mode every time the connection is established. Yes, it is an odd architecture; however, such an odd architecture exists purposefully as that's really the only way possible to do some things when the application can't run in other environments.
Look to Citrix for such a solution in the event that you can afford it (remember there's extra windows licenses involved) and you can tolerate it's performance and quirks.

Bridge between the Java applet and the text input controls on the web page

I have been working with a Java applet which is an applet that helps to write using only a mouse. For my case, I am trying to incorporate this into my webiste project as follows:
When the user clicks on any input element (textbox/textarea) on the page, this JAVA applet loads on the webpage itself. In the screenshot of the JAVA applet seen below, the user points to an alphabet to and the corresponding text gets written in the text box of the applet.
Now what I am trying to do is to get this text from the TextBox of the applet to the input element on the webpage. I know that this needs an interaction between the Java and JavaScript, but not being a pro, I really do not have the catch. Here's the Java applet and the code I have written.
Java applet and jQuery code (298kB): http://bit.ly/jItN9m
Please could somebdoy help for extending this code.
Thanks a lot!
Update
I searched somewhere and found this -> To get the text inside of Java text box, a getter method in the Applet to retrieve the text:
public class MyApplet extends JApplet {
// ...
public String getTextBoxText() { return myTextBox.getText(); }
}
In the JQuery code, the following lines are to be added I think:
var textBoxText = $("#applet-id")[0].getTextBoxText();
//Now do something with the text
For the code of the applet, I saw a GNOME git page here. The getText call already exists -- look at the bottom of this file: http://git.gnome.org/browse/dasher/tree/java/dasher/applet/JDasherApplet.java
I'd need to call 'getCurrentEditBoxText' but when should this method 'getCurrentEditBoxText' be called?
In my case, I would probably have to do it when the user clicks in a new input control etc.
You can have full communication between your Applet and any javascript method on the page. Kyle has a good post demonstrating how the Javascript can call the applet and request the text value. However, I presume you want the HTML Textfield to update with each mouse click, meaning the applet needs to communicate with the page. I would modify your javascript to something like this:
var activeTextArea = null;
$('textarea, input').click(function() {
$(this).dasher();
activeTextArea = this;
});
function updateText(text) {
// Careful: I think textarea and input have different
// methods for setting the value. Check the
// jQuery documentation
$(activeTextArea).val(text);
}
Assuming you have the source for the applet, you can have it communicate with the above javascript function. Add this import:
import netscape.javascript.JSObject;
And then, in whatever onClick handler you have for the mouse clicks, add:
// After the Applet Text has been updated
JSObject win = null;
try {
win = (JSObject) JSObject.getWindow(Applet.this);
win.call("updateText", new Object[] { textBox.getText() });
} catch (Exception ex) {
// oops
}
That will update the text each time that chunk of code is called. If you do NOT have access to the applet source, things get trickier. You'd need to set some manner of javascript timeout that constantly reads the value from the applet, but this assumes the applet has such a method that returns the value of the textbox.
See Also: http://java.sun.com/products/plugin/1.3/docs/jsobject.html
Update Modifying the applet is your best shot since that is where any event would be triggered. For example, if you want the HTML TextField to change on every click, the click happens in the applet which would need to be modified to trigger the update, as described above. Without modifying the applet, I see two options. Option #1 uses a timer:
var timer;
var activeTextArea;
$('textarea, input').click(function() {
$(this).dasher();
activeTextArea = this;
updateText();
}
function updateText() {
// Same warnings about textarea vs. input
$(activeTextArea).val($('#appletId')[0].getCurrentEditBoxText());
timer = setTimeout("updateText()", 50);
}
function stopUpdating() {
clearTimeout(timer);
}
This is similar to the code above except clicking on a text area triggers the looping function updateText() which will set the value of the HTML text field to the value of the Applet text field every 50ms. This will potentially introduce a minor delay between click and update, but it'll be small. You can increase the timer frequency, but that will add a performance drain. I don't see where you've 'hidden' the applet, but that same function should call stopUpdating so that we are no longer trying to contact a hidden applet.
Option #2 (not coded)
I would be to try and capture the click in the Applet as it bubbles through the HTML Dom. Then, you could skip the timer and put a click() behavior on the Applet container to do the same update. I'm not sure if such events bubble, though, so not sure if this would work. Even if it did, I'm not sure how compatible it would be across browsers.
Option #3
Third option is to not update the HTML text field on every click. This would simply be a combination of Kyle's and my posts above to set the value of the text field whenever you 'finish' with the applet.
Here's a possible solution. To get the text inside of your Java text box, write a getter method in the Applet to retrieve the text:
public class MyApplet extends JApplet {
// ...
public String getTextBoxText() { return myTextBox.getText(); }
}
In your JQuery code, add the following lines:
var textBoxText = $("#applet-id")[0].getTextBoxText();
//Now do something with the text
I found most of what I posted above here. Hope this helps.
This page explains how to manipulate DOM from a Java applet. To find the input element, simply call the document.getElementById(id) function with id of an id attribute of the text input box.

Categories