1. Trang chủ
  2. » Công Nghệ Thông Tin

Java 2 Bible Enterprise Edition phần 7 pot

71 293 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 71
Dung lượng 222,82 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

• Dynamic Invocation Interface DII — The DII allows applications to call remote objects without the help of the client stub.. Figure 18−3: Interaction between server and client The follo

Trang 1

Tip You can't control bean−security issues through the policy files used by J2SE These policy files onlycontrol functions of a particular API, such as file I/O or threading, and they won't work because they must

be available across all clients and servers In addition, the environment (for example Java code embedded

in an Oracle database as a trigger) may not support them

The assignment of a set of access restrictions is known as a role in EJB terminology A role acts as a grouping

mechanism You don't use it to predefine access capabilities or users who wish to attempt certain tasks; rather

it acts as a means of collecting like−minded methods together after you have written them

A particular user of the system is known as a security principal When your servlet code needs to access an

EJB, it has an identity, which is the principal's name The name represents the user attempting to perform thetask The role information forms the other half of the request At some point during the deployment, theperson responsible for deploying beans will pull up the administration tool and provide a mapping of principalnames to roles Consider it a many−to−many mapping where a single principal may be allocated a number ofroles, but a role may be assigned to many principal names How the roles and principles are arranged depends

on your application requirements

Determining who is calling

As we alluded to earlier, some programmatic ways of accessing security information exist The two methodsprovided enable you to determine the identity of the principal calling you and to check the role of the caller.Caution The J2EE specification explicitly warns against using these methods as means of

controlling secure access to your code They should be treated as purely informational,because if your method has been called, the assumption is that the EJB container hasalready performed all the necessary checks

Finding out the identity of the principal calling your code is the job of the getSecurityPrincipal() method ofthe EJBContext The return value of the method is java.security.Principal, which represents the underlyingauthorization mechanism (for example, Keberos or NIS) You can then obtain the name of the user as a Stringwith the getName() method

So why would you want to know the name of the user calling you? Let's say you are running an applicationthat is a data−entry terminal, such as a terminal in the dispatch warehouse The user logs on and then startsprocessing orders The terminal brings up the next order pending Off goes the storeman to acquire the items,parcel them up, and call the courier Before the storeman can move on to the next item, the order is marked asbeing processed, and the next order comes up As far as he or she is concerned, "Order completed" is the onlybutton on the screen Down the back, on the EJB server, the database requires a record of who actually

processed the order Instead of having to ask the storeman to enter his or her name each time, you can use thegetSecurityPrincipal() method to access the login name and assign it to your database record For example,you might find the following business method in the Order bean (ignoring exception handling):

public void orderCompleted() {

Principal operator = ejbContext.getSecurityPrincipal();

String op_name = operator.getName();

InitialContext ctx = new InitialContext();

Object home_ref = ctx.lookup("ejb/EmployeeLocalHome");

EmployeeLocalHome home = (EmployeeLocalHome)home_ref;

Employee emp = home.findByPrimaryKey(op_name);

Trang 2

// now assign the reference to the employee bean here as we

// are assuming a CMR field

setEmployee(emp);

}

Notice that the code uses the operator's login name as the primary key for the employee bean The assumptionhere is that the login name is always unique and therefore valid for a unique identifier for a bean To accessthe real details of the employee, you can then look up the bean or one of the other server−administration tools.Using the operator details, the code then looks up the representative bean and assigns it to this order−beaninstance so that the relationship is established and then maintained by the EJB container using

container−managed relationship capabilities

On the odd occasion when the deployment−descriptor handling of role−based information is not sufficient,you can enforce tighter rules using the isCallerInRole() method from EJBContext For example, the beanmight impose a maximum number of simultaneous requests for a particular role, backed by information in adatabase

The isCallerInRole() method takes a single argument of a String, representing the name of the desired role tocheck against In return you are given a Boolean value indicating whether the caller is using the nominatedrole For example, if you want to check that the user about to process an order as complete is actually thestoreman, then the following code becomes useful:

public void orderCompleted() {

if(!ejbContext.isCallerInRole("stores"))

throw new SecurityException("The caller is not " +

"authorized to complete an order");

.

}

It is important to understand that the role information that is checked is what the caller is acting as, not whatyour bean code is currently acting as These may well be two separate things — you could allow four roles toaccess your code, but be described by a completely different role

Profiling the user for access capabilities

Now we get into the specifics of applying role and security information to individual bean instances All theinformation in this section is described in the deployment descriptor As you will see, it is quite verbose as aprocess and will usually be easier to set up in the tool provided by your EJB server vendor However, read on,

as you will need to understand the terminology used in all those wizard dialog boxes

Security information is defined in so many places in a deployment descriptor that deciding where to start can

be a daunting exercise In order to make the following sections more understandable, we're going to introducethe ideas in the order in which you might consider security issues from the deployment perspective

Unfortunately, that means that we'll be jumping all over the deployment descriptor to insert the new

information provided in each step We hope not to confuse you too much!

The Role Chain of Execution

In all but the simplest systems, your particular bean may be at the end of a long series of method calls Inorder to reach your code, a request may have passed through a servlet or two, a JMS message queue, and then

a few layers of beans By the time you receive a request, how do you know whether the original caller was

Trang 3

actually allowed to access the information?

Roles have the interesting ability to form a chain The original caller sets the role, and then all subsequentmethod calls maintain that role So even if you are buried under 10 levels of method calls and beans, you willstill maintain the original caller's role In this way, you can determine whether the original caller was a servlet,message queue, or any other type of bean

For example, if you have a servlet and you set its role to be customer_servlet, then your order bean's

ejbCreate() method will return isCallerInRole("customer_servlet") as true However, if the order was placed

as a telephone operator using a kiosk application, the method will return false Even if you are called by otherbeans between the servlet and your code, the role is not changed by any of the intermediaries

The only time you have a chance of influencing the role used is when your bean is directly accessed byapplication code For example, a kiosk application accesses your bean directly The application does not have

a role associated with it, so the EJB container will take the role assigned to your bean as the originating role

Declaring role information

The first task in building security information is deciding on the various roles that will be assumed by thebeans and the bean clients Ideally you will decide in a very early stage of the project's analysis and design,not right at the end when you have finished testing

You start the process by declaring all the roles to be used by the beans Role declarations take place in thesecurityưrole element, which is in turn held in the hithertoưunseen assemblyưdescriptor element

You declare assemblyưdescriptor as the last child of the ejbưjar element — after the enterpriseưbeans element

in which you have so far been placing all your information:

Tip The security roles defined by the securityưrole elements are scoped to the ejbưjar file level, and apply toall the enterprise beans in the ejbưjar file If you have two JAR files that nominate the same roles, they aretreated as independent entities as far as the container is concerned

Inside the securityưrole element is only one required tag — the name of the role being declared:

<assemblyưdescriptor>

<securityưrole>

<roleưname>customer_servlet</roleưname>

</securityưrole>

Trang 4

Tip You can add a description string with each role's name, just as you can with most other items in

the deployment descriptor

Declaring role names is just the first step It is a declaration of who might want to use the system for thedeployment tool to look at in order to start putting things in order The next step is to assign a role to anindividual bean to be used when no other information is known about the caller (that is, when no role

information is present yet)

Forcing a bean to run as a particular user

To define information about the default security information for a bean, we now jump back to the

deployment−descriptor declarations dealing with a specific bean instance (such as entity or session elements).When declaring user information for a bean, you have two options: provide a specific role name to run underevery time, or always use whatever the caller provides The choice here is binary — you can't provide bothpaths In either case, you start by specifying the security−identity element The new element is placed betweenthe primkey−field and query elements if you are using an entity bean, and after the transaction−type element

if you are using a session bean, as shown in the following example:

Trang 5

Nominating security information

Earlier you saw the use of the programmatic methods for checking the caller−role information When you dothis, you need to let the container know that you are going to be performing these checks, and exactly whatyou will be checking for The effect of these checks is to imply the roles the bean code wants to check for aspart of the deployment process

References to roles declared in code are contained in the security−role−ref element This element is placedjust before the security−identity element if you declared it earlier In the role declaration, you place the name

of one role that you have declared in code and an optional element that provides a link between the codedeclaration and one of your defined declarations in the security−role section If more than one role is beingchecked in the bean's code, you just declare more security−role−ref elements

Tip Security−role nomination is not available to message−driven beans

You use link information when you wish to map the code's role declarations to your own preferred

declarations For example, a third−party bean declares a name that conflicts with one of your names, so youwant to map it to something else or to a broader category:

Getting picky with per−method security

Once you have defined the larger perspective of security, you can become much more detailed in yourrequirements Should you require it, you can become as detailed as individual method calls when singling outwho can access what functionality

In each of the following pieces of functionality, the method is always described by a single structure: themethod element Different behaviors are then wrapped around this structure The purpose of the method

Trang 6

element is to describe, in as much detail as necessary, the method signature So you start with the beanaffected:

<method>

<ejb−name>Product</ejb−name>

<method−name>findByCategory</method−name>

</method>

Mapping the Bean's View to the Real World

From your perspective, the security net starts with the deployment descriptor In the deployment descriptor,you describe the access requirements of the various pieces of code in terms of roles In order for these

definitions to take effect, they must mean something in the greater scope of the entire system

Roles don't have any meaning in the real world of the server's operating system They are not required to,either Roles are only a construct of the EJB server software If the roles do have any relationship to userdetails on the underlying system, it is purely due to the server administrator's creating matching information

However, roles are much smaller in scope than a standard user login, so it would be unusual to see a directmapping of EJB roles to system users A role may only encompass a single method call out of thousands ofbeans If your system consisted of hundreds or thousands of beans, the management issues would become anightmare as you tried to keep the EJB parts synchronized with the servers

When you have only one of this method in the class, you can stop here However, when you have overloadedmethods, such as create(), you might want to single a specific method out for separate treatment by providingthe method arguments To specify a particular method based on the argument list, use the method−paramselement, which looks and works identically to the examples you saw earlier with EJB QL:

<method>

<ejb−name>Product</ejb−name>

<method−name>findByCategory</method−name>

<method−params>

Trang 7

is inserted between the ejb−name and method−name elements There are four valid values: Local, Remote,Home, and LocalHome.

<method>

<ejb−name>Product</ejb−name>

<method−intf>Remote</method−intf>

<method−name>findByCategory</method−name>

Now that you know how to declare methods, it's time to use them in something You can declare methods to

be completely off−limits, or you can create a free−for−all

At the tightest end of the spectrum is the list of methods that cannot be called at all These methods are listed

in the exclude−list element exclude−list is placed as the last element of the assembly−descriptor (before theexclude−list are a couple of elements that we'll be covering shortly) Inside exclude−list you list all themethods that should not be accessed:

Inside the method−permission element, you find a collection of individual methods and the role(s) that areallowed to access them Each permission declaration starts with the list of acceptable role names, followed bythe method declarations of all the methods affected by these permissions:

Trang 8

Caution The EJB 2.0 specification does not mention the order of priorities when declarations conflict with

each other It is best to double−check everything you provide to make sure no conflicts exist

If you would like to go all the way and let any user call a method, you can substitute the empty elementunchecked for the list of role−name in the method−permission The result is that the server always letsrequests to these methods go through:

in the requirements and implementation

Dealing with Bean−Configuration Issues

The last topic that we wish to cover with regard to beans is dealing with configuration issues You've beeninundated with one aspect of configuration already: specifying deployment information with the deploymentdescriptor What we have not covered so far are all the small details, like environmental properties — itemsthat you have traditionally used Java properties files and the java.util.Properties class to deal with

New Feature The J2SE 1.4 API introduces a standardized preferences API for the first time in the

java.util.prefs package J2EE 1.3 requires only J2SE 1.3, and so you may or may not haveaccess to these capabilities

Under the EJB specification, providing property information to configure your beans is just as important asbefore Although beans like stateless session beans are not supposed to be individually configured, plenty ofareas still exist in which you can provide configuration information for business logic These include areas inwhich you might need a constant defined, such as maximum and minimum values of a range check

Trang 9

Summary of existing configuration techniques

Before venturing into the approved method of providing configuration information to beans, let's quickly goback over the previously existing options and where they fail in the EJB worldview

Properties files

Until the release of J2SE 1.4, no standard system for storing and loading user preferences existed If a

programmer wanted to create a portable application that was configurable, the only option, apart from creating

a custom system, was to use text−properties files and use the Properties class to load and save the information.J2EE requires a heavy restriction on the use of file I/O The use of the java.io.File class is not permitted within

a bean implementation This leaves you rather handicapped because you have no real way of reading, andmore importantly no way of saving again, a properties file There is a potential alternative method to locateand open the file using ClassLoader's getSystemResourceAsStream() method and storing the property file inthe EJB−JAR file This tactic is thwarted by the rule that bean implementations are not permitted to access thecurrent class loader that the method call relies on

JNDI driver registration

Throughout this book you have been seeing examples of how configuration and storage information is

maintained For example, JDBC drivers are registered by the system, and you access the current driver

through JNDI Each of these drivers is externally configured as part of the J2EE middleware−vendor's

software

Because no standard configuration mechanism exists for low−level drivers, this lack of a standard systemdoes not make the idea of portable environment variables particularly appealing Each time you move to anew system, you need to build a new set of configuration files If you are providing a bean library for others touse, the requirement that each customer build his or her own set of configuration files can be a major

headache

Providing system−agnostic configuration properties

Providing property information falls to the pairing of JNDI and the deployment descriptor Once again, thedeployment descriptor holds the values to be used during runtime, while your bean−implementation codeaccesses values through JNDI

Accessing properties in code

In your bean−implementation code, accessing environment properties starts with creating a JNDI

InitialContext instance Accessing property values starts with you performing a lookup() operation on thename of the variable (just like you've done before with JDBC data sources and bean home interfaces) Thisobviously requires you to know what those property names are beforehand The root name to use in the JNDIcontext is the same as that of all other J2EE items: java:comp/env Below this, you provide the name of theproperty that you are after For example:

InitialContext i_ctx = new InitialContext();

Context env = i_ctx.createSubcontext("java:comp/env");

Object prop = env.lookup("MyProperty");

Trang 10

Tip The J2EE specification makes no recommendations for naming conventions for properties, unlike forJDBC drivers or EJBs Properties are only visible to their particular beans, so there is no need to come upwith really long, convoluted names.

Property values are restricted to using only the primitive types available in Java Effectively, that meansstrings, integers, and floating−point values When you access a value through the lookup() method you willthen need to cast the return value to the appropriate class type, as follows:

Integer max_int = (Integer)env.lookup("MaxRange");

Integer min_int = (Integer)env.lookup("MinRange");

int max_value = max_int.intValue();

int min_value = min_int.intValue();

That's all there is to using properties in your bean code The next step is to declare the property values

Declaring property values

Completing the task of using property values requires us to wander back to our old friend, the deploymentdescriptor Properties are defined with the bean in which they are used, rather than as a global setting

Therefore you can have properties with the same name in different beans that use different datatypes andvalues! We really don't recommend it, though, and always suggest using clear, meaningful names for eachproperty

Property values are contained in the env−entry element, which you can find just after the primkey−field ofentity beans, and in the transaction−type element of session and message−driven beans You must declare oneenv−entry per property Within env−entry, you then provide a name, the Java class type that it must use, andthe value, in that order For example, to declare the MaxRange value we used in the preceding code snippet,you need to declare the following in the deployment descriptor:

is that the entry type must be the fully qualified Java class type rather than just the class name

If you need more than one property defined, then just use more env−entry elements For example:

Trang 11

Who Is Looking After the Code?

Code, code, code When you look back over the past two chapters, all we ever talk about is how you can writethis bit of wonderful code that does all these terrific things Barely do we stop to consider that there are peoplealso involved in the system If you read between the lines, you will have noticed passing references to otherpeople – system administrators, architects, users and more EJBs fulfill one very small part of a very bigsystem – it is a little, tiny, bit of code in amongst a billion dollar company that employs thousands of people.Surely at least one or two of these might be a bit interested in what you are doing with the company's moneyand very expensive hardware

Before you even start looking at code, and well after you have finished, there are many other people involved

in the process of giving your fellow workers a useful piece of software The EJB specification defines anumber of roles that make up the process of getting the code from the drawing board to the user As you couldimagine, not all these roles involve code cutting

Note The roles outlined in this section only consider the EJB worldview Where you have middleware, youwill need a client application, and a datastore The roles described here do not consider these other roles

of the full application development

EJB development roles

The EJB specification defines six roles involved in the development of an EJB All of these roles have somerelationship to the process of developing code Depending on the size of your organization and the project, aperson may fulfill more than one of these roles However, as you can see, these roles are distinct phases in thedevelopment process

The bean provider

That's you — the code cutter You are required to code the complete bean: home and remote interfaces, localinterfaces if needed, and the implementation class If you must use other code libraries inside your

implementation, then you may need to code those as well After coding, and testing, your bean you are also

responsible for creating the EJB−JAR file That is, you must put together the deployment descriptor andcreate the JAR file

At this stage, the assumption is that you are coding one bean at a time That bean represents a specific piece ofinformation, and you are the expert in that area Your role does not need to consider higher−level issues such

as transaction management or how the beans may be deployed on the server If you have container−managedbeans, then you must also provide the EJB QL statements

The application assembler

After a collection of beans have been written, they need to be assembled into the EAR file so that it may bedeployed to the server This function is performed by the application assembler They take your collection ofEJB−JAR files and add more information to the deployment descriptor The main function of this role is toconsider architectural issues such as how transactions are to be managed

Trang 12

An application will consist of more than just the beans A further task for this role is to collect the work of theclient−side developers, such as servlets, JSPs and any standalone applications, and include those in the EARfiles.

The deployer

With all the code packaged, ready to go, the next role is to deploy that EAR file onto the middleware server.The deployer role must resolve any external dependencies during this process That means if your beanrequires JDBC data sources or environment entries to be set, the deployer must provide all of that information.Put simply, this person customizes the beans to the particular environment that they will exist in

The person fulfilling the role of the deployer is not likely to be a code−cutter Typically he or she is an expert

in that particular environment — for example he or she will have an Oracle or Websphere certification

The server provider

Unless you are working on an Open Source project like JBoss, you are unlikely to be fulfilling this role withinyour company The role of the server provider is taken by the various product vendors, such as Oracle, IBM orBEA They are required to provide you with server software, which may involve many different products Forexample, you might have DB2 database from IBM, BEA's Weblogic for the middleware and Apache/Tomcatfor the web tier Each of these is a server provider role

The container provider

In most cases, the container provider role is the same thing as the server provider role While the serverprovider role can be quite general, this role focuses purely on the job of taking bean code and providing tools

to make those beans available to all takers

The container provider is required to provide deployment tools as well as the software that manages theruntime instances of the beans If there are clusters of servers, then the container provider must also providethe management facilities for the cluster

The system administrator

Finally the management of the whole system — servers, networking, communications and software falls tothe system administrator role This role is just your standard sysadmin that has to deal with installing

software, fixing broken printers and keeping the users happy

Non−development roles

In addition to the development roles, there are also roles that do not involve the development These roles arenot defined in the EJB specification, but you are going to come across these people once you start developingreal−world code

The Business Analyst

Before you even start coding, someone has to decide what needs to be coded Deciding what needs to becoded must start with a person talking to other people, such as the users In this role, the business analyst isresponsible for doing that thing that all techies detest — talking to the end user Believe it or not, that's areally useful thing to do, because with happy users, you have happy managers With happy managers, youhave a much better life The key to happy users is to provide them with software that they want, not what you

Trang 13

feel like hacking up in your spare time between games of Q3 or Everquest.

Business analysts are the people that do a lot of the basic footwork of getting around to all of the people thathave a vested interest in the project and trying to make sense out of all their wishes They filter the variouswishes and build a list of requirements and the tasks the users will be performing Sometimes they may getinvolved in specifying the user interface layout It will be your job to take the information they present andturn it into a usable application

be better done in a different manner Better to do that change early in the development rather than right at theend or even end up with unhappy users after you have finished

The management

Everybody loves to hate them Of course, the management role is just as important as any other in the

software development Not only do they make sure you get paid, but they are the ones that have to sponsoryour project work Management roles extend all the way from your team leader up to the CEO At each stage,there are a different set of responsibilities, but each makes sure that development proceeds, or stops They willalso feed requirements into your development — deadlines, testing requirements, hardware and more

Summary

Writing and deploying Enterprise JavaBeans is a huge part of any enterprise−level application As they havegained more acceptance, the specification has grown to include new uses for them This chapter has coveredmost of the new functionality included in the EJB 2.0 specification As you can see, it is a big chapter already,without covering the now−obsolete EJB 1.1 spec!

We covered many detailed topics in this chapter The most important of these were:

Advanced EJB topics such as method granularity

Trang 14

The success of a software product depends on the following factors: code reusability, code efficiency, andcode maintainability Of these criteria, reusability is probably the most important, as it drives the other two —that is, code that is written with reusability in mind tends to be both efficient and easily maintainable So, theobject−oriented techniques plays an important role in mainstream software design.

The Need for CORBA

The need for design of "objects" that could be used across networks by multiple users resulted in the

development of CORBA specifications These specifications, developed by the Object Management Group(OMG), were designed exclusively for a distributed−applications framework Developers using these

specifications can create applications that can be used across multiple configurations and that are both

fault−tolerant and sophisticated in their core functionality

Business units today, even within the same organization, have the flexibility to use diverse IT software,hardware, and networking systems Business units therefore look for applications that are supported by thesediverse systems CORBA enables developers to develop applications that work seamlessly across thesesystems

Consider the following example: A needs to send a package to B A and B are in different locations Assumethat A sends his package through the postal service to B Earlier, the only information A could receive aboutthe status of the package was an acknowledgement of receipt at the other end by B Now, however, thanks tothe improvements brought about by the Internet, A can not only know whether the package has reached itsdestination, but can also track it throughout its transit, enabling A (the sender), B (the recipient), and thepostal service to know exactly where the package is at any given time The postal service enables this byproviding access to a tracking application that both sender and receiver can use to get the status of the

package

This is a simple example that illustrates how diverse systems across multiple organizations are required toexecute the same code object CORBA is a set of tools that can be used to develop objects whose centralfeature is global usability

What Is CORBA?

CORBA is the acronym for Common Object Request Broker Architecture It is an open, vendor−independent

specification developed by the Object Management Group (OMG) to support applications designed to workacross networks (both within the same organization and across multiple organizations) This model, because itenables the interoperability of distributed objects across diverse architectures and platforms, allows clients toaccess and execute various objects across networks with ease Basic architectural features provided by theCORBA architecture are as follows:

Location transparency — This allows client applications to access objects across the network without

knowing where they reside As far as the client is concerned (at least in theory), the object beingcalled could be in the same server as the client, in another server on the same LAN, or ten thousandmiles away, accessed through a WAN

Trang 15

Support for distributed networks — CORBA−compliant products are all platform−independent,

which allows applications to work on a wide range of systems A CORBA object can be invoked, byany client that uses the proper interface definition, regardless of the hardware and software platformsrunning on the client system

Seclusion of interface and implementation — Because clients "talk to" (that is, invoke) objects only

through appropriately defined interfaces, implementation changes in the server do not directly affectthe client In fact, clients are unaware of implementation changes in the object, as they interact onlythrough interface definitions, which are constant for an object invoked from a client This feature ofCORBA enables you to modify and upgrade objects without having to also change how clients invokethe object — or, indeed, anything else about the clients

The Object Management Architecture

Understanding the Object Management Architecture (OMA) is critical to developing a proper understanding

of how CORBA works The OMA acts as the base for the CORBA architecture It is a mature model, enablinglocation−transparency of objects across heterogeneous networks The OMG originally designed the OMAspecifications, like CORBA, in order to standardize applications developed for CORBA

Figure 18−1 illustrates the structure of the OMA Its relevance to CORBA is that it uses an ORB to mediatecommunication between services provided through objects and the client applications that invoke them

Figure 18−1: Object Management Architecture (OMA)

of CORBA services in the later sections (CORBA Services)

Trang 16

Object Request Broker

The Object Request Broker (ORB) is the heart of the OMA and of CORBA It allows objects to interact witheach other regardless of the platforms they reside and execute on The ORB is the coordinating core for allobjects in the system, receiving and processing requests and responses from objects and from requestingclients across the network A client requesting an object gains access to it through the ORB The ORB

provides a layer of abstraction between the client and the application

CORBA objects are prohibited from interacting directly with each other When two objects do have to

communicate, they do so through an interface These interfaces are in turn based on a set of OMG−definedspecifications known as the Interface Definition Language (IDL) Applications use IDL to create commoninterfaces with which clients and objects can interact with other objects independent of the underlying

programming languages and platforms they have been designed to run on IDLs in turn are mapped to anyprogramming language using an appropriate IDL compiler As interfaces are designed to be

language−independent, accessing the CORBA object is relatively simple Multiple ORBs communicate bymeans of a messaging protocol known as Internet InterOperable Protocol (IIOP)

Structure and Action of ORB

Figure 18−2 shows the structure of the ORB The various elements are as follows:

Figure 18−2: Structure of the Object Request Broker (ORB)

Client — The application that requests the remote object.

IDL compiler — The IDL compiler creates the language maps of IDL code, based on the

programming language(s) used

IDL stub — The IDL interface created on the client by the IDL compiler It ensures the marshalling

of the appropriate parameters involved in the invocation of the remote object Marshalling is theprocess by which the necessary parameters for calling the remote object's method are inserted into theremote object and sent to the server for processing

Trang 17

IDL skeleton — The IDL interface created on the server by the IDL compiler It ensures the

unmarshalling of parameters involved in the invocation of the remote object Unmarshalling is the

process by which the skeleton extracts the parameters from the remote object for processing It has thesame functionality as the IDL stub, except that it resides on the server instead of the client

Dynamic Invocation Interface (DII) — The DII allows applications to call remote objects without the

help of the client stub In effect, this allows clients to call remote object methods whose types areunknown DII also improves performance, as it allows client applications to execute other tasks untilthe request is served

ORB interface — The ORB interface has some local functions that object implementations and clients

can use to talk to other CORBA services, such as the naming service and the lifecycle service

Object implementation — The layer in which the remote objects are implemented Typically, the IDL

skeleton or DSI layer communicates with this object implementation to access the real remote object

Object adapter — The object adapter helps the ORB locate the target object implementation in the

server

Interface repository — This repository stores all the interface definitions defined by the IDL The

ORB uses it as a lookup directory for all interface definitions when the DII is used It acts as a

substitute for the client stub when there is a need to type−check objects

Upon initialization, the ORB performs the following series of steps for each object:

Initialize the ORB component

Figure 18−3 illustrates how ORB achieves its purpose

Figure 18−3: Interaction between server and client

The following are the steps a client typically goes through when it calls a (remote) CORBA object throughORB:

To call the remote object, the client first needs an object reference Because the remote object can beaccessed from within any ORB framework, it is also referred to as an Interoperable Object Reference.Once the client obtains the Object Reference, the IDL stub containing the necessary interface

definitions creates and sends a CORBA defined request object containing the necessary parameters tothe ORB The process of inserting the parameters into the request object is called marshalling As

1

Trang 18

explained in the bulleted list at the beginning of this section, this process can also be done through theDII.

The ORB then sends an IIOP message through the network to locate the remote object needed

Dynamic Invocation Interface (DII)

Remote calls to CORBA objects are made when the client calls a method that is resident in the remote object.The client calls the method by means of the client stub created by the IDL compiler, which "knows" themethod — that is, the number and type of the parameters, the exceptions that will occur, and the return type.This is how objects are invoked through static invocation, in which the client has all the details about theobject at compile time

The Dynamic Invocation Interface (DII), as the name suggests, allows client applications to dynamically callremote objects This process does not require a client stub; instead, the ORB uses the Interface Repository tocheck and resolve calls to the remote objects This in effect enables client applications to invoke and useobjects that were not available at compile time In addition, it allows client applications to use newly createdobjects that are available at runtime Dynamic invocation is also useful in synchronous applications Usually,the client makes a request for the object and waits until the server sends the response back to it With the help

of dynamic invocation, the client can send the request to the server and monitor the response, simultaneouslyexecuting other tasks until it receives the response This improves the performance and efficiency of theapplication Additionally, client applications are not restricted to use any particular remote objects and neednot be recompiled when they use new objects The only drawback is the programming effort required toreplace the stub in the client application

The following are the steps involved in making calls using the DII:

The remote object's reference must be obtained

Trang 19

Dynamic Skeleton Interface (DSI)

The Dynamic Skeleton Interface (DSI) resolves client requests dynamically to transfer control to the targetCORBA object The DSI helps clients locate target CORBA objects that the clients do not have compile−timeknowledge of When a client submits a request, the ORB interface attempts to locate the target object with thehelp of this interface, thus performing the role of the static skeleton The DSI makes use of the InterfaceRepository to resolve object calls

Interface Repository

The Interface Repository acts as a dictionary, containing definitions of the remote objects It plays an

important role in the dynamic invocation of remote objects, and does some of the work of the client stub indynamic invocations Because the Interface Repository holds the definitions of all object interfaces, clientapplications that use it do not need to restrict themselves to the use of objects that were available when theirapplications were compiled Client applications can use it to invoke objects created after application compiletime through dynamic invocation The Interface Repository is also used to check the accuracy of the

inheritance graphs

Implementation Repository

The Implementation Repository contains all the relevant information about object implementations The ORBuses it as a dictionary to monitor the process of locating and activating remote objects It also stores additionalinformation associated with the object implementation that could potentially be useful to the ORB

Object adapters

Adapters are units in the ORB that serve as intermediaries between the ORB and the object implementation.The ORB uses the object adapter to obtain information about CORBA objects In order to execute the

operations on the CORBA object as requested by the client, the ORB in the server must determine the details

of the implementation of that particular object The function of the object adapter is to find the correct object

implementation The object that implements the CORBA interface is called the servant object; it may also be called the object implementation.

When a client invokes a method on the CORBA object, the client ORB bundles the request and sends it to theserver ORB The server ORB then passes the client request to the object adapter The object adapter, whichmaintains details about all the servant objects (object implementations) that implement the CORBA object,locates the appropriate servant object and passes control to the static skeleton layer or the DSI The skeletonlayer extracts the input parameters and passes them to the servant object (object implementation) to performthe necessary operations, as illustrated in Figure 18−4

Figure 18−4: Structure of the object adapter

Trang 20

Before you can understand object adapters, you must understand the servant object The term "servant object"indicates that this is the object that is created in and residing in the server, and that it actually implements theCORBA interface Since servant objects implement the CORBA interface, the object adapter must haveaccess to the relevant information about CORBA entities and their associated servant objects Object adaptersperform the following functions:

Registering servant objects — Servant objects, once created, must be registered with the object

adapter so that the adapter is aware that that particular servant exists in the server The object adapter

identifies the servant objects with the help of an object ID (defined later in this section) that acts as a

unique (within the adapter only) key for identification

Activating and deactivating CORBA objects — Activation is the process by which the CORBA object

is made eligible to service client requests It typically involves creating and associating a servant

object with a CORBA entity Deactivation is the process by which the association between the

CORBA entity and the servant object is removed, during which the servant object may be destroyed

Maintaining the object map — It is the responsibility of the object adapter to maintain an associative

map of the CORBA object and its servant so that the servant can be located when a client makes arequest

Two types of object adapters are in use, Basic Object Adapters (BOAs) and Portable Object Adapters (POAs)

Basic Object Adapters

Basic Object Adapters are the simplest type of object adapter in use These are the adapter whose interfaceswere initially introduced by the OMG The object adapter's function is to help the ORB in the server locate theright target object when the ORB receives the client request The BOA provides interfaces for creating,activating, deactivating, and destroying objects, and also monitors them in the server The BOA uses certainactivation models to maintain server processes These are as follows:

Shared server model — As the name indicates, this model allows the server to share the existence of

the various CORBA objects, thus enabling support of CORBA objects of different types

Unshared server model — This model allows only one CORBA object of a particular type to reside in

the server

Persistent object model — This model allows the server to be launched by the user code, a shared

server that supports CORBA objects of different types

Server−per−operation model — This model creates a separate server process for all incoming

requests

The BOA was the first adapter type introduced by the OMG, and largely because of the lack of

standardization associated with several of its key features, it has some deficiencies that reduce its portability.For example:

No standard interface defines the association between the object adapter and the skeleton layer

Portable Object Adapter

Portable Object Adapter (POA) is the recent, flexible object adapter in use It maintains the objects by

assigning them a unique ID called the object ID This adapter maintains an active object map that is used to

map the CORBA servant objects with the object IDs This object ID will be unique well within the POA.When the client passes an object reference, the client ORB sends an object key that is used to locate the target

Trang 21

object The object ID is a part of that object key The object key may also contain information about the POA.Unlike BOA, the Portable Object Adapter uses the concept of nesting, starting with a root POA This allowsthe server to have multiple POAs that can cover different CORBA objects, and it also provides functions toestablish the association between the object adapter and the skeleton layer The Portable Object Adaptersupports multi−threading, which does not exist in the Basic Object Adapter Portable Object Adapters are themost common adapters in use now.

The Portable Object Adapter incorporates policies to maintain and organize the objects in use Some of theimportant policies are:

Object ID assignment policy

Client applications can get references to a CORBA object in many different ways The two important means

of obtaining object references are Naming Services and stringified object references

Naming Services

As the name suggests, Naming Services refer to the locators of object references Naming Services provided

by CORBA enable storage of object references in the depository by assigning unique names to them Thisname−reference binding helps the service locate object references at client requests Naming contexts store

this name−reference binding, known as the name component, in the naming service The naming context can

be a single object−reference binding, or a group of object−reference bindings stored hierarchically Since thenaming context acts as a lookup directory that clients can use to obtain object references, it is the server'sresponsibility to insert the object reference with a name — that is, to create the naming context in the NamingServices

Following are the details of how Naming Services work to connect servers and clients to objects, whenNaming Services are first invoked:

The resolve_initial_references function of the ORB is called as the first step to obtain the CORBAobject reference from the root (the initial object reference)

On the server side, now that the server has access to the naming context, it has to create a component

to be stored in the naming context

Trang 22

The client also creates a name component to query the naming context about that particular objectreference.

8

The naming context then resolves the name component and returns the object As the type of thereturned object is generic, the object is converted to a specific object reference with the help of itsHelper class

The following example, which creates an object reference−name binding using Naming Services, may helpyou understand Naming Services better First, assume the existence of a CORBA application called Welcome,which welcomes a new user with the message "Welcome to CORBA." Consider the steps the server performs

to add the object−reference binding in the naming service:

Implement the interface Assume that the implementation already exists:

class WelcomeServant extends _WelcomeImplBase {

// Implementation code goes here

}

1

Create an instance of the object in the main server application Also create the ORB object Then, addthe object to the ORB with the help of connect( ) method of the ORB:

public class WelcomeServer {

public static void main(String args[])

{

ORB orb = ORB.init(args,null);

WelcomeServant wsRef = WelcomeServant();

orb.connect(wsRef);

}

}

2

Get the initial object reference from the ORB by calling the resolve_initial_ references method in the

ORB interface, as follows (Where "NameService" is the initial name of the service):

org.omg.CORBA.Object objtRef =

ORB.resolve_initial_references("NameService");

3

This method returns a CORBA object In order to use it as a naming context object, you must narrow

it down to a naming−context object by invoking the narrow() method present in the NamingContextHelper class:

NamingContext nmctRef = NamingContextHelper.narrow(objtRef);

4

Subsequently, a name component is created, and is used to uniquely identify the CORBA object("Welcome") The first parameter is the ID, and the second parameter is its kind (which, in principle,can be null):

NameComponent nct = new NameComponent("Welcome","");

5

Since only object−reference binding exists, and no hierarchical structure is involved, a

single−dimensioned array of NameComponents is created to store the object−name binding:

Trang 23

You can perform the name−object binding by calling either the bind() or the rebind() methods of theNamingContext interface.

On the client side, steps 2–6 are repeated to create the NamingContext object As the client has to query on theNamingContext object, it invokes the resolve method of the NamingContext interface to return the object.This object must be narrowed down to the specific object the client requested

Stringified object references

As the name suggests, the object reference is stored as a string so that the client can make use of it As yousaw with the Naming Services, you obtain the initial object reference by calling the

resolve_initial_references() method of the ORB This generic object reference is narrowed down to the

naming context object type by calling the narrow() method of the naming−context object's Helper class Thename component is created for the CORBA object and is bound with a unique name The ORB interface has afunction called object_to_string() that converts this object reference to a string, which can be stored in a Javafile When a request comes in for an object reference from the client, the client can access the file containingthe object reference and use it This is useful in an environment where no Naming Services are available

Internet Inter−ORB Protocol

The Internet Inter−ORB Protocol (IIOP) is the protocol with which the ORB achieves its objectives When aclient requests a CORBA object, it uses an inter−operable reference to identify the CORBA object in theserver The ORB on the client side then passes this reference to the ORB in the server, which identifies theCORBA object and processes the request The client ORB and the server ORB communicate through theInternet Inter−ORB Protocol As the name indicates, this protocol carries inter−operable references acrosswide−area networks (such as the Internet) to facilitate communication between CORBA objects, as shown inFigure 18−5

Figure 18−5: IIOP protocol

The IIOP specification uses a data format called Common Data Representation (CDR), which supports several

of the datatypes in the OMG IDL The IIOP protocol uses this format along with some specific messageformats to send messages across the ORBs The message format supported by IIOP can be transmitted across

a variety of protocols that are currently in vogue, including TCP/IP and SNA, and this helps CORBA achievelocation transparency The main advantage of using the IIOP protocol is platform independence, which helpsCORBA objects interact with each other even when they are not physically located on the same server

Interface Definition Language

Remote objects can be accessed from client applications only when the client invokes a method on thatparticular object Clients, to be able to identify these objects, must have the definition of the remote object'sinterface at compile time This interface definition is provided by the Interface Definition Language (IDL).The IDL file stores the interface definitions of the remote objects needed by client applications IDL files aretypically not written in any programming language, but instead can be mapped to any programming languagewith the appropriate IDL−Language compilers For IDL−to−Java mapping, for example, you would use theidltojava compiler (in version 1.2) or the idlj compiler (version 1.3 and above) to create the equivalent

interface definitions

The following is a simple IDL file with an interface called Sample.idl:

Trang 24

public interface Sample

extends org.omg.CORBA.Object, org.omg.CORBA.portable.IDLEntity

Sample.java is the file that contains the mapping of the IDL interface in Java As the name indicates,

SampleStub.java is the client stub, and SampleImplBase.java the IDL skeleton created by the IDL compiler.This leaves SampleHelper.java and SampleHolder.java

The Helper classes allow the applications to write objects to and read them from the stream They also help toconvert generic object references to specific objects in use with the help of the narrow() method defined in theHelper class, and list the repository ID of the object The Helper classes also allow the applications to extractdata from or add them to a special datatype (called Any) that the IDL uses

The Holder classes provide functionality for manipulating the in/out parameters used in the interfaces SinceJava does not provide any mechanism for resolving the in/out parameters, Holder classes help pass the

parameters properly to achieve the correct results For example, the omg.org.CORBA package offers Holder

classes for all the basic datatypes, while user−defined datatypes have their Holder classes defined as <user

type>Holder.java, and Holder classes for basic datatypes in turn are defined as <datatype>Holder Holder

classes for basic datatypes are typically initialized with default values

Note The following general rules apply to the IDL definitions: Identifiers are usually case−sensitive,

comments can be written as C++ or Java comments, and all statements end in a semicolon

Trang 25

An IDL file supports the use of basic datatypes, complex datatypes (such as structures, unions, enums, arrays,and so forth), and user−defined exceptions Much like Java interfaces, it also supports the inheritance ofinterfaces.

Constants

Constants can be defined in IDL just as in any other programming language Constants play an important role

in many applications For example, if a generic application calculates the area of all available geometricshapes, it becomes necessary to define pi as a constant in the IDL file Pi will in turn be mapped as a Javaconstant, as in the following example

datatypes are not interchangeable; take care when defining datatypes as one or the other

Table 18−1: IDL Datatypes

Trang 26

IDL Definition

module SampleApp {

interface Sample {

struct usr_time {

Trang 27

public short hour;

public short min;

public short sec;

Typedefs

The typedef defines the user−defined type that will be used in the application For example, in a collegeadmission application, in order to store the course in which the student is enrolled, a user−defined datatypecalled COURSE is created This will be a string datatype, but defining and using an intuitive name for thedatatype makes the name clearer

As the typedef also creates a separate class file, no code will be available in Sample.java This definition will

be available under COURSEHelper.java in the sub−package called SamplePackage, which falls under themain SampleApp package

Trang 28

Java Definition

package SampleApp.SamplePackage;

public class COURSEHelper {

// It is useless to have instances of this class

private COURSEHelper() { }

public static void write(org.omg.CORBA.portable.OutputStream

out, String that) {

private static org.omg.CORBA.TypeCode _tc;

synchronized public static org.omg.CORBA.TypeCode type() {

Trang 29

signifies You can arrange this setup with an enumerated data type, for which the definition looks like this:

Trang 30

Arrays play an important role in most applications, as they have proven to be a simple structure in which tostore values Arrays are a common feature of several applications, which in effect makes them a necessity invirtually every language Going back to our college admission–application example, assume that the

admission application has to store test scores for 50 students In order to do this, the application can use anarray In the following example, two arrays are defined — one to store the names of the students and another

to store their test scores

Trang 31

Exceptions are of two types — system exceptions and user exceptions System exceptions can be raised by the

system in situations such as when invalid parameters are passed to remote objects, or if problems are

encountered during memory allocation User exceptions are created mainly by users or clients who take onerror−handler roles Exceptions raised by methods are passed back to their calling objects through the ORB.User exceptions are defined much like the struct datatype in IDL They can have members but not methods Infact, even user exceptions defined without any members are allowed and treated as valid The following codeshows how to write the exceptions in IDL

public final class NoNameFoundException

extends org.omg.CORBA.UserException implements

public final class MarksNotFoundException

extends org.omg.CORBA.UserException implements

Trang 32

public MarksNotFoundException(String name) {

self−evident If the type of parameter is designated as in, it is an input parameter, meaning that it sends valuesfrom the client to the server for processing The client stub must marshal this parameter properly beforepassing it on to the server Parameters designated as out are values processed and set by the server, whichmeans that parameters designated as out will be manipulated only by the server Parameters marked inout will

be accessed and manipulated by both clients and servers The client stub marshals the parameters, while theserver processes requests and sends the output

Going back to the college application example: Assume that an application has to determine an applicant'sgrade by finding the average of the scores of two test papers This requires that test scores be passed as inputparameters and the grade as the output parameter The requirement definition is as follows:

module SampleApp {

interface Sample {

attribute string name;

attribute float score1;

attribute float score2;

string calculateResult(in float score1,in float

score2,out char grade);

void score2(float arg);

boolean calculateResult(float score1, float score2,

org.omg.CORBA.CharHolder grade);

}

In the Java file, the attributes are mapped as member variables of the interface, which therefore contains bothset and get methods for member variables The in parameters are maintained as in the IDL definition, whilethe out parameter is resolved as a CharHolder object Since the server will manipulate it directly, the

CharHolder object is passed as a parameter This CharHolder object will be initialized to 0 (the default valuefor a variable of the char datatype)

Trang 33

Interfaces can be inherited just like Java interfaces Any derived interface can have its own attributes andmethods, in addition to inherited interface definitions Inheritance from multiple interfaces is also possible.

The idltojava compiler

The idltojava compiler is the tool used to create the Java mapping for the OMG IDL You can download itfrom the http://www.java.sun.com/

The idltojava compiler is not included in JDK 1.2, and so you must download it separately In recent versions

of JDK 1.3 and 1.4, the compiler is available bundled with the JDK development kit itself, and is called idljcompiler in the recent versions

The syntax of the idltojava command is as follows:

idltojava −<flags> −<options> <IDL file name>

These are two of the important flags used in the idltojava compiler:

flist−flags — Lists the status of all the flags The value can be on or off

idltojava −fno−cpp <IDL file name>

This command tells the idltojava compiler not to run the IDL source code through the C/C++ preprocessorbefore it is compiled

Example: Calculating Simple Interest

Now try a simple CORBA application to call a method to calculate simple interest for bank deposits Recallthat simple interest is calculated by the following formula:

Simple Interest = Principal* Period (in years)* Annualized Interest Rate (%)

The following are the steps in developing the interest calculation application:

Writing the IDL interface

Trang 34

Step 1: Writing the IDL interface

Take as an example an interest calculator, for the calculation of simple interest Essential input parameters forthe interest calculator are the principal amount, the term of the deposit in years, and the annualized rate ofinterest The application stores these three parameters as the interface's members In order to uniquely identifydeposits, a customer name and Social Security number are also associated with each set of details

The steps involved in creating the IDL interface are as follows:

Create a file called Interest.idl by opening a text editor

attribute double Principal;

attribute unsigned long Years;

attribute float Rate ;

C:\> idltojava Interest.idl

4

This code will create an equivalent Java file in which:

The module statement in the IDL file will correspond to the package name in the Java file, and theinterface will correspond to the interface statement in Java (the server will implement this interface)

Step 2: Compiling the IDL file

The steps involved in compiling the IDL file are as follows:

Go to the command prompt

Trang 35

InterestHelper.java: The Helper class converts the generic CORBA object reference to the "Interest"object reference with the help of the narrow() method present in the Helper class.

public interface Interest

extends org.omg.CORBA.Object, org.omg.CORBA.portable.IDLEntity

Step 3: Coding the InterestServer

In order to create and run the server, you must first implement the CORBA object In the server, the CORBAobject is implemented through an object known as the servant The servant object resides in the server andperforms all the operations requested by the clients, as outlined in the following steps:

Create a file called InterestServer.java by opening the text editor The first statement in the server file

is to import the InterestApp package and other relevant CORBA packages, as follows:

class InterestServant extends _InterestImplBase {

// Implement the defined interface

// Declare the variables

Ngày đăng: 12/08/2014, 19:21

TỪ KHÓA LIÊN QUAN