JavaBeans Enterprise

Paso 7: Escribir el Cliente JavaBean Enterprise

Si hemos completado con éxito los pasos del 1 al 6, el DemoBean debería estar desplegado dentro del contenedor de JavaBeans Enterprise y estará listo para aceptar llamadas de un cliente a cualquiera de los métodos especificados en el interface remoto.

Escribir el Cliente

La escritura del cliente es otra de las partes del proceso donde tendremos que escribir algún código, aparte de la propia lógica de negocio del Bean JavaBean Enterprise.

El cliente de un JavaBean Enterprise puede ser una gran variedad de cosas: por ejemplo, un servelt, un applet, o quizás un programa C/C++. El ejemplo DemoClient.java es el cliente para el JavaBean Enterprise DemoBean, creado en los pasos anteriores. Las cosas más importantes a observar en este programa son:

Otra cosa a observar es que como hemos desplegado el Bean en diferentes servidores/contenedores, necesitaremos diferentes versiones del código del cliente. Las diferencias en este código no se espera que sean importantes, pero podrían crear problemas, como los strings correctos para la conexión inicial. Por ejemplo, consideremos el siguiente código, que configura el objeto Properties para que el Bea WebLogic recupere el objeto initialContext JNDI. Podría diferir del string Properties de Oracle para obtener el objeto initialContext.

    p.put(Context.INITIAL_CONTEXT_FACTORY,
    "weblogic.jndi.T3InitialContextFactory");
Hay una gran variedad de pequeños problemas que podrían requerir algún ajuste o recompilación del código del cliente, pero no se espera que se necesiten grandes cantidades de trabajo.

El siguiente cliente demuestra cómo localizar el JavaBean Enterprise y como invocar a su métodos remotos:

(Código fuente) de DemoClient.java

  /**
  * DemoClient -- demonstrates using a minimal 
  * Java application to talk to the DemoBean 
  * stateless session bean
  */
  
package ejb.demo;
  
import javax.ejb.*;
import javax.naming.*;
import java.rmi.*;
import java.util.Properties;
    
  /**
  * DemoClient demonstrates using a minimal stateless 
  * session bean.
  * Remember view session beans as an extension of your 
  * client running in the server.
  */
  
public class DemoClient {
  public static void main(String[] args) {
    System.out.println("\nBegin DemoClient...\n");
  
    parseArgs(args);
    try {
    // Create A DemoBean object, in the server
    // Note: the name of the class corresponds to the
    // JNDI property declared in the 
    // DeploymentDescriptor
    // From DeploymentDescriptor ...
    // beanHomeName demo.DemoHome
      Context ctx = getInitialContext();
      DemoHome dhome = (DemoHome) 
        ctx.lookup("demo.DemoHome");
  
   // Now you have a reference to the DemoHome object
   // factory use it to ask the container to creat an
   // instance of the Demo bean
     System.out.println("Creating Demo\n");
     Demo demo = dhome.create();
  
   // Here is the call that executes the method on the
   // server side object
     System.out.println("The result is "
       + demo.demoSelect());
  
  
    }
    catch (Exception e) {
      System.out.println(" => Error <=");
      e.printStackTrace();
    }
    System.out.println("\nEnd DemoClient...\n");
  }
  
  static void parseArgs(String args[]) {
    if ((args == null) || (args.length == 0))
      return;
    for (int i = 0; i < args.length; i++) {
      if (args[i].equals("-url"))
        url = args[++i];
      else if (args[i].equals("-user"))
        user = args[++i];
      else if (args[i].equals("-password"))
        password = args[++i];
    }
  }
  
  static String user = null;
  static String password = null;
  static String url = "t3://localhost:7001";
  
   /**
   * Gets an initial context.
   *
   * @return Context
   * @exception java.lang.Exception if there is
   * an error in getting a Context
   */
  static public Context getInitialContext() 
      throws Exception {
    Properties p = new Properties();
    p.put(Context.INITIAL_CONTEXT_FACTORY,
      "weblogic.jndi.T3InitialContextFactory");
    p.put(Context.PROVIDER_URL, url);
    if (user != null) {
      System.out.println ("user: " + user);
      p.put(Context.SECURITY_PRINCIPAL, user);
      if (password == null)
        password = "";
      p.put(Context.SECURITY_CREDENTIALS, password);
    }
    return new InitialContext(p);
  }
}

Ozito