Java Beans by pengxiang


									  Presentation Outline of Commercial Systems

• Bahman
   Part A: Java Beans
   Part B: Enterprise Java Beans

• John

• Andrew
Java Beans   &   Enterprise Java Beans

      Component-Based Design

           Bahman Kalali
      Computer Systems Group

                              Spring 2002
                     Outline (Part A)

   Introduction to JavaBeans
   A Bean's Public Interface
   Bean Properties
   Bean Events
   Bean Methods
   Reflection API
   Bean Distribution
   Summary

Java Bean is a reusable platform-neutral software component that
can be visually manipulated in a visual application builder tool.

This definition has two distinct parts:

       A bean is a software component.
       A bean can be visually manipulated in a tool.
Construction from Components
          A Bean's Public Interface
   Properties
   Methods
   Events
                       Bean’s Properties

At the source code level, a bean's property is nothing more than a
private attribute of a class that is supported by public getter and/or setter

Type of Properties
      Simple
      Boolean
      Index
      Bound
      Constrained
Sample Account Property Balance
                 Exposing Simple Properties
   Naming convention to expose a simple property:

    public void setXxx (<type> arg)
    public <type> getXxx()

   Example for Account's balance property:

    public void setBalance( int amount )
    public int getBalance()

By applying a naming pattern to the set/get Balance methods above,
the visual builder tool will expose a read/write "balance" property that
has the type int.
               Exposing Boolean Properties
   Naming convention to expose a boolean property:

    public void setXxx (boolean arg)
    public boolean isXxx()

   Example for overdrawn property:

    public void setOverdrawn( boolean overdrawn )
    public boolean isOverdrawn()

Boolean properties may be exposed by using the isXxx naming convention.
           Exposing Indexed Properties

   Naming convention to expose an indexed property:

    public void setXxx ( <type> [] arg)
    public <type>[] getXxx()
    public void setXxx (int index, <type> arg)
    public <type> getXxx (int index)

   Example for an Account owner property:

    public void setOwner(String[] owners)
    public String getOwner()
    public void setOwner(int index, String owner)
    public String getOwner(int index)
          Account Bean with a balance Property
// Account Class - non visual Java Bean

 public class Account extends Object {
   int balance = 0;
   public Account() { // constructor }
   public void setBalance ( int newBalance ) { balance = newBalance; }
   public int getBalance() { return balance; }
   public void deposit ( int pennies ) { setBalance ( getBalance() + pennies ); }
   public void withdraw ( int pennies ) { setBalance ( getBalance() - pennies ); }

// end of class Account
                          Bound Properties

•   A Bean properties changes, another Bean may want to be notified of the
    change and react to the change.

•    Whenever a bound properties changes, notification of change is sent to
    interested listeners.

•   It is up to the source Bean to keep track of listeners.
       Account Bean with a Balance Property

• PropertyChangeSupport object constructs a PropertyChangeEvent object
  and passes it to the Listener chain.

• Listener objects will interrogate the property that is changing and process
                  Constrained Properties

1) setBalance called
2) Account notifies the VetoableChangeListeners
   of pending change request
3) Listeners can optionally throw exception
4) balance is updated if no exception is thrown
                       Bean Custom Events

•   Bound and constrained properties fire events when properties are changed.

•   Java Beans can also fire other kind of events (custom events).

•   The application developer can wire up to these events without writing code.
        Exposing Bean Custom Events
   Naming conventions are used

public void addXxxListener ( XxxListener listener)
public void removeXxxListener ( XxxListener listener)

   Example for exposing an OverdrawEvent

public void addOverdrawListener ( OverdrawListener listener)
public void removeOverdrawListener ( OverdrawListener listener)

   In addition to these methods, the source object also provides:

1) OverdrawEvent class
2) OverdrawListener interface
3) code to fire the event
4) code to manage the listener chain
                            Bean Methods

•   To expose a method in the Bean’s public interface, simply make the method
      How does a visual Builder tool determines
            a Bean’s public interface?

•    At development time the visual builder tool is able to
    interrogate beans, and figure out what's in there.

•   How does it do that?  The Java Reflection API
                        Reflection API
In Java 1.1 and higher, anyone can inspect a class using the
Reflection API

 Account account = new Account();
 Class classObject = account.getClass();
 Method [] methodsArray = classObject.getDeclaredMethods();

methodsArray now contains an array of Method objects for the class

A method objects contain information about a method's:

       Method name
       Return type
       Argument list
       Access type
                           Bean Distribution

   Beans can be distributed in a JAR file (basically a ZIP file).

   The JAR utility that comes with the JDK can be used to create JAR files.

   JAR files can contain any type of file, not just Java bytecodes,
     image,sound and text.

   A manifest file describes the contents of the JAR.
   Beans
        are software components
        are usable by programming tools
        are packaged in JAR files
        use a standard naming convention
        have a public interface

   A Bean's Public Interface composed of:
        Properties
            Simple
            Indexed
            Boolean
            Bound
            Constrained

        Events
            Signalled by changing properties
            Signalled for custom state change

        Methods
           Default is any public method
                  Outline (Part B)
   Introduction to Enterprise Java Beans
   Three-Tiered Architecture
   JBoss Application Server
   Enterprise Java Beans
   Accessing a Business Method
   Case Study: Distributed Shoe Web Application
   Demonstration of application lifecycle
   Summary
   EJB specification defines an architecture for the development
    and deployment of transactional, distributed object applications-
    based, server-side software components.

   Case Study
        Shoe Retailer Company
                                  25   Running Montreal Nike        50

                                  id    name    branch brand


             Three-Tiered Architecture
   Client Layer

   Presentation Layer

   Business Logic Layer

   Data Layer
                   Logical Layers           Typical Web

Upper Tier            Client Layer            Browser

                                     Java Beans
                    Presentation              Web Server
Middle Tier
                   Business Logic    EJB
                                              Application Server

Lower Tier           Data Layer               Database
                  JBoss Application Server

   JBoss is an application server written in Java that can host EJB
   JBoss provides a container.
   An EJB container implicitly manages resources for EJB:
        Threads
        Socket
        Database connections
        Remote accessibility
        Mutliclient support
        Persistence management
                  Enterprise Java Beans
Bean Types
      Session Beans           =>        models business processes
      Entity Beans            =>        models business data

              Web Server
                   JSP/Java Beans                 Servlet        Layer

          Application Server

                     EJB Container
                                Session Bean                 Business Logic
                                    Entity Bean

              Enterprise Java Beans (contd.)
                                                           JBoss Application Server
                 Home                                               EJB Container
               Interface              EJB
                                  Home Object
  Client                              Object               Bean Class

Enterprise Bean Components composed of:

      (1) Bean Class ( i.e.
      (5) Home Interface ( i.e.
      (3) Remote Interface ( i.e.
      (2) EJB Object
      (4) EJB Home Object( Responsibility: Create, Find, Remove EJB object)
      (6) Deployment Descriptor( i.e ejb-jar.xml)
              Accessing a Business Method
         Retrieval of the Home object reference and generation of
         remote EJB object reference.

                       5: Return EJB       object reference

                              3: Request new
         Client Code                                          EJB Container
                              EJB object
1: Retrieve
Home Object
reference                                      Home Object
                                     Home Interface      4: Create EJB object
                       2: Return Home
                       Object reference                                   Enterprise Bean

                                                  EJB Object
                                     Remote Interface

          Directory Service
       Accessing a Business Method (cont’d.)
      Handling a client request to a business method.

                                                       EJB Container

                            Home Interface
    Client Code
                                       Home Object
                      4: Return
                    value to client                               3:Method Returns

      1:Call a Method                                                   Enterprise Bean

                                          EJB Object

                               Remote Interface        2: Acquire a Bean, and delegate
                                                           the method to the Bean

       Shoe Distributed Web Application
                                                        Web Browser
 Client Layer

                                                           JSP Pages
                                     Java Bean
                                                     Servlet Container

                                                      Tomcat Web Server

                                   Session Bean
Business Logic
                                     Entity Bean
                                                        EJB Container

                   Hypersonic database
  Data Layer
                                                    JBoss Application Server
            Demonstration of application lifecycle
           Build
           Package
                                                  shoe.jar                                              shoe.war

cs854-ApplicationServer                                      cs854-WebServer
                             Shoe.class                                  WEB-INF
                             ShoeBean.class                                        classes
           shoecollection                                            header.html
                             ShoeCollection.class                                            JspShoeBrowse.class
                             ShoeCollectionHome.class                search.jsp        lib
                     utils                                           browse.jsp    web.xml   shoe.jar
                             ShoeExistsException.class               mext.jsp
                             ejb-jar.xml                             prev.jsp

           Deploy
           Run


               CORBA Key Concepts

• Com+mon Object Request Broker Architecture

• Location Transparency

• Objects

• Portable

• Standard
                 Simplified Architecture

• Interface Definition Language(IDL)

• Application Programming Interface(API)

• Object Request Broker(ORB)
            CORBA Architecture
                                           Object Implementation

   Dyn.         IDL            ORB              IDL          Object
   Inter-       Stub           Interface        Skeleton     Adapter
Object Services: naming, events, life cycle, persistence, transactions,
concurrency, relationships, externalization, object licensing,
properties, object query.

    OS Kernel                                         OS Kernel
    IDL Interface for Quoter
interface Stock {
     double price ();

        readonly attribute string symbol;
        readonly attribute string full_name;

interface Stock_Factory {
    Stock get_stock (in string stock_symbol)
      raises (Invalid_Stock_Symbol);
     Client - Manage ORB in Stock Quoter

In client.cpp:

int main (int argc, char* argv[])
  try {
    // First initialize the ORB, that will remove some arguments...
    CORBA::ORB_var orb =
      CORBA::ORB_init (argc, argv,
                       "" /* the ORB name, it can be anything! */);
    // Get Reference to desired object
    // call methods to access object
    orb->destroy ();
  catch (CORBA::Exception &ex) {
    std::cerr << "CORBA exception raised!" << std::endl;
  return 0;
      Client - Get Quoter
      Object R
In client.cpp:

#include "QuoterC.h”

CORBA::Object_var factory_object = orb->string_to_object(argv[1]);

    Quoter::Stock_Factory_var factory =
          Quoter::Stock_Factory::_narrow ( ());

for (int i = 2; i != argc; ++i)
           try {
           // Get the stock object
           Quoter::Stock_var stock = factory->get_stock (argv[i]);
      Implement Get_Stock
      Method                                                   Stock_

In stock_factory_i.cpp

// Return Object Reference
Quoter::Stock_ptr Quoter_Stock_Factory_i::get_stock
                                         (const char *symbol)
       throw (Quoter::Invalid_Stock_Symbol)
       if (strcmp (symbol, "RHAT") == 0)
              { return this->rhat_._this(); }
       else if (strcmp (symbol, "MSFT") == 0)
              { return this->msft_._this (); }
         throw Quoter::Invalid_Stock_Symbol ();
            Implementing Stock Interface
In stock_i.cpp

// Access object
class Quoter_Stock_i : public POA_Quoter::Stock
       Quoter_Stock_i (const char *symbol, const char*full_name,
              CORBA::Double price);

         std::string symbol_;
         std::string full_name_;
         CORBA::Double price_;
    Stock Operations
    and Attributes                                        Stock_i.cpp

In stock_i.cpp:

// Access object
class Quoter_Stock_i : public POA_Quoter::Stock
   public: // some details omitted
     char *symbol () throw (CORBA::SystemException);
     char *full_name () throw (CORBA::SystemException);

       CORBA::Double price () throw (CORBA::SystemException);

   // In the .cpp file:
    char * Quoter_Stock_i::symbol () throw
        { return CORBA::string_dup (this->symbol_.c_str ());
           Server                                                     Server.cpp

int main (int argc, char* argv[])
      { // First initialize the ORB, that will remove some arguments…
          CORBA::ORB_var orb = CORBA::ORB_init (argc, argv, "" /* the ORB name, it
                                                             can be anything! */);
         CORBA::Object_var poa_object =
                           orb->resolve_initial_references ("RootPOA");
         PortableServer::POA_var poa =
                           PortableServer::POA::_narrow ( ());
         PortableServer::POAManager_var poa_manager =
                          poa->the_POAManager ();
         poa_manager->activate ();

        // The application code goes here!

       // Destroy the POA, waiting until the destruction terminates
        poa->destroy (1, 1); orb->destroy ();
    catch (CORBA::Exception &ex) { std::cerr << "CORBA exception raised!" <<
                                                   std::endl; } return 0; }
             Software Bus

•CORBA provides a communication
infrastructure for a heterogeneous, distributed
collection of collaborating objects
•Analogous to “hardware bus”
                      OLE Overview

• Object Linking and Embedding

• Microsoft   's technology for supporting compound documents

• A way for Windows to create documents containing objects from
  other programs.

• Components can be re-used by many applications (referred to
  as component containers).
                      OLE Example

• Pie chart generated by Excel
  embedded in a word
  document being displayed in
  a PowerPoint presentation..
                     OLE Technology

• A set of APIs to create and display a (compound) document

• The Component Object Model (COM) now takes in OLE as part
  of a larger concept. It has become a set of standard COM

• Embedded documents retain all their original properties. If the
  user decides to edit the embedded data, Windows activates the
  originating application and loads the embedded document.
                      OLE Extensions

• Automation is an OLE technology, which enables third party
  applications to remotely control Office applications.

• e.g. Puppeteer invokes Automation interfaces to modify
  application behavior when executing on bandwidth limited

• using Automation interfaces, Puppeteer can act as a buffer for a
  large PowerPoint presentation, loading slides while the user
                       ActiveX - Overview

•   A loosely-defined set of technologies developed by Microsoft, ActiveX
    is an outgrowth of two other Microsoft technologies called OLE (Object
    Linking and Embedding) and COM (Component Object Model). ActiveX
    applies to a whole set of COM-based technologies.

•   ActiveX control is Microsoft    's answer to the Java technology from
          . An ActiveX control is roughly equivalent to a    applet, but is
    known as an ActiveX control.

•   Writing a program to run in the ActiveX environment creates a self-
    sufficient program that can be run anywhere in your ActiveX network

•   This component is known as an ActiveX control, and is often used to
    attach a program to a web page.
                ActiveX - Implementation

• An ActiveX control can be created using one of several
  languages or development tools, including C++ and Visual
  Basic, or PowerBuilder, or with scripting tools such as VBScript.

• Currently, ActiveX controls run in 95/98/NT/2000 and in
             . Microsoft plans to support ActiveX controls for

• Similar (but different) security issues as applets


      Resp = Window.Confirm "Use the MS Agent?"
      If Resp Then
      Window.Alert "Loading ActiveX Controls."
      Document.WriteLn "<OBJECT ID='Agent' width=0 height=0"
      Document.WriteLn "CLASSID='CLSID:F5BE8BD2-7DE6-11D0-91FE-
      Document.WriteLn " CODEBASE='" & _
      Document.WriteLn "<" & Chr(47) & "OBJECT>"
      Document.WriteLn "<OBJECT ID='TruVoice' width=0 height=0"
      Document.WriteLn " CLASSID='CLSID:B8F2846E-CE36-11D0-AC83-
      Document.WriteLn " CODEBASE='" & _
      Document.WriteLn "<" & Chr(47) & "OBJECT>"
      End If
      End Sub
   Commercial Products :
Microsoft COM/DCOM/COM+

       Andrew Trevors
 Software Architecture Group

• What is COM / DCOM / COM+?
   –   Client/Server Model
   –   Objects & Interfaces
   –   COM Servers
   –   COM Clients
   –   COM Library
   –   COM Example
• COM+
    What is COM / DCOM / COM+?

• COM (Component Object Model)
   – software architecture which allows components from multiple
     vendors to be combined in a variety of applications
   – binary standard for component interoperability
   – platform and language independent, distributed, object-oriented.
   – is the foundation technology for Microsoft's OLE and ActiveX®
     technologies, as well as others.
• DCOM (Distributed Component Object Model)
   – enables software components to communicate directly over a
     network in a reliable, secure, and efficient manner.
   – is designed for use across multiple network transports.
   – based on the OSF's DCE-RPC specification.
    What is COM / DCOM / COM+?

• COM+ (Component Services)
   – upgrade of the original COM
   – Adds
      • Transaction processing from Microsoft Transaction Manager
      • Queued components
      • Object pooling
      • Publish-subscribe event service
      • much, much, more.
          Client/Server Model

                    (4) Call interface
  Client                                           Object

                     (3) Get object                 Server
                   interface pointer,
                    return to Client
     (1) “Create
       Object”                             (2) Locate
               Objects & Interfaces
• Interface
   – a set of member functions that a client can call to access that object
   – all interfaces start with an ‘I”, followed by a descriptive label
     identifying what services they provide.
   – all interfaces have a IID (interface identifier) which uniquely
     identifies them.
• Object
   – an implementation of one or more interfaces
   – If object wishes to allow COM to locate and launch its
     implementation then it needs to have a CLSID (class identifier)
   – at very least, objects must implement IUnknown interface
       • QueryInterface(), AddRef(), Release()
                      COM Servers

• Servers come in three varieties:
   – In-process
       • Server loaded into the clients process space
       • loaded as a Dynamic Linked Library (DLL)
   – Local
       • Server that runs as a separate process on the same machine as
         the client
       • run as an executable (EXE) application
   – Remote
       • Server that runs as a separate process on another machine
       • DLL or EXE
                       COM Servers

• Servers have four responsibilities
    – Allocate a CLSID for each supported class and provide a mapping
      between CLSID and server module (registry)
    – Implement a class factory object with the IClassFactory interface
      (CreateInstance & LockServer) for each CLSID
    – Expose the class factory so the COM Library can find it once it is
      loaded (CoRegisterClassObject or DllGetClassOjbect)
    – Provide for unloading the factory if is serving no objects and no
      locks are in place
                        COM Clients

• Any application which uses COM to instantiate objects
• Object usage involves:
   – Using CLSID through COM Library or class factory to get an
     interface pointer
       • Interface pointer is actually a pointer to a pointer to a table of
         function pointers
   – Using interface pointer to call member functions or to obtain other
   – Calling Release() function when done with object.
                       COM Library

• COM Library provides :
   – A small number of API functions that facilitate the creation of COM
       • clients (object creation).
       • servers (object exposure).
   – Implementation locator services
       • COM determines, from a class identifier, which server
         implements that class and where that server is located
   – Transparent remote procedure calls when an object is running in a
     local or remote server
                      COM Example
class StockQuote : public IUnknown {
       HRESULT QueryInterface( IID & iid, void** ppvObj );
       ULONG AddRef();
       ULONG Release();
       HRESULT getSymbol( char** symbol );
       HRESULT getLongName( char** name );
       HRESULT getPrice( int* price )
       int _price;
       char* _symbol;
       char* _name
                      COM Example
HRESULT StockQuote::QueryInterface( IID & iid, void** ppvObj ) {
  HRESULT retVal = S_OK;
  if( IsEqualID( iid, IID_IUnknown )
         *ppvObj = ( IUnknown*) this;
  else {
         *ppvObj = NULL;
         retVal = E_NOINTERFACE;
  return retVal;
                    COM Example
hRes = CoCreateInstance(&CLSID_STOCK, NULL,
                                 &IID_IUnknown, &pStock);
if (SUCCEEDED(hRes)) {
     // do something with pStock
else {
     // report error

• Extends COM to support object communication across
• DCOM protocol, Object RPC, extends DCE RPC
   – Uses RPC packets with extra information such as interface pointer
   – Programmers generally write an IDL and use an IDL compiler
     (MIDL) to generate proxies/stubs
• Pinging for garbage collection

Client Process
                                                  Local Server Process

                 In-Process Server                              Object
 Application                               COM
                                     RPC                       Local Server

                     COM                            Remote Machine

                                                  Remote Server Process

                                     RPC                        Remote
                                            Stub                Object

                                                               Remote Server

• Transactions
   – Coordination between COM+ and DTC (Distributed
     Transaction Coordinator) to ensure ACID properties.
• Queued Components
   – Provides asynchronous component invocation and execution
     through the use of Microsoft Message Queuing Service
• Object Pooling
   – Automatic service provided by COM+ which allows
     components to have instances of itself kept active in a pool
      • Stateless
      • No thread affinity
      • Aggregatable

• COM+ Events

To top