Overview of Distributed Object Computing by fB7N0g

VIEWS: 4 PAGES: 51

									Distributed Callbacks (cont.);
 CORBA Common Services;
     Dynamic Interfaces

   DS 520 - Distributed System Frameworks
               Distributed Callbacks (cont.);
                CORBA Common Services;
                    Dynamic Interfaces
   Review & Continued from Last Time
           Distributed Callbacks


   Today
           Example: Callback Bank with Subscription Service
           Overview of CORBA Common Services
           CORBA Dynamic Interfaces




Distributed System Frameworks                                  2
                                 Distributed Callbacks
 Distributed callbacks break a synchronous call that returns some data
  into a pair of calls: a request and a response
       The request call is made by the client which (supply an object reference to accept a response
       The response call is made on this object reference by the server-side object implementation
       To allow the server-side object to call the client back, the client must host an object that
        implements an IDL defined “callback” interface; the reference of this client-side object is
        provided as an in parameter of the request call.


                                                               Client Object    delivers
      Note: The client creates an object
                                                      calls                     results
      that implements the callback
      interface; this could be done globally
      (one callback object that receives all       Client Proxy           Callback Object
      callbacks), or a separate callback
      object can be instantiated for each
                                                                request           response
      invocation.
                                                      Server
                                                              Object Implementation



 Distributed System Frameworks                                                                      3
                 Using Distributed Callbacks
 Define interfaces for the client and server
       For each method the client intends to make asynchronous, the client
        should define a callback object in OMG IDL.
       The callback should contain parameters for all of the return
        information required from the server. For increased performance,
        the client callback may be defined as a CORBA "oneway" operation.
       The conversion to oneway:
              "in" parameters should remain the same
              "inout" parameters should be converted to an "in" parameter and also added
               to the list of return information in the client callback
              "out" parameters should be removed from the OMG IDL interface and added
               to the list of parameters in the client callback
              if the operation has a return type, it should be replaced with a void and added
               as a parameter in the client callback interface

Distributed System Frameworks                                                                4
       The Distributed Bank Application with
               Subscription Service
        // Bank.idl

        module BankModule {

            interface Account {
              float balance();
                   string acctName();
                   string custName();
            };

            interface Callback {
                   oneway void update(in Account accounts);
            };

            interface AccountManager {
                   typedef sequence<Account> AccountArray;
                   void register(in Callback callback);
                   Account open(in string custName, in string acctName);
                   Account getAccount(in string custName, in string acctName);
                   AccountArray getAccounts();
            };

        };

Distributed System Frameworks                                                    5
               The Callback Implementation
               import org.omg.CORBA.*;
               import BankModule.*;

               public class CallbackImpl extends _CallbackImplBase {

                      private BankClient myApplet;

                      // constructor
                      CallbackImpl(BankClient client) {
                           super();
                           myApplet = client;
                           System.out.println("Client Callback Created");
                      }

                      public synchronized void update(Account account) {
                          myApplet.msgArea.setText("");
                                myApplet.msgArea.append(account.custName()+
                                         " has opened a "+ account.acctName()+" account.\n");
                      }
               }




Distributed System Frameworks                                                                   6
   Distributed
   Bank with
   Subscription
   Service: Client
   Interface




Distributed System Frameworks   7
                                 BankClient Applet
            import     java.awt.*;
            import     java.applet.*;
            import     java.awt.event.*;
            import     java.io.*;
            import     java.lang.String;
            import     BankModule.*;

            public class BankClient extends Applet implements ActionListener {
                      TextArea msgArea, listArea;
                      Button registerButton, newButton, balanceButton, refreshButton;
                      TextField custNameField, balanceField;
                      Label label1, label3, label4;
                      CheckboxGroup Group1;
                      Checkbox checking, savings;
                      AccountManager manager;

                           public void init() { // Set up the GUI (not shown)
                               // Initialize the ORB (using the Applet).
                               org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(this);
                               // Locate an account manager.
                               manager = AccountManagerHelper.bind(orb, "BankManager");
                           }

                           ...




Distributed System Frameworks                                                             8
                     BankClient Applet (Cont.)
             . . .
             // BankClient Continued

                            public synchronized void actionPerformed(ActionEvent event) {

                                if (event != null) {
                                       java.lang.Object src = event.getSource();

                                       if (src instanceof Button) {
                                               Button srcB = (Button) src;

                                               if (srcB == registerButton)
                                                 register();

                                               else if (srcB == newButton)
                                                 open();

                                               else if (srcB == balanceButton)
                                                 getBalance();

                                               else if (srcB == refreshButton)
                                                 refresh();
                                       }
                                }
                            }




Distributed System Frameworks                                                               9
                     BankClient Applet (Cont.)
              public void register() {

                                // Initialize the ORB (using the Applet).
                                org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(this);

                                // Create a callback object.
                                CallbackImpl callback = new CallbackImpl(this);
                                orb.connect(callback);

                                // Register callback with the Bank Manager.
                                manager.register((Callback) callback);
                                msgArea.append(" You are now subscribed to the"+
                                                    " Bank notification service.\n");

              }



              We don’t need a separate client thread to handle the callbacks from the server,
              since the ORB makes clients implicitly multi-threaded. In this case, Visibroker
              will use thread pooling by default for each request.



Distributed System Frameworks                                                                   10
                     BankClient Applet (Cont.)
  . . .
  // BankClient Continued

                  public void open() {
                            balanceField.setText("");
                            String custName = new String();
                            String acctName = new String();
                            custName = custNameField.getText();
                            Account account = null;
                            if (savings.getState())
                               acctName = savings.getLabel();
                            else
                               acctName = checking.getLabel();
                            if (custName != null && custName.length() > 0) {
                               // Check to see if the account already exists
                               account = manager.getAccount(custName, acctName);
                               if (account != null)
                                  msgArea.append("A "+acctName+" account for "
                                                           +custName+" already exists.\n");
                               else {
                                   // Request the account manager to open a named account.
                                   // Get the account name from the name text widget.
                                   account = manager.open(custName, acctName);
                                   msgArea.append(account.acctName()+ " has been created for "
                                      +account.custName()+" with a random balance.\n");
                               }
                            }
                  }


Distributed System Frameworks                                                                11
                           BankClient Applet (Cont.)
      public void getBalance() {
                balanceField.setText("");
                String custName = new String();
                String acctName = new String();
                custName = custNameField.getText();
                if (savings.getState())
                   acctName = savings.getLabel();
                else
                   acctName = checking.getLabel();
                if (custName != null && custName.length() > 0) {
                   // Set the balance text widget to the account's balance.
                   Account account = manager.getAccount(custName, acctName);
                   if (account != null)
                      balanceField.setText("$"+ Float.toString(account.balance()));
                   else {
                      msgArea.append("No "+acctName+" for "
                           +custName+" exists.\n"+"You must first open an account!\n");
                   }
                }
      }

      public void refresh() {
                listArea.setText("");
                Account[] accounts = manager.getAccounts();
                for (int i = 0; i < accounts.length; i++) {
                   listArea.append(accounts[i].custName()+"'s ”
                                        + accounts[i].acctName()+" \n");
                }
      }                                                 } // End of ClientApplet


Distributed System Frameworks                                                             12
            Account Class Implementation
              // AccountImpl.java

              import BankModule.*;
              import java.lang.String;

              public class AccountImpl extends _AccountImplBase {

                  private float balance;
                  private String custName;
                  private String acctName;

                  public AccountImpl(String custName, String acctName, float balance) {
                    this.balance = balance;
                    this.custName = custName;
                    this.acctName = acctName;
                  }

                  public float balance() {
                    return this.balance;
                  }

                  public String custName() {
                    return this.custName;
                  }

                  public String acctName() {
                    return this.acctName;
                  }

              }


Distributed System Frameworks                                                             13
       Account Manager Implementation
                   // AccountManagerImpl.java

                   import java.util.*;
                   import BankModule.*;
                   import java.lang.String;

                   public class AccountManagerImpl extends _AccountManagerImplBase {

                      int maxClients = 10;
                      private long counter;
                      private Dictionary _accounts = new Hashtable();
                      private Random _random = new Random();

                      public Callback[] clients = new Callback[maxClients];

                      public AccountManagerImpl(String name) {
                        super(name);
                        counter = 0;
                        for (int i=0; i < maxClients; i++) {
                            clients[i] = null;
                        }
                      }

                      public synchronized void register(Callback cbRef) {
                        System.out.println("Client "+ counter + "registered.\n");
                              clients[(int)counter++] = cbRef;
                      }


Distributed System Frameworks                                                          14
                AccountManagerImpl (Cont.)
                public synchronized Account open(String custName, String acctName) {

                     // Lookup the account in the account dictionary.
                     Account account = (Account) _accounts.get(custName+acctName);
                     // If there was no account in the dictionary, create one.
                     if(account == null) {
                       // Make up the account's balance, between 0 and 1000 dollars.
                       float balance = Math.abs(_random.nextInt()) % 100000 / 100f;
                       // Create the account implementation, given the balance.
                       account = new AccountImpl(custName, acctName, balance);
                       // Make the object available to the ORB.
                       _boa().obj_is_ready(account);
                       // Print out the new account.
                       System.out.println("Created "+custName+"'s "+
                                               acctName+"account: "+account);
                       // Save the account in the account dictionary.
                       _accounts.put(custName+acctName, account);

                        // Send callback to registered clients about the new account.
                        for (int i=0; i < maxClients; i++) {
                            if (clients[i] != null)
                               clients[i].update(account);
                            }
                        }
                     // Return the account.
                     return account;
                 }



Distributed System Frameworks                                                           15
                  AccountManagerImpl (Cont.)
            public synchronized Account getAccount(String custName,
                                                        String acctName) {
               // Lookup the account in the account dictionary.
               Account account = (Account) _accounts.get(custName+acctName);
               return account;
             }

              public synchronized Account[] getAccounts() {
                int i = 0;
                int size = _accounts.size();
                Account[] accounts = new Account[size];

                  Enumeration e = _accounts.elements();
                  while (e.hasMoreElements()) {
                         accounts[i] = (Account) (e.nextElement());
                         i++;
                  }
                  return accounts;
              }

          }




Distributed System Frameworks                                                  16
                                The Bank Server
            // Server.java

            import BankModule.*;

            public class Server {

                public static void main(String[] args) {
                  // Initialize the ORB.
                  org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args,null);
                  // Initialize the BOA.
                  org.omg.CORBA.BOA boa = orb.BOA_init();
                  // Create the account manager object.
                  AccountManager manager =
                    new AccountManagerImpl("BankManager");
                  // Export the newly create object.
                  boa.obj_is_ready(manager);
                  System.out.println(manager + " is ready.");
                  // Wait for incoming requests
                  boa.impl_is_ready();
                }

            }


Distributed System Frameworks                                                  17
                        Bank Example in Action




Distributed System Frameworks                    18
                        Bank Example in Action




Distributed System Frameworks                    19
                        Bank Example in Action




Distributed System Frameworks                    20
                        Bank Example in Action




Distributed System Frameworks                    21
                        Bank Example in Action




Distributed System Frameworks                    22
            Subscription Bank - POA Version
Changes to the Bank Client Applet:
. . .
import BankModule.*;
import org.omg.CORBA.*;
import org.omg.PortableServer.*;

public class BankClient extends Applet implements ActionListener {
    . . .
    AccountManager manager;
    Callback callback;

        public void init() { // Set up the GUI (not shown). . .

               try {
                  // Initialize the ORB (using the Applet).
                  ORB orb = ORB.init(this, null);

                   // Locate an account manager.
                   byte[] managerId = "BankManager".getBytes();
                   manager = AccountManagerHelper.bind(orb, "/bank_agent_poa", managerId);

                   // Create Callback Object and Register with POA
                   POA poa = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
                   org.omg.CORBA.Object obj = poa.servant_to_reference(new CallbackImpl(this));
                   callback = CallbackHelper.narrow(obj);
                   poa.the_POAManager().activate();
               }
               . . .
        }
. . .
 Distributed System Frameworks                                                                23
  The POA Bank Manager - The Server
// Server.java
import java.io.FileInputStream;
import java.util.Properties;
import org.omg.CORBA.*;
import org.omg.PortableServer.*;

public class Server {
  public static void main(String[] args){
    try {
      // Initialize the ORB.
      ORB orb = ORB.init(args, null);
      // get a reference to the root POA
      POA rootPOA =
        POAHelper.narrow(orb.resolve_initial_references("RootPOA"));

        // Create bankPOA with the right policies; for registering AccountManager
        Policy[] policies = new org.omg.CORBA.Policy[]
          { rootPOA.create_lifespan_policy(LifespanPolicyValue.PERSISTENT) };
        POA bankPOA =
          rootPOA.create_POA("bank_agent_poa",rootPOA.the_POAManager(), policies);

        // Create accountPOA with the right policies; for registering Accounts
        policies = new org.omg.CORBA.Policy[]
          { rootPOA.create_lifespan_policy(LifespanPolicyValue.TRANSIENT) };
        POA accountPOA =
          rootPOA.create_POA("account_agent_poa",
                                      rootPOA.the_POAManager(), policies);

        . . .

Distributed System Frameworks                                                        24
  The POA Bank Manager - The Server
   // … (Continued)

             // Create the servant
             AccountManagerImpl managerServant = new AccountManagerImpl();

             // Activate the servant with the ID on myPOA
             byte[] managerId = "BankManager".getBytes();
             bankPOA.activate_object_with_id(managerId, managerServant);

             // Activate the POA manager
             rootPOA.the_POAManager().activate();
             System.out.println("Bank Server is ready.");

             // Wait for incoming requests
             orb.run();
           } catch (Exception e) {
             e.printStackTrace();
           }
       }
   }




Distributed System Frameworks                                                25
               POA Bank - AccountManager
The only difference is in the open() method:
// AccountManagerImpl.java
import org.omg.PortableServer.*;
import BankModule.*;

public class AccountManagerImpl extends AccountManagerPOA {
   . . .
   public synchronized Account open(String custName, String acctName) {

      // Lookup the account in the account dictionary.
      Account account = (Account) _accounts.get(custName+acctName);
      // If there was no account in the dictionary, create one.
      if(account == null) {
         // Make up the account's balance, between 0 and 1000 dollars.
         float balance = Math.abs(_random.nextInt()) % 100000 / 100f;
         // Create the account implementation, given the balance.
         AccountImpl accountServant = new AccountImpl(custName, acctName, balance);
         try {
             // Activate it on the transient POA
             POA rootPOA = POAHelper.narrow(_orb().resolve_initial_references("RootPOA"));
             POA acctPOA = rootPOA.find_POA("account_agent_poa", true);
             acctPOA.activate_object(accountServant);
             account =
                 BankModule.AccountHelper.narrow(acctPOA.servant_to_reference(accountServant));
         }
         catch (Exception e) { e.printStackTrace();}
      . . .
// … rest is same as before
Distributed System Frameworks                                                                 26
                   CORBA Services Overview
 Concurrency Control Service
        Provides an interface for managing concurrency in shared CORBA objects; this
         is done through the use of locks.
 Event Service
        The Event Service provides a mechanism through which CORBA objects can
         send and receive events. Some features are:
               Reliable delivery, which ensures that an event will reach its destination(s)
               Support for push and pull models of event delivery
               Anonymous messaging, when suppliers need not know the identities of event
                consumers, or vice versa
               Event channels, a mechanism similar to publish/subscribe, through which consumers
                can subscribe to certain types of events
 Life Cycle Service
        Offers facilities for creating, deleting, copying, and moving CORBA objects.
        Also supports the notion of an object factory (a CORBA object that creates other
         CORBA objects).

Distributed System Frameworks                                                                       27
      CORBA Services Overview (cont.)
 Externalization Service
        Provides interfaces for externalizing (serializing) and internalizing objects.
        When an object is externalized, it can be internalized within the same process or
         a different process.
        Objects can be externalized into a portable file format (defined with the
         Externalization Service Specification).
        One possible application: a pass-by-value mechanism for CORBA objects.


 Naming Service
        The Naming Service enables CORBA objects to register and be located by name.
        Uses the notion of a naming context, which contains a set of unique names.
        Also supports a federated architecture: name servers can be distributed across
         the network and work in conjunction with each other.
        Visibroker’s OSAgent along with the “bind” mechanism, can be thought of as a
         miniature Naming Service, but it is not portable or scalable.


Distributed System Frameworks                                                            28
      CORBA Services Overview (cont.)
 Licensing Service
        Enables the provider to define policies that control the use of services.
        Supports three types of licensing policies:
               Time enables a license to set a start date, expiration date, and duration.
               Value mapping enables licensing based on units (resource usage metering, number of
                concurrent users, and so on).
               Consumer assigns services for use by a particular user or machine.
        Potentially useful for pay-as-you-go or rentable software when they are realized.


 Persistent Object Service
        Provides a set of interfaces for managing the persistence of objects.
        Typically, implementations for this service are provided by database vendors.
        Persistent objects are objects whose lifetime can transcend the lifetime of any one
         application; while not in use, the object resides in a persistent store, such as a
         database or a flat file; the object can then be retrieved, or resurrected, when
         needed.

Distributed System Frameworks                                                                    29
      CORBA Services Overview (cont.)
 Object Trader Service
        Like the Naming Service, enables other objects to locate CORBA objects: rather
         than use a name to locate an object, a client object looks for services based on
         operation names, parameters, and result types.
        Trader Service Versus Naming Service
               the Naming Service can be thought of as a “white pages”, in which you look up a
                particular service if you know its exact name
               the Trader Service is a “yellow pages” service, in which you locate a service, based on
                its location, function, or even name.

 Query Service
        Supports the use of queries on objects.
        Queries can contain predicates that specify objects to act on, based on attribute
         values. The service also supports object indexing as well as nested queries.
        Query capability provides database-like semantics to CORBA objects: just as an
         application can perform queries on tables and rows in a relational database, the
         Query Service allows an application to perform queries on CORBA objects.

Distributed System Frameworks                                                                        30
      CORBA Services Overview (cont.)
 Property Service
        Enables objects to define sets of properties, which are name/value pairs: the
         name in a pair is a CORBA string; the value is a CORBA any.
        Access to properties can be restricted, e.g., a property can be read-only or fixed.
        The idea of using properties to describe objects is similar to the use of object
         models such as JavaBeans.


 Relationship Service
        Enables the representation of relationships between objects.
        Provides for full constraint checking of relationship type and cardinality (one-to-
         many, one-to-one, etc.)
        Can work in conjunction with the Life Cycle Service to copy, move, and remove
         related objects.




Distributed System Frameworks                                                                  31
      CORBA Services Overview (cont.)
 Time Service
        The Time Service enables a user to obtain the current time; it can determine
         event ordering and can generate events based on timers.


 Transaction Service
        The Transaction Service provides the interfaces to support transaction
         capabilities.
        It supports flat and nested transaction models as well as external TP monitors.
        Transaction services can also interoperate with each other.
        Transaction semantics are an integral part of almost every non-trivial application
               Example: in a banking application, to coordinate a transfer between accounts at
                different banks, a transaction should be initiated that would cause the banks involved
                either to both commit the transaction or to both abort the transaction; otherwise,
                inconsistent data (such as account balances) would result.




Distributed System Frameworks                                                                            32
      CORBA Services Overview (cont.)
 Security Service
        The Security Service specifies the interfaces for security features.
        Some features are:
               Identification and authentication of users, which verify that a user is who he or she
                claims to be.
               Authorization and access control determine which users are enabled access to which
                services or objects.
               Security auditing, which provides records of users' actions.
               Security of communication, which includes authentication of users to services (and
                vice versa), integrity protection, and confidentiality protection.
               Non-repudiation, which provides capabilities similar to those offered by digital
                signatures; that is, the origin of data or the receipt of data can be proven irrefutably.
               Administration of various security policies.




Distributed System Frameworks                                                                               33
                                Dynamic Requests
  The Dynamic Invocation Interface (DII) allows clients to
   dynamically:
         discover objects’ interfaces;
         create requests;
         invoke requests;
         receive responses.
  Major features of Dynamic Invocation Interface:
         requests appear as objects themselves;
         requests are reusable;
         invocation may be synchronous or asynchronous
         requests may be generated dynamically, statically or in combination.
  Integrated Interface Repository can provide:
         Dynamic client access to interface definitions to construct a request.
         Dynamic type-checking of request signatures.
         ORB-to-ORB interoperability.

Distributed System Frameworks                                                      34
                                Request Components
  Object reference
         identifies the target object
  Operation
         identifies which operation to perform
  Parameters
         the input, output and in-out parameters defined for the operation
         may be specified individually or as a list
  Context object
         the context within which the request is to be performed
  Results
         the result values returned by the operation
  Environment
         the execution environment and exception information of the operation
  Request handle
         the identifier for this instance of the request
Distributed System Frameworks                                                    35
                   Making a Dynamic Method Call
 Assuming that a reference to the remote object has been obtained, some of
  these steps must be followed to invoke a remote operation on the object:

       Use the get_interface() method on the object; this returns a reference to an
        InterfaceDef object; various methods can be called on this new object, for
        example:
              describe_interface() method will return a reference to
               org.omg.CORBA.InterfaceDefPackage.FullInterfaceDescription,
               which in turn contains the names of operations, etc.
              lookup_name() can be used to find the interface to specific operations; this is usually
               used in conjunction with describe() to obtain complete IDL definition for the
               operation.


       Create an argument list for the method parameters; this is done by creating a Name-
        Value list using an NVList object which has operations for creating and
        manipulating the name-value pairs.


 Distributed System Frameworks                                                                     36
       Making a Dynamic Method Call (Cont.)
      Construct the request object: this can be done in two ways:
             calling the create_request() method with parameters that include the name of the
              operation, the NVList, and a reference to the return value of the operation;
             or, we can use the _request() method to create a Request object, and then use
              combinations of add_arg(), add_value(), etc. to populate the request object.


      Finally, we can invoke the request:
             invoke() operation sends the request and waits for the response
             send_deferred() sends the requests and returns control to client; client can then
              use poll_response() and get_response() methods to obtain the results
             send_oneway() is used if no response is required.




Distributed System Frameworks                                                                     37
   Example: Building a Dynamic Request
    public static org.omg.CORBA.Request buildRequest(Counter.Count counter)
      {
        //get interface for Count object
        org.omg.CORBA.InterfaceDef CountInterface = counter._get_interface();

           // describe interface for Count object
           org.omg.CORBA.InterfaceDefPackage.FullInterfaceDescription intDesc =
           CountInterface.describe_interface();

           if (intDesc.operations[0].name.compareTo("increment") == 0)
           {
             //create request object for dynamic increment
             org.omg.CORBA.Request request = counter._request("increment");
             // initialize result value
             request.result().value().insert_long(0);
             return request;
           } else
             System.out.println("Unknown method");
           return null;
       }


             The client can then use     request = buildRequest(counter);
             this to invoke a request:    . . .
                                         request.invoke();

Distributed System Frameworks                                                     38
                                Interface Repository
  An interface repository (IR) is like a database of CORBA object
   interface meta-information
         an IR's data describes interfaces (types); there may or may not be instances
          satisfying the interfaces in an IR
         The information in an IR is equivalent to the information in an IDL file (or
          files), but it is represented in a way that is easier for clients to use
         an IR enables clients to learn about or update interface descriptions at runtime
         An interface repository contains hierarchies of objects whose methods divulge
          information about interfaces

  The Count Example:
         must start IR and add Count IDL to the repository

                           Prompt> start irep myIR myIR.dat
                           Prompt> idl2java -replace count.idl

         the replace method allows any interface definition already stored in IR to be
          overridden with the new one
Distributed System Frameworks                                                                39
                      What Does an IR Contain
  Psuedo-objects represent constructs in the IDL
         IR may contain ModuleDef objects, which can contain InterfaceDef objects,
          which can contain OperationDef objects
         from an IR ModuleDef, we can learn what InterfaceDefs it contains; also, given
          an InterfaceDef you can learn what ModuleDef it is contained in
         All other IDL constructs--including exceptions, attributes, and parameters--can be
          represented in an interface repository
  IR Contains TypeCodes
         Typecodes are not explicitly listed in IDL files, but are automatically derived from the
          types that are defined or declared in IDL files
         Typecodes are used to encode and decode instances of the CORBA any type
         recall that any type has methods for constructing an any associated with a particular
          type, and methods for extracting the type from any objects
  Repository Ids
         a character string that uniquely identifies an IRObject
         contains three components, separated by ":” delimiters, "IDL:”; a sequence of identifiers
          separated by "/" characters; and the version number
         e.g., "IDL:Bank/AccountManager:1.0"

Distributed System Frameworks                                                                        40
              Example: Dynamic Count Client
                class CountClientDii
                { public static void main(String args[]) {
                    boolean loop_all = false;
                    long startTime, stopTime;
                    org.omg.CORBA.Request request;

                         // Initialize the ORB and obtain reference to Count object.
                         . . .
                         counter.sum((int)0);
                         if ((args.length != 0) &&
                             (args[0].compareTo("loop_all") == 0))
                            loop_all = true;
                         if (loop_all) {
                           System.out.println("Starting IR lookup + invoke test");
                           // Calculate Start time
                           startTime = System.currentTimeMillis();
                           for (int i = 0 ; i < 1000 ; i++ )
                             { request = buildRequest(counter);
                               request.invoke(); }
                         } else {
                             System.out.println("Starting invoke only test");
                             request = buildRequest(counter);
                             startTime = System.currentTimeMillis();
                             for (int i = 0 ; i < 1000 ; i++ )
                               { request.invoke();
                               }
                         }
                         // Calculate stop time; print out statistics, etc. ...


Distributed System Frameworks                                                          41
                            Overhead of Using DII
  Trade-off between flexibility and performance
         biggest overhead is associated with building a request
         in Count example, the overhead factor was 15 to 1
         there is also the overhead of having to write more complex code


  DII Versus Alternatives
                    Usage Pattern                         Which Method to Use
       Client invokes objects frequently        Static Precompiled stubs
       and server objects change infrequently
       Server objects invoked infrequently      Dynamic Invocation
       Client discovers objects at run-time     Dynamic Invocation
       Client runs within browser               Static Stubs with Client Applet




Distributed System Frameworks                                                     42
                  Example: Dynamic Bank Client
 // Client.java
 public class Client {
     public static void main(String[] args) {
       if(args.length != 2) {
         System.out.println("Usage: vbj Client <manager-name> <account-name>\n");
         return;
       }
       String managerName = args[0];
       String accountName = args[1];
       org.omg.CORBA.Object accountManager, account;
       org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args,null);
         ...
         accountManager = orb.bind("IDL:Bank/AccountManager:1.0", managerName, null, null);
         org.omg.CORBA.Request request = accountManager._request("open");
         request.add_in_arg().insert_string(accountName);
         request.set_return_type(orb.get_primitive_tc( org.omg.CORBA.TCKind.tk_objref) );
         request.invoke();
         account = request.result().value().extract_Object();
         ...
         org.omg.CORBA.Request request = account._request("balance");
         request.set_return_type(orb.get_primitive_tc( org.omg.CORBA.TCKind.tk_float) );
         request.invoke();
         float balance = request.result().value().extract_float();
         System.out.println
             ("The balance in " + accountName + "'s account is $" + balance);
     }
 }


Distributed System Frameworks                                                            43
                                Dynamic Skeletons
 The Dynamic Skeleton Interface (DSI)
      normally, an object implementation is derived from a skeleton class generated by the
       idl2java compiler
      DSI allows an object to register itself with the ORB, receive operation requests from a
       client, process the requests, and return the results to the client without inheriting from a
       skeleton class
 Using DSI
      Instead of extending a skeleton object, design your object implementation so that it extends
       the org.omg.CORBA.DynamicImplementation abstract class
      Declare and implement the invoke method, which the ORB will use to dispatch client
       requests to your object
      Register your object implementation with the BOA in the normal way, using the
       boa.obj_is_ready method
 Note:
      The ORB presents a client operation request to a DSI object implementation by using the
       object's invoke method and passing a ServerRequest object
      From the perspective of a client application, an object implemented with DSI behaves just
       like any other ORB object

Distributed System Frameworks                                                                         44
               Dynamic Skeletons: Bank Server
                      // Server.java
                      import java.util.*;
                      class Account extends org.omg.CORBA.DynamicImplementation {
                        Account(float balance) {
                          super(null, "IDL:Bank/Account:1.0");
                          _balance = balance;
                        }
                        public void invoke(org.omg.CORBA.ServerRequest request) {
                          // make sure the operation name is correct
                          if(!request.op_name().equals("balance")) {
                            throw new org.omg.CORBA.BAD_OPERATION();
                          }
                          // no parameters, so simply invoke the balance operation
                          float balance = this.balance();
                          // create an any for the result
                          org.omg.CORBA.Any balanceAny = _orb().create_any();
                          // put in the balance,
                          balanceAny.insert_float(balance);
                          // set the request's result
                          request.result(balanceAny);
                        }
                        float balance() {
                          return _balance;
                        }
                        private float _balance;
                      }
                      ...


Distributed System Frameworks                                                        45
                     Dynamic Bank Server (Cont.)
          class AccountManager extends org.omg.CORBA.DynamicImplementation {
            AccountManager(String name) {
              super(name, "IDL:Bank/AccountManager:1.0");
            }
            public void invoke(org.omg.CORBA.ServerRequest request) {
              // make sure the operation name is correct
              if(!request.op_name().equals("open")) {
                throw new org.omg.CORBA.BAD_OPERATION(); }
              // create an empty parameter list
              org.omg.CORBA.NVList params = _orb().create_list(0);
              // create an any for the name parameter
              org.omg.CORBA.Any nameAny = _orb().create_any();
              // set the any's type to be a string
              nameAny.type(_orb().get_primitive_tc( org.omg.CORBA.TCKind.tk_string) );
              // add "in" the parameter to the parameter list
              params.add_value("name", nameAny, org.omg.CORBA.ARG_IN.value);
              // obtains the params from the request
              request.params(params);
              // get the name parameter from the any
              String name = nameAny.extract_string();
              // invoke the open operation
              Account account = this.open(name);
              // create an any for the result
              org.omg.CORBA.Any accountAny = _orb().create_any();
              // put in the new account object
              accountAny.insert_Object(account);
              // set the request's result
              request.result(accountAny);
            }

Distributed System Frameworks                                                            46
                     Dynamic Bank Server (Cont.)
              // class AccountManager (Continued)

              // Note that the open method looks exactly as before

                public synchronized Account open(String name) {
                   // Lookup the account in the account dictionary.
                   Account account = (Account) _accounts.get(name);
                   if(account == null) {
                     // Create a new account with between 0 and 1000 dollars.
                     float balance = Math.abs(_random.nextInt()) % 100000 / 100f;
                     account = new Account(balance);
                     // Export the new object reference.
                     _boa().obj_is_ready(account);
                     System.out.println("Created " + name + "'s account: " + account);
                     // Save the account in the account dictionary.
                     _accounts.put(name, account);
                   }
                   // Return the account.
                   return account;
                 }
                 private Dictionary _accounts = new Hashtable();
                 private Random _random = new Random();
              }
              …
              }




Distributed System Frameworks                                                            47
                                Project Phase 2
  Multiple active auctions must be supported
          each with one seller and potentially many bidders (need an object factory
           “AuctionManager” to create multiple auctions dynamically)
          a given user may be playing seller and bidder roles in separate auctions
  Client must be an applet
          should support both bidder and seller interfaces
          could be a single applet or multiple applets in the same html page
  Callbacks
          Changes in auction status must be delivered to the user interface without the
           need for user initiative
  Registration
          users must “register” or log in before they can use the system (a user who has
           not logged in cannot invoke any functionality other than the login operation)
          each user may be logged at most once at any given time (at most one display
           needs to be updated for any given user)

Distributed System Frameworks                                                               48
                                  Project Phase 2
                                        Each user of the system is identified by a login name and a
                                        password. Login names are unique. When logged in, their
                                        displays will be automatically updated as described in the
              Registration              Auction_status use case.
                                        Operations supported:
                                            Log in new user
                                            Log in existing user
                                            Log user out
                                            Automatic user logout


                                Each registered user will be presented with two lists of current auctions
                                       1. auctions in which the user is in the Seller role
User                                   2. auctions on which the user could potentially bid
                                • For each auction, user can view the item desc. & current price. The
             Auction              user can manually update the display at any time, retrieving current
              Status              data on all auctions.
                                • For auctions in which the user is in the Seller role, the current price
                                  will be automatically updated.
                                • For auctions in which the user is in the Bidder role and has the
                                  current high bid, the Bidder will be automatically notified if the bid is
                                  accepted by the Seller, or if the bid is superceded by a higher bid.

Distributed System Frameworks                                                                             49
                                Midterm Exam
  Overview of Distributed Object Computing
          Why use DOC
          Requirements of DOC systems
          General architecture for DOC systems
  CORBA and OMG
          Background on CORBA and OMG
          Basic CORBA interfaces and services
          Components of the CORBA framework
          Notion of “Object Web” and long-term vision of OMG
  Basic CORBA
          IDL to Java Mapping
          Roles of generated classes and their relationships
          Semantics of remote calls
          Use of complex types and Semantics of parameter passing
          Exceptions and exception handling
          Steps in development and deployment of CORBA applications
Distributed System Frameworks                                          50
                                  Midterm Exam
  CORBA Design Patterns
          Object factories
          ORBlets and use of applets as clients (and servers)
          Distributed Callbacks
  Other Material
          Basic understanding of CORBA Common Services
          Basics of Dynamic Interfaces
  Relevant Text Material
          Orfali & Harkey:
                 Chapters 1-4 (Basics)
                 Chapter 5 (Applets)
                 Chapter 9 (Callbacks - ignore details of Naming Service)
          Brose, Vogel & Duddy
                 Chapters 1-2, 4 (Basics), Chapter 5 (IDL to Java mapping - for reference)
                 Chapter 8 (Building Applications - ignore details of Naming Service)
                 Section 15.1 (Scalability Issues, Threading Models, Callbacks)

Distributed System Frameworks                                                                 51

								
To top