Hot questions for Using Applets in exception

Question:

First off, I am not a Java developer. I had to create a Java applet to invoke some code in a native DLL I wrote from the browser.

I use JNA to load a native DLL and invoke its methods. I have signed the applet using a self-signed certificate. The browser asks me whether or not to allow the execution of the applet. The applet code which loads my DLL is enclosed within AccessController.doPrivileged block.

Like this:

public String Test()
{
    pHelper = AccessController.doPrivileged(new PrivilegedAction<IHelper>() 
    {
        @Override
        public IHelper run() 
        {
            return (IHelper)Native.loadLibrary("Helper", IHelper.class);
        }
    });

    return "test";
}

The code works fine when debugged inside Eclipse.

It does not work when invoked from JavaScript. Causes PrivilegedActionException.

If I remove the entire AccessController.doPrivileged block and leave return "test" only, the code runs when invoked from JavaScript. Any code that doesn't require privileges runs fine when invoked from JavaScript.

Tested from Chrome version 40.something and Firefox 36 on Windows 8.1 64-bit. The native DLL is 32-bit as well as JRE used to run the applet.

Any tips?


Answer:

I have never resolved this particular mystery. However, I was able to find a workaround, thanks to my applet design specification which doesn't require exposing any applet methods which need to be invoked to perform privileged operations.

I have found that executing privileged operations inside the applet init() function will work. Only privileged operations executed by invoking from JavaScript seem to cause problems. Consider the following code.

public class MyApplet extends JApplet {
    private IHelper pHelper = null;
    private MyReturnedInfo pInfo = null;

    public void init() {
        pHelper = (IHelper)Native.loadLibrary("Helper", IHelper.class);
        if (pHelper != null) {
            pInfo = pHelper.GetInfo();
        }
    }

    public String GetInfoString() {
        if (pInfo != null) {
            // need to call toString to convert from native wide char to something JavaScript will be able to interpret
            return pInfo.MyInfoString.toString(); 
        }
        return null;
    }
}

Upon loading this applet, calling document.myApplet.GetInfoString() from JavaScript (providing the applet has an ID "myApplet") will return the required information.

Interestingly though, after signing the applet with a certificate issued by a trusted authority such as VeriSign, even this would not work in IE, while it would work properly in FF and Chrome. I have seen signed Java applets which work fine when called from JavaScript in IE, but I guess my applet is special because it requires all-permissions attribute in the manifest and IE probably doesn't like that. It's a guess. However, I have never found the real reason for that either, because I was able to resort to another workaround. :) If you are reading this answer then I bet you are interested in it as well.

Java applets allow us to provide additional parameters which we are able to obtain by calling this.getParameter() from inside the init() function. Also, if we allow the applet to call JavaScript functions from our HTML document by using mayscript attribute, we can easily combine these two facts to provide the JavaScript function for applet to call after the information from our native DLL has been obtained.

Let's say that in our HTML, we define the JavaScript like this.

<script type="text/javascript" src="https://www.java.com/js/deployJava.js"></script>
<script type="text/javascript">
    var attributes = {
        id: "myApplet",
        name: "myApplet",
        code: "MyApplet.class",
        mayscript: "true",
        scriptable: "true",
        archive: "/path(s)/to/jar(s)",
        width: 0,
        height: 0
   };

    var params = {
        "AppletReady": "appletInitialized",
    };

    // For convenience, it's easier to deploy the applet using deployJava,
    // so it writes the applet HTML tag for us after checking if Java is installed.
    // We have included it above.
    deployJava.runApplet(attributes, params, "1.8.0");

    function appletInitialized(myString, someOtherArgument) {
        // do something with your parameters
        // NOTE: do NOT call alert() from this function! 
        // Because it will most likely cause your browser to freeze, 
        // I've found that's also one of the things Java doesn't like.
    };
</script>

Then, we modify the Java applet code to look like this.

public class MyApplet extends JApplet {
    private IHelper pHelper = null;
    private MyReturnedInfo pInfo = null;

    public void init() {
        // Read the AppletReady parameter as passed from JavaScript
        String paramKey = "AppletReady";
        String jsLoadedCallback = this.getParameter(paramKey);

        // Load the library and get the information
        pHelper = (IHelper)Native.loadLibrary("Helper", IHelper.class);
        if (pHelper != null) {
            pInfo = pHelper.GetInfo();
            if (pInfo != null && jsLoadedCallback != null) {
                // Get the window which contains "this" applet
                JSObject jsObject = JSObject.getWindow(this);

                // Call the provided JavaScript function.
                // You can use as many parameters as you need.
                jsObject.call(jsLoadedCallback, new Object[] {
                        pInfo.MyInfoString.toString(),
                        pInfo.SomeOtherStringMaybe.toString()
                });
            }
        }
    }
}

However, if you need the applet to call your native DLL methods dynamically during runtime (I.E. you require the applet to expose functions which need to be called to perform privileged operations dynamically) this solution will not work for you and you are out of luck, at least if using JNA.

Question:

I have the following problem:

I have a Java program that receives via Applet a binary file.

I received that file with getParameter(file) and read that file with java.io.FileInputStream(file).

I put this file on web server and call the java program via javascript

First, when I was running the program, was occuring the message error:

Java.security.Access.ControlException: access denied("java.io.FilePermission" "[object file]" "read")

I created a key via keytool and signed the jar file with jarsigner.

But, even executing the command jarsigner, when I run the Java program again, the error message continues occuring:

Java.security.Access.ControlException: access denied("java.io.FilePermission" "[object file]" "read"). 

Therefore, the error persists even after signing.

I really do not know what to do.

Can anyone help me?

Below the java code:

public class InJava extends Applet{
    String parametro;    
    public void sayHello() {

        parametro = getParameter("parametro");

        java.io.FileInputStream fis = null;

        try  {
            fis = new java.io.FileInputStream(parametro);
        }
        catch (Exception e)  {
            String retorno_exc = e.toString();
            return ;
        }

    }

Answer:

You need to wrap your code in AccessController.doPrivileged, like:

public class InJava extends Applet{

  public void sayHello() {

    final String parametro = getParameter("parametro");

    FileInputStream fis =  AccessController.doPrivileged(new PrivilegedAction<FileInputStream>() {
      public FileInputStream run() {
        try  {
          retrun new FileInputStream(parametro);
        } catch (IOException e)  {
          // handle exception
        }
      }
    });
  }

Make sure that your applet jar(s) are signed, and that you understand all other consequences of running an applet.

Question:

I developed an applet in Java Card and it works fine. Now I am working on the sturdiness of this applet and more precisely, what happens if the card is deplugged during the applet execution for example.

I am wondering if there is an Exception which handle this kind of things ?

I am searching for something like :

try {
...
}
// If the card is disconnected while the applet execution
catch (Exception e) {
...
}

Thank you in advance.


Answer:

As the smart cards haven't any battery inside, you can't have any try ... catch ... like this. Alternatively you can take advantages of Transactions. The Transaction APIs are provided just for your goal. The operations that are between beginTransation() and commitTransation() methods, apply only if the commitTransation() complete successfully. And if any exeption/card tear or card reset happens before commitTransation(), everything returns to its original state (i.e. to the state that it has before beginTransaction())

It is like this :

    .
    .
    JCSystem.beginTransaction();
    //put your critical code here.
    JCSystem.commitTransaction();
    .
    .

You can also use JCSystem.commitTransaction(); to terminate a transaction in a specific situation as follow :

    .
    .
    JCSystem.beginTransaction();

    //put your critical code here.
    if (condition) {
    JCSystem.commitTransaction();
    }

    JCSystem.commitTransaction();
    .
    .

Note that:

  1. Transactions have a limited buffer in cards. So you can't put whole the program inside a transaction. But for typical critical methods, it has enough buffer size.
  2. You can't use nested Transactions.

Question:

This is my code so far:

// Imported Classes
public class Timer extends Applet
{
    public void paint (Graphics page) throws InterruptedException
    {
        Thread.sleep(1000);
    }
}

I just want to know how I can get this to work. I've used the Thread.sleep() method in other code before, but never with Graphics. I don't have much experience with Exceptions either, I usually try my best to avoid or correct them.


Answer:

You should never call methods such as Thread.sleep on the event dispatch thread (i.e. in paint methods). This will render the whole GUI unresponsive.

You should instead use timers such as SwingTimer to perform animations etc. See the following related questions:

  • how to use a swing timer to start/stop animation
  • Java Applet Thread Animation
  • How to make applet animation?
  • Drawing images continuously in Java Applet

Question:

when i run the code below,

-in an Applet on JRE8, on the line con.getInputStream() it throws the exception

-in an Applet on JRE7 or JRE6 it does not throws.

-in a Desktop app on any JRE it does not throws.

when i remove the lines starts with setRequestPropery, it does not throws the exception on any JRE.

        URLConnection con = new URL(adress).openConnection();
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setUseCaches(false);
        con.setRequestProperty("Content-Type",
                "application/octet-stream");
        con.setRequestProperty("pragma:", "no-cache");
        PrintStream ps = new PrintStream(con.getOutputStream());
        ps.println("Test");
        ps.close();
        in = new DataInputStream(conn.getInputStream());

Exception:

java.lang.IllegalArgumentException: invalid actions string
at java.net.URLPermission.init(Unknown Source)
at java.net.URLPermission.<init>(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.URLtoSocketPermission(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown Source)

In my applet, i am trying to open a connection and i need those request properties.

Do you know what causes this exception on JRE8? and why only in an applet and not desktopapp.


Answer:

Debugin your code snippet in an applet, shows that the parameter actions passed to URLPermission, which ist new win java8, has the value GET:pragma: which is not valid according to javadoc for that argument:

The actions string of a URLPermission is a concatenation of the method list and the request headers list. These are lists of the permitted request methods and permitted request headers of the permission (respectively). The two lists are separated by a colon ':' character and elements of each list are comma separated. Some examples are:

     "POST,GET,DELETE"
     "GET:X-Foo-Request,X-Bar-Request"
     "POST,GET:Header1,Header2"

and according to the code in oracle's jdk8:

int colon = actions.indexOf(':');
if (actions.lastIndexOf(':') != colon) {
    throw new IllegalArgumentException("invalid actions string");
}

The code above expects one single colon or none.

To solve the problem you need to remove the colon after pragma in your call

con.setRequestProperty("pragma", "no-cache");

Running your snippet as simple junit test does not provoke this exception, because the URLPermition class is not invoked. Whether it invoked or not depends on the context where the application is running.

Note. Depending on the context of use, some request methods and headers may be permitted at all times, and others may not be permitted at any time. For example, the HTTP protocol handler might disallow certain headers such as Content-Length from being set by application code, regardless of whether the security policy in force, permits it.

So it seems, when in the context of an applet some permition checks are performed.

Question:

In my web application, I am using a applet which is signed jar and this applet was working fine before jre 1.6 and 1.7. But after security popup and blocking error of applet we had to purchased a java code signing certificate.

I have signed this applet jar successfully and this applet is running without any problem on HTTP protocol. If I open this applet on HTTPS, it start giving exceptions of SSLHandshakeException. I have tried every possible solution to run this but it failed.

*Java Plug-in 11.25.2.18
Using JRE version 1.8.0_25-b18 Java HotSpot(TM) Client VM
User home directory = C:\Users\home
----------------------------------------------------
c:   clear console window
f:   finalize objects on finalization queue
g:   garbage collect
h:   display this help message
l:   dump classloader list
m:   print memory usage
o:   trigger logging
q:   hide console
r:   reload policy configuration
s:   dump system and deployment properties
t:   dump thread list
v:   dump thread stack
x:   clear classloader cache
0-5: set trace level to <n>
----------------------------------------------------
basic: Added progress listener: sun.plugin.util.ProgressMonitorAdapter@1d2bd52
security: Expected Main URL: https://www.example.com/test.jar
basic: Plugin2ClassLoader.addURL parent called for https://www.example.com/test.jar
security: Accessing keys and certificate in Mozilla user profile: null
security: JSS is not configured
network: Cache entry not found [url: https://www.example.com/test.jar, version: null]
network: Connecting https://www.example.com/test.jar with proxy=DIRECT
network: Cache entry not found [url: file:/C:/Program%20Files/Java/jre1.8.0_25/lib/ext/sunec.jar, version: null]
network: Cache entry not found [url: file:/C:/Program%20Files/Java/jre1.8.0_25/lib/ext/sunjce_provider.jar, version: null]
network: Connecting http://www.example.com:443/ with proxy=DIRECT
javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
    at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(Unknown Source)
    at sun.plugin.PluginURLJarFileCallBack.connect(Unknown Source)
    at sun.plugin.PluginURLJarFileCallBack.retrieve(Unknown Source)
    at sun.net.www.protocol.jar.URLJarFile.retrieve(Unknown Source)
    at sun.net.www.protocol.jar.URLJarFile.getJarFile(Unknown Source)
    at sun.net.www.protocol.jar.JarFileFactory.get(Unknown Source)
    at sun.net.www.protocol.jar.JarURLConnection.connect(Unknown Source)
    at sun.plugin.net.protocol.jar.CachedJarURLConnection.connect(Unknown Source)
    at sun.plugin.net.protocol.jar.CachedJarURLConnection.getJarFileInternal(Unknown Source)
    at sun.plugin.net.protocol.jar.CachedJarURLConnection.getJarFile(Unknown Source)
    at com.sun.deploy.security.DeployURLClassPath$JarLoader.getJarFile(Unknown Source)
    at com.sun.deploy.security.DeployURLClassPath$JarLoader.access$800(Unknown Source)
    at com.sun.deploy.security.DeployURLClassPath$JarLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.deploy.security.DeployURLClassPath$JarLoader.ensureOpen(Unknown Source)
    at com.sun.deploy.security.DeployURLClassPath$JarLoader.<init>(Unknown Source)
    at com.sun.deploy.security.DeployURLClassPath$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.deploy.security.DeployURLClassPath.getLoader(Unknown Source)
    at com.sun.deploy.security.DeployURLClassPath.getLoader(Unknown Source)
    at com.sun.deploy.security.DeployURLClassPath.getResource(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader$2.run(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader$2.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.plugin2.applet.Plugin2ClassLoader.findClassHelper(Unknown Source)
    at sun.plugin2.applet.Applet2ClassLoader.findClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadCode(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.io.EOFException: SSL peer shut down incorrectly
    at sun.security.ssl.InputRecord.read(Unknown Source)
    ... 42 more
network: Cache entry not found [url: https://www.example.com/test.jar, version: null]
network: Connecting https://www.example.com/test.jar with proxy=DIRECT
network: Connecting http://www.example.com:443/ with proxy=DIRECT
javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
    at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(Unknown Source)
    at sun.plugin.PluginURLJarFileCallBack.connect(Unknown Source)
    at sun.plugin.PluginURLJarFileCallBack.retrieve(Unknown Source)
    at sun.net.www.protocol.jar.URLJarFile.retrieve(Unknown Source)
    at sun.net.www.protocol.jar.URLJarFile.getJarFile(Unknown Source)
    at sun.net.www.protocol.jar.JarFileFactory.get(Unknown Source)
    at sun.net.www.protocol.jar.JarURLConnection.connect(Unknown Source)
    at sun.plugin.net.protocol.jar.CachedJarURLConnection.connect(Unknown Source)
    at sun.plugin.net.protocol.jar.CachedJarURLConnection.getJarFileInternal(Unknown Source)
    at sun.plugin.net.protocol.jar.CachedJarURLConnection.getJarFile(Unknown Source)
    at com.sun.deploy.security.DeployURLClassPath$JarLoader.getJarFile(Unknown Source)
    at com.sun.deploy.security.DeployURLClassPath$JarLoader.access$800(Unknown Source)
    at com.sun.deploy.security.DeployURLClassPath$JarLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.deploy.security.DeployURLClassPath$JarLoader.ensureOpen(Unknown Source)
    at com.sun.deploy.security.DeployURLClassPath$JarLoader.<init>(Unknown Source)
    at com.sun.deploy.security.DeployURLClassPath$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.deploy.security.DeployURLClassPath.getLoader(Unknown Source)
    at com.sun.deploy.security.DeployURLClassPath.getLoader(Unknown Source)
    at com.sun.deploy.security.DeployURLClassPath.getResource(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader$2.run(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader$2.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.plugin2.applet.Plugin2ClassLoader.findClassHelper(Unknown Source)
    at sun.plugin2.applet.Applet2ClassLoader.findClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadCode(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.io.EOFException: SSL peer shut down incorrectly
    at sun.security.ssl.InputRecord.read(Unknown Source)
    ... 40 more
network: Cache entry not found [url: https://www.example.com/Apps.class, version: null]
network: Connecting https://www.example.com/Apps.class with proxy=DIRECT
network: Connecting http://www.example.com:443/ with proxy=DIRECT
network: Cache entry not found [url: https://www.example.com/Apps/class.class, version: null]
network: Connecting https://www.example.com/Apps/class.class with proxy=DIRECT
network: Connecting http://www.example.com:443/ with proxy=DIRECT
java.lang.ClassNotFoundException: Apps.class
    at sun.plugin2.applet.Applet2ClassLoader.findClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadCode(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)
basic: load: class Apps.class not found.
java.lang.ClassNotFoundException: Apps.class
    at sun.plugin2.applet.Applet2ClassLoader.findClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadCode(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)
Ignored exception: java.lang.ClassNotFoundException: Apps.class
basic: Dialog type is not candidate for embedding
security: Reset deny session certificate store
basic: Removed progress listener: sun.plugin.util.ProgressMonitorAdapter@1d2bd52
security: Reset deny session certificate store*

In applet, I am using simple applet

import java.applet.*;
import java.awt.*;

public class Apps extends Applet{

   public void paint(Graphics g){
      g.drawString("Welcome in Java Applet.",40,20);
   }
}

Answer:

We are having this same issue. I believe this is a bug in the way Java implemented TLS 1.2 for SSL.

According to their documentation, https://blogs.oracle.com/java-platform-group/entry/java_8_will_use_tls, they claim that by enabling TLS 1.2, it is backwards compatible with older versions.

However, this is not the case. When TLS 1.2 is disabled, we no longer get the "Remote host closed connection during handshake" error.

TLS 1.2 support can be turned off from the Advanced Settings in the Java Control Panel.

Once this is done, the applets will work.

Question:

I have a JAVA Applet to perform digital signatures, certificate validations, and so on. It's signed with a valid certificate, it has a correct Manifest (I suppose) with values as:

Permissions: all-permissions
Specification-Title: Applet Certificados digitales
Specification-Version: v1.3
Specification-Vendor: mycompany
Application-Name: Applet Java mycompany

And, it works perfectly, into a "applet" tag, thanks to NPAPI friendly browsers (tested only on Firefox and IExplorer). It has been running so by years ...

Now I want to let Chrome and Edge users use it, by using JNLP. And here it's ALMOST ok. I say "almost" because I can read store certificates, access to my ASP.NET WebApi, perform digital signatures .... but now I can't open smart cards to read certificates, due that SecurityException when I set the security manager:

  public SmartCardProvider_SecurityManager(final ApduConnection conn) {
    super(NAME, VERSION, INFO);
    defaultConnection = conn;

    AccessController.doPrivileged(new PrivilegedAction<Void>() {
        @Override
        public Void run() {
            if (!(System.getSecurityManager() instanceof SmartCardProvider_SecurityManager)) {
                    System.setSecurityManager(new SmartCardProvider_SecurityManager(System.getSecurityManager()));
                   // Exception -> JVM Shared, not allowed to set security manager
            }
.... 

Where

private static final class SmartCardProvider_SecurityManager 
     extends SecurityManager { .....

This is my JNLP:

<?xml version="1.0" encoding="utf-8"?> 
 <jnlp spec="1.0+" codebase="" href="thefile.JNLP">
 <information>
   <title>mycompany - JAVA apps</title>
   <vendor>mycompany</vendor>
   <homepage href="http:\\www.mycompany.com" />
   <description>the description</description>
 </information>
 <security>
   <all-permissions/>
 </security>
 <resources>
   <j2se version="1.7+" href="http://java.sun.com/products/autodl/j2se"/>
   <jar href="APPLET_NAME.jar" main="false"  />
 </resources>
 <applet-desc documentBase="" 
    name="the_name" 
      main-class="myjavanamespace.clsApplet" 
      width="450" 
      height="250"> 
    <param name="0123225223   ..... /> some ciphred params ... 
    <param name="permissions" value="all-permissions" /> 
</applet-desc>

My last try was to add this param:

<param name="separate_jvm" value="true"/>

But I get the same exception. I am out of ideas, so any help will be appreciated.

Current run enviroment:

  • Java Plugin 11.72.2.15

  • Using JRE 1.8.0_72-b15 Java HotSpot(TM) 64-Bit Server VM


Answer:

I have migrated the funcionality to a stand-alone java app, invoking it with "the same" JNLP ('application-desc' instead of 'applet-desc', and 'arguments' insted or 'params nodes'). The security error has gone.

I was trying to change the smart code provider, to get the real reason of this question, but, as Andrew Thompson said, and I agree, it's worthless to spoil more effort with an applet, as they are going to be discontinued on March 2017 aprox.

By now, I will keep my old applet meanwhile the new app comes to Production.

Question:

I am making an applet and I made a try catch block that when the program is getting the text from three of the textfields, if any of the textfield is not an integer it should show a dialogue box saying invalid input, however, nothing shows up and I'm not sure how to add a dialogue box onto my applet

try{
        if (e.getSource() == bttn)
        {

            as=T1.getText();
            ag=T2.getText();
            ab=T3.getText();
            as=as.trim();
            ag=ag.trim();
            ab=ab.trim();

            redColor= Integer.parseInt(as);
            greenColor= Integer.parseInt(ag);
            blueColor= Integer.parseInt(ab);
        }
    }
    catch (InputMismatchException exception){
        JOptionPane.showMessageDialog(null,"Invalid Input","TITLE",JOptionPane.WARNING_MESSAGE);

    }

Answer:

Your problem is probably here :

if (e.getSource() == bttn)

This condition is probably never true.

change it to

if (e.getSource().equals(bttn))

Oh, and parseInt throws NumberFormatException, not InputMismatchException.

Question:

CacheEntry[http://localhost:8080/CreateDPdf/CreatePdf.jar]: updateAvailable=true,lastModified=Tue Jul 07 21:15:58 IST 2015,length=8112
Exception in thread "AWT-EventQueue-2" java.security.AccessControlException: access denied ("java.io.FilePermission" "Report.pdf" "write")
    at java.security.AccessControlContext.checkPermission(Unknown Source)
    at java.security.AccessController.checkPermission(Unknown Source)
    at java.lang.SecurityManager.checkPermission(Unknown Source)
    at sun.plugin2.applet.AWTAppletSecurityManager.checkPermission(Unknown Source)
    at java.lang.SecurityManager.checkWrite(Unknown Source)
    at java.io.FileOutputStream.<init>(Unknown Source)
    at java.io.FileOutputStream.<init>(Unknown Source)
    at createpdf.CreatePdfApplet.jButton_pdfActionPerformed(CreatePdfApplet.java:119)
    at createpdf.CreatePdfApplet.access$100(CreatePdfApplet.java:21)
    at createpdf.CreatePdfApplet$2.actionPerformed(CreatePdfApplet.java:84)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(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$1.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$1.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$1.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)

I can run my applet but I am not able to create a PDF file from the input text area after a button click. I am using iTextPDF.


Answer:

I could able to sort out my problem by adding following codes to my C:\Program Files\Java\jre1.8.0_45\lib\security\java.policy

grant codeBase "http://localhost/-" {
 permission java.security.AllPermission;
 permission java.io.FilePermission "<<ALL FILES>>", "read";
 permission java.io.FilePermission "<<ALL FILES>>", "write";
};

Question:

I have a Java Applet that is using a library I made. The library, used inside another project on Eclipse works perfectly. On the applet, when I call the constructor of the "main" class, I get a PrivilegedActionException. The only thing the constructor does is creating an instance of an object that, ultimately, implements Java's Serializable, which is used to access the internet. You can see the class here: CommonsDataLoader.java. This class implements DataLoader.java that, as you can see, implements Serializable.

I can run a test function inside the applet that simply receives a string from JS and returns a new one. This works perfectly.

So... I don't seem to be doing anything wrong here, nor accessing anything out of the ordinary. So why the exception?

NOTES:

I'm using maven to build the jar. The manifest is created using the <addDefaultImplementationEntries>true</addDefaultImplementationEntries> tag of the maven-assembly-plugin. I considered that I had to provide the Permissions: all-permissions to the manifest, but if I do this, the test function doesn't even work.

EDIT:

Manifest's header:

Manifest-Version: 1.0
Implementation-Title: myApplet
Implementation-Version: 0.0.1-SNAPSHOT
Archiver-Version: Plexus Archiver
Built-By: pedrocunha
Implementation-Vendor-Id: myProject
Created-By: Apache Maven
Build-Jdk: 1.8.0_25

Line on the manifest concerning DataLoader:

Name: eu/europa/ec/markt/dss/validation102853/loader/DataLoader.class
SHA-256-Digest: Aua3IW0faYfh4Mf3Q08wMxZc/WU0S2DuF6fJoE+pRpM=

Line on the manifest concerning CommonsDataLoader:

Name: eu/europa/ec/markt/dss/validation102853/https/CommonsDataLoader.class
SHA-256-Digest: d4zCM6GVllA0Fy/pm4D6Z8OZf+jHR58VPCUIq786cr0=

Answer:

So, I think I figured out what was missing/happening. First and foremost, there was an issue with some of the poms of subprojects that were declared as pom and not as jar. Then, the manifest needs the all-permissions declaration and the codebase. I assigned * to the codebase. Everything inside every jar must be signed. The jnlp file must contain

<security>
all-permissions
</security>

The code inside the applet that requires the privileges need to be inside a doPrivileged (i.e. Access to hardware, sockets, etc).

If all this is set, then it'll work. At least it did for me.

Question:

I'm making a maze game using tiles. The maze changes shape in regular intervals. At this time the tilearray gets empty before the maze recreates. I'm getting NPE errors after different intervals and after a while the game stops. Probably because some methods tries to access before it is actually recreated. I tried to put if(... !=null) in some places and even tried to synchronize some part (which I'm not really familiar with).

Edit: Thank you for Arvind for pointing out the problem. I managed to fix it but I would still appriciate some more help as it is not the best and most neat fix I think. Tile t was equal to null at some cases. I simply just checked it and put a continue; into the for loop to avoid the error.

Thank you very much for any help and advice in advance!

With this error the game still runs:

Exception in thread "AWT-EventQueue-1" java.lang.NullPointerException
at shiftingmaze.Game.paintTiles(Game.java:161)
at shiftingmaze.Game.paint(Game.java:115)
at shiftingmaze.Game.update(Game.java:107)
at sun.awt.RepaintArea.updateComponent(Unknown Source)
at sun.awt.RepaintArea.paint(Unknown Source)
at sun.awt.windows.WComponentPeer.handleEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$400(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$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.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$1.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)

And after a while it freezes with this error:

Exception in thread "Thread-4" java.lang.NullPointerException
at shiftingmaze.Game.updateTiles(Game.java:153)
at shiftingmaze.Game.run(Game.java:86)
at java.lang.Thread.run(Unknown Source)

Here is some parts of the code:

@Override
public void start() {

    hero = new Hero();

    Timer t = new Timer();

    t.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            tilearray.clear();
            shiftMaze();
        }
    }, 0, 1000);

    Thread thread = new Thread(this);
    thread.start();
}

@Override
public void stop() {

}

@Override
public void destroy() {

}

@Override
public void run() {

    while (true) {
        hero.update();
        updateTiles();
        repaint();
        try {
            Thread.sleep(17);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

@Override
public void update(Graphics g) {

    if (image == null) {
        image = createImage(this.getWidth(), this.getHeight());
        second = image.getGraphics();
    }

    second.setColor(getBackground());
    second.fillRect(0, 0, getWidth(), getHeight());
    second.setColor(getForeground());
    paint(second);
    g.drawImage(image, 0, 0, this);
}

@Override
public void paint(Graphics g) {

    g.drawImage(background, 0, 0, this);
    paintTiles(g);
    // g.drawRect((int)Hero.rect.getX(), (int)Hero.rect.getY(),
    // (int)Hero.rect.getWidth(), (int)Hero.rect.getHeight());
    // g.drawRect((int)Hero.bigRect.getX(), (int)Hero.bigRect.getY(),
    // (int)Hero.bigRect.getWidth(), (int)Hero.bigRect.getHeight());
    g.drawImage(character, hero.getHeroX(), hero.getHeroY(), this);
}

public void shiftMaze() {

    final int MAZEROW = 24;
    final int MAZECOL = 40;

    for (int i = 0; i < MAZEROW * MAZECOL / 2; i++) {
        int n = rand.nextInt(MAZECOL - 2) + 1;
        int m = rand.nextInt(MAZEROW - 2) + 1;
        if (!(n == 1 && m == 1) && !(n == MAZECOL - 2 && m == MAZEROW - 2)) {
            Tile t = new Tile(n, m);
            tilearray.add(t);
        }
    }

    for (int i = 0; i < MAZECOL; i++) {
        for (int j = 0; j < MAZEROW; j++) {
            if (i == 0 || i == MAZECOL - 1 || j == 0 || j == MAZEROW - 1)
                if (!(i == 1 && j == 0)
                        && !(i == MAZECOL - 2 && j == MAZEROW - 1)) {
                    Tile t = new Tile(i, j);
                    tilearray.add(t);
                }
        }
    }
}

public void updateTiles() {

    for (int i = 0; i < tilearray.size(); i++) {
        Tile t = (Tile) tilearray.get(i);
        t.update();
    }
}

public void paintTiles(Graphics g) {

    for (int i = 0; i < tilearray.size(); i++) {
        Tile t = (Tile) tilearray.get(i);
        g.drawImage(t.getTileImage(), t.getTileX(), t.getTileY(), this);
    }
}

This is from the Tile class:

public Tile(int x, int y) {

    tileX = x * 20;
    tileY = y * 20;
    tileImage = Game.getWall();

    r = new Rectangle();
}

public void update() {

    r.setBounds(tileX, tileY, 20, 20);
    if (r.intersects(Hero.bigRect))
        checkCollision(Hero.rect);
}

Answer:

The problem is here:

public void updateTiles() {
    for (int i = 0; i < tilearray.size(); i++) {
        Tile t = (Tile) tilearray.get(i);//<-- tile is null in some cases
        t.update();
    }
}

There are many options to avoid this:

Option 1: Sub-class ArrayList and override the method add() and addAll() with null check.

Option 2: After populating the tilearray, remove the null values by using this line

    tilearray.removeAll(Collections.singleton(null));

EDIT

If you are looking for second option then you should try this:

public void shiftMaze() {
    //<-- to do here
    tilearray.removeAll(Collections.singleton(null));//<-- at the end
}

Question:

I tried myself on a little "project" . It is basically a survival game. You move by using W,A,S,D and you shoot in different directions by using the arrow keys. You basically have to survive for as long as possible. The enemies follow you and they freeze on hit and start moving again after about 3 seconds.

The code is the following (execute the "window" class)

Window-class

package TestGame;
    import java.awt.Graphics;



public class Window extends GameIntern{

public void init(){
    setSize(windowX,windowY);   
    Thread th = new Thread(this);
    th.start();
    offscreen = createImage(windowX,windowY);
    d = offscreen.getGraphics();
    addKeyListener(this);
}


public void paint(Graphics g){
    d.clearRect(0,0,windowX,windowY);//clear window
    d.drawString(numberEnemies.toString(), 10, 10);//"Score" number of enemies displayed
    d.drawRect(x, y, playerWidth, playerHeight);//draw player
    for(Enemy e : enemies){//draw all enemies
        d.drawRect(e.getx(), e.gety(), playerWidth, playerHeight);
    }
    for(Bullet b : bullets){//draw all bullets
        d.drawOval(b.getx(), b.gety(), bulletSize, bulletSize);
    }
    g.drawImage(offscreen,0,0,this);
}


public void update(Graphics g){
    paint(g);
}
}

GameIntern-class

    package TestGame;


import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.Random;

public class GameIntern extends Applet implements Runnable , KeyListener {

    public int windowX = 854;//size of the window in x direction
    public int windowY = 460;//size of the window in y direction
    public static int x;//x-coordinate of player
    public static int y;//y-coordinate of player
    public int playerpositionX = x;
    public int playerpositionY = y;
    public int playerHeight = 20;//player height
    public int playerWidth = 20;//player width
    public int playerSpeed = 3;//pixel per frame
    public int bulletSize = 5;//diameter of bullets
    public int spawnTime = 4;//time for new enemies to spawn in seconds
    public int enemySleepTime = 180;//Time an enemy does nothing in Frames per second (180 in 60fps = 3sec)
    public boolean alive = true;
    public Image offscreen;
    public Graphics d;
    public boolean up,down,left,right;
    private int delay;
    private Random random= new Random();
    public Integer numberEnemies = new Integer(enemies.size());
    protected static ArrayList<Enemy> enemies = new ArrayList<Enemy>(); //List of all enemies
    protected static ArrayList<Bullet> bullets = new ArrayList<Bullet>();//List of all bullets
    protected static ArrayList<PowerUps> pUps = new ArrayList<PowerUps>();//List of all powerUps


    public void run() {
        this.x = 400;//startingposition x
        this.y = 240;//startingposition y

        double ns = 1000000000.0 / 60.0;    //60 "frames" 
        double delta = 0;
        long lastTime = System.nanoTime();
        while (alive) {
            long now = System.nanoTime();
            delta += (now - lastTime) / ns;
            lastTime = now;
            while (delta >= 1) {
                repaint();
                tick();
                collisionEnemy();
//              collisionPowerUp();
                delta--;
            }
        }
    }

    /**
     * Method to calculate all objects and their positions per frame 
     */
    private void tick() {
        if(left == true){
            if(x>=0 + playerSpeed){
                x-=playerSpeed;
            }else{ x=0;}//Farthest left x-coordinate
            repaint();
        }
        if(right == true){
            if(x<=windowX - playerWidth - playerSpeed){
                x+=playerSpeed;
            }else{ x=windowX - playerWidth;}//Farthest right x-coordinate
            repaint();
        }
        if(up == true){
            if(y>=0 + playerSpeed){
                y-=playerSpeed;
            }else{ y=0;}//Highest y-coordinate
            repaint();
        }
        if(down == true){
            if(y<=windowY - playerHeight - playerSpeed){
                y+=playerSpeed;
            }else{y=windowY - playerHeight;}//Lowest y-coordinate
            repaint();
        }
        for (Enemy e : enemies) {   //Tick every enemy
            e.tick();
        }
        for (Bullet b : bullets){   //Tick every bullet
            b.tick();
        }
        if(delay % (60 * spawnTime) == 0){  //Spawn enemy 
            enemies.add(new Enemy(random.nextInt(windowX), random.nextInt(windowY)));
            numberEnemies++;
        }
        delay++;

        for(Enemy e : enemies){         //collision : enemy & bullet
            for(Bullet b : bullets){
                if(b.getx()+bulletSize >= e.getx() && b.getx() <= e.getx()+20){
                    if(b.gety()+bulletSize >= e.gety() && b.gety() <= e.gety()+20){
                        e.setHit();
                        b.setRemove();
                    }
                }
            }
        }
        for(int i = 0; i< bullets.size(); i++){ //Remove bullets from ArrayList 
            if(bullets.get(i).remove){
                bullets.remove(i);
            }
        }

    }

    public void keyPressed(KeyEvent e) {

        if(e.getKeyCode() == 65){//W
            left=true;
        }
        if(e.getKeyCode() == 87){//A
            up=true;
        }
        if(e.getKeyCode() == 68){//S
            right=true;
        }
        if(e.getKeyCode() == 83){//D
            down=true;
        }
    }


    public void keyReleased(KeyEvent e) {

        if(e.getKeyCode() == 65){//Arrowkey left
            left=false;
        }
        if(e.getKeyCode() == 87){//Arrowkey up
            up=false;
        }
        if(e.getKeyCode() == 68){//Arrowkey right
            right=false;
        }
        if(e.getKeyCode() == 83){//Arrowkey dowm
            down=false;
        }
        if(e.getKeyCode() == 37){//Arrowkey left
            bullets.add(new Bullet(x,y,false,false,true,false)); //Direction the bullet has to go 
        }
        if(e.getKeyCode() == 38){//Arrowkey up
            bullets.add(new Bullet(x,y,true,false,false,false));//Direction the bullet has to go
        }
        if(e.getKeyCode() == 39){//Arrowkey right
            bullets.add(new Bullet(x,y,false,false,false,true));//Direction the bullet has to go
        }
        if(e.getKeyCode() == 40){//Arrowkey down
            bullets.add(new Bullet(x,y,false,true,false,false));//Direction the bullet has to go
        }
    }

    public void keyTyped(KeyEvent e){}

    /**
     * Method to see if the player collided with an enemy
     */
    public void collisionEnemy(){
        for(Enemy e : enemies){ 
            for(int i = 0;i <= playerWidth; i++){
                if(GameIntern.x+i >= e.getx() && GameIntern.x+i <= e.getx()+playerWidth){
                    if(GameIntern.y+i >= e.gety() && GameIntern.y+i <= e.gety()+playerHeight){
                        alive = false;
                    }
                }
            }
        }
    }

//  public void addEnemy(){
//      enemies.add(new Enemy(random.nextInt(windowX), random.nextInt(windowY)));
//      
//      //Spawn enemies inside the filed, not outside the boarder
//      if (playerpositionX < playerWidth * 2 || playerpositionX * 2 > windowX - 2*playerWidth || playerpositionY * 2 > windowY - 2*playerHeight || playerpositionY < playerHeight * 2){
//              enemies.add(new Enemy(random.nextInt(windowX - 3*playerWidth), random.nextInt(windowY - 3*playerHeight)+3*playerHeight));   
//      }else {
//          int temp1 = random.nextInt(windowX-3*playerWidth);
//          if (temp < playerpositionX){
//              
//          }
//          enemies.add(new Enemy(random.nextInt(windowX), random.nextInt(windowY)));
//      }
//  
//  }
}

Bullet-class

package TestGame;

public class Bullet extends GameIntern{
    public int x,y;
    public boolean up,down,left,right;
    public boolean remove;

    public Bullet(int x, int y,boolean up,boolean down, boolean left, boolean right){
        this.x = x + 8;
        this.y = y + 8;
        this.up = up;
        this.down = down;
        this.left = left;
        this.right = right;
    }

    public int getx(){
        return this.x;
    }
    public int gety(){
        return this.y;
    }
    public void setRemove(){
        remove=true;
    }

    public void tick() {

        if (up == true) y-=2;
        if (down == true) y+=2;
        if (left == true) x-=2;
        if (right == true) x+=2;
        if(x < 0){
            remove = true;
        }
        if(x > 840){
            remove = true;
        }
        if(y < 0){
            remove = true;
        }
        if(y > 470){
            remove = true;
        }
    }
}

Enemy-class

package TestGame;

public class Enemy extends GameIntern {

    public int x,y;
    public boolean hit = false;
    public int counter = 0;

    public Enemy(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getx(){
        return this.x;
    }
    public int gety(){
        return this.y;
    }
    public void setHit(){
        hit = true;
        counter = enemySleepTime;
    }

    public void tick() {
        if(counter == 0){
            if(hit == true){
                hit=false;
            }
            if (x < GameIntern.x) x++;
            if (x > GameIntern.x) x--;
            if (y < GameIntern.y) y++;
            if (y > GameIntern.y) y--;
        }else {counter--;}
    }
}

After playing for a while i get a

java.util.ConcurrentModificationException

What does that mean?

Also, I struggle to improve the enemy spawn prcess. Right now it sometimes happens, that enemies spawn inside the player. I want to have an imaginary box around the player where enemies dont spawn inside and enemies should always spawn inside the window.

If you have any questions, please feeld free to ask :)

sincerely Viktor


Answer:

From the JavaDocs:

The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.

The problem is likely caused because you're removing bullets from the ArrayList while trying to paint them in a separate thread. The issue is that the two threads are iterating over the bullets list simultaneously.

    //The following for loop is likely the cause
    for(int i = 0; i< bullets.size(); i++){ 
        if(bullets.get(i).remove){
            bullets.remove(i); // <-- this is the problem 
        }
    }

Instead, try using a thread-safe implementation, e.g.

protected static List<Enemy> enemies = 
    Collections.synchronizedList(new ArrayList<Enemy>()); //List of all enemies
protected static List<Bullet> bullets = 
    Collections.synchronizedList(new ArrayList<Bullet>());//List of all bullets

Furthermore, you should change the remove code to avoid an IndexOutOfBoundsException:

    LinkedList<Bullet> bulletsToRemove = new LinkedList<>();
    for(Enemy e : enemies){         //collision : enemy & bullet
        for(Bullet b : bullets){
            if(b.getx()+bulletSize >= e.getx() && b.getx() <= e.getx()+20){
                if(b.gety()+bulletSize >= e.gety() && b.gety() <= e.gety()+20){
                    e.setHit();
                    bulletsToRemove.add(b);
                }
            }
        }
    }
    for(Bullet b : bulletsToRemove){ //Remove bullets from ArrayList 
        bullets.remove(b);
    }

Regarding the spawning process, a simplistic approach is to just define a minimum distance from the player, call it minDist. Now just pick a random location anywhere on the screen, call it p1. If p1 is less than minDist away from the player, pick a new random location. As long as the player and enemy sprites are relatively small compared to the screen area, this approach should work well.

Question:

I'm new to programming with Applets and wanted to make an Applet to put on a website. So here we go.

The Goal of this project was that if you click the button, it will open a JFrame on top of the browser. but while testing, it gives me a java.lang.ExceptionInInitializerError. This is the source code:

public class LaunchMenu extends Applet {

    public static LoginScreen login;
    public static Game game;
    public JButton button;
    public void init() {
        try {button= new JButton("Press this button to start");
        add(button);

        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                login = new LoginScreen();

            }
        });
        } catch (Exception e) {
            e.getMessage();
            e.getCause();
        }
    }

    public void start() {
        login = new LoginScreen();
    }

    public void stop() {
        login.dispose();
        game.stop();
    }

    public static void main(String[] args) {

    }

}

note: It works in Eclipse with it's Applet window, but not on the website.

edit:

Exception in thread "AWT-EventQueue-2" java.lang.IllegalStateException: Applet's parent container not set up
    at sun.plugin2.applet.Plugin2Manager.start(Unknown Source)
    at sun.plugin2.main.client.PluginMain$StartAppletRunner.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$1.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)
CacheEntry[http://localhost/AppletTest/Applet.jar]: updateAvailable=true,lastModified=Mon Apr 13 12:24:52 CEST 2015,length=5051938

Answer:

Ok I fixed my problem. Here's the solution that worked for me.

SourceCode stays the same (except for a minor change)* :

public class LaunchMenu extends Applet {

    public static LoginScreen login;
    public static Game game;
    public JButton button;
    public void init() {
        try {button= new JButton("Start the game");
        add(button);

        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                login = new LoginScreen();
                login.setVisible(true); *

            }
        });
        } catch (Exception e) {
            e.getMessage();
            e.getCause();
        }
    }

    public void start() {
        login = new LoginScreen();
    }

    public void stop() {
        login.dispose();
        game.stop();
    }

    public static void main(String[] args) {

    }
}

But I added a java.policy file in the same folder as the Applet. Within this file I wrote the following code:

grant { 
      permission java.security.AllPermission; 
}; 

After this was setup, I ran in another problem named java.lang.RuntimePermission: "exitVM.0"

The solution to this problem was simple. In the class with my JFrame, in my case LoginScreen, there was a line code setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);. Delete this or comment it, this worked for me and now my Applet is visible and the Login frame opens. which was all I needed.

Hope this helps alot of people with the same problem.

Question:

I'm supposed to create a java applet project and in that I need to read data from .csv file and put it in a scrollable table. I tried to dothat and i get a FileNotFoundException exception.

Here is my code:

import java.applet.Applet;
import java.awt.BorderLayout;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

@SuppressWarnings("serial")
public class Test extends Applet
{  
   Table table;
   public void init()
   {
      try
      {
         table = new Table();
      }
      catch (Exception e)
      {
         e.printStackTrace();
      }
      this.add(table);
   }
}



class Table extends JPanel
{
   private String[][] productList;
   private JTable table;

   public Table() throws Exception
   {
      read();
      BorderLayout layout = new BorderLayout();
      layout.addLayoutComponent(new JScrollPane(table), BorderLayout.CENTER);

      setLayout(layout);
   }

   private void read() throws Exception
   {
      ArrayList<String[]> list = new ArrayList<String[]>();
      try
      {
         BufferedReader br = new BufferedReader(new FileReader("Products.csv"));
         String line = br.readLine();

         while ((line = br.readLine()) != null)
         {
            String[] toBeAdded = line.split(",");
            list.add(toBeAdded);
         }
      }
      catch (Exception e)
      {
         e.printStackTrace();
      }

      productList = new String[list.size()][3];
      for (int i = 0; i < productList.length; i++)
         for (int j = 0; j < productList[i].length; j++)
            productList[i][j] = list.get(i)[j];
   }
}

The products.csv is there in the root folder. I try to read in a normal non swing project and it works but not for this. Can anyone help me?


Answer:

I can think of two potential problems:

  1. An applet can't read files located on the web server.
  2. If the file is packed inside a jar file, you need special code in order to read it. Specifically, you need a ClassLoader's getResourceAsStream.

For the second, the easiest way to get the ClassLoader's getResourceAsStream is to call Class's getResourceAsStream.

I haven't tested it, but something like this should work:

BufferedReader br = new BufferedReader(new InputStreamReader(Table.class.getResourceAsStream("/Products.csv")));

If that doesn't compile, change Table.class to this.getClass()

Note that the / is there to indicate that Products.csv is at the root of the .jar file. Otherwise, it will use the package name as a directory to look in (i.e. if the package was package this.is.my.boomstick;, it'd try to open this/is/my/boomstick/Products.csv)

Question:

I created a Vector called lines that stores the coordinate points of the end points of drawn line. It accomplishes the task that I want by drawing lines from the stored coordinates but produces the following exception:

Exception in thread "AWT-EventQueue-1" java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 10
    at java.util.Vector.get(Vector.java:748)
    at DrawPad.paint(DrawPad.java:149)
    at java.awt.Container.update(Container.java:1995)
    at sun.awt.RepaintArea.updateComponent(RepaintArea.java:255)
    at sun.awt.RepaintArea.paint(RepaintArea.java:232)
    at sun.awt.windows.WComponentPeer.handleEvent(WComponentPeer.java:358)
    at java.awt.Component.dispatchEventImpl(Component.java:4967)
    at java.awt.Container.dispatchEventImpl(Container.java:2294)
    at java.awt.Component.dispatchEvent(Component.java:4713)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.awt.EventQueue$4.run(EventQueue.java:729)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Answer:

You need to check to see if the element exists before calling lines.get(i). Also, use lines.size() instead of lines.capacity().

for(int i = 0; i < lines.size(); i += 4)
{
    if((i+3) < lines.size())
    {
        g.drawLine(lines.get(i), lines.get(i + 1), lines.get(i + 2), lines.get(i + 3));
    }
}

Question:

I am trying to write an applet that run in html page . If I run the applet in eclipse with debug as JApplet it runs fine, but if i put it in an html it has an error.

Java console say :

basic: eccezione: java.lang.ExceptionInInitializerError 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 org.restlet.resource.ClientResource.(ClientResource.java:405) at com.gabrielepiscitelli.JAppletGui.RestClient.Client.listAllThreads(Client.java:39) at com.gabrielepiscitelli.JAppletGui.Gui.GUIApplet.(GUIApplet.java:191) 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$400(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$1.doIntersectionPrivilege(Unknown Source) at java.security.ProtectionDomain$1.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$1.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.security.AccessControlException: access denied ("java.util.PropertyPermission" "java.util.logging.config.file" "read") at java.security.AccessControlContext.checkPermission(Unknown Source) at java.security.AccessController.checkPermission(Unknown Source) at java.lang.SecurityManager.checkPermission(Unknown Source) at sun.plugin2.applet.AWTAppletSecurityManager.checkPermission(Unknown Source) at java.lang.SecurityManager.checkPropertyAccess(Unknown Source) at java.lang.System.getProperty(Unknown Source) at org.restlet.engine.Engine.configureLog(Engine.java:194) at org.restlet.engine.Engine.register(Engine.java:380) at org.restlet.engine.Engine.register(Engine.java:368) at org.restlet.engine.Engine.getInstance(Engine.java:252) at org.restlet.data.Method.(Method.java:334) at org.restlet.data.Method.(Method.java:393) at org.restlet.data.Method.(Method.java:358) at org.restlet.data.Method.(Method.java:57) ... 28 more

the code at Client.java:39 is the line cr = new ClientResource(lURI); in this part of java file:

 /**
 * 
 */
package com.gabrielepiscitelli.JAppletGui.RestClient;

import java.io.IOException;

import org.restlet.data.Status;
import org.restlet.resource.ClientResource;
import org.restlet.resource.ResourceException;

import com.gabrielepiscitelli.JAppletGui.DataGui.DataGuiPost;
import com.gabrielepiscitelli.JAppletGui.DataGui.DataGuiThread;
import com.gabrielepiscitelli.JAppletGui.DataGui.DataGuiUser;
import com.gabrielepiscitelli.SystemForum.Utils.ExceptionForum;
import com.google.gson.Gson;

/**
 * @author Gabriele
 *
 */
public class Client {
    /**
     * 
     * @return
     * @throws ExceptionForum 
     */
    public static DataGuiThread[] listAllThreads() throws ExceptionForum{

        DataGuiThread[] lRestDataGuiThreads = null;

        ClientResource cr   = null;
        Gson gson           = new Gson();
        Status status       = null;
        String json         = null;

        String lURI = "http://localhost:8182/ListThreadsAll";

        cr = new ClientResource(lURI);
        try {
            json = cr.get().getText();
            status = cr.getStatus();

            if (status.getCode() != 200) {
//              System.out.println(status);
//              System.exit(status.getCode());
                Status lStatusJson = gson.fromJson(json, Status.class);
                throw new ExceptionForum(ExceptionForum.ExType.CLIENT, 
                          "Client error.", 
                          lStatusJson.getDescription() + lStatusJson.getReasonPhrase());
            } else {
                lRestDataGuiThreads = gson.fromJson(json, DataGuiThread[].class);
            }

        } catch (ResourceException e) {
//          e.printStackTrace();
            throw new ExceptionForum(ExceptionForum.ExType.CLIENT, 
                      "Client error.", 
                      e.getMessage());

        } catch (IOException e) {
//          e.printStackTrace();
            throw new ExceptionForum(ExceptionForum.ExType.CLIENT, 
                      "Client error.", 
                      e.getMessage());
        }

        return lRestDataGuiThreads;
    }

Html file is simply :

<html><body>
 <p>
  <applet code="com.gabrielepiscitelli.JAppletGui.Gui.GUIApplet.class" archive="GUIApplet.jar,miglayout15-swing.jar,org.restlet.jar,gson-2.2.4.jar"
   width="800" height="640"></applet>
 </p>

Is there someone that can explain me the problem? thanks in advances!


Answer:

Caused by: java.security.AccessControlException: access denied
    ("java.util.PropertyPermission" "java.util.logging.config.file" "read")

This applet needs to be trusted. Digitally sign the applet code.