Question

My Java Applet works perfectly fine when I run from Netbeans and the jar file created works fine too. However, when I embed the applet into the browser, I have this error "RuntimeException java.lang.reflect.InvocationTargetException" I have surfed through to debug this error but I couldn't seem to find a solution for my codes. Please help. Thank You.

Here are my codes:

SerialTest.java (this is my main class, in the main method, I call the applet so that whatever that should be printed in the Java console will be printed in the applet instead)

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Enumeration;
import java.util.Scanner;


public class SerialTest implements SerialPortEventListener {

    SerialPort serialPort;

    /**
     * The port we're normally going to use.
     */
    public static final String PORT_NAMES[] = {
        "/dev/cu.usbserial-A9014NQP" //, Mac OS X
    //"/dev/ttyUSB0", // Linux
    //"COM3", // Windows
    };
    /**
     * A BufferedReader which will be fed by a InputStreamReader converting the
     * bytes into characters making the displayed results codepage independent
     */
    public BufferedReader input;
    /**
     * The output stream to the port
     */
    public OutputStream output;
    /**
     * Milliseconds to block while waiting for port open
     */
    public static final int TIME_OUT = 2000;
    /**
     * Default bits per second for COM port.
     */
    public static final int DATA_RATE = 9600;

    public void initialize() {
        CommPortIdentifier portId = null;
        Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

        //First, Find an instance of serial port as set in PORT_NAMES.
        while (portEnum.hasMoreElements()) {
            CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
            for (String portName : PORT_NAMES) {
                if (currPortId.getName().equals(portName)) {
                    portId = currPortId;
                    break;
                }
            }
        }
        if (portId == null) {
            //portnotdetected = "Could not find COM port.";
            System.out.println("Could not find COM port.");
            return;
        }

        try {
            // open serial port, and use class name for the appName.
            serialPort = (SerialPort) portId.open(this.getClass().getName(),
                    TIME_OUT);

            // set port parameters
            serialPort.setSerialPortParams(DATA_RATE,
                    SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);

            // open the streams
            input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
            output = serialPort.getOutputStream();

            // add event listeners
            serialPort.addEventListener(this);
            serialPort.notifyOnDataAvailable(true);
        } catch (Exception e) {
            System.err.println(e.toString());
        }
    }

    /**
     * This should be called when you stop using the port. This will prevent
     * port locking on platforms like Linux.
     */
    public synchronized void close() {
        if (serialPort != null) {
            serialPort.removeEventListener();
            serialPort.close();
        }
    }

    /**
     * Handle an event on the serial port. Read the data and print it.
     */
    public synchronized void serialEvent(SerialPortEvent oEvent) {

        if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            try {
                String inputLine = input.readLine().trim();
                //String readID = inputLine.substring(1);

                System.out.println("Read Tag ID: " + inputLine); //this is the tagID read

                Connection conn = null;

                try {

                    String userName = "root";
                    String password = "root";
                    String url = "jdbc:mysql://localhost:8889/RFID";

                    Class.forName("com.mysql.jdbc.Driver").newInstance();
                    conn = DriverManager.getConnection(url, userName, password);

                    //System.out.println("Database connection established");
                    Statement stmt = null;
                    ResultSet rs = null;
                    //SQL query command
                    String SQL = "SELECT * FROM Inventory WHERE (SerialID = '" + inputLine + "')";
                    //String SQL = "SELECT * FROM Inventory";
                    stmt = conn.createStatement();
                    rs = stmt.executeQuery(SQL);


                    if (rs != null && rs.next()) {
                        String SerialID = rs.getString("SerialID");
                        String name = rs.getString("Name");
                        String description = rs.getString("Description");

                        if (inputLine.equals(SerialID)) {

                            System.out.println(SerialID + "\t " + name + "\t " + description + "\n"); //from Database

                        }
                    } else {
                        System.out.println("Sorry Tag ID " + inputLine + " not found database \n");
                    }

                } catch (Exception e) {

                    System.err.println("Cannot connect to database server");
                    e.printStackTrace();

                }
            } catch (Exception e) {
                System.err.println(e.toString());
            }
        }
        // Ignore all the other eventTypes, but you should consider the other ones.
    }


    public static void main(String[] args) throws Exception {
        new SerialApp();

        SerialTest main = new SerialTest();
        main.initialize();
        Thread t = new Thread() {
            public void run() {
                //the following line will keep this app alive for 1000 seconds,
                //waiting for events to occur and responding to them (printing incoming messages to console).
                try {
                    Thread.sleep(1000000);
                } catch (InterruptedException ie) {
                }
            }
        };
        t.start();

        System.out.println("Started");

        /*
        Scanner scanner = new Scanner(System.in);

         String userInput = scanner.next();
         if ("q".equals(userInput)) {
         System.exit(0);
         }      
         */
    }
}

SerialApp.java (this is where I create my applet)

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JApplet;
import javax.swing.JFrame;

public class SerialApp extends JApplet implements Runnable, ActionListener
{
    public JFrame frame;
    public TextArea textArea;
    public Thread reader;
    public Thread reader2;
    public boolean quit;

    public final PipedInputStream pin=new PipedInputStream(); 
    public final PipedInputStream pin2=new PipedInputStream(); 

    Thread errorThrower; // just for testing (Throws an Exception at this Console

        public void init() {

        }

    public SerialApp()
    {
        // create all components and add them
        frame=new JFrame("RFID");
        Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();
        Dimension frameSize=new Dimension((int)(screenSize.width/2),(int)(screenSize.height/2));
        int x=(int)(frameSize.width/2);
        int y=(int)(frameSize.height/2);
        frame.setBounds(x,y,frameSize.width,frameSize.height);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                textArea=new TextArea();
        textArea.setEditable(false);

                Container container = getContentPane();// Get the content pane of the frame
                container.setLayout(new BorderLayout());
                container.add(textArea, BorderLayout.CENTER);

                //Button button=new Button("clear"); //create button

        /*
                Panel panel=new Panel();
        panel.setLayout(new BorderLayout());
        panel.add(textArea,BorderLayout.CENTER);
        //panel.add(button,BorderLayout.SOUTH); //button location
                */

        frame.add(container);
                frame.setVisible(true); 

        //button.addActionListener(this); //add button

        try
        {
            PipedOutputStream pout=new PipedOutputStream(this.pin);
            System.setOut(new PrintStream(pout,true)); 
        } 
        catch (java.io.IOException io)
        {
            textArea.append("Couldn't redirect STDOUT to this console\n"+io.getMessage());
        }
        catch (SecurityException se)
        {
            textArea.append("Couldn't redirect STDOUT to this console\n"+se.getMessage());
        } 

        try 
        {
            PipedOutputStream pout2=new PipedOutputStream(this.pin2);
            System.setErr(new PrintStream(pout2,true));
        } 
        catch (java.io.IOException io)
        {
            textArea.append("Couldn't redirect STDERR to this console\n"+io.getMessage());
        }
        catch (SecurityException se)
        {
            textArea.append("Couldn't redirect STDERR to this console\n"+se.getMessage());
        }       

        quit=false; // signals the Threads that they should exit

        // Starting two seperate threads to read from the PipedInputStreams             
        //
        reader=new Thread(this);
        reader.setDaemon(true); 
        reader.start(); 
        //
        reader2=new Thread(this);   
        reader2.setDaemon(true);    
        reader2.start();

    }


    public synchronized void actionPerformed(ActionEvent evt)
    {
        textArea.setText("");
    }

    public synchronized void run()
    {
        try
        {           
            while (Thread.currentThread()==reader)
            {
                try { this.wait(100);}catch(InterruptedException ie) {}
                if (pin.available()!=0)
                {
                    String input=this.readLine(pin);
                    textArea.append(input);
                }
                if (quit) return;
            }

            while (Thread.currentThread()==reader2)
            {
                try { this.wait(100);}catch(InterruptedException ie) {}
                if (pin2.available()!=0)
                {
                    String input=this.readLine(pin2);
                    textArea.append(input);
                }
                if (quit) return;
            }           
        } catch (Exception e)
        {
            textArea.append("\nConsole reports an Internal error.");
            textArea.append("The error is: "+e);            
        }

        // just for testing (Throw a Nullpointer after 1 second)
        if (Thread.currentThread()==errorThrower)
        {
            try { this.wait(1000); }catch(InterruptedException ie){}
            throw new NullPointerException("Application test: throwing an NullPointerException It should arrive at the console");
        }

    }

    public synchronized String readLine(PipedInputStream in) throws IOException
    {
        String input="";
        do
        {
            int available=in.available();
            if (available==0) break;
            byte b[]=new byte[available];
            in.read(b);
            input=input+new String(b,0,b.length);                                                       
        }while( !input.endsWith("\n") &&  !input.endsWith("\r\n") && !quit);
        return input;
    }               
}

applet.html

<html>
<head>
<title>Applet</title>
</head>

<body>
<applet code="SerialTest.class" archive="SerialApplet.jar" width="550" height="550">
</applet>
</body>
</html> 
Was it helpful?

Solution 2

I have this error "RuntimeException java.lang.reflect.InvocationTargetException"

Because , You are overruling the rules provided by sandbox of java Applet. I guess, gnu.io.SerialPort has something to do with this. Look at here to know more about applet sandbox: What Applets Can and Cannot Do

OTHER TIPS

I have this error "RuntimeException java.lang.reflect.InvocationTargetException"

This is because You are putting the applet code tag as :

<applet code="SerialTest.class" archive="SerialApplet.jar" width="550" height="550">

And SerialTest is not an Applet..Applets don't use a main method to execute. Instead they are started with their init() and start() methods. Have a look at the following official tutorial to know more about Applets : Java Applets

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top