Adding an applet to a website - java

First time posting here. I made a simple calculator program using java and I am trying to put it onto my website. From what I've gathered from previous help posts is that I need to create a JApplet with all my program contents and compress it into a .jar file. Then I need to create a .JNLP file, which describes how to applet should be launched.
So here is where I am having trouble.
package calculator;
import javax.swing.JApplet;
import javax.swing.SwingUtilities;
public class CalculatorApplet extends JApplet {
public void init()
{
try
{
SwingUtilities.invokeAndWait(new Runnable()
{
public void run() {
Calculator calc = new Calculator();
add(calc);
}
});
}
catch(Exception e)
{
System.err.println("GUI creation failed");
}
}
}
It seems my applet was not constructed properly. Whenever I run it a "java.lang.reflect.InvocationTargetException" is thrown. Whenever I run my Calculator class independently from the applet it works as expected. Any ideas where the source of my error is?

I think JNLP files are used for Java Web Start. That's something you won't need with an average Java applet. Please do correct me if I'm wrong.
If you have the working .jar file, an HTML file that calls the applet will be sufficient to run the applet. Insert the code <applet width="300" height="300" archive="jar.jar" code="class.class"></applet> into an HTML file, where class.class is the class extending Applet or JApplet and jar.jar the location of the jar file. Loading the HTML file in a browser will display the applet.
Alternatively, you can use Java's Applet Viewer to open the HTML page and open the applet locally.

You can certainly use JNLP with applets.
See https://docs.oracle.com/javase/tutorial/deployment/deploymentInDepth/runAppletFunction.html and https://docs.oracle.com/javase/tutorial/deployment/deploymentInDepth/embeddingJNLPFileInWebPage.html

Related

class not found exception java in server?

I have a java applet which works in eclipses, and i exported it like this, right click folder, export, export as jar, selected class files and project files and 'src' folder, then press 'next' 'next' and then i pick the main class which is called Main_run, which has a main class but don't have anything in it
public class Main_run extends Applet implements Runnable, KeyListener, MouseMotionListener, MouseListener
{
public static void main (String[] args )
{
}
}
this is because the applet start with 'init()'
Then I made a html page which has this on it
<b><applet code="Desktop.jar/Main_run.class" width="320" height="120"></b>
not (<) should be <.
then I added both file, the exported jar file and the index to the server im getting this error
"ClassNotFoundException"
Any idea how to fix it?
You might want to take a look at the question at How to embed jar in HTML.
In other words, use <applet archive="Desktop.jar" code="Main_run.class" width="320" height="120">. That's my thought on the subject.

Java applet doesn't draw or accept mouse inputs in browser, but does in Eclipse Appletviewer

I'm doing a personal project called "Electromagnetic Field Hockey" (named after Electric Field Hockey on The University of Colorado's PhET website). I've decided to port the application to a java applet on my website.
The problem is that the applet will not accept any mouse input, and I don't even know if it started because the graphics disappear when I switch tabs and back. I know the applet is finding the code and codebase because the applet initializes and renders the first frame of the graphics correctly, then does nothing. What's peculiar is the applet works fine in Eclipse's Appletviewer. I suspect that the culprit is the start() method, which I think somehow isn't being executed in a browser.
In case it helps, you can find the applet at http://leo.scruffohio.net/programs/EMFieldHockey.html. I tested it with Firefox on Linux and Safari on a Mac so it's not a system-dependent issue. Note that the application works when you run the jar file (located at http://leo.scruffohio.net/programs/java/thebombzen-emhockey-dev3.jar).
My applet code is very simple:
public class EMFieldHockeyApplet extends JApplet {
private static final long serialVersionUID = 8145754973708683690L;
#Override
public void init() {
this.setBackground(Color.WHITE);
this.setLayout(new GridLayout());
this.add(ElectromagneticFieldHockey.getInstance());
// that's the main application JPanel
}
#Override
public void start() {
ElectromagneticFieldHockey.start();
}
#Override
public void stop(){
ElectromagneticFieldHockey.stop();
}
}
It seems that problem in your jar signing, try with it
http://docs.oracle.com/javase/tutorial/deployment/jar/signing.html

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

Getting a SecurityException: Permission denied in java

I am getting the java.lang.SecurityException: Permission denied: file:////Videos/public/scripts/screenshot.jar when I try to use an applet.
Here is the applet code:
<applet code="Screenshot" archive="file:////Videos/public/scripts/screenshot.jar" width="100px" height="100px">
</applet>
How do I fix it and what the problem even means?
EDIT:
From what I see I need to sign the applet. Could some one explain how and why this is done? The site provided does a bad job explaining it because it doesn't even address the fact that I am embedding this into my site and want every client to use it and not have to sign anything. Just click run.
EDIT2:
The code of the app itself:
/*
By Bavo Bruylandt (Http://www.realapplets.com")
*/
// and now The inevidable "Hello World" example :)
// tell the compiler where to find the methods you will use.
// required when you create an applet
import java.applet.*;
// required to paint on screen
import java.awt.*;
// the start of an applet - HelloWorld will be the executable class
// Extends applet means that you will build the code on the standard Applet class
public class Screenshot extends Applet
{
// The method that will be automatically called when the applet is started
public void init()
{
// It is required but does not need anything.
}
// This method gets called when the applet is terminated
// That's when the user goes to another page or exits the browser.
public void stop()
{
// no actions needed here now.
}
// The standard method that you have to use to paint things on screen
// This overrides the empty Applet method, you can't called it "display" for example.
public void paint(Graphics g)
{
//method to draw text on screen
// String first, then x and y coordinate.
g.drawString("Hey hey hey",20,20);
g.drawString("Hellooow World",20,40);
}
}
It all depends on what is your applet trying to do, is it accessing the filesystem for example. Is it a signed applet or not? Applets run in a special sandbox by default with limited permissions.
You would have to check out more info on Applet security, for starters have a look into Informit article here: http://www.informit.com/articles/article.aspx?p=433382&seqNum=2
EDIT:
Try to add a policy file eg.
/* AUTOMATICALLY GENERATED ON Tue Apr 16 17:20:59 EDT 2002*/
/* DO NOT EDIT */
grant {
permission java.security.AllPermission;
};
named eg. java.policy.applet and place it on your classpath. Have a look at this question here about the policy files: Where to place java applet policy file?

Java - Applet calling/invoking another Applet

I wrote earlier about the following problem and received an answer to use either Splash Screen or JDialog. As I was researching about the above 2 solutions, now I think that I might be able to solve my problem by using another applet.
The problem: Before my main applet GUI runs I need to download certain files to local PC for the GUI to work. Therefore, I am now thinking of having 2 applets where Applet1 downloads the files, Applet2 is the main GUI.
I would use the Splash Screen or JDialog but at the moment they don't seem to be what I need. How can I invoke Applet2 from Applet1 automatically in the same window, and fully close Applet1 once Applet1 is done downloading files? Is the Applet idea better solution for my problem than Splash Screen or JDialog?
Here is the code of my main applet (in this case it would be Applet2):
#Override
public void init() {
/* Create and display the Applet2 once Applet1 is done */
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
#Override
public void run() {
initComponents();//Draw the GUI
}
});
} catch (Exception ex) {}
}
My earilier post:
Java - Pause initComponents from running?

Categories