private static Echo[] spawnAndTest() {

    System.err.println("\nCreate Test-->");

    Echo[] echo = new Echo[protocol.length];

    for (int i = 0; i < protocol.length; i++) {

      JavaVM serverVM =
          new JavaVM("EchoImpl", "-Djava.security.policy=" + TestParams.defaultPolicy, protocol[i]);

      System.err.println("\nusing protocol: " + (protocol[i] == "" ? "none" : protocol[i]));

      try {
        /* spawn VM for EchoServer */
        serverVM.start();

        /* lookup server */
        int tries = 12; // need enough tries for slow machine.
        echo[i] = null;
        do {
          try {
            echo[i] = (Echo) Naming.lookup("//:" + REGISTRY_PORT + "/EchoServer");
            break;
          } catch (NotBoundException e) {
            try {
              Thread.sleep(2000);
            } catch (Exception ignore) {
            }
            continue;
          }
        } while (--tries > 0);

        if (echo[i] == null) TestLibrary.bomb("server not bound in 12 tries", null);

        /* invoke remote method and print result*/
        System.err.println("Bound to " + echo[i]);
        byte[] data = ("Greetings, citizen " + System.getProperty("user.name") + "!").getBytes();
        byte[] result = echo[i].echoNot(data);
        for (int j = 0; j < result.length; j++) result[j] = (byte) ~result[j];
        System.err.println("Result: " + new String(result));
        echo[i].shutdown();

      } catch (Exception e) {
        TestLibrary.bomb("test failed", e);

      } finally {
        serverVM.destroy();
        try {
          Naming.unbind("//:" + REGISTRY_PORT + "/EchoServer");
        } catch (Exception e) {
          TestLibrary.bomb("unbinding EchoServer", e);
        }
      }
    }
    return echo;
  }
  public static void main(String[] argv) {
    try {
      System.setSecurityManager(new RMISecurityManager());

      Addition Hello = new Addition();
      Naming.rebind("rmi://localhost/ABCD", Hello);

      System.out.println("Addition Server is ready.");
    } catch (Exception e) {
      System.out.println("Addition Server failed: " + e);
    }
  }
示例#3
0
文件: GuiClient.java 项目: x-mel/eva
  // 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;
  }
  private static void reactivateAndTest(Echo[] echo) {

    System.err.println("\nReactivate Test-->");

    for (int i = 0; i < echo.length; i++) {
      try {
        System.err.println("\nusing protocol: " + (protocol[i] == "" ? "none" : protocol[i]));
        byte[] data = ("Greetings, citizen " + System.getProperty("user.name") + "!").getBytes();
        byte[] result = echo[i].echoNot(data);
        for (int j = 0; j < result.length; j++) result[j] = (byte) ~result[j];
        System.err.println("Result: " + new String(result));
        echo[i].shutdown();
      } catch (Exception e) {
        TestLibrary.bomb("activating EchoServer for protocol " + protocol[i], e);
      }
    }
  }
示例#5
0
  public static void main(String args[]) {
    try {
      String serverName = args[0];

      Solver solver = new Solver();
      String rmiObServer = "rmi://" + HOST + "/" + serverName;
      Naming.rebind(rmiObServer, solver);
      System.out.println("Server ready");
    } catch (ArrayIndexOutOfBoundsException ex) {
      System.out.println("Error! E' necessario specificare il nome del server");
    } catch (RemoteException r) {
      System.out.println("Error while rebind object");
      r.printStackTrace();
      System.exit(1);
    } catch (MalformedURLException m) {
      System.out.println("Error! Malformed url require");
    }
  }
示例#6
0
  private static void setup() {

    try {

      NotActivatableInterface rsi; // Remote server interface

      System.setSecurityManager(new RMISecurityManager());

      rsi = (NotActivatableInterface) Activatable.register(ACTIVATION_DESC);
      System.out.println("Got stub for " + SERVER_OBJECT + " implementation");

      Naming.rebind(SERVER_OBJECT, rsi);
      System.out.println("Exported " + SERVER_OBJECT + " implementation");

    } catch (Exception e) {
      System.err.println("Exception: " + e);
      e.printStackTrace();
    }
  }
示例#7
0
文件: GuiClient.java 项目: x-mel/eva
  // 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);
    }
  }
 public void crash() {
   System.exit(0);
 }
示例#9
0
      public void actionPerformed(ActionEvent e) {
        if (e.getSource() == Connect) {
          if (nbr < 3) {
            if (nom.getText().length() == 0
                || pwd.getPassword().length == 0
                || jTextField1.getText().length() == 0) {
              JOptionPane.showMessageDialog(
                  null,
                  "Vous devez donner votre pseudonyme, votre mot de passe ainsi que l'adresse du serveur de chat",
                  "Informations manquantes",
                  JOptionPane.WARNING_MESSAGE);
              nbr++;
            } else {
              try {
                J = (Contrat) Naming.lookup("rmi://" + jTextField1.getText() + ":1099/JChat");
              } catch (RemoteException ex4) {
                JOptionPane.showMessageDialog(
                    null,
                    "La connexion au serveur a échoué",
                    "Serveur non démarré",
                    JOptionPane.WARNING_MESSAGE);
                System.out.println(ex4);
                nbr++;
              } catch (MalformedURLException ex4) {
                JOptionPane.showMessageDialog(
                    null, "Connexion 2", "Erreur de connexion", JOptionPane.WARNING_MESSAGE);
                nbr++;
              } catch (NotBoundException ex4) {
                JOptionPane.showMessageDialog(
                    null,
                    "Serveur non joignable",
                    "Erreur de connexion",
                    JOptionPane.WARNING_MESSAGE);
                System.out.println(ex4);
                System.exit(0);
              }
              if (J != null) {
                try { // de la méthode connect distante
                  // Récupération de l'adresse de la machine du client
                  try {
                    adr = InetAddress.getLocalHost().getHostName();
                  } catch (UnknownHostException ex3) {
                  }
                  // Si le nom et le mot de passe fournies par le client sont valides
                  // Envoi du nom et mot de passe pour la vérification de la validité de ce client
                  // ainsi que le num de port
                  // , adresse de la machine du client et nom de l'objet distant du client pour
                  // pouvoir l'invoquer ultérieurementulté
                  num_port = J.get_num_port();
                  if (J.connect(nom.getText(), new String(pwd.getPassword()), adr, num_port)) {
                    srv_Adr = jTextField1.getText();
                    srv_state = true;
                    // fermeture de la fenetre de connexion
                    fermer();
                    try {
                      java.rmi.registry.LocateRegistry.createRegistry(num_port);
                      System.out.println("Ecoute sur le port : " + num_port);
                      // Placement de l'objet distant du client sur sa machine : localhost dans le
                      // registre pour le numéro de port spécifié
                      Naming.rebind("//" + adr + ":" + num_port + "/" + nom.getText(), retourObj());
                      System.out.println(Naming.list("//" + adr + ":" + num_port)[0]);
                    } catch (MalformedURLException ex2) {
                      System.out.println(ex2);
                    } catch (RemoteException ex1) {
                      System.out.println(ex1);
                    }
                    // Constructeur graphique de la classe Client
                    C = new Client(nom.getText(), new String(pwd.getPassword()));
                    Essai essai = new Essai();
                    SplashWindowApp splash = new SplashWindowApp(C, 2000, essai);
                    if (J.getnbrcon() >= 2) {
                      System.out.println("Mise à jour de la liste du nouveau connecté");
                      // Mise à jour de la liste des destinataires du nouveau connecté
                      for (int i = 0; i < J.getnbrcon(); i++)
                        if (J.list_con()[i].compareTo(nom.getText()) != 0) C.ajout(J.list_con()[i]);
                    }
                  } else {
                    JOptionPane.showMessageDialog(
                        null, "Vérifiez votre pseudonyme ou mot de passe");
                    nbr++;
                  }

                } catch (RemoteException ex) {
                  System.out.println(ex);
                }
              }
            }
            if (nbr == 3) {
              JOptionPane.showMessageDialog(null, "Nombre maximum d'essai est atteint");
              System.exit(0);
            }
          }
        } else {
          if (e.getSource() == Annuler) System.exit(0);
        }
      }
示例#10
0
  /**
   * Contact a belief network context, get the helper list, and search the list to see if there's a
   * helper which matches the type sequence specified. If there's more than one helper which
   * matches, find the ``best fit.''
   *
   * <p>The class and count scores of the best-fitting helper class are written into
   * <tt>max_class_score[0]</tt> and <tt>max_count_score[0]</tt>, respectively.
   */
  public static Class find_helper_class0(
      Vector seq, String helper_type, int[] max_class_score, int[] max_count_score)
      throws ClassNotFoundException {
    long t0 = System.currentTimeMillis();
    if (bnc != null) // make sure the reference is still alive
    try {
        bnc.get_name();
      } catch (RemoteException e) {
        bnc = null;
      }

    if (bnc == null) // need to locate a context
    {
      String cb = System.getProperty("java.rmi.server.codebase", "http://localhost");
      long tt0 = System.currentTimeMillis();
      try {
        bnc = BeliefNetworkContext.locate_context(new URL(cb).getHost());
      } catch (Exception e) {
        throw new ClassNotFoundException("nested: " + e);
      }
    }

    String[] helperlist;
    try {
      helperlist = bnc.get_helper_names(helper_type);
    } catch (RemoteException e) {
      throw new ClassNotFoundException("bnc.get_helper_names failed");
    }

    int[] class_score1 = new int[1], count_score1 = new int[1];
    max_class_score[0] = -1;
    max_count_score[0] = -1;
    Class cmax_score = null;

    for (int i = 0; i < helperlist.length; i++) {
      try {
        Class c = RMIClassLoader.loadClass(helperlist[i]);
        SeqTriple[] sm = (SeqTriple[]) invoke_description(c);
        if (sm == null) continue; // apparently not a helper class
        if (MatchClassPattern.matches(sm, seq, class_score1, count_score1)) {
          if (class_score1[0] > max_class_score[0]
              || (class_score1[0] == max_class_score[0] && count_score1[0] > max_count_score[0])) {
            cmax_score = c;
            max_class_score[0] = class_score1[0];
            max_count_score[0] = count_score1[0];
          }
        }
      } catch (Exception e2) {
        System.err.println("PiHelperLoader: attempt to load " + helperlist[i] + " failed; " + e2);
      }
    }

    if (cmax_score == null) {
      System.err.println("find_helper_class0: failed; helper list:");
      for (int i = 0; i < helperlist.length; i++) System.err.println("\t" + helperlist[i]);

      String s = "";
      for (Enumeration e = seq.elements(); e.hasMoreElements(); ) {
        try {
          Class c = (Class) e.nextElement();
          s += c.getName() + ",";
        } catch (NoSuchElementException ee) {
          s += "???" + ",";
        }
      }

      throw new ClassNotFoundException("no " + helper_type + " helper for sequence [" + s + "]");
    }

    // FOR NOW IGNORE THE POSSIBILITY OF TWO OR MORE MATCHES !!!
    return cmax_score;
  }
示例#11
0
public class PiHelperLoader {
  /** The helper cache. The keys are instances of <tt>HelperCacheKey</tt>. */
  public static Hashtable helper_cache;

  /** The last time (in milliseconds since the epoch) the cache was emptied. */
  public static long cache_timestamp = System.currentTimeMillis();

  /** The helper cache is emptied every <tt>HELPER_CACHE_REFRESH</tt> milliseconds. */
  public static long HELPER_CACHE_REFRESH = 24L * 365L * 3600L * 1000L; // effectively never !!!

  // PERHAPS WE OUGHT TO MAINTAIN REFS TO SEVERAL CONTEXTS -- BOTH LOCAL AND REMOTE ??? !!!
  public static AbstractBeliefNetworkContext bnc = null;

  /**
   * When this class is loaded, preload the cache with a few items which we think will often be
   * needed. This can avoid the necessity of running a belief network context in simple problems.
   */
  static {
    System.err.println("PiHelperLoader.static: preload the helper cache.");

    helper_cache = new Hashtable();
    Vector seq = new Vector();

    seq.addElement(riso.distributions.ConditionalDiscrete.class);
    seq.addElement(riso.distributions.Discrete.class);

    helper_cache.put(
        new HelperCacheKey("pi", seq),
        riso.distributions.computes_pi.ConditionalDiscrete_Discrete.class);

    seq = new Vector();
    seq.addElement(riso.distributions.Discrete.class);

    helper_cache.put(
        new HelperCacheKey("lambda", seq), riso.distributions.computes_lambda.Discrete.class);

    seq = new Vector();
    seq.addElement(riso.distributions.AbstractDistribution.class);
    seq.addElement(riso.distributions.AbstractDistribution.class);

    helper_cache.put(
        new HelperCacheKey("pi_message", seq),
        riso.distributions.computes_pi_message.AbstractDistribution_AbstractDistribution.class);

    seq = new Vector();
    seq.addElement(riso.distributions.ConditionalDiscrete.class);
    seq.addElement(riso.distributions.Discrete.class);
    seq.addElement(riso.distributions.Discrete.class);

    helper_cache.put(
        new HelperCacheKey("lambda_message", seq),
        riso.distributions.computes_lambda_message.ConditionalDiscrete_Discrete_Discrete.class);

    seq = new Vector();
    seq.addElement(riso.distributions.ConditionalDiscrete.class);
    seq.addElement(riso.distributions.Discrete.class);

    helper_cache.put(
        new HelperCacheKey("lambda_message", seq),
        riso.distributions.computes_lambda_message.ConditionalDiscrete_Discrete_.class);

    seq = new Vector();
    seq.addElement(riso.distributions.Discrete.class);
    seq.addElement(riso.distributions.Discrete.class);

    helper_cache.put(
        new HelperCacheKey("posterior", seq),
        riso.distributions.computes_posterior.Discrete_Discrete.class);

    System.err.println("PiHelperLoader.static: helper_cache.size(): " + helper_cache.size());
  }

  public static PiHelper load_pi_helper(
      PiHelper pi_helper_cache, ConditionalDistribution pxu, Distribution[] pi_messages)
      throws Exception {
    if (pi_messages.length == 0) return new TrivialPiHelper();

    Vector seq = new Vector();
    seq.addElement(pxu.getClass());
    for (int i = 0; i < pi_messages.length; i++) seq.addElement(pi_messages[i].getClass());

    if (pi_helper_cache != null
        && MatchClassPattern.matches(pi_helper_cache.description(), seq, new int[1], new int[1]))
      return pi_helper_cache;

    Class c = find_helper_class(seq, "pi");
    return (PiHelper) c.newInstance();
  }

  /**
   * This method returns a <tt>Class</tt> for a helper which can handle the list of distributions
   * specified by <tt>seq1</tt>. We maintain a cache of recently-loaded helpers, so check the cache
   * before going to the trouble of searching for a helper. The cache is blown away every
   * <tt>HELPER_CACHE_REFRESH</tt> seconds.
   *
   * <p>If we can't find a helper in the cache, we must search through the list of available helpers
   * to find an appropriate one. First try to find helper using class sequence as specified by
   * <tt>seq</tt>. Whether or not that succeeds, promote any <tt>Gaussian</tt> in the sequence to
   * <tt>MixGaussians</tt>, and try again. If we get a better match on the second try, return the
   * helper thus found.
   */
  public static Class find_helper_class(Vector seq1, String helper_type)
      throws ClassNotFoundException {
    // Let's see if an appropriate helper is in the cache.
    // If the cache is too old, empty it and search for the helper anew.

    if (System.currentTimeMillis() - cache_timestamp > HELPER_CACHE_REFRESH) {
      helper_cache = new Hashtable();
      cache_timestamp = System.currentTimeMillis();
      // Go on and search for appropriate helper.
    } else {
      HelperCacheKey key = new HelperCacheKey(helper_type, seq1);
      Class helper_class = (Class) helper_cache.get(key);
      if (helper_class != null) {
        if (Global.debug > -1)
          System.err.println(
              "PiHelperLoader.find_helper_class: found helper class: "
                  + helper_class
                  + "; no need to search.");
        return helper_class;
      }
      // else no luck; we have to search for helper.
    }

    // Well, we didn't find a helper in the cache, so let's go to work.
    if (Global.debug > -1)
      System.err.println(
          "PiHelperLoader.find_helper_class: DID NOT FIND HELPER CLASS; NOW SEARCH.");

    Class c1 = null, c2 = null;
    ClassNotFoundException cnfe1 = null, cnfe2 = null;
    int[] class_score1 = new int[1], count_score1 = new int[1];
    int[] class_score2 = new int[1], count_score2 = new int[1];

    try {
      c1 = find_helper_class1(seq1, helper_type, class_score1, count_score1);
    } catch (ClassNotFoundException e) {
      cnfe1 = e;
    } // hang on, we may need to re-throw later.

    Class gaussian_class = Class.forName("riso.distributions.Gaussian");
    MixGaussians mog = new MixGaussians(1, 1);

    Vector seq2 = new Vector(seq1.size());
    for (int i = 0; i < seq1.size(); i++)
      if (gaussian_class.isAssignableFrom((Class) seq1.elementAt(i)))
        seq2.addElement(mog.getClass());
      else seq2.addElement(seq1.elementAt(i));

    try {
      c2 = find_helper_class1(seq2, helper_type, class_score2, count_score2);
    } catch (ClassNotFoundException e) {
      cnfe2 = e;
    }

    if (cnfe1 == null && cnfe2 == null) {
      // Both matched; see which one fits better.
      // Break ties in favor of the helper for non-promoted messages.

      if (class_score1[0] >= class_score2[0]
          || (class_score1[0] == class_score2[0] && count_score1[0] >= count_score2[0])) {
        if (Global.debug > 1)
          System.err.println(
              "\taccept helper " + c1 + " for non-promoted classes instead of " + c2);
        if (Global.debug > 1)
          System.err.println(
              "\t\t"
                  + class_score1[0]
                  + ", "
                  + class_score2[0]
                  + "; "
                  + count_score1[0]
                  + ", "
                  + count_score2[0]);
        helper_cache.put(new HelperCacheKey(helper_type, seq1), c1);
        return c1;
      } else {
        if (Global.debug > 1)
          System.err.println("\taccept helper " + c2 + " for promoted classes instead of " + c1);
        if (Global.debug > 1)
          System.err.println(
              "\t\t"
                  + class_score1[0]
                  + ", "
                  + class_score2[0]
                  + "; "
                  + count_score1[0]
                  + ", "
                  + count_score2[0]);
        helper_cache.put(new HelperCacheKey(helper_type, seq1), c2);
        return c2;
      }
    } else if (cnfe1 == null && cnfe2 != null) {
      // Only the first try matched, return it.
      helper_cache.put(new HelperCacheKey(helper_type, seq1), c1);
      return c1;
    } else if (cnfe1 != null && cnfe2 == null) {
      // Only the second try matched, return it.
      helper_cache.put(new HelperCacheKey(helper_type, seq1), c2);
      return c2;
    } else {
      // Neither try matched. Re-throw the exception generated by the first try.
      throw cnfe1;
    }
  }

  /**
   * Check the helpers currently stored in the helper cache to see if any of them can handle the
   * sequence we've just been given. This avoids pinging the belief network context to get a helper
   * list.
   */
  public static Class find_helper_class1(
      Vector seq, String helper_type, int[] max_class_score, int[] max_count_score)
      throws ClassNotFoundException {
    int[] class_score1 = new int[1], count_score1 = new int[1];
    max_class_score[0] = -1;
    max_count_score[0] = -1;
    Class cmax_score = null;

    for (Enumeration e = helper_cache.keys(); e.hasMoreElements(); ) {
      try {
        HelperCacheKey key = (HelperCacheKey) e.nextElement();
        if (!key.helper_type.equals(helper_type)) continue;
        Class c = (Class) helper_cache.get(key);
        SeqTriple[] sm = (SeqTriple[]) invoke_description(c);
        if (sm == null) continue; // apparently not a helper class
        if (MatchClassPattern.matches(sm, seq, class_score1, count_score1)) {
          if (class_score1[0] > max_class_score[0]
              || (class_score1[0] == max_class_score[0] && count_score1[0] > max_count_score[0])) {
            cmax_score = c;
            max_class_score[0] = class_score1[0];
            max_count_score[0] = count_score1[0];
          }
        }
      } catch (Exception e2) {
      } // eat it; stagger forward
    }

    if (Global.debug > 1)
      System.err.println(
          "PiHelperLoader.find_helper_class1: helper "
              + (cmax_score == null ? "is NOT" : "is")
              + " in cache.");
    if (cmax_score == null) // no luck; try to get a helper list from the bnc & plunge ahead
    return find_helper_class0(seq, helper_type, max_class_score, max_count_score);
    else // success!
    return cmax_score;
  }

  /**
   * Contact a belief network context, get the helper list, and search the list to see if there's a
   * helper which matches the type sequence specified. If there's more than one helper which
   * matches, find the ``best fit.''
   *
   * <p>The class and count scores of the best-fitting helper class are written into
   * <tt>max_class_score[0]</tt> and <tt>max_count_score[0]</tt>, respectively.
   */
  public static Class find_helper_class0(
      Vector seq, String helper_type, int[] max_class_score, int[] max_count_score)
      throws ClassNotFoundException {
    long t0 = System.currentTimeMillis();
    if (bnc != null) // make sure the reference is still alive
    try {
        bnc.get_name();
      } catch (RemoteException e) {
        bnc = null;
      }

    if (bnc == null) // need to locate a context
    {
      String cb = System.getProperty("java.rmi.server.codebase", "http://localhost");
      long tt0 = System.currentTimeMillis();
      try {
        bnc = BeliefNetworkContext.locate_context(new URL(cb).getHost());
      } catch (Exception e) {
        throw new ClassNotFoundException("nested: " + e);
      }
    }

    String[] helperlist;
    try {
      helperlist = bnc.get_helper_names(helper_type);
    } catch (RemoteException e) {
      throw new ClassNotFoundException("bnc.get_helper_names failed");
    }

    int[] class_score1 = new int[1], count_score1 = new int[1];
    max_class_score[0] = -1;
    max_count_score[0] = -1;
    Class cmax_score = null;

    for (int i = 0; i < helperlist.length; i++) {
      try {
        Class c = RMIClassLoader.loadClass(helperlist[i]);
        SeqTriple[] sm = (SeqTriple[]) invoke_description(c);
        if (sm == null) continue; // apparently not a helper class
        if (MatchClassPattern.matches(sm, seq, class_score1, count_score1)) {
          if (class_score1[0] > max_class_score[0]
              || (class_score1[0] == max_class_score[0] && count_score1[0] > max_count_score[0])) {
            cmax_score = c;
            max_class_score[0] = class_score1[0];
            max_count_score[0] = count_score1[0];
          }
        }
      } catch (Exception e2) {
        System.err.println("PiHelperLoader: attempt to load " + helperlist[i] + " failed; " + e2);
      }
    }

    if (cmax_score == null) {
      System.err.println("find_helper_class0: failed; helper list:");
      for (int i = 0; i < helperlist.length; i++) System.err.println("\t" + helperlist[i]);

      String s = "";
      for (Enumeration e = seq.elements(); e.hasMoreElements(); ) {
        try {
          Class c = (Class) e.nextElement();
          s += c.getName() + ",";
        } catch (NoSuchElementException ee) {
          s += "???" + ",";
        }
      }

      throw new ClassNotFoundException("no " + helper_type + " helper for sequence [" + s + "]");
    }

    // FOR NOW IGNORE THE POSSIBILITY OF TWO OR MORE MATCHES !!!
    return cmax_score;
  }

  public static Object invoke_description(Class c) {
    try {
      Field f = c.getField("description_array");
      return f.get(null);
    } catch (NoSuchFieldException e) {
    } // eat the exception; apparently c is not a helper
    catch (Exception e) {
    } // HMM, SHOULD WE TRY HARDER TO FIGURE OUT WHAT'S GOING ON HERE ???

    return null;
  }
}
示例#12
0
  /**
   * This method returns a <tt>Class</tt> for a helper which can handle the list of distributions
   * specified by <tt>seq1</tt>. We maintain a cache of recently-loaded helpers, so check the cache
   * before going to the trouble of searching for a helper. The cache is blown away every
   * <tt>HELPER_CACHE_REFRESH</tt> seconds.
   *
   * <p>If we can't find a helper in the cache, we must search through the list of available helpers
   * to find an appropriate one. First try to find helper using class sequence as specified by
   * <tt>seq</tt>. Whether or not that succeeds, promote any <tt>Gaussian</tt> in the sequence to
   * <tt>MixGaussians</tt>, and try again. If we get a better match on the second try, return the
   * helper thus found.
   */
  public static Class find_helper_class(Vector seq1, String helper_type)
      throws ClassNotFoundException {
    // Let's see if an appropriate helper is in the cache.
    // If the cache is too old, empty it and search for the helper anew.

    if (System.currentTimeMillis() - cache_timestamp > HELPER_CACHE_REFRESH) {
      helper_cache = new Hashtable();
      cache_timestamp = System.currentTimeMillis();
      // Go on and search for appropriate helper.
    } else {
      HelperCacheKey key = new HelperCacheKey(helper_type, seq1);
      Class helper_class = (Class) helper_cache.get(key);
      if (helper_class != null) {
        if (Global.debug > -1)
          System.err.println(
              "PiHelperLoader.find_helper_class: found helper class: "
                  + helper_class
                  + "; no need to search.");
        return helper_class;
      }
      // else no luck; we have to search for helper.
    }

    // Well, we didn't find a helper in the cache, so let's go to work.
    if (Global.debug > -1)
      System.err.println(
          "PiHelperLoader.find_helper_class: DID NOT FIND HELPER CLASS; NOW SEARCH.");

    Class c1 = null, c2 = null;
    ClassNotFoundException cnfe1 = null, cnfe2 = null;
    int[] class_score1 = new int[1], count_score1 = new int[1];
    int[] class_score2 = new int[1], count_score2 = new int[1];

    try {
      c1 = find_helper_class1(seq1, helper_type, class_score1, count_score1);
    } catch (ClassNotFoundException e) {
      cnfe1 = e;
    } // hang on, we may need to re-throw later.

    Class gaussian_class = Class.forName("riso.distributions.Gaussian");
    MixGaussians mog = new MixGaussians(1, 1);

    Vector seq2 = new Vector(seq1.size());
    for (int i = 0; i < seq1.size(); i++)
      if (gaussian_class.isAssignableFrom((Class) seq1.elementAt(i)))
        seq2.addElement(mog.getClass());
      else seq2.addElement(seq1.elementAt(i));

    try {
      c2 = find_helper_class1(seq2, helper_type, class_score2, count_score2);
    } catch (ClassNotFoundException e) {
      cnfe2 = e;
    }

    if (cnfe1 == null && cnfe2 == null) {
      // Both matched; see which one fits better.
      // Break ties in favor of the helper for non-promoted messages.

      if (class_score1[0] >= class_score2[0]
          || (class_score1[0] == class_score2[0] && count_score1[0] >= count_score2[0])) {
        if (Global.debug > 1)
          System.err.println(
              "\taccept helper " + c1 + " for non-promoted classes instead of " + c2);
        if (Global.debug > 1)
          System.err.println(
              "\t\t"
                  + class_score1[0]
                  + ", "
                  + class_score2[0]
                  + "; "
                  + count_score1[0]
                  + ", "
                  + count_score2[0]);
        helper_cache.put(new HelperCacheKey(helper_type, seq1), c1);
        return c1;
      } else {
        if (Global.debug > 1)
          System.err.println("\taccept helper " + c2 + " for promoted classes instead of " + c1);
        if (Global.debug > 1)
          System.err.println(
              "\t\t"
                  + class_score1[0]
                  + ", "
                  + class_score2[0]
                  + "; "
                  + count_score1[0]
                  + ", "
                  + count_score2[0]);
        helper_cache.put(new HelperCacheKey(helper_type, seq1), c2);
        return c2;
      }
    } else if (cnfe1 == null && cnfe2 != null) {
      // Only the first try matched, return it.
      helper_cache.put(new HelperCacheKey(helper_type, seq1), c1);
      return c1;
    } else if (cnfe1 != null && cnfe2 == null) {
      // Only the second try matched, return it.
      helper_cache.put(new HelperCacheKey(helper_type, seq1), c2);
      return c2;
    } else {
      // Neither try matched. Re-throw the exception generated by the first try.
      throw cnfe1;
    }
  }
示例#13
0
 public void exit() throws RemoteException {
   System.exit(0);
 }
示例#14
0
public class NotActivatableServerImpl extends UnicastRemoteObject
    implements NotActivatableInterface {

  private static final String PROG_NAME = "NotActivatableServerImpl";
  private static final String SERVER_OBJECT = "NotActivatableServer";
  private static final String CLASS_NAME = "activation.NotActivatableServerImpl";

  private static final String POLICY_FILE = "policy_file";

  private static final String USER_DIR = System.getProperty("user.dir").replace('\\', '/');

  private static final String CODE_LOCATION = "file:" + USER_DIR + "/";

  private static final MarshalledObject DATA = null;
  private static ActivationDesc ACTIVATION_DESC = null;

  public NotActivatableServerImpl() throws RemoteException {}

  public void ping() throws RemoteException {}

  public void exit() throws RemoteException {
    System.exit(0);
  }

  private static void setup() {

    try {

      NotActivatableInterface rsi; // Remote server interface

      System.setSecurityManager(new RMISecurityManager());

      rsi = (NotActivatableInterface) Activatable.register(ACTIVATION_DESC);
      System.out.println("Got stub for " + SERVER_OBJECT + " implementation");

      Naming.rebind(SERVER_OBJECT, rsi);
      System.out.println("Exported " + SERVER_OBJECT + " implementation");

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

  public static void main(String[] args) {

    try {
      Properties props = new Properties();
      props.setProperty("java.security.policy", POLICY_FILE);

      ActivationGroupDesc agd = new ActivationGroupDesc(props, null);

      ActivationGroupID agid = ActivationGroup.getSystem().registerGroup(agd);

      ACTIVATION_DESC = new ActivationDesc(agid, CLASS_NAME, CODE_LOCATION, DATA, false);
    } catch (Exception e) {
      System.err.println("Exception: " + e);
      e.printStackTrace();
    }

    setup();
  }
}
示例#15
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();
    }
  }
示例#16
0
  public static void main(String args[]) {

    sameGroup = true;

    RMID rmid = null;

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

    try {
      TestLibrary.suggestSecurityManager("java.lang.SecurityManager");

      registry = java.rmi.registry.LocateRegistry.createRegistry(TestLibrary.REGISTRY_PORT);

      // must run with java.lang.SecurityManager or the test
      // result will be nullified if running with a build where
      // 4180392 has not been fixed.
      String smClassName = System.getSecurityManager().getClass().getName();
      if (!smClassName.equals("java.lang.SecurityManager")) {
        TestLibrary.bomb("Test must run with java.lang.SecurityManager");
      }

      // start an rmid.
      RMID.removeLog();
      rmid = RMID.createRMID();
      rmid.start();

      // rmid.addOptions(new String[] {"-C-Djava.rmi.server.logCalls=true"});

      // Ensure that activation groups run with the correct
      // security manager.
      //
      Properties p = new Properties();
      p.put("java.security.policy", TestParams.defaultGroupPolicy);
      p.put("java.security.manager", "java.lang.SecurityManager");

      // This action causes the following classes to be created
      // in this VM (RMI must permit the creation of these classes):
      //
      // sun.rmi.server.Activation$ActivationSystemImpl_Stub
      // sun.rmi.server.Activation$ActivationMonitorImpl_Stub
      //
      System.err.println("Create activation group, in a new VM");
      ActivationGroupDesc groupDesc = new ActivationGroupDesc(p, null);
      ActivationSystem system = ActivationGroup.getSystem();
      ActivationGroupID groupID = system.registerGroup(groupDesc);

      System.err.println("register activatable");
      // Fix for: 4271615: make sure activation group runs in a new VM
      ActivationDesc desc = new ActivationDesc(groupID, "StubClassesPermitted", null, null);
      canCreateStubs = (CanCreateStubs) Activatable.register(desc);

      // ensure registry stub can be passed in a remote call
      System.err.println("getting the registry");
      registry = canCreateStubs.getRegistry();

      // make sure a client cant load just any sun.* class, just
      // as a sanity check, try to create a class we are not
      // allowed to access but which was passed in a remote call
      try {
        System.err.println("accessing forbidden class");
        Object secureRandom = canCreateStubs.getForbiddenClass();

        TestLibrary.bomb(
            "test allowed to access forbidden class," + " sun.security.provider.SecureRandom");
      } catch (java.security.AccessControlException e) {

        // Make sure we received a *local* AccessControlException
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(bout);
        e.printStackTrace(ps);
        ps.flush();
        String trace = new String(bout.toByteArray());
        if ((trace.indexOf("exceptionReceivedFromServer") >= 0) || trace.equals("")) {
          throw e;
        }
        System.err.println("received expected local access control exception");
      }

      // make sure that an ActivationGroupID can be passed in a
      // remote call; this is slightly more inclusive than
      // just passing a reference to the activation system
      System.err.println("returning group desc");
      canCreateStubs.returnGroupID();

      // Clean up object
      System.err.println("Deactivate object via method call");
      canCreateStubs.shutdown();

      System.err.println("\nsuccess: StubClassesPermitted test passed ");

    } catch (Exception e) {
      TestLibrary.bomb("\nfailure: unexpected exception ", e);
    } finally {
      try {
        Thread.sleep(4000);
      } catch (InterruptedException e) {
      }

      canCreateStubs = null;
      ActivationLibrary.rmidCleanup(rmid);
      System.err.println("rmid shut down");
    }
  }