Getting a SecurityException: Permission denied in java - 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?

Related

How am I supposed to draw an image from my Java Applet?

I am not sure how to fully express this but, I have probably gone through 10 pages of Google links on this topic and not one of them has helped me solve my issue.
I thought it would be simple enough, I was just trying to add an image to the paint function of my java applet, like any other shape, but this has turned out to be a nightmare for me.
The problem is that every time I try to run the drawImage function it keeps saying Access Denied ("java.io.FilePermission" "Image.jpg" "read"). Yet, none of the tutorials mention this at all, all they ever say is that I should do the following:
import java.applet.*;
import java.awt.*;
Image img;
//These would go in the paint function
img=getImage(getDocumentBase(),"/Image.jpg"); //I have tried without the slash too
g.drawImage(img,20,20,this);
This is all they do and it works for them, but it just won't work for me. Other methods are far too complex for the sake of just adding an image, and even when I go through the toil of doing those it keeps giving me the "Access Denied" message. There's also the method of "signing" it, but I really don't think that's going to help given all that I have tried, so I am afraid it might just be another wasted endeavor. None of the tutorials even tell you to have your applet signed.
I have the image in the "build" (also called bin) folder together with the classes.
The program seemed to run when I included the entire file path, but even then the image did not display. That is not to mention I can't really include the complete path from my own computer because then it wouldn't work when I actually send it to another person.
Please, I just want to know why it doesn't work for me yet seems to work perfectly for others. That, and if there's a way around this.
This is an example of what I am doing:
import java.applet.*;
import java.awt.*;
public class JavaProject extends JApplet
{
Image img;
public void init()
{
img=getImage(getDocumentBase(),"/Image.jpg");
}
public void paint(Graphics g)
{
super.paint(g);
g.drawImage(img,20,20,this);
}
}
This is my HTML file:
<html>
<head>
<title> My First Web Page </title>
</head>
<body>
<applet code="JavaProject.class" width="400" height="500">
</applet>
</body>
</html>
According JApplet java docs method getImage(URL url, String name) should have two parameter: URL-link to picture and String name.
Is method getDocumentBase() returnig an URL-link?
You must start by understanding that an Applet, unless signed, may not read from the file system. It must use either classpath resources or things fetched from the same place it was fetched from. You have to decide which of these applies to you. If the image is a fixed image, you can put it in your classpath as a resource, and use Class.getResourceAsStream. If it's a different image every time, you'll have to use HTTP.
Try this one if the image in the "build" (also called bin) folder together with the classes.
import java.awt.Graphics;
import java.awt.Image;
import java.net.URL;
import javax.swing.JApplet;
public class JavaProject extends JApplet {
Image img;
public void init() {
img = getImage(getDocumentBase(), "images/222.png");
// Please ensure that 222.png is placed under bin/images folder directly
}
#Override
public void paint(Graphics g) {
update(g);
}
#Override
public void update(Graphics g) {
g.drawImage(img, 20, 20, this);
}
}
Try with HTTP URL first
URL myURL = new URL("https://www.gravatar.com/avatar/a94613cea642e6e9e2105867bc2e103e?s=32&d=identicon&r=PG&f=1");
img = getImage(myURL);
If you are using Eclipse under Windows then have a look at below screenshot:
Please have a look at below post to get some understanding about it.
java.io.FilePermission exception - Read from jar file?

Adding an applet to a website

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

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