Plug It In

Listing 1. The pluggable application client code in a class named Invoker is a traditional Java application that contains a main function.

import java.rmi.RemoteException;
import java.util.Properties;

import javax.ejb.CreateException;
import javax.naming.InitialContext;

import com.ibm.Reciprocate;
import com.ibm.ReciprocateHome;

public class Invoker {

  public static void main(String[] args) {
    InitialContext initialContext =
      null;

    // Get the parameter for providerURL from the 
    // command line properties
    String providerUrl =
      System
        .getProperties()
        .getProperty(
        "java.naming.provider.url");

    // Get the parameter for InitialContextFactory from 
    // the command line properties
    String namingFactory =
      System
        .getProperties()
        .getProperty(
        "java.naming.factory.initial");

    // Get the JNDI context for our EJB Server
    Properties properties =
      new Properties();

    // Supply the provider url of the server
    properties.put(
      javax
        .naming
        .Context
        .PROVIDER_URL,
      providerUrl);

    // Supply the initial context factory
    properties.put(
      javax
        .naming
        .Context
        .INITIAL_CONTEXT_FACTORY,
      namingFactory);

    // create the InitialContext.
    try {
      initialContext =
        new InitialContext(properties);
    } catch (
      javax
        .naming
        .NamingException namingEx) {
      namingEx.printStackTrace();
    }

    // perform the lookup.
    java.lang.Object objRef = null;
    try {

      // Obtain a reference to the ReciprocateHome
      objRef =
        initialContext.lookup(
          "cell/nodes/localhost/servers/server1/ejb/
          com/ibm/ReciprocateHome");
    } catch (
      javax
        .naming
        .NamingException namingEx) {
      namingEx.printStackTrace();
    }

    // Cast object returned by the JNDI lookup to the
    // appropriate datatype (Reciprocate Home)

    ReciprocateHome ejbHome =
      (ReciprocateHome) javax
        .rmi
        .PortableRemoteObject
        .narrow(
          objRef,
          ReciprocateHome
            .class);

    try {

      // Use the home interface to create a
      // new instance of the Reciprocate bean.

      Reciprocate reciprocateEJB =
        ejbHome.create();

      // Use the business method
      System.out.println("The reciprocal of 0.8 is: " + 
        reciprocateEJB
          .reciprocal(
          0.8F));
    } catch (RemoteException remoteException) {
      remoteException
        .printStackTrace();
    } catch (CreateException createException) {
      createException
        .printStackTrace();
    }

  }
}