/**
   * 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);
  }
  public static void main(String[] args) {
    String host = args[0];
    int port = Integer.parseInt(args[1]);
    long id = Long.parseLong(args[2]);
    String character = args[3];
    long actorId = Long.parseLong(args[4]);

    // Install an RMISecurityManager, if there is not a
    // SecurityManager already installed
    if (System.getSecurityManager() == null) {
      System.setSecurityManager(new RMISecurityManager());
    }

    String name = "rmi://" + host + ":" + port + "/MovieDatabase";

    try {
      MovieDatabase db = (MovieDatabase) Naming.lookup(name);
      db.noteCharacter(id, character, actorId);

      Movie movie = db.getMovie(id);
      out.println(movie.getTitle());
      for (Map.Entry entry : movie.getCharacters().entrySet()) {
        out.println("  " + entry.getKey() + "\t" + entry.getValue());
      }

    } catch (RemoteException | NotBoundException | MalformedURLException ex) {
      ex.printStackTrace(System.err);
    }
  }
 /**
  * Costruttore di classe. Inizializza la griglia e si collega al server.
  *
  * @throws MalformedURLException
  * @throws RemoteException
  * @throws NotBoundException
  */
 public TicTacToeClient() throws MalformedURLException, RemoteException, NotBoundException {
   idGameCreated = "";
   idGameJoined = "";
   grid = new int[Game.GRID_DIMENSION][Game.GRID_DIMENSION];
   for (int i = 0; i < Game.GRID_DIMENSION; i++)
     for (int j = 0; j < Game.GRID_DIMENSION; j++) grid[i][j] = Game.FREE_CELL;
   wrs = new LinkedList<Watcher>();
   server = (TicTacToeServer) Naming.lookup("rmi://" + IP_SERVER + "/tictactoe");
 }
 public TopoAPI getHandle() {
   TopoAPI topo = null;
   ManagedObject child = null;
   TopoObject to = null;
   Vector v = new Vector();
   try {
     topo = (TopoAPI) Naming.lookup("//192.168.15.70/TopoAPI");
     System.out.println("sucessfully got	 the handle");
   } catch (Exception exx) {
     System.out.println("Exception while getting handle " + exx);
   }
   return topo;
 }
Esempio n. 5
0
  // we define the method for getting a video link when pressing enter
  public String getvidlink() {
    try {
      System.setSecurityManager(new SecurityManager());

      ipadd = tfIP.getText();
      Interface client = (Interface) Naming.lookup("rmi://" + ipadd + "/getvid");

      // Get the String entered into the TextField tfInput, convert to int
      link = tfInput.getText();
      vlink = client.getvid(link);

    } catch (Exception e) {
      System.out.println("[System] Server failed: " + e);
    }
    return vlink;
  }
  /**
   * Instantiates an event handler for forwarding events from a specific object.
   *
   * @param receiverAddress The address of the RMI service to be called when the notification is
   *     forwarded.
   * @param rmiConnectorServer The Rmi connector Server
   */
  public RmiNotificationForwarder(
      RmiConnectorAddress receiverAddress, RmiConnectorServer rmiConnectorServer)
      throws RemoteException, IllegalAccessException {

    this.receiverAddress = receiverAddress;
    this.rmiConnectorServer = rmiConnectorServer;

    // ---------------------------
    // build the RMI url
    // ---------------------------
    String receiverName =
        new String(
            "rmi://"
                + receiverAddress.getHost()
                + ":"
                + receiverAddress.getPort()
                + "/"
                + receiverAddress.getName());
    if (logger.finestOn()) {
      logger.finest("Constructor", "looking for " + receiverName);
    }

    // ---------------------------
    // We are going to try to get a reference on the receiver
    // ---------------------------
    try {
      this.rmiNotificationReceiver = (RmiNotificationReceiver) Naming.lookup(receiverName);
      connected = true;
      if (this.rmiNotificationReceiver == null) {
        if (logger.finestOn()) {
          logger.finest("handleEvent", "receiver is null");
        }
        throw new RemoteException(
            "Can't contact RMI Notification receive server at " + receiverName);
      }
    } catch (Exception x) {
      throw new RemoteException("Can't contact RMI Notification receive server at " + receiverName);
    }
  }
Esempio n. 7
0
  /**
   * Generate random data and assign it to a variable in a belief network. The command line
   * arguments are:
   *
   * <pre>
   *   java riso.remote_data.RandomEvidence [-h rmi-host] [-s server-name]
   * </pre>
   *
   * The <tt>rmi-host</tt> is the name of the host running <tt>rmiregistry</tt>. The
   * <tt>server-name</tt> is the name by which this data source will be known.
   */
  public static void main(String[] args) {
    String bn_name = null, variable_name = null;
    int i, j;

    for (i = 0; i < args.length; i++) {
      switch (args[i].charAt(1)) {
        case 'b':
          bn_name = args[++i];
          break;
        case 'x':
          variable_name = args[++i];
          break;
      }
    }

    System.err.println("RandomEvidence: bn_name: " + bn_name + " variable_name: " + variable_name);

    try {
      String url = "rmi://" + bn_name;
      AbstractBeliefNetwork bn = (AbstractBeliefNetwork) Naming.lookup(url);
      AbstractVariable v = (AbstractVariable) bn.name_lookup(variable_name);
      Distribution p = bn.get_posterior(v);
      System.err.println("RandomEvidence: sample from: ");
      System.err.println(p.format_string("\t"));

      while (true) {
        double[] x = p.random();
        bn.assign_evidence(v, x[0]);
        try {
          Thread.sleep(10000);
        } catch (InterruptedException e) {
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }
  }
Esempio n. 8
0
  // we define the method for downloading when pressing on the download button
  public void qrvidlink() {
    try {
      System.setSecurityManager(new SecurityManager());

      ipadd = tfIP.getText();
      Interface client = (Interface) Naming.lookup("rmi://" + ipadd + "/getvid");

      // Get the String entered into the TextField tfInput, convert to int
      link = tfInput.getText();
      vlink = client.getvid(link);

      // here we receive the image serialized into bytes from the server and
      // saved it on the client as png image
      byte[] bytimg = client.qrvid(vlink);
      BufferedImage img = ImageIO.read(new ByteArrayInputStream(bytimg));
      File outputfile = new File("qrcode.png");
      ImageIO.write(img, "png", outputfile);

      // img= new ImageIcon(bytimg.toByteArray());
    } catch (Exception e) {
      System.out.println("[System] Server failed: " + e);
    }
  }
Esempio n. 9
0
  public static void main(String[] args) {
    boolean all_x = false, do_bind = false;
    String bn_name = "", context_name = "";
    int i;

    for (i = 0; i < args.length; i++) {
      if (args[i].charAt(0) != '-') continue;

      switch (args[i].charAt(1)) {
        case 'b':
          bn_name = args[++i];
          break;
        case 'c':
          context_name = args[++i];
          break;
        case 'r':
          do_bind = true;
          break;
      }
    }

    AbstractBeliefNetworkContext bnc = null;
    AbstractBeliefNetwork bn = null;
    AbstractVariable x = null, e_var = null;

    try {
      if ("".equals(context_name)) {
        BeliefNetworkContext local_bnc = new BeliefNetworkContext(null);
        bnc = local_bnc;
      } else {
        String url = "rmi://" + context_name;
        System.err.println("Informativeness: url: " + url);
        long t0 = System.currentTimeMillis();
        bnc = (AbstractBeliefNetworkContext) Naming.lookup(url);
        long tf = System.currentTimeMillis();
        System.err.println(
            "Informativeness: Naming.lookup complete (for belief net context), elapsed time: "
                + ((tf - t0) / 1000.0)
                + " [s]");
      }

      bn = (AbstractBeliefNetwork) bnc.load_network(bn_name);
      if (do_bind) {
        System.err.println("Informativeness: bind belief net.");
        bnc.bind(bn);
      }

      String e_name, x_name;
      double e_value;

      for (i = 0; i < args.length; i++) {
        if (args[i].charAt(0) != '-') continue;

        switch (args[i].charAt(1)) {
          case 'x':
            if ("-xall".equals(args[i])) {
              AbstractVariable[] u = bn.get_variables();
              for (int j = 0; j < u.length; j++) {
                Distribution xposterior = bn.get_posterior(u[j]);
                System.out.println("Informativeness: posterior for " + u[j].get_name() + ":");
                System.out.print("  " + xposterior.format_string("  "));
              }
            } else {
              x_name = args[++i];
              long t0 = System.currentTimeMillis();
              x = (AbstractVariable) bn.name_lookup(x_name);
              long tf = System.currentTimeMillis();
              System.err.println(
                  "Informativeness: Naming.lookup complete (for variable ref), elapsed time: "
                      + ((tf - t0) / 1000.0)
                      + " [s]");
              if (x == null) throw new Exception("name_lookup failed: x: " + x_name);
              Distribution xposterior = bn.get_posterior(x);
              System.out.println("Informativeness: posterior for " + x.get_name() + ":");
              System.out.print("  " + xposterior.format_string("  "));
            }
            break;
          case 'e':
            if (args[i].length() > 2 && args[i].charAt(2) == '-') {
              e_name = args[++i];
              System.err.println("Informativeness.main: evidence: clear " + e_name);
              e_var = (AbstractVariable) bn.name_lookup(e_name);
              bn.clear_posterior(e_var);
            } else {
              e_name = args[++i];
              e_value = Double.parseDouble(args[++i]);
              System.err.println(
                  "Informativeness.main: evidence: set " + e_name + " to " + e_value);

              long t0 = System.currentTimeMillis();
              e_var = (AbstractVariable) bn.name_lookup(e_name);
              long tf = System.currentTimeMillis();
              System.err.println(
                  "Informativeness: Naming.lookup complete (for variable ref), elapsed time: "
                      + ((tf - t0) / 1000.0)
                      + " [s]");
              bn.assign_evidence(e_var, e_value);
            }
            break;
          default:
            continue;
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    System.exit(0);
  }
Esempio n. 10
0
  public static void main(String args[]) {
    if (args.length != 2) {
      System.err.println("Uso: ObservadorCentralita hostregistro numPuertoRegistro");
      return;
    }

    // Instancia gestor de seguridad
    if (System.getSecurityManager() == null) {
      System.setSecurityManager(new SecurityManager());
    }
    try {
      // Obtiene referencia remota del servicio de rmiregistry
      ServicioCentralita srv =
          (ServicioCentralita) Naming.lookup("//" + args[0] + ":" + args[1] + "/Centralita");
      //                                                            |               |-> Número de
      // puerto escucha
      //                                                            |-> Host en el que se ejecuta el
      // servicio

      String nombreServicio = "default";

      while (nombreServicio == "default") {
        // Captura el nombre del servicio
        System.out.println(
            "Elija el servicio:\n\t[1] Bomberos\n\t[2] Sanitarios\n\t[3] Policía\n\t[4] Guardia Civil");
        Scanner input = new Scanner(System.in);
        String tipoServicio = input.nextLine();

        switch (tipoServicio) {
          case "1":
            nombreServicio = "Bomberos";
            break;
          case "2":
            nombreServicio = "Sanitarios";
            break;
          case "3":
            nombreServicio = "Policia";
            break;
          case "4":
            nombreServicio = "Guardia Civil";
            break;
          default:
            nombreServicio = "default";
            break;
        }
      }

      // Crea nuevo observador y lo registra en la lista
      ObservadorImpl o = new ObservadorImpl(nombreServicio);

      // Llamada al método remoto 'addObservador' del servicio
      srv.addObservador(o, nombreServicio);

      // Comrpeuba el nombre del servicio para imprimir código de color
      if (nombreServicio.equals("Bomberos")) {
        System.out.println(
            "\u001B[31mObservador " + nombreServicio + " registrado en la centralita\u001B[0m\n");
      } else if (nombreServicio.equals("Sanitarios")) {
        System.out.println(
            "\u001B[35mObservador " + nombreServicio + " registrado en la centralita\u001B[0m\n");
      } else if (nombreServicio.equals("Policia")) {
        System.out.println(
            "\u001B[34mObservador " + nombreServicio + " registrado en la centralita\u001B[0m\n");
      } else if (nombreServicio.equals("Guardia Civil")) {
        System.out.println(
            "\u001B[32mObservador " + nombreServicio + " registrado en la centralita\u001B[0m\n");
      }

      // Se mantiene esperando hasta que se para con Ctrl+D
      System.out.println("Para salir, pulsar Ctrl+D\n");
      Scanner sleep = new Scanner(System.in);
      while (sleep.hasNextInt()) {}

      // Elimina de la lista al observador. Llamada al método remoto 'delObservador' del servicio
      srv.delObservador(o, nombreServicio);
      System.exit(0);
    }
    // Excepción RMI
    catch (RemoteException e) {
      System.err.println("Error de comunicación: " + e.toString());
    }
    // Excepción cliente
    catch (Exception e) {
      System.err.println("Excepción en ObservadorCentralita: ");
      e.printStackTrace();
    }
  }