RMI connection refused - java

I am trying to get a rmi connection going. I have ran into many security issues but have been unable to find a way past all this. I execute my jar file with:
java -Djava.security.policy=java.security.AllPermission -jar "myjarfile"
The code I have been using to create this is:
public class server
{
public static void main(String args[])throws Exception
{
if (System.getSecurityManager() == null)
System.setSecurityManager ( new RMISecurityManager() {
public void checkConnect (String host, int port) {}
public void checkConnect (String host, int port, Object context) {}
});
try
{
sampleserverimpl server = new sampleserverimpl();
System.out.println("SERVER IS WAITING");
LocateRegistry.createRegistry(2020);
//Runtime.getRuntime().exec("rmiregistry 2020");
Naming.rebind("//localhost:2020/SERVER", server);
}
catch(Exception e)
{
System.out.println(e);
}
}
};
The error trace I am receiving is:
Exception in thread "RMI TCP Connection(idle)" java.security.AccessControlExcept
ion: access denied (java.net.SocketPermission 127.0.0.1:31199 accept,resolve)jav
a.rmi.UnmarshalException: Error unmarshaling return header; nested exception is:
java.io.EOFException
I have tried different ways to get around this, can anyone see the issue here?
Thanks

-Djava.security.policy accepts a URL which points to a policy file which in turn contains the permissions. So you should have: -Djava.security.policy=/some/path/my.policy as the JVM argument where the my.policy file contains:
grant {
permission java.security.AllPermission;
};
Also, in order to avoid the NULL check present in your code and the manual creation of a SecurityManager, you can request a SecurityManager be automatically installed for your application by passing the JVM switch: -Djava.security.manager.
Your final JVM invocation should look like:
java -Djava.security.manager -Djava.security.policy=/some/path/my.policy

This is two separate exceptions. The first is a permission problem. The second one, the EOFException, could have any of a number of causes. I would need to see java -version and the complete stack trace to assist further.

Related

How to open a websocket directly to a wss: in Java

I am trying to establish a websocket connection in java to wss://data.tradingview.com/socket.io/websocket?from=chart%2F&date=2023_01_26-12_41&type=chart to acquire both historical and current chart data.
I have search and read through multiple posts and online resources and I am confused as to the correct procedure to connect to a websocket and acquire incoming data.
I found a post that is very close to what I'm trying to do that open a websocket and uses a ws as the target location. Here I've modified it slightly to implement the solution suggested.
import java.io.IOException;
import java.net.URI;
import javax.websocket.*;
#ClientEndpoint
public class ExampleTest2 {
Session session;
//Problem resolved, this original echo server is no longer operational
//private final static String url = "ws://echo.websocket.org:80";
private final static String url = "wss://websocket-echo.com:443/";
public static void main(String[] args) throws Exception, IOException {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
System.out.println("connecting...");
container.connectToServer(ExampleTest2.class,
URI.create(url));
System.out.println("Press ENTER key to exit.");
System.in.read();
}
#OnMessage
public void newMessage(String message, Session session) {
System.out.println(message);
}
#OnOpen
public void newConnection(Session session) throws IOException {
this.session = session;
System.out.println("The connection has been started");
session.getBasicRemote().sendText("hello");
}
#OnClose
public void disconnection() {
System.out.println("The connection has been ended");
}
}
This is the error output I receive.
Exception in thread "main" java.lang.RuntimeException: Could not find an implementation class.
at javax.websocket.ContainerProvider.getWebSocketContainer(ContainerProvider.java:73)
at ExampleTest2.main(ExampleTest2.java:14)
I continued to search and found a post about that specific error. Here Their solution is to use a different external library. I was using javax.websocket-api-1.1.jar now I've switched to their recommendation of tyrus, tyrus-standalone-client-2.1.2
However it's still not connecting properly.
Exception in thread "main" jakarta.websocket.DeploymentException: Handshake error.
at org.glassfish.tyrus.client.ClientManager$3$1.run(ClientManager.java:658)
at org.glassfish.tyrus.client.ClientManager$3.run(ClientManager.java:696)
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at org.glassfish.tyrus.client.ClientManager$SameThreadExecutorService.execute(ClientManager.java:849)
at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:118)
at org.glassfish.tyrus.client.ClientManager.connectToServer(ClientManager.java:493)
at org.glassfish.tyrus.client.ClientManager.connectToServer(ClientManager.java:299)
at ExampleTest2.main(ExampleTest2.java:19)
Caused by: org.glassfish.tyrus.core.HandshakeException: Response code was not 101: 200.
at org.glassfish.tyrus.client.TyrusClientEngine.processResponse(TyrusClientEngine.java:301)
at org.glassfish.tyrus.container.grizzly.client.GrizzlyClientFilter.handleHandshake(GrizzlyClientFilter.java:323)
at org.glassfish.tyrus.container.grizzly.client.GrizzlyClientFilter.handleRead(GrizzlyClientFilter.java:292)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:88)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:246)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:178)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:118)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:96)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:51)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:510)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:82)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:83)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:101)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:535)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:515)
at java.base/java.lang.Thread.run(Thread.java:832)
At this point I am very much in the weeds and I'm not even sure if I'm going in the right direction anymore I'm just following rabbit hole after rabbit hole. At this point I'm trying to resolve indirect problems that I'm not even sure if it is required to accomplish my task of opening a socket and acquiring data.
Any help like code examples or learning material directly related to the task would be greatly appreciated.
I just found the solution. The original server in the code is no longer operation. I used this one instead "wss://websocket-echo.com:443/"

Error message not going away in Netbeans, why? "java.net.BindException: Address already in use: bind"

It seems like a duplicate question of how to kill a process already running on that port, but it is a different question. When I killed the process and restart it, it still gives me that error message, seems like Netbeans has a problem, and the error message got stuck and keeps appearing even when the port is not in use.
I've used the tool at : http://www.yougetsignal.com/tools/open-ports/ to check the port : 6600
Here is what it says :
My code looks like the following :
import java.io.*;
import java.util.*;
import com.sun.net.httpserver.*;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import Utility.*;
public class Http_Server
{
static int Port=6600,Thread_Count=50,Resume_Count=0; // 8080
InetSocketAddress addr;
HttpServer server;
static String App_Id="Resume_App";
static Resume_Loader Resume_loader;
static Get_Time Timer=new Get_Time();
static Vector<String> Current_Keywords_Vector=new Vector();
static boolean Debug_B=true;
public Http_Server(int Port)
{
if (Port>-1) this.Port=Port;
Srart_Server();
}
void Srart_Server()
{
try
{
Resume_loader=new Resume_Loader();
addr=new InetSocketAddress(Port);
server=HttpServer.create(addr,0); // Line : 34
server.createContext("/"+App_Id,new MyHandler(server));
server.setExecutor(Executors.newCachedThreadPool());
server.start();
Out("Server is listening on port : "+Port);
}
catch (Exception e)
{
Resume_App.Save_To_Log(e.toString()+"\n"+Tool_Lib_Simple.Get_Stack_Trace(e));
e.printStackTrace();
Out(e.toString());
}
}
private static void out(String message) { System.out.print(message); }
private static void Out(String message) { System.out.println(message); }
public static void main(String[] args) { Http_Server Demo=new Http_Server(-1); }
}
It was running fine yesterday, but this morning I changed :
InetSocketAddress addr; to static InetSocketAddress addr;
HttpServer server; to static HttpServer server;
When I ran it, I got the following error message :
Server is listening on port : 6600
java.net.BindException: Address already in use: bind
at sun.nio.ch.Net.bind0(Native Method)
at sun.nio.ch.Net.bind(Net.java:437)
at sun.nio.ch.Net.bind(Net.java:429)
at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223)
at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
at sun.net.httpserver.ServerImpl.<init>(ServerImpl.java:100)
at sun.net.httpserver.HttpServerImpl.<init>(HttpServerImpl.java:50)
at sun.net.httpserver.DefaultHttpServerProvider.createHttpServer(DefaultHttpServerProvider.java:35)
at com.sun.net.httpserver.HttpServer.create(HttpServer.java:130)
at Http_Server.Srart_Server(Http_Server.java:34)
at Http_Server.<init>(Http_Server.java:24)
at Http_Server.main(Http_Server.java:51)
Then I realize if they are static, they might keep them selves in memory and occupy the port, so I changed them back to non-static like the above code. But now when I run it, the error message keeps appearing, and in Netbeans there is a "notification" saying something like : "package-info.class is in wrong place, delete it or put it in the right sub directory ..." don't remember the exact wording. But when I open the url, the web page works fine as if there is no error message, and when I stop the server the page won't appear as it supposed to be.
So it seems like a Netbeans 8.0.2 malfunctioning, but I don't know how to make the error message not appear, or as it suggested how to delete "package-info.class" or put it into the correct sub dir, I can't even find where it is, how to fix it ?
Regarding :
there is a "notification" saying something like : "package-info.class is in wrong place, delete it or put it in the right sub directory ..." don't remember the exact wording
Please make it happen again and copy and paste or screenshot the exact wording into your question.
I think it would be much better to explicitly call shutdown() on your ExecutiveService and stop(1) on your HttpServer rather than hoping garbage collection will do it. And it would allow you to control print some messages confirming it.
eg.
InetSocketAddress addr = new InetSocketAddress(6600);
ExecutorService es = Executors.newCachedThreadPool();
HttpServer server = HttpServer.create(addr, 0);;
server.createContext("/foo", new HttpHandler() {
#Override
public void handle(HttpExchange he) throws IOException {
String response = "My Response";
he.sendResponseHeaders(200, response.length());
OutputStream os = he.getResponseBody();
os.write(response.getBytes());
os.close();
}
});
server.setExecutor(es);
server.start();
System.out.println("Press enter to stop server.");
// block waiting for user to press enter.
System.in.read();
System.out.println("Shutting down");
server.stop(1);
es.shutdownNow();
System.out.println("should be shutdown now.");
Also at the bottom of netbeans there is a status line.
If you see this you need to click the little x to stop whatever process you launched but perhaps forgot about.

ConsoleAppender is blocking

I am not sure what is happening here. I am starting a RMI server in a separate JVM. While connecting to the instance calling the remote method, the method get stuck after a very short time. The execution continues as soon as I shutdown the client process.
What am I doing wrong?
class Client
...
//name some kind of name
String name= "HelloService";
//libname points to a runnable jar with the server class as main class
ProcessBuilder jvm= new ProcessBuilder(javaPath, "-jar", libname, "-n", name);
jvm.start();
//Waiting for RMI server to start
try { Thread.sleep(10000); } catch ...
try {
Registry registry= LocateRegistry.getRegistry(1199);
//String as input and String as output
IRemoteService<String, String> service= (IRemoteService<String, String>) registry.lookup(name)
String returnVal= service.execute("SomeValue");
return returnVal;
} catch ...
Following by the server code snip. The server code is packed in a runnable jar with itself as the MainClass.
class Server implements IRemoteService<String, String>
//Is not returning a value, due the fact that I liked to examine the behaviour of
//this method. Doing this by running an infinite loop.
public String execute(String str) {
log.info("Running doExectue from "+getClass().getSimpleName());
int i=0;
while(true) {
i++;
log.info(String.valueOf(i));
}
}
protected static void register(String name, IRemoteService service) {
try {
IRemoteService rsStub= (IRemoteService) UnicastRemoteObject.exportObject(service,0);
Registry registry= LocateRegistry.getRegistry(1199);
try {
registry.bind(name, rsStub);
} catch (ConnectException ce) {
registry= LocateRegistry.createRegistry(1199);
registry.bind(name, rsStub);
}
} catch ...
}
public static void main(String[] args) {
String rmiName= args[1];
IRemoteService<String, String> service= (IRemoteService<String, String>) new Server();
register(rmiName, service);
}
Now if I start the client the log file displayes 36 runs of the loop in method "execute". Than it stops. There is no other client getting this object or calling this method too.
It starts a again and is running forever as soon as I killed the Client process.
For me it looks like that the client is blocking the execution of the remote server methods. But I have no clue how to overcome this situation.
Thanks for any help in advance,
Danny
What you describe is impossible. The client can't block the server while the server is executing a remote method. Find another explanation.
thanks for your support. You are right a RMI client can't block the server. So I was really confused. But I found the failure.
It about the process is writing to the console. As soon as the buffer is full the process is stopping to wait for someone collecting the output.
After I removed the ConsoleAppender from the log configuration the job runs as expected.

Rserve Exception: Handshake failed

I am new to language R
and was trying a simple program in java using RConnection but it is giving this exception
org.rosuda.REngine.Rserve.RserveException: Handshake failed: expected 32 bytes header, got -1
at org.rosuda.REngine.Rserve.RConnection.<init>(RConnection.java:107)
at org.rosuda.REngine.Rserve.RConnection.<init>(RConnection.java:60)
at org.rosuda.REngine.Rserve.RConnection.<init>(RConnection.java:44)
at test.sandeep.main(sandeep.java:9)
thats in the contuctor of RConnection. Can anyone tell what might be wrong
package test;
import org.rosuda.REngine.Rserve.RConnection;
public class sandeep {
public static void main(String[] str) {
try {
System.out.println("hii");
RConnection c = new RConnection();
System.out.println("hii");
double d[] = c.eval("rnorm(10)").asDoubles();
for (double td : d) {
System.out.println(td);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
The error says that read has failed immediately after connecting to Rserve. Your Java code is fine (assumint you are connecting to a local instance of Rserve). The issue is likely on the other side -- check that Rserve is running (see Rserve FAQ). You can also start Rserve in debug mode (Rserve(TRUE) in R) to see what happens on the server side.
If you are running RServe on a linux box, make sure that you have the configuration file in /etc/ location with name "Rserv.conf" and with contents
remote enable
This enables remote access to RServe

"Could not load known_hosts" exception using SSHJ

I am getting an exception while using SSHJ.
Here is how I implemented it:
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
final SSHClient ssh = new SSHClient();
ssh.loadKnownHosts();
ssh.connect("serverName");
try{
ssh.authPublickey("myUserId");
final Session session = ssh.startSession();
try{
final Command cmd = session.exec("net send myMachineName Hello!!!");
System.out.println(cmd.getOutputAsString());
System.out.println("\n Exit Status: "+cmd.getExitStatus());
}finally{
session.close();
}
}finally{
ssh.disconnect();
}
}
}
But I get the following exception:
Exception in thread "main" java.io.IOException: Could not load known_hosts
at net.schmizz.sshj.SSHClient.loadKnownHosts(SSHClient.java:528)
at SSHTEST.main(SSHTEST.java:25)
What am I doing wrong?
Use the folowing code
final SSHClient ssh = new SSHClient();
ssh.addHostKeyVerifier(
new HostKeyVerifier() {
public boolean verify(String arg0, int arg1, PublicKey arg2) {
return true; // don't bother verifying
}
}
);
ssh.connect("LocalHost");
Remove the call to loadKnownHosts() method, which as erickson mentioned checks under ~/.ssh/known_hosts by default (you can specify the location as an argument as well though), and replace it with:
ssh.addHostKeyVerifier("public-key-fingerprint");
To find out what the fingerprint is, the twisted way would be to connect without that statement - you'll find out from the exception ;-)
It sounds like it's trying to read a "known_hosts" file, but can't find it, or possibly it in an invalid format.
The SSH known hosts file records the public key for various hosts to thwart some spoofing attacks. Normally it resides in ~/.ssh/known_hosts. Try creating an empty file there and see if that satisfies the library.
The library documentation is likely to address the necessary configuration files.

Categories