I am trying to "connect" two classes together, MyJFrame and MySerialPort, using the interface SerialPortListener, but I am clueless as how to do it. The reason I am doing this is because yesterday I had a problem assigning data from a serial port buffer to a global String (finalString), in the MySerialPort class. This string should be returned to MyJFrame where a label displays it. The problem was that my label would display finalString before anything
was assigned to finalString, since classes were running in different threads. I posted the question on the forum and received a suggestion to use interface to connect their threads, and I modified the code according. Where do I use the keyword implements SerialPortListener and how do I get the value?
SerialPortListener Interface code
public interface SerialPortListener {
void stringReveivedFromSerialPort(String s);
}
MyJFrame class code
public class MyJFrame extends JFrame{
public MySerialPorts msp = new MySerialPorts();
public MyJFrame(){
initComponents();//draws GUI components
initSerialPorts();//initializes serial ports
}
private void initSerialPorts(){
msp.getPortName();//gets serial port's name (in this example COM1)
msp.openPort();//opens the communication for port COM1
}
private String firmwareVersion(){
//This is the method I call when I want to get the Firmware Version
msp.getFirmwareVersion();//sends command to receive reply from serial device
lblFirmwareVersion.setText();//label that prints the firmware version String
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new MainJFrame().setVisible(true);
}
});
}
private JLabel lblFirmwareVersion;
}
MySerialPort class code
public class MySerialPort {
//this method is using the jSSC API (java simple serial connector)
//http://code.google.com/p/java-simple-serial-connector/
private SerialPort serialPort;
private int iBaudRate = SerialPort.BAUDRATE_57600;
private int iDataBits = SerialPort.DATABITS_8;
private int iStopBits = SerialPort.STOPBITS_1;
private int iParity = SerialPort.PARITY_NONE;
private String portName = "";
// private String finalString = "";
// private StringBuilder sbBuffer = new StringBuilder();
private List<SerialPortListener> portListeners = new ArrayList<SerialPortListenerInterface>();
public void addMyPortListener(SerialPortListener listener) {
portListeners.add(listener);
}
public void removeMyPortListener(SerialPortListener listener) {
portListeners.remove(listener);
}
public void getFirmwareVersion() {
sendPortCommand("<VersFV1A2>\r\n");
}
// public String returnFinalString() {
// return finalString;
// }
public void getPortName() {
String[] ports = SerialPortList.getPortNames();
portName = ports[0];
}
public void openPort() {
serialPort = new SerialPort(portName);
try {
if (serialPort.openPort()) {
if (serialPort.setParams(iBaudRate, iDataBits, iStopBits, iParity)) {
serialPort.addEventListener(new Reader(), SerialPort.MASK_RXCHAR
| SerialPort.MASK_RXFLAG
| SerialPort.MASK_CTS
| SerialPort.MASK_DSR
| SerialPort.MASK_RLSD);
} else {
//Error Message - Can't set selected port parameters!
serialPort.closePort();
}
} else {
//Error Message - Can't open port!
}
} catch (SerialPortException | HeadlessException ex) {
//Error Message - Can't open port! - Do nothing
}
}
private void sendPortCommand(String sSendPortCommand) {
if (sSendPortCommand.length() > 0) {
try {
serialPort.writeBytes(sSendPortCommand.getBytes());
} catch (Exception ex) {
//Error Message - Error occured while sending data!
}
}
}
private class Reader implements SerialPortEventListener {
private String sBuffer = "";
#Override
public void serialEvent(SerialPortEvent spe) {
if (spe.isRXCHAR() || spe.isRXFLAG()) {
if (spe.getEventValue() > 0) {
try {
//Read chars from buffer
byte[] bBuffer = serialPort.readBytes(spe.getEventValue());
sBuffer = new String(bBuffer);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
for (SerialPortListenerInterface listener : portListeners) {
listener.stringReveivedFromSerialPort(sBuffer);
}
}
});
// The following is the code I had prior to suggestion of using invokeLater instead of invokeAndWait
//
// sbBuffer.setLength(0);
//
// SwingUtilities.invokeAndWait(
// new Runnable() {
//
// #Override
// public void run() {
// sbBuffer.append(sBuffer);
// }
// });
//
// finalString = new String(sbBuffer);
} catch (Exception ex) {
}
}
}
}
}
}
Here's some code that you could add to your initSerialPorts() method, and which would open a dialog box displaying the text received from the serial port:
msp.addMyPortListener(new SerialPortListener() {
#Override
public void stringReveivedFromSerialPort(String s) {
JOptionPane.showMessageDialog(MyJFrame.this, s);
}
});
It creates an anonymous SerialPortListener instance, which displays a dialog box containing the received text as message, and adds it to your MySerialPort msp instance.
I believe that you want your MyJFrame class to implement SerialPortListener:
public class MyJFrame extends JFrame implements SerialPortListener {
/* blah */
#Override
public void stringReveivedFromSerialPort(String s) {
lblFirmwareVersion.setText(s);
}
/* blah */
}
Related
Please tell me why my program ends immediately after launch. It's a Java Telegram Bot running on my home PC. I created the project using Maven.
MainClass
public class MainClass extends TelegramWebhookBot {
BootConfig cfg = new BootConfig();
public static void main(String[] args) {
ApiContextInitializer.init();
TelegramBotsApi telegramBotsApi = new TelegramBotsApi();
try {
telegramBotsApi.registerBot(new MainClass());
} catch (TelegramApiException ex) {
ex.printStackTrace();
}
}
#Override
public BotApiMethod onWebhookUpdateReceived(Update update) {
if (update.hasMessage() && update.getMessage().hasText()) {
SendMessage sendMessage = new SendMessage();
sendMessage.setChatId(update.getMessage().getChatId().toString());
sendMessage.setText("Well, all information looks like noise until you break the code.");
return sendMessage;
}
return null;
}
#Override
public String getBotUsername() {
return cfg.WEBHOOK_USER;
}
#Override
public String getBotToken() {
return cfg.WEBHOOK_TOKEN;
}
#Override
public String getBotPath() {
return cfg.WEBHOOK_USER;
}
}
BootConfig class:
public class BootConfig {
public static final String WEBHOOK_TOKEN = "SECRET";
public static final String WEBHOOK_USER = "archopobbkbot";
Console output:
Process finished with exit code 0
My scheme: ajax long polling to Tomcat. Tomcat executes selenium "operations".
Im trying to execute selenium scenario from tomcat.
Its working ok but i need to get logs back to js client.
Javascript client partially receives messages from server when selenium working.
Inside some selenium operations im using Thread.sleep(). Maybe mistakes because of this ?
Please tell me why messages partially received (i think) by client
Here is ServerInfoLogger. BaseLogger outputs messages to console and file
public class ServerInfoLogger extends BaseLogger {
public ServerSession clientServerSession;
protected void logToClient(String message) {
super.log(message);
sendMessage(message);
}
// Server.serverSession and Server.clientServerSession not null but messages partially not received by client
private void sendMessage(String message) {
// send message to client
if (Server.serverSession!=null && Server.clientServerSession!=null) {
Server.clientServerSession.deliver(Server.serverSession, "/message", message);
} else {
System.err.println("Server error. Server.serverSession=" + Server.serverSession + " clientServerSession=" + clientServerSession);
}
}
}
Here is selenium scenario
public class Task extends ServerInfoLogger {
public static boolean datesAvailable = false;
private TaskParser parser = new TaskParser();
protected ArrayList<Step> steps = new ArrayList<>();
private WebDriver webDriver;
protected int currentStepIndex = 0;
protected Step currentStep;
private WebDriverFactory webDriverFactory = new WebDriverFactory();
private int currentTryout = 1;
private int maxTryouts = 40;
public Task(ServerSession clientServerSession, String taskData) {
this.clientServerSession = clientServerSession;
logToClient("new task"); // client always receives this message
steps = parser.parse(taskData);
logToClient("steps parsed. total: "+steps.size()); // client always receives this message
start();
}
protected void start() {
createWebDriver();
startStep();
}
protected void startStep() {
currentStep = steps.get(currentStepIndex);
currentStep.setWebDriver(webDriver);
currentStep.clientServerSession = clientServerSession;
boolean stepComplete = false;
try {
stepComplete = currentStep.start();
} catch (StepException e) {
logToClient(e.getMessage()+" step id: "+e.getStepId());
e.printStackTrace();
}
log("step complete = "+stepComplete);
if (stepComplete) {
onStepComplete();
} else {
onStepError();
}
}
private void onStepError() {
currentTryout++;
if (currentTryout > maxTryouts) {
destroyWebDriver();
logToClient("Max tryouts reached"); // client never receives this message
} else {
logToClient("Step not complete. Restarting task. currentTryout=" + currentTryout); // client partially receives this message
restart();
}
}
private void onStepComplete() {
currentStepIndex++;
if (currentStepIndex < steps.size()) {
startStep();
} else {
destroyWebDriver();
taskComplete();
}
}
private void destroyWebDriver() {
webDriver.quit();
webDriver = null;
}
private void taskComplete() {
logToClient("Task complete !!!"); // client **never** receives this message
TaskEvent taskEvent = new TaskEvent(TaskEvent.TASK_COMPLETE);
EventDispatcher.getInstance().dispatchEvent(taskEvent);
}
public void restart() {
logToClient("Task restart");
try {
setTimeout(Application.baseOperationWaitSecondsUntil);
new SwitchToDefaultContentOperation().execute();
} catch(OperationException exception) {
logToClient("Cannot get default content"); // client partially receives this message
}
currentStepIndex = 0;
startStep();
}
private void setTimeout(int seconds) {
webDriver.manage().timeouts().implicitlyWait(seconds, TimeUnit.SECONDS);
}
private void createWebDriver() {
webDriver = webDriverFactory.getDriver(BrowserType.CHROME).getDriver();
}
public int getCurrentStepIndex() {
return currentStepIndex;
}
}
Here is creation of logger
private void createLogger() {
Date currentDate = new Date();
String logFilePostfix = currentDate.getMonth()+"_"+currentDate.getDate()+"-"+currentDate.getHours()+"_"+currentDate.getMinutes()+"_"+currentDate.getSeconds();
logger = Logger.getLogger(appName);
logger.setUseParentHandlers(false);
FileHandler fh;
SimplestFormatter formatter = new SimplestFormatter();
try {
fh = new FileHandler("C:\\consultant\\logs\\log_"+logFilePostfix+".txt");
logger.addHandler(fh);
fh.setFormatter(formatter);
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Selenium operation with Thread.sleep()
public class SwitchToMainFrameOperation extends BaseOperation {
private WebElement mainIframe;
private WebDriverWait wait;
#Override
public boolean execute() throws OperationException {
switchToRoot();
sleepThread();
log("switchToMainIFrame by xPath "+Page.getMainIframeXPath()); // log to console and file
wait = new WebDriverWait(webDriver, Application.baseOperationWaitSecondsUntil);
try {
mainIframe = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(Page.getMainIframeXPath())));
webDriver.switchTo().frame(mainIframe);
log("main frame switch OK"); // log to console and file
} catch(StaleElementReferenceException exception) {
log("main frame switch error. StaleElementReferenceException - trying again"); // log to console and file
wait = null;
sleepThread();
execute();
}
return true;
}
private void switchToRoot() {
log("switch to root");
webDriver.switchTo().defaultContent();
}
private void sleepThread() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
I have a server that contains an ArrayList in " ServerInfo " and when I try to take from ClientRMI an element of the ArrayList(in ServerInfo) for example adf.getSGM ( 0 ).incrementCount( ) ;
"count" does not increase it's as if every time I call it instantiates a new class SGM
in a few words I want to interact from ClientRMI with ArrayList that is on ServerInfo (SORRY FOR ENGLISH)
Hear are the classes :
SERVER
public class ServerRMI {
public static void main(String[] args) {
Registry registry = null;
String name = "ServerInfo";
try {
System.out.println("Init RMI");
ServerInfoInterface sir = ServerInfo.getInstance();
ServerInfoInterface stub = (ServerInfoInterface) UnicastRemoteObject.exportObject(sir, 0);
registry = LocateRegistry.createRegistry(9000);
registry.bind(name, stub);
System.out.println("RMI OK");
System.out.println("Init SGM...");
for(int i=0;i<3;i++){
ServerInfo.getInstance().addSGM(new SGM());
}
System.out.println("Init SGM OK");
} catch (Exception e) {
System.out.println("RMI Error"+e.toString());
registry = null;
}
}
}
public class ServerInfo implements ServerInfoInterface{
private ArrayList<SGM> sgmHandler = new ArrayList<SGM>();
// Singleton pattern
private static ServerInfo instance;
// Singleton pattern
public static ServerInfo getInstance() {
if (instance == null){
System.out.println("ServerInfo new instance");
instance = new ServerInfo();
}
return instance;
}
#Override
public synchronized void addSGM(SGM sgm) throws RemoteException {
sgmHandler.add(sgm);
}
#Override
public synchronized SGM getSGM(int i) throws RemoteException {
return sgmHandler.get(i);
}
}
public interface ServerInfoInterface extends Remote{
public void addSGM(SGM sgm) throws RemoteException;
public SGM getSGM(int i) throws RemoteException;
}
public class SGM implements Serializable{
/**
*
*/
private static final long serialVersionUID = -4756606091542270097L;
private int count=0;
public void incrementCount(){
count++;
}
public void decrementCount(){
count--;
}
public int getCount(){
return count;
}
}
CLIENT
public class ClientRMI {
private ServerInfoInterface sgmInterface;
public void startServer() {
String name = "ServerInfo";
Registry registry;
try {
registry = LocateRegistry.getRegistry(9000);
try {
sgmInterface = (ServerInfoInterface) registry.lookup(name);
sgmInterface.getSGM(0).incrementCount();
System.out.println(sgmInterface.getSGM(0).getCount()); // always 0
} catch (AccessException e) {
System.out.println("RIM AccessException"+ e.toString());
} catch (RemoteException e) {
System.out.println("RIM RemoteException"+ e.toString());
} catch (NotBoundException e) {
System.out.println("RIM NotBoundException"+ e.toString());
}
} catch (RemoteException e) {
System.out.println("RIM RemoteException registry"+ e.toString());
}
}
}
You're creating an SGM at the server, passing it via Serialization to the client, incrementing its count at the client, and then expecting that count to be magically increased at the server.
It can't work.
You will have to make SGM a remote object, with its own remote interface, or else provide a remote method in the original remote interface to increment the count of a GSM, specified by index.
Getting error while using OutboundMessageListener and MessageListener by using this code:
public class MainClass extends UiApplication implements OutboundMessageListener,MessageListener
{
public static void main(String[] args)
{
MainClass mainClass = new MainClass();
mainClass.enterEventDispatcher();
}
public MainClass()
{
try
{
MessageConnection _mc = (MessageConnection)Connector.open("sms://");
_mc.setMessageListener(this);
}
catch (IOException e)
{
}
UiApplication.getUiApplication().pushScreen(new SmsCountScreen());
}
public void notifyIncomingMessage(MessageConnection conn)
{
UiApplication.getUiApplication().invokeAndWait(new Runnable()
{
public void run()
{
Dialog dialog = new Dialog(Dialog.D_OK, "Message Received!", 0, null, Dialog.FIELD_HCENTER);
Ui.getUiEngine().pushGlobalScreen(dialog, 1, UiEngine.GLOBAL_MODAL);
}
});
}
public void notifyOutgoingMessage(Message message)
{
UiApplication.getUiApplication().invokeAndWait(new Runnable()
{
public void run()
{
Dialog dialog = new Dialog(Dialog.D_OK, "Message Sent!", 0, null, Dialog.FIELD_HCENTER);
Ui.getUiEngine().pushGlobalScreen(dialog, 1, UiEngine.GLOBAL_MODAL);
}
});
}
}
using this code and getting error
IOException: operation not permitted on a client connection
Please help to solve this?
Looking at this example on the BlackBerry support forums, they use this code:
public class MyMessageListener implements OutboundMessageListener
{
public void notifyOutgoingMessage(javax.wireless.messaging.Message m)
{
try {
String msg = null;
msg = getMessage(m); // my call to convert Message to String
//... process msg
}
catch(Exception ex) {
// handle exception
}
}
public void notifyIncomingMessage(MessageConnection conn)
{
// handle received sms here
}
}
to register the listener
MyMessageListener ml = new MyMessageListener();
MessageConnection mc;
try {
mc = (MessageConnection)Connector.open("sms://:0");
mc.setMessageListener(el);
} catch (Exception e) {
// handle exception
}
Note that the port is specified in the Connection.open() URL. I'd also recommend testing this on a real device, not the simulators.
I'm building an application in Java which requires a Hashtable to be accessed from instances of two classes and both extend threads. I have declared the Hashtable in one of the two classes. I always get null when i try to access the Hashtable contents from one of the classes. The other class is able to access the contents without any problem. I thought this was a problem of concurrency control. Since these are threads of different classes we cannot use synchronized methods. Is there a way to make the Hashtable accessible from threads of both the classes?
Here are the some parts of the code of my application
This is the class which stores the HashMap:
public class DataStore {
public Map ChatWindows ;
public DataStore()
{
ChatWindows = new ConcurrentHashMap();
}
public synchronized void putWindow(String with,ChatWindow t)
{
ChatWindows.put(with,t);
notifyAll();
}
public synchronized ChatWindow getWindow(String with)
{
notifyAll();
return (ChatWindow)ChatWindows.get(with);
}
public synchronized void ChatWindowOpen(chatClient cc,String with,String msg)
{
// chatWith = with;
ChatWindow t;
System.out.println(with);
t = getWindow(with);
if(t == null)
{
t = new ChatWindow(cc,with,msg);
// th = new Thread(t);
putWindow(with, t);
// th.start();
}
else
{
t.setVisible(true);
}
}
}
Two classes which access 'ChatWindows' HashMap
public class chatClient extends javax.swing.JFrame implements
Runnable,ListSelectionListener,MouseListener,WindowListener{
static String LoginName,chatWith,msgToChatWindow;
Thread listThread=null,th,chatListen;
static Socket soc;
static DataOutputStream dout,dout1;
static DataInputStream din,din1;
DefaultListModel listModel;
ChatWindow t;
public DataStore ds;
/** Creates new form chatClient */
public chatClient(Login l,DataStore ds) {
listModel = new DefaultListModel();
initComponents();
clientList.addListSelectionListener(this);
clientList.addMouseListener(this);
addWindowListener(this);
this.LoginName=l.loginName;
soc = l.soc2;
din = l.din2;
dout = l.dout2;
dout1 = l.dout1;
din1 = l.din1;
super.setTitle(LoginName);
listThread = new Thread(this);
listThread.start();
this.ds = ds;
}
.
.
.
.
public void mouseClicked(MouseEvent e)
{
chatWith = (String)clientList.getSelectedValue();
ds.ChatWindowOpen(this,chatWith,"");
}
This class has run() method too, but that doesn't use the HashMap. This class is able to access the 'ChatWindows' properly.'ChatListenThread' class is not able to access the contents of HashMap properly.
public class ChatListenThread implements Runnable{
DataOutputStream dout1;
DataInputStream din1;
public static chatClient cc;
public static ChatWindow t;
public DataStore ds;
public ChatListenThread(Login l,DataStore ds)
{
din1 = l.din1;
dout1= l.dout1;
this.ds = ds;
}
.
.
.
.
public void run(){
while(true)
{
try{
String msgFromServer=new String();
msgFromServer = din1.readUTF();
StringTokenizer st=new StringTokenizer(msgFromServer);
String msgFrom=st.nextToken();
String MsgType=st.nextToken();
String msg = "";
while(st.hasMoreTokens())
{
msg=msg+" " +st.nextToken();
}
ds.ChatWindowOpen(cc,msgFrom,msg);
}
catch(IOException e)
{
System.out.println("Read failed");
}
}
}
}
It's possible. Take a look at Sharing data safely between two threads.
Okey, I couldn't use your code because I don't understand, what I did see was that you want something like this:
Create a empty JFrame with a JTabbedPane and start a thread that connects to a Socket
When input comes on the socket, create a ChatPanel (~JTextArea) and add it to one of the tabs
Add the ChatPanel to a Map that handles the messages from "from"
Pass the message to the newly created ChatPanel
So I did that and I'm posting the code below! Hope that you can use it!
If you like to test this, first start the TestChatServer (code below) and then the ChatSupervisor.
This is the code for the client
public class ChatSupervisor extends JFrame implements Runnable {
JTabbedPane tabs = new JTabbedPane();
Map<String, ChatPanel> chats = new ConcurrentHashMap<String, ChatPanel>();
public ChatSupervisor() {
super("Test Chat");
add(tabs, BorderLayout.CENTER);
new Thread(this).start();
}
public void run() {
Socket sock = null;
try {
sock = new Socket("localhost", 32134);
Scanner s = new Scanner(sock.getInputStream());
while (true) {
String from = s.next();
String type = s.next();
String message = s.nextLine();
getChat(from).incomingMessage(type, message);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (sock != null) try { sock.close(); } catch (IOException e) {}
}
}
public ChatPanel getChat(String from) {
if (!chats.containsKey(from))
chats.put(from, new ChatPanel(from));
return chats.get(from);
}
public static void main(String[] args) {
ChatSupervisor cs = new ChatSupervisor();
cs.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cs.setSize(400, 300);
cs.setVisible(true);
}
class ChatPanel extends JTextArea {
public ChatPanel(final String from) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
tabs.addTab(from, ChatPanel.this);
}
});
}
public void incomingMessage(final String type, final String message) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
append("[" + type + "]" + message);
append("\n");
}
});
}
}
}
This is the code for the test server:
public class TestChatServer {
public static void main(String[] args) throws Exception {
Socket s = new ServerSocket(32134).accept();
System.out.println("connected");
PrintWriter p = new PrintWriter(s.getOutputStream());
while (true) {
p.println("hello info Hello World!");
p.flush();
Thread.sleep(1000);
for (int i = 0; i < 10; i++) {
p.println("test" + i + " warn Testing for testing " + i);
p.flush();
Thread.sleep(100);
}
}
}
}