Hot questions for Using Applets in web

Question:

To protect our users from maliciuos applets I wanted to disable the Java browser plug-in.

In a test (JRE 7) I noticed that deactivating the plug-in also disables Java Web Start. We need to use one Web Start application so it seems that we have no choice than keeping the browser plug-in enabled.

Is this correct, or is there a way to use Web Start without enabling the browser plug-ins?


Test steps:

Its message translates to

This application could not be downloaded because Java over Internet is deactivated. You can activate Java on this system over the Java Control Panel

I have not seen an option to activate "Java over Internet" in the Java Control Panel. When I enable the browser plug-in, the Java Web Start application can be launched.

The same error message appears if I execute a local copy of the JNLP file

jawas <path to local jnlp file>

The jnlp file (slightly cleaned up):

<?xml version="1.0" encoding="UTF-8"?>
<jnlp spec="1.0+" codebase="https://example.com/path/to/" href="webstartapp.jnlp">
    <information>
        <title>...</title>
        <vendor>...</vendor>
        <homepage href="..." />
        <description>...</description>
        <description kind="short">...</description>
        <description kind="tooltip">...</description>
        <offline-allowed />
    </information>
    <security>
        <all-permissions />
    </security>
    <resources>
        <j2se version="1.7+" initial-heap-size="128m" max-heap-size="256m" />
        <jar href="Client/lib/Launcher.jar" main="true" />
    </resources>
    <application-desc main-class="com.veda.launcher.Start">
        <argument>...</argument>
        <argument>*</argument>
    </application-desc>
</jnlp>

Answer:

AFAIK, the "Enable Java content in the browser" checkbox on the Security tab of the Java Control Panel is controlling BOTH applets and web start. Indeed, on Mac, the equivalent checkbox is called "Enable applet plug-in and Web Start applications".

Therefore, it's unlikely that you can accomplish this via the Java Control Panel. However, you might be able to leave the global Java setting ON in the Control Panel and disable Java individually in each browser.

Question:

I want to acces a scanner at client side, before I was using java applet without problem but after chrome has decided to not support java what can I do. If there's solution with JS, Jquery or other language please tell me


Answer:

Atalasoft has a web scanning toolkit that should meet your needs: Atalasoft WingScan product page

The product does not use browser-specific plugins and therefore works nicely in all modern browsers (IE8+, Chrome, Firefox).

Architecturally, there is a small local component that should be installed, which exposes RESTful web service. Web page uses standard JavaScript/jQuery to communicate with the service and scan/import/enhance images.

Here is the online demo, so you could try it out right away: Wing Scan Demo page

The scanning component is based on the EZTwain library, and it includes a number of image processing algorithms that improve quality of scanned images (deskew, autorotate, blank page detection, etc.)

You can optionally license and use embedded VRS technology, which I have to say is impressively good at cleaning up scans.

Question:

Current situation

We currently use an applet to perform some operations, after which it redirects the current page. In its core, you could see the applet as the following:

public class ExampleApplet extends Applet {
    @Override
    public void init() {
        Button redirect = new Button("Redirect");
        this.add(redirect);
        final String target = this.getParameter("targetPage");
        redirect.addActionListener((ActionEvent e) -> {
            try {
                getAppletContext().showDocument(new URL(target), "_parent");
            } catch (MalformedURLException ex) {}
        });
    }
}

with the applet being called in its simplest way:

<applet code="com.example.applet.ExampleApplet.class" archive="${appletUrl}" width="100" height="30">
    <param name="targetPage" value="http://localhost:8080/applet/"/>
</applet><br/><br/>

where ${appletUrl} returns the location of the applet JAR.

So the applet is nothing more than a simple button that calls getAppletContext().showDocument(new URL(target), "_parent"); to refresh the current page. This has done its job correctly for a long time. Now here's the issue.

Migration

As many may know, Chrome does not support Applets. Which was put aside for a while since IE and FireFox still supported them. At the end of 2016, they will also no longer support them. So we decided to migrate the applet using JWS and JNLP.

Migrating this simple redirect button example would give the following html snippet and JNLP file:

<a href="${jnlpUrl}">Launch JNLP</a>

${jnlpUrl} returns the location to the JNLP file which is:

<?xml version="1.0" encoding="utf-8"?>
<jnlp spec="1.0+" codebase="http://localhost:8080/applet/assets/1.0-SNAPSHOT-DEV/app/assets/" href="jnlp/example.jnlp">
    <security>
        <all-permissions/>
    </security>
    <resources>
        <j2se version="1.5+" initial-heap-size="32m" max-heap-size="128m" />
        <property name="jnlp.versionEnabled" value="false"/>
        <jar href="applets/ExampleApplet.jar" main="true"/>
    </resources>
    <applet-desc name="code" main-class="com.example.applet.ExampleApplet.class" width="30" height="30" >
        <param name="targetPage" value="http://localhost:8080/applet/"/>
    </applet-desc>
</jnlp>

So far so good, the same applet successfuly deploys as a JWS application. Allowing it to be used from any browser since it's executed outside of it. Which also is kind of the problem.

The problem

The line getAppletContext().showDocument(new URL(target), "_parent"); still does a redirect, but it's using the default browser as stated in the migration documentation.

For AppletContext.showDocument(URL url, String target), the target argument will be ignored by Java Web Start technology.

Similar to AppletContext.showDocument, Java Web Start applications are capabile of showing an HTML page using the system's default web browser by using the BasicService.showDocument API.

So if my default browser is FireFox, but I happen to be browsing to this JWS-enabled applet in IE/Chrome, a new tab will be opened in FireFox. This is a problem, since I have information (e.g. login) stored in the original browser!

Findings

Since the application is running outside of the browser, I'm having issues to think of possibilities to communicate back to the original browser. I can't use JavaScript since it doesn't run within the browser. I can't really define a system-independent way to open a tab in the original browser. I've also thought of WebSockets since they could allow direct communication, but from what I've read it's pretty high-level and requires a server, not a simple applet.

Is there any possibility of communicating between the original browser (e.g. websockets and parameters) or passing the session from one browser to another when the applet opens a new window?


Answer:

I have found out a working solution.

Since the applet loses all connection to the browser and its session, another way to provide communication is with WebSockets or Comet. In my case I used Comet with the Atmosphere framework and a Tapestry-Atmosphere implementation, since Tapestry is the view-framework I'm using.

Without going too deep into the Tapestry implementation, I have done the following:

  • Set up a Topic on the client-side browser which will listen to broadcasted messages in a typical publish/subscribe manner.
  • Provide the Topic's ID which is unique to the current browsing user into the Applet, along with a URL to send a request to. Using the Topic ID as a request parameter for the url.
  • Server-side I have the endpoint of the request which receives the Topic as a request parameter. Using this parameter, it sends a broadcast (possibly empty) to the topic.
  • The client-side Topic receives the notification and executes an event in itself. The event being to re-render specific content of the page.

Since it's using Comet (but could also use WebSockets) it happens directly in the browser. Every browser subscribed to that Topic actually, but here there's only one.

Making it in fact possible, to update the page from a simple request from the applet. The applet only had the line getAppletContext().showDocument(new URL(target), "_parent"); changed to new URL(target).openConnection().getInputStream();. With target being a URL with the included request parameter.

Question:

I'm working on research to move an existing applet (extends Applet) to Java Web Start due to the deprecation in Java 9. However, it seems like most of Oracle's migration docs instruct the dev to use the "applet-desc" tag to create a new JNLP and migrate. Does this mean that launching applets outside of the browser will not be deprecated?

If not, then what is the recommended approach? Saying "rewrite your applet" doesn't help... that's what everyone says. Doesn't really give me the "how".

What are possible solutions and examples/tutorials of migration? I can't seem to find much newer documentation out there, I see a lot of stuff between 2001 and 2011. It seems like most websites that provide examples no longer host the applications, or they aren't properly signed.

EDIT

My most important part of the question is: Is Oracle deprecating the Applet class when deprecating the browser plugin? Or, can we still use classes extending Applet within the tag in a JNLP, without a deprecation warning?

My applet requires user authentication and session cookies that are dynamically generated in our JSP. I've seen online that this is possible. This JWS application is not to be used offline, and is meant to be launched from an HREF. Is this still valid?


Answer:

The thing that is deprecated is done by the browser manufacturers (though Oracle, realising the situation now advises not to develop them). So Oracle has not 'deprecated' the applet tag(1) in the same way that it has deprecated other classes, methods or attributes as occasionally mentioned in the Java Docs.

As to launching the applet using JWS, yes that should still 'work'. But note that whereas (for example) Chrome used to pass a JNLP direct to the program registered as a consumer of that file type (wherein it would be passed to the Java Web Start Client included in the JRE), it now causes the user to first download the JNLP, then explicitly choose to launch that file.

  1. Update: Oracle may not have deprecated the applet tag, but they'll do effectively the same thing come Java 9. From JDK 9 and the Java Plugin:

By late 2015, many browser vendors have either removed or announced timelines for the removal of standards based plugin support, eliminating the ability to embed Silverlight, Java, Flash and other standards-based plugin technologies.

Oracle plans to deprecate the Java browser plugin in Java Standard Edition Development Kit 9 (JDK 9). Deprecation is a warning for developers to stop using this technology. JRE 9 will continue to provide the Java Plugin and support launching applets on browsers that still offer standard plugin support. This browser plugin will be removed from the Oracle JDK and JRE in a future Java SE release. Developers and users who want to learn more about this planned change can find out more in this blog post.

Question:

Is it possible use the WebSocket API of JavaScript, to communicate with a native application, on the client side, like an alternative to an applet, which have to access to the file system?

I will communicate with the client side by ws://localhost:xxxx, but I don't know if I could do it.

And If I could, this will be secure. Will I have to take some security considerations?


Answer:

No, you can not install a WebSocket server on a user's machine to replace the functionality of accessing the local filesystem in the same way that Java applets would.

Not without the user actively installing the WebSocket server on their own machine intentionally.

Your biggest problem is that the Javascript client code does not have unrestricted access to the user's filesystem. This is a security feature. This is an important security feature. You can not place arbitrary files on the user's machine in arbitrary places.

After that, Javascript client code also can not start processes on your system, even if it could get a WebSocket server installed in an arbitrary location. Again, this is a critical security feature.

And finally, if your Javascript client code could install and execute arbitrary software on the user's machine, you wouldn't need a WebSocket server for the use case you're looking for right now.


If you were to convince a user to install a WebSocket server on their own machine for your use case, which is to access the user's local filesystem, then you would have major security concerns to take into consideration. Not all filesystems have user and group based read/write/execute permissions... and even then, the user might start the server from within a privileged account.

The browser is designed to implicitly trust the server that it's attached to as far as whatever Javascript it receives. If your user later browses a malicious site which knows about your locally installed WebSocket server, and what commands it might expect, the browser will quite happily allow the malicious server to send any commands to your user's WebSocket server that they wish.

With my strong personal recommendation to respect the sanctity of the user's filesystem and obey the restrictions that browsers place on Javascript clients access to the local machine, if you do decide to try to convince your users to install a local WebSocket server, you must take absolute care to be as security conscious as possible. Validate *all* input, regardless of whether you think an attacker can't possibly generate it, and never blacklist known risks, ONLY whitelist known safe functions.

Remember, if you do anything to expose the user's filesystem to the web, you are pretty much handing the keys to their computer over to anyone who can find the door.

Question:

I am running Java 1.7.0_67-b01. We have an applet which downloads into the browser. Normally the user receives two prompts the first time the user employs the applet. The first one reads "Do you want to run this application" It then give the name of the application, the publisher, and the location and then states "This application will run with unrestricted access..." At the end of the prompt, the user has the option of checking a box to "Do not show this again for apps from the publisher and location above.". Clicking on the checkbox and then clicking the RUN button will result in the certificate of the applet being installed in an area accessible from the Java control panel.

Then the user receives a second prompt: "Allow access to the following application from this web site?" Again the Application and the Publisher are identified. And the following statement appears: "This web site is requesting access and control of the java application shown above. Allow access only if you trust the web site and know the application is intended to run on this site." Again there is a check box: "Do not show this again for this app and web site."

Oracle calls the act of clicking the check box and pressing the "Allow button" or "Run" button depending on the prompt, a "trust decision". If you choose to trust an application running from a particular web site, you can undo your decision by going to the Java Control Panel and clicking on the "Restore Security Prompts" button.

A permanent change occurs in the environment but I don't understand where the change is made. It is obvious that some information related to the website identified in the prompt is stored because making a trust decision, causes the prompt to disappear. But where is it stored? I've looked within the browser (I'm using IE9) and the control panel for java. I did discover that the certificates themselves are stored in a file called trusted.certs. This is located on my Windows 7 machine under Users\\AppData\LocalLow\Sun\Java\Deployment\security. When I click on the Restore Security Prompts button, the file changes. And it also updates when I make a trusted decision in response to the first prompt. But, not so the latter. Interestingly, if I copy the trusted.certs file to a different machine whatever decisions I made to the first prompt carry to the second machine. This suggests that by deploying the trusted.certs file to my user population, I can spare them the problem of having to be confronted with the first security prompt.

However, where data is stored related to the second prompt remains a mystery to me at this time. If anyone knows something about this prompt and where the data related to the trusted decision associated with this prompt is kept, I would appreciate it.

Is there also a way to avoid having the user having to make trust decisions? If this is a protected intranet environment, there should be a way to bypass this cumbersome security provision in the JRE.


Answer:

I never did find out where the JRE stores data related to the second prompt. But this is much less important than figuring out how to control prompting in situations where it is inconvenient for users to make trust decisions or just not possible. Oracle has a way around this in its most recent releases of the JRE through the use of something called a rule set. I enclose the links that describe these below:

http://docs.oracle.com/javase/7/docs/technotes/guides/jweb/security/deployment_rules.html

http://www.java.com/en/download/faq/release_changes.xml

Below is a sample ruleset that worked with our application:

<ruleset version="1.0+">
  <rule> <!-- allow anything signed with company's public cert --> 
    <id location="http://10.190.65.254/myapp">
    </id>
    <action permission="run"/>
  </rule>

 <rule>
   <id />
    <action permission="default"/>
  </rule>
</ruleset> 

We packaged the rule set in a signed jar and deposited it in a directory:

C:\Windows\Sun\Java\Deployment

After that, no more prompting.

Question:

I have an Applet that I would like to convert to a JWS file because of all this problem with compatibility with Chrome (and now, Edge). The problem is that I never used this technology so I would like some help.

Is there a step-by-step guide on doing this conversion? I mean, I have a class that extends java.applet.Applet implementing init and start, how do I change it to a JWS/JNPL class? And can it receive parameters like the applet?

We don't need it to run in the browser, so downloading and executing is fine. But it would be better if the browser executed it right away, instead of the user clicking on file downloaded. Is that possible?


Answer:

Is there a step-by-step guide on doing this conversion?

The JWS info. page here at SO has all the best JWS related links I could think to include.

I mean, I have a class that extends java.applet.Applet implementing init and start, how do I change it to a JWS/JNPL class?

By Jarring the classes and digitally signing the Jars (if not already done) then writing a JNLP file to launch it (and possibly configuring the server to return the correct content-type for a JNLP file).

And can it receive parameters like the applet?

Yes, they are specified in the JNLP file.

Question:

I'm going to migrate a Java Applet to be started via JNLP as a Java Web Start Application and run into some troubles/missunderstandings ... One of the resources I've got is this: 6 Migrating Java Applets to Java Web Start and JNLP:

But let's start:

Currently the application is an applet (JApplet) and was started in past by embedding into an HTML with the applet tag referring to a JNLP.

Now since applet support was dropped by all browsers, I should run it as Java Web Start.

Simply calling same JNLP failed as the resources (JAR files) couldn't be loaded. This was as a first step fixed by adding an code base attribute to the JNLP file.

Applet is starting outside of the browser.

But now the hard part ... I should/would like to get rid of any applet dependency.

But how? What is the right approach for that? The guide doesn't really tell, and therefore I have some questions:

  1. e.g.: How do I replace the usage of the applet.getAppletContext() and related usage of it?
  2. The guide says I should place a static main in my "main" applet class. But How should I do this?

I tried & to start the applet in different ways, but after that my applet was not starting any more.

How do I really replace it? What should be the right wrapper for an application instead of applet? How to start it?

Is there maybe a more elaborate guide/sample/tutorial to follow with a real example?


Answer:

An alternative containment for you application could be a JFrame. A migration path would be refactoring (moving) the actuall UI Code into a JPanel. That one can be placed into the JApplet or for an Java WebStart application into a JFrame. (during that time you could have a hybrid application).

<!-- main in MyApplication -->
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            public void run() {
                JFrame frame = new JFrame();
                frame.setTitle("MyApplication via JWS");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                // add here the real UI to the frame: setUpGUI(frame);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }

<!-- Init() in MyApplication extends JApplet -->

    @Override
    public void init() {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                // add here the real UI to the applet: setUpGUI(MyApplication.this);
            }
        });
    }

Note: the EventQueue.

According Question 1: Some of the Applet specifica have to be replaced be different ways. Find the basics here: https://docs.oracle.com/javase/9/deploy/jnlp-api-examples.htm e.g.: for AppletContext there is the BasicService as some kind of replacement.

Question:

I have a project that is built on Applets and that also comprises of Corba calls to backend (which is in C language). Now I need to remove Applets and convert it into JSP and Javascript combination. But the code seems to be complex as it also consist of backend calls. I am facing problem in figuring out what is to be converted in JSP and what in Javascript.

If I convert all the applet logic in Javascript, how will I pass the javascript data to the Java objects to pass it as input for corba calls.

I can't implement all the logic in JSP as the existing logic depends on the dynamic change of data by user.

I tried various links but couldn't find the proper solution to my problem. I read somewhere that Google Web Toolkit (GWT) might help me converting Java Logic to Javascript, but couldn't figure out what exactly needs to be done for that.

Can anyone guide me how should I start and what exactly should I do to complete my project?


Answer:

First the bad news. There is no generic and magic solution that can convert your legacy (as you are describing it) into modern n-tiers web application.

I can suggest you the following steps.

  1. decide what kind of client and server side technologies you are going to use and learn them to become familiar enough to start coding.
  2. learn your legacy code and re-design it. Decide which parts of the code must be re-written, what you can use as-is and what you have to change and/or re-package.

To choose client side technology try to search for "client side javascript frameworks" or something like this. Popularity of GWT that you mentioned is going down now. The most modern framework these days are AngularJS.

Concerning server side technologies I personally prefer Spring but you can take a look on Guice and EJB too. You can also implement whole server side as as collection of servlets. It is up to you.

Start learning this amazing world and come back with more concrete questions. Good luck.

Question:

I'm maintaining a Java applet launched via Java Web Start but I know little about this technology (we are in the process of moving away from applets but we need some maintenance on it). This applet depends on some external JAR files (batik, etc.).

We use gradle as the build system. We build a normal JAR and a fat JAR (with the com.github.johnrengelman.shadow plugin) as follows:

sourceSets {
  main {
    java {
    }
  }
}
repositories {
  flatDir {
    dirs 'lib'
  }
}
dependencies {
  compile 'commons-lang:commons-lang:2.0',
    'jargs:jargs:1.0',
    'org.apache.xmlgraphics:batik-svggen:1.7',
    'org.apache.xmlgraphics:batik-dom:1.7',
    'org.apache.xmlgraphics:batik-awt-util:1.7',
    'org.apache.xmlgraphics:batik-util:1.7',
    'org.apache.xmlgraphics:batik-xml:1.7',
    'xerces:xercesImpl:2.8.0'
}
jar {
  manifest {
    attributes  'Application-Name': project.name,
                'Permissions': 'all-permissions',
                'Implementation-Title': project.name,
                'Implementation-Version': version,
                'Main-Class': 'Foo',
                'Class-Path': configurations.compile.files.collect{ "lib/${it.name}" }.join(' ')
  }
  baseName project.name
  // include dependencies into lib dir in produced jar
  into('lib') {
    from configurations.runtime
  }
  from "README.md"
}
shadowJar {
  baseName project.name
}

gradle includes the JAR files in lib/ folder inside the main JAR and they are added to the Class-Path in MANIFEST.MF.

The applet works on client computers with the normal JAR but I don't fully understand why.

Somehow, the JAR files are loaded when Java Web Start launches the applet. They are not mentioned in the JNLP file (no <resource>) and there is no class loader (we don't use JarRsrcLoader or similar) so I guess it's because they are in Class-Path but I am not sure and I haven't been able to produce a MWE. In fact all the information that I have found states the opposite (at least for applications as opposed to applets).

Does anybody know if it's the case or a simple explanation/tutorial ?


Answer:

Well, I was wrong. In fact the JAR files are not loaded: when one tries to access the functionality that needs batik, it fails. This confirms my readings and @eckes and @zakki comments.

I also discovered that I can simplify our build.gradle file.

Question:

A small Java applet [Edited: that might not even be the right word: this is JNLP] in a site I support is currently compiled for Java v1.7. As v1.8 becomes increasingly common, our users are getting warnings like Firefox's "This application would like to use a version of Java (1.7) that is not installed on your system. We recommend running the application with the latest version of Java on your computer." Is there some way we could rebuild our applet to try for the 1.8 Java first and only try for the older 1.7 if 1.8 isn't available, preferably without needing to ask the user in either case? (FWIW, I'm a very experienced developer, but a rather inexperienced Java developer.)


Answer:

The applet can specify the version of java required using a line like this in the <resources> section of the code:

<j2se version="1.7*">

The version number specified can either end with a number, and asterisk or a plus sign.

  • 1.7 would mean the version must be 1.7.
  • 1.7* means anything at or higher than 1.7 but less than 1.8 (like 1.7.1).
  • 1.7+ means anything 1.7 or higher (including 1.8).

If your code should run fine on Java 7 or Java 8, then you'd want "1.7+" to indicate you're not that picky about it.

Question:

I am developing a java application(although, I am unsure if it should be developed as a desktop application, applet, or JWS). The application is basically a database of homeworks and tasks in physics. It uses .txt files in which it keeps records of these tasks, and the user has to have the ability to modify theese .txt files(through the API I will provide to the user - basically, the user can add tasks, or remove tasks, and, upon adding or removing a task the changes should be modified in the .txt files).

For example, if 'tasks.txt' contains the following lines: 0 1 2

These numbers(0,1,2) are interpreted as TaskId, meaning the database 'tasks.txt' represents contains 3 tasks, and their ID's are: 0, 1, and 2.

If a user is to add a task, the database('tasks.txt') would change into: 0 1 2 3

The task with ID 3 is the newly added task.

Now, I have already developed a GUI using Swing, which allows the user to add tasks, and remove tasks using add/remove buttons, and these actions update the 'task.txt' file. In order not to be misunderstood, let me say that I already have this functionality for a desktop(stand-alone) java application.

What I don't know how to do(or how to even approach it/which java technollogy to use, or how this is usually done) is the following:

  • I would like all the users, when they download and start my application, to be able to read from the same task database('tasks.txt')

  • All the changes one user makes to the database from a remote computer, should somehow be updated for all users, for example:

  • If a user from a home computer in China adds a new task, the user from a home computer in France should be able to see this change(this new task)

So, how can I accomplish this. Should I keep this .txt file on some webpage, and then access it and modify it(could you refer me to some articles explaining how is this done).

Should I develop my app as an applet, and then somehow modify the 'tasks.txt' file on webpage(and how can applets modify files on webpages)?

I am quite new to web development, so any articles explaining communication between users through webpages are more than welcome. Thanks for your help.


Answer:

Should I develop my app as an applet,

No! See Why CS teachers should stop teaching Java applets for lots of reasons not to code applets.

..and then somehow modify the 'tasks.txt' file on webpage(and how can applets modify files on webpages)?

The 'somehow' is with the help of the server. Add a JSP/servlet that the client side app. uses to perform the change.

Question:

I know you ca specify a file that is going to override the java.security f

java -Djava.security.properties=myProperties

How can I set this parameter in a JNLP file?


Answer:

Properties in JNLP file you can set using this tag:

<property name="key" value="overwritten"/>

But you can't set java.security.properties in JNLP. Not all properties are allowed to set in jnlp. For more info see here.

Why do you need to change this property?

Question:

Is there a modern way to run java application on the web? As far as I know, java applets and java web start both are deprecated.

I have an android app, written in java, which I want to run on server (of course, altered in some way). While java is cross-platform there is no problem to transfer it to desktop (no matter, javafx, swing or etc.).

Apparently, it would be great not to re-write it in some other language.


Answer:

Nowadays, we're using GWT at work. Well.. It's efficient, it's fast and compatible with all browsers. And it's so easy to build a web page with GWT. You can check tutorials from this link.

And you can look up for Spring MVC. Not the most flexible choice for UI, I know. But give it a shot. link

But.. If you're open to new things, I'll totally recommend React Js. It's flexible,it's super fast with perfect UI. If you ever think of using Java just for back end, React js is a great deal for UI. link

Question:

So, how much trust do I need to have in a publisher before I run their applet in the web browser?

In other words, I understand that a java applet is run in a sandbox in the browser, but this article suggests that the applet can actually access files stored on the local computer.

Can you please clarify the security limits of a java applet run in a modern browser, such as Firefox 50?


Answer:

I understand that a java applet is run in a sandbox in the browser, but this article suggests that the applet can actually access files stored on the local computer.

There are potentially three different levels of security available to a Java applet.

  1. The first is as you described 'sandboxed'. They can only access resources from their own server, nothing on your local file system unless they are launched using Java Web Start & will thereby have access to the services of the JNLP API. You might note that two of the services are the FileOpenService / FileSaveService! If the applet goes to use these, the end user will be prompted to permit the action via a dialog that states what the applet is trying to do, and asking for permission to proceed (to show a file chooser & go from there). These services provide back a 'file like' object that is more limited than the normal File API would supply. For example, it will not provide the path to the resource, just it's name and access to the content.
  2. The level up from that can be specified in the launch file - '(J2EE) application client permissions'. This level removes the prompts for use of the JNLP API services.
  3. The highest level of access is obtained by requesting, and being granted, 'all permissions'. Then the applet should have full access to File objects, be able to communicate with servers other than the one that launched it, etc. One of the few things they would still not be permitted to do in this mode is to call System.exit(n) to effectively 'kill the JRE' - this is something that is commonly done in other desktop apps.

But then there are JRE bugs, that screw all that up. Sun, then Oracle, kept stuffing up security so poorly (& regularly) that many browser manufacturers are entirely removing the support for applets (and other embedded objects requiring plug-ins) in web pages.

See Java Plugin support deprecated and Moving to a Plugin-Free Web for more detail.

..how much trust do I need to have in a publisher before I run their applet in the web browser?

I cannot answer for you, but my take would be that I would need to know them personally, and trust completely both their integrity and competence before I'd run their code in any browser I controlled.

Having said that, I don't think I have a single browser installed that even supports applets, and my complete lack of motivation to set something up, is probably a good view on whether I'd allow applets to run on this PC at all.

Question:

I am trying to copy few jar files from web-inf/lib folder to src/main/webapp/applet folder which are all the required archive for applets so that jar files present in the output war file.

I want this copy operation need to be performed during maven build.Already I tried two options one with

maven-war-plugin which goes below.

<webResources>
    <resource>      
        <directory>src/main/webapp/WEB-INF/lib</directory>
        <filtering>true</filtering>
        <includes>
            <include>**/*.jar</include>
        </includes>
        <targetPath>${basedir}/src/main/webapp/applet</targetPath>
    </resource>
</webResources>

and the trace of the build goes below.

[INFO] --- maven-war-plugin:2.6:war (default-war) @ myapp ---
[INFO] Packaging webapp
[INFO] Assembling webapp [myapp] in [C:\jboss_projects\myapp\src\main\webapp]
[INFO] Processing war project
[INFO] Copying webapp webResources [C:\jboss_projects\myapp\src/main/webapp/WEB-INF/lib] to [C:\jboss_projects\myapp\src\main\webapp]
[INFO] Webapp assembled in [999 msecs]
[INFO] Building war: C:\jboss_projects\myapp\target\myapp.war

The next try is with maven-resources-plugin which goes below.

<plugin>
    <artifactId>maven-resources-plugin</artifactId>
    <version>2.6</version>
    <executions>
        <execution>
            <id>copy-resources</id>
            <phase>validate</phase>
            <goals>
                <goal>copy-resources</goal>
            </goals>
            <configuration>
                <outputDirectory>${basedir}/src/main/webapp/applet</outputDirectory>
                <overwrite>true</overwrite>
                <resources>
                    <resource>
                        <directory>src/main/webapp/WEB-INF/lib</directory>
                        <filtering>true</filtering>
                        <includes>
                            <include>**/*.jar</include>
                        </includes>
                    </resource>
                </resources>
            </configuration>
        </execution>
    </executions>
</plugin>

Note: in both trials I found the applet folder created inside webapp while updating project but during build that folder is not modified/created.

Any advice would be much appreciated.Please don't mark this as a duplicate every reference i looked into helps how to copy from a source to web-inf/lib folder. not this one.


Answer:

wemu suggestion worked.This is how it is configured to get the dependent jars from local repo.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <version>${maven-dependency-plugin.version}</version>
    <executions>
        <execution>
            <id>applet-dependencies</id>
            <phase>prepare-package</phase>
            <goals>
                <goal>copy</goal>
            </goals>
            <configuration>
                <artifactItems>                                 
                    <artifactItem>
                        <groupId>com.xxx.yyy</groupId>
                        <artifactId>yyy</artifactId>
                        <version>1.0</version>
                        <type>jar</type>
                        <overWrite>true</overWrite>
                        <outputDirectory>${basedir}/src/main/webapp/applet</outputDirectory>
                        <destFileName>yyy.jar</destFileName>
                    </artifactItem>
                </artifactItems>
            </configuration>
        </execution>
    </executions>
</plugin>

Question:

I'm working in an application based on Applets, with Swing and awt. My current task is to replace the call to an applet by a given web site, let say instead of opening an old applet I have to open the address https://stackoverflow.com/. After a short discussion with my technical supervisor he advised me to enbed the web site into the applet.

The issue is the following:

  • Can We embed a web site into an applet?
  • If yes, how? May be embedding the site into a JPanel, isn't it?

I did found plenty of ways of embedding an applet into a html page but not the other way around.

Thanks a lot in advance!

EDIT: As a matter of completing the question I finally found some links on Stackoverflow that may help someonelse:

  • Best Java/Swing browser component?
  • Embed Firefox browser in Java Swing
  • Display a webpage inside a swing application

Answer:

I am unsure if this will work in an applet since the example is for desktop use, however see this Oracle Example on creating a Swing Browser.

This utilizes the WebEngine class as part of JavaFX.

Question:

When developing a Java web-based application, is it necessary to use AWT?

I've been researching this question and the answers are confusing. Take for example, Runescape. The user visits the website and can play the game right there. They can also download a desktop application to play the game with.

If I am developing a game application, and my main window is created in a JFrame but all of my graphics are processed in a JPanel inside the main window, will I be able to implement this inside of a web page without much difficulty in the future? I want my game to be accessible simply by visiting the website and running the application.

Additionally, I've seen people reference "Java Web Start". Will this load the java application inside of the website, or does it install/run Java and execute the program (so if my main function opens a JFrame, it would appear on your taskbar). Perhaps I'm having some confusion between a Java application and a Java applet.


Answer:

..will I be able to implement this inside of a web page without much difficulty in the future?

No. The security environment around applets was made much stronger in recent times, but even then, browsers tend to put further hurdles between applets and 'onscreen, loaded applets'. Chrome is set to remove the plug-in which would normally embed applets and a few other things.

I want my game to be accessible simply by visiting the website and running the application.

Additionally, I've seen people reference "Java Web Start". ..

Yes, offering a link to a JWS launched JFrame will be a lot easier, and a better experience for the end user.

Question:

I have a C++ library that I have compiled for OS X, Windows & Unix. For each one I have created a separate project in Eclipse and have exported them with the name convention: library-OS.jar.

Each jar basically contains:

library-OS.jar |

-> library.ext

What I was thinking was from my main Jar applet to load them by extracting them to a temp location and using system.loadlibrary.

Unfortunately I don't know how to get the resource.

I was trying to do it using Extract and load DLL from JAR but it is for relative paths and not online browser applets.

So my question is how to load the C library based on the OS of the client. I'm using JNI to talk to it and that one is in a separate JAR as well which loads the library. I was looking into JNLP but I don't know how to get the Jar name if I use JNLP. :/

EDIT:

public static void loadJarDll(String name) throws IOException {
    InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(name);
    byte[] buffer = new byte[1024];
    int read = -1;
    File temp = new File(new File(System.getProperty("java.io.tmpdir")), name);
    FileOutputStream fos = new FileOutputStream(temp);

    while((read = in.read(buffer)) != -1) {
        fos.write(buffer, 0, read);
    }
    fos.close();
    in.close();

    System.load(temp.getAbsolutePath());
}

This is the code I'm currently using. In order to load the library I pass the name variable which MUST contain the extension of the library. What I want to do is just request the library with it's generic name for each OS (like if it's foobar.dll for windows and foobar.so for unix to just call it foobar when loading). I want to load it like this because when I use JNLP I will only have one JAR containing the native library for that specific OS and platform.


Answer:

Java Web Start already has inbuilt support for partitioning and loading natives.

  1. Partitioning: Add the Jar to a system specific resources section. Each OS will only download the resources intended for it.
  2. Loading: Put the natives in the root of the Jar mentioned above, and it will be extracted and placed on the run-time class-path of the app.

Question:

I'm working on a project where the idea is to estimate a price and send all via e-mail so that the person can then be contacted.

I have created an applet that works exactly how I want it to. It gets the required information and sends it via e-mail. The problem is that when I start the application in a browser the e-mail never gets sent.

I cannot seem to get my head around what I am missing. I have the .java file and the .class file, I also have a simple .html file to start the code in the web page

<html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<body>
<applet code=priceCalculator.Calculator1.class archive="javax.mail-1.5.5.jar" width="450" height="400" >
</applet>
</body>
</html>

What else am I missing? Do I need another file, or am I missing code from the html file?


Answer:

As been said in the comments Applets can only open network connections to the host from where they were downloaded. So unless the mail server is running on the same host you are not going to be able send the mail.

You can read the What Applets Can and Cannot Do to see the limitations

Question:

On our company we have the solution inside web application where customer on web application can pre-define paths to files on disk (i.e: c:/invoices/summary.txt).

Afterwards by Java Applet we are reading files under defined paths to web application and modify the files on user disk.

Yes - here the problem appears - the Java Applets. The Chrome does not support it anymore and it is a legacy / unsecured solution. We are looking the replacement for this solution which allows us to modify the files on user disk and will support different Browsers / OS.

We considered the following solutions:

  • dedicated external apps for OS which will be upload the defined files to our system (like Dropbox) but the problem is that we have to develop application for various OS and support it - a lot of work
  • WebDav API and solution where customer download the script from web app and run it, script upload the files to server - the problem is that the script could be error prone
  • HTML 5 solutions - we considered it but we want to achieve the situation that user defines the path only once

Does anyone see other sensible solutions for this case worth to try?


Answer:

You may consider using Microsoft Silverlight in place of Java applets. It has read-write access to local filesystem (only trusted ones). You can create silverlight app in Visual Studio which can run both as local application and as a web applet.

A simple code to write file in C# (Silverlight 4) would be

public void WriteFile(object sender, RoutedEventArgs event) {
    string path = System.IO.Path.Combine(Environment.GetFolerPath(Environment.SpecialFolder.MyDocuments), "TextFile.txt");

    /// or

    string other_path = "C:/invoices/summary.txt";

    StreamWriter writer;
    if (!File.Exists(path))
        writer = File.CreateText(path);

    writer.Write("Some text to write");
    writer.Close();
}

You can read more about creating trusted applications with silverlight.

Question:

I have a web page to test ,in which an java applet also runs.When i logon to the page it takes 30 to 50 seconds to load the java applet and it is showing java unsigned applet security alert.So when i run my selenium scripts,the execution is getting stopped whenever this alert popped.I cannot able to accept the java alert because i don't know when it is going to pop.

So my problem here is , I was forced to wait until my applet loads applet alert comes, accept it and then execute my steps.Is there a way to write a listener kind of a thing so that whenever the java security alert comes it should automatically accept the alert and continue with the execution of my script.


Answer:

If i understand your question correctly, you want to poll the presence of the alert on screen.

To correctly wait for Alert, you got WebDriverWait implemented especially for it:

WebDriverWait wait = new WebDriverWait(driver, 5); //5 seconds wait
element.click() //trigger for alert to appear
wait.until(ExpectedConditions.alertIsPresent());

Now you can handle the alert:

Alert alert = driver.switchTo().alert();
alert.accept(); //Accepting the alert

Of course, instead of accepting you can do something else, according to this.

Also, you can implement some simple alert validation like this:

public Boolean isAlertExistAndAccepted(WebDriver driver) {
        try {
            Alert alert = driver.switchTo().alert();
            alert.accept();
            return true;
        } catch (NoAlertPresentException e) {
            return false;
        }
    }

In do-while mechanism something like this one:

do {

} while ( !isAlertExist() );

Question:

I am using JNLP to load an Applet on browser. My applet is running fine with java version Java 1.7.0_25 but facing problem when running with Java 1.7.0_45. My error stacktrace is as follows

NLParseException[ Could not parse launch file. Error at line 6.]
 at com.sun.javaws.jnl.XMLFormat.throwNewException(Unknown Source)
 at com.sun.javaws.jnl.XMLFormat.parse(Unknown Source)
 at com.sun.javaws.jnl.LaunchDescFactory.buildDescriptor(Unknown Source)
 at com.sun.javaws.jnl.LaunchDescFactory.buildDescriptor(Unknown Source)
 at com.sun.javaws.jnl.LaunchDescFactory._buildDescriptor(Unknown Source)
 at com.sun.javaws.jnl.LaunchDescFactory.buildDescriptor(Unknown Source)
 at com.sun.javaws.jnl.LaunchDescFactory.buildDescriptor(Unknown Source)
 at sun.plugin2.applet.JNLP2Manager.initialize(Unknown Source)
 at sun.plugin2.main.client.PluginMain.initManager(Unknown Source)
 at sun.plugin2.main.client.PluginMain.access$200(Unknown Source)
 at sun.plugin2.main.client.PluginMain$2.run(Unknown Source)
 at java.lang.Thread.run(Unknown Source)
Error while initializing manager: JNLParseException[ Could not parse launch file. Error at line 6.], bail out

My jnlp file is

<%@page contentType="application/x-java-jnlp-file" pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<?xml version="1.0" encoding="UTF-8"?>
<jnlp spec="1.0+" codebase="ds">
    <information>
        <title>D S Applet</title>
        <vendor>ABC</vendor>
    </information>
    <security>
      <all-permissions/>
    </security>
    <resources>
        <!-- Application Resources -->
        <j2se version="1.6+" href="http://java.sun.com/products/autodl/j2se"/>
        <jar href="ds.jar" main="true"/>
    </resources>
    <applet-desc name="MyApplet" main-class="pkg.MyApplet" width="600" height="600">
        <param name="separate_jvm" value="true"/>
        <param name="urlToGetFilesFromServer" value="${urlToGetFilesFromServer}"/>       
        <param name="urlToSendFilesToServer" value="${urlToSendFilesToServer}"/>
        <param name="recordIds" value="${recordIds}"/>
        <param name="urlAfterSuccess" value="${urlAfterSuccess}"/>
        <param name="jsonMapOfFilenameAndChecksum" value='${jsonMapOfFilenameAndChecksum}'/>
        <param name="checksumOfJson" value='${checksumOfJson}'/>
        <param name="pkcsConfigFilePath" value="${pkcsConfigFilePath}" />
    </applet-desc>
    <update check="background"/>
</jnlp>

I am not getting the problem - problem with my jnlp file or problem with java version?


Answer:

Problem was in my server side code, not in JNLP file.

Question:

I have an web application which connect with a security by javaCV. My applet Works perfectly when I execute in the desktop. However, when I integrate this in my JSF page, there are no errors, but the instance of OpenCVFrameGrabber does not start. why? Below is how I call the Applet in the web page (all dependencies are already in the jar):

<applet code="com.br.spacnet.camera.CameraApplet" archive="CameraApplet.jar" width="1000" height="1000"/>

Below is the source code of the applet (here I'm using local camera connection for test purposes):

try {

    OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(0);
    jLabel1.setText(jLabel1.getText() + "; instanciou o grabber");
    //grabber.setFormat("mjpeg");
    grabber.start();
    jLabel1.setText(jLabel1.getText() + "; iniciou o Grab");
    opencv_core.IplImage frame = grabber.grab();

    while (jPanel1.isVisible()) {
        jLabel1.setText(jLabel1.getText() + "; entrou no laço");

        jPanel1.getGraphics().drawImage(frame.getBufferedImage(), 0, 0, 320, 240, null);
        jLabel1.setText(jLabel1.getText() + "; redesenhou painel");

    }
    grabber.stop();
    jLabel1.setText(jLabel1.getText() + "; parou o grabber");
    System.exit(0);
} catch (Exception ex) {

    jLabel1.setText("Erro " + ex.getMessage());
}

Answer:

Thanks, Andrew Thompson! I enabled my Java Console and I could see several security bloks of JRE. So, I added the following lines to the java.policy, and it worked fine:

permission java.util.PropertyPermission "org.bytedeco.javacpp.loadlibraries", "read";

permission java.util.PropertyPermission "org.bytedeco.javacpp.platform", "read";

permission java.security.AllPermission;

permission java.lang.RuntimePermission "shutdownHooks";

Question:

I am developing a Web page using jsp and html where in I need to read/write from/to a Device connected on Client's System who are accessing the Webpage. The Device is a Serial Device which is connected as COM1(Eg) in Windows. I went through different options available. I found this which serves my purpose. I started learning JNLP for the same. I imported the project and made changes according to my needs. (This project is using jssc.jar). I generated the jar (jSSC-Terminal.jar) and signed with self-generated key. The GUI is being loaded properly but I am unable to access the Serial port on client's machine. Here is my jnlp file launch.jnlp

   <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<jnlp href="launch.jnlp" spec="1.0+"   codebase="http://192.168.1.33:8080/abc" 
    href="launch.jnlp">
    <information>
        <title>jSSC-Terminal</title>
        <vendor>scream3r</vendor>
        <homepage href="scream3r.org"/>
        <description>jSSC-Terminal</description>
        <description kind="short">jSSC-Terminal</description>

    </information>
<update check="background"/>
<security>
<all-permissions/>
</security>
    <resources>
<j2se version="1.5+"/>
<jar href="jSSC-Terminal.jar" main="true"/>

<jar href="jssc.jar" download="eager"/>



</resources>
    <applet-desc height="500" main-class="applet.Main" name="Main" width="700">

    <param name="separate_jvm" value="true"/>
<param name="draggable" value="true"/>
</applet-desc>
</jnlp>

Here is my html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
          <title>jSSC-Terminal</title>
            <style type="text/css">
              body {
                margin-left: 10px;
                margin-top: 10px;
                margin-right: 10px;
                margin-bottom: 10px;
              }
        </style>
        </head>
  <body>
  <applet code="applet.Main" archive="http://192.168.1.33:8080/abc/jSSC-Terminal.jar, http://192.168.1.33:8080/amar/lib/jssc.jar" width="700" height="500">
      <param name="separate_jvm" value="true"/>
      <param name="draggable" value="true"/>
          </applet>
        </body>
</html>

I have placed all these files in Tomcat directory as below

/Tomcat/webapps/abc/launch.jnlp
/Tomcat/webapps/abc/jSSC-Terminal.jar
/Tomcat/webapps/abc/index.html
/Tomcat/webapps/abc/lib/jssc.jar

I am unable to get the SerialPort List when run as jnlp. Kindly help me out with a fix if available. Or are there any alternate things available in JSP. Thanks and Regards.

Edit :

Finally found out thank you. I replaced my applet tag and included jnlp location as below :

<applet code="applet.Main" archive="http://192.168.1.33:8080/abc/jSSC-Terminal.jar,    http://192.168.1.33:8080/abc/lib/jssc.jar,"http://192.168.1.33:8080/abc/test.jnlp" width="700" height="500">
      <param name="separate_jvm" value="true"/>
      <param name="draggable" value="true"/>
          </applet>
        </body>

Answer:

Your <applet> tag doesn't refer to the .jnlp file. You give access to COM ports in the jnlp file but it's not being used. You have to either use the jnlp file or set permissions in the <applet> tag.

Your link to the jssc example is a page that shows how to use the jnlp file from the <applet> tag.

I've done what you are trying to do with a Java Webstart app and the PureJavaComm library. I bet what you are doing will work once you get the permissions right, though. But if you want to have a look at how I set this up the jnlp file is here: https://bitminter.com/client/bitminter.jnlp (live app)

Question:

I have checked to make sure my Java is up-to-date and enabled. I ran the command java -showversion in cmd, output:

java version "1.8.0_65"

Java(TM) SE Runtime Environment (build 1.8.0_65-b17)

Java HotSpot(TM) 64-bit Server VM (build 25.65-b01, mixed mode)

And to check if enabled, I am using Internet Explorer, went to Tools --> Internet Options --> Security Tab --> Custom Level --> Scripting Of Java Applets --> Enabled

The applet will not run. . . I am new to Java, any help would be appreciated.

Simple HTML:

 <!DOCTYPE html>
 <html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=us-ascii">
 <title>Applet</title>
 </head>
 <body>
 <APPLET CODE="http://www.example.com/dir/applet.class" width=400 height=400></APPLET> 
 </body>
 </html>

Java Code:

 import javax.swing.*;
 import java.awt.*;

 public class javaClass extends JApplet {

     public void init()
     {
         JLabel label = new JLabel("My Example label.!?");
         setLayout(new FlowLayout());
         add(label);
     }

 }

Answer:

The applet code (in the <body>) is attempting to access the applet class in the dir directory in example.com, which I would presume is incorrect.

What you would want instead, assuming that the HTML file is in the same directory as the javaClass is the following as the <body>:

<body>
<APPLET CODE = "javaClass.class" WIDTH=400 HEIGHT=400></APPLET>
</body>

The reason this works is because the string after CODE = looks for the compiled class within the same directory of the corresponding Java source code. This means that you need to compile javaClass before it can be run as an applet: either within an IDE (such as NetBeans, Eclipse, or IntelliJ) or by using the javac command.

Then to actually view the applet, open the HTML file in your browser.

(Personally, I would use this cmd command: appletviewer javaClass.html instead of opening it in the browser (assuming the html file is called javaClass))

Question:

I am having a java application and using JDialog in it. I am using setMinimumSize(640,400). And whenever user resizes the dialog to some custom height and width. This new dimension has to be saved such that next time when the user loads the same dialog, it should render in new user customized dimension instead of minimum size.

Can someone help me how to store the new dimension in all the user sessions .?


Answer:

There are any number of possible solutions you might use

You could...

Use the Properties API. This just class backed by a HashMap but it can easily be saved and loaded.

This API provides you with full control over where the file is saved, so you would probably want to save to to the user.home location to associate it with a given user.

Have a look at the Properties trail for more details

You could...

Use the Preference API. It provides some useful functionality which allows you to define the context in which the values are stored (ie the user or system) and it controls the storage of the values itself, so you don't need to worry about trying to save or load the values yourself

Have a look at the JavaDocs for more details

You could...

Simply write the data to a file yourself, using JSON, XML or simply plain old text. This is complicated and requires a decent amount of work, but gives you complete control

You could...

Store the values in some kind of database system, if you have one available

No matter choice you use, you'll probably find you need to write the width and height properties out individually

How to get the dialog size?

Well, that would depend on a lot on what you are already doing. For example, I might be tempted to create a custom dialog, which when closed, wrote out the size properties itself. It would also load them itself it was constructed, this way, you're just relying on JDialog#getSize

Question:

Im using Oracle JRE 9.1, and trying to execute an applet (Oracle Forms) through Java Web Start. On my JNLP file its defined by the tag applet-desc.

It works on Oracle Java 6,7 and 8. But with the version 9, i get the following error:

java.lang.IllegalAccessError: class oracle.forms.engine.Main
 (in unnamed module ... ) cannot access class sun.applet.AppletViewer 
(in module java.desktop) because module java.desktop does not
 export sun.applet to unnamed module ...

I know that applets are deprecated on 9, but it should be only a warning right ?

Any ideas would be appreciated.


Answer:

Java 9 is not supported by Oracle Forms. You should still use Java 8.

They have also posted an article that says that Oracle Forms won't support java 9 in the future.

Question:

I am writing a program for my school final project. I wrote the whole project with frames, only to find out it needs to be an applet. So I tried converting everything but it does not work.

Source Code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.applet.Applet;
public class AlteredBattleship extends Applet implements ActionListener{
  int ro;//holds row input
  int co;//holds column input
  int[][] shots=new int[10][10];//holds all shots taken
  boolean displayLose=false;//boolean triggers if game is lost
  boolean displayWin=false;//boolean triggers if game is won
  //the next six variables hold how many parts of ships haven't been hit
  int two=2;
  int three=3;
  int four=4;
  int threeTwo=3;
  int five=5;
  //boolean triggers if a boat is sunk
  boolean twoSunk=false;
  boolean threeSunk=false;
  boolean threeTwoSunk=false;
  boolean fourSunk=false;
  boolean fiveSunk=false;
  //holds difficulty
  boolean b=true;
  boolean n=false;
  boolean e=false;
  ArrayList<Integer> misses= new ArrayList<Integer>();//holds all missed  shots
  ArrayList<Integer> hits= new ArrayList<Integer>();//holds all hit shots
  int shotCount=75;//how many shots player has to win
  int[][] board=new int[10][10];//holds all ship positions
  JApplet main =new JApplet();//holds all graphics
  TextField input=new TextField(2);//takes input from player
  TextField count=new TextField(2);//displays shots left
  public void actionPerformed(ActionEvent e) { 
  };
  //places the four long ship
  public void placeFour(){
    int fourStartx=(int)(Math.random()*5);
    int fourStarty=(int)(Math.random()*9);
    for(int i=0; i<4; i++){
      board[fourStartx+i][fourStarty]=4;
    }
  }
  //places the three long ship
  public void placeThree(){
    int threeStartx=(int)(Math.random()*9);
    int threeStarty=(int)(Math.random()*6);
    if(board[threeStartx][threeStarty]==0&& board[threeStartx][threeStarty+1]==0&&board[threeStartx][threeStarty+2]==0){
      board[threeStartx][threeStarty]=3;
      board[threeStartx][threeStarty+1]=3;
      board[threeStartx][threeStarty+2]=3;
    }
    else
      this.placeThree();
  }
  //places the two long ship
  public void placeTwo(){
    int twoStartx=(int)(Math.random()*7);
    int twoStarty=(int)(Math.random()*9);
    if(board[twoStartx][twoStarty]==0&& board[twoStartx+1][twoStarty]==0){
      board[twoStartx][twoStarty]=2;
      board[twoStartx+1][twoStarty]=2;
    }
    else
      this.placeTwo();
  } 
  //places the second three long ship
  public void placeThreeTwo(){
    int threeStartx=(int)(Math.random()*6);
    int threeStarty=(int)(Math.random()*9);
    if(board[threeStartx][threeStarty]==0&& board[threeStartx+1][threeStarty]==0&&board[threeStartx+2][threeStarty]==0){
      board[threeStartx][threeStarty]=6;
      board[threeStartx+1][threeStarty]=6;
      board[threeStartx+2][threeStarty]=6;
    }
     else
       this.placeThreeTwo();
  }
  //places the five long ship
  public void placeFive(){
    int twoStartx=(int)(Math.random()*9);
    int twoStarty=(int)(Math.random()*4);
    if(board[twoStartx][twoStarty]==0&& board[twoStartx][twoStarty+1]==0&& board[twoStartx][twoStarty+2]==0&& board[twoStartx][twoStarty+3]==0&& board[twoStartx][twoStarty+4]==0){
      board[twoStartx][twoStarty]=5;
      board[twoStartx][twoStarty+1]=5;
      board[twoStartx][twoStarty+2]=5;
      board[twoStartx][twoStarty+3]=5;
      board[twoStartx][twoStarty+4]=5;
    } 
    else 
      this.placeFive();
  } 
  //this method creates the frame and builds the interactable parts of the GUI
  public void init() {
    main = new JApplet();
    DrawPanel drawPanel = new DrawPanel();
    main.add(drawPanel);
    JPanel holder=new JPanel();
    JPanel line=new JPanel();
    JPanel space=new JPanel();
    space.setMaximumSize(new Dimension(50,150));
    space.setBackground(Color.lightGray);
ButtonGroup level=new ButtonGroup();//holds all difficulty radioButtons
JRadioButton beginner = new JRadioButton();//beginner difficulty button
beginner.setSelected(true);
beginner.setBackground(Color.lightGray);
beginner.addActionListener(new ActionListener() { //makes the button set difficulty to beginner
public void actionPerformed(ActionEvent i) { 
  b=true;
  n=false;
  e=false;
} 
});
space.add(beginner);//adds button to panel
JRadioButton normal = new JRadioButton();//normal difficulty button
normal.setBackground(Color.lightGray);
space.add(normal);//adds button to panel
normal.addActionListener(new ActionListener() { //makes the button set difficulty to normal
public void actionPerformed(ActionEvent i) { 
  b=false;
  n=true;
  e=false;
} 
});
JRadioButton expert = new JRadioButton();
expert.setBackground(Color.lightGray);
expert.addActionListener(new ActionListener() {//makes the button set difficulty to expert 
public void actionPerformed(ActionEvent i) { 
  b=false;
  n=false;
  e=true;
} 
});
space.add(expert);//adds button to panel
level.add(beginner);
level.add(normal);
level.add(expert);
count.setEditable(false);
count.setText(Integer.toString(shotCount));
line.setMaximumSize(new Dimension(105,100));
line.setBackground(Color.lightGray);
line.add(count);
holder.setLayout(new BoxLayout(holder, BoxLayout.Y_AXIS));//creates panel that holds all other panels
holder.setMaximumSize(new Dimension(20,50));
JPanel inputHold=new JPanel();//creates panel that holds input textField
inputHold.setMaximumSize(new Dimension(40,100));
inputHold.add(input);//adds textField to panel
//makes input take shot and put it through program
input.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) { 
  String row=input.getText().substring(0,1);//makes the first letter of input the row
  String column=input.getText().substring(1,input.getText().length());//makes number portion column
  ro=row.compareTo("A");//makes row a number representation
  co=Integer.parseInt(column)-1;//makes the String into int
  if(row.compareTo("A")<10 && Integer.parseInt(column)<=10&&shots[ro][co]==0){//makes sure shot is in bounds and not already called
    if(board[ro][co]==0){//checks for miss
      misses.add(ro);
      misses.add(co);
    }
    else{//makes sure it's a hit
      hits.add(ro);
      hits.add(co);
      if(board[ro][co]==2){//checks if hit is two ship
        two--;
        if (two==0)//checks to see if two is sunk
          twoSunk=true;
      }
      else if(board[ro][co]==3){//checks if hit is three ship
        three--;
        if (three==0)//checks to see if three is sunk
          threeSunk=true;
      }
      else if(board[ro][co]==6){//checks if hit is other three ship
        threeTwo--;
        if(threeTwo==0)//checks if other three ship is sunk
          threeTwoSunk=true;
      }
      else if(board[ro][co]==4){//check if hit is four ship
        four--;
        if (four==0)//check if four ship is sunk
          fourSunk=true;
      }
      else if(board[ro][co]==5){//check if hit is five ship
        five--;
        if(five==0)//check if five ship is sunk
          fiveSunk=true;
      }
    }
    shotCount--;//takes away a shot
    shots[ro][co]=1;//remembers spot as an already taken shot
  }
  if(twoSunk&&threeSunk&&fourSunk&&threeTwoSunk&&fiveSunk){//checks for win status
    displayWin=true;
  }
  input.setText("");//resets textField
  //frame.repaint();//resets board with new shot
  count.setText(Integer.toString(shotCount));//resets shotCount to new number
  if(shotCount==0){//checks for lose status
    displayLose=true;
    input.setEditable(false);
  }

} 
});
JPanel spacer=new JPanel();
JButton newB=new JButton("New Game");//creates new game button
newB.addActionListener(new ActionListener() { //makes button work
public void actionPerformed(ActionEvent i) {
  //resets all variables to new game status
  displayLose=false;
  displayWin=false;
  twoSunk=false;
  threeSunk=false;
  threeTwoSunk=false;
  fourSunk=false;
  fiveSunk=false;
  two=2;
  three=3;
  threeTwo=3;
  four=4;
  five=5;
  misses= new ArrayList<Integer>();
  hits= new ArrayList<Integer>();
  if(b)
    shotCount=75;
  else if(n)
    shotCount=65;
  else if(e)
    shotCount=50;
  count.setText(Integer.toString(shotCount));
  board=new int[10][10];
  shots=new int[10][10];
  placeFour();
  placeThree();
  placeThreeTwo();
  placeFive();
  placeTwo();
  main.repaint();
} 
});
//adds all panels to frame
spacer.add(newB,BorderLayout.NORTH);
spacer.setBackground(Color.lightGray);
inputHold.setBackground(Color.lightGray);
spacer.setBackground(Color.lightGray);
spacer.setMaximumSize(new Dimension(100,32));
holder.add(space,BorderLayout.NORTH);
holder.add(line,BorderLayout.NORTH);
holder.add(inputHold, BorderLayout.NORTH);
holder.add(spacer,BorderLayout.SOUTH);
holder.setBackground(Color.lightGray);
main.add(holder,BorderLayout.EAST);
main.setVisible(true);
//places ships
this.placeFour();
this.placeThree();
this.placeTwo();
this.placeThreeTwo();
this.placeFive();
  }

And my html is: <EMBED type="application/x-java-applet;version=1.2" code="AlteredBattleship.class" WIDTH=680 HEIGHT=400> </EMBED> I'm sorry if the answer is really obvious I am fairly new to Java and extremely new to graphics. Thank you for your time


Answer:

You have made a mistake.

 public class AlteredBattleship extends Applet implements ActionListener

should be:

public class AlteredBattleship extends JApplet implements ActionListener

If the Applet still doesn't works, please inform.

Question:

I am having the following exception when launching a Gluon application via webstart... i understand this is not GLUON particle directly related... it seems more a problem with the jar sign. The Exception:

java.lang.RuntimeException: java.lang.ExceptionInInitializerError
at com.sun.deploy.uitoolkit.impl.awt.AWTAppletAdapter.instantiateApplet(Unknown Source)
at sun.plugin2.applet.Plugin2Manager.initAppletAdapter(Unknown Source)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.ExceptionInInitializerError
at com.gluonhq.particle.application.Particle.<init>(Particle.java:170)
at com.gluonhq.particle.application.ParticleApplication.<init>(ParticleApplication.java:89)
at mx.gob.scjn.inventario.InventarioAJ.<init>(InventarioAJ.java:22)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at com.sun.deploy.uitoolkit.impl.awt.AWTAppletAdapter$1.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: java.lang.IllegalStateException: Toolkit not initialized
    at com.sun.javafx.application.PlatformImpl.runLater(Unknown Source)
    at com.sun.javafx.application.PlatformImpl.runLater(Unknown Source)
    at com.sun.javafx.application.PlatformImpl.setPlatformUserAgentStylesheet(Unknown Source)
    at com.sun.javafx.application.PlatformImpl.setDefaultPlatformUserAgentStylesheet(Unknown Source)
    at javafx.scene.control.Control.<clinit>(Unknown Source)
... 28 more

I already create my certificates using:

keytool -genkey -keyalg rsa -alias CLS -keystore mykeyStorte

then exporting it:

keytool -export -alias CLS -file rsatest.cer -keystore mykeyStore

I imported into the java control panel and sign the jar using:

jarsigner -keystore mykeyStore InventarioAJ.jar CLS

Obviously I am missing something... ¿Any clue? Greetings After getting the answer i got a "duplicate question" mark... but the right answer is not (as i thought) JUST the security/signing part... as a matter of fact the real and important part of the answer has to do with the fact that the Application class can not be cast as an applet and that requiers another change on the JNLP file.


Answer:

That's right, Java 8 introduces some changes on JavaFX ( i really think this changes were in a later update, but that's not the point).. somehow today the JavaFX Application can't behave like an Applet, so the JNLP file has to look something like:

<?xml version="1.0" encoding="UTF-8"?>
<jnlp spec="1.0+" codebase="http://localhost/inventarioaj/" href="InventarioAJ.jnlp">
 <resources>
    <j2se version="1.8+" href=
       "http://java.sun.com/products/autodl/j2se"/>
    <jar href="/inventarioaj/InventarioAJ.jar" main="true" />
    <jar href="lib/controlsfx-8.40.10.jar"/>
    <jar href="lib/javax.inject-1.jar"/>
    <jar href="lib/particle-1.1.0.jar"/>
    <jar href="lib/h2-1.4.191.jar"/>
    <jar href="lib/eclipselink.jar"/>
    <jar href="lib/javax.persistence_2.1.0.v201304241213.jar"/>
    <jar href="lib/org.eclipse.persistence.jpa.modelgen_2.5.2.v20140319-9ad6abd.jar"/>
    <jar href="lib/org.eclipse.persistence.jpars_2.5.2.v20140319-9ad6abd.jar"/>
 </resources>
 <security>
    <all-permissions/>
 </security>
 <application-desc name="Inventario de XXXX"
 main-class="mx.xxxxx.InventarioAJ"/>

So the "applet-desc" tag was removed and replaced by the "application-desc" tag and the "security" tag should be in place to allow the application to have access to the file system as well as the network communications. If that's the case (all permissions needed) then all jars must be signed. Greetings