示例#1
0
  public static void main(String[] args) {
    String groupName = "TestGroup";
    MulticastStrategy tree = new TreeBaseMulticast();
    Orderer causal = new CausalOrderer();

    try {

      ComMember mbr1 = new ComMember(tree, "mbr1");
      ComObserver m = new MemberImpl(causal, mbr1);
      mbr1.addObserver(m);
      mbr1.addObserver(new groupRegisteringTest());
      Registry dictionary = LocateRegistry.getRegistry(NamingService.SERVER_PORT);
      NamingServiceRemote server =
          (NamingServiceRemote) dictionary.lookup(NamingService.SERVICE_NAME);
      LinkedList<String> groups = server.getGroups();
      if (!(groups.isEmpty())) {
        System.out.println("Available groups : ");
        for (String grp : groups) System.out.println("\t- " + grp);
      }
      RemoteMember leader = server.joinGroup("TestGroup", mbr1);
      System.out.println(leader.toString());
      leader.deliver(new ComMessage<String>(new String("Hej Hej!")));
      // mbr.post( new CommMessage<String>( new String("Hej Hej!") ), server.getSharedObjects() ) ;
    } catch (RemoteException e) {
      e.printStackTrace();
    } catch (NotBoundException e) {
      e.printStackTrace();
    }
  }
示例#2
0
  /** Stop. */
  public void stop() {
    this.lookupTask.stop();

    if (this.stub != null) {
      try {
        this.reg.unbind(this.bindingName);

        this.dist.unexportClients();

        this.dist.unexportServer();

        UnicastRemoteObject.unexportObject(this.dist, true);
      } catch (RemoteException rex) {
        logger.warning(rex.getMessage());
      } catch (NotBoundException nbex) {
        logger.warning(nbex.getMessage());
      }
    }

    try {
      UnicastRemoteObject.unexportObject(this.reg, true);
    } catch (NoSuchObjectException ex) {
      ex.printStackTrace();
    }
  }
示例#3
0
文件: Arene.java 项目: clem822/bl
  /**
   * Renvoie la console correspondant a la reference RMI donnee.
   *
   * @param refRMI reference RMI
   * @return console correspondante
   * @throws RemoteException
   */
  protected IConsole consoleFromRef(int refRMI) throws RemoteException {
    int p = port + refRMI;
    String ip = null;
    String adr = null;
    IConsole console = null;

    try {
      ip = personnages.get(refRMI).getAdresseIp();
      adr = Constantes.nomRMI(ip, p, "Console" + refRMI);
      console = (IConsole) Naming.lookup(adr);

    } catch (MalformedURLException e) {
      console = null;
      logger.severe(Constantes.nomClasse(this), "Erreur : acces a " + adr + "\n" + e.toString());
      e.printStackTrace();

    } catch (NotBoundException e) {
      console = null;
      logger.severe(Constantes.nomClasse(this), "Erreur : acces a " + adr + "\n" + e.toString());
      e.printStackTrace();

    } catch (NullPointerException e) {
      console = null;
    }

    return console;
  }
  /** Instanciação e Inicialização do ZonaDesembarqueRegister */
  public ZonaDesembarqueRegister() {
    super();
    canEnd = false;

    try {
      registry = LocateRegistry.getRegistry(registryHostname, registryPort);
      log = (LoggingInterface) registry.lookup("Logging");
    } catch (RemoteException e) {
      GenericIO.writelnString("Excepção na localização do Logging: " + e.getMessage() + "!");
      e.printStackTrace();
      System.exit(1);
    } catch (NotBoundException e) {
      GenericIO.writelnString("O Logging não está registado: " + e.getMessage() + "!");
      e.printStackTrace();
      System.exit(1);
    }

    desembarque = new ZonaDesembarque(log, this);
    try {
      desembarqueInterface =
          (ZonaDesembarqueInterface)
              UnicastRemoteObject.exportObject(
                  desembarque, portNumber[Globals.MON_ZONA_DESEMBARQUE]);
    } catch (RemoteException e) {
      System.exit(1);
    }
  }
示例#5
0
  /** @param args */
  public static void main(String[] args) {
    try {
      CardValidator cv = (CardValidator) Naming.lookup("rmi://172.25.12.148/Cards");

      Scanner scanner = new Scanner(System.in);
      System.out.println("Enter the cardNo");
      long cardNo = scanner.nextLong();
      System.out.println("Enter the amount");
      float amount = scanner.nextFloat();

      boolean flag = cv.validateCard(cardNo, amount);
      if (flag) {
        System.out.println("Card Accepted");
      } else {
        System.out.println("Card Declined");
      }
    } catch (MalformedURLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (RemoteException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (NotBoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
示例#6
0
  public Object start(IApplicationContext context) {

    // create and register a backend server
    // TODO: this info should be saved, not hard coded.
    try {
      context.applicationRunning(); // only run one
      //			MonitorServerManager.getInstance().getServers().get("");
      MonitorServer server = new MonitorServer("admin", "", "admin");
      MonitorServerManager.getInstance().registerServer(server);
      if (!login(server)) return IApplication.EXIT_OK;
      //			MonitorServerManager.getInstance().getCurServer().connectAndLogin();
      //			server.connectAndLogin();

    } catch (RemoteException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (NotBoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    Display display = PlatformUI.createDisplay();
    try {
      int returnCode = PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor());

      if (returnCode == PlatformUI.RETURN_RESTART) {
        return IApplication.EXIT_RESTART;
      }
      return IApplication.EXIT_OK;
    } finally {
      display.dispose();
    }
  }
示例#7
0
 private void checkSslConfig() throws IOException {
   // Get the reference to the RMI Registry and lookup RMIServer stub
   //
   Registry registry;
   try {
     registry =
         LocateRegistry.getRegistry(registryHostName, registryPort, sslRMIClientSocketFactory);
     try {
       stub = (RMIServer) registry.lookup("jmxrmi");
     } catch (NotBoundException nbe) {
       throw (IOException) new IOException(nbe.getMessage()).initCause(nbe);
     }
     sslRegistry = true;
   } catch (IOException e) {
     registry = LocateRegistry.getRegistry(registryHostName, registryPort);
     try {
       stub = (RMIServer) registry.lookup("jmxrmi");
     } catch (NotBoundException nbe) {
       throw (IOException) new IOException(nbe.getMessage()).initCause(nbe);
     }
     sslRegistry = false;
   }
   // Perform the checks for secure stub
   //
   try {
     checkStub(stub, rmiServerImplStubClass);
     sslStub = true;
   } catch (SecurityException e) {
     sslStub = false;
   }
 }
  /**
   * Create a MonitoredHostProvider instance using the given HostIdentifier.
   *
   * @param hostId the host identifier for this MonitoredHost
   * @throws MonitorException Thrown on any error encountered while communicating with the remote
   *     host.
   */
  public MonitoredHostProvider(HostIdentifier hostId) throws MonitorException {
    this.hostId = hostId;
    this.listeners = new ArrayList();
    this.interval = DEFAULT_POLLING_INTERVAL;
    this.activeVms = new HashSet();

    String rmiName;
    String sn = serverName;
    String path = hostId.getPath();

    if ((path != null) && (path.length() > 0)) {
      sn = path;
    }

    if (hostId.getPort() != -1) {
      rmiName = "rmi://" + hostId.getHost() + ":" + hostId.getPort() + sn;
    } else {
      rmiName = "rmi://" + hostId.getHost() + sn;
    }

    try {
      remoteHost = (RemoteHost) Naming.lookup(rmiName);

    } catch (RemoteException e) {
      /*
       * rmi registry not available
       *
       * Access control exceptions, where the rmi server refuses a
       * connection based on policy file configuration, come through
       * here on the client side. Unfortunately, the RemoteException
       * doesn't contain enough information to determine the true cause
       * of the exception. So, we have to output a rather generic message.
       */
      String message = "RMI Registry not available at " + hostId.getHost();

      if (hostId.getPort() == -1) {
        message = message + ":" + java.rmi.registry.Registry.REGISTRY_PORT;
      } else {
        message = message + ":" + hostId.getPort();
      }

      if (e.getMessage() != null) {
        throw new MonitorException(message + "\n" + e.getMessage(), e);
      } else {
        throw new MonitorException(message, e);
      }

    } catch (NotBoundException e) {
      // no server with given name
      String message = e.getMessage();
      if (message == null) message = rmiName;
      throw new MonitorException("RMI Server " + message + " not available", e);
    } catch (MalformedURLException e) {
      // this is a programming problem
      e.printStackTrace();
      throw new IllegalArgumentException("Malformed URL: " + rmiName);
    }
    this.vmManager = new RemoteVmManager(remoteHost);
    this.timer = new Timer(true);
  }
示例#9
0
  private boolean login(final MonitorServer server) {
    boolean firstTry = true;
    SecureLoginDialog loginDialog = new SecureLoginDialog(null);
    while (!(MonitorServerManager.getInstance().getLoginSucess())) {
      IPreferencesService service = Platform.getPreferencesService();
      boolean auto_login =
          service.getBoolean(Application.PLUGIN_ID, GeneralPreferencePage.AUTO_LOGIN, false, null);
      MonitorServer details = loginDialog.getConnectionDetails();
      if (!auto_login || details == null || !firstTry) {
        if (loginDialog.open() != Window.OK) return false;
        details = loginDialog.getConnectionDetails();
      }
      firstTry = false;

      //			session.setConnectionDetails(details);
      //			MonitorServerManager.getInstance().registerServer(server);
      MonitorServerManager.getInstance().setCurServer(details);
      try {
        MonitorServerManager.getInstance().registerServer(details);
      } catch (RemoteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (NotBoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      connectWithProgress(details);
    }
    return true;
  }
示例#10
0
  public SetupDataClient() throws RemoteException {

    try {
      // get the registry
      registry = LocateRegistry.getRegistry(serverAddress, (new Integer(serverPort)).intValue());
      // look up the remote object
      rmiServer = (databaseinter) registry.lookup("Database");

      rmiServer.receiveMessage("abc");
      // starting time
      long time1 = System.currentTimeMillis();
      // call the remote method

      System.out.println("sending " + text + " to " + serverAddress + ":" + serverPort);
      // receiving time
      long time2 = System.currentTimeMillis();
      long timedelay = time2 - time1;
      System.out.println("RMI delay time: " + timedelay);
      // converting process

      // finish converting
      long time3 = System.currentTimeMillis();
      long timefinish = time3 - time1;
      System.out.println("Total time: " + timefinish);
    } catch (NotBoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      System.out.println("File not found");
      System.out.println(e.getMessage());
      e.printStackTrace();
    }
  }
示例#11
0
  public JParSolverImpl(String host, int port) throws RemoteException {
    if (System.getSecurityManager() == null) {
      System.setSecurityManager(new RMISecurityManager());
    }

    String serverName = "JParServer";
    try {
      Registry registry = LocateRegistry.getRegistry(host, port);
      this.server = (JParServer) registry.lookup(serverName);
    } catch (AccessException e) {
      System.err.println("Solver: Java RMI AccessException: " + e.getMessage());
      return;
    } catch (RemoteException e) {
      System.err.println("Solver: Java RMI Exception: " + e.getMessage());
      return;
    } catch (NotBoundException e) {
      System.err.println("Solver: " + serverName + " lookup failed:" + e.getMessage());
      return;
    } catch (Exception e) {
      System.err.println("Solver: JParSolver Constructor:" + e.getMessage());
      e.printStackTrace();
      return;
    }

    this.taskSynchObj = new Object();
    this.pendingJob = JOB_WAITING_FOR;

    if (this.register()) {
      initialized = true;
    }
  }
 @Override
 public int replyToCoordinatingServer(int articleId, Article article, ConsistencyType type)
     throws RemoteException {
   final String method = CLASS_NAME + ".replyToCoordinatingServer()";
   LogUtil.log(
       method,
       "Server:"
           + Server.getServerId()
           + " "
           + "Replying to: "
           + articleId
           + " article : "
           + article
           + " in Coordinating server");
   try {
     TimeUtil.delay();
     return coordServerImpl.replyToCoordinatingServer(articleId, article, type);
   } catch (MalformedURLException e) {
     LogUtil.log(method, "Got exception : " + e.getMessage());
     throw new RemoteException("Got exception in connection to other servers.", e);
   } catch (InvalidArticleException e) {
     LogUtil.log(method, "Got exception : " + e.getMessage());
     throw new RemoteException("Got exception in connection to other servers.", e);
   } catch (NotBoundException e) {
     LogUtil.log(method, "Got exception : " + e.getMessage());
     throw new RemoteException("Got exception in connection to other servers.", e);
   }
 }
示例#13
0
  public void init() {

    // read network configuration
    Configuration config = null;
    try {
      config = new PropertiesConfiguration("network.cfg");
    } catch (ConfigurationException e) {
      e.printStackTrace();
    }

    urls = config.getStringArray("node.url");
    processes = new ArrayList<DA_Schiper_Eggli_Sandoz_RMI>();

    // locate processes
    for (String url : urls) {
      try {
        DA_Schiper_Eggli_Sandoz_RMI process = (DA_Schiper_Eggli_Sandoz_RMI) Naming.lookup(url);
        process.reset();
        processes.add(process);

      } catch (RemoteException e1) {
        e1.printStackTrace();
      } catch (NotBoundException e2) {
        e2.printStackTrace();
      } catch (MalformedURLException e3) {
        e3.printStackTrace();
      }
    }
  }
  @Override
  @SuppressWarnings("unchecked")
  public void process(Object instance) throws MakeATestRMIAssertionError {
    // Get Remote Interface to Mock
    Field[] fields = this.annotated.getDeclaringClass().getDeclaredFields();
    for (int i = 0; i < fields.length; i++) {
      Field field = fields[i];
      if (field.getName().equals(this.fixtureName)) {
        this.contextMockType = (Class<? extends Remote>) field.getType();
        break;
      }
    }

    // Validations
    if (this.contextMockType == null)
      throw new MakeATestRMIAssertionError(
          "Não foi encontrado nenhuma instância com o nome "
              + this.fixtureName
              + " neste contexto.");
    System.out.println("AssertObjectOnServer process");

    RMIController rmi = new RMIController();
    try {
      Assert.assertTrue(rmi.objectOnServer(this.contextMockType, this.serverName));
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (RemoteException e) {
      e.printStackTrace();
    } catch (NotBoundException e) {
      e.printStackTrace();
    }
  }
示例#15
0
文件: Expense.java 项目: Hanifor/SE2
 public Expense() {
   try {
     expenseData = (ExpenseDataService) Naming.lookup(RMIConfig.PREFIX + ExpenseDataService.NAME);
   } catch (MalformedURLException e) {
     e.printStackTrace();
   } catch (RemoteException e) {
     e.printStackTrace();
   } catch (NotBoundException e) {
     e.printStackTrace();
   }
 }
示例#16
0
 private void initBL() {
   try {
     bankAccountBLService = BLFactory.getBankAccountBLService();
   } catch (MalformedURLException e) {
     System.out.println(e.getMessage());
   } catch (RemoteException e) {
     new TranslucentFrame(this, MessageType.RMI_LAG, Color.ORANGE);
   } catch (NotBoundException e) {
     System.out.println(e.getMessage());
   }
 }
示例#17
0
  private Descrittore contatta_server(String nome) {

    // variabili per l'RMI
    RMIServerInt serv = null; // server
    Descrittore descr_rit = null; // descrittore ritornato

    if (nome == null) {
      System.out.println("## contatta_server di Download ha ricevuto parametro null ! ");
      return null;
    }

    System.out.println("@ provo a contattare il server RMI ");
    // ################  RMI ################
    if (System.getSecurityManager() == null) {
      System.setSecurityManager(new SecurityManager());
    }

    Object o = null;
    try {
      // o = Naming.lookup("rmi://192.168.0.10:1099/srmi");
      Registry registry = LocateRegistry.getRegistry(server.getHostAddress());
      o = registry.lookup("srmi");

    } catch (RemoteException e) {
      System.out.println("## Problemi nell'RMI di Download - contatta_server di " + nome);
      e.printStackTrace();
    } catch (NotBoundException e) {
      System.out.println("## Problemi nell'RMI di Download - contatta_server di " + nome);
      e.printStackTrace();
    }

    if (o == null) {
      System.out.println(
          "## l'RMI di Download - contatta_server di " + nome + " ha ritornato l'oggetto o null");
      return null;
    }

    serv = (RMIServerInt) o;

    try {
      descr_rit = serv.lookup(nome, InetAddress.getLocalHost());
    } catch (RemoteException e) {
      e.printStackTrace();
      System.out.println("## Problemi con Lookup di " + nome);
      return null;

    } catch (UnknownHostException e) {
      e.printStackTrace();
      System.out.println("## Problemi con Lookup di " + nome);
      return null;
    }

    return descr_rit;
  }
示例#18
0
 /**
  * ***************************************************************
  *
  * @param ip
  * @param port
  * @return
  */
 public ChordMessageInterface rmiChord(String ip, int port) {
   ChordMessageInterface chord = null;
   try {
     Registry registry = LocateRegistry.getRegistry(ip, port);
     chord = (ChordMessageInterface) (registry.lookup("Chord"));
     return chord;
   } catch (RemoteException e) {
     e.printStackTrace();
   } catch (NotBoundException e) {
     e.printStackTrace();
   }
   return null;
 }
示例#19
0
 public static void main(String args[]) {
   try {
     // 在RMI服务注册表中查找名称为Hello的对象,并调用其上的方法
     HelloService helloService = (HelloService) Naming.lookup("rmi://localhost:8888/Hello");
     LOGGER.debug(helloService.sayHello("zhangsan"));
   } catch (NotBoundException e) {
     e.printStackTrace();
   } catch (MalformedURLException e) {
     e.printStackTrace();
   } catch (RemoteException e) {
     e.printStackTrace();
   }
 }
示例#20
0
 public static void main(String args[]) {
   try {
     // 在RMI服务注册表中查找名称为RHello的对象,并调用其上的方法
     IHello rhello = (IHello) Naming.lookup("rmi://localhost:8888/RHello");
     System.out.println(rhello.helloWorld());
     System.out.println(rhello.sayHelloToSomeBody("熔岩"));
   } catch (NotBoundException e) {
     e.printStackTrace();
   } catch (MalformedURLException e) {
     e.printStackTrace();
   } catch (RemoteException e) {
     e.printStackTrace();
   }
 }
  /**
   * notifyMasterOfReduceTaskFailure: Get master's communicator and call reduceTaskFailed on it with
   * the failed reduceTask and the exception
   *
   * @param task
   * @param e
   */
  public void notifyMasterOfReduceTaskFailure(ReduceTask task, Exception e) {
    Registry registry;
    String masterNode = communicator.getMasterHostName();

    try {
      registry = LocateRegistry.getRegistry(masterNode, communicator.getREGISTRY_PORT());
      CommunicatorInterface communicator =
          (CommunicatorInterface) registry.lookup("communicator_" + masterNode);
      communicator.reduceTaskFailed(task, e);
    } catch (RemoteException e1) {
      e1.printStackTrace();
    } catch (NotBoundException e1) {
      e1.printStackTrace();
    }
  }
  /**
   * notifyMasterOfReduceTaskCompletion: Get the master's communicator and call reduceTaskCompleted
   * on it
   *
   * @param finished: the reduce task that just completed
   */
  private void notifyMasterOfReduceTaskCompletion(ReduceTask finished) {
    Registry registry;
    String masterNode = communicator.getMasterHostName();

    try {
      registry = LocateRegistry.getRegistry(masterNode, communicator.getREGISTRY_PORT());
      CommunicatorInterface communicator =
          (CommunicatorInterface) registry.lookup("communicator_" + masterNode);
      communicator.reduceTaskCompleted(finished);
    } catch (RemoteException e) {
      e.printStackTrace();
    } catch (NotBoundException e) {
      e.printStackTrace();
    }
  }
示例#23
0
 /** 增加机构信息 */
 public void addInstitution(InstitutionVO institutionvo) {
   try {
     DatabaseFactory database = (DatabaseFactory) Naming.lookup(RMIConnect.RMI);
     InformationFactory inf = database.getInformationFactory();
     InformationInsertDataService infoinsert = inf.getInformationInsertData();
     InstitutionPO ip = new InstitutionPO(institutionvo.getID(), institutionvo.getLocation());
     infoinsert.insert(ip);
   } catch (MalformedURLException e) {
     e.printStackTrace();
   } catch (RemoteException e) {
     e.printStackTrace();
   } catch (NotBoundException e) {
     e.printStackTrace();
   }
 }
 public static void startManagers() {
   try {
     if (gerenciadornuvem0 == null)
       gerenciadornuvem0 =
           (Gerenciadornuvem0Interface) Naming.lookup("rmi://0:1099/gerenciadornuvem0");
     if (gerenciadornuvem1 == null)
       gerenciadornuvem1 =
           (Gerenciadornuvem1Interface) Naming.lookup("rmi://1:1099/gerenciadornuvem1");
   } catch (RemoteException e) {
     e.printStackTrace();
   } catch (NotBoundException e) {
     e.printStackTrace();
   } catch (MalformedURLException e) {
     e.printStackTrace();
   }
 }
 @Override
 public List<Article> readFromCoordinatingServer(ConsistencyType type) throws RemoteException {
   final String method = CLASS_NAME + ".readFromCoordinatingServer()";
   LogUtil.log(
       method, "Server:" + Server.getServerId() + " " + "Reading from Coordinating server");
   try {
     TimeUtil.delay();
     return coordServerImpl.readFromCoordinatingServer(type);
   } catch (MalformedURLException e) {
     LogUtil.log(method, "Got exception : " + e.getMessage());
     throw new RemoteException("Got exception in connection to other servers.", e);
   } catch (NotBoundException e) {
     LogUtil.log(method, "Got exception : " + e.getMessage());
     throw new RemoteException("Got exception in connection to other servers.", e);
   }
 }
  /** Ciclo de vida do ZonaDesembarqueRegister */
  public synchronized void run() {
    String entry = "ZonaDesembarque";
    String nameEntryBase = "RegisterHandler";
    Register register = null;

    try {
      register = (Register) registry.lookup(nameEntryBase);
    } catch (RemoteException e) {
      GenericIO.writelnString("RegisterRemoteObject lookup exception: " + e.getMessage());
      e.printStackTrace();
      System.exit(1);
    } catch (NotBoundException e) {
      GenericIO.writelnString("RegisterRemoteObject not bound exception: " + e.getMessage());
      e.printStackTrace();
      System.exit(1);
    }

    try {
      register.bind(entry, desembarqueInterface);
    } catch (RemoteException e) {
      System.exit(1);
    } catch (AlreadyBoundException e) {
      System.exit(1);
    }

    GenericIO.writelnString("O serviço ZonaDesembarque foi estabelecido!");
    GenericIO.writelnString("O servidor esta em escuta.");

    try {
      while (!canEnd) {
        wait();
      }
    } catch (InterruptedException ex) {

    }
    try {
      register.unbind(entry);
    } catch (RemoteException ex) {
      System.exit(1);
    } catch (NotBoundException ex) {
      System.exit(1);
    }
    try {
      UnicastRemoteObject.unexportObject(desembarque, false);
    } catch (NoSuchObjectException ex) {
    }
  }
 public void launch() {
   if (System.getSecurityManager() == null) {
     System.setSecurityManager(new SecurityManager());
   }
   try {
     Remote service = Naming.lookup("//127.0.0.1:1099/finger");
     FingerService fingerService = (FingerService) service;
     String response = fingerService.usersReport();
     System.out.println("Finger Service Response: " + response);
   } catch (MalformedURLException ex) {
     ex.printStackTrace();
   } catch (NotBoundException ex) {
     ex.printStackTrace();
   } catch (RemoteException ex) {
     ex.printStackTrace();
   }
 }
示例#28
0
 public static void main(String[] args) {
   try {
     main();
   } catch (UnknownHostException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (RemoteException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (MeteoServiceException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (NotBoundException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
  @Override
  public synchronized Map<String, Object> bootstrap(Map<String, String> playerProperties)
      throws RemoteException {
    Registry registry = LocateRegistry.getRegistry(1099);
    Map<String, Object> gameProps = new HashMap<String, Object>();
    state = GameStateFactory.getGameState();
    PeerProperties peerProp = P2Player.getPeerProp();
    String name = playerProperties.get("name");
    String uuid = playerProperties.get("uuid");

    try {
      String primaryIP = (String) peerProp.getPrimaryProperties().get("ip");
      Nominator nominator = (Nominator) registry.lookup(uuid);
      if (state.getNumPlayers() == 1) {
        System.out.println("Backup server has arrived");
        gameProps.put("isNominated", true);
        gameProps.put("isSameMachine", primaryIP.equals(playerProperties.get("ip")) ? true : false);
        nominator.nominate(gameProps);
        state.setNumPlayers(state.getNumPlayers() + 1);
        peerProp.getSecondaryPeerIp().put("uuid", uuid);
        peerProp.getSecondaryPeerIp().put("ip", playerProperties.get("machineIP"));

        if (primaryIP.equals(playerProperties.get("machineIP"))) {
          peerProp.getSecondaryPeerIp().put("port", "1100"); // TODO: Looks incorrect, so changed
        } else {
          peerProp.getSecondaryPeerIp().put("port", "1099"); // TODO: Looks incorrect, so changed
        }
      } else {
        gameProps.put("isNominated", false);
        gameProps.put(
            "isSameMachine", primaryIP.equals(playerProperties.get("machineIP")) ? true : false);
        nominator.nominate(gameProps);
        state.setNumPlayers(state.getNumPlayers() + 1);
      }
    } catch (NotBoundException e) {
      e.printStackTrace();
    }
    gameProps.put("waitTime", peerProp.getInitTime() - System.currentTimeMillis());
    Player player = new Player(name, uuid);
    player.setPlayerDispId(playerDispId++);
    gameProps.put("playerDispId", playerDispId);
    state.getPlayers().put(uuid, player);
    while (!state.initializePlayer(uuid)) ;
    return gameProps;
  }
示例#30
0
  @Override
  public void inicio() throws GenericException {
    System.out.println("Servidor->" + servidor);
    // PEGO O SERVIDOR
    String nomeServidorJogo;
    try {
      nomeServidorJogo = ClientSession.getSession().getServerPrincipal().getServidor(servidor);
      ClientSession.getSession().setNomeServidor(nomeServidorJogo);
      IServidorRmi servidorJogo =
          (IServidorRmi) ClientSession.getSession().getRServidor().lookup("IServidorRmi");
      ClientSession.getSession().setServidor(servidorJogo);
      // PEGO A MINHA REFERENCIA
      // TODO ...........
      String logado =
          ClientSession.getSession().getServidorJogo().login(nomeServidorJogo, email, senha, 0);
      ClientSession.getSession().setJogador(logado);

      // EXPORTO O MEU OBJETO REMOTO
      // prepara o objeto remoto para registro
      UnicastRemoteObject.exportObject(frameChat, 0);

      // registra o(s) objeto(s) remoto(s)
      try {
        ClientSession.getSession().getRCliente().bind("JWarServerRmi", frameChat);
      } catch (AlreadyBoundException e) {
      }

      // PEGO A REFERENCIA PRO MEU CHAT
      String nomeChat = servidorJogo.connect(nomeServidorJogo, logado, frameChat);
      ClientSession.getSession().setChatName(nomeChat);
      IChatRmi chat = (IChatRmi) ClientSession.getSession().getRServidor().lookup("IChatRmi");
      ClientSession.getSession().setChat(chat);

    } catch (RemoteException e) {
      e.printStackTrace();
      throw new GenericException(e.getMessage(), RemoteException.class);

    } catch (NotBoundException e) {
      e.printStackTrace();
      throw new GenericException(e.getMessage(), NotBoundException.class);
    } catch (LoginException e) {
      e.printStackTrace();
      throw new GenericException(e.getMessage(), LoginException.class);
    }
  }