how resolve java.security.AccessControlException - java

I'm trying to create an rmi application : the client transfer file to the serve. But , when running the code i get security manager exception.
Here is the client side :
import java.rmi.Naming;
import java.rmi.RMISecurityManager;
import java.util.Scanner;
public class StartFileClient {
public static void main(String[] args) {
if (System.getSecurityManager() == null)
System.setSecurityManager(new RMISecurityManager());
try{
FileClient c=new FileClient("imed");
FileServerInt server=(FileServerInt)Naming.lookup("rmi://localhost/abc");
server.login(c);
System.out.println("Listening.....");
Scanner s=new Scanner(System.in);
while(true){
String line=s.nextLine();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
Here is the server side :
import java.rmi.Naming;
public class StartFileServer {
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
java.rmi.registry.LocateRegistry.createRegistry(1099);
FileServer fs=new FileServer();
fs.setFile("itcrowd.avi");
Naming.rebind("rmi://localhost/abc", fs);
System.out.println("File Server is Ready");
}catch(Exception e){
e.printStackTrace();
}
}
}
Also, i create a file security.policy
grant {
permission java.security.AllPermission;
};
Thanks for helping.

Clearly your policy file isn't being found. You need to specify its location via the java.security.policy system property.
BUT Unless you're using the codebase feature, remove the security manager.

Related

Constantly receive java.lang.ClassNotFoundException

I am very new to Java and the RMI system. I am following a tutorial but I am unsure why I keep getting the following errors[1]
[1]: https://i.stack.imgur.com/xeYTn.png
I have attached the code (taken directly from the tutorial here: https://docs.oracle.com/javase/1.5.0/docs/guide/rmi/hello/hello-world.html)
I have tried:
removing any lines with 'package'
changing classpath variables
reinstalling java and javac
setting classpath in the 'rmiregistry &' command
Any help would be appreciated
edit: forgot to attach the code.
Hello.java
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Hello extends Remote {
String sayHello() throws RemoteException;
}
Client.java
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Client {
private Client() {
}
public static void main(String[] args) {
String host = (args.length < 1) ? null : args[0];
try {
Registry registry = LocateRegistry.getRegistry(host);
Hello stub = (Hello) registry.lookup("Hello");
String response = stub.sayHello();
System.out.println("response: " + response);
} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
}
Server.java
import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class Server implements Hello {
public Server() {
}
public String sayHello() {
return "Hello, world!";
}
public static void main(String args[]) {
try {
Server obj = new Server();
Hello stub = (Hello) UnicastRemoteObject.exportObject((Remote) obj, 0);
// Bind the remote object's stub in the registry
Registry registry = LocateRegistry.getRegistry();
registry.bind("Hello", stub);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
You have to run the command rmiregistry & in the folder the code is compiled into. In this case, "files"
the "getting started" tutorial didn't mention that.

Java problems with accessing resource files when application is used as library

I have two Java applications. One application will contain resource files and will be used as library to other Java application.
First app com.test.resourceusing.MainClass.java which contains res/base.xml resource file.
package com.test.resourceusing;
import java.io.BufferedInputStream;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
public class MainClass {
public MainClass() {
super();
}
public static void main(String[] args) {
MainClass main = new MainClass();
try {
main.start();
} catch (MalformedURLException e) {
}
}
public void start() throws MalformedURLException {
URL url = getClass().getResource("res/base.xml");
System.out.println(url.getPath());
System.out.println(url.getFile());
File f = new File(url.getFile());
if (f.exists()) {
System.out.println("File exist!");
BufferedInputStream result = (BufferedInputStream)
getClass().getResourceAsStream("res/base.xml");
Scanner scn = new Scanner(result);
while(scn.hasNext()){
System.out.println(scn.next());
}
} else {
System.out.println("Not working! :(");
}
}
}
Result is:
/C:/Work/Projects/ResourceUsing/classes/com/test/resourceusing/res/base.xml
/C:/Work/Projects/ResourceUsing/classes/com/test/resourceusing/res/base.xml
File exist!
<?xml
version='1.0'
encoding='utf-8'?>
<schema>
</schema>
Then I create .jar file which contains all resource files and try to use it as library in other application.
Second app:
resourcetest.MainClassTest.java
package resourcetest;
import com.test.resourceusing.MainClass;
import java.net.MalformedURLException;
public class MainClassTest {
public MainClassTest() {
super();
}
public static void main(String[] args) {
MainClass main = new MainClass();
try {
main.start();
} catch (MalformedURLException e) {
}
}
}
Result is:
file:/C:/Work/Projects/ResourceUsing/deploy/archive1.jar!/com/test/resourceusing/res/base.xml
file:/C:/Work/Projects/ResourceUsing/deploy/archive1.jar!/com/test/resourceusing/res/base.xml
Not working! :(
I don't understand why it's not working, is there problems in my code? Or this solution is not possible in Java?
Do you see the difference in the location of those files?
/C:/Work/Projects/ResourceUsing/classes/com/test/resourceusing/res/base.xml
file:/C:/Work/Projects/ResourceUsing/deploy/archive1.jar!/com/test/resourceusing/res/base.xml
You cannot access a resource that is located in a JAR file with the File API.
Your code is already on the way. A simple edit should work:
public void start() throws IOException {
URL url = getClass().getResource("res/base.xml");
if (url != null) {
System.out.println(url.getPath());
System.out.println(url.getFile());
System.out.println("File exist!");
try(InputStream result = url.openStream()) {
try(Scanner scn = new Scanner(result)) {
while(scn.hasNext()) {
System.out.println(scn.next());
}
}
}
} else {
System.out.println("Not working! :(");
}
}
After deeper searching looks like I found a reason - https://stackoverflow.com/a/10605316/1117515.
In this case I need to use getResourceAsStream().

java.net.connectexception connection timeout

hi i am using this codes for rmi
RmiServer.java
import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.*;
import java.net.*;
public class RmiServer extends java.rmi.server.UnicastRemoteObject
implements ReceiveMessageInterface
{
int thisPort;
String thisAddress;
Registry registry; // rmi registry for lookup the remote objects.
// This method is called from the remote client by the RMI.
// This is the implementation of the gReceiveMessageInterfaceh.
public void receiveMessage(String x) throws RemoteException
{
System.out.println(x);
}
public RmiServer() throws RemoteException
{
try{
// get the address of this host.
thisAddress= (InetAddress.getLocalHost()).toString();
}
catch(Exception e){
throw new RemoteException("can't get inet address.");
}
thisPort=3232; // this port(registryfs port)
System.out.println("this address="+thisAddress+",port="+thisPort);
try{
// create the registry and bind the name and object.
registry = LocateRegistry.createRegistry( thisPort );
registry.rebind("rmiServer", this);
}
catch(RemoteException e){
throw e;
}
}
static public void main(String args[])
{
try{
RmiServer s=new RmiServer();
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
RmiClient.java
import java.rmi.*;
import java.rmi.registry.*;
import java.net.*;
public class RmiClient
{
static public void main(String args[])
{
ReceiveMessageInterface rmiServer;
Registry registry;
String serverAddress=args[0];
String serverPort=args[1];
String text=args[2];
System.out.println("sending "+text+" to "+serverAddress+":"+serverPort);
try{
// get the �gregistry�h
registry=LocateRegistry.getRegistry(
serverAddress,
(new Integer(serverPort)).intValue()
);
// look up the remote object
rmiServer=
(ReceiveMessageInterface)(registry.lookup("rmiServer"));
// call the remote method
rmiServer.receiveMessage(text);
}
catch(RemoteException e){
e.printStackTrace();
}
catch(NotBoundException e){
e.printStackTrace();
}
}
}
ReceiveMessageInterface.java
import java.rmi.*;
public interface ReceiveMessageInterface extends Remote
{
public void receiveMessage(String x) throws RemoteException;
}
This works fine normally , but when the a computer is connected to internet through mobile or it shares internet from other pc it doesn't work
I get this error.
java.net.connectexception connection timeout
when i tried to telnet it fails to connect but when i try to run this program that pc
to my pc it works.
Please let me know how to solve this issue.
Sounds like a firewall or proxy server issue.

Kryonet Client connection issues Java

I have a kryonet client/server that work find.. well mostly. The client remains idle and eventually disconnects after awhile but thats not the issue i'm trying to solve currently. Currently, the server and client can establish a connection and send data back and forth(Before the client times out) as long as the client and server are on the same computer. If you try to connect to a different computer on the LAN the connection times out and fails.
So here's my question(s):
What would be a possible cause for the connection issue?
What is the proper way to keep a client alive? ( secondary goal but if you know it, that'd be great)
*I'm using LibGDX and Kryonet for this. As far as I know, they shouldn't have any conflicts.
Server:
package com.me.mygdxgame;
import java.io.IOException;
import java.util.ArrayList;
import com.badlogic.gdx.math.Vector2;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Listener;
import com.esotericsoftware.kryonet.Server;
import com.me.mygdxgame.Network.Obstacles;
public class GameServer {
Server server;
public GameServer () throws IOException {
server = new Server() {
protected Connection newConnection () {
return new PlayerConnection();
}
};
Network.register(server);
//Sends Stuff to Client
server.addListener(new Listener() {
public void received (Connection c, Object object) {
PlayerConnection connection = (PlayerConnection)c;
if (object instanceof Obstacles) {
if (connection.name != null) return;
ArrayList<Vector2> obs = ((Obstacles)object).obstacles;
if (obs == null) return;
System.out.println("Obstacles recieved.");
for(int i = 0; i < obs.size(); i++)
System.out.println("Obstacle " + i + "- x: " + obs.get(i).x );
return;
}
}
});
server.bind(Network.port);
server.start();
}
public void sendAll () { //Send out data
Obstacles ob = new Obstacles();
ob.obstacles = new ArrayList<Vector2>();
for(int i =0; i < Map.obstacles.size(); i++){
ob.obstacles.add(new Vector2(Map.obstacles.get(i).x,Map.obstacles.get(i).y));
}
server.sendToAllTCP(ob);
}
static class PlayerConnection extends Connection {
public String name;
}
}
Client:
package com.me.mygdxgame;
import java.awt.EventQueue;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import com.badlogic.gdx.ApplicationListener;
import com.esotericsoftware.kryonet.Client;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Listener;
import com.me.mygdxgame.Network.Obstacles;
public class GameClient implements ApplicationListener{
Client client;
String name;
String RefreshHost;
boolean Connected = false;
ArrayList<String> hosts = new ArrayList<String>();
public static String host;
public GameClient (String host) {
client = new Client();
client.start();
this.host = host;
Network.register(client);
client.addListener(new Listener() {
public void connected (Connection connection) {
System.out.println("connected");
Connected = true;
}
public void received (Connection connection, Object object) {
if (object instanceof Obstacles) {
Obstacles obs = (Obstacles)object;
System.out.println("Obstacle recieved on client - " + obs.obstacles.size());
client.sendTCP(obs);
System.out.println("Obstacles sent back.");
return;
}else {
System.out.println("invalid packet");
}
}
public void disconnected (Connection connection) {
EventQueue.invokeLater(new Runnable() {
public void run () {
System.out.println("closed");
Connected = false;
client.close();
}
});
}
});
new Thread("Connect") {
public void run () {
try {
client.connect(5000, GameClient.host, Network.port);
System.out.println("Connected!");
client.setKeepAliveTCP(NORM_PRIORITY);
while(Connected) {
//System.out.println(client.isIdle());
}
client.run();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}.start();
}
#Override
public void create() {
// TODO Auto-generated method stub
}
#Override
public void resize(int width, int height) {
// TODO Auto-generated method stub
}
#Override
public void render() {
// TODO Auto-generated method stub
}
#Override
public void pause() {
// TODO Auto-generated method stub
}
#Override
public void resume() {
// TODO Auto-generated method stub
}
#Override
public void dispose() {
// TODO Auto-generated method stub
}
}
I suggest you set the host BEFORE you start the client
public GameClient (String host) {
client = new Client();
this.host = host;
client.start();
I am not familiar with kryonet Client, but it makes sense to do it that way.
Generally make sure that your client is trying to connect to the host that you have server running on...
One possible cause for such connection issue is a firewall blocking your Network.port
Another one, sorry but I have to ask: Is the server-app running in the other machine?
I ask because I dont'see a main function in your server code
public static void main(String[] args) throws IOException {
Log.set(Log.LEVEL_DEBUG);
new GameServer();
}
I use to get running my server-app with this terminal command
java -jar myserverfile.jar
How do you get it running in the "remote" machine?
By the way, I am using libgdx and kryonet for my game and so far I haven't get issues using them together.
In my case I have the server in a AWS instance listening for game-client testing from my computer.

RMI access denied error all the time

i am having a problem creating RMIserver class because i keep getting this error : access denied (java.net.SocketPermission 127.0.0.1:1099 connect,resolve)
now i read on google something about cerating new policy file but i dont really understand how to do so, can please someone help me ?
here is my server code :
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.RMISecurityManager;
import java.rmi.server.UnicastRemoteObject;
import java.rmi.registry.*;
import java.security.Permission;
import java.security.Security;
public class RmiServer extends UnicastRemoteObject
implements RmiServerIntf
{
public static final String MESSAGE = "Hello world";
public RmiServer() throws RemoteException
{
}
public String getMessage()
{
return MESSAGE;
}
public static void main(String args[])
{
System.out.println("RMI server started");
// Create and install a security manager
if (System.getSecurityManager() == null)
{
System.setSecurityManager(new RMISecurityManager());
System.out.println("Security manager installed.");
}
else
{
System.out.println("Security manager already exists.");
}
try
{ //special exception handler for registry creation
LocateRegistry.createRegistry(1099);
System.out.println("java RMI registry created.");
}
catch (RemoteException e)
{
//do nothing, error means registry already exists
System.out.println("java RMI registry already exists.");
}
try
{
//Instantiate RmiServer
RmiServer obj = new RmiServer();
// Bind this object instance to the name "RmiServer"
Naming.rebind("//localhost/RmiServer", obj);
System.out.println("PeerServer bound in registry");
}
catch (Exception e)
{
System.err.println("RMI server exception:" + e);
e.printStackTrace();
}
}
}
You are using a SecurityManager (why?) but your security policy doesn't grant you the permission specified in the exception. You don't need a SecurityManager at all unless you are planning to use the RMI codebase feature: are you?
You really need to read the manual of RMI, and how to create a policy file:
http://docs.oracle.com/javase/tutorial/rmi/running.html

Categories