Solved

Simple RMI Example

Posted on 2004-03-24
31
424 Views
Last Modified: 2013-12-29
Hello all,

I am having trouble getting a simple RMI program to run. I want to setup a client and a server on each machine, so that a client can query the opposing server and vice versa. It is a game of battlefields. Can someone please look at this code and let me know if it is wrong, or if it is because I am compiling it wrong. The error seems to be with the Naming.rebind in setupServer(). I have put hostnameinhere for now as the host names but they are setup right. The test classes, one calls attack() to start calling the remote lookup() method and the other waits for his turn using defend().


import java.rmi.*;
import java.rmi.server.*;

/* Sets up the Server and places object in RMI Registry */

public class Game extends UnicastRemoteObject implements RemoteGrid {
    final int X = 10;
    final int Y = 10;
    private String[] [] playerGrid = new String[X] [Y];
    final String miss = "MISS";
    final String hitA = "HIT AIRCRAFT CARRIER";
    final String hitB = "HIT BATTLESHIP";
    final String hitC = "HIT CRUISER";
    final String hitS = "HIT SUBMARINE";

    public Game() throws RemoteException {
        super();
    }

    public String lookup(int xCoord, int yCoord) {
        // lookup in here
        if (playerGrid[xCoord] [yCoord].equals("0")) {
            /* send miss */

            return miss;
        } else if (playerGrid[xCoord] [yCoord].equals("A")) {
             /* send HIT aircraft carrier */

            return hitA;
        } else if (playerGrid[xCoord] [yCoord].equals("C")) {
            /* send HIT cruiser */

            return hitC;
        } else if (playerGrid[xCoord] [yCoord].equals("B")) {
            /* send HIT battleship */

            return hitB;
        } else if (playerGrid[xCoord] [yCoord].equals("S")) {
            /* send HIT submarine */

            return hitS;
        } else {
            /* Error */

            System.out.println("Error");
            return "Error";
        }
    }
    // this should be main method
    public void setupServer(String[] [] getPlayerGrid) {
        playerGrid = getPlayerGrid;
        if (System.getSecurityManager() == null) {
            System.setSecurityManager(new RMISecurityManager());
        }
        String name = "//hostnameinhere/RemoteGrid";
        try {
            /* Setup a Game object */

            RemoteGrid theRemoteGrid = new Game();
            Naming.rebind(name, theRemoteGrid);
            System.out.println("Game bound");
        } catch (Exception e) {
            System.err.println("Game exception: " + e.getMessage());
            e.printStackTrace();
        }
    }
}


import java.rmi.*;
import java.math.*;

public class LocalGame {
    RemoteGrid opponentGrid = null;
    int winningCounter = 0;
    String FLAG = "";

    public void setupClient() {
        if (System.getSecurityManager() == null) {
            System.setSecurityManager(new RMISecurityManager());
        }
        try {
            String name = "//hostnameinhere/RemoteGrid";
            RemoteGrid opponentGrid = (RemoteGrid) Naming.lookup(name);
            // call lookup in here on opponentGrid
        } catch (Exception e) {
            System.err.println("LocalGame exception: " +
                               e.getMessage());
            e.printStackTrace();
        }
    }

   // pass in grid
    public void attack(GridBuilder theGrid) {
        int[] shipCoords = new int[2];
        int x, y;
        shipCoords = theGrid.getCoords("SHOTCOORDS");
        x = shipCoords[0];
        y = shipCoords[1];
        String result = "";
        try {
            result = opponentGrid.lookup(x,y);
            FLAG = result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (result.equals("MISS")) {
                System.out.println("MISS!");
                defend(theGrid); // switch to defending
                } else {
                System.out.println("You HIT A " + result);
                winningCounter++;
                if (winningCounter == 50) {
                    System.out.println("YOU ARE THE BATTLESHIPS LEGEND!!!!!");
                    System.exit(0);
                }
                attack(theGrid);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void defend(GridBuilder theGrid){
        while (!FLAG.equals("MISS")){
        }
        attack(theGrid);

    }

}


public class GameTest {
       public static void main(String[] args) {
        final int X = 10;
        final int Y = 10;
        String[] [] playerGrid = new String[X] [Y];
        GridBuilder theGrid = new GridBuilder();
        LocalGame localGame = new LocalGame();
        try {
            Game game = new Game();
            theGrid.initialseGrids(); // Initialise grids
            theGrid.addPlayerShips(); // Allow player to add ships to grid
            playerGrid = theGrid.getGrid(); // Get local copy of completed grid
            localGame.setupClient(); // Set up a client
            game.setupServer(playerGrid); // Set up a server with the local grid
            localGame.defend(theGrid);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}



public class GameTestTwo {
    public static void main(String[] args) {
        final int X = 10;
        final int Y = 10;
        String[] [] playerGrid = new String[X] [Y];
        GridBuilder theGrid = new GridBuilder();
        LocalGame localGame = new LocalGame();
        try {
            Game game = new Game();
            theGrid.initialseGrids(); // Initialise grids
            theGrid.addPlayerShips(); // Allow player to add ships to grid
            playerGrid = theGrid.getGrid(); // Get local copy of completed grid
            localGame.setupClient(); // Set up a client
            game.setupServer(playerGrid); // Set up a server with the local grid
            localGame.attack(theGrid);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

0
Comment
Question by:mtcmedia
  • 14
  • 13
  • 2
31 Comments
 
LVL 30

Expert Comment

by:mayankeagle
ID: 10668063
>> Can someone please look at this code and let me know if it is wrong, or if it is because I am compiling it wrong.

Do you get any errors while compiling? What errors and at what lines? And if you don't get any compilation errors but get exceptions while running, then pls tell us at which lines and what exceptions.
0
 
LVL 14

Expert Comment

by:Daniel Junges
ID: 10669241

Make sure that you have starte the rmiregistry.exe before start the server application. rmiregistry muss know the server classpath.
0
 
LVL 2

Author Comment

by:mtcmedia
ID: 10669399
This is what I have tried:

$ javac *.java
$ rmic Game
$ rmiregistry &

$java -Djava.rmi.server.codebase=http://urlinhere/~username/BattleShipsRMI/ GameTest


LocalGame exception: access denied (java.net.SocketPermission urlwasinhere resolve)
java.security.AccessControlException: access denied (java.net.SocketPermission urlwasinhere  resolve)
        at java.security.AccessControlContext.checkPermission(AccessControlContext.java:272)
        at java.security.AccessController.checkPermission(AccessController.java:399)
        at java.lang.SecurityManager.checkPermission(SecurityManager.java:545)
        at java.lang.SecurityManager.checkConnect(SecurityManager.java:1042)
        at java.net.InetAddress.getAllByName0(InetAddress.java:559)
        at java.net.InetAddress.getAllByName0(InetAddress.java:540)
        at java.net.InetAddress.getByName(InetAddress.java:449)
        at java.net.Socket.<init>(Socket.java:100)
        at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:25)
        at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:120)
        at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:499)
        at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:190)
        at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:174)
        at sun.rmi.server.UnicastRef.newCall(UnicastRef.java:318)
        at sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source)
        at java.rmi.Naming.lookup(Naming.java:84)
        at LocalGame.setupClient(LocalGame.java:16)
        at GameTest.main(GameTest.java:22)
Game exception: access denied (java.net.SocketPermission urlwasinhere resolve)
java.security.AccessControlException: access denied (java.net.SocketPermission urlwasinhere resolve)
        at java.security.AccessControlContext.checkPermission(AccessControlContext.java:272)
        at java.security.AccessController.checkPermission(AccessController.java:399)
        at java.lang.SecurityManager.checkPermission(SecurityManager.java:545)
        at java.lang.SecurityManager.checkConnect(SecurityManager.java:1042)
        at java.net.InetAddress.getAllByName0(InetAddress.java:559)
        at java.net.InetAddress.getAllByName0(InetAddress.java:540)
        at java.net.InetAddress.getByName(InetAddress.java:449)
        at java.net.Socket.<init>(Socket.java:100)
        at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:25)
        at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:120)
        at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:499)
        at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:190)
        at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:174)
        at sun.rmi.server.UnicastRef.newCall(UnicastRef.java:318)
        at sun.rmi.registry.RegistryImpl_Stub.rebind(Unknown Source)
        at java.rmi.Naming.rebind(Naming.java:160)
        at Game.setupServer(Game.java:62)
        at GameTest.main(GameTest.java:23)

I have removed the actual server addresses with "urwasinhere" for security reasons.
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 10669494
Do you have a policy file?
0
 
LVL 14

Expert Comment

by:Daniel Junges
ID: 10669562


-Check if the lastest stubs are present in http://urlinhere/~username/BattleShipsRMI/

-Try to run it without  -Djava.rmi.server.codebase=...
0
 
LVL 2

Author Comment

by:mtcmedia
ID: 10669583
I dont have a policy file, and I put the stubs in another directory at as I though I had to do that?

http://urlinhere/~username/codebase/
0
 
LVL 14

Expert Comment

by:Daniel Junges
ID: 10669774

you can try to replace you setSecurityManager with the follow:

if (System.getSecurityManager() == null) {      
      System.setSecurityManager(new RMISecurityManager() {
            public void checkConnect(String host, int port) {
            }
            public void checkConnect(String host, int port, Object context) {
            }
      });
}// if you use it then you not need policy files

0
 
LVL 2

Author Comment

by:mtcmedia
ID: 10669796
What is the checkConnect method for? Its empty? Ill try keeping the stubs in http://urlinhere/~username/BattleShipsRMI/, and running without  -Djava.rmi.server.codebase
0
 
LVL 14

Expert Comment

by:Daniel Junges
ID: 10670080

take a look at http://www.ccs.neu.edu/home/kenb/com3337/rmi_tut.html#secure


i have an rmi interface in my application. The difference is that i leave the stubs in the same directory as the server and client classes. it works without trouble. the only incovenience for me is to copy the stubs to client sides directory.
0
 
LVL 2

Author Comment

by:mtcmedia
ID: 10670153
I just checked, and the stubs are in the correct directory, when I moved them I copied them, so they were still in the same directory as the server and client classes.

Do I have to copy the stubs myself to the client sides directory? If so, this will mean I have to do it both ways, and wont they have the same filenames and just overwrite?? eg Game_Stub.class and Game_Skel.class
0
 
LVL 14

Expert Comment

by:Daniel Junges
ID: 10670712

I suggest: firstly try to run both, client and server, on the same mashine, with subs in same directory. Use above setSecurityManager and test again.
0
 
LVL 2

Author Comment

by:mtcmedia
ID: 10670962
Where will I put your security manager?

Also, when I use rmic to generate the stubs, do I have to move them anywhere or do they just get left in the working directory?
0
 
LVL 14

Expert Comment

by:Daniel Junges
ID: 10671114


in your code replace all
-----------------------------------------------------------------
 if (System.getSecurityManager() == null) {
            System.setSecurityManager(new RMISecurityManager());
  }
-----------------------------------------------------------------
with
-----------------------------------------------------------------
if (System.getSecurityManager() == null) {    
     System.setSecurityManager(new RMISecurityManager() {
          public void checkConnect(String host, int port) {
          }
          public void checkConnect(String host, int port, Object context) {
          }
     });
-----------------------------------------------------------------

i go home now, i see your posting tomorrow

0
 
LVL 2

Author Comment

by:mtcmedia
ID: 10671418
When I run it, using the security manager you gave me in both places, and I also use "rmi://localhost/RemoteGrid", this is what happened:

$ java *.java
Exception in thread "main" java.lang.NoClassDefFoundError: Game/java
rmic Game
$ rmiregistry &
[1] 1715
$ java GameTest
NOTE: Please enter all coordinates in the form x,y!

Please enter a coordinate for your Aircraft Carrier:
0,0
Is the Aircraft Carrier facing North N, South S, West W or East E:
Please Enter N, S, W or E:
E

Please enter a coordinate for your Cruiser:
1,0
Is the Cruiser facing North N, South S, West W or East E:
Please Enter N, S, W or E:
E
Sorry The Coordinates/Orientation You Entered Are Occupied/Out Of Range.

Please enter a coordinate for your Cruiser:
2,0
Is the Cruiser facing North N, South S, West W or East E:
Please Enter N, S, W or E:
E

Please enter a coordinate for your Cruiser:
3,0
Is the Cruiser facing North N, South S, West W or East E:
Please Enter N, S, W or E:
E

Please enter a coordinate for your Battleship:
4,0
Is the Battleship facing North N, South S, West W or East E:
Please Enter N, S, W or E:
E

Please enter a coordinate for your Battleship:
5,0
Is the Battleship facing North N, South S, West W or East E:
Please Enter N, S, W or E:
E

Please enter a coordinate for your Battleship:
6,0
Is the Battleship facing North N, South S, West W or East E:
Please Enter N, S, W or E:
E

Please enter a coordinate for your Battleship:
7,0
Is the Battleship facing North N, South S, West W or East E:
Please Enter N, S, W or E:
E

Please enter a coordinate for your Submarine:
8,0
Is the Submarine facing North N, South S, West W or East E:
Please Enter N, S, W or E:
E

Please enter a coordinate for your Submarine:
9,0
Is the Submarine facing North N, South S, West W or East E:
Please Enter N, S, W or E:
E

Please enter a coordinate for your Submarine:
8,2
Is the Submarine facing North N, South S, West W or East E:
Please Enter N, S, W or E:
E

Please enter a coordinate for your Submarine:
8,4
Is the Submarine facing North N, South S, West W or East E:
Please Enter N, S, W or E:
E

Please enter a coordinate for your Submarine:
8,6
Is the Submarine facing North N, South S, West W or East E:
Please Enter N, S, W or E:
E

Please enter a coordinate for your Submarine:
9,2
Is the Submarine facing North N, South S, West W or East E:
Please Enter N, S, W or E:
E
All ships successfully added to grid.
Contacting other player to initiliase game.
 A A A A A 0 0 0 0 0
 0 A A A A A 0 0 0 0
 C C C C C C 0 0 0 0
 C C C C C C 0 0 0 0
 B B B B 0 0 0 0 0 0
 B B B B 0 0 0 0 0 0
 B B B B 0 0 0 0 0 0
 B B B B 0 0 0 0 0 0
 S S S S S S S S 0 0
 S S S S 0 0 0 0 0 0
9,java.security.AccessControlException: access denied (java.net.SocketPermission 138.251.200.28:33042 accept,resolve)
        at java.security.AccessControlContext.checkPermission(AccessControlContext.java:272)
        at java.security.AccessController.checkPermission(AccessController.java:399)
        at java.lang.SecurityManager.checkPermission(SecurityManager.java:545)
        at java.lang.SecurityManager.checkAccept(SecurityManager.java:1162)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.checkAcceptPermission(TCPTransport.java:567)
        at sun.rmi.transport.tcp.TCPTransport.checkAcceptPermission(TCPTransport.java:206)
        at sun.rmi.transport.Transport$1.run(Transport.java:151)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.Transport.serviceCall(Transport.java:148)
        at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:465)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:706)
        at java.lang.Thread.run(Thread.java:484)
Game bound
4java.security.AccessControlException: access denied (java.net.SocketPermission 138.251.200.28:33044 accept,resolve)
        at java.security.AccessControlContext.checkPermission(AccessControlContext.java:272)
        at java.security.AccessController.checkPermission(AccessController.java:399)
        at java.lang.SecurityManager.checkPermission(SecurityManager.java:545)
        at java.lang.SecurityManager.checkAccept(SecurityManager.java:1162)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.checkAcceptPermission(TCPTransport.java:567)
        at sun.rmi.transport.tcp.TCPTransport.checkAcceptPermission(TCPTransport.java:206)
        at sun.rmi.transport.Transport$1.run(Transport.java:151)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.Transport.serviceCall(Transport.java:148)
        at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:465)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:706)
        at java.lang.Thread.run(Thread.java:484)
java.security.AccessControlException: access denied (java.net.SocketPermission 138.251.200.28:33045 accept,resolve)
        at java.security.AccessControlContext.checkPermission(AccessControlContext.java:272)
        at java.security.AccessController.checkPermission(AccessController.java:399)
        at java.lang.SecurityManager.checkPermission(SecurityManager.java:545)
        at java.lang.SecurityManager.checkAccept(SecurityManager.java:1162)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.checkAcceptPermission(TCPTransport.java:567)
        at sun.rmi.transport.tcp.TCPTransport.checkAcceptPermission(TCPTransport.java:206)
        at sun.rmi.transport.Transport$1.run(Transport.java:151)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.Transport.serviceCall(Transport.java:148)
        at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:465)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:706)
        at java.lang.Thread.run(Thread.java:484)
java.security.AccessControlException: access denied (java.net.SocketPermission 138.251.200.28:33046 accept,resolve)
        at java.security.AccessControlContext.checkPermission(AccessControlContext.java:272)
        at java.security.AccessController.checkPermission(AccessController.java:399)
        at java.lang.SecurityManager.checkPermission(SecurityManager.java:545)
        at java.lang.SecurityManager.checkAccept(SecurityManager.java:1162)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.checkAcceptPermission(TCPTransport.java:567)
        at sun.rmi.transport.tcp.TCPTransport.checkAcceptPermission(TCPTransport.java:206)
        at sun.rmi.transport.Transport$1.run(Transport.java:151)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.Transport.serviceCall(Transport.java:148)
        at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:465)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:706)
        at java.lang.Thread.run(Thread.java:484)
java.security.AccessControlException: access denied (java.net.SocketPermission 138.251.200.28:33047 accept,resolve)
        at java.security.AccessControlContext.checkPermission(AccessControlContext.java:272)
        at java.security.AccessController.checkPermission(AccessController.java:399)
        at java.lang.SecurityManager.checkPermission(SecurityManager.java:545)
        at java.lang.SecurityManager.checkAccept(SecurityManager.java:1162)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.checkAcceptPermission(TCPTransport.java:567)
        at sun.rmi.transport.tcp.TCPTransport.checkAcceptPermission(TCPTransport.java:206)
        at sun.rmi.transport.Transport$1.run(Transport.java:151)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.Transport.serviceCall(Transport.java:148)
        at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:465)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:706)
        at java.lang.Thread.run(Thread.java:484)
java.security.AccessControlException: access denied (java.net.SocketPermission 138.251.200.28:33048 accept,resolve)
        at java.security.AccessControlContext.checkPermission(AccessControlContext.java:272)
        at java.security.AccessController.checkPermission(AccessController.java:399)
        at java.lang.SecurityManager.checkPermission(SecurityManager.java:545)
        at java.lang.SecurityManager.checkAccept(SecurityManager.java:1162)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.checkAcceptPermission(TCPTransport.java:567)
        at sun.rmi.transport.tcp.TCPTransport.checkAcceptPermission(TCPTransport.java:206)
        at sun.rmi.transport.Transport$1.run(Transport.java:151)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.Transport.serviceCall(Transport.java:148)
        at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:465)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:706)
        at java.lang.Thread.run(Thread.java:484)
java.security.AccessControlException: access denied (java.net.SocketPermission 138.251.200.28:33049 accept,resolve)
        at java.security.AccessControlContext.checkPermission(AccessControlContext.java:272)
        at java.security.AccessController.checkPermission(AccessController.java:399)
        at java.lang.SecurityManager.checkPermission(SecurityManager.java:545)
        at java.lang.SecurityManager.checkAccept(SecurityManager.java:1162)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.checkAcceptPermission(TCPTransport.java:567)
        at sun.rmi.transport.tcp.TCPTransport.checkAcceptPermission(TCPTransport.java:206)
        at sun.rmi.transport.Transport$1.run(Transport.java:151)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.Transport.serviceCall(Transport.java:148)
        at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:465)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:706)
        at java.lang.Thread.run(Thread.java:484)
java.security.AccessControlException: access denied (java.net.SocketPermission 138.251.200.28:33050 accept,resolve)
        at java.security.AccessControlContext.checkPermission(AccessControlContext.java:272)
        at java.security.AccessController.checkPermission(AccessController.java:399)
        at java.lang.SecurityManager.checkPermission(SecurityManager.java:545)
        at java.lang.SecurityManager.checkAccept(SecurityManager.java:1162)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.checkAcceptPermission(TCPTransport.java:567)
        at sun.rmi.transport.tcp.TCPTransport.checkAcceptPermission(TCPTransport.java:206)
        at sun.rmi.transport.Transport$1.run(Transport.java:151)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.Transport.serviceCall(Transport.java:148)
        at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:465)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:706)
        at java.lang.Thread.run(Thread.java:484)
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 2

Author Comment

by:mtcmedia
ID: 10671434
I had to cancel it as it kept on repeating those exceptions. Can anyone else help while junges is away?
0
 
LVL 14

Expert Comment

by:Daniel Junges
ID: 10675767

Hi mtcmedia,

try to disable completely the  System.setSecurityManager(...) part.
I saw that i have do it because my jdbc connection security issues.
0
 
LVL 2

Author Comment

by:mtcmedia
ID: 10676226
Looking on the Sun site, they say that you need to install a security manager. HELP!!!

Can someone try and run the code, and see if they can help?
0
 
LVL 14

Expert Comment

by:Daniel Junges
ID: 10678865

i canot build it for tests
i missing the class GridBuilder
0
 
LVL 2

Author Comment

by:mtcmedia
ID: 10679786
Sorry, here it is:

/* Generated by Together */

import java.io.*;
import java.util.*;

public class GridBuilder {
    /**
     * Value for the size of the grid. The number of rows in the grids.
     */
    final int X = 10;

    /**
     * Value for the size of the grid. The number of columns in the grids.
     */
    final int Y = 10;

        /* 2 x 2D Arrays for grids A[row][column] */

    /**
     * Grid data structure to hold the local player ships.
     */
    private String[] [] playerGrid = new String[X] [Y];

    /**
     * Grid data structure to hold the local player guesses.
     */
    private String[] [] guessGrid = new String[X] [Y];

    public String[] [] getGrid() {
        return playerGrid;
    }

        /** Initialise method to initialise two main data stuctures by filling with "0"'s. */
    public void initialseGrids() {
        /* Fill grids with 0's */

        for (int i = 0; i < X; i++) {
            for (int j = 0; j < Y; j++) {
                playerGrid[i] [j] = "0";
                guessGrid[i] [j] = "0";
            }
        }
    }

    /* Holder method allow user to place ships */

    /** Method to allow the player to place their ships on their local grid. */
    public void addPlayerShips() {
        System.out.println("NOTE: Please enter all coordinates in the form x,y!");
        String[] shipTypes = new String[4];
        int[] shipCoords = new int[2];
        String orientation = "";
        int x, y, count;
        shipTypes[0] = "Aircraft Carrier";
        shipTypes[1] = "Cruiser";
        shipTypes[2] = "Battleship";
        shipTypes[3] = "Submarine";

        /* Get Details For Aircraft Carrier And Add To Grid */

        shipCoords = getCoords(shipTypes[0]);
        x = shipCoords[0];
        y = shipCoords[1];
        orientation = getOrientation(shipTypes[0]);
        while (addACarrier(x, y, orientation) == false) { //if not added to grid successfully
            System.out.println("Sorry The Coordinates/Orientation You Entered Are Occupied/Out Of Range.");
            shipCoords = getCoords(shipTypes[0]);
            x = shipCoords[0];
            y = shipCoords[1];
            orientation = getOrientation(shipTypes[0]);
        }

        /* Get Details For Other Ships And Add To Grid */

        /* Add Cruisers x 2 */

        for (int i = 0; i < 2; i++) {
            count = 6;
            shipCoords = getCoords(shipTypes[1]);
            x = shipCoords[0];
            y = shipCoords[1];
            orientation = getOrientation(shipTypes[1]);
            while (addGenericShip(x, y, count, shipTypes[1], orientation) == false) {
                System.out.println("Sorry The Coordinates/Orientation You Entered Are Occupied/Out Of Range.");
                shipCoords = getCoords(shipTypes[1]);
                x = shipCoords[0];
                y = shipCoords[1];
                orientation = getOrientation(shipTypes[1]);
            }
        }

           /* Add Battleships x 4 */

        for (int i = 0; i < 4; i++) {
            count = 4;
            shipCoords = getCoords(shipTypes[2]);
            x = shipCoords[0];
            y = shipCoords[1];
            orientation = getOrientation(shipTypes[2]);
            while (addGenericShip(x, y, count, shipTypes[2], orientation) == false) {
                System.out.println("Sorry The Coordinates/Orientation You Entered Are Occupied/Out Of Range.");
                shipCoords = getCoords(shipTypes[2]);
                x = shipCoords[0];
                y = shipCoords[1];
                orientation = getOrientation(shipTypes[2]);
            }
        }

                   /* Add Submarines x 6 */

        for (int i = 0; i < 6; i++) {
            count = 2;
            shipCoords = getCoords(shipTypes[3]);
            x = shipCoords[0];
            y = shipCoords[1];
            orientation = getOrientation(shipTypes[3]);
            while (addGenericShip(x, y, count, shipTypes[3], orientation) == false) {
                System.out.println("Sorry The Coordinates/Orientation You Entered Are Occupied/Out Of Range.");
                shipCoords = getCoords(shipTypes[3]);
                x = shipCoords[0];
                y = shipCoords[1];
                orientation = getOrientation(shipTypes[3]);
            }
        }
        System.out.println("All ships successfully added to grid.");
        System.out.println("Contacting other player to initiliase game.");
        printGrid();
    }

    /** Method to print out the current contents of the local grid. */
    public void printGrid() {
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 10; j++) {
                System.out.print(" " + playerGrid[i] [j]);
            }
            System.out.println();
        }
    }

    /** Method to allow the user to enter coordinates. */
    public int[] getCoords(String shipType) {
        int[] shipCoords = new int[2];
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String str = "";
        int x = 0;
        int y = 0;
        char cX;
        char cY;
        System.out.println("");
        if (shipType.equals("SHOTCOORDS")) {
            try {
                System.out.println("Please enter a coordinate to fire at: ");
                str = in.readLine();
                cX = str.charAt(0);
                cY = str.charAt(2);
                x = (cX - 48);
                y = (cY - 48);
                shipCoords[0] = x;
                shipCoords[1] = y;
            } catch (IOException e) {
                System.out.println(e);
            }
            return shipCoords;
        } else {
            try {
                System.out.println("Please enter a coordinate for your " + shipType + ": ");
                str = in.readLine();
                cX = str.charAt(0);
                cY = str.charAt(2);
                x = (cX - 48);
                y = (cY - 48);
            } catch (IOException e) {
                System.out.println(e);
            }
            shipCoords[0] = x;
            shipCoords[1] = y;
            return shipCoords;
        }
    }

    /** Method to allow the user to enter an orientation. */
    public String getOrientation(String shipType) {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String str = "";
        try {
            System.out.println("Is the " + shipType + " facing North N, South S, West W or East E: ");
            System.out.println("Please Enter N, S, W or E: ");
            str = in.readLine();
        } catch (IOException e) {
            System.out.println(e);
        }
        return str;
    }

        /* Generic Ship Placement */

    /** Generic add method to deal with adding all ship types (apart from Aircraft Carrier) to the local grid. */
    public boolean addGenericShip(int x, int y, int count, String shipType, String orientation) {
        int xPos = x;
        int yPos = y;
        int xPosC = x;
        int yPosC = y;
        if (orientation.equals("E")) {
            /* First check all of the allocated coords are free */

            for (int i = 0; i < count; i++) {
                if (xPosC <= 9 && xPosC >= 0 && yPosC <= 9 && yPosC >= 0 && playerGrid[xPosC] [yPosC].equals("0")) {
                    yPosC++;
                } else {
                    return false;
                }
            }

            /* Now place in the grid */

            for (int i = 0; i < count; i++) {
                if (shipType.equals("Cruiser")) {
                    playerGrid[xPos] [yPos] = "C";
                } else if (shipType.equals("Battleship")) {
                    playerGrid[xPos] [yPos] = "B";
                } else if (shipType.equals("Submarine")) {
                    playerGrid[xPos] [yPos] = "S";
                }
                yPos++; // increment column
            }
            return true;
        } else if (orientation.equals("S")) {
                        /* First check all of the allocated coords are free */

            for (int i = 0; i < count; i++) {
                if (xPosC <= 9 && xPosC >= 0 && yPosC <= 9 && yPosC >= 0 && playerGrid[xPosC] [yPosC].equals("0")) {
                    xPosC++;
                } else {
                    return false;
                }
            }

            /* Now place in the grid */

            for (int i = 0; i < count; i++) {
                if (shipType.equals("Cruiser")) {
                    playerGrid[xPos] [yPos] = "C";
                } else if (shipType.equals("Battleship")) {
                    playerGrid[xPos] [yPos] = "B";
                } else if (shipType.equals("Submarine")) {
                    playerGrid[xPos] [yPos] = "S";
                }
                xPos++; // increment row
            }
            return true;
        } else if (orientation.equals("W")) {
            /* First check all of the allocated coords are free */

            for (int i = 0; i < count; i++) {
                if (xPosC <= 9 && xPosC >= 0 && yPosC <= 9 && yPosC >= 0 && playerGrid[xPosC] [yPosC].equals("0")) {
                    yPosC--;
                } else {
                    return false;
                }
            }

            /* Now place in the grid */

            for (int i = 0; i < count; i++) {
                if (shipType.equals("Cruiser")) {
                    playerGrid[xPos] [yPos] = "C";
                } else if (shipType.equals("Battleship")) {
                    playerGrid[xPos] [yPos] = "B";
                } else if (shipType.equals("Submarine")) {
                    playerGrid[xPos] [yPos] = "S";
                }
                yPos--; // decerement column
            }
            return true;
        } else if (orientation.equals("N")) {
            /* First check all of the allocated coords are free */

            for (int i = 0; i < count; i++) {
                if (xPosC <= 9 && xPosC >= 0 && yPosC <= 9 && yPosC >= 0 && playerGrid[xPosC] [yPosC].equals("0")) {
                    xPosC--;
                } else {
                    return false;
                }
            }

            /* Now place in the grid */

            for (int i = 0; i < count; i++) {
                if (shipType.equals("Cruiser")) {
                    playerGrid[xPos] [yPos] = "C";
                } else if (shipType.equals("Battleship")) {
                    playerGrid[xPos] [yPos] = "B";
                } else if (shipType.equals("Submarine")) {
                    playerGrid[xPos] [yPos] = "S";
                }
                xPos--; // decrement row
            }
            return true;
        }
        return true;
    }

        /* Aircraft Carrier Placement */

    /** Method to allow the adding of an aircraft carrier to the local grid. */
    public boolean addACarrier(int x, int y, String orientation) {
        int xPos = x;
        int yPos = y;
        int xPosC = x;
        int yPosC = y;
        if (orientation.equals("E")) {
            /* First check all of the allocated coords are free */

            for (int i = 0; i < 5; i++) {
                if (xPosC <= 9 && xPosC >= 0 && yPosC <= 9 && yPosC >= 0 && playerGrid[xPosC] [yPosC].equals("0")) {
                    yPosC++;
                } else {
                    return false;
                }
            }
            yPosC = y + 1; // increment column
            xPosC = x + 1; // increment row
            for (int j = 0; j < 5; j++) {
                if (xPosC <= 9 && xPosC >= 0 && yPosC <= 9 && yPosC >= 0 && playerGrid[xPosC] [yPosC].equals("0")) {
                    yPosC++; // increment column
                } else {
                    return false;
                }
            }

            /* Now place in the grid */

            for (int i = 0; i < 5; i++) {
                playerGrid[xPos] [yPos] = "A";
                yPos++; // increment column
            }
            yPos = y + 1; // increment column
            xPos = x + 1; // increment row
            for (int j = 0; j < 5; j++) {
                playerGrid[xPos] [yPos] = "A";
                yPos++; // increment column
            }
            return true;
        } else if (orientation.equals("S")) {
            /* First check all of the allocated coords are free */

            for (int i = 0; i < 5; i++) {
                if (xPosC <= 9 && xPosC >= 0 && yPosC <= 9 && yPosC >= 0 && playerGrid[xPosC] [yPosC].equals("0")) {
                    xPosC++;
                } else {
                    return false;
                }
            }
            yPosC = y - 1; // derement column
            xPosC = x + 1; // increment row
            for (int j = 0; j < 5; j++) {
                if (xPosC <= 9 && xPosC >= 0 && yPosC <= 9 && yPosC >= 0 && playerGrid[xPosC] [yPosC].equals("0")) {
                    xPosC++; // increment column
                } else {
                    return false;
                }
            }

            /* Now place in the grid */

            for (int i = 0; i < 5; i++) {
                playerGrid[xPos] [xPos] = "A";
                xPos++; // increment row
            }
            yPos = y - 1; // derement column
            xPos = x + 1; // increment row
            for (int j = 0; j < 5; j++) {
                playerGrid[xPos] [yPos] = "A";
                xPos++;
            }
            return true;
        } else if (orientation.equals("W")) {
            /* First check all of the allocated coords are free */

            for (int i = 0; i < 5; i++) {
                if (xPosC <= 9 && xPosC >= 0 && yPosC <= 9 && yPosC >= 0 && playerGrid[xPosC] [yPosC].equals("0")) {
                    xPosC++;
                } else {
                    return false;
                }
            }
            yPosC = y - 1; // derement column
            xPosC = x + 1; // increment row
            for (int j = 0; j < 5; j++) {
                if (xPosC <= 9 && xPosC >= 0 && yPosC <= 9 && yPosC >= 0 && playerGrid[xPosC] [yPosC].equals("0")) {
                    xPosC++; // increment column
                } else {
                    return false;
                }
            }

            /* Now place in the grid */

            for (int i = 0; i < 5; i++) {
                if (xPos <= 9 && xPos >= 0 && yPos <= 9 && yPos >= 0 && playerGrid[xPos] [yPos].equals("0")) {
                    yPos--;
                } else {
                    return false;
                }
            }
            yPos = y - 1; // derement column
            xPos = x - 1; // decrement row
            for (int j = 0; j < 5; j++) {
                if (xPos <= 9 && xPos >= 0 && yPos <= 9 && yPos >= 0 && playerGrid[xPos] [yPos].equals("0")) {
                    yPos--; // increment column
                } else {
                    return false;
                }
            }
            for (int i = 0; i < 5; i++) {
                playerGrid[xPos] [xPos] = "A";
                yPos--; // decrement column
            }
            yPos = y - 1; // derement column
            xPos = x - 1; // decrement row
            for (int j = 0; j < 5; j++) {
                playerGrid[xPos] [yPos] = "A";
                yPos--;
            }
            return true;
        } else if (orientation.equals("N")) {
            /* First check all of the allocated coords are free */

            for (int i = 0; i < 5; i++) {
                if (xPosC <= 9 && xPosC >= 0 && yPosC <= 9 && yPosC >= 0 && playerGrid[xPosC] [yPosC].equals("0")) {
                    xPosC--;
                } else {
                    return false;
                }
            }
            yPosC = y - 1; // increment column
            xPosC = x - 1; // decrement row
            for (int j = 0; j < 5; j++) {
                if (xPosC <= 9 && xPosC >= 0 && yPosC <= 9 && yPosC >= 0 && playerGrid[xPosC] [yPosC].equals("0")) {
                    xPosC--; // increment column
                } else {
                    return false;
                }
            }

            /* Now place in the grid */

            for (int i = 0; i < 5; i++) {
                playerGrid[xPos] [xPos] = "A";
                xPos--; // decrement row
            }
            yPos = y - 1; // increment column
            xPos = x - 1; // decrement row
            for (int j = 0; j < 5; j++) {
                playerGrid[xPos] [yPos] = "A";
                xPos--;
            }
            return true;
        }
        return true;
    }



}
0
 
LVL 14

Expert Comment

by:Daniel Junges
ID: 10680308

Hi mtcmedia, now it run without exceptions:

what is to do:

1- In the File GameTest i have changed the start order, firstly the server and then the client:
--->game.setupServer(playerGrid); // Set up a server with the local grid
--->localGame.setupClient(); // Set up a client

2- i used this setSecurityManager;
if (System.getSecurityManager() == null) {    
     System.setSecurityManager(new RMISecurityManager() {
          public void checkConnect(String host, int port) {
          }
          public void checkConnect(String host, int port, Object context) {
          }
     });
}


0
 
LVL 2

Author Comment

by:mtcmedia
ID: 10682081
It runs, asking you to place your ships in the grid. But as soon as the RMI code starts then I get the same exceptions.
0
 
LVL 14

Expert Comment

by:Daniel Junges
ID: 10685673

There are you files that i have used, i not understand why you continue receiving Exceptions.
ftp://200.102.160.107/mtcmedia.zip
0
 
LVL 2

Author Comment

by:mtcmedia
ID: 10686064
Did you run the program, past the point where it asks you to place your ships in the grid?
0
 
LVL 14

Expert Comment

by:Daniel Junges
ID: 10686150

I have typed exactly the same as you and this appears at the end:

All ships successfully added to grid.
Contacting other player to initiliase game.
 A A A A A 0 0 0 0 0
 0 A A A A A 0 0 0 0
 C C C C C C 0 0 0 0
 C C C C C C 0 0 0 0
 B B B B 0 0 0 0 0 0
 B B B B 0 0 0 0 0 0
 B B B B 0 0 0 0 0 0
 B B B B 0 0 0 0 0 0
 S S S S S S S S 0 0
 S S S S 0 0 0 0 0 0
Game bound

I not understand what is this, but it works without exception.


0
 
LVL 2

Author Comment

by:mtcmedia
ID: 10698956
The last question is, is there a way I can test if the server is ready before setting up the client? For example I want to check the remote server grid is ready before I set up my client and try to bind to the remote object. How do I do this?
0
 
LVL 2

Author Comment

by:mtcmedia
ID: 10699058
I know I could setup a Socket to send a message when the server is ready for clients, but doesnt RMI have a function to do this?
0
 
LVL 14

Accepted Solution

by:
Daniel Junges earned 250 total points
ID: 10700039

my suggestion:
1- Interface extention for:
   - Calling the server status(RMI interface).
   - Passing the grid into server object.
2- Startup the server before filling the grid, fill the grid and pass it into server.

So you client can bind with the server and call it status with the new function present on server interface.

sincerely
junges
0
 
LVL 2

Author Comment

by:mtcmedia
ID: 10707948
I like that idea, good I will do that.

So are you sure that the game works? Does it let you take a guess at the opponent grid, and print out "HIT" or "MISS"?
0
 
LVL 14

Expert Comment

by:Daniel Junges
ID: 10722628

hi mtcmedia, i dont know if it works because i self not know how to play with it correctly :-)
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now