Rserve() error in the first instance of running a Java application - java

I am writing a Java application in IntelliJ IDE. The application uses Rserve() to connect to R and access scripts. I have a java script which sends a command to the shell to start Rserve(). The problem I am facing now is the first time when I run the application, I get the following error:
Exception in thread "main" java.lang.NoSuchMethodError: org.rosuda.REngine.REngineException.<init>(Lorg/rosuda/REngine/REngine;Ljava/lang/String;Ljava/lang/Throwable;)V
at org.rosuda.REngine.Rserve.RserveException.<init>(RserveException.java:59)
at org.rosuda.REngine.Rserve.RConnection.<init>(RConnection.java:90)
at org.rosuda.REngine.Rserve.RConnection.<init>(RConnection.java:60)
at org.rosuda.REngine.Rserve.RConnection.<init>(RConnection.java:44)
at de.uni_jena.bioinformatik.RecalibrationGUI.Application.main(Application.java:40)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
And, when the next time I run the application, it works perfectly. From what I can understand, in the first run, it just established the Rserve() connection and then in the second run it works. Can someone help me fix this, so that the application connects to Rserve() in the first instance and also runs perfectly?
Here is the java class which calls Rserve()
public class InvokeRserve {
public static boolean invoke() {
try {
Process p = Runtime.getRuntime().exec("R CMD Rserve --vanilla");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
}
catch (IOException e) {
System.out.println("Rserve connection: Exception occurred: ");
e.printStackTrace();
System.exit(-1);
}
return true;
}
}
And, here is the main java class which starts the application and calls the invoke() method:
public class Application {
/**
* Main method for the Swing application
*
* #param args
* #throws Exception
*/
public static void main(String[] args) throws Exception {
boolean value = InvokeRserve.invoke();
RConnection check = new RConnection();
if(check.isConnected())
{
// Run the GUI construction in the Event-Dispatching thread for thread-safety
SwingUtilities.invokeLater(new Runnable() {
/**
* run method which create a new GUIMain object
*/
#Override
public void run() {new GUIMain("Java Application"); // Let the constructor do the job
}
});
}
else
System.out.println("There was no R connection found.");
}
}
Also, is there a way to stop an existing Rserve() connection (I read different answers which suggest using shutdown(), but it is not working for me)? Every time, I have to restart my computer to shutdown an existing connection and start a new connection to test the above code.
I also looked into the StartRserve.java example file at http://www.rforge.net/DATRAS/files/org/rosuda/Mondrian/StartRserve.java. But when I use the method StartRserve.checkLocalRserve() in the main class of my application, I get the same Rserve() error as shown above.

Your invoke() method returns before Rserve is actually started, so you're apparently trying to connect too early. You may want to add p.waitFor();. See also the StartRserve class which is far more robust in starting Rserve from Java.
PS: I'd recommend using the stats-rosuda-devel mailing list for Rserve questions which gives you much faster responses.

I have a solution for shutting Rserve connection withoutt shutting down the computer. Try this while opening an Rconnection:
RConnection rconn=null;
try{
rconn=new RConnection();
//Your personal code here
} catch(Exception exc){
exc.printStackTrace(out);
} finally{
if (rconn!=null){
rconn.close();
}
}
This way when the app stops halfway with an exception, it still runs the finally part and closes the connection.
Hope this helps in time.
As for the exception-part details, it would be possible to answer if you could display the line numbers beside the code, as the exception log refers to the code by line numbers.

Related

Is it safe to restart Java after uncaught exception with another Java program?

I am working on a project that has to process external signals passed as an input to Java program. The signals can be corrupted (i.e. we don't have much control of the input) which may lead to processing errors (such as DivisionByZeroException).
What my team wants is that each time uncaught exception is thrown, which causes the Java program to terminate, SOME CODE should just restart the Java program from scratch.
Therefore, my main question is: Any danger of writing SOME CODE in the following way?
MY SOLUTION (SOME CODE will be another Java class):
Suppose our Java program is implemented as a method M of class C that gets called once and ideally should run forever.
I firstly make class C implement Runnable interface.
I then override run method as:
class C implements Runnable {
#Override
public void run() {
this.M();
}
public void M() {
// Code for main method to be called ONCE and ideally run FOREVER
....
}
}
Finally, I create a wrapper (called Recovery class) around class C to restart C.M() each time an exception is thrown:
class Recovery {
final Object lock = new Object();
void runAndRecover(final Runnable runnable) { // Will pass an instance of C
while (true) {
// Synchronising to make sure that only one instance
// of runnable input is running at the time.
synchronized(lock) {
try {
runnable.run();
// Ideally the process should run forever
// (no termination),
// and the code of THIS FILE will be blocked HERE
// with the runnable RUNNING (which is what we want).
} catch (Exception exception) {
// If the process was interrupted
// by uncaught exception,
// we will restart it.
lock.notifyAll();
}
}
}
}
}
What I hope is that we could run the system as follows:
public static void main(final String[] args) {
C c = new C();
Recovery recovery = new Recovery();
recovery.runAndRecover(c);
// My hope is that code gets blocked HERE and runs REGARDLESS
// of anything happening inside c. Can I make such assumption?
}
A side question: if this approach is not safe, I could then write a shell script to restart the Java program each time exception is thrown. What would be a simple shell loop to repeatedly execute command sudo java /path/to/Program? Is writing a shell script safer?

Using a Synchronized collection between threads

Code -> http://pastebin.com/1PFCGWQy
Blocks that I'm having problems with
class ClientSender implements Runnable {
Socket server;
ServerClientFrontEnd SCFE;
public ClientSender(Socket server, ServerClientFrontEnd SCFE){
this.server = server;
this.SCFE = SCFE;
}
public void run(){
try(ObjectOutputStream out = new ObjectOutputStream(server.getOutputStream())){
//System.out.println("Client chat ver. 0.1");
//Scanner get = new Scanner(System.in);
while(!server.isClosed()){
//System.out.print("YOU:");
if(!SCFE.synchronizedOutputCollection.isEmpty()) // Here
{
logger.info("Has made it to ClientSender!");
String string = SCFE.synchronizedOutputCollection.firstElement();
logger.info(string);
out.writeObject(string); // Here
logger.info("Output Queue: " + SCFE.synchronizedOutputCollection.toString());
}
//else{ logger.info("It failed the conditional"); }
}
} catch (IOException ex) {
//logger.info("Closing connection...");
//System.exit(0);
}
}
}
class ClientReceiver implements Runnable {
Socket server;
ServerClientFrontEnd SCFE;
public ClientReceiver(Socket server, ServerClientFrontEnd SCFE){
this.server = server;
this.SCFE = SCFE;
}
public void run(){
try(ObjectInputStream in = new ObjectInputStream(server.getInputStream())){
while(!server.isClosed()){
SCFE.ChatBox.setText(SCFE.ChatBox.getText() + "\nOTHER: " + (String) in.readObject()); //Here
logger.info("Receiver has read object!");
}
} catch (IOException ex) {
logger.info("Closing connection");
System.exit(0);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
For some reason, I can not get this to work. I already got it working on a command-line environment, quite perfectly, but I wanted to port it to a graphical user interface and this problem has had me stumped for more than on hour. I didn't know how to handle the fact that Client's original class called other threads which I needed to send and receive the information to and from the server.
Basically, my program works by having the client connect to the server via a ServerSocket, which THEN processes each request. Of course, I've just recently learned about sockets on Thursday but I wanted to make a program of my own... anyway, moving on, the problem is with the ServerClientFrontEnd Class, which for some reason, and I don't know how for the life of me, the collection I'm using to get the inputted text either remains empty or it just will not read from it.
Maybe it might have to do with my while loop, but it worked perfectly before. I have a TON of loggers everywhere to log everything, and if I add an else statement when it checks if the collection is empty, it definitely activates the else statement repeatedly, EVEN AFTER the synchronizedOutputCollection was given a value. In fact, I even print the value inside of the collection when the send button is pressed. In fact, when I attempt a similar print statement inside the thread, the collection is empty and it remains empty.
How can I share a synchronized collection of objects among threads? This question is plaguing me and I would really appreciate a reply.
Also this is runnable, you just have to activate server and 2 clients to test it. P.S I have tried BlockingQueues but they make the GUI thread to freeze up because the queue is never read from, causing a deadlock.
As #markspace pointed out in a comment you have lots of funny things going on in your code. You should take a step backward, go back to the command line interface and rework your entire class structure. Remove those inner classes, use some interfaces like MessageListener or ConnectionListnener that your client or server uses to talk to other classes (like your GUI) about things like messages received or connection created/lost.
When you get done your client main method should look very simple:
public static void main(String [] args) {
Client client = new Client("127.0.0.1");
client.addMessageListener(new MessageListener() {
public void messageRecieved(String message) {
System.out.println(message);
}
});
client.connect();
System.out.println("Connected to server.");
Scanner scanner = new Scanner(System.in);
String userInput = null;
boolean quit = false;
do {
userInput = scanner.readLine();
if(userInput != null && userInput.equals("quit")) {
client.sendMessage(userInput);
} else {
quit = true;
}
} while(!quit);
}
Of course I just made this up but its just an example of once you have your class structure properly broken out and things where they should be it will be very easy to hook a GUI up.
The list could go on but bottom line is you need to take a hard look at what classes need to know what information and why. Break apart classes and make fields private and dont share information unless they need to be shared! Its important that you really think about reducing code coupling.
Any way enough rambling and onto the actual problem with your code: in ServerClientFrontEnd.main you have this snipplet:
new ServerClientFrontEnd().startClient();
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ServerClientFrontEnd().setVisible(true);
}
});
You are creating 2 instances of ServerClientFrontEnd, one that starts the client the other that shows the GUI. The one that shows the GUI is the one where you change the List of strings and the other list is always empty. To make it work change the snipplet to read:
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
ServerClientFrontEnd fontEnd = new ServerClientFrontEnd();
fontEnd.startClient();
fontEnd.setVisible(true);
}
});

Java Swing application terminates unexpectedly

I'm trying to write a Swing application in Java that also runs the Google AppEngine Dev-Server (see Developing a Java Application that uses an AppEngine database) and am running into a strange problem with the Swing Eventloop.
I have the following two classes:
A debug-window, which will eventually receive log messages, etc:
public class DebugWindow {
private static JFrame debugWindow = null;
private static JTextArea debugContent = null;
public static void show() {
debugWindow = new JFrame("Debug");
debugWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
debugContent = new JTextArea("Debug messages go here!");
debugWindow.add(debugContent, BorderLayout.CENTER);
debugWindow.pack();
debugWindow.setVisible(true);
}
}
A helper-class that loads the Google AppEngine Dev-Server:
// other imports
import com.google.appengine.tools.development.DevAppServerMain;
public class DevServer {
public static void launch(final String[] args, boolean waitFor) {
Logger logger = Logger.getLogger("");
logger.info("Launching AppEngine server...");
Thread server = new Thread() {
#Override
public void run() {
try {
DevAppServerMain.main(args); // run DevAppServer
} catch (Exception e) { e.printStackTrace(); }
}
};
server.setDaemon(true); // shut down server when rest of app completes
server.start(); // run server in separate thread
if (!waitFor) return; // done if we don't want to wait for server
URLConnection cxn;
try {
cxn = new URL("http://localhost:8888").openConnection();
} catch (IOException e) { return; } // should never happen
boolean running = false;
while (!running) {
try {
cxn.connect(); // try to connect to server
running = true;
} catch (Exception e) {}
}
logger.info("Server running.");
}
}
My main(...) method looks like this:
public static void main(final String[] args) throws Exception {
DevServer.launch(args, true); // launch and wait for AppEngine dev server
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
DebugWindow.show(); // create and show debug window
}
});
}
With this I'm getting some very strange behavior regarding the Swing Eventloop:
First, the way Swing should work: If I comment out the line DevServer.launch(...) in main(...), the application launches, shows the debug window, keeps running, and when I close the debug window, it shuts down.
If I add DevServer.launch(...) back in, it launches the server as expected, and then quits immediately (it probably also showed the debug window briefly, but it's too quick to see).
If I move DevServer.launch(...) line after SwingUtilities.invokeLater(...), it shows the debug window, then launches the server, and when the server is up, it quits immediately.
Now it get's really weird: If I change the line to DevServer.launch(args, false), i.e. I don't wait for the server to actually launch, but simply let my main(...) method complete immediately, the debug window shows, the server loads correctly, the application keeps running, but doesn't quit if I close the debug window?!
If I then also change JFrame.DISPOSE_ON_CLOSE to JFrame.EXIT_ON_CLOSE, the debug window shows, the server loads correctly, the application keeps running, and it quits correctly if I close the debug window.
Any idea what is going on with the Swing event loop here? I'm stumped... Are there things that will cause the Swing event loop to terminate early (scenario 2 and 3)? Do multi-threaded applications prevent Swing from detecting the last disposed window (scenario 4)?
For reference, here is the source of the Google AppEngine Dev Server.
Items #4 and #5 are actually expected behavior. A Java/Swing application doesn't stop when the last Swing window is disposed, but when the last thread stops executing. These two conditions are equivalent for single-threaded applications, but not for multi-threaded ones.
As for #1, #2 and #3: looking through the AppEngine Dev Server code, I noticed a fair amount of System.exit(int) calls in there. One of these is probably the culprit. If the code you're showing is all that's relevant, then the offending System.exit is likely called in response to the connection established after if (!waitFor) return; (due to #4)

Java Console Restart

How can I restart my Java Console Application.
I want to create a method that when it's being called it restart or relaunch the console application. Can you guys give me some ideas how can I do it?
Have you tried calling main(args) passing in String[] args
If you really want a restart() method you could do something like
private void restart(String[] strArr)
{
main(strArr);
}
Crude mini example
import java.io.*;
public class Test{
public static void main(String[] args)
{
try{
System.out.println("Type 'R' to restart");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
if(input.equals("R"))
restart(args);
else
System.out.println("You did not restart");
}
catch(Exception e)
{e.printStackTrace();}
}
private static void restart(String[] strArr)
{
System.out.println("You restarted");
main(strArr);
}
}
I can't think of a way to do it using just Java, you will need some help from scripting. You could restart by finishing the JVM execution with System.exit() and using a special value for the caller to know if it needs to be restarted rather than finished. So in your Java code you would have something like this:
public class Test {
public static final int RESTART_CODE = 100;
public static void main(String ... args) throws IOException {
// DO something...
restart();
}
static void restart() {
System.exit(RESTART_CODE);
}
}
And then a script invoking the JVM (in this case a Linux bash script, you could do something similar with a *.bat file if you're using Windows). Tee script:
#!/bin/bash
java Test "$#"
[ $? == 100 ] && ./test.sh "$#"
An then you can call your program with
java.sh _argument1_ _argument2_ ...
Theoretically, you should be able to called Runtime.exec() and pass in the command to run your Java Console App.
For precaution, prior to calling Runtime.exec(), you should save all the data or reach the state where your application is ready to exit.
As Runtime.exec() will execute another instance of console app, and the new instance could have loaded all the data.
After successfully called Runtime.exec(), the existing app can peacefully die off.
Let me know if this can be done, as my concern is whether the new instance will be killed off when the existing app exited.

Components I used to draw a form won't appear after compile

I'm trying to create a chat program in java but I had a problem when I run the server form, that the components I used to draw won't appear.
this is the code I used in the run of the form :
public void run() {
Server s = new Server();
s.setVisible(true);
// Etablir la connexion
try
{
ServerSocket ecoute;
ecoute = new ServerSocket(1111);
Socket service = null;
System.out.println("Serveur en attente d'un client !");
while(true)
{
service = ecoute.accept();
System.out.println("Client connécté !");
DataInputStream is = new DataInputStream(service.getInputStream());
s.jTextArea1.setText("Client dit : " + is.readUTF().toUpperCase());
service.close();
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
You said nothing happens when this code is ran. The presence of a public void run() method tells me that this is a thread, or at least a Runnable.
Because of the while(true), if this thread is not started in the proper manner, it will not run independently; that is it will hold up the entire program.
Instead of calling thread.run();, call thread.start();. This will call the run method for you, after starting a new thread that will run in parallel to the main thread.
If this code is not in a thread, and you just used public void run() by chance, then it will still provide the same problem for you.
For more information, refer to the Documentation on Threads

Categories

Resources