예제 #1
0
  public void deploy(URL url, boolean master, ClassLoader cL, String remoteHost) {
    try {
      FileObject filetoScan = fsManager.resolveFile("jar:" + url.toString() + "!/");
      HashSet<Class<?>>[] classes = new HashSet[] {new HashSet()};

      VFSClassLoader jarCL;

      if (cL != null) {
        jarCL = new VFSClassLoader(new FileObject[] {filetoScan}, fsManager, cL);
      } else {
        jarCL =
            new VFSClassLoader(
                new FileObject[] {filetoScan},
                fsManager,
                Thread.currentThread().getContextClassLoader());
      }
      Class[] annot = new Class[] {DeployRMI.class};
      scanJar(filetoScan, classes, annot, jarCL);
      for (Class<?> rmiClass : classes[0]) {
        DeployRMI rmiAnnot = rmiClass.getAnnotation(DeployRMI.class);
        if (master) {
          rmiProxyHandler = new RMIProxyHandler(rmiAnnot.jndiBinding(), remoteObjects);
          rmiproxy =
              Proxy.newProxyInstance(
                  rmiClass.getClassLoader(), rmiClass.getInterfaces(), rmiProxyHandler);
          remoteobj =
              UnicastRemoteObject.exportObject(
                  (Remote) rmiproxy, Integer.parseInt(serverConfig.getRmiregistryport()));
          rmiproxyObjs.put(rmiAnnot.jndiBinding(), rmiproxy);
          rmiproxyHandler.put(rmiAnnot.jndiBinding(), rmiProxyHandler);
          remoteProxyObjs.put(rmiAnnot.jndiBinding(), remoteobj);
          ic.bind("java:/" + rmiAnnot.jndiBinding(), remoteobj);
          registry.bind(rmiAnnot.jndiBinding(), (Remote) remoteobj);
          cLMap.put(rmiAnnot.jndiBinding(), jarCL);
        } else {
          Remote remoteObj = (Remote) rmiClass.newInstance();
          remoteSlaveObjs.put(rmiAnnot.jndiBinding(), remoteObj);
          Object remoteobj =
              UnicastRemoteObject.exportObject(
                  (Remote) remoteObj, Integer.parseInt(serverConfig.getRmiregistryport()));
          ic.bind("java:/" + rmiAnnot.jndiBinding(), remoteobj);
          registry.bind(rmiAnnot.jndiBinding(), (Remote) remoteobj);
          if (remoteObjects.get(rmiAnnot.jndiBinding()) != null) {
            ConcurrentMap<String, Remote> remoteObjs = remoteObjects.get(rmiAnnot.jndiBinding());
            remoteObjs.put(remoteHost, (Remote) remoteobj);
          } else {
            ConcurrentHashMap<String, Remote> remoteObjs = new ConcurrentHashMap<String, Remote>();
            remoteObjs.put(remoteHost, (Remote) remoteobj);
            remoteObjects.put(rmiAnnot.jndiBinding(), remoteObjs);
          }
        }
      }
    } catch (Exception e) {
      log.error("unable to deploy the package " + url, e);
    }
  }
예제 #2
0
파일: Annuaire.java 프로젝트: opnczk/SRCS
  public static void main(String args[]) {
    AnnuaireIF annuaire = new Annuaire();
    try {
      UnicastRemoteObject.exportObject(annuaire, 0);
    } catch (RemoteException e) {
      System.out.println("Lancé de nain lors de l'export de l'objet !");
      e.printStackTrace();
      System.exit(0);
    }

    Registry registry = null;
    try {
      registry = LocateRegistry.createRegistry(5500);
      // registry = LocateRegistry.getRegistry("localhost", 5500);
    } catch (RemoteException e) {
      System.out.println("Lancé de nain lors de la localisation de registry !");
      e.printStackTrace();
      System.exit(0);
    }
    try {
      registry.bind("Annuaire", annuaire);
    } catch (RemoteException | AlreadyBoundException e) {
      System.out.println("Lancé de nain lors du bind !");
      e.printStackTrace();
      System.exit(0);
    }

    System.out.println("Serveur lancé sans lancé de nain !");
  } // fin du main
예제 #3
0
  /**
   * Start.
   *
   * @return true, if successful
   */
  public boolean start() {
    reg = null;

    // Create or connect to the registry
    try {
      reg = this.regInfo.connect(this.initRegistry);
      this.dist = new Distributor(this);
      this.stub = (IDistributor) UnicastRemoteObject.exportObject(dist, 0);
      reg.bind(this.bindingName, this.stub);

    } catch (RemoteException rex) {
      logger.severe("Remote error: " + rex.getMessage());
      return false;
    } catch (AlreadyBoundException abex) {
      logger.severe(
          "The binding name \""
              + this.bindingName
              + "\" is already in use. Maybe this server is already started?");
      return false;
    }

    logger.info("\"" + this.bindingName + "\" started up");

    this.lookupTask.start();

    return true;
  }
예제 #4
0
  public static void main(String[] args) {
    try {
      Registry registry = LocateRegistry.getRegistry(1099);
      MonitorInterface monitor = (MonitorInterface) registry.lookup("//localhost/monitor");

      Random random = new Random();
      int id = monitor.getID();
      int max = monitor.getMax();
      Bank bank = new Bank(id, max, monitor, random.nextInt(100), registry);

      registry.bind("//localhost/bank" + id, bank);
      System.out.println("Bank " + id + " ready! Hit to start...");
      System.in.read();

      for (int j = 0; j < 1000; j++) {
        int d = random.nextInt(max - 1);
        if (d >= id) d++;

        int q = random.nextInt(10);

        bank.transfer(q, d);
        Thread.sleep(random.nextInt(5000));
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
예제 #5
0
  public static void main(String args[]) throws Exception {
    try {
      testPkg.Server obj = new testPkg.Server();
      testPkg.Hello stub = (testPkg.Hello) UnicastRemoteObject.exportObject(obj, 0);
      // Bind the remote object's stub in the registry
      Registry registry = LocateRegistry.getRegistry(TestLibrary.READTEST_REGISTRY_PORT);
      registry.bind("Hello", stub);

      System.err.println("Server ready");

      // now, let's test client
      testPkg.Client client = new testPkg.Client(TestLibrary.READTEST_REGISTRY_PORT);
      String testStubReturn = client.testStub();
      if (!testStubReturn.equals(obj.hello)) {
        throw new RuntimeException("Test Fails : unexpected string from stub call");
      } else {
        System.out.println("Test passed");
      }
      registry.unbind("Hello");

    } catch (Exception e) {
      System.err.println("Server exception: " + e.toString());
      e.printStackTrace();
    }
  }
예제 #6
0
 public RmiServer() {
   try {
     IRmiServer server = (IRmiServer) UnicastRemoteObject.exportObject(this, 0);
     registry = LocateRegistry.createRegistry(16666);
     registry.bind("Server", server);
   } catch (RemoteException | AlreadyBoundException e) {
     catcher.catchException(e);
   }
 }
  public static void main(String[] args) throws Exception {
    System.err.println("\nRegression test for bug 6261402\n");
    System.setProperty(
        "java.rmi.activation.port",
        Integer.toString(TestLibrary.INHERITEDCHANNELNOTSERVERSOCKET_ACTIVATION_PORT));
    RMID rmid = null;
    Callback obj = null;
    try {
      /*
       * Export callback object and bind in registry.
       */
      System.err.println("export callback object and bind in registry");
      obj = new CallbackImpl();
      Callback proxy = (Callback) UnicastRemoteObject.exportObject(obj, 0);
      Registry registry =
          LocateRegistry.createRegistry(TestLibrary.INHERITEDCHANNELNOTSERVERSOCKET_REGISTRY_PORT);
      registry.bind("Callback", proxy);

      /*
       * Start rmid.
       */
      System.err.println("start rmid with inherited channel");
      RMID.removeLog();
      rmid =
          RMID.createRMID(
              System.out,
              System.err,
              true,
              true,
              TestLibrary.INHERITEDCHANNELNOTSERVERSOCKET_ACTIVATION_PORT);
      rmid.addOptions(
          new String[] {
            "-Djava.nio.channels.spi.SelectorProvider=" + "InheritedChannelNotServerSocket$SP"
          });
      rmid.start();

      /*
       * Get activation system and wait to be notified via callback
       * from rmid's selector provider.
       */
      System.err.println("get activation system");
      ActivationSystem system = ActivationGroup.getSystem();
      System.err.println("ActivationSystem = " + system);
      synchronized (lock) {
        while (!notified) {
          lock.wait();
        }
      }
      System.err.println("TEST PASSED");
    } finally {
      if (obj != null) {
        UnicastRemoteObject.unexportObject(obj, true);
      }
      ActivationLibrary.rmidCleanup(rmid);
    }
  }
예제 #8
0
 public static void registryObject(String name, Remote remoteObj)
     throws AccessException, RemoteException, AlreadyBoundException {
   // Đăng ký đối tượng vào bộ đăng ký
   // Nó được gắn với tên nào đó
   // Client sẽ tìm kiếm trong bộ đăng ký với tên này để có thể gọi đối
   // tượng
   registry.bind(name, remoteObj);
   System.out.println(
       "Registered: " + name + " -> " + remoteObj.getClass().getName() + "[" + remoteObj + "]");
 }
예제 #9
0
  public static void main(String[] args) {

    try {
      HelloImpl h = new HelloImpl("Hello Everyone!");
      Hello h_stub = (Hello) UnicastRemoteObject.exportObject(h, 1200);
      SecondImpl s = new SecondImpl();
      Second s_stub = (Second) UnicastRemoteObject.exportObject(s, 1201);
      // create registry entry for remote object
      Registry registry = LocateRegistry.getRegistry();
      registry.bind("Hello1", h_stub);
      registry = LocateRegistry.getRegistry();
      registry.bind("second", s_stub);
      System.out.println("I am server : --> application ready <-- ");

    } catch (Exception e) {
      System.out.println("Error while executing request");
      e.printStackTrace();
    }
  }
예제 #10
0
  /**
   * Public constructor.
   *
   * @param port port between a reasonable number of 1024 and 65000
   * @throws Exception if any exception occurs, shutdown the server immediately.
   */
  public Server(int port) {
    try {
      System.out.println("STARTING TO INITIALIZE THE SERVER");
      if (port < 1024 || port > 65000) {
        throw new Exception("Port number is invalid. Must be between 1024 and 65000");
      }

      registry = LocateRegistry.createRegistry(port);
      handler = new ServerHandler();
      registry.bind(serverName, handler);

      // Load the agent into the running JVM process
      if (!AgentLoader.loadAgentFromClasspath(
          "avaje-ebeanorm-agent", "debug=1;packages=com.elementstcg.server.game.**")) {
        System.err.println("avaje-ebeanorm-agent not found in classpath - not dynamically loaded");
      }

      System.out.println("SERVER IS UP AND RUNNING\n---------------");
      System.out.println("ELEMENTS TCG SERVER");
      System.out.println(
          "SERVER RUNNING AT: "
              + Inet4Address.getLocalHost().getHostAddress()
              + ":"
              + port
              + "  -  Server Name: "
              + serverName);
      System.out.println("VERSION: 1.0 Beta");
      System.out.println("HAVE FUN!");
      System.out.println("---------------");

      // Loop so that you can exit the server by hand.
      Scanner scanner = new Scanner(System.in);
      while (!scanner.nextLine().equals("exit")) {}

      // Shutting down the server
      System.out.println("INITIATING THE TIME BOMB!");
      System.out.println("SERVER WILL DIE IN 5 SECONDS!");

      // Adds a new timer to schedule it's death.
      Timer timer = new Timer();
      timer.schedule(
          new TimerTask() {
            @Override
            public void run() {
              System.out.println("SHUTTING DOWN THE SERVER NOW!!!");
              System.exit(1);
            }
          },
          5000);

    } catch (Exception ex) {
      System.err.println(ex.getMessage());
      System.exit(1);
    }
  }
예제 #11
0
 public static void main(String[] args) throws IOException {
   try {
     Server server = new Server();
     BookingInterface stub = (BookingInterface) UnicastRemoteObject.exportObject(server, 0);
     Registry registry = LocateRegistry.getRegistry();
     registry.bind("BookingInterface", stub);
     System.out.println("Server running, waiting on client connection....");
   } catch (Exception e) {
     System.err.println("Server error:" + e.toString());
   }
 }
예제 #12
0
  public void main(String[] args) {

    try {

      ProfileMatcher profileMatcher = FabricaDeServicos.crieProfileMatcher();
      profileMatcher = (ProfileMatcher) UnicastRemoteObject.exportObject(profileMatcher);

      Registry registry = LocateRegistry.getRegistry();
      registry.bind("ProfileMatcher", profileMatcher);

    } catch (Exception e) {
      System.err.println("Erro no servidor: " + e.toString());
      e.printStackTrace();
    }
  }
예제 #13
0
  public static void main(String[] args) {
    if (System.getSecurityManager() == null) {
      System.setSecurityManager(new SecurityManager());
    }
    try {
      String name = "Compute";
      Compute engine = new ComputeEngine();
      Compute stub = (Compute) UnicastRemoteObject.exportObject(engine, 8081);
      Registry registry = LocateRegistry.getRegistry();
      registry.bind(name, stub);

      System.out.println("ComputeEngine bound");
    } catch (Exception e) {
      System.err.println("ComputeEngine exception:");
      e.printStackTrace();
    }
  }
예제 #14
0
  public static void main(String args[]) {

    try {
      Server obj = new Server();

      Hello stub = (Hello) UnicastRemoteObject.exportObject(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();
    }
  }
예제 #15
0
  /** Starts the server. */
  @CommandArgument
  public void start() {
    System.out.println("Starting server");
    try {

      Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
      EmbeddedDataSource ds = new EmbeddedDataSource();
      ds.setConnectionAttributes("create=true");
      ds.setDatabaseName("classes");

      logger.info("Initializing jobProgressStates monitor");
      ProgressStateFactory factory = new ProgressStateFactory();
      jobProgressStates = factory.getProgressStates();

      logger.info("Initializing folders...");
      Preferences pref = Preferences.userNodeForPackage(JobServer.class);
      String path = pref.get("rootDirectory", "./server");
      File rootDirectory = new File(path);
      File jobsDirectory = new File(rootDirectory, "jobs");

      rootDirectory.mkdir();
      jobsDirectory.mkdir();

      logger.info("Initializing service");
      DbClassManager classManager = new DbClassManager(ds);
      classManager.prepareDataSource();

      TaskScheduler scheduler = new PrioritySerialTaskScheduler();
      Executor executor = Executors.newCachedThreadPool();
      jobServer = new JobServer(jobsDirectory, factory, scheduler, classManager, executor);
      AuthenticationServer authServer = new AuthenticationServer(jobServer, JdcpUtil.DEFAULT_PORT);

      logger.info("Binding service");
      Registry registry = getRegistry();
      registry.bind("AuthenticationService", authServer);

      logger.info("Server ready");
      System.out.println("Server started");

    } catch (Exception e) {
      System.err.println("Failed to start server");
      logger.error("Failed to start server", e);
    }
  }
  @SuppressWarnings("UseOfSystemOutOrSystemErr")
  protected static void start(Remote remote) throws Exception {
    setupRMI();
    banJNDI();

    if (ourRemote != null) throw new AssertionError("Already started");
    ourRemote = remote;

    Registry registry;
    int port;
    for (Random random = new Random(); ; ) {
      port = random.nextInt(0xffff);
      if (port < 4000) continue;
      try {
        registry = LocateRegistry.createRegistry(port);
        break;
      } catch (ExportException ignored) {
      }
    }

    try {
      Remote stub = UnicastRemoteObject.exportObject(ourRemote, 0);
      final String name = remote.getClass().getSimpleName() + Integer.toHexString(stub.hashCode());
      registry.bind(name, stub);

      String id = port + "/" + name;
      System.out.println("Port/ID: " + id);

      long waitTime = 2 * 60 * 1000L;
      Object lock = new Object();
      //noinspection InfiniteLoopStatement
      while (true) {
        //noinspection SynchronizationOnLocalVariableOrMethodParameter
        synchronized (lock) {
          lock.wait(waitTime);
        }
        RemoteDeadHand deadHand = (RemoteDeadHand) registry.lookup(RemoteDeadHand.BINDING_NAME);
        waitTime = deadHand.ping(id);
      }
    } catch (Throwable e) {
      e.printStackTrace(System.err);
      System.exit(1);
    }
  }
예제 #17
0
  public static void main(String[] args) {
    try {
      String serverAddress = args[0];
      int port = Integer.parseInt(args[1]);
      String localAddress = args[2];

      /** create a httpServer */
      System.out.println("Starting HTTP server");
      HttpServer httpServer = HttpServer.create(new InetSocketAddress(80), 0);
      httpServer.createContext("/", new HttpFileHandler());
      httpServer.setExecutor(null);
      httpServer.start();

      System.out.println("Creating RMI Registry");
      Registry registry = LocateRegistry.createRegistry(1099);
      Reference reference =
          new javax.naming.Reference(
              "client.ExportObject", "client.ExportObject", "http://" + localAddress + "/");
      ReferenceWrapper referenceWrapper = new com.sun.jndi.rmi.registry.ReferenceWrapper(reference);
      registry.bind("Object", referenceWrapper);

      System.out.println("Connecting to server " + serverAddress + ":" + port);
      Socket socket = new Socket(serverAddress, port);
      System.out.println("Connected to server");
      String jndiAddress = "rmi://" + localAddress + ":1099/Object";

      org.springframework.transaction.jta.JtaTransactionManager object =
          new org.springframework.transaction.jta.JtaTransactionManager();
      object.setUserTransactionName(jndiAddress);

      System.out.println("Sending object to server...");
      ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
      objectOutputStream.writeObject(object);
      objectOutputStream.flush();
      /*
      while(true) {
      	Thread.sleep(1000);
      }
      */
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /* (non-Javadoc)
   * @see org.objectweb.proactive.core.remoteobject.RemoteObjectFactory#register(org.objectweb.proactive.core.remoteobject.RemoteObject, java.net.URI, boolean)
   */
  public RemoteRemoteObject register(
      InternalRemoteRemoteObject target, URI url, boolean replacePreviousBinding)
      throws ProActiveException {
    RmiRemoteObject rro = null;
    try {
      Constructor<? extends RmiRemoteObject> c =
          clRemoteObject.getConstructor(InternalRemoteRemoteObject.class);
      rro = c.newInstance(target);
    } catch (Exception e) {
      throw new ProActiveException(e);
    }

    Registry reg = null;
    try {
      reg = getRegistry(url);
    } catch (Exception e) {
      LOGGER_RO.debug("creating new rmiregistry on port : " + url.getPort());
      try {
        LocateRegistry.createRegistry(URIBuilder.getPortNumber(url));
      } catch (RemoteException e1) {
        LOGGER_RO.warn("damn cannot start a rmiregistry on port " + url.getPort());
        throw new ProActiveException(e1);
      }
    }

    try {
      if (replacePreviousBinding) {
        reg.rebind(URIBuilder.getNameFromURI(url), rro);
      } else {
        reg.bind(URIBuilder.getNameFromURI(url), rro);
      }
      LOGGER_RO.debug(" successfully bound in registry at " + url);
    } catch (java.rmi.AlreadyBoundException e) {
      LOGGER_RO.warn(url + " already bound in registry", e);
      throw new AlreadyBoundException(e);
    } catch (RemoteException e) {
      LOGGER_RO.debug(" cannot bind object at " + url);
      throw new ProActiveException(e);
    }
    return rro;
  }
  public FacilityManagerMasterImpl(Config config)
      throws IOException, AlreadyBoundException, InterruptedException {
    super(config);

    currentNode = 0;
    String[] participants = config.getParticipantIps();
    int expectedNumParticipants = participants.length;

    managers = new FacilityManager[expectedNumParticipants];
    managers[getNodeId()] = this;

    clusterName = config.getClusterName();
    rmiPort = config.getRmiPort();

    /* FILESYSTEM INIT */
    fsTable = Collections.synchronizedMap(new HashMap<String, Map<Integer, Set<Integer>>>());

    Registry r = LocateRegistry.createRegistry(rmiPort);
    r.bind(clusterName + REGISTRY_MASTER_KEY, UnicastRemoteObject.exportObject(this, 0));
    connectParticipants();

    System.out.println("Waiting for slaves to connect...");
    while (managers.length != expectedNumParticipants) {
      Thread.sleep(1000);
    }

    healthChecker = new HealthChecker(this, expectedNumParticipants);
    scheduler = new JobScheduler(this, config);
    dispatcher = new JobDispatcher(this, config);
    dispatcher.setScheduler(scheduler);
    scheduler.setDispatcher(dispatcher);
    scheduler.setHealthChecker(healthChecker);

    healthChecker.start();
    dispatcher.start();

    System.out.println("All slaves connected.");
  }
예제 #20
0
  public void run() {
    // set the security manager
    try {
      int port = 2100;
      try {
        port =
            Integer.parseInt(
                MainFrame.getMainInstance().getProperties().getProperty("RMIServerPort", "2100"));
      } catch (Exception ex) {
        ex.printStackTrace();
      }
      Registry reg = LocateRegistry.createRegistry(port);

      // put the local instance in the registry
      // Naming.rebind("iReportServer" , Server);
      reg.bind("iReportServer", this);
      System.out.println("RMI iReportServer waiting on port " + port + ".....");
    } catch (java.rmi.AlreadyBoundException abe) {
      System.out.println("Service already bound! Is another iReport instance running?");
    } catch (RemoteException re) {
      System.out.println("Remote exception: " + re.toString());
    }
  }
  /**
   * Creates and exports a registry (using an inherited channel, if any, as specified below), and
   * binds the specified name to the specified proxy in that registry.
   *
   * <p>First, the registry is exported as follows:
   *
   * <ul>
   *   <li>If the <code>System.inheritedChannel</code> method returns a <code>ServerSocketChannel
   *       </code> instance, the registry is exported with an <code>RMIServerSocketFactory</code>
   *       whose <code>createServerSocket</code> method returns a <code>ServerSocket</code> for the
   *       inherited <code>ServerSocketChannel</code> that delays accepting requests until the
   *       specified proxy is bound in the registry.
   *   <li>If the <code>System.inheritedChannel</code> method returns <code>null</code>, then the
   *       registry is exported with an <code>RMIServerSocketFactory</code> whose <code>
   *       createServerSocket</code> method returns a <code>ServerSocket</code> constructed with the
   *       specified port that delays accepting requests until the specified proxy is bound in the
   *       registry. In this case, if the port is <code>0</code>, then an <code>
   *       IllegalArgumentException</code> is thrown.
   *   <li>Otherwise, if the <code>System.inheritedChannel</code> returns an instance of any other
   *       type, an <code>IOException</code> is thrown.
   * </ul>
   *
   * <p>Once the registry is exported, the registry's <code>bind</code> method is invoked with the
   * specified name and proxy as arguments.
   *
   * @param obj the proxy for a remote object
   * @param name the name for the remote object in the registry
   * @param port a port to export the registry on if there is no inherited channel
   * @throws IllegalArgumentException if the inherited channel is <code>null</code> and the port is
   *     <code>0</code>
   * @throws IllegalStateException if this method was called previously
   * @throws IOException if the inherited channel is not an instance of <code>ServerSocketChannel
   *     </code> or <code>null</code>
   * @throws RemoteException if the registry could not be exported
   */
  public static void initializeWithInheritedChannel(Remote proxy, String name, int port)
      throws IOException {
    /*
     * Only allow this method to be invoked once.
     */
    synchronized (InitializeRegistry.class) {
      if (initialized) {
        throw new IllegalStateException("already invoked");
      }
      initialized = true;
    }

    Channel channel = System.inheritedChannel();
    ServerSocket serverSocket = null;

    /*
     * Handle inherited channel, if any.
     */
    if (channel instanceof ServerSocketChannel) {
      /*
       * Service launched from inetd.  Get server socket from
       * inherited server socket channel.
       */
      serverSocket = ((ServerSocketChannel) channel).socket();

    } else if (channel instanceof SocketChannel) {
      throw new IllegalArgumentException("got a Socket Channel instead");
    } else if (channel == null) {
      /*
       * Service launched from the command line.  In this case, the
       * port specified for the registry must be nonzero
       */
      if (port == 0) {
        throw new IllegalArgumentException("port must be nonzero");
      }
      serverSocket = new ServerSocket(port);

    } else {
      throw new IOException(
          "unexpected channel returned from inheritedChannel: " + channel.toString());
    }

    /*
     * Create server socket factory for registry to delay accepting
     * calls until a service is bound in the registry.
     */
    RMIServerSocketFactory ssf = new RegistryServerSocketFactory(serverSocket);

    /*
     * Create/export registry and bind name to proxy in registry.
     */
    Registry registry = LocateRegistry.createRegistry(port, null, ssf);
    try {
      registry.bind(name, proxy);
    } catch (RemoteException impossible) {
      throw new AssertionError(impossible);
    } catch (AlreadyBoundException impossible) {
      throw new AssertionError(impossible);
    }

    /*
     * Notify registry's socket factory that the service proxy is
     * bound in the registry, so that the registry can accept
     * incoming requests to look up the service.
     */
    synchronized (lock) {
      serviceAvailable = true;
      lock.notifyAll();
    }
  }
예제 #22
0
 public void instaceRegistration()
     throws RemoteException, AlreadyBoundException, UnknownHostException, SocketException {
   Registry registry = LocateRegistry.getRegistry(this.regPort);
   this.registry = registry;
   registry.bind("Reg", this);
 }
 public static void startCooking(String host, int port) throws Exception {
   final Registry registry = LocateRegistry.getRegistry(host, port);
   registry.bind(RemoteDeadHand.BINDING_NAME, ourHand);
 }
  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");
      }
    }
  }