示例#1
0
  private void createRegistry() throws IOException {
    // already created?
    if (registry != null) {
      return;
    }
    // Ensure cryptographically strong random number generator used
    // to choose the object number - see java.rmi.server.ObjID
    System.setProperty("java.rmi.server.randomIDs", "true");

    // set RMI hostname to host if property isn't set already
    // This fixes a hard to understand connection refused issue.
    String rmi_host = System.getProperty("java.rmi.server.hostname");
    if (rmi_host == null) {
      System.setProperty("java.rmi.server.hostname", host);
    }

    // Start or reuse an RMI registry on specified port
    try {
      registry = LocateRegistry.getRegistry(port);
      // provoke a RemoteException if registry doesn't exist yet.
      registry.list();
    } catch (Exception ignored) {
      registry = LocateRegistry.createRegistry(port);
    }
    /*catch (IOException ex) {
        registry = LocateRegistry.createRegistry(port);
    }*/

  }
示例#2
0
  /**
   * Starts the common RMI registry. In order to provide RMI stub for remote client, the JMX RMI
   * connector should be register into an RMI registry. Each server will maintain its own private
   * one.
   *
   * @throws Exception if the registry cannot be started
   */
  private void startCommonRegistry() throws Exception {
    int registryPort = jmxConnectionHandler.getListenPort();

    //
    // create our local RMI registry if it does not exist already
    if (debugEnabled()) {
      TRACER.debugVerbose("start or reach an RMI registry on port %d", registryPort);
    }
    try {
      //
      // TODO Not yet implemented: If the host has several interfaces
      if (registry == null) {
        rmiSsf = new OpendsRmiServerSocketFactory();
        registry = LocateRegistry.createRegistry(registryPort, null, rmiSsf);
      }
    } catch (RemoteException re) {
      //
      // is the registry already created ?
      if (debugEnabled()) {
        TRACER.debugWarning("cannot create the RMI registry -> already done ?");
      }
      try {
        //
        // get a 'remote' reference on the registry
        Registry reg = LocateRegistry.getRegistry(registryPort);

        //
        // 'ping' the registry
        reg.list();
        registry = reg;
      } catch (Exception e) {
        if (debugEnabled()) {
          //
          // no 'valid' registry found on the specified port
          TRACER.debugError("exception thrown while pinging the RMI registry");

          //
          // throw the original exception
          TRACER.debugCaught(DebugLogLevel.ERROR, re);
        }
        throw re;
      }

      //
      // here the registry is ok even though
      // it was not created by this call
      if (debugEnabled()) {
        TRACER.debugWarning("RMI was registry already started");
      }
    }
  }
示例#3
0
 public ClientRMI() throws RemoteException, NotBoundException {
   try {
     // betHouse -  este nome identifica o objecto que o servidor regustou no registry, para o
     // cliente lhe aceder
     Registry registry = LocateRegistry.getRegistry(7000);
     for (String n : registry.list()) {
       System.out.println("> " + n);
     }
     server = (ServerInterface) registry.lookup("betHouse");
     menu();
   } catch (RemoteException ex) {
     ex.printStackTrace();
     System.out.println("Server offline.");
     System.exit(0);
   }
 }
  public ArrayList<KeyValueServerInterface> getServersList() throws RemoteException {
    //
    ArrayList<KeyValueServerInterface> res = new ArrayList();

    try {
      Registry registry = LocateRegistry.getRegistry();
      String[] name = registry.list();
      for (String str : name) {

        // if( str.equals(server_name) ) continue;

        KeyValueServerInterface obj = (KeyValueServerInterface) registry.lookup(str);
        res.add(obj);
      }

    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
    return res;
  }
  /* (non-Javadoc)
   * @see org.objectweb.proactive.core.remoteobject.RemoteObjectFactory#list(java.net.URI)
   */
  public URI[] list(URI url) throws ProActiveException {
    try {
      Registry registry = getRegistry(url);
      String[] names = registry.list();

      if (names != null) {
        URI[] uris = new URI[names.length];
        for (int i = 0; i < names.length; i++) {
          uris[i] =
              URIBuilder.buildURI(
                  URIBuilder.getHostNameFromUrl(url),
                  names[i],
                  protocolIdentifier,
                  URIBuilder.getPortNumber(url));
        }
        return uris;
      }
    } catch (Exception e) {
      throw new ProActiveException(e);
    }
    return null;
  }
  public static void main(String args[]) throws RuntimeException {

    System.err.println("\nRegression test for bug/rfe 4254808\n");

    Registry registry = null;
    LegalRegistryNames legal = null;

    boolean oneFormFailed = false;
    String[] names = null;
    Vector legalForms = getLegalForms();
    Remote shouldFind = null;

    // create a registry and the test object
    try {
      legal = new LegalRegistryNames();

      System.err.println("Starting registry on default port");
      registry = LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
    } catch (Exception e) {
      TestLibrary.bomb("registry already running on test port");
    }

    // enumerate through all legal URLs to verify that a remote
    // object can be bound and unbound
    String s = null;
    Enumeration en = legalForms.elements();
    while (en.hasMoreElements()) {
      s = (String) en.nextElement();

      System.err.println("\ntesting form: " + s);

      try {
        Naming.rebind(s, legal);
        names = registry.list();

        // ensure that the name in the registry is what is expected
        if ((names.length > 0) && (names[0].compareTo("MyName") != 0)) {
          oneFormFailed = true;
          System.err.println("\tRegistry entry for form: " + s + " is incorrect: " + names[0]);
        }

        // ensure that the object can be unbound under the URL string
        shouldFind = Naming.lookup(s);
        Naming.unbind(s);
        System.err.println("\tform " + s + " OK");

      } catch (Exception e) {

        e.printStackTrace();
        oneFormFailed = true;
        System.err.println(
            "\tunexpected lookup or unbind " + "exception for form: " + s + e.getMessage());
      }
    }
    if (oneFormFailed) {
      TestLibrary.bomb("Test failed");
    }

    // get the test to exit quickly
    TestLibrary.unexport(legal);
  }
  private static IStatus collectServerInfos(
      String address,
      int port,
      final SpecialAddress special,
      final List<RemoteR> infos,
      final SubMonitor progress) {
    try {
      if (special != null) {
        address = special.fPublicHost;
        port = special.fPort;
      }
      progress.subTask(
          NLS.bind(Messages.RRemoteConsoleSelectionDialog_task_Resolving_message, address));
      final InetAddress inetAddress = InetAddress.getByName(address);
      final String hostname = inetAddress.getHostName();
      final String hostip = inetAddress.getHostAddress();
      progress.worked(1);
      if (progress.isCanceled()) {
        return Status.CANCEL_STATUS;
      }

      progress.subTask(
          NLS.bind(Messages.RRemoteConsoleSelectionDialog_task_Connecting_message, hostname));
      final Registry registry;
      if (special != null) {
        final RMIClientSocketFactory socketFactory = special.getSocketFactory(progress.newChild(5));
        RjsComConfig.setRMIClientSocketFactory(socketFactory);
        registry = LocateRegistry.getRegistry(special.fPrivateHost, port, socketFactory);
      } else {
        RjsComConfig.setRMIClientSocketFactory(null);
        registry = LocateRegistry.getRegistry(address, port);
      }
      final String rmiBase =
          (port == Registry.REGISTRY_PORT)
              ? "//" + address + '/'
              : //$NON-NLS-1$
              "//" + address + ':' + port + '/'; // $NON-NLS-1$
      final String[] names = registry.list();
      for (final String name : names) {
        try {
          final Remote remote = registry.lookup(name);
          if (remote instanceof Server) {
            final Server server = (Server) remote;
            final ServerInfo info = server.getInfo();
            final String rmiAddress = rmiBase + name;
            final RemoteR r = new RemoteR(hostname, hostip, rmiAddress, info);
            infos.add(r);
          }
        } catch (final Exception e) {
        }
      }
      return Status.OK_STATUS;
    } catch (final RemoteException e) {
      return new Status(IStatus.WARNING, RConsoleUIPlugin.PLUGIN_ID, address);
    } catch (final UnknownHostException e) {
      return new Status(
          IStatus.ERROR,
          RConsoleUIPlugin.PLUGIN_ID,
          "Unknown host: " + e.getLocalizedMessage()); // $NON-NLS-1$
    } catch (final CoreException e) {
      return e.getStatus();
    } finally {
      RjsComConfig.clearRMIClientSocketFactory();
    }
  }
 /**
  * Test the given RMI registry, calling some operation on it to check whether it is still active.
  *
  * <p>Default implementation calls <code>Registry.list()</code>.
  *
  * @param registry the RMI registry to test
  * @throws RemoteException if thrown by registry methods
  * @see java.rmi.registry.Registry#list()
  */
 protected void testRegistry(Registry registry) throws RemoteException {
   registry.list();
 }
  public void run() {

    int remote_RMI_port_integer1 = 0;
    int remote_RMI_port_integer2 = 0;
    int RMI_port_integer = 0;
    String IP_Address_Remote_RMI1_string = "";
    String IP_Address_Remote_RMI2_string = "";
    String s = "";

    Scanner scanServ = new Scanner(System.in);

    System.out.println("What is the server port?");
    String port_string = scanServ.nextLine();

    int port_value = Integer.parseInt(port_string);

    // Setting up connection!
    ServerSocket ss = null;
    try {
      ss = new ServerSocket(port_value);
    } catch (IOException e) {
      System.out.println("Couldn't Listen!");
      System.exit(0);
    }

    // Add code here to bind to the RMI Registry
    try {

      System.out.println("Local RMI Port: ");
      String RMI_port_string = scanServ.nextLine();
      System.out.println("IP Address of Remote Server 1: ");
      IP_Address_Remote_RMI1_string = scanServ.nextLine();
      System.out.println("Remote RMI Registry Port 1: ");
      String remote_RMI_port_string1 = scanServ.nextLine();
      System.out.println("IP Address of Remote Server 2: ");
      IP_Address_Remote_RMI2_string = scanServ.nextLine();
      System.out.println("Remote RMI Registry Port 2: ");
      String remote_RMI_port_string2 = scanServ.nextLine();

      InetAddress myIPAddress = InetAddress.getLocalHost();
      // System.out.println(myIPAddress);
      String hostaddress = myIPAddress.getHostAddress();
      String registry_string = "IP: " + hostaddress + " Port: " + port_string;
      System.out.println(registry_string);

      FileServer obj = new FileServer();
      Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);
      // Bind the remote object's stub in the registry
      // add code to convert FROM STRING TO INTEGER!!!
      RMI_port_integer = Integer.parseInt(RMI_port_string);

      remote_RMI_port_integer1 = Integer.parseInt(remote_RMI_port_string1);
      remote_RMI_port_integer2 = Integer.parseInt(remote_RMI_port_string2);

      Registry registry = LocateRegistry.getRegistry(RMI_port_integer);
      registry.bind(registry_string, stub);
      Registry registry_remote1 =
          LocateRegistry.getRegistry(IP_Address_Remote_RMI1_string, remote_RMI_port_integer1);
      Registry registry_remote2 =
          LocateRegistry.getRegistry(IP_Address_Remote_RMI2_string, remote_RMI_port_integer2);
      // add code here also for the case of the ip address of the remote host! :)

      System.err.println("Server ready");
    } catch (Exception e) {
      System.err.println("Server exception: " + e.toString());
      e.printStackTrace();
    }

    while (true) {

      System.out.println("Listening...");

      Socket cs = null;
      try {
        cs = ss.accept();
        System.out.println("Connection established" + cs);
      } catch (Exception e) {
        System.out.println("Accept failed");
        System.exit(1);
      }
      try {
        PrintWriter put = new PrintWriter(cs.getOutputStream(), true);
        BufferedReader st = new BufferedReader(new InputStreamReader(cs.getInputStream()));
        String x = st.readLine();

        /**
         * *********************************************************************************************
         * ***************************************Client
         * Download!***************************************
         * *********************************************************************************************
         */
        if (x.equals("1")) {
          System.out.println("\nAttempting to Send File to Client!");

          s = st.readLine();
          String testfilename = s;
          System.out.println("The requested file is : " + s);
          File f = new File(s);

          // ***********************SERVER HAS FILE**********************/
          if (f.exists()) // server has the file, so we service the request
          {
            put.println("SERVER_HAS_FILE");

            BufferedInputStream d = new BufferedInputStream(new FileInputStream(s));
            BufferedOutputStream outStream = new BufferedOutputStream(cs.getOutputStream());

            BufferedReader disb = new BufferedReader(new InputStreamReader(cs.getInputStream()));
            int amountClientRead = Integer.parseInt(disb.readLine());
            System.out.println("\n\n\nAMOUNT THE CLIENT HAS READ!" + amountClientRead);
            if (amountClientRead > 0) {
              System.out.println("\n\nRESUMING DOWNLOAD!!!");
            }

            byte buffer[] = new byte[1024];
            int read;
            while ((read = d.read(buffer)) != -1) {
              outStream.write(buffer, 0, read);
              outStream.flush();
            }
            // put.println("SERVER_HAS_FILE");
            d.close();
            outStream.close();
            System.out.println("File Transferred to Client Succesfully!");
            cs.close();
          }
          // ***********************SERVER DOES NOT HAVE REQUESTED FILE**********************/
          else {
            System.out.println("Looks like we don't have the file on this server!");
            // This server does not have the requested file!

            // String host = (args.length < 1) ? null : args[0];
            try {
              System.out.println(
                  "\nSending out a broadcast to the other servers to see if they have the file!");
              // wait until receiving the responses...
              Registry registry = LocateRegistry.getRegistry(RMI_port_integer);
              String[] registry_list = registry.list();
              String[] hasFileList =
                  new String
                      [registry_list
                          .length]; // an array of strings for holding the ip&port of servers that
              // have the file

              System.out.println("DEBUGGING THIS");

              Registry registry_remote1 =
                  LocateRegistry.getRegistry(
                      IP_Address_Remote_RMI1_string, remote_RMI_port_integer1);
              String[] registry_list_remote1 = registry_remote1.list();
              String[] hasFileList_remote1 =
                  new String
                      [registry_list_remote1
                          .length]; // an array of strings for holding the ip&port of servers that
              // have the file
              Registry registry_remote2 =
                  LocateRegistry.getRegistry(
                      IP_Address_Remote_RMI2_string, remote_RMI_port_integer2);
              String[] registry_list_remote2 = registry_remote2.list();
              String[] hasFileList_remote2 =
                  new String
                      [registry_list_remote2
                          .length]; // an array of strings for holding the ip&port of servers that
              // have the file

              System.out.println("I got here!!!");
              // going through all of the entries in the registry, assuming we have fewer than 10000
              // servers
              /// *****************************************LOCAL check**********************/
              try {
                int numHasFile = 0; // the number of mirrors with the requested file
                int testcount = 0;
                while (testcount < 10000) {
                  System.out.println(registry_list[testcount]);
                  // add code fix here where you get rid of the hardcoded lookup!  i.e. we will need
                  // to broadcast!
                  Hello stub = (Hello) registry.lookup(registry_list[testcount]);
                  // Hello stub = (Hello) registry.lookup("1235");
                  String response = stub.sayHello(testfilename);
                  System.out.println("response: " + response);

                  // response == yes, has file list places the value
                  if (response.equals(
                      "YES")) { // adds the ip and port values for servers which responded with yes
                    // to an array of strings!
                    hasFileList[numHasFile] = registry_list[testcount];
                    // System.out.println(hasFileList[numHasFile]);
                    numHasFile++;
                  }
                  testcount++;
                  // add code for NOW passing the list to the client!
                  // make a list based upon the responses to transmit the (IP Address, Port #)
                  // passing the responses from the broadcast back to the client here
                }
              } catch (Exception fail) {
                System.out.println("registry end");
              }
              /// *****************************************1st**********************/
              try {
                int numHasFile = 0; // the number of mirrors with the requested file
                int testcount = 0;
                while (testcount < 10000) {
                  System.out.println(registry_list_remote1[testcount]);
                  // add code fix here where you get rid of the hardcoded lookup!  i.e. we will need
                  // to broadcast!
                  Hello stub1 = (Hello) registry_remote1.lookup(registry_list_remote1[testcount]);
                  String response_remote1 = stub1.sayHello(testfilename);
                  System.out.println("response: " + response_remote1);
                  // response == yes, has file list places the value
                  if (response_remote1.equals(
                      "YES")) { // adds the ip and port values for servers which responded with yes
                    // to an array of strings!
                    hasFileList_remote1[numHasFile] = registry_list_remote1[testcount];
                    // System.out.println(hasFileList[numHasFile]);
                    numHasFile++;
                  }
                  testcount++;
                  // add code for NOW passing the list to the client!
                  // make a list based upon the responses to transmit the (IP Address, Port #)
                  // passing the responses from the broadcast back to the client here
                }
              } catch (Exception fail) {
                System.out.println("registry end 2");
              }
              //// ****************************************2nd**********************/
              try {
                int numHasFile = 0; // the number of mirrors with the requested file
                int testcount = 0;
                while (testcount < 10000) {
                  System.out.println(registry_list_remote2[testcount]);
                  // add code fix here where you get rid of the hardcoded lookup!  i.e. we will need
                  // to broadcast!
                  Hello stub2 = (Hello) registry_remote2.lookup(registry_list_remote2[testcount]);
                  String response_remote2 = stub2.sayHello(testfilename);
                  System.out.println("response: " + response_remote2);
                  // response == yes, has file list places the value
                  if (response_remote2.equals(
                      "YES")) { // adds the ip and port values for servers which responded with yes
                    // to an array of strings!
                    hasFileList_remote2[numHasFile] = registry_list_remote2[testcount];
                    // System.out.println(hasFileList[numHasFile]);
                    numHasFile++;
                  }
                  testcount++;
                  // add code for NOW passing the list to the client!
                  // make a list based upon the responses to transmit the (IP Address, Port #)
                  // passing the responses from the broadcast back to the client here
                }
              } catch (Exception fail) {
                System.out.println("registry end 3");
              }
              /**
               * ***********************FORWARDING DETAILS OF MIRROR SERVERS TO
               * CLIENT*******************************************
               */
              // print what you want to send to the client here from hasFileList arrays of strings
              // for now
              System.out.println("Will send these mirrors to the client: ");
              try // ADD CODE HERE
              {
                // display the contents of the three arrays of strings concatenated!
                // handle the case of no other servers being available

                String[] combinedHasFileArray =
                    new String
                        [hasFileList.length
                            + hasFileList_remote1.length
                            + hasFileList_remote2.length];
                System.arraycopy(hasFileList, 0, combinedHasFileArray, 0, hasFileList.length);
                System.arraycopy(
                    hasFileList_remote1,
                    0,
                    combinedHasFileArray,
                    hasFileList.length,
                    hasFileList_remote1.length);
                System.arraycopy(
                    hasFileList_remote2,
                    0,
                    combinedHasFileArray,
                    hasFileList.length + hasFileList_remote1.length,
                    hasFileList_remote2.length);

                put.println("SERVER_NOT_HAVE_FILE");
                System.out.println("THE CODE GOT HERE!");
                int i = 0;
                while (i < combinedHasFileArray.length) {
                  put.println(combinedHasFileArray[i]);
                  System.out.println(combinedHasFileArray[i]); // add code to send this to client!!!
                  i++;
                }
                put.println("END!!!");
              } catch (Exception Noooooooooooo) {
                System.out.println("Noooooooo");
              }

            } catch (Exception e) {
              System.err.println("Server without file exception: " + e.toString());
              e.printStackTrace();
            }
            cs.close(); // temporarily have this to close the client socket!
          }
        }

        /**
         * *********************************************************************************************
         * ***************************************Client
         * Upload!***************************************
         * *********************************************************************************************
         */
        else if (x.equals("2")) {
          System.out.println("Attempting to Retrieve File from Client!");

          s = st.readLine();
          System.out.println("\nThe file to be uploaded is : " + s);
          s = st.readLine();
          System.out.println("\nThe uploading file will be stored here : " + s);

          // Take the file from the client!!!
          File test = new File(s);
          /** ************************RESUME CASE********************************** */
          if (test.exists()) {
            System.out.println("File already exists!");
            System.out.println("Resuming!");

            // get the amount of bytes already uploaded to the server by the client!
            int amountRead = ((int) test.length()); // amount of bytes already read
            System.out.println("THIS IS THE AMOUNT OF BYTES READ: " + amountRead);

            FileOutputStream fs = new FileOutputStream(s, true);
            BufferedInputStream d = new BufferedInputStream(cs.getInputStream());

            // send file size to server
            put.println(amountRead);

            byte buffer[] = new byte[1024];
            int read;
            while ((read = d.read(buffer)) != -1) {
              fs.write(buffer, 0, read);
              fs.flush();
            }
            d.close();
            System.out.println("File taken from client successfully!");
            cs.close();
            fs.close();
          }

          /** ************************NORMAL CASE********************************** */
          else {
            FileOutputStream fs = new FileOutputStream(s);
            BufferedInputStream d = new BufferedInputStream(cs.getInputStream());

            put.println(
                0); // send the file size as zero to the client so we know to send the full file
            byte buffer[] = new byte[1024];
            int read;
            while ((read = d.read(buffer)) != -1) {
              fs.write(buffer, 0, read);
              fs.flush();
            }
            d.close();
            System.out.println("File taken from client successfully!");
            cs.close();
            fs.close();
          }

        }
        /**
         * *********************************************************************************************
         * ***************************************Mirror
         * Download!***************************************
         * *********************************************************************************************
         */
        else if (x.equals("3")) {
          System.out.println("Service Discovery!");

          // add code here to service the request
          // this is where the client has selected this server for download after the initial server
          // did not have the file!
          // so basically just do a normal download ?
          // this server is listening and a request comes in from another server
          // to search the files located at this server
        }

      } catch (Exception e) {
        System.out.println("error");
      }
    }
  }