Applet Security - java

I have embedded an applet in an html page which access User's file directory. Its signed. When I write code inside init function then it works very well but when I write this code inside a method and call it with Javascript Then it sends me security exception. Have u any idea how can I solve this problem?
public class App extends javax.swing.JApplet {
#Override
public void init() {
}
public void callMethod(){
File file = new File("D:/test.txt");
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Javascript:
window.document.applets[0].callMethod();

See if the answers to this very similar question can help you: signed applet gives AccessControlException: access denied, when calling from javascript

To be trusted, every frame on the stack must be accounted for. Once JavaScript is in the mix, that stops being the case.
To fix it, wrap the trusted code in an AccessController.doPrivileged() method. See the JavaDocs for an example.

Related

Open a File with Desktop Application with Applet

somehow I want to open a file form a web application with the desktop application from client side.
My boss told me to use Applet. I've been through all the internet could provide me, but still can't find how to do it.
I've build a code program from java class to open the file directly but I can't make the applet running from JSP file.
Here's my code :
public static void main(String[] a) {
try {
URI uri = new URI("your/local/file/path");
Desktop desktop = null;
if (Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop();
}
if (desktop != null)
desktop.browse(uri);
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (URISyntaxException use) {
use.printStackTrace();
}
}
If somebody ever done it before, I'll be really thankful.
Normally, Applets do not have access to the local file system due to security issues. However, there are ways to grant file system access to applets. This article describes the procedure: https://www.developer.com/java/other/article.php/3303561/Creating-a-Trusted-Applet-with-Local-File-System-Access-Rights.htm. Altough I have not tested it myself and it is rather old, the article seems promising. I hope, this helps you.

How to set a Java Gui listener for unexpected program end

I am making a personal planning program. I utilize XML documents to store user data and login data. This does not utilize a server and all accounts created in the program are localized to the computer it is stored on (in the XML documents.)
In the login XML document, I keep track of the users that are logged in so that one user can't have two windows at the same time to prevent any conflicts with data. This feature runs smoothly and I have no problem with it.
The only thing I want to know is if there is some way to catch an unexpected shut down of a program (such as a task-manager close or a forced close when shutting down the computer) so that I can "log" the user off of the XML document. Otherwise the user would never be able to get back on after an unexpected program close without going into the XML document and deleting the username from the logged in list.
It seems a shutdown hook does not work well with the event queue for a java GUI. much like this thread
I tried setting up my code exactly as shown and the shutdown hook doesn't work for me either. Are there any suggestions for ways of catching an unexpected shutdown without shutdown hooks?
this is my code:
import java.awt.EventQueue;
public class Gui {
private static Controller controller;
public static void main (String[] args) {
controller = new Controller();
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
controller.saveState();
controller.logUserOut();
}
});
EventQueue.invokeLater(
new Runnable() {
public void run() {
controller.start();
}
});
}
}
This is a closer look at my controller that logs the user out
public void logUserOut() {
loginDatabase.logUserOut(username);
saveLoginState();
}
All loginDatabase does is removes that username from the list of logged in users so that user is free to log in again
public void saveLoginState() {
XStream xStream = new XStream(new DomDriver());
OutputStream outFile;
try {
String filePath = "data" + File.separator + "loginDatabase.xml";
outFile = new BufferedOutputStream(new FileOutputStream(filePath));
xStream.toXML(loginDatabase, outFile); // This writes your state to the outputFile;
outFile.close(); //close the writer
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
This is my process for writing on the login state xml file. I suspect it might be too long for a Shutdown Hook even if it were actually being called as I expect.
Any suggestions? I thought for a long time about possibly using simple variables to solve the problem but because I have the program set so that the user can be logged into multiple accounts, the use of variables is impossible.
Also, will the controller object contained in the scope of the shutdown hook be the same controller that is modified in the event queue scope?
The shutdown hook can be a solution here. For details see e.g. this answer: https://stackoverflow.com/a/2541618/2045440
[Off topic] However, if you're at risk that unexpected termination of your application can result in lost of important data, maybe it would be worth to consider the more persistent way of processing this data (autosaving, backup files etc).
I resolved the problem by checking the task manager of the operating system. It allowed me to see if the user the xml document said was logged in actually had a program open. If not then I knew there was a problem. This is a fix for my particular program but it might be a help for others as well.
The link to that thread is here.

Open multiple link with browser with delay

I did this program that opens multiple link with default browser:
ArrayList<String> linkList = new ArrayList<>();
for (int i = 0; i < linkList.size(); i++) {
ClassRunnable_OpenLink obj = new ClassRunnable_OpenLink ( linkList.get(i) );
Thread thread = new Thread(obj);
thread.start();
}
private class ClassRunnable_OpenLink implements Runnable {
private URL link;
private String string;
public ClassRunnable_OpenLink (String string) {
this.string = string;
}
private void OpenWithBrowser () {
try {
link = new URL ( string );
edu.stanford.ejalbert.BrowserLauncher launcher = null;
try {
launcher = new BrowserLauncher(null);
} catch ( BrowserLaunchingInitializingException | UnsupportedOperatingSystemException ex) { }
launcher.openURLinBrowser( link );
} catch ( MalformedURLException ex | IOException | URISyntaxException ex) { }
}
#Override
public void run() {
OpenWithBrowser( );
}
}
This works great only if browser (say it's firefox) is already opened, but if it's not, my program only opens the first link and then I have a firefox message that tells me the the browser is still running so I need to close it first.
Same thing with chromium.
So I thought, if I had a way to check when the browser is closed I could use ProcessBuilder to open new firefox process, but I don't know if it's the best way to do this. Besides my java program allows user to select default browser so it could be complicated to use ProcessBuilder in that case.
So do you a have any idea to solve my problem? Maybe I could set a delay between each Thread in this way the system has the time to execute browser process first time, then opening first link and after the browser is running, opening other links, but how about the delay time in seconds? I'm not able to know the time that browser needs to open so it's not a good idea.
I hope you can help me. Thanks
Since java 6 you don't have to use 3rd party implementations to open a webpage with the standard browser. Try
java.awt.Desktop.getDesktop().browse(uri);
Since this maps to the underlying OS functions chances are high multiple calls will work as expected.
A workaround to this (without knowing your exact expectations), could be to do the following:
After first URL open, you could build a delay of for example 10 seconds.
Then in any consecutive URL openings, you can assume that the browser is now surely open, and start opening the next URL's fast after each other.
One note though: Always add some delay to opening URL's (not sure if your framework already does this), because else the browser might crash from the number of URL openings.
UPDATE: You say that Thread.sleep() causes your program to block, this should never happen.
You should always seperate long-during actions from the rest of your program (The (Graphical) User Interface).
So it would be better to write your 'URL opener facility' in another thread.
You can read more about that here: http://docs.oracle.com/javase/tutorial/essential/concurrency/

How do you open web pages in Java?

Is there a simple way to open a web page within a GUI's JPanel?
If not, how do you open a web page with the computer's default web browser?
I am hoping for something that I can do with under 20 lines of code, and at most would need to create one class. No reason for 20 though, just hoping for little code...
I am planning to open a guide to go with a game. The guide is online and has multiple pages, but the pages link to each other, so I am hoping I only have to call one URL with my code.
Opening a web page with the default web browser is easy:
java.awt.Desktop.getDesktop().browse(theURI);
Embedding a browser is not so easy. JEditorPane has some HTML ability (if I remember my limited Swing-knowledge correctly), but it's very limited and not suiteable for a general-purpose browser.
There are two standard ways that I know of:
The standard JEditorPane component
Desktop.getDesktop().browse(URI) to open the user's default browser (Java 6 or later)
Soon, there will also be a third:
The JWebPane component, which apparently has not yet been released
JEditorPane is very bare-bones; it doesn't handle CSS or JavaScript, and you even have to handle hyperlinks yourself. But you can embed it into your application more seamlessly than launching FireFox would be.
Here's a sample of how to use hyperlinks (assuming your documents don't use frames):
// ... initialize myEditorPane
myEditorPane.setEditable(false); // to allow it to generate HyperlinkEvents
myEditorPane.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ENTERED) {
myEditorPane.setToolTipText(e.getDescription());
} else if (e.getEventType() == HyperlinkEvent.EventType.EXITED) {
myEditorPane.setToolTipText(null);
} else if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
try {
myEditorPane.setPage(e.getURL());
} catch (IOException ex) {
// handle error
ex.printStackTrace();
}
}
}
});
If you're developing an applet, you can use AppletContext.showDocument. That would be a one-liner:
getAppletContext().showDocument("http://example.com", "_blank");
If you're developing a desktop application, you might try Bare Bones Browser Launch.
haven't tried it at all, but the cobra HTML parser and viewer from the lobo browser, a browser writen in pure java, may be what you're after. They provide sample code to set up an online html viewer:
import javax.swing.*;
import org.lobobrowser.html.gui.*;
import org.lobobrowser.html.test.*;
public class BareMinimumTest {
public static void main(String[] args) throws Exception {
JFrame window = new JFrame();
HtmlPanel panel = new HtmlPanel();
window.getContentPane().add(panel);
window.setSize(600, 400);
window.setVisible(true);
new SimpleHtmlRendererContext(panel, new SimpleUserAgentContext())
.navigate("http://lobobrowser.org/browser/home.jsp");
}
}
I don't know if such a built-in exists, but I would use the Runtime class's exec with iexplore.exe or firefox.exe as an argument.
Please try below code :
import java.awt.Desktop;
import java.net.URI;
import java.net.URISyntaxExaception;
//below is the code
//whatvever the url is it has to have https://
Desktop d = Desktop.getDesktop();
try {
d.browse(new URI("http://google.com"));
} catch (IOException | URISyntaxException e2) {
e2.printStackTrace();
}

How to know if is Applet or Application

I have this code inside a class that is used by an application and by an applet.
static
{
if (System.getProperty("os.name").startsWith("Windows"))
{
System.loadLibrary("extmapi");
}
}
Unfortunately, when the applet loads this code I get an error, because it can't load the "extmapi" library.
To avoid this error, I need to know if the code I'm running is an Applet or an application, so that I can do:
if (isApplet)
return;
else
//load library
How can I know if I'm running inside an Applet?
Can't you just catch the (Security?) exception?
Your top-level container will be an instance of Applet.
if (thispanel instanceof Applet)

Categories

Resources