I start Rserve:
C:\Program Files\R\R-3.5.0\bin\x64> "C:\Users\XXXX\DOCUME~1\R\WIN-LI~1\3.5\Rserve\libs\x64\Rserve.exe" --RS-port 1000
Run the following java code:
import org.rosuda.REngine.REXPMismatchException;
import org.rosuda.REngine.Rserve.RConnection;
import org.rosuda.REngine.Rserve.RserveException;
public class TestR {
private RConnection con;
private RConnection con2;
public TestR(){
try {
con = new RConnection();
con2 = new RConnection();
} catch (RserveException e) {
e.printStackTrace();
}
}
public Double test(){
try {
double d = con.eval("1+1").asDouble();
double c = con2.eval("1+1").asDouble();
return d+c;
} catch (RserveException | REXPMismatchException e) {
return (double)(-1);
}
}
}
I created the following class on JUnit to test it:
import org.junit.Test;
import static org.junit.Assert.*;
public class TestRTest {
#Test
public void test(){
TestR t = new TestR();
t.test();
}
}
When I run this test, it stops while instaciating the connections, it creates the first one, but does hangs on the second. Any idea why this could be happening?
ok
ok
hangs
Your issue might be related to a problem with Multithreading.
Unix: no problem, one Rserve instance can serve mulitple calls.
Windows: Rserve can't create a seperate process by forking the current process.
--> create a new Rserve process for each thread (listening on a different port), a new Rserve connection on the corresponding port has to be established as well.
RConnection connection = new RConnection(HOST, PORT);
If you need more input, do not hesitate to ask. I can also provide my full class code for creating several R instances with Rserve if you want to.
See this Java class I used to run several instances of R with Rserve.
Related
I'm trying to make a basic java echo client server app and the textbook I'm reading says I should run the Server.java file first and then the Client.java second. But for some reason VSCode doesn't seem to be doing that. I run my Server.java file and get this which is what I'm expecting:
Simple Echo Server
Waiting for connection.....
And then I go to my Client.java file and run that, but nothing happens there are no errors, it stays at the two lines shown above, I can CTRL+C to terminate the batch job.
I'm expecting it to say this:
Simple Echo Server
Waiting for connection.....
Connected to client
But that's not happening - I am getting no errors though. I don't think it's a problem with my code since it's identical to the textbook's but I'll post it here.
Server.java
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws Exception {
System.out.println("Simple Echo Server");
try (ServerSocket serverSocket = new ServerSocket(6000)) {
System.out.println("Waiting for connection.....");
Socket clientSocket = serverSocket.accept();
System.out.println("Connected to client");
} catch (IOException ex) {
}
}
}
Client.java
import java.io.*;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws Exception {
try {
System.out.println("Waiting for connection.....");
InetAddress localAddress = InetAddress.getLocalHost();
try (Socket clientSocket = new Socket(localAddress, 6000);
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))) {
}
}
catch (IOException ex) {
} // Handle exceptions
}
}
Is it possible that VS code can't run two java files at one time?
EDIT Tried the dual configuration below, but the result is the same, nothing is changing.
It's achievable in VS Code.
Click to create launch.json, keep the default configurations which should be similar to mine in the following picture then add compounds in it:
Turn to the selection box and choose compounds to run by clicking the left green triangle button, you'll get your wanted result:
I am developing a Client-Server application with several other programmers, in Java. At this point in time I do not want to be running the code locally. I want to be able to connect to the Server from any machine.
I wrote a test server and test client, just to make sure that things are working properly. But they are not. I am using Amazon AWS EC2 Linux that comes with Java. I am able to compile and run my Server after I SSH into the EC2, but the Client on my local disk is just not connecting. Here is the code.
// Code found online (https://cs.lmu.edu/~ray/notes/javanetexamples/)
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
public class TestServer {
public static void main(String[] args) throws Exception {
try (ServerSocket listener = new ServerSocket(50000)) {
System.out.println("The capitalization server is running...");
System.out.println(listener.getInetAddress());
ExecutorService pool = Executors.newFixedThreadPool(20);
while (true) {
pool.execute(new Capitalizer(listener.accept()));
}
}
}
private static class Capitalizer implements Runnable {
private Socket socket;
Capitalizer(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
System.out.println("Connected: " + socket);
try {
Scanner in = new Scanner(socket.getInputStream());
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
while (in.hasNextLine()) {
out.println(in.nextLine().toUpperCase());
}
} catch (Exception e) {
System.out.println("Error:" + socket);
} finally {
try { socket.close(); } catch (IOException e) {}
System.out.println("Closed: " + socket);
}
}
}
}
// Code found online (https://cs.lmu.edu/~ray/notes/javanetexamples/)
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class TestClient {
public static void main(String[] args) throws Exception {
try (Socket socket = new Socket("ADDRESS HERE", 50000)) {
System.out.println("Enter lines of text then Ctrl+D or Ctrl+C to quit");
Scanner scanner = new Scanner(System.in);
Scanner in = new Scanner(socket.getInputStream());
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
while (scanner.hasNextLine()) {
out.println(scanner.nextLine());
System.out.println(in.nextLine());
}
}
}
}
In place of "ADDRESS HERE" in the Client, I have tried the private IP and public IP of my Amazon EC2 instance. I have also tried the public DNS name. Nothing seems to work. There is just no connection from the Client to the Server. In fact, "Enter lines of text then Ctrl+D or Ctrl+C to quit" never prints.
All help is appreciated. Thank you.
Allow your IP address to send request to the EC2. For this, you need to go to your Security Group and add your IP there. Follow these steps-
GO to your AWS console.
Click on EC2, then under Resources you will find Security Groups.
Select your security group.
Follow the steps in the given image.
Since you're able to connect to EC2 instance via SSH, your Security Group allows this.
Now you need to allow requests from the client in this Security Group. You will either need to provide a concrete IP, IP range or allow all IPs (not recommended) in the group.
You can find how to do this here.
Hi I am setting up rserve based on the instructions on this website.
http://www.codophile.com/how-to-integrate-r-with-java-using-rserve/
However in eclipse I am getting an error when using 'eval'
double d[] = c.eval("rnorm(10)").asDoubles();
error - 'The method eval(String) is undefined for the type RConnection'
The JARS have been correctly loaded into the build path and rserve is running, however I cannot figure out why only the eval function is causing an issue.
In addition to this the import of ...
import org.rosuda.REngine.Rserve.RConnection;
causes an error - 'The import org.rosuda.REngine.Rserve.RConnection conflicts with a type defined in the same file'
does anyone have any idea why this is the case? Thanks
all imports :
import org.rosuda.REngine.REXPMismatchException;
import org.rosuda.REngine.Rserve.RConnection;
import org.rosuda.REngine.Rserve.RserveException;
public class RConnection {
public int[] mean(String a[]) {
setupR();
return null;
}
public void setupR(){
try {
/* Create a connection to Rserve instance running
* on default port 6311
*/
RConnection c = new RConnection();// make a new local connection on default port (6311)
double d[] = c.eval("rnorm(10)").asDoubles();
org.rosuda.REngine.REXP x0 = c.eval("R.version.string");
System.out.println(x0.asString());
} catch (RserveException e) {
e.printStackTrace();
} catch (REXPMismatchException e) {
e.printStackTrace();
}
}
}
By using import org.rosuda.REngine.Rserve.RConnection; you are tying to make RConnection known in the local namespace.
However, you already defined a class called RConnection locally.
Please rename your class RConnection, and you should be able to import org.rosuda.REngine.Rserve.RConnection.
So, i done search for this question..
My directories and files structure looks like (all *.java files have server package):
run2 (shell script)
[server] (folder)
\
\ Server.java
ClientThread.java
ServerConnectionManager.java
.. some other files ...
run2 contains:
find . -name "*.class" -type f -delete
javac -classpath .:server:server/lib/mysqlconn.jar server/Server.java
java -classpath .:server:server/lib/mysqlconn.jar server.Server
As you see, it runs Server. Go look there:
package server;
// imports
public class Server {
public static final int BUFFSIZE = 32;
public static void main (String[] args) throws IOException {
ServerConnectionManager server = new ServerConnectionManager(1234);
server.start();
server.acceptConnections();
server.shutdown();
}
}
Nothing weird in this class, right? Anyway, i think like that.
In this class, as we see, Server create instance of ServerConnectionManager
and call some functions.
Go look at acceptConnections:
public void acceptConnections() {
while(true) {
try {
Socket clientConnection = connection.accept();
ClientThread client = new ClientThread(clientConnection);
/*clients.add(client);
client.start();
System.out.println("[INF] Client connected");
System.out.println("[INF] Summary: " + clients.size() + " clients connected");*/
} catch (IOException e) {
System.out.println("[ERR] Accepting client connection failed");
}
}
}
I commented some lines. I really not need them now.
More about problem:
When i run run2 - server runs and works fine. netstat shows what server wait for connections.
But when i run client, and try connect to server, it shows to me next error:
Exception in thread "main" java.lang.NoClassDefFoundError: server/ClientThread
at server.ServerConnectionManager.acceptConnections(ServerConnectionManager.java:36)
at server.Server.main(Server.java:15)
Caused by: java.lang.ClassNotFoundException: server.ClientThread
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 2 more
I can't understand, why i have this exception ?
Look at directories and files. ClientThread.java exists and placed into server directory and have server package. Compilation doesn't show any error.
What i doing wrong?
There is connection class for client
package client;
// imports
public class ClientConnectionManager {
public Socket connection;
public String host;
public Integer port;
public Boolean connected;
public ClientConnectionManager(String h, Integer p) {
host = h;
port = p;
}
public void connect() {
try {
connection = new Socket(host, port);
} catch (IOException e) {
System.out.println("[INF] Failed connect to server");
}
}
public void disconnect() {
try {
connection.close();
} catch (IOException e) {
System.out.println("[ERR] Connection closing failed");
}
}
}
package server;
// some imports just not removed yet
import java.io.IOException;
import java.net.*;
import java.lang.*;
import java.io.*;
import java.util.*;
import java.sql.*;
class ClientThread extends Thread {
public Socket clientSocket;
public OutputStream out;
public InputStream in;
public Tasks tasks;
public User user;
public ClientThread(Socket socket) {
clientSocket = socket;
try {
out = clientSocket.getOutputStream();
in = clientSocket.getInputStream();
} catch (IOException e) {
System.out.println("Cant initialize I/O in for client socket");
}
}
public void run() {
ServerDatabaseConnectionManager database = new ServerDatabaseConnectionManager();
database.connect();
tasks = new Tasks(database.connection);
user = new User(database.connection);
/** listen for requests from client*/
try {
out.write(new String("_nelo_").getBytes());
} catch (IOException e) {
System.out.println("Cant send auth cmd");
}
ServerInputHandler listen = new ServerInputHandler(this);
listen.start();
}
}
You need to compile ClientThread.java as well
add this before running as well
javac -classpath .:server:server/lib/mysqlconn.jar server/ClientThread.java
This is painful way of managing classpath and compilation, better go for some IDE and build tool (maven)
Server.java does not import ClientThread.java or use ClientThread at all inside the Server class, so your compiler ignores compiling it.
In order to fix this problem, simply include ClientThread.java in the batch you use to compile your project.
javac -classpath .:server:server/lib/mysqlconn.jar server/ClientThread.java
I suggest you look into an IDE though
What is the preferred way of passing data (a list of string) from a Java program to a Python script. The python script performs some processing on the data and then I need to get the results back in my Java program.
Is there is a framework that allows you to do this easily?
EDIT: More specific requirements.
My Java program is a scheduler (runs every X minutes and Y seconds ) that connects to an external service and gets the RAW data and send it to python.
I can rewrite everything in Python but that will take a me good amount of time. I was looking if there is a way to reuse what I already have.
I want to use an existing Python script with minimal change. My python script uses a bunch of external libraries (e.g., numpy)
The data passed from Java to Python is in Json format and the data returned by Python is also Json.
Using sockets is an options but then I've to run server processes.
I hacked this together a couple of months ago when I was faced with an similar problem. I avoided Jython because I wanted separate processes. The Java code is the server as it listens for requests but it doesn't re-connect on failure. The concept is is that the classes are extended threads that have a socket member so the send and receive commands can block the object threads and leave the host threads unaffected.
Python Code:
import StringIO
import re
import select
import socket
import sys
import threading
class IPC(threading.Thread):
def __init__(self, line_filter = None):
threading.Thread.__init__(self)
self.daemon = True
self.lock = threading.Lock()
self.event = threading.Event()
self.event.clear()
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.recv_buffer_size = 8192
self.buffer = StringIO.StringIO()
if(line_filter == None):
self.line_filter = lambda x: x
else:
self.line_filter = line_filter
def run(self):
self.sock.connect(("localhost", 32000))
data = True
while data:
try:
data = self.sock.recv(self.recv_buffer_size)
except socket.error, e:
print e
self.sock.close()
break
self.lock.acquire()
self.buffer.write(data)
self.lock.release()
self.event.set()
def readlines(self):
self.lock.acquire()
self.buffer.seek(0)
raw_lines = self.buffer.readlines()
self.buffer.truncate(0)
self.lock.release()
lines = map(self.line_filter, raw_lines)
return lines
proc_control = IPC()
while True:
proc_control.event.wait()
data = proc_control.readlines()
if(data):
# Do Stuff
proc_control.event.clear()
Java Code:
SocketIPC.java:
package project;
import java.net.Socket;
import java.net.ServerSocket;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.PrintWriter;
import java.io.OutputStreamWriter;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class SocketIPC {
public PrintWriter out;
public BufferedReader in;
Socket socket = null;
ServerSocket serverSocket = null;
ConnectionListener connlisten = null;
DataListener datalisten = null;
Thread connlisten_thread = null;
Thread datalisten_thread = null;
CommandObject ipc_event_cmd = null;
// Server thread accepts incoming client connections
class ConnectionListener extends Thread {
private int port;
ConnectionListener(int port) {
this.port = port;
}
#Override
public void run() {
try {
serverSocket = new ServerSocket(port);
socket = serverSocket.accept();
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
datalisten = new DataListener();
datalisten_thread = new Thread(datalisten);
datalisten_thread.start();
} catch (Exception e) {
System.err.println("SocketIPC creation error: " + e.getMessage());
}
}
}
// Server thread accepts incoming client connections
class DataListener extends Thread {
String data_str = null;
DataListener() {
}
#Override
public void run() {
try {
while(true) {
data_str = recv();
ipc_event_cmd.buffer.add(data_str);
ipc_event_cmd.execute();
}
} catch (Exception e) {
System.err.println("SocketIPC reading error: " + e.getMessage());
}
}
public String read() {
String ret_string = null;
if(!ipc_event_cmd.buffer.isEmpty()) {
ret_string = ipc_event_cmd.buffer.remove(0);
}
return ret_string;
}
}
public SocketIPC(int port) {
ipc_event_cmd = new CommandObject();
connlisten = new ConnectionListener(port);
connlisten_thread = new Thread(connlisten);
connlisten_thread.start();
}
public void send(String msg) {
if (out != null) {
out.println(msg);
}
}
public void flush() {
if (out != null) {
out.flush();
}
}
public void close() {
if (out != null) {
out.flush();
out.close();
try {
in.close();
socket.close();
serverSocket.close();
} catch (Exception e) {
System.err.println("SocketIPC closing error: " + e.getMessage());
}
}
}
public String recv() throws Exception {
if (in != null) {
return in.readLine();
} else {
return "";
}
}
public void set_cmd(CommandObject event_cmd) {
if (event_cmd != null) {
this.ipc_event_cmd = event_cmd;
}
}
}
CommandObject.java:
package project;
import java.util.List;
import java.util.ArrayList;
public class CommandObject {
List<String> buffer;
public CommandObject() {
this.buffer = new ArrayList<String>();
}
public void execute() {
}
}
DoStuff.java:
package project;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Random;
public class DoStuff extends CommandObject {
public DoStuff () {
}
#Override
public void execute() {
String tmp_string = null;
while (!buffer.isEmpty()) {
tmp_string = buffer.remove(0);
// Do Stuff
}
}
}
Sounds like a job for Jython! Jython is an embeddedable Python runtime written in Java. As long as you don't need to run your Python script in another process (e.g., want to be able to kill it, may use lots of memory, etc.), this is the best way by far.
If you are trying to work Java and python together then make your life simple with Jython.
Jython, successor of JPython, is an implementation of the Python
programming language written in Java. Jython programs can import and
use any Java class. Except for some standard modules, Jython programs
use Java classes instead of Python modules. Jython includes almost all
of the modules in the standard Python programming language
distribution, lacking only some of the modules implemented originally
in C.
Assuming you have java lib in your python path. Here is a code snippet to give you an idea how simple it is to use the java classes:
'''
Import JavaUtilities class from a java package
'''
from com.test.javalib import JavaUtilities
'''
Call a java method
'''
response = JavaUtilities.doSomething();
Please have a look Jython,which is best for communication between java and Python.