Use data from different class in the current project java - java

I'm facing a problem regarding of using the data from rf transmision on a class that I wish to use to store on the database. Code 1 is the code for the RF transmission. Is there anyway I can use the data in the
highlight of data to be used in code 1?
public synchronized void serialEvent(SerialPortEvent oEvent) {
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
String inputLine=input.readLine();
String[] parts = inputLine.split(",");
String part1 = parts[0];
String part2 = parts[1];
System.out.print(part1); // data to be used
System.out.print(" , ");
System.out.println(part2); //data to be used
//System.out.println(data);
code 1
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.util.Enumeration;
public class test implements SerialPortEventListener {
SerialPort serialPort;
/** The port we're normally going to use. */
private static final String PORT_NAMES[] = {
"COM4", // Windows
};
/**
* A BufferedReader which will be fed by a InputStreamReader
* converting the bytes into characters
* making the displayed results codepage independent
*/
private BufferedReader input;
/** The output stream to the port */
private OutputStream output;
/** Milliseconds to block while waiting for port open */
private static final int TIME_OUT = 2000;
/** Default bits per second for COM port. */
private 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) {
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();
String[] parts = inputLine.split(",");
String part1 = parts[0];
String part2 = parts[1];
System.out.print(part1); // data to be used
System.out.print(" , ");
System.out.println(part2); //data to be used
//System.out.println(data);
} 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 {
test main = new test();
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");
}

I am probably still confused as to what your asking. I think the simplest way for another class to use the variables would be for it to be passed the values in arguments to one of its functions.
eg.
class ClassThatUsesPart1Part2 {
public void usePart1Part2(String part1, String part2) {
// put code that uses part1 and part2 here
}
}
Add another variable to your class.
private BufferedReader input;
/** The output stream to the port */
private OutputStream output;
/** Milliseconds to block while waiting for port open */
private static final int TIME_OUT = 2000;
/** Default bits per second for COM port. */
private static final int DATA_RATE = 9600;
/** Variable of class that will use part1, part2.*/
private ClassThatUsesPart1Part2 part12User = new ClassThatUsesPart1Part2();
Then use it within your function.
String inputLine=input.readLine();
String[] parts = inputLine.split(",");
String part1 = parts[0];
String part2 = parts[1];
part12User.usePart1Part2(part1,part2);
Is this what you were looking for or have I just completely misunderstood?

Related

Java showInputDialog when data not correct

import javax.swing.*;
import java.io.Serializable;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Server implements Serializable{
public static void main(String[] args) {
String test1= JOptionPane.showInputDialog(null,"Port(0-65535):","Port",JOptionPane.QUESTION_MESSAGE);
int portnumber = tryParse(test1);
if (portnumber !=0) {
try {
Registry reg = LocateRegistry.createRegistry(portnumber); //Creates and exports a Registry instance on the local host that accepts requests
RmiImplementation imp = new RmiImplementation("C://ServerStorage");
reg.bind("remoteObject", imp);
System.out.println("Server is ready.");
System.out.println(portnumber);
} catch (Exception e) {
System.out.println("Server failed: " + e);
}
}
}
private static Integer tryParse(String text) {
try {
return Integer.parseInt(text);
} catch (Exception e) {
return 0;
}
}
}
The above code helps me to set up my file server.
when the application is run, the dialog port number is requested.
If I type letters instead of numbers the program stops running, but I want it to continue and show me the dialog again.
Try with a do-while,
int portnumber = 0;
do {
String text= JOptionPane.showInputDialog(null,"Port(0-65535):","Port",JOptionPane.QUESTION_MESSAGE);
portnumber = tryParse(text);
}while(portnumber==0);

Two Way Serial Communication- Cannot access string read from Serial Reader Thread

I declared a twoWaySerialComm object to to configure the port connection. Inside the twoWaySerialComm class I created a thread to read the incoming serial data in a class called 'SerialReader'. How can access the serial data from the main thread 'twoWaySerialComm'?
I had read the incoming serial data into 'hex' string in the 'SerialReader' class inside a while loop. I am able to print the incoming data inside the while loop, But i am unable to access this 'hex' string in the 'twoWaySerialComm' class. Why can't I access the 'hex' string outside the while loop? how can this be done?
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author asanka
*/
public class TwoWaySerialComm {
private static TwoWaySerialComm twoWaySerialComm;
String read;
private TwoWaySerialComm() throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException, IOException {
String portName = "/dev/ttyUSB0";
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
if (portIdentifier.isCurrentlyOwned()) {
System.out.println("Error: Port is currently in use");
} else {
CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
if (commPort instanceof SerialPort) {
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
InputStream in = serialPort.getInputStream();
OutputStream out = serialPort.getOutputStream();
SerialReader reader;
(new Thread(reader = new SerialReader(in))).start();
read = reader.readHex();
} else {
System.out.println("Error: Only serial ports are handled by this example.");
}
}
}
public static TwoWaySerialComm getTwoWaySerialComm() throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException, IOException {
if (twoWaySerialComm == null) {
twoWaySerialComm = new TwoWaySerialComm();
}
return twoWaySerialComm;
}
public String data() {
return read;
}
/**
*
*/
public static class SerialReader implements Runnable {
String hex;
InputStream in;
public SerialReader(InputStream in) {
this.in = in;
}
public void run() {
byte[] buffer = new byte[1024];
int len;
try {
while ((len = this.in.read(buffer)) > -1) {
hex = new String(buffer, 0, len).replaceAll("\\s", "");
Thread.sleep(1000);
System.out.println(hex);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException ex) {
Logger.getLogger(TwoWaySerialComm.class.getName()).log(Level.SEVERE, null, ex);
}
}
public String readHex() {
return hex;
}
}
/**
*
*/
public static class SerialWriter implements Runnable {
OutputStream out;
public SerialWriter(OutputStream out) {
this.out = out;
}
public void run() {
try {
int c = 0;
while ((c = System.in.read()) > -1) {
this.out.write(c);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
As far as I can see, you're running the read operation in another Thread. When calling the readHex() method, that Thread probably hasn't filled in the hex field yet.
You'll need to call join() on the new Thread first, to ensure it has finished.
Or use the CompletableFuture from the java.util.concurrent package.

re-implementation of org.apache.commons.net.io.Util to parse an InputStream

org.apache.commons.net.io.Util uses InputStream which cannot be parsed live until the stream terminates. Is that correct or incorrect?
The IOUtil class is a blackbox for me. It uses org.apache.commons.net.io.Util but this is equally opaque.
Specifically, the line Util.copyStream(remoteInput, localOutput); of IOUtil is intriguing:
copyStream
public static final long copyStream(InputStream source,
OutputStream dest)
throws CopyStreamException
Same as copyStream(source, dest, DEFAULT_COPY_BUFFER_SIZE);
Throws:
CopyStreamException
How can I read either the original stream or its copy as it comes in? Live telnet connections will have an InputStream which does not terminate. I see no such functionality in the API.
Alternately, re-implementing Apache examples.util.IOUtil leads back to the original problem:
package weathertelnet;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;
public class StreamReader {
private final static Logger LOG = Logger.getLogger(StreamReader.class.getName());
private StringBuilder stringBuilder = new StringBuilder();
private InputStream inputStream;
public StreamReader() {
}
public void setInputStream(InputStream inputStream) throws IOException {
this.inputStream = inputStream;
readWrite();
}
public void readWrite() throws IOException {
Thread reader = new Thread() {
#Override
public void run() {
do {
try {
char ch = (char) inputStream.read();
stringBuilder.append(ch);
} catch (IOException ex) {
}
} while (true); //never stop reading the stream..
}
};
Thread writer = new Thread() {
#Override
public void run() {
//Util.copyStream(remoteInput, localOutput);
//somehow write the *live* stream to file *as* it comes in
//or, use org.apache.commons.net.io.Util to "get the data"
}
};
}
}
Either I have a fundamental misunderstanding, or, without re-implementing (or using reflection, maybe) these API's do not allow processing of a live, unterminated InputStream.
I'm really not inclined to use reflection here, the next stage is, I think, to start breaking down what org.apache.commons.net.io.Util does and how it does it, but that's really going down the rabbit hole. Where does it end?
http://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/io/Util.html#copyStream%28java.io.InputStream,%20java.io.OutputStream%29
You can copy a Stream "live" but the InputStream will probably block when there is no more input.
You can see the code for org.apache.commons.net.io.Util#copyStream(...) here
output first:
thufir#dur:~$
thufir#dur:~$ java -jar NetBeansProjects/SSCCE/dist/SSCCE.jar
print..
makeString..
cannot remove java.util.NoSuchElementException
------------------------------------------------------------------------------
* Welcome to THE WEATHER UNDERGROUND telnet service! *
------------------------------------------------------------------------------
* *
* National Weather Service information provided by Alden Electronics, Inc. *
* and updated each minute as reports come in over our data feed. *
* *
* **Note: If you cannot get past this opening screen, you must use a *
* different version of the "telnet" program--some of the ones for IBM *
* compatible PC's have a bug that prevents proper connection. *
* *
* comments: jmasters#wunderground.com *
------------------------------------------------------------------------------
Press Return to continue:finally -- waiting for more data..
cannot remove java.util.NoSuchElementException
finally -- waiting for more data..
------------------------------------------------------------------------------
* Welcome to THE WEATHER UNDERGROUND telnet service! *
------------------------------------------------------------------------------
* *
* National Weather Service information provided by Alden Electronics, Inc. *
* and updated each minute as reports come in over our data feed. *
* *
* **Note: If you cannot get past this opening screen, you must use a *
* different version of the "telnet" program--some of the ones for IBM *
* compatible PC's have a bug that prevents proper connection. *
* *
* comments: jmasters#wunderground.com *
------------------------------------------------------------------------------
Press Return to continue:
cannot remove java.util.NoSuchElementException
^Cthufir#dur:~$
thufir#dur:~$
then code:
thufir#dur:~$ cat NetBeansProjects/SSCCE/src/weathertelnet/Telnet.java
package weathertelnet;
import static java.lang.System.out;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Logger;
import org.apache.commons.net.telnet.TelnetClient;
public final class Telnet {
private final static Logger LOG = Logger.getLogger(Telnet.class.getName());
private TelnetClient telnetClient = new TelnetClient();
public Telnet() throws SocketException, IOException {
InetAddress host = InetAddress.getByName("rainmaker.wunderground.com");
int port = 3000;
telnetClient.connect(host, port);
final InputStream inputStream = telnetClient.getInputStream();
final ConcurrentLinkedQueue<Character> clq = new ConcurrentLinkedQueue();
final StringBuilder sb = new StringBuilder();
Thread print = new Thread() {
#Override
public void run() {
out.println("print..");
try {
char ch = (char) inputStream.read();
while (255 > ch && ch >= 0) {
clq.add(ch);
out.print(ch);
ch = (char) inputStream.read();
}
} catch (IOException ex) {
out.println("cannot read inputStream:\t" + ex);
}
}
};
Thread makeString = new Thread() {
#Override
public void run() {
out.println("makeString..");
do {
try {
do {
char ch = clq.remove();
sb.append(ch);
// out.println("appended\t" + ch);
} while (true);
} catch (java.util.NoSuchElementException | ClassCastException e) {
out.println("cannot remove\t\t" + e);
try {
Thread.sleep(1000);
} catch (InterruptedException interruptedException) {
out.println("cannot sleep1\t\t" + interruptedException);
}
} finally {
out.println("finally -- waiting for more data..\n\n" + sb + "\n\n\n");
try {
Thread.sleep(1000);
} catch (InterruptedException interruptedException) {
out.println("cannot sleep1\t\t" + interruptedException);
}
}
} while (true);
}
};
print.start();
makeString.start();
}
private void cmd(String cmd) throws IOException {//haven't tested yet..
byte[] b = cmd.getBytes();
System.out.println("streamreader has\t\t" + cmd);
int l = b.length;
for (int i = 0; i < l; i++) {
telnetClient.sendCommand(b[i]);
}
}
public static void main(String[] args) throws SocketException, IOException {
new Telnet();
}
}thufir#dur:~$
thufir#dur:~$

RuntimeException: InvocationTargetException in web browser

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

Automatically detect which Com Port is connected to a USB GSM Modem using Java

I wrote a Java application that reads and sends SMS messages from a USB GSM modem. I'm using SMSLib (which uses JavaCommAPI), and it runs on Windows. I need to pass in the COM PORT, that the modem appears to be connected to.
So far, I've been looking up the COM PORT manually using the Windows Device Manager, and write it into a properties file. I'm wondering if there's a way to detect which COM PORT, the modem is connected to programmatically?
It'll save the trouble of looking it up every time
The port number changes if I unplug/replug it sometimes
Thanks!!
package com.cubepro.util;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Formatter;
import org.apache.log4j.Logger;
import org.smslib.helper.CommPortIdentifier;
import com.cubepro.general.CommonConstants;
import com.cubepro.util.SendMessage;
public class CommPortTester {
private static final String _NO_DEVICE_FOUND = " no device found";
private final static Formatter _formatter = new Formatter(System.out);
private static Logger log = Logger.getLogger(CommPortTester.class);
static CommPortIdentifier portId;
static Enumeration<CommPortIdentifier> portList;
static int bauds[] = { 9600, 14400, 19200, 28800, 33600, 38400, 56000,
57600, 115200 };
public static final String MAINCLASS = "org.smslib.Service";
public CommPortTester() throws Exception {
Class.forName(MAINCLASS);
}
/**
* Wrapper around {#link CommPortIdentifier#getPortIdentifiers()} to be
* avoid unchecked warnings.
*/
private static Enumeration<CommPortIdentifier> getCleanPortIdentifiers() {
return CommPortIdentifier.getPortIdentifiers();
}
public String testAndQualifyPort() throws Exception {
String status = CommonConstants.MODEM_STATUS_ERROR;
SendMessage sendMessage = new SendMessage();
log.debug("\nSearching for devices...");
portList = getCleanPortIdentifiers();
while (portList.hasMoreElements()) {
portId = portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
_formatter.format("%nFound port: %-5s%n", portId.getName());
try {
if(portId.getName()
boolean comPortSuccess = sendMessage.doIt(portId.getName());
if(comPortSuccess == true){
return portId.getName();
}
} catch (final Exception e) {
log.debug(" Modem error occured -",e);
}
}
}
log.debug("\nTest complete.");
return status;
}
public static void main(String[]args){
try{
CommPortTester tester = new CommPortTester();
tester.testAndQualifyPort();
}catch(Exception e){
e.printStackTrace();
}
}
}

Categories