How to embed jar in HTML - java

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.

Related

Java jface calling browser from an relative location

I have encountered a small problem that I need some help on. The issue is that I wish to call a browser window which calls a html page. The html file opens in 3 different browsers so the code for that should be correct. The actual problem is that it brings up a page can't be displayed error message
Here is the code that gets the location
package org.error;
public class BrowserLocation {
private String test1 = "org\\error\\PatientNumberError.html";
public BrowserLocation() {
}
public String patientNumberAddress() {
return test1;
}
}
and here is the code that creates the browser component and calls the location of the html file.
Browser browser = new Browser(container, SWT.NONE);
browser.setForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_BLUE));
browser.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
browser.setUrl(browserLocation.patientNumberAddress());
browser.setBounds(25, 25, 315, 180);
Would it be possible to find the error of my ways?
setUrl require a URL so you need something like:
browser.setUrl(new File(path).toURI().toURL().toString());
Sorry for not getting back to you earlier.
Someone that I know who is a senior Java programmer told me the problem that I was having was a case of absolute address versus relative address.
The reason for this is that if I was reading and writing to a file, then I would be able to use a relative address. However If I'm interacting with a server which is the case here as eventually It could go on-line (If I had the money) it would need to be an absolute address.
As I am still learning Java programming this was a very specific and important lesson to learn. I hope this would help anybody else who has had this issue.

Signed Java applet permission [duplicate]

I have designed an Applet to take a screenshot and save it on the users computer using the java.awt.Robot class. I need to embedd this applet into an html page (using the object tag) so that when the user clicks a button on the webpage the screenshot is taken.
The applet itself works fine, i've tested it by adding a temporary main method to it and running it on my local machine as a regular java app.
Where I'm having difficulty is setting up permissions to allow it to run from its embedded location. Obviously the robot class is somewhat hazardous so an AWTPermission needs to be established and the applet itself needs to be signed.
I followed through the tutorial at http://download.oracle.com/javase/tutorial/security/toolsign/index.html and succeeded in creating a signed .jar file and then a policy file that allowed the demo application in that tutorial to run. Where I am now running into issues is how to reconcile what I've learned with the situation my applet will be used in.
My target audience comprises around 100 machines and I need it to be executable on all of them. I have packed my java .class file into a .jar and signed it using keytool and jarsigner. I then uploaded the .jar and .cer files to the server directory where the pages in question are hosted.
However: When I then used policytool to create a new policy file on one of the machines to test the setup I am still unable to execute the applet from the HTML. I get Java.Security.AccessControlException Acess Denied java.awt.AWTPermission createRobot errors.
I rather suspect its the policy step that is going awry, so I'll outline the steps I took:
I download the certificate to the local machine and generate a keystore from it, I launch 'policytool' from this directory through the commandline
I add the directory on the local machine where the keystore generated from and my certificate is located.
I then hit the add policy button and enter the SignedBy alias
Then Add Permissions and select AWTPermission
Targets name I select createRobot
The function field I have been leaving blank as I cant think what would apply here
Signed By in this window is also left blank
I then hit 'OK' and 'Done' and get a warning that there is no public key for the alias I've entered in the first step. I do a 'save as' and save my policyfile to the same directory as I put the certificate and the keystore generated from it.
This is not allowing me to run the applet from the webpage however and my limited understanding of this aspect of programming offers no clues as to what has gone wrong.
Ideas, thoughts, observations? If I havent explicitly mentioned something then I havent done it. My biggest suspect is the warning I recieve but I cant seem to find why its appearing
EDIT: Forgot to mention a step. I manually added to my jre\lib\security\java.security file the line 'policy.url.3=file:/C:/Testing/debugpolicy' since thats the path and policy filename I created during the above steps. I also just now managed to remove the warning I mentioned earlier, I'd been mixing up my alias' and gave the alias for the private keystore rather than the public one during policyfile creation, however I still encounter the same problems
If an applet is correctly signed, no policy file is required, nor is it required to separately upload any certificate. A correctly signed applet will prompt the user for permission when the applet is visited, before it loads. Does the prompt appear?
Here is a small demo. I wrote that demonstrates Defensive loading of trusted applets. That is the security prompt I am referring to.
If the applet is both digitally signed by the developer and trusted by the end user, it should be able to take a screen-shot.
There is one other thing you might try if the applet is trusted, just as an experiment (1). Early in the applet init(), call System.setSecurityManager(null). That will both test if the applet has trust, and wipe away the last remnants of the 'trusted' security manager given to applets.
And in the case that works, and it makes the screen capture successful, it suggests either a bug or Oracle changed their mind about the defaults of what a trusted applet could do.
1) Don't do this in a real world or production environment. To quote Tom Hawtin:
This question appears to have given some the impression that calling System.setSecurityManager(null); is okay. ... In case anyone has any doubts, changing global state in an applet will affect all applets in the same process. Clearing the security manager will allow any unsigned applet to do what it likes. Please don't sign code that plays with global state with a certificate you expect anyone to trust.
Edit 1:
Here is the source of the simple applet used in that demo. For some reason when I originally uploaded it, I decided the source was not relevant. OTOH 3 people have now asked to see the source, for one reason or another. When I get a round tuit I'll upload the source to my site. In the mean time, I'll put it here.
package org.pscode.eg.docload;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
import java.security.*;
/** An applet to display documents that are JEditorPane compatible. */
public class DocumentLoader extends JApplet {
JEditorPane document;
#Override
public void init() {
System.out.println("init()");
JPanel main = new JPanel();
main.setLayout( new BorderLayout() );
getContentPane().add(main);
try {
// It might seem odd that a sandboxed applet can /instantiate/
// a File object, but until it goes to do anything with it, the
// JVM considers it 'OK'. Until we go to do anything with a
// 'File' object, it is really just a filename.
File f = new File(".");
// set up the green 'sandboxed page', as a precaution..
URL sandboxed = new URL(getDocumentBase(), "sandbox.html");
document = new JEditorPane(sandboxed);
main.add( new JScrollPane(document), BorderLayout.CENTER );
// Everything above here is possible for a sandboxed applet
// *test* if this applet is sandboxed
final JFileChooser jfc =
new JFileChooser(f); // invokes security check
jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
jfc.setMultiSelectionEnabled(false);
JButton button = new JButton("Load Document");
button.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent ae) {
int result = jfc.showOpenDialog(
DocumentLoader.this);
if ( result==JFileChooser.APPROVE_OPTION ) {
File temp = jfc.getSelectedFile();
try {
URL page = temp.toURI().toURL();
document.setPage( page );
} catch(Exception e) {
e.printStackTrace();
}
}
}
} );
main.add( button, BorderLayout.SOUTH );
// the applet is trusted, change to the red 'welcome page'
URL trusted = new URL(getDocumentBase(), "trusted.html");
document.setPage(trusted);
} catch (MalformedURLException murle) {
murle.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (AccessControlException ace) {
ace.printStackTrace();
}
}
#Override
public void start() {
System.out.println("start()");
}
#Override
public void stop() {
System.out.println("stop()");
}
#Override
public void destroy() {
System.out.println("destroy()");
}
}

How to alter WM_CLASS value in a Java GUI application based on Swing or NetBeans Platform?

All Swing/NetBeans-based Java GUI applications seem to have the same WM_CLASS value:
WM_CLASS(STRING) = "sun-awt-X11-XFramePeer", "java-lang-Thread"
This parameter can be viewed by issuing xprop command and pointing to the window. The practical purpose of customizing it is to let Mac-like docks (AWN, for example (and, perhaps, Ubuntu's Unity)) distinguish the application windows and group them under the application's pinned launcher icon. For this to work StartupWMClass parameter is to be set accordingly in the .application file in ~/.local/share/applications or /usr/share/applications. Needless to say, AWN (and analogues) get confused in case more than one application uses the same string for WM_CLASS.
This blog post found the field in Toolkit that controls it, named awtAppClassName. It suggests using reflection to modify it:
Toolkit xToolkit = Toolkit.getDefaultToolkit();
java.lang.reflect.Field awtAppClassNameField = xToolkit.getClass().getDeclaredField("awtAppClassName");
awtAppClassNameField.setAccessible(true);
awtAppClassNameField.set(xToolkit, applicationName);

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) {
}

jQuery and Java applets

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();
});

Categories