0% found this document useful (0 votes)
57 views230 pages

MiddlewareText 123

The document discusses middleware and enterprise integration technologies. It begins with an introduction to object-oriented systems, covering key concepts like classes, objects, methods, inheritance, encapsulation, abstraction, and polymorphism. It then discusses distributed object systems, defining them and providing examples. Distributed systems are defined as systems where components located on networked computers communicate through message passing. The types of distributed systems discussed include clusters, grids, and peer-to-peer networks. Features of distributed systems mentioned include functional separation, inherent distribution, and concurrency.

Uploaded by

Anaida Lewis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views230 pages

MiddlewareText 123

The document discusses middleware and enterprise integration technologies. It begins with an introduction to object-oriented systems, covering key concepts like classes, objects, methods, inheritance, encapsulation, abstraction, and polymorphism. It then discusses distributed object systems, defining them and providing examples. Distributed systems are defined as systems where components located on networked computers communicate through message passing. The types of distributed systems discussed include clusters, grids, and peer-to-peer networks. Features of distributed systems mentioned include functional separation, inherent distribution, and concurrency.

Uploaded by

Anaida Lewis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 230

Middleware and Enterprise Integration Technologies

MIDDLEWARE AND ENTERPRISE INTEGRATION


TECHNOLOGIES

SEMESTER VI
INFORMATION TECHNOLOGY

MUMBAI UNIVERSITY

NILESH M. PATIL

1
Middleware and Enterprise Integration Technologies

Chapter 1

Introduction to Object Oriented Systems


1.1 Preview of Object Orientation

Object Oriented Programming or OOP is the technique to create programs based on the real world. Unlike
procedural programming, here in the OOP programming model programs are organized around objects
and data rather than actions and logic. Objects represent some concepts or things and like any other
objects in the real Objects in programming language have certain behavior, properties, type, and identity.
In OOP based language the principal aim is to find out the objects to manipulate and their relation
between each other. OOP offers greater flexibility and compatibility and is popular in developing larger
application. Another important work in OOP is to classify objects into different types according to their
properties and behavior. So OOP based software application development includes the analysis of the
problem, preparing a solution, coding and finally its maintenance.

1.1.1 Concepts in Object Orientation


We first need to understand several fundamentals related to objects. These include class, method,
inheritance, encapsulation, abstraction, polymorphism etc.
Class - It is the central point of OOP and that contains data and codes with behavior. In Java
everything happens within class and it describes a set of objects with common behavior. The class
definition describes all the properties, behavior, and identity of objects present within that class. As far
as types of classes are concerned, there are predefined classes in languages like C++ and Pascal. But in
Java one can define his/her own types with data and code.
Object - Objects are the basic unit of object orientation with behavior, identity. As we mentioned
above, these are part of a class but are not the same. An object is expressed by the variable and
methods within the objects. Again these variables and methods are distinguished from each other as
instant variables, instant methods and class variable and class methods.
Methods - We know that a class can define both attributes and behaviors. Again attributes are defined
by variables and behaviors are represented by methods. In other words, methods define the abilities of
an object.
Inheritance - This is the mechanism of organizing and structuring software program. Though objects
are distinguished from each other by some additional features but there are objects that share certain
things common. In object oriented programming classes can inherit some common behavior and state
from others. Inheritance in OOP allows to define a general class and later to organize some other
classes simply adding some details with the old class definition. This saves work as the special class
inherits all the properties of the old general class and as a programmer you only require the new
features. This helps in a better data analysis, accurate coding and reduces development time.
Abstraction - The process of abstraction is used to hide certain details and only show the essential
features of the object. In other words, it deals with the outside view of an object (interface). . In
computer programming, abstraction can apply to control or to data: Control abstraction is the
abstraction of actions while data abstraction is that of data structures.

• Control abstraction involves the use of subprograms and related concepts control flows
• Data abstraction allows handling data bits in meaningful ways.

2
Middleware and Enterprise Integration Technologies

Encapsulation - This is an important programming concept that assists in separating an object's


state from its behavior. This helps in hiding an object's data describing its state from any further
modification by external component. In Java there are four different terms used for hiding data
constructs and these are public, private, protected and package. As we know an object can
associated with data with predefined classes and in any application an object can know about the
data it needs to know about. So any unnecessary data are not required by an object can be hidden by
this process. It can also be termed as information hiding that prohibits outsiders in seeing the inside
of an object in which abstraction is implemented.
Polymorphism - It describes the ability of the object in belonging to different types with specific
behavior of each type. So by using this, one object can be treated like another and in this way it can
create and define multiple level of interface. Here the programmers need not have to know the exact
type of object in advance and this is being implemented at runtime.

1.1.2 Advantages of Object Orientation

The major advantages of object orientation are:

• Simplicity: Software objects model real world objects, so the complexity is reduced and the
program structure is very clear;

• Modularity: Each object forms a separate entity whose internal workings are decoupled from
other parts of the system;

• Modifiability: It is easy to make minor changes in the data representation or the procedures in an
OO program. Changes inside a class do not affect any other part of a program, since the only
public interface that the external world has to a class is through the use of methods;

• Extensibility: Adding new features or responding to changing operating environments can be


solved by introducing a few new objects and modifying some existing ones;

• Maintainability: Objects can be maintained separately, making locating and fixing problems
easier;

• Re-usability: Objects can be reused in different programs.

1.2 Concept of Distributed Object Systems

A distributed system is one in which components are located at networked computers and devices
communicate and coordinate their actions by message passing for sharing resources and for distributing
computational workload. It is built on top of a network which hides the existence of multiple autonomous
computers. It appears as a single entity providing the user with whatever services are required. A network
is a medium for interconnecting entities (such as computers and devices) enabling the exchange of
messages based on well-known protocols between these entities, which are explicitly addressable (using
an IP address, for example).

3
Middleware and Enterprise Integration Technologies

There are several definitions and view points on what distributed systems are:-

1. Coulouris defines a distributed system as “a system in which hardware or software


components located at networked computers communicate and coordinate their actions only by
message passing”.

2. Tannenbaum defines it as “a collection of independent computers that appear to the users of the
system as a single coherent system.” The first is the use of the word independent. This means that,
architecturally, the machines are capable of operating independently. The second point is that the
software enables this set of connected machines to appear as a coherent system to the users of the
system. This is known as the single system image and is a major goal in designing distributed
systems that are easy to maintain and operate.

Example:

Fig.1.1 Automatic Banking (Teller Machine) System

1.2.1 Types of Distributed Systems

There are various types of distributed systems, such as Clusters, Grids, P2P (Peer-to-Peer) networks,
distributed storage systems and so on.

A cluster is a dedicated group of interconnected computers that appears as a single super-computer,


generally used in high performance scientific engineering and business applications.

A grid is a type of distributed system that enables coordinated sharing and aggregation of distributed,
autonomous, heterogeneous resources based on users’ QoS (Quality of Service) requirements. Grids are
commonly used to support applications emerging in the areas of e-Science and e-Business, which
commonly involve geographically distributed communities of people who engage in collaborative
activities to solve large scale problems and require sharing of various resources such as computers, data,
applications and scientific instruments.

4
Middleware and Enterprise Integration Technologies

P2P networks are decentralized distributed systems, which enable applications such as file-sharing,
instant messaging, online multi-user gaming and content distribution over public networks.

Distributed storage systems such as NFS (Network File System) provide users with a unified view of
data stored on different file systems and computers which may be on the same or different networks.

1.2.2 Features of Distributed System (June 2010) (10 Marks)

The main features of a distributed system include:

• Functional Separation: Based on the functionality/services provided, it determines


capability and purpose of each entity in the system.

• Inherent distribution: Entities such as information, people, and systems are inherently
distributed. For example, different information is created and maintained by different people.
This information could be generated, stored, analyzed and used by different systems or
applications which may or may not be aware of the existence of the other entities in the
system.

• Reliability: Long term data preservation and backup (replication) at different locations.

• Economy: Sharing of resources by many entities to help reduce the cost of ownership. As a
consequence of these features, the various entities in a distributed system can operate
concurrently and possibly autonomously. Tasks are carried out independently and actions are
coordinated at well-defined stages by exchanging messages. Also, entities are heterogeneous,
and failures are independent. Generally, there is no single process, or entity, that has the
knowledge of the entire state of the system.

• Fault-Tolerant: It can recover from component failures without performing incorrect


actions.

• Highly Available: It can restore operations, permitting it to resume providing services even
when some components have failed.

• Recoverable: Failed components can restart themselves and rejoin the system, after the cause
of failure has been repaired.

• Consistent: The system can coordinate actions by multiple components often in the presence
of concurrency and failure. This underlies the ability of a distributed system to act like a non-
distributed system.

• Scalable: It can operate correctly even as some aspect of the system is scaled to a larger size.
For example, we might increase the size of the network on which the system is running. This
increases the frequency of network outages and could degrade a "non-scalable" system.
Similarly, we might increase the number of users or servers, or overall load on the system. In
a scalable system, this should not have a significant effect.

• Predictable Performance: The ability to provide desired responsiveness in a timely manner.

5
Middleware and Enterprise Integration Technologies

• Secure: The system authenticates access to data and services.

1.2.3 Advantages of Distributed Systems

1 Data communications costs are lower with distributed databases because processing can be
performed locally.
2 Since storage unit costs are typically less expensive than telecommunications costs, providing
access to distributed data may be less expensive than providing access to centralized data.
3 Distributed databases can take advantage of benefits of a centralized database (in particular,
data sharing).
4 Distributed environments may be less affected by a breakdown than a centralized system.

1.2.4 Disadvantages of Distributed Systems

1 Distributed databases introduce data management complexities for issues relating to data
concurrency and integrity.
2 Data replicated at several sites may lead to inconsistencies if the data is modified.
3 Distributing data, processing, and computing staff may lead to local "patches" to satisfy local
user needs.
4 Complex networking software is needed to control data communications.
5 Communication overhead may be quite high.

1.2.5 Challenges faced by the Distributed Systems (Dec 2010) (10 Marks)

Various kinds of distributed systems operate today, each aimed at solving different kinds of problems.
The challenges faced in building a distributed system vary depending on the requirements of the
system. In general, however, most systems will need to handle the following issues.
• Heterogeneity - Various entities in the system must be able to interoperate with one another,
despite differences in hardware architectures, operating systems, communication protocols,
programming languages, software interfaces, security models, and data formats.
• Transparency - The entire system should appear as a single unit and the complexity and
interactions between the components should be typically hidden from the end user.
• Fault tolerance and failure management - Failure of one or more components should not
bring down the entire system, and should be isolated.
• Scalability - The system should work efficiently with increasing number of users and
addition of a resource should enhance the performance of the system.
• Concurrency - Shared access to resources should be made possible.
• Openness and Extensibility – Interfaces should be cleanly separated and publicly available
to enable easy extensions to existing components and add new components.
• Migration and load balancing - Allow the movement of tasks within a system without
affecting the operation of users or applications, and distribute load among available resources
for improving performance.
• Security - Access to resources should be secured to ensure only known users are able to
perform allowed operations.

1.3 Reasons to Distribute for Centralized objects

6
Middleware and Enterprise Integration Technologies

Centralized system is one in which communication takes place through one or more central computer
(or hub). This central computer performs the computing functions and controls the remote terminals.
This type of system relies completely on this central computer. If this central computer crashes, the
entire system will go down.

The following are the reasons to distribute centralized objects:

1. Better reliability and extensibility.

2. Dividing the complex jobs into smaller tasks enable them to execute
concurrently.

3. Facilitates load balancing across the network.

4. Facilitates language independence and platform independence.

5. Facilitates resource sharing.

6. Easy maintenance of large data in remote computers.

7. Facilitates fault tolerance ability.

1.4 Client/Server System Architecture (Dec 2010) (10 Marks)

Client-server is a computing architecture which separates a client from a server, and is almost always
implemented over a computer network. Each client or server connected to a network can also be referred
to as a node. The most basic type of client-server architecture employs only two types of nodes: clients
and servers. This type of architecture is sometimes referred to as two-tier. It allows devices to share files
and resources. Each instance of the client software can send data requests to one or more connected
servers. In turn, the servers can accept these requests, process them, and return the requested information
to the client. Although this concept can be applied for a variety of reasons to many different kinds of
applications, the architecture remains fundamentally the same.

1.4.1 Two-Tier Architecture

• Two-tier is the simplest of the architecture types, consisting of only the server and the client
application.
• The server, also known as the database, houses the information of a network, while the client
requests to access the information.
• In a two-tier model, this request is direct, thus easy to develop and maintain.

7
Middleware and Enterprise Integration Technologies

• Though this architecture type is more common, it is usually only implemented in smaller, less
demanding conditions.

Fig.1.2 Two-Tier Architecture

Advantages:

1. Improves usability by supporting user-friendly interface.

2. Improves flexibility by sharing data within homogenous environment.

3. Robust

4. Requires minimal operator intervention.

1.4.2 Three- Tier Architecture

• The three-tier model adds another level to the two-tier setup.


• Instead of the client connecting directly to the server as it does with the two-tier type, the client
application must make requests to the server through a server application.
• For example, if you were trying to access a website with a three-tier architecture type, your
computer would connect to the website's database application.
• The database application would then send a request, on your behalf, to the main server.
• The main server would process your request and forward it back to the database application,
which would then present the information to you.

8
Middleware and Enterprise Integration Technologies

Fig.1.3 Three-Tier Architecture


Advantages:
1. More scalable than two-tier architecture.
2. Easier to modify or replace any tier without affecting the other tiers.
3. Better load balancing by separating business logic and database functionality.
4. Increases flexibility in resource allocation and software implementation.

1.5 Multitier System Architecture

• Some designs are more sophisticated and consist of three different kinds of nodes: clients,
application servers which process data for the clients and database servers which store data for
the application servers.

• This configuration is called three-tier architecture, and is the most commonly used type of client-
server architecture.

• Designs that contain more than two tiers are referred to as multi-tiered or n-tiered.

Fig.1.4 Multitier Architecture

Advantages

1. Reuse of components.

2. Easy and safe access to data and functions.

3. Different aspects of the application can be developed.

9
Middleware and Enterprise Integration Technologies

4. More scalable and maintainable.

5. Balance and distribute the processing load among multiple, often redundant, specialized
server nodes.

Disadvantages

1. More load on the network itself, due to a greater amount of network traffic.
2. More difficult to program and test than in two-tier architectures because more devices have
to communicate in order to complete a client’s request.

1.6 Types of Servers (Dec 2010) (10 Marks)

i. File Server

• File Servers are useful for sharing information across the network

• The client passes a request for file records over a network to the file server.

• This is the most primitive type of data service used for exchanging messages over the
network to find the requested data.

• The file servers provide access to the remote server processors. In the typical implementation
the software, shared data, databases and backups are stored on disk, tape and optical storage
devices that are managed by the file server.

Application

Application
File Calls
File Server

Fig.1.5 Client/Server with a File Server

10
Middleware and Enterprise Integration Technologies

ii. Database Server

• The client passes the SQL requests as messages to the database server; the result of each SQL
command is returned over the network.

• The code, which processes the SQL request and the data, reside in the same machine, the
server uses its own processing power to find the requested data back to the client, instead of
passing all the records back to the client. This results in a much more efficient use of the
distributed processing power.

• Note that the application code resides on the client; thus you must either write code for the
client or you can buy a shrink-wrap query tool.

• The database servers provide the foundation for decision-support systems and also provide
key role in data warehousing.

Application

SQL CALLS
Application DBMS Server

Fig.1.6 Client/Server with the Database Servers

iii. Transaction Servers

• The client can invoke remote procedure or services that reside on the server with an SQL
database engine using the transaction server.

• The network exchange consists of a single request/ reply. The SQL statements either all
succeeded or fail as a unit.

• These grouped SQL statements are called transactions.

• With a transaction server you create the client/server application by writing the code for both
the client and the server components.

11
Middleware and Enterprise Integration Technologies

• The client component usually includes a Graphical User Interface (GUI). The server
component consists of SQL transaction against a database. These applications are called
Online Transaction Processing or OLTP.

• The OLTP are mission-critical applications that require a very less response time (1-3 sec).

• The OLTP applications also require tight controls over the security and integrity of the
database.

• It has two forms

o TP-Lite: based on the stored procedures provided by database vendors.

o TP-Heavy: bases on the TP Monitors which is provided by OLTP vendors.

Application

TRANSACTIONS
Application
DBMS
TP Monitor

Fig.1.7 Client/Server with the Transaction Servers

iv. Groupware Servers

• It involves the management of semi-structured information such as text, image, mail, bulletin
boards and the flow of work.
• These client/server system places people in direct contact with other people. Best examples
are Lotus Notes and Microsoft Exchange.
• Specialized groupware software can be built on top of a vendor’s canned set of client/server
API’s. In many cases, applications are created using a scripting language and form-based
interfaces provided by the vendor. Now many groupware products use e-mail as their

12
Middleware and Enterprise Integration Technologies

standard messaging middleware. Also, Internet is quickly becoming the middleware platform
of choice for groupware.

Application

Groupware
Application Message
File Server

Fig.1.8 Client/Server with the Groupware Message Servers

v. Object Application Servers.

• The client/server application is written as a set of communicating objects with an object


server.

• The client object uses the Object Request Broker (ORB) to communicate with the server
objects.

• The ORB locates an instance of that object server class, invokes the requested method and
returns the results to the client object.

• The server objects must support the concurrency and sharing aspects. The ORB and a new
generation of CORBA application servers bring it all together.

13
Middleware and Enterprise Integration Technologies

• The commercial ORB’s that comply with the Object Management Group’s CORBA standard
include Iona’s Orbix, Inprise’s VisiBroker, ICL’s DAIS, JavaSoft’s Java IDL , BEA’s
ObjectBroker, IBM’s SOM and Expersoft’s PowerBroker.

• CORBA is also the basic foundation technology for the Enterprise JavaBeans component
model. The new generation CORBA application servers are also called as the Object
Transaction Monitors (OMTs) provide server-side component coordination services.

• Microsoft hat Distributed Component Object Model (DCOM) as an competitor for CORBA;
Where DCOM is the foundation technology for Microsoft’s enterprise software and also it s
ActiveX component model. The Microsoft Transaction Server (MTS) is the application
server for ActiveX components; it is also called as COM+.

vi. Web Application Server

• Web application servers are a new class of Internet software. They combine the standard
HTTP servers with server-side component frameworks. Functionally they are very similar to
the object servers.

• This model of the client/server consists of thin, portable, and “universal” client that talk to the
super fat servers. Here the Web server returns documents when clients ask for them by name.
The clients and the servers communicates using and RPC like protocol called HTTP, which
defines a simple set of commands, parameters which are passed as strings, with no provision
for typed data.

• In case of Microsoft, the MTS distributed object server is also the Web Application Server.
Whereas in case of CORBA/Java; Enterprise JavaBeans has become common currency of
Web Application servers.

• Some of these servers also provide the COM/CORBA bridges.

• The examples of the CORBA/Java Web application servers are Netscape /Kiva’s Application
Server, BEA’s WebLogic, Bluestone’s Sapphire Web, IBM’s WebSphere, SilverStream’s
SilverStream Application Server 2.0, Novera’s jBusiness Application Server etc.

--------------------------

University Questions

14
Middleware and Enterprise Integration Technologies

1. Mention and explain the different features of distributed computing environment. (June 2010)

2. List the issues to be considered in the design of distributed object systems. (Dec 2010)

3. Explain in detail the different types of client/server architecture with neat diagrams. (Dec 2010)

4. Write short note on: Types of Servers. (Dec 2010)

Chapter 2

Introduction to Middleware Technologies


2.1 Middleware

Middleware is computer software that connects software components or some people and their
applications. The software consists of a set of services that allows multiple processes running on one or
more machines to interact.
Middleware sits "in the middle" between application software that may be working on different operating
systems. It is similar to the middle layer of three-tier single system architecture, except that it is stretched
across multiple systems or applications.
Middleware generally consists of a library of functions, and enables a number of applications–simulations
or federates in high level architecture (HLA) to page these functions from the common library rather than
re-create them for each application.
Middleware does not include the software that provides the actual service that’s in the server’s domain. It
also does not include the user interface or the application’s logic that’s in the client’s domain. It starts

15
Middleware and Enterprise Integration Technologies

with the API set on the client side that is used to invoke a service, and it covers the transmission of the
request over the network and the resulting response.

Use of Middleware

Middleware services provide a more functional set of application programming interfaces to allow an
application to:
1. Locate transparently across the network, thus providing interaction with another service or
application
2. Filter data to make them friendly usable or public via anonymization process for privacy
protection (for example)
3. Be independent from network services
4. Be reliable and always available
5. Add complementary attributes like semantics when compared to the operating system and
network services.

2.2 Types of Middleware

Middleware divided into two broad classes:

(a) General Middleware


(b) Service-Specific Middleware

(a) General Middleware

• It is the substrate for most client/server interactions


• It includes the communication stacks, distributed directories, authentication stacks, distributed
directories, authentication services, network time, remote procedure calls, and queuing services.
• Products that fall into the general middleware category include DCE, ONC+, NetWare,
NamedPipes, LAN Server, LAN Manager, Vines, TCP/IP, APPC and NetBIOS.
• Message Oriented Middleware (MOM) products from Peerlogic, Covia, Message Express,
System Strategies and IBM.
• These are depends on message queue system and increases portability, interoperability,
flexibility.

(b) Service-Specific Middleware

• It is need to accomplish a particular client/server type of service.


• This includes
o Database-specific middleware such as ODBC, DRDA, EDA/SQL, SAG/CLI and Oracle
Glue allows direct access to data structures and provides interaction directly with
database. It also manages replication of database entities to enhance performance and
improve system reliability.
o OLTP-specific middleware such as Tuxedo’s ATMI and /WS, Encina’s Transactional
RPC, and X/Open’s TxRPC and XATMI consists of transaction processing (TP) monitors
which accepts transactions, queries it and then manages it. It also has the ability to
connect different DBMSs in a single transaction. This architecture is more scalable than
two-tier architecture.
o Groupware-specific middleware such as MAPI, VIM, VIC, SMTP and Lotus Notes
Calls involves the management of semi-structured information such as text, image, mail,

16
Middleware and Enterprise Integration Technologies

bulletin boards and the flow of work. These system places people in direct contact with
other people.
o Object-specific middleware such as OMG’s CORBA and Microsoft’s Network OLE (or
DCOM) facilitates reusability and interoperability of distributed objects.
o Internet-specific middleware such as HTTP, S-HTTP and SSLs helps in
communication over the Internet. It also defines how messages are formatted and
transmitted and what action Web Servers and browsers should take in response to various
commands.
o Communication-specific middleware such as Sun RPC, ONC RPC enable the logic of
an application to be distributed across the network.
o Message-Oriented middleware like Peerlogic and IBM’s MOM enables applications to
exchange messages with each other irrespective of different operating system and
processors.
o Work-flow management middleware focuses on the management of activity flow in the
client/server system.

2.3 Distributed Computing Environment

In network computing, DCE (Distributed Computing Environment) is an industry-standard


software technology for setting up and managing computing and data exchange in a system of
distributed computers. DCE is typically used in a larger network of computing systems that
include different size servers scattered geographically. DCE uses the client/server model. Using
DCE, application users can use applications and data at remote servers. Application programmers
need not be aware of where their programs will run or where the data will be located.

Much of DCE setup requires the preparation of distributed directories so that DCE applications
and related data can be located when they are being used. DCE includes security support and
some implementations provide support for access to popular databases such as IBM's CICS, IMS,
and DB2 databases.

DCE was developed by the Open Software Foundation (OSF) using software technologies
contributed by some of its member companies.

In computer data transmission, DCE (Data Communication Equipment) is the RS-232C interface
that a modem or other serial device uses in exchanging data with the computer.

2.3.1 Goals of DCE:

1. Can run on many different computers, operating systems (Unix, Os/2, VMS,windows) and
networks in a distributed system, Provide a coherent seamless platform for running distributed
applications.

2. Provide a mechanism for synchronizing clocks on different machines.

17
Middleware and Enterprise Integration Technologies

3. Provide tools to make it easier to write distributed applications in which multiple users at multiple
locations can work together.

4. Provide extensive tools for authentication and access protection.

2.3.2 DCE Architecture

Fig. 2.1 DCE Architecture

• DCE cell: It is the basic unit of operation in the DCE. A cell is a group of users, systems, and
resources that are typically centered on a common purpose and that share a common DCE
services. It is an administrative domain that allows users, machines, and resources to be managed
through functions distributed within the network in which they are in. Members working on the
same project in an organization are likely belonging to the same cell.

• DCE thread package: It is a collection of user-level library procedures that allow processes to
create, delete, and manipulate threads. Multiple tasks could occur at the same time to complete a
process (work). It is designed to minimize the impact on the existing software: a single threaded
program can be converted into multithreaded one by setting parameter indicating that more
threads will be used. All threads in a process share the same address space, file system, and other
process resources. Each thread has its own program counter, stack, and registers.

• RPC: DCE is based on the client/server model. RPC package of DCE allows a client process to
call a procedure on a remote computer. It allows application programmer to extend the local
procedure call to a distributed environment. The application programmer doesn’t have to be
concerned with the detail of the network communications between client and server nodes. RPC
hides communication detail and removes system and hardware dependencies. It can
automatically handle data type conversions between the client and the server without considering
whether they run on the same or different architecture, or have same or different byte ordering.

• DCE directory service: Provide up-to-date addressing information by keeping track of where all
resources (user, machine, file, server…) are located. So users can identify these resources by
names and gain access to them without needing to know where they are located. It’s distributed

18
Middleware and Enterprise Integration Technologies

service because the information that forms database is stored in different places. It’s also a
replicated service because the information is replicated and stored in more than one location
which make it more readily available
• Time Service: It enables distributed applications on different computers to determine event
sequencing, duration, and scheduling. It keeps clocks on separate computers participating in
distributed system synchronization. It uses universal coordinated time(UTC) to synchronize DCE
host’s time.

• Security Service: It controls interactions between clients and servers. It allows client and servers
to authenticate each other and perform authenticated RPC. It offers integrity and privacy of
communications without having password appearing on the network. It controls access to
resources by authorization;

• Distributed File Service: It’s a worldwide distributed file system. It allows users to access and
share files stored on a file server anywhere on the network without knowing the physical location
of the file. The physical file system (DCE local file system) is able to do several tasks: Replicate
data; log file system data, enable quick recovering after a crash; Simple administration by
dividing the file system into easily managed units; Associate access control list with files and
directory.

2.3.3 Advantages of DCE:


1. The services provided by DCE is much easier to use than the ones found in other computer
networking environments: i.e.: the DCE remote procedure call provide a much simpler way for
communicating between software modules running on different system than using socket calls.
2. The DCE security service provides a reliable way to determine if a user in a distributed system
should be allowed to perform certain action.
3. Supports portability and interoperability by hiding differences among the various hardware,
software, and networking elements in a large network.
4. Supports distributed file service which means files present on workstation in a network are
available to this network.

2.4 Client/ Server Building Blocks

Client server is network architecture which separates a client (often an application that uses a graphical
user interface) from a server. Each instance of the client software can send requests to a server. Specific
Types of servers include application servers, file servers, terminal servers, and mail servers. While their
purpose varies somewhat, the basic architecture remains the same.

Although this idea is applied in a variety of ways, on many different kinds of applications, the easiest
example to visualize is the current use of web pages on the internet. For example, if you are reading this
article on Wikipedia, your computer and web browser would be considered a client, and the computers,
databases, and applications that make up Wikipedia would be considered the server. When your web
browser requests a particular article from Wikipedia, the Wikipedia server finds all of the information
required to display the article in the Wikipedia database, assembles it into a web page, and sends it back
to your web browser for you to look at.

Characteristics of a server:

19
Middleware and Enterprise Integration Technologies

• Passive (slave)
• Waits for requests
• Upon receipt of requests, processes them and then serves replies

Characteristics of a client:

• Active (master)
• Sends requests
• Waits for and receives server replies

Servers can be stateless or stateful. A stateless server does not keep any information between requests. A
stateful server can remember information between requests. The scope of this information can be global
or session. A HTTP server for static HTML pages is an example of a stateless server while Apache
Tomcat is an example of a stateful server.

The interaction between client and server is often described using sequence diagrams. Sequence diagrams
are standardized in the UML.

Fig 2.2 Client/ Server Building Blocks

The Client Building Block

• Runs the client side of the application

• It runs on the OS that provides a GUI or an OOUI and that can access distributed services,
wherever they may be.

• The client also runs a component of the Distributed System Management (DSM) element.

The Server Building Block

• Runs the server side of the application

• The server application typically runs on top of some shrink-wrapped server software package.

20
Middleware and Enterprise Integration Technologies

• The five contending server platforms for creating the next generation of client/server applications
are SQL database servers, TP Monitors, groupware servers, Object servers and the Web server.

• The server side depends on the OS to interface with the middleware building block.

• The server also runs DSM component

• It may be a simple agent or a shared object database etc.

The Middleware Building Block

• Runs on both the client and server sides of an application

• This broken into three category

o Transport Stacks

o NOS

o Service-specific middleware

• Middleware is the nervous system of the client/server infrastructure

• This also has the DSM component.

DSM

• Runs on every node in the client/server network.

• A managing workstation collects information from all its agents on the network and displays it
graphically.

• The managing workstation can also instruct its agents to perform actions on its behalf.

Server-to-server Middleware

• Server-to-server interactions are usually client/server in nature – servers are clients to other
servers.

• However, some server-to-server interactions require specialized server middleware. For example,
Two-Phase commit protocol may be used to coordinate a transaction that executes on multiple
servers.

• Servers on mail backbone will use special server-to-server middleware for doing store-and-
forward type messaging.

21
Middleware and Enterprise Integration Technologies

• But most modern software follows the client/server paradigm.

2.4.1 Fat / Thick Client

1. Fat-client computing refers to a multi-tier client server paradigm where (in the simplest model)
the client part of the application (i.e., those programs used by the end-user) execute on the
desktop PC and the server part of the application (i.e., those programs used to drive the relational
database) reside on a single server together with the application code.

2. Fat-client computing requires a relatively low power server because the bulk of the processing is
done on the desktop PCs.

3. In the case of a Fat-client Application the bulk of the processing is done by the desktop PCs.

4. In a Fat-client Application processing power is decentralized; the environment is not single-point


sensitive.

5. In a Fat-client Application we can make do with a relatively small and unsophisticated server.

2.4.2 Thin Client

1. Thin-client computing refers to multi-tier client server paradigm where the client (end-user)
programs display in a browser (such as Internet Explorer or Netscape) but the execution of that
user code takes place on a central web server, not at the desktop PC.

2. Thin-client computing requires a high power server because it has to do all of the work previously
done by desktop PCs.

3. In the case of the Thin-client Application the bulk of the processing is done by the web server.

4. In a Thin-client Application processing power is centralized and we are single point sensitive.

5. In a Thin-client Application we must have a relatively large and complex server.

2.5 Remote Procedure Call (Dec 2010) (10 Marks)

RPC is a powerful technique for constructing distributed, client-server based applications. It is based on
extending the notion of conventional or local procedure calling, so that the called procedure need not exist
in the same address space as the calling procedure. The two processes may be on the same system, or they
may be on different systems with a network connecting them. By using RPC, programmers of distributed
applications avoid the details of the interface with the network. The transport independence of RPC
isolates the application from the physical and logical elements of the data communications mechanism
and allows the application to use a variety of transports.

RPC makes the client/server model of computing more powerful and easier to program. When combined
with the ONC RPCGEN protocol compiler clients transparently make remote calls through a local
procedure interface.

22
Middleware and Enterprise Integration Technologies

2.5.1 How RPC Works

An RPC is analogous to a function call. Like a function call, when an RPC is made, the calling arguments
are passed to the remote procedure and the caller waits for a response to be returned from the remote
procedure. Fig. 2.3 shows the flow of activity that takes place during an RPC call between two networked
systems. The client makes a procedure call that sends a request to the server and waits. The thread is
blocked from processing until either a reply is received, or it times out. When the request arrives, the
server calls a dispatch routine that performs the requested service, and sends the reply to the client. After
the RPC call is completed, the client program continues. RPC specifically supports network applications.

Fig. 2.3 Remote Procedure Call Mechanism

2.5.2 Communication Model using RPC

ONC RPC is used to implement client/server model. It is easier to program than sockets. When
the client process makes call to the remote function, the following steps are executed to complete
the RPC (Fig. 2.4)

1. Client procedure calls client stub using a local procedure call. Conceptually, a client stub contains
a set of function with the same name as the remote function. This function has the code that sends
a request message to the server containing the actual parameters to the remote function, waits till
it receives the reply, read the reply and result. Stubs can be generates automatically using stub
compilers such as rpcgen. The stub is included in the code during compilation.

23
Middleware and Enterprise Integration Technologies

2. The client stub calls the network routines using system calls. It includes preparing the message
buffer, packing parameters into buffer, building the message and issuing the send request to the
kernel.

3. In this step, the local kernel sends the message to the remote kernel. The process is performed by
the kernel. The message is copied onto the kernel and the destination address is determined. Then
the network interface is set up and a timer is started for re-transmission of the message.

4. Once the message is successfully received by the remote kernel, it is transferred to the server stub
using system calls. The packet is initially checked for validity and then the stub to which the
message is to be sent is determined. If the stub is waiting, then the message is copied onto the
server stub.

5. Once the control is handed to the server stub, it unpacks the parameters and calls the server
procedure. This process is called unmarshalling.

6. The server does the process and returns the results to the server stub.

7. The server stub then packs the results in a message and sends it to the kernel.

8. The server’s kernel then transmits the results to the client’s kernel.

9. The client’s kernel then gives the result to the client stub.

10. The client stub unpacks the results and returns them to the client procedure.

24
Middleware and Enterprise Integration Technologies

Fig. 2.4 RPC Model

2.5.3 Advantages of RPC

• Server independent
• Process-oriented and thread oriented models supported by RPC
• The development of distributed systems is simple because it uses straightforward semantics and
easier.
• Like the common communications between the portions of an application, the development of the
procedures for the remote calls is quite general.
• The procedure calls preserves the business logics which is apt for the application.
• The code re-writing / re-developing effort is minimized.
• Enables the usage of the applications used in the distributed environment, not only in the local
environment.

2.5.4 Disadvantages of RPC

• Context switching increases scheduling costs


• RPC is not a standard – it is an idea that can be implemented in many ways
• RPC does not solve the most of the distribution creation problems
• RPC is only interaction based. This does not offer any flexibility in terms of hardware
architecture.

2.6 Messaging : The MOM Middleware (Dec 2010) (10 Marks)

25
Middleware and Enterprise Integration Technologies

• MOM is a key piece of middleware that is absolutely essential for a class of client/server
products.
• Message oriented middleware (MOM) is inherently loosely coupled, asynchronous technology.
• Message queuing implements an indirect, connectionless, asynchronous communication link
between two or more processes.
• A queue manager running on a separate sever manages the queues and ensures that no matter
what happens to the network, only one copy of the message eventually arrives at the
destination.
• If the application can tolerate a certain level of time-independent responses, MOM provides the
easiest path for creating enterprise and inter-enterprise client/server systems.
• This accumulates outgoing transactions in queue and do a bulk upload when a connection can be
established with an office server.
• MOM allows general purpose messages to be exchanged in a client/server system using message
queues.
• Applications communicate over networks by simply putting messages in queues and getting
messages from queues.
• MOM hides all the nasty communications from applications and typically provides a very simple
high-level of API to its services.
• A MOM consortium was formed in mid-1993 with the goal of creating standards for messaging
middleware.
• Members are product providers including
o IBM – MQSeries
o Covia – Communications Integrator
o Peerlogic – PIPES
o Horizon Strategies – Message Express
o System Strategies – ezBridge
• MOM’s messaging and queuing allows clients and servers to communicate across a network
without being linked by a private, dedicated, logical connection.
• The clients and servers can run at different times.
• Everybody communicates by putting messages on queues and by taking messages from queues.

Fig.2.5 Messages in Queue

• MOM products provide their own NOS services – including hierarchical naming, security, and a
layer that isolates applications from the network.
• They use virtual memory on the local OS to create their queues.
• Most messaging products allow the sender to specify the name of the reply queue.

26
Middleware and Enterprise Integration Technologies

• The products also include some type of format field that tells the recipient how to interpret the
message data.
• MOM enabled programs do not talk to each other directly, so either program can be busy,
unavailable, or simply not running at the same time.
• The target program can even be started several hours later.

Fig.2.6 Messages Processed after several hours

• Many clients are sending requests to one server queue.


• The messages are picked off the queue by multiple instances of the server program that are
concurrently servicing the clients.
• The server instances can take messages off the queue either on a FIFO basis or accounting to
some priority to load-balancing scheme.
• The message queue can be concurrently accessed.
• The servers can also use messaging filters to throw away the messages they don’t want to
process, or they can pass them on to other servers.
• The MOM messaging products provide persistent (logged on disk) and non-persistent (in
memory) message queues.
• Persistent messages are slower, that they can be recovered in case of power failures after a system
restart.
• A message queue can be local to the machine or remote.
• System administrators can usually specify the number of messages a queue can hold and the
maximum message size.

27
Middleware and Enterprise Integration Technologies

Fig. 2.4 MOM Message Queue

There are a number of key differences between message queuing and other types of middleware:

• Queues have names.


• Queues are independent of a process. Thus, many processes can put messages into the same
queue or get messages from the same queue. A process can also access multiple queues.
• If the network goes down or a destination goes down, the messages can wait in the queue until the
network comes up again.
• Queues can be stored on disk so that if the queue manager goes down, the queue is not lost.
• The queue manager can co-operate with a transaction manager. This means that if a transaction is
started and a message is put into a queue during the transaction which is later aborted, then not
only is the database rolled back, but the message is taken out of the queue and not sent.

The communication between the client and server sides of the application is as follows (Fig.2.5):

1. Client side of the application starts the communication. It attaches itself to two
communication queues. This is done using the operations provided by the communication
bus. These message queues access the communication bus.
2. The client side of the application puts the message into its output queue. This message
contains the information to be sent and address of the destination queue. From now, the
message is taken care of by the middleware and the client side of the application can
continue with its own processing.
3. The middleware program then reads the message from the source queue and transfers it to
the destination queue across the network.
4. Once the server side of the application is active, it attaches itself to its source and
destination queues and waits for incoming messages.
5. Once a message is available in its input queue, the server reads the messages from its
input queue.

28
Middleware and Enterprise Integration Technologies

6. The server then processes the messages and returns the result to the client side of the
application.
7. The server side puts the result message in its output queue.
8. The middleware picks up this message and transfers it to the input queue on the client
side.
9. The client side of the application then reads the message from its queue.

Fig.2.5 Message queue communication protocol

2.6.1 Advantages of MOM

• Provides reliable once-only delivery of messages.

• Processes communicate asynchronously with no direct connection between them.

• Allows applications to run independently.

29
Middleware and Enterprise Integration Technologies

2.6.2 Disadvantages of MOM

• There is no interface definition language and no marshalling and demarshalling of message


contents. It is up to the application developer to ensure that the sender and receiver know the
message format.
• Since clients do not block after a message is put into the queue, clients can make requests faster
than servers can respond to the requests which can overload the system.

2.6.3 Comparison of MOM Vs RPC (June 2010)(10 Marks)

Table 2.1 MOM Vs RPC


Feature MOM RPC
Metaphor Post-office like Telephone like
Client/Server time Asynchronous. Clients and Synchronous. Clients and Servers
relationship Servers may operate at different must run concurrently. Servers
times and speeds must keep up with clients.
Client/Server No fixed sequence Servers must first come up
Sequencing before clients can talk to them.
Style Queued Call-Return
Partners need to No Yes
be available
Load-balancing Single queue can be used to Requires a separate TP Monitor.
implement FIFO or priority
based policy
Transactional Yes (Some Products) Message No. Requires a Transactional
Support Queue can participate in the RPC.
commit synchronization
Message Filtering Yes No
Performance Slow. An intermediate hop is Fast
required
Asynchronous Yes. Queues and triggers are Limited. Requires threads and
processing required tricky code for managing threads

2.7 Peer-to-Peer (P2P) Communications

Peer-to-peer systems allow users to share resources and files located on their computers and to access
shared resources found on other computers. However, they do not have a file server or a centralized
management source (See Fig. 2.7).

30
Middleware and Enterprise Integration Technologies

Fig.2.7 Peer-to-peer network

In a peer-to-peer network, all computers are considered equal; they all have the same abilities to use
the resources available on the network. Peer-to-peer networks are designed primarily for small to
medium local area networks. AppleShare and Windows for Workgroups are examples of programs
that can function as peer-to-peer network operating systems.

2.7.1 Advantages of a peer-to-peer network:

• Less initial expense - No need for a dedicated server.

• Setup - An operating system (such as Windows XP) already in place may only need to be
reconfigured for peer-to-peer operations.

2.7.2 Disadvantages of a peer-to-peer network:

• Decentralized - No central repository for files and applications.

• Security - Does not provide the security available on a client/server network.

2.7.3 Examples of P2P Protocols:

1. Unix Sockets

2. Novell Netware

3. IBM’s NetBIOS

4. Named Pipes

2.7.4 Sockets

Normally, a server runs on a specific computer and has a socket that is bound to a specific port number.
The server just waits, listening to the socket for a client to make a connection request.

31
Middleware and Enterprise Integration Technologies

On the client-side: The client knows the hostname of the machine on which the server is running and the
port number on which the server is listening. To make a connection request, the client tries to rendezvous
with the server on the server's machine and port. The client also needs to identify itself to the server so it
binds to a local port number that it will use during this connection. This is usually assigned by the system.

Fig. 2.8 Connection Request

If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket
bound to the same local port and also has its remote endpoint set to the address and port of the client. It
needs a new socket so that it can continue to listen to the original socket for connection requests while
tending to the needs of the connected client.

Fig. 2.9 Connection Established

On the client side, if the connection is accepted, a socket is successfully created and the client can
use the socket to communicate with the server.

The client and server can now communicate by writing to or reading from their sockets.

Definition: A socket is one endpoint of a two-way communication link between two programs
running on the network. A socket is bound to a port number so that the TCP layer can identify the
application that data is destined to be sent.

An endpoint is a combination of an IP address and a port number. Every TCP connection can be
uniquely identified by its two endpoints. That way you can have multiple connections between your
host and the server.

The java.net package in the Java platform provides a class, Socket, that implements one side of a
two-way connection between your Java program and another program on the network. The Socket
class sits on top of a platform-dependent implementation, hiding the details of any particular system

32
Middleware and Enterprise Integration Technologies

from your Java program. By using the java.net.Socket class instead of relying on native code, your
Java programs can communicate over the network in a platform-independent fashion.

Additionally, java.net includes the ServerSocket class, which implements a socket that servers can
use to listen for and accept connections to clients. This lesson shows you how to use the Socket and
ServerSocket classes.

2.7.5 Client/Server Communication with Connection-Oriented Protocol using Sockets

(June 2010) (10 Marks)

The communication between client and server with connection-oriented protocol using sockets is
illustrated using the interaction diagram in Fig.2.10. The system calls shown in the figure are
explained as below.

1. socket: This call creates an entry in the object/file description table to allow I/O based on file
descriptors. It then returns the index in object description table.

2. bind: This call determines the local address and local process. It assigns a name to an
unnamed socket. It informs the system of its address, so that messages sent to this address are
dispatched to the process.

3. listen: It sets queue length for client processes waiting to connect to the socket.

4. accept: It waits for another process to connect to this socket after creating another file
descriptor for actual communication with client to read and write data.

5. connect: Using this call, the client tries to connect to a waiting server process through the
socket created.

6. write: Once the client is connected to the server, it passes input to the server and waits for the
reply.

7. process: The server processes it and sends the output to the client.

8. read: The client reads the output.

33
Middleware and Enterprise Integration Technologies

Fig. 2.10 Client/Server interaction in connection-based protocol.

2.7.6 Client/Server Communication with Connectionless Protocol using Sockets

The communication between client and server with connectionless protocol using sockets is
illustrated using the interaction diagram in Fig.2.11. The system calls shown in the figure are
explained as below.

1. socket: This call creates an entry in the object/file description table to allow I/O based on file
descriptors. It then returns the index in object description table.

2. bind: This call determines the local address and local process. It assigns a name to an
unnamed socket. It informs the system of its address, so that messages sent to this address are
dispatched to the process.

3. recvfrom: This call is used receive request/replies.

4. sendto: This call is used to send replies/request. Once the client is connected to the server, it
passes input to server and waits for the reply.

5. process: The server processes the input and sends the output to the client.

34
Middleware and Enterprise Integration Technologies

6. read: The client reads the output.

Fig.2.11 Client/Server interaction in connectionless protocol

2.8 Java RMI (Dec 2010) (10 Marks)

A remote method invocation from a client to a remote server object travels down through the layers of the
RMI system to the client-side transport, then up through the server-side transport to the server. A client
invoking a method on a remote server object actually makes use of a stub or proxy for the remote object
as a conduit to the remote object. A client-held reference to a remote object is a reference to a local stub.
This stub is an implementation of the remote interfaces of the remote object and forwards invocation
requests to that server object via the remote reference layer.

Java RMI is comprised of three layers that support the interface as shown in Fig.2.12.

35
Middleware and Enterprise Integration Technologies

Fig. 2.12 RMI Architecture

The Stub/Skeleton Layer

The stub/skeleton layer is the interface between the application layer and the rest of the RMI system. This
layer does not deal with specifics of any transport, but transmits data to the remote reference layer via the
abstraction of marshal streams. Marshal streams employ a mechanism called object serialization which
enables Java objects to be transmitted between address spaces. Objects transmitted using the object
serialization system are passed by copy to the remote address space, unless they are remote objects, in
which case they are passed by reference.

The Remote Reference Layer

The remote reference layer deals with the lower level transport interface. This layer is also responsible for
carrying out a specific remote reference protocol which is independent of the client stubs and server
skeletons. Each remote object implementation chooses its own remote reference subclass that operates on
its behalf. Various invocation protocols can be carried out at this layer, for example:

• Unicast point-to-point invocation.

• Invocation to replicated object groups.

• Support for a specific replication strategy.

• Support for a persistent reference to the remote object (enabling activation of the remote
object).

• Reconnection strategies (if remote object becomes inaccessible).

The remote reference layer has two cooperating components: the client-side and the server-side
components. The client-side component contains information specific to the remote server (or servers, if
the remote reference is to a replicated object) and communicates via the transport to the server-side
component. During each method invocation, the client and server-side components perform the specific

36
Middleware and Enterprise Integration Technologies

remote reference semantics. For example, if a remote object is part of a replicated object, the client-side
component can forward the invocation to each replica rather than just a single remote object.

The Transport Layer

In general, the transport layer of the RMI system is responsible for:

• Setting up connections to remote address spaces.

• Managing connections.

• Monitoring connection "liveness."

• Listening for incoming calls.

• Maintaining a table of remote objects that reside in the address space.

• Setting up a connection for an incoming call.

• Locating the dispatcher for the target of the remote call and passing the connection to
this dispatcher.

The concrete representation of a remote object reference consists of an endpoint and an object identifier.
This representation is called a live reference. Given a live reference for a remote object, a transport can
use the endpoint to set up a connection to the address space in which the remote object resides. On the
server side, the transport uses the object identifier to look up the target of the remote call.

The process of RMI is done using the following steps as shown in Fig. 2.13. When the client process
makes call to the remote function, the following steps are executed to complete the RPC:

1. The Remote object, which is willing to provide the service, registers in the RMI registry. RMI
registry has details of the remote object name and remote object reference.

2. The client refers the RMI registry using object name.

3. The RMI registry returns the OR of the remote object.

4. Client procedure calls client stub using a local procedure call. Conceptually, a client sub contains
a set of functions with the same name as the remote function. This function has the code that
sends a request message to the server containing the actual parameters to the remote function,
waits till it receives the replay, reads the replay and returns the results. Stubs can be generated
automatically using the stub compilers like rmic (RMI compiler) and are included in code during
compilation.

5. The client stub calls the network routines using system calls. It includes preparing the message
buffer, packing parameters into buffer, building the message and issuing the second request to the
kernel.

37
Middleware and Enterprise Integration Technologies

6. In this step, the local kernel sends the message to the remote kernel. The message is copied onto
the kernel and the destination address is determined. Then the network interface is set up and a
timer is started for re-transmission of the message.

7. Once he message is successfully received by the remote kernel, it is transferred to the RRL. The
packet is initially checked for validity and then the tub and RRL to which the message is to be
sent are determined.

8. RRL then transfer the call to the server stub using system calls. If the stub is waiting then the
message is copied onto the server stub.

9. Once the control is handed to the server stub, it unpacks the parameters and calls the server
procedure. This process is called as Unmarshalling.

10. Server does the work and returns the result to the server stub.

11. The server stub then packs the results in message to RRL.

12. RRL contacts the request-replay protocol layer.

13. The server kernel then transmits the results to the client kernel.

14. The client kernel gives the results to the client stub.

15. The client stub unpacks the results and returns them to the client procedure.

38
Middleware and Enterprise Integration Technologies

Fig. 2.13 Remote Method Invocation

Advantages of RMI

• Simple and clean to implement that leads to more robust, maintainable and flexible applications
• Distributed systems creations are allowed while decoupling the client and server objects
simultaneously
• It is possible to create zero-install client for the users.
• No client installation is needed except java capable browsers
• At the time of changing the database, only the server objects are to be recompiled but not the
server interface and the client remain the same.

Disadvantages of RMI

• Less efficient than Socket objects.


• Assuming the default threading will allow ignoring the coding, being the servers are thread- safe
and robust.
• Cannot use the code out of the scope of java.

39
Middleware and Enterprise Integration Technologies

• Security issues need to be monitored more closely


Lab Experiments on RMI
1. Program to print Hello, From IT Department

Step 1: Implement the interface as HelloInterface.java

import java.rmi.*;
public interface HelloInterface extends Remote
{
public String say() throws RemoteException;
}

Step 2: Implement the class for interface as Hello.java

import java.rmi.*;
import java.rmi.server.*;

public class Hello extends UnicastRemoteObject implements HelloInterface {


private String message;
public Hello (String msg) throws RemoteException {
message = msg;
}
public String say() throws RemoteException {
return message;
}
}

Step 3: Implement the RMI Server as HelloServer.java

import java.rmi.Naming;
public class HelloServer
{
public static void main (String[] argv)
{
try {
Naming.rebind ("Hello", new Hello ("Hello, From IT Department!"));
System.out.println ("Server is connected and ready for operation.");
}
catch (Exception e) {
System.out.println ("Server not connected: " + e);
}
}
}

Step 4: Implement the RMI Client as HelloClient.java

import java.rmi.Naming;
public class HelloClient
{

40
Middleware and Enterprise Integration Technologies

public static void main (String[] argv) {


try {
HelloInterface hello =(HelloInterface) Naming.lookup ("//127.0.0.1/Hello");
System.out.println (hello.say());
}
catch (Exception e){
System.out.println ("HelloClient exception: " + e);}
}
}

Execution Steps:

1. Now, open the command prompt and compile the above four java files as:
C:\Program Files\Java\jdk1.6.0_04\bin>javac HelloInterface.java
C:\Program Files\Java\jdk1.6.0_04\bin>javac Hello.java
C:\Program Files\Java\jdk1.6.0_04\bin>javac HelloServer.java
C:\Program Files\Java\jdk1.6.0_04\bin>javac HelloClient.java
2. Now use rmic to create the stub and skeleton class files.
rmic Hello
3. Start RMI Registry in command prompt as:
start rmiregistry
You will see one window popped up.
4. Now execute in command prompt HelloServer.java as:
C:\Program Files\Java\jdk1.6.0_04\bin>java HelloServer
You will get output as
Server is connected and ready for operation.

5. Then execute in other command prompt HelloClient.java as:

C:\Program Files\Java\jdk1.6.0_04\bin>java HelloClient

You will get output as:

Hello, From IT Department!

2. Program for Calculator Operations

Step 1: Implement the interface as Calculator.java

public interface Calculator extends java.rmi.Remote


{
public long add(long a, long b)
throws java.rmi.RemoteException;

public long sub(long a, long b)


throws java.rmi.RemoteException;

public long mul(long a, long b)


throws java.rmi.RemoteException;

41
Middleware and Enterprise Integration Technologies

public long div(long a, long b)


throws java.rmi.RemoteException;
}

Step 2: Implement the class for interface as CalculatorImpl.java

public class CalculatorImpl extends java.rmi.server.UnicastRemoteObject implements Calculator


{

// Implementations must have an explicit constructor in order to declare the RemoteException


//exception
public CalculatorImpl() throws java.rmi.RemoteException {
super();
}

public long add(long a, long b) throws java.rmi.RemoteException {


System.out.println ("Adding " + a + " and " + b);
return a + b;
}

public long sub(long a, long b) throws java.rmi.RemoteException {


System.out.println ("Subtracting " + b + " from " + a);
return a - b;
}

public long mul(long a, long b) throws java.rmi.RemoteException {


System.out.println ("Multiplying " + a + " by " + b);
return a * b;
}

public long div(long a, long b) throws java.rmi.RemoteException {


System.out.println ("Dividing " + a + " by " + b);
return a / b;
}
}

Step 3: Implement the RMI Server as CalculatorServer.java

import java.rmi.Naming;

public class CalculatorServer {

public CalculatorServer() {
try {
Calculator c = new CalculatorImpl();
Naming.rebind("rmi://localhost:1099/CalculatorService", c);
} catch (Exception e) {
System.out.println("Trouble: " + e);
}

42
Middleware and Enterprise Integration Technologies

public static void main(String args[]) {


new CalculatorServer();
}
}

Step 4: Implement the RMI Client as CalculatorClient.java

import java.rmi.Naming;
import java.rmi.RemoteException;
import java.net.MalformedURLException;
import java.rmi.NotBoundException;

public class CalculatorClient {

public static void main(String[] args) {

// determine the machine of the server


if (args.length == 0)
serverName = "127.0.0.1";
else
serverName = args[0];
String rmiName = "rmi://" + serverName + "/CalculatorService");

System.out.println ("Connecting to: " + rmiName);

try {
Calculator c = (Calculator) Naming.lookup(rmiName);
// "rmi://localhost/CalculatorService");

System.out.println( c.sub(4, 3) );
System.out.println( c.add(4, 5) );
System.out.println( c.mul(3, 6) );
System.out.println( c.div(9, 3) );
}
catch (MalformedURLException murle) {
System.out.println();
System.out.println("MalformedURLException");
System.out.println(murle);
}
catch (RemoteException re) {
System.out.println();
System.out.println("RemoteException");
System.out.println(re);
}
catch (NotBoundException nbe) {
System.out.println();
System.out.println("NotBoundException");
System.out.println(nbe);

43
Middleware and Enterprise Integration Technologies

}
catch (
java.lang.ArithmeticException ae) {
System.out.println();
System.out.println("java.lang.ArithmeticException");
System.out.println(ae);
}
}
}

Execution Steps:

1. Now, open the command prompt and compile the above four java files as:
C:\Program Files\Java\jdk1.6.0_04\bin>javac Calculator.java
C:\Program Files\Java\jdk1.6.0_04\bin>javac CalculatorImpl.java
C:\Program Files\Java\jdk1.6.0_04\bin>javac CalculatorServer.java
C:\Program Files\Java\jdk1.6.0_04\bin>javac CalculatorClient.java
2. Now use rmic to create the stub and skeleton class files.
rmic CalculatorImp
3. Start RMI Registry in command prompt as:
start rmiregistry
You will see one window popped up.
4. Now execute in command prompt HelloServer.java as:
C:\Program Files\Java\jdk1.6.0_04\bin>java CalculatorServer
5. Then execute in other command prompt HelloClient.java as:

C:\Program Files\Java\jdk1.6.0_04\bin>java CalculatorClient

You will get output as:


1
9
18
3

--------------------------

University Questions
1. Explain with neat labeled diagram the working of connection oriented protocol using
Sockets. (June 2010)
2. Differentiate Remote Procedure Method and Message Oriented Messaging. (June 2010)
3. State the characteristics of RPC middleware. Explain RPC mechanism.(Dec 2010)
4. Explain the process of RMI using stubs/proxy/skeletons. (Dec 2010)
5. Write short note on: Message Queues .(Dec 2010)

44
Middleware and Enterprise Integration Technologies

Chapter 3

Introduction to Distributed Objects

3.1 Computing Standards

A distributed computing system consists of a number of computers that are connected and managed so
that they automatically share the job processing load among themselves. There are various computing
standards that coordinate the execution of data processing tasks by message sent through a
communication system.

These standards are as follows:


1. ORB developed by OMG consortium
2. CORBA developed by OMG consortium.
3. COM and DCOM developed by Microsoft.
4. RMI application developed by Sun.

3.2 OMG

The Object Management Group, Inc. (OMG) is an international organization supported by over 800
members, including information system vendors, software developers and users. In 1989, this consortium,
which included IBM Corporation, Apple Computer Inc. and Sun Microsystems Inc., mobilized to create a
cross-compatible distributed object standard. The OMG promotes the theory and practice of object-
oriented technology in software development. The organization's charter includes the establishment of
industry guidelines and object management specifications to provide a common framework for
application development. Primary goals are the reusability, portability, and interoperability of object-
based software in distributed, heterogeneous environments. Conformance to these specifications will
make it possible to develop a heterogeneous applications environment across all major hardware
platforms and operating systems.

OMG specifications include

• Business Process Modeling Notation (BPMN) specification provides a graphical


notation for expressing business processes in a Business Process Diagram (BPD). The
BPMN specification also provides a binding between the notation's graphical elements
and the constructs of block-structured process execution languages, including BPML and
BPEL4WS.
• CORBA is the acronym for Common Object Request Broker Architecture. It was
developed under the auspices of the Object Management Group (OMG). It is middleware.
A CORBA-based program from any vendor, on almost any computer, operating system,
programming language, and network, can interoperate with a CORBA-based program
from the same or another vendor, on almost any other computer, operating system,
programming language, and network.
The first service-oriented architecture for many people in the past was with the use of
Object Request Brokers (ORBs) based on the CORBA specification. The CORBA
specification is responsible for really increasing the awareness of service-oriented
architectures.

45
Middleware and Enterprise Integration Technologies

• The Meta-Object Facility (MOF) is a set of standard interfaces that can be used to
define and manipulate a set of interoperable meta-models and their corresponding
models.
The MOF is intended to support a range of usage patterns and applications. To
understand the possible usage patterns for the MOF, you need to understand is the two
viewpoints for the MOF:

a. Modeling viewpoint: The designer's viewpoint, looking "down" the meta levels.
From the modeling viewpoint, the MOF is used to define an information model
for a particular domain of interest. This definition is then used to drive
subsequent software design and/or implementation steps for software connected
with the information model.
b. Data viewpoint: The programmer's viewpoint, looking at the current meta-level,
and possibly looking up at the higher meta-levels. From the data viewpoint, the
MOF (or more accurately, a product of the MOF) is used to apply the OMA-
based distributed computing paradigm to manage information corresponding to a
given information model. In this mode, it is possible for a CORBA client to
obtain the information model descriptions and to use them to support reflection.

The MOF specification is intended to provide an open-ended information modeling


capability. The specification defines a core MOF model that includes a relatively small
set of constructs for object-oriented information modeling. The MOF model can be
extended by inheritance and composition to define a richer information model that
supports additional constructs. Alternatively, the MOF model can be used as a model for
defining information models. This feature allows the designer to define information
models that differ from the philosophy or details of the MOF model. In this context, the
MOF Model is referred to as a meta-metamodel because it is being used to define
metamodels such as the UML.

• The Model Driven Architecture (MDA) is an open, vendor-neutral approach to


interoperability using OMG's modeling specifications: Unified Modeling Language
(UML), Meta-Object Facility (MOF), and Common Warehouse Meta-model (CWM).

As new platforms and technologies emerge, MDA enables rapid development of new
specifications that use them, streamlining the process of integration. The intent of MDA
is to provide a comprehensive, structured solution for application interoperability and
portability into the future.

The architecture encompasses a range of services already specified by OMG, including


Directory Services, Event Handling, Persistence, Transactions, and Security. The core
logic of many of these services is already available for multiple implementation
technologies; for instance, Sun's J2EE platform uses Java interfaces to CORBA's
transactions and security services. MDA should make it easier and faster to design
similar multiple-platform interfaces to common services.

MDA also enables the creation of standardized Domain Models for specific vertical
industries. These standardized models can be realized for multiple platforms now and in
the future, presumably easing multiple platform integration issues and protecting IT
investments against the uncertainty of changing fashions in platform technology.

46
Middleware and Enterprise Integration Technologies

3.3 Overview of CORBA

The Common Object Request Broker Architecture (CORBA) is a standard developed by the Object
Management Group (OMG) to provide interoperability among distributed objects. CORBA is the world's
leading middleware solution enabling the exchange of information, independent of hardware platforms,
programming languages, and operating systems. CORBA is essentially a design specification for an
Object Request Broker (ORB), where an ORB provides the mechanism required for distributed objects to
communicate with one another, whether locally or on remote devices, written in different languages, or at
different locations on a network.
The CORBA Interface Definition Language, or IDL, allows the development of language and location-
independent interfaces to distributed objects. Using CORBA, application components can communicate
with one another no matter where they are located, or who has designed them. CORBA provides the
location transparency to be able to execute these applications.
CORBA is often described as a "software bus" because it is a software-based communications interface
through which objects are located and accessed.

It has the following parts:


1. ORB Core: It is responsible for implementing the request-reply protocol.
2. Object Adapter (OA): It maps interoperable object reference (IOR) to actual local object
references. It then dispatches invocations to the corresponding server skeletons. Each OA
corresponds to a single server process.
3. CORBA Naming Service: It maps names to IORs.
4. Client Proxies and Server Skeletons: They marshal and unmarshals the arguments and results.
Each server skeleton corresponds to a CORBA object.

The invocation of the remote CORBA object is done as follows (Fig. 3.1)
1. The remote CORBA object registers itself in the CORBA naming server. It provides a
mapping for the remote object name and IOR.

2. The client refers the CORBA naming service using the object name.

3. The CORBA naming service returns the IOR of the remote object.

4. Client procedure calls client stub using a local procedure call. Conceptually, a client stub
contains a set of functions with the same name as the remote function. Stubs can be
generated automatically using the IDL compilers and are included in code during
compilation.

5. The client stub calls the network routines using system calls.

6. In this step, the local kernel sends the message to the remote kernel.

7. Once the message is successfully received by the remote kernel, it is transferred to the
OA.

8. OA then transfers the call to the server skeleton.

47
Middleware and Enterprise Integration Technologies

9. Once the control is handed to the server skeleton, it unpacks the parameters and calls the
server procedure. This process is called as unmarshalling.

10. Server does the work and returns the result to the skeleton.
11. The skeleton then packs the results in a message to OA.
12. OA contacts the RPC layer protocol (ORB core).
13. ORB then transmits the results to the client.
14. The client’s kernel gives the results to the client stub.
15. The client stub unpacks the results and returns them to the client procedure.

Fig. 3.1 Remote Method Invocation in CORBA

Advantages of CORBA

1. Multilingual

2. Multiplatform

3. Relatively lightweight

48
Middleware and Enterprise Integration Technologies

4. Good for infrastructure applications

 Like systems management applications

Disadvantages of CORBA

1. Integration required

2. Not primary programming model in industry

3. No reference implementation

3.4 Overview of COM

The demand for businesses to deploy solutions across multiple servers is bound to increase. With the
growth and acceptance of the Internet, businesses have come to think of their applications and
information be connected and distributed across multiple servers from remote locations. Also data can be
processed and accessed through the use of Web browsers and by user interfaces. But a number of
problems stand on the way towards developing and deploying mission-critical business applications on
several server systems. These applications are named as distributed software applications. They are
communication issues among different programming languages and platforms and security. There are a
few promising technologies for promoting these critical applications. Microsoft has come out with a new
technology called as Component Object Model (COM) that addresses these problems towards the goal of
design of distributed software components.

Component Object Model (COM) is a binary-interface standard for software component introduced by
Microsoft in 1993. It is used to enable interprocess communication and dynamic object creation in a large
range of programming languages. The term COM is often used in the Microsoft software development
industry as an umbrella term that encompasses the OLE, OLE Automation, ActiveX, COM+ and DCOM
technologies.

COM uses system-level code that is implemented in the form of dynamic link libraries, which are
collectively called COM library. The COM library consists of several application programming interface
(API) functions that are necessary for COM components to do various tasks. COM library is responsible
for locating and activating server applications. With client applications, COM APIs contains the
necessary functions for instantiating objects that the client wants to use. Also the COM library provides
locator services using the System Control Manager (SCM), which also provides transparent remote
procedure calls when an object is executing out-of-process in a local or remote server.

Advantages of COM

1. COM promotes component-based software development - before component-based


development came, software programs have been coded using procedural programming
paradigm, which supports linear form of program execution. But component-based program
development comes with a number of advantages, such as the ability to use pre-packaged
components and tools from third party vendors into an application and support for code
reusability in other parts of the same application.

49
Middleware and Enterprise Integration Technologies

2. COM promotes code reusability - standard classes are normally reused in the same
application but not to be used easily in other applications. But COM components are designed to
separate themselves from single applications and hence can be accessed and used by several
different applications without any hassle.
3. COM promotes Object-oriented programming (OOP) - The primary characteristics of OOP
are encapsulation, which allows the implementation details of an object to be hidden,
polymorphism, which is the ability to exhibit multiple behaviors, and inheritance, which allows
for the reuse of existing classes in order to design new and more specialized classes. Among
these, encapsulation is one of COM's most important characteristics. Encapsulation helps to hide
how an object has implemented a method internally. This ultimately helps to incorporate more
vigorously implemented or advanced implementation into an object at later time without affecting
the client which uses it.
4. COM comprises the necessary mechanisms for COM components to communicate with
each other - In the normal case, two components coded using two different programming
languages cannot communicate with each other. But COM can make it possible for different
language components, which adhere to the COM specification, to interact with each other and
hence COM is language-independent.
5. COM helps to access components loaded in different machines on the network - COM
component can reside anywhere on our computer or even on another computer connected to a
network. That is, applications using COM can access and share COM components regardless of
their locations. Thus COM provides location transparency and COM components are location
independent.

3.5 Overview of DCOM

DCOM (Distributed Component Object Model) is an extension of COM that allows network-
based component interaction. While COM processes can run on the same machine but in different
address spaces, the DCOM extension allows processes to be spread across a network.

The DCOM, previously called as network OLE, is a protocol that enables software components to
communicate directly over a network in a reliable, secure and efficient manner.

DCOM is based on the Open Software Foundation's DCE RPC specifications.

As DCOM is a Microsoft API, it is platform-dependent. DCOM is suitable for PC-based


distributed systems architecture.

DCOM makes it easy to write a distributed application that—

• Scales from the smallest single computer environment to the biggest pool of server
machines.
• Provides rich, symmetric communication between components.
• Can be robustly expanded to meet new functional requirements.
• Takes advantage of existing custom and off-the-shelf components.
• Integrates teams proficient in any programming language and development tool.
• Uses network bandwidth carefully, while providing great response times for end-users.

50
Middleware and Enterprise Integration Technologies

• Is inherently secure.
• Provides a smooth migration path to sophisticate load-balancing and fault-tolerance
features.
• Can be efficiently deployed and administered.
• Can be used with any network protocol and integrated into any hardware platform.
• Can seamlessly take advantage of other Internet standards and protocols.
• Separation of Interface from the Implementation: Both DCOM and CORBA define an
Interface Definition Language (IDL) for use by component developers to specify a
component's interface independent of a programming language.
• Component Object Services: In addition to transparent invocation of requests both
DCOM and CORBA come with a complementary set of fundamental component services.
• Uniform Exception Handling schema: For any object which runs on a heterogeneous
distributed environment, a uniform, descriptive, elaborate Exception Handling
mechanism is necessary. In DCOM, each method call returns a well-defined "flat"
structure whose bit settings encode the return status.

The Fig. 3.2 below shows the steps that are carried out to invoke a remote object in DCOM:
1. First the client requests local SCM.
2. If an object resides at a remote machine, the local SCM contacts a remote SCM.
3. The remote SCM creates a COM object and request the COM to create a stub manager
for target object. COM passes object's interface pointer and assigns object identifier
(OID). COM creates object reference (OBJREF) and establishes RPC channel.
4. COM then marshals the OBJREF.
5. It transfers the OBJREF back to client SCM.
6. On client side, COM creates a proxy manager and unmarshals OBJREF. Then COM
establishes object RPC (ORPC) connection between interface proxy and interface stub.
7. Client calls the method through interface proxy.
8. Interface proxy delegates the call to id proxy manager in COM runtime library, which
marshals the call.
9. The marshaled call is transferred through the RPC runtime and n/w layer.
10. It then passes through the RPC channel
11. Stub manager receives it.
12. The call is delegated to the target interface stub.
13. Interface stub unmarshals the parameters and then invokes target method.
14. It then receives and marshals the result to the stub manager.
15. Stub manager transfers the results to the client.
16. Proxy manager transfers the result to the interface proxy.
17. The interface proxy unmarshals the result to the client.

51
Middleware and Enterprise Integration Technologies

Fig.3.2 Remote Procedure Call in DCOM


3.6 Overview of EJB

Enterprise JavaBean (EJB) is a server-side component framework that simplifies the process of
building enterprise-class distributed component applications in Java. It’s a server-side component
that executes specific business logic. It is deployed on an application server and provides services
to local and remote clients. It gets the services of the application server by establishing contract
between application server and the component.

Enterprise beans run in the EJB container, a runtime environment within the Application Server.
Although transparent to the application developer, the EJB container provides system-level
services such as transactions and security to its enterprise beans.

Enterprise beans run in the EJB container, a runtime environment within the Application Server.
Although transparent to the application developer, the EJB container provides system-level
services such as transactions and security to its enterprise beans.

Following diagram describes a role of EJB in multi-tier enterprise applications.

EJB Server

Servlet / JSP
running in Web
Web client Container
52

Java GUI Java Bean(EJB) DBMS


application, running in
Applet
Middleware and Enterprise Integration Technologies

Fig.3.3 Role of EJB in Multi-tier Application

In a typical J2EE application, EJB contains the application’s business logic and live business
data. Although, it is possible to use standard Java objects to contain your business logic and
business data, using EJB addresses many of the issues of using simple Java objects, such as
scalability, life-cycle management and state management.

Advantages of EJB

1. It simplifies the development of small and large scale enterprise applications by providing
standard system level services to the components from containers in the application servers.

2. Its component based architecture promotes re-usability of existing components.

3. It scalability facilitates the easy addition/removal of server-side resources.

4. The business logic resides in the bean components. So the thin client needs to concentrate only on
the development and maintenance of user interfaces.

Disadvantages of EJB

1. EJB has large and complicated specifications.

2. It is a heavy weight framework.

53
Middleware and Enterprise Integration Technologies

3. It is difficult to code and debug.

4. It’s a cutting edge technology and hence the current specifications become obsolete and changes
occur very soon.

5. It is only suitable for highly scalable, secure and transactional objects.

------------------------------

54
Middleware and Enterprise Integration Technologies

Chapter 4

EJB Architecture
4.1 Overview of EJB software architecture

Enterprise JavaBean (EJB) is a server-side component framework that simplifies the process of
building enterprise-class distributed component applications in Java. It’s a server-side component
that executes specific business logic. It is deployed on an application server and provides services
to local and remote clients. It gets the services of the application server by establishing contract
between application server and the component.

Enterprise beans run in the EJB container, a runtime environment within the Application Server.
Although transparent to the application developer, the EJB container provides system-level
services such as transactions and security to its enterprise beans.

Enterprise beans run in the EJB container, a runtime environment within the Application Server.
Although transparent to the application developer, the EJB container provides system-level
services such as transactions and security to its enterprise beans.

In a typical J2EE application, EJB contains the application’s business logic and live business
data. Although, it is possible to use standard Java objects to contain your business logic and
business data, using EJB addresses many of the issues of using simple Java objects, such as
scalability, life-cycle management and state management.

Advantages of EJB

1. It simplifies the development of small and large scale enterprise applications by providing
standard system level services to the components from containers in the application servers.

2. Its component based architecture promotes re-usability of existing components.

3. It scalability facilitates the easy addition/removal of server-side resources.

4. The business logic resides in the bean components. So the thin client needs to concentrate only on
the development and maintenance of user interfaces.

Disadvantages of EJB

55
Middleware and Enterprise Integration Technologies

1. EJB has large and complicated specifications.

2. It is a heavy weight framework.

3. It is difficult to code and debug.

4. It’s a cutting edge technology and hence the current specifications become obsolete and changes
occur very soon.

5. It is only suitable for highly scalable, secure and transactional objects.

Comparison of Java Beans with Enterprise JavaBeans (June2010, Dec 2010)


(10 Marks)

Table 3.1 Java Beans Vs Enterprise JavaBeans


Java Beans Enterprise JavaBeans
1) Java Beans may be visible or non-visible at runtime 1)Enterprise Java Bean is non-visual, remote object
2)Java Beans are client based 2)Enterprise Java Beans are server based
3) Java Beans do not need a container 3) Enterprise Java Beans need a container
4) Java Beans are development components 4) Enterprise Java Beans are deployment components
5)Java Beans is intra-process component 5)EJB is an Inter-Process component
6) Java Beans don’t have any types 6)Three types of EJBs-
a)Entity Beans
b)Session Beans
c)Message-Driven Beans
7) Java Beans are classes with no argument 7) Enterprise Java Beans are assembled to form a
constructor complete application
8) Java Beans have a get() and a set() 8) Enterprise Java Beans are based on RMI IIOP and
method of them JNDI technologies
9)Java Beans consist of BeanInfo class property editors 9) BeanInfo class does not exist
or Customizers
10) Java Beans are reusable components of 10)EJB provides remote access to enterprise
applications. application logic
11) Java Beans is used to CUSTOMIZE EXISTING 11) EJBs are basically used to STANDARDIZE the
OBJECTS. i.e., you can create USER OBJECTS, way, in which business logic is written.
which are based on existing objects.
12) Component bridges are available for Java Beans. 12) An EJB cannot be deployed as an ActiveX control

56
Middleware and Enterprise Integration Technologies

Java Beans Enterprise JavaBeans


because ActiveX controls are intended to run at the
desktop and EJB's are server side components.
13) Java Bean is a component technology to create 13) EJB don’t have applets.
generic Java components that can be composed
together into applets and applications.
14) No explicit support exists for transactions in 14) EJB's may be transactional and the EJB servers
JavaBeans. provide transactional support

EJB Architecture (June 2010)(10 Marks)


EJB framework consists of following components (Fig. 4.1):

1. EJB server: It provides the execution environment for the server components. Also, provides
system services such as multiprocessing, load balancing, device access, naming and transaction
processing. It hosts EJB containers.

2. EJB Container: It serves as an interface between EJB and the outside world. EJB client can
access a bean only through the container generated methods. According to the type of beans
different containers are used. Containers host following components:

a. EJB Object: A client invokes a bean instance through EJB Object. As it intercepts the
messages requests from client to the bean instance, it is also called as request interceptor.

b. Remote Interface: It is written by a bean provider. It duplicates the methods (usually


business methods) of the bean class and hence all clients access remote object through
this interface.

c. Home Object: The clients create and destroy the EJB objects through the EJB Object
factory called the home object.

d. Home Interface: It exposes the methods for creating destroying and finding bean
objects. Each bean is supposed to have a corresponding home interfaces. All home
objects implement home interface.

57
Middleware and Enterprise Integration Technologies

Fig. 4.1 EJB Architecture

3. Enterprise beans: These are the J2EE components that implement business logic of the
applications. The EJB container acts as a run-time environment for the enterprise beans. There are
three types of enterprise beans.

A) Session beans which represent an action or process that executes synchronously.

B) Entity beans which represent data or a unique record in the database.

C) Message driven bean which also represent an action or process that executes asynchronously.

4. EJB Client: It makes use of the EJB to perform their operations. Clients locate the EJB container
by making use of Java Naming and Directory Interface (JNDI). Then the client invokes the bean
methods through container.

5. Deployment Descriptor: It lists the bean’s properties and elements. Some of the parts of
Deployment descriptor are as follow,

a. Home and Remote interfaces,

b. Bean implementation class

c. JNDI name of the class

d. Environment variables

58
Middleware and Enterprise Integration Technologies

e. Transactional attribute. etc.

4.2 View of EJB Conversation


EJB is a server side component and to communicate with the beans client has to perform following tasks
(Fig.4.2):

1. Finding the Bean:

Client can locate the bean using two different techniques. One is Java Naming and Directory
Interface (JNDI). Here, a symbolic name is assigned to the object. The other is Domain Name
Service (DNS). Once the server is able to resolve the name, it returns an address to the client.
Client can also find Bean by using CORBA’s Object Service (COS naming service).

2. Getting Access to the Bean:

The result of naming lookup is a reference to an object implementing an EJB component’s home
interface. A client uses the home interfaces to lookup the existing EJB instances, or to create new
ones.

Fig. 4.2 Bean Invocation Process

3. Calling Bean’s methods:

After the client has a reference to an object implementing the object’s remote interface, it can
then invoke the methods that the EJB object makes public in the remote interface.

4. Destroying the Bean :

When a client has finished its interaction with the remote EJB Object, it can call remove() method
on the home interface or an object’s remote interface.

If remove() is invoked for stateful bean, the container can discard the object and make space
available for other bean instances.

59
Middleware and Enterprise Integration Technologies

Calling remove() on stateless bean, just returns the bean to a pool.

If remove() method is called on Entity beans, it signals that you want to remove the underlying
object from persistence storage.

4.3 Building and Deploying EJBs

The following steps are followed in developing an EJB application:


1. Creation of a Home Interface
The home interface extends EJBHome. This container implemented interface
lists one or more create() methods to create an instance of the enterprise bean.
2. Creation of a Remote Interface
It extends EJBObject. It describes the methods exposed by the enterprise bean
class.
3. Creation of Primary Key Class
This is used to identify the object in persistent storage. Hence it is used only by
the entity beans.
4. Creation of an enterprise bean class
It implements session bean or entity bean interfaces. Its method names and
signatures must exactly match the method names and signatures of the remote
interfaces.
5. Creation of a deployment descriptor
It specifies functional properties of the bean.

4.4Roles in EJB
An EJB application’s life cycle involve three main phases – development, deployment and
administration. Depending on the size and scale of the application, the activities related to these
phases can range from simple to complex. Different parties (single person or group of people)
are involved at different stages as follows (Fig. 4.3):

1. Bean Provider:

He supplies a business components or enterprise beans. He does the tasks of writing a business
component and test it stand alone. This bean can be further assembled into an enterprise
application.

2. Application Assembler:

Application assembler is a overall application architect. His responsibility is to understand how


various components can fit together. He may write a code (called as glue code) to make the
components work together.

He may also design and develop an user interface for the application that uses these components.

60
Middleware and Enterprise Integration Technologies

The role of an application assembler can be played by a system integrator, a consulting firm or
an in-house developer.

3. EJB Deployer:

After an application assembler builds an application, the application must be deployed in a


running operational environment. Sometimes he has to use special skills to deploy the
application, because it might happen that the bean provider and assembler were unaware of the
operational environment for the bean.

Thus, he configures the security, transaction and performance of the system.

4. System Administrator:

The system administrator is responsible for the upkeep and monitoring of the deployed system
and may make use of various performance monitoring and application management tools in the
process.

61
Middleware and Enterprise Integration Technologies

Fig. 4.3 Roles in EJB

5. EJB Server / Container Provider:

An EJB server provider provides a server that can contain EJB containers. The container’s job is
to provide services to bean. The container forwards requests from client to the server. The
container provider must provide transaction support, security and persistence to the beans.
Examples of such servers include BEA WebLogic, Oracle Application Server, etc.

6. Tool vendors:
They supply IDEs to facilitate rapid modeling, building and debugging of the components. Some
of the examples of such tools are Rational Rose for modeling, Eclipse for building the
applications and JUnit for testing the applications.

62
Middleware and Enterprise Integration Technologies

-----------------------------
University Questions
1. Illustrate and describe the different components of EJB framework. (June 2010)
2. Differentiate Java Bean with EJB. (June 2010, Dec 2010)

Chapter 5

EJB Applications

Enterprise Java Beans (EJB) is a Server Side Component for Java Enterprise Edition (Java EE).
Enterprise beans run in the EJB container [a runtime environment within the Application Server]. It
enables rapid and simplified development of distributed, transactional, secure and portable applications
which is based on Java technology.
It is write-once, run-anywhere (WORA), middle-tier components which consists of methods that
implements the business logic. You can develop the application once and then deploy on any one of the
JEE 5 complaint Application Server [For e.g. – Glass Fish, JBOSS Application Server, Oracle WebLogic,
IBM WebSphere etc.]

Benefits of Enterprise Beans

For several reasons, enterprise beans simplify the development of large, distributed applications.
• The EJB container provides system-level services to enterprise beans, the bean developer can
concentrate on solving business problems. The EJB container (Not the bean developer) is
responsible for system-level services such as transaction management and security authorization.
• The enterprise beans, [not the clients] contain the application's business logic; the client
developer can focus on the presentation of the client. The client developer does not have to code
the routines that implement business rules or access databases. As a result, the clients are thinner,
a benefit that is particularly important for clients that run on small devices.
• Enterprise beans are portable components; the application assembler can build new applications
from existing beans. These applications can run on any compliant Java EE server provided that
they use the standard APIs.

When to Use Enterprise Beans

• Distributed and Scalable - To accommodate a growing number of users, we may need to


distribute an application's components across multiple machines. Not only can the enterprise
beans of an application run on different machines, but also their location will remain transparent
to the clients.
• Transactions - It must ensure data integrity. Enterprise beans support transactions, the
mechanisms that manage the concurrent access of shared objects.
• Variety of clients - With only a few lines of code, remote clients can easily locate enterprise
beans. These clients can be thin, various, and numerous.

Characteristics of Enterprise Beans

The essential characteristics of an enterprise bean are:


• Contains business logic that operates on the enterprise’s data.
• Instances are managed at runtime by a container.
• Can be customized at deployment time by editing its environment entries.

63
Middleware and Enterprise Integration Technologies

• Various service information, such as transaction and security attributes, may be specified together
with the business logic of the enterprise bean class in the form of metadata annotations, or
separately, in an XML deployment descriptor. This service information may be extracted and
managed by tools during application assembly and deployment.
• Client access is refereed by the container in which the enterprise bean is deployed.
• If an enterprise bean uses only the services defined by the EJB specification, the enterprise bean
can be deployed in any compliant EJB container. Specialized containers can provide additional
services beyond those defined by the EJB specification. An enterprise bean that depends on such
a service can be deployed only in a container that supports that service.
• An enterprise bean can be included in an assembled application without requiring source code
changes or recompilation of the enterprise bean.
• The Bean Provider defines a client view of an enterprise bean. The Bean Provider can manually
define the client view or it can be generated automatically by application development tools. The
client view is unaffected by the container and server in which the bean is deployed. This ensures
that both the beans and their clients can be deployed in multiple execution environments without
changes or recompilation.

5.1 Types of Enterprise Beans

1. Session Beans
• A session bean represents a single client inside the J2EE server.
• To access an application that is deployed on the server, the client invokes the session bean's
methods.
• The session bean performs work for its client, shielding the client from complexity by executing
business tasks inside the server.
• As its name suggests, a session bean is similar to an interactive session.
• A session bean is not shared--it may have just one client, in the same way that an interactive
session may have just one user.
• Like an interactive session, a session bean is not persistent. (That is, its data is not saved to a
database.)
• When the client terminates, its session bean appears to terminate and is no longer associated
with the client.

a. Stateless Session Bean


• It is a server-side enterprise component that encapsulates the business logic of an
application.
• Implements the javax.ejb.SessionBean interface and is deployed with the declarative
attribute “Stateless”.
• It is called "Stateless" because it does not maintain conversational state specific to a
client session.
• When a client invokes the method of a stateless bean, the bean's instance variables may
contain a state, but only for the duration of the invocation.
• When the method is finished, the state is no longer retained.
• Except during method invocation, all instances of a stateless bean are equivalent,
allowing the EJB container to assign an instance to any client.

Advantages of Stateless Session Bean

64
Middleware and Enterprise Integration Technologies

1. Perform business functions for the clients


2. Represents business process without having persistent storage mechanism
3. Enable a Conversation between a client and the J2EE Server
4. Lightweight Component
5. Same Session Bean instance can handle multiple client requests
6. Improves the scalability of an application

Limitations of Stateless Session Bean:

1. Executes Business operations without maintaining the client state


2. Not permanent in Nature
3. Not having instance variables to store information
4. Can’t used when information need to be used various method calls

When to Use Stateless Session Beans?

1. At any given time, only one client has access to the bean instance.
2. The state of the bean is not persistent, existing only for a short period.
3. The bean implements a web service.
4. The bean's state has no data for a specific client.
5. In a single method invocation, the bean performs a generic task for all clients. For
example, you might use a stateless session bean to send an email that confirms an online
order.
6. The bean fetches from a database a set of read-only data that is often used by clients.
Such a bean, for example, could retrieve the table rows that represent the products that
are on sale this month.

b. Stateful Session Bean

• It is a server-side enterprise component that encapsulates the business logic of an


application.

• Implements the javax.ejb.SessionBean interface and is deployed with the declarative


attribute Stateful.

• Called "stateful" because they maintain a conversational state with the client, in other
words we can say that, a client want to store information across various request, means
we want to maintain all actions performed by client, for e.g. Online Shopping
Application.

• The state is retained for the duration of the client-bean session. If the client removes the
bean or terminates, the session ends and the state disappears.

• This transient nature of the state is not a problem, however, because when the
conversation between the client and the bean ends there is no need to retain the state.

Advantages of Stateful Session Bean:

• Maintains the state of a client

65
Middleware and Enterprise Integration Technologies

• Stores client state in instance variable


• Can used when information need to be used various methods calls

Limitations of Stateful Session Bean:

• Stateful bean instance can service the requests of a single client only
• Not having persistent storage mechanism
• Reduces application scalability

When to Use Stateful Session Beans?

• The bean's state represents the interaction between the bean and a specific client.
• The bean needs to hold information about the client across method invocations.
• The bean mediates between the client and the other components of the application,
presenting a simplified view to the client.
• Behind the scenes, the bean manages the work flow of several enterprise beans.

2. Entity Beans
• An entity bean represents persistent data maintained in a domain model, as well as
methods that act on that data. To be more specific, an entity bean maps to a record in
your domain model.
• In a relational database context, one bean exists for each row in a table. This is not a new
concept; this is how object databases have been modeled all along.
• A primary key identifies each entity bean. Entity beans are created by using an object
factory create() method.
• Entity beans are also implicitly persistent, as an EJB object can manage its own
persistence or delegate its persistence to its container.
• Entity beans always have states, which can be persisted and stored across multiple
invocations. Multiple EJB clients may, however, share an entity bean.
• The lifetime of an entity bean is not limited by the lifetime of the virtual machine within
which it executes.
• A crash of the virtual machine may result in a rollback of the current transaction, but will
neither destroy the entity bean nor invalidate the references that other clients have to this
entity bean.
• Moreover, a client can later connect to the same entity bean using its object reference
because it encapsulates a unique primary key allowing the enterprise bean or its container
to reload its state. Entity beans can thus survive system shutdowns.

Persistence in entity beans is of two types:

1. Container-managed persistence: Here, the EJB container is responsible for saving the
state of the entity bean. Because it is container-managed, the implementation is
independent of the data source. All container-managed fields need to be specified in the
deployment descriptor, however, for the persistence to be automatically handled by the
container.
2. Bean-managed persistence: Here, the entity bean is directly responsible for saving its
own state and the container does not need to generate any database calls. Consequently,
this implementation is less adaptable than the previous one as the persistence needs to be
hard-coded into the bean.

66
Middleware and Enterprise Integration Technologies

To summarize, every entity bean has the following characteristics:


• Entity beans can share access from multiple users.
• Entity beans can participate in transactions.
• Entity beans represent data in a domain model.
• Entity beans are persistent. They live as long as the data lives in the domain model.
• Entity beans can survive EJB server crashes. Any EJB server crash is always transparent to the
client.
• Entity beans have a persistent object reference. The object reference encapsulates the persistent
key for this bean.
Table 5.1 Comparison of CMP Vs BMP

Difference Container-Managed Bean-Managed


Class definition Abstract Not abstract
Database access calls Generated by tools Coded by developers
Persistent state Represented by virtual Coded as instance variables
persistent fields
Access methods for Required None
persistent and relationship
fields
findByPrimaryKey method Handled by container Coded by developers
Customized finder methods Handled by container, but the Coded by developers
developer must define the
EJB QL) queries
Select methods Handled by container None
Return value of ejbCreate Should be null Must be the primary key

Table 5.2 Comparison of Session Bean Vs Entity Bean

Session Bean Entity Bean


The data members of the session bean contain The data members of the entity bean represent
conversational state. actual data in the domain model.
A session bean may handle database access for a Entity beans share database access for multiple
single client. clients.
Because session beans are about a conversation Because entity beans are shared between multiple
with a single client, session beans are allowed to clients, they do not allow storage of per-client
store per-client state information. state information.
The relationship between a session bean and its The relationship between an entity bean and a
client is one-to-one. row in the domain model is one-to-one.
The life of the session bean is limited to the life An entity bean persists as long as the data exists in
of its client. the database.
Session beans can be transaction aware. Entity beans are transactional.
Session beans do not survive server crashes. Entity beans survive server crashes.

3. Message Driven Beans

• A message-driven bean is an enterprise bean that allows Java EE applications to process


messages asynchronously. It normally acts as a JMS message listener, which is similar to an
event listener except that it receives JMS messages instead of events.

67
Middleware and Enterprise Integration Technologies

• The messages can be sent by any Java EE component--an application client, another enterprise
bean, or a web component--or by a JMS application or system that does not use Java EE
technology. Message-driven beans can process JMS messages or other kinds of messages.

Characteristics of Message-Driven Bean

The essential characteristics of a Message-Driven Bean are:


• Executes upon receipt of a single client message.
• Invoked asynchronously.
• Relatively short-lived.
• Represent directly shared data in the database, but they can access and update this data.
• They can be transaction-aware.
• It is stateless.

When to Use Message-Driven Beans

In general, we should use a Message-driver bean in the following conditions:


• Session beans allow us to send JMS messages and to receive them synchronously, but not
asynchronously. In general, JMS messages should not be sent or received synchronously. To
receive messages asynchronously, use a message-driven bean.

5.2 Lifecycle of Beans

An enterprise bean goes through various stages during its lifetime, or life cycle. Each type of enterprise
bean--session, entity, or message-driven--has a different life cycle.

1. The Life Cycle of a Stateful Session Bean

Fig. 5.1 illustrates the stages that a session bean passes through during its lifetime. The client initiates
the life cycle by invoking the create() method. The EJB container instantiates the bean and then invokes
the setSessionContext() and ejbCreate() methods in the session bean. The bean is now ready to have its
business methods invoked.

68
Middleware and Enterprise Integration Technologies

Fig.5.1 Life Cycle of a Stateful Session Bean

While in the ready stage, the EJB container may decide to deactivate, or passivate, the bean by moving it
from memory to secondary storage. (Typically, the EJB container uses a least-recently-used algorithm to
select a bean for passivation.) The EJB container invokes the bean's ejbPassivate() method immediately
before passivating it. If a client invokes a business method on the bean while it is in the passive stage,
the EJB container activates the bean, moving it back to the ready stage, and then calls the bean's
ejbActivate() method.

At the end of the life cycle, the client invokes the remove method and the EJB container calls the bean's
ejbRemove() method. The bean's instance is ready for garbage collection.

2. The Life Cycle of a Stateless Session Bean

Because a stateless session bean is never passivated, its life cycle has just two stages: Does not exist and
ready for the invocation of business methods. Fig. 5.2 illustrates the stages of a stateless session bean.

69
Middleware and Enterprise Integration Technologies

Fig.5.2 Life Cycle of a Stateless Session Bean

3. The Life Cycle of an Entity Bean

Fig. 5.3 shows the stages that an entity bean passes through during its lifetime. After the EJB container
creates the instance, it calls the setEntityContext() method of the entity bean class. The
setEntityContext() method passes the entity context to the bean.

After instantiation, the entity bean moves to a pool of available instances. While in the pooled stage, the
instance is not associated with any particular EJB object identity. All instances in the pool are identical.
The EJB container assigns an identity to an instance when moving it to the ready stage.

There are two paths from the pooled stage to the ready stage. On the first path, the client invokes the
create() method, causing the EJB container to call the ejbCreate() and ejbPostCreate() methods. On the
second path, the EJB container invokes the ejbActivate() method. While in the ready stage, an entity
bean's business methods may be invoked.

There are also two paths from the ready stage to the pooled stage. First, a client may invoke the
remove() method, which causes the EJB container to call the ejbRemove() method. Second, the EJB
container may invoke the ejbPassivate() method.

70
Middleware and Enterprise Integration Technologies

Fig.5.3 Life Cycle of an Entity Bean

At the end of the life cycle, the EJB container removes the instance from the pool and invokes the
unsetEntityContext() method.

In the pooled state, an instance is not associated with any particular EJB object identity. With bean-
managed persistence, when the EJB container moves an instance from the pooled state to the ready
state, it does not automatically set the primary key. Therefore, the ejbCreate() and ejbActivate()
methods must assign a value to the primary key. If the primary key is incorrect, the ejbLoad() and
ejbStore() methods cannot synchronize the instance variables with the database. The ejbCreate()
method assigns the primary key from one of the input parameters. The ejbActivate() method sets the
primary key (id) as follows:

id = (String)context.getPrimaryKey();

71
Middleware and Enterprise Integration Technologies

In the pooled state, the values of the instance variables are not needed. You can make these instance
variables eligible for garbage collection by setting them to null in the ejbPasssivate() method.

4. The Life Cycle of a Message-Driven Bean

Fig.5.4 illustrates the stages in the life cycle of a message-driven bean. The EJB container usually creates
a pool of message-driven bean instances. For each instance, the EJB container instantiates the bean and
performs these tasks:

1. It calls the setMessageDrivenContext() method to pass the context object to the instance.

2. It calls the instance's ejbCreate() method.

Fig.5.4 Life Cycle of a Message-Driven Bean

Like a stateless session bean, a message-driven bean is never passivated, and it has only two states:
nonexistent and ready to receive messages.

At the end of the life cycle, the container calls the ejbRemove() method. The bean's instance is then
ready for garbage collection.

5.3 EJB Clients

EJB clients are application clients that interact with the J2EE EJB tier. EJB clients are GUI programs that
typically execute on a desktop computer; they manage their own GUI and offer a user experience similar
to that of native applications.

72
Middleware and Enterprise Integration Technologies

EJB clients interact with the J2EE EJB tier using the RMI-IIOP protocol. A variety of middle-tier services
are available to an application client: JNDI for directory lookups, JMS for messaging, and JDBC for
relational database access.

An EJB client depends on a client container to provide some system services. Such a container is typically
very lightweight compared to other J2EE containers and usually provides security and deployment
services.

Strengths and Weaknesses of EJB Client

EJB clients have a number of strengths, including:

• Provide a more flexible user interface

Application clients can be made to look and feel more like native applications on the client
machine. Since these clients implement their own user interface, they can provide a richer,
more natural interface to the application tasks.

• Distribute the workload

An application client can share some of the computational expense by doing the task on the client
desktop, and thereby reducing load on the server. In particular, the work of generating the user
interface is performed by each client. This is useful for applications with specific graphical display
capabilities.

• Handle complex data models

Sometimes the data associated with an application is sufficiently complex and the manipulation
interface rich enough, that a Web-based interface to manage the interaction is not enough. In such
cases, you want direct access to the underlying object model on the client and to manipulate it
directly.

For example, in a financial analysis system, it might make sense to off-load some of the complex
financial-projection number crunching to the client. Or consider an application that allows
manipulation of CAD schemas such as a design of a circuit board (PCB). An application client, with
direct access to the objects of the CAD system, can redraw views of the layout more easily than a
Web-based interface, and with better performance. The server should be delegated to background
tasks such as converting a PCB layout to a plot of the PCB traces.

• Are transaction-capable

Since EJB clients communicate using RMI-IIOP, they are capable of participating in client-demarcated
transactions through JTA APIs.

• Provide integrated security

73
Middleware and Enterprise Integration Technologies

Application client containers can integrate with the security of the underlying operating system
where the client is executed, thereby providing a more transparent and manageable security
infrastructure.

For example, in an enterprise intranet, where the client and the server belong to the same security
domain, an application client container might simply forward the credentials of the user already
logged into the client desktop operating system, thereby effecting single sign-on. A Web client, on
the other hand, would require explicit sign on and security management.

The disadvantages of EJB clients are that they:

• Require explicit deployment

EJB clients need to be distributed and installed on the client desktops. In an intranet, where
desktops can be standardized, this is less of an issue. However, on the Internet, distribution
becomes a serious consideration. Furthermore, upgrades and fixes to the client need to be
distributed as well, and the server has to deal with multiple versions of the client programs.

• Require firewall reconfiguration

The RMI-IIOP protocol does not usually go through firewalls without additional setup on the firewall
host. This makes use of EJB clients on the Internet very limited.

• Tend to be more complex

Since the application client needs to manage its own user interface, its implementation is more
complex. Furthermore, it communicates with the J2EE server at a much lower level than browser-
based Web clients and needs to handle the complexity introduced as a result.

Types of EJB Clients

EJB clients can be implemented using either the Java programming language, or languages such as Visual
Basic or C++. When a language other than Java is used, depending on the implementation on the client
container, some of the facilities of the J2EE platform may not be available.

1. Java Technology Clients

Java clients execute in their own Java virtual machine. Following the model for Java applications, they
are invoked at their main method and run until the virtual machine is terminated. Security and
deployment services are provided through the use of a client container.

The Java programming language should be used for implementation of EJB clients. Since the EJB server
communicates using RMI-IIOP, the client needs to support RMI-IIOP. This is most naturally done using
services provided by the standard Java platform.

Some facilities cannot be easily implemented in other languages as a result, client containers for these
languages may not provide the full set of features.

74
Middleware and Enterprise Integration Technologies

Multitier Clients

Java technology clients are usually stand-alone Java applications. However, when appropriately signed
and trusted, Java applets can also be used as EJB clients. Applets and applications have essentially the
same set of platform service available to them. Additionally, a Java applet can communicate with the
Web tier as well as the application tier to get its job done. In this sense it is a multitier client.

2. Non-Java Clients

EJB clients can be implemented in programming languages other than Java. Since the EJB server uses
RMI-IIOP, this requires some form of RMI-IIOP support available to the client.

5.4 Steps in Developing

The following steps are followed in developing an EJB application:


1. Creation of a Home Interface
The home interface extends EJBHome. This container implemented interface
lists one or more create() methods to create an instance of the enterprise bean.

//customerHome.java
import javax.ejb.*;
import java.rmi.*;
public interface customerHome extends EJBHome
{
public customerRemote create(String a,String b,String c)
throws RemoteException, CreateException;
public customerRemote findByPrimaryKey(String a)
throws RemoteException, FinderException;
}

2. Creation of a Remote Interface


It extends EJBObject. It describes the methods exposed by the enterprise bean
class.
//customerRemote.java
import javax.ejb.*;
import java.rmi.*;
public interface customerRemote extends EJBObject
{
public String getName()throws RemoteException;
public void setName(String s) throws RemoteException;
public String getPlace()throws RemoteException;
publicvoid setPlace(String s) throws RemoteException;
}

3. Creation of Primary Key Class


This is used to identify the object in persistent storage. Hence it is used only by
the entity beans.

75
Middleware and Enterprise Integration Technologies

public class customerid implements java.io.Serializable {


public String key;
public String hashcode() {
return key; }
public Boolean equals(Object obj) {
if (obj instanceOf customerid) {
if (((customerid)obj).id==id)
return true;
}
return false;
}
}

4. Creation of an enterprise bean class


It implements session bean or entity bean interfaces. Its method names and
signatures must exactly match the method names and signatures of the remote
interfaces.
//customerBean.java
import javax.ejb.*;
import java.rmi.*;
public class customerBean implements EntityBean
{
public String key;
public String name;
public String place;
public String getName()
{
return name;
}
public String getPlace()
{
return place;
}
//---------------------------
public void setName(String b)
{
name=b;
}
public void setPlace(String c)
{
place=c;
}
//-------------------------------
public String ejbCreate(String a, String b,String c) throws CreateException
{
this.key=a;

76
Middleware and Enterprise Integration Technologies

this.name=b;
this.place = c;
return null;//it should be null!
}
public void ejbPostCreate(String a,String b,String c) throws CreateException{}
public void ejbActivate(){}
public void ejbPassivate(){}
public void ejbRemove(){}
public void ejbLoad(){}
public void ejbStore(){}
public void setEntityContext(EntityContext ec){ }
public void unsetEntityContext(){ }
}

5. Creation of a deployment descriptor


It specifies functional properties of the bean.

<?xml version="1.0"?>
<!DOCTYPE ejb-jar PUBLIC '-//Sun Microsystems, Inc.//DTD Enterprise
JavaBeans 1.1//EN' 'http://java.sun.com/dtd/ejb-jar_1_1.dtd'>
<ejb-jar>
<enterprise-beans>
<entity>
<ejb-name>customerBean</ejb-name>
<home>customerHome</home>
<remote>customerRemote</remote>
<ejb-class>customerBean</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>java.lang.String</prim-key-class>
<reentrant>False</reentrant>
<cmp-field>
<field-name>key</field-name>
</cmp-field>
<cmp-field>
<field-name>name</field-name>
</cmp-field>
<cmp-field>
<field-name>place</field-name>
</cmp-field>
<primkey-field>key</primkey-field>
</entity>
</enterprise-beans>
</ejb-jar>

77
Middleware and Enterprise Integration Technologies

Lab Experiments
1. Stateless Session Bean
(Use Netbeans 5.0 and GlassFish Server 3)

Creating the Java Class Library

In this section you will create a Java Class Library project that will contain the remote interface for the
EJB. The remote interface behaves as an API for the EJB that is used by clients to communicate with the
EJB.
The library JAR is easy to distribute to any clients that may need to call the EJB. Clients that want to
access the EJB only need to add the library JAR to the project classpath. The EJB implementation uses
the same JAR to implement the interface.
1. Choose File > New Project and select Java Class Library in the Java category. Click Next.
2. Type EJBRemoteInterface for the Project Name. Click Finish.

When you click Finish, the IDE creates a Java Class Library project. In the next section you will create a
Java EE enterprise application and an EJB module. You will then use a wizard to create a session bean
and the remote interface for your session bean in the Class Library project. The application client will
access the session bean via the interface in the class library.

Creating an EJB Module


In this section you will create an enterprise application and an EJB module. When you create an EJB, the
EJB should be created as part of an enterprise application and packaged as an EAR archive and deployed
in to the server.

Creating the Enterprise Application


In this section you will use the New Project wizard to create an enterprise application containing an EJB
module. The wizard provides an option to create an EJB module when you create the application.

78
Middleware and Enterprise Integration Technologies

1. Choose File > New Project and select Enterprise Application in the Java EE category. Click Next.
2. Type EntAppEJB for the Project Name. Click Next.
3. Select GlassFish Server 3 for the Server.
4. Confirm that Create EJB Module is selected and deselect Create Web Application Module. Click
Finish.

When you click Finish, the IDE creates an enterprise application and an EJB module. In the Projects
window, you can see that the EJB Module project is listed under the Java EE Modules node of the
enterprise application project.

You can see that three types of projects are now listed in the Projects window: class library, enterprise
application and EJB module.

Creating the Session Bean


In this exercise you will use a wizard to create a session bean in the EJB module project. In the wizard
you will also create a remote interface for the session bean in the Class Library project.

79
Middleware and Enterprise Integration Technologies

1. Right-click the EJB module project and choose New > Session Bean.
2. Type MySession for the EJB Name.
3. Type ejb for the Package.
4. Select Stateless for the Session Type.
5. Select the Remote option for Create Interface.
6. Select the EJBRemoteInterface project from the dropdown list. Click Finish.

When you click Finish, the IDE creates the session bean in the ejb package in the EJB module and opens
the class in the editor. You can see that MySession implements the MySessionRemote interface and that
the EJBRemoteInterface JAR was added as a library of the EJB module.
The wizard also creates a remote interface named MySessionRemote in the ejb package of the
EJBRemoteInterface project. The IDE automatically adds the Java EE 6 API Library that is required for
the EJB interface.

80
Middleware and Enterprise Integration Technologies

Adding a Business Method

In this exercise you will create a simple business method in the session bean that returns a String.
1. Right-click in the editor of MySession and choose Insert Code (Ctrl+I) and select Add Business
Method.
2. Type getResult for the Method Name and String for the Return Type. Click OK.
3. Make the following changes to modify the getResult method to return a String.
The class should look like the following.
@Stateless
public class MySession implements MySessionRemote {

public String getResult() {


return "This is My Session Bean";
}
}
4. Save your changes.
You now have an enterprise application with a simple EJB that is exposed through a remote interface.
You also have an independent class library that contains the EJB interface that can be distributed to other
developers. Developers can add the library to their projects if they want to communicate with the EJB that
is exposed by the remote interface and do not need to have the sources for the EJB. When you modify the
code for the EJB, you only need to distribute a JAR of the updated class library if any of the interfaces
change.
When you use the Add Business Method dialog, the IDE automatically implements the method in the
remote interface.

Deploying the Enterprise Application


You can now build and run the enterprise application. When you run the application, the IDE will deploy
the EAR archive to the server.

81
Middleware and Enterprise Integration Technologies

1. Right-click the EntAppEJB enterprise application and choose Run.


When you click Run, the IDE builds the enterprise application and deploys the EAR archive to the server.
If you look in the Files window you can see that the EJBRemoteInterface JAR is deployed with the
application.
In the Services window, if you expand the Applications node of GlassFish Server 3 you can see that the
EntAppEJB was deployed.

Creating the Application Client

In this section you will create a new enterprise application that contains an application client. When
creating the application client, the project needs the EJBRemoteInterface Java class library as a library in
order to reference the EJB.
When you run the enterprise application, the IDE will package the application client and the Java class
library JAR in the EAR archive. Library JARs must be packaged in an EAR with the application client if
you want to access the JARs from the application client.

Creating the Enterprise Application

In this exercise you will use the New Project wizard to create an enterprise application project and
application client project.
1. Choose File > New Project and select Enterprise Application in the Java EE category. Click Next.
2. Type EntAppClient for the Project Name. Click Next.
3. Select GlassFish Server 3 for the Server.
4. Deselect Create EJB Module and Create Web Application Module.
5. Select Create Application Client. Click Finish.

When you click Finish, the IDE creates an enterprise application and an application client project.

Adding the Class Library

The class library that contains the remote interface now needs to be added to the classpath of the project
to enable the application to reference the EJB. The class library project is open, so you can use the Call
Enterprise Bean dialog to help you generate the code to call the EJB.
If the class library project is not open, you can add the class library to the project in the Projects window
by right-clicking the Libraries node and locating the JAR of the EJBRemoteInterface project.

82
Middleware and Enterprise Integration Technologies

1. Expand the Source Packages node of the EntAppClient project and open Main.java in the editor.
2. Right-click in the source code and choose Insert Code (Ctrl+I) and select Call Enterprise Bean to
open the Call Enterprise Bean dialog.
3. Expand the EntAppEJB project node and select MySession. Click OK.

The dialog automatically selects Remote as the interface type. When you click OK, the IDE adds the
following annotation to Main.java.
@EJB
private static MySessionRemote mySession;
The IDE also automatically adds EJBRemoteInterface as a project Library.
Modify the main method to retrieve the String of the getResult method via the MySessionRemote
interface. Save your changes.

public static void main(String[] args) {


System.err.println("result = " + mySession.getResult());
}

Running the Application Client


You can now run the application client by building and deploying the EntAppClient enterprise
application.
1. Right-click the EntAppClient enterprise application project and choose Run.
When you click Run, the IDE builds the enterprise application project that contains the application client
and deploys the EAR to the server. You can see the message from the application client in the Output
window.

2. Stateful Session Bean

83
Middleware and Enterprise Integration Technologies

Following are the steps to create EJB Stateful Session Bean using Netbeans 5.0 and Sun Java System
Application Server 8.
1. Go to File  New Project Enterprise  EJB Module
Type Project Name: MyCourseEJB
Server Sun Java Application Server
J2EE Version  J2EE 1.4
Click Set Source Level to 1.4 and Set as Main Project
Click on Finish Button.

2. Right Click on MyCourseEJB -> New-> SessionBean

EJB NameCourse Package  university


Session TypeStateful Create InterfaceRemote
Click on Finish
3. Go to MyCourseEJB Source Package university
Delete CourseRemoteBusiness.java

4. Replace CourseBean with Following Code:


//CourseBean.java
package university;
import java.util.Enumeration;
import java.util.Vector;
import javax.ejb.*;
/**
* This is the bean class for the CourseBean enterprise
bean.
* @author
*/
public class CourseBean implements SessionBean
{
private SessionContext context;
String studentName;
String studentRollNo;
Vector selectedCourse;
public void setSessionContext(SessionContext aContext)
{
context = aContext;
}
public void ejbActivate() { }
public void ejbPassivate() { }
public void ejbRemove()
{
studentName = null;
studentRollNo = null;
}
public void ejbCreate(String sName, String sRollNo)
throws
CreateException
{
if(sName == null)
{
throw new CreateException ("Null Person not allowed");

84
Middleware and Enterprise Integration Technologies

}
else
{
studentName = sName;
studentRollNo = sRollNo;
}
selectedCourse = new Vector();
}
public String addCourse(String Cname)
{
if (Cname==null)
{
return "";
}
try
{
if(!selectedCourse.isEmpty())
{
Enumeration enumer = selectedCourse.elements();
String title="";
while(enumer.hasMoreElements())
{
title = (String)enumer.nextElement();
if(title!=null)
{
/* Checks whether a same course is again
selected.*/
if(Cname.equals(title))
{
return "You have already selected this
course";
}
}
} // end of while loop
/* Adds the course in the cart.*/
selectedCourse.addElement(Cname);
} // end of if
else
{
/* Adds the course in the cart.*/
selectedCourse.addElement(Cname);
}
}
catch(Exception e)
{
return "Error : " + e.toString();
}
return "";
}
public String removeCourse(String Cname)
{
/* Removes a course from the cart.*/
boolean result = selectedCourse.removeElement(Cname);
if (result == false)
{
return Cname + "course is not in cart.";

85
Middleware and Enterprise Integration Technologies

}
return "Course Removed";
}
public Vector getSelectedCourse()
{
return selectedCourse;
}
}

5. Replace CourseRemote with Following Code:


//CourseRemote.java
package university;
import java.rmi.RemoteException;
import javax.ejb.EJBObject;
import java.util.Vector;
/**
* This is the remote interface for Course enterprise
bean.
*/
public interface CourseRemote extends EJBObject
{
public String addCourse(String cName)throws
RemoteException;
public String removeCourse(String cName) throws
RemoteException;
public Vector getSelectedCourse() throws RemoteException;
}
6. Replace CourseRemoteHome with Following Code
//CourseRemoteHome.java
package university;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome;
/**
* This is the home interface for Course enterprise bean.
*/
public interface CourseRemoteHome extends EJBHome
{
CourseRemote create(String sName, String sRollNo) throws
CreateException, RemoteException;
}
7. Right Click on MyCourseEJB  DeployProject
8. Step to create EJB Stateful Bean Web Client Application
File  New Project  Category : web  Web Application
Click Next Project Name: MyCourseWeb Server : Sun Java System Application
Server
Click on Finish Button
9. Add the Reference of EJB Module to Client
Go to MyCourseWeb  Right Click on Libraries Add Project
10. Select the Name of EJB Module [MyCourseEJB]  Add Project JAR Files
11. Replace index.jsp page with following code
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>

86
Middleware and Enterprise Integration Technologies

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01


Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Student Details</title>
</head>
<body bgcolor="pink">
<h1><center>Student Information</center></h1>
<hr>
<br><h2> <center> Please Enter the Following Details
!!!</center> </h2> <br>
<form method="get" name="f1" action="courseCart.jsp">
<table align="center">
<tr>
<td> <b>Name of Student : </b></td>
<td> <input type="text" name="stdname" size="20"> </td>
</tr>
<tr>
<td> <b>Student Roll Number: </b> </td>
<td> <input type="text" name="stdrollno" size="20"></td>
</tr>
<tr>
<td align="right"> <b><input type="submit" value="Submit">
</b> </td>
<td align="center"> <b> <input type="reset" value="Reset">
</b></td>
</tr>
</table>
</form>
</body></html>
12. Steps to create a JSP file
Right click on Web Pages -> New -> JSP
JSP File Name : courseCart
Options  JSP File (Standard Syntax)
Click on Finish Button
13. Replace courseCart.jsp page with following code

<%@ page import="javax.ejb.*,javax.naming.*,


javax.rmi.PortableRemoteObject,java.rmi.RemoteException,univ
ersity.*,java.util.*" %>
<%!
private CourseRemote course = null;
CourseRemoteHome home=null;
public void _jspInit()
{
/* Locating the stateful session bean.*/
try
{
Context ic = new InitialContext();
Object objRef = ic.lookup("ejb/CourseBean");
home=(CourseRemoteHome)PortableRemoteObject.narrow(objRef,
CourseRemoteHome.class);

87
Middleware and Enterprise Integration Technologies

}
catch(Exception ex){ } } %>
<html> <head>
<title>University Registration Application</title> </head>
<body bgcolor="pink">
<form method="get" name="f1">
<%
String stdname = request.getParameter("stdname");
String stdrollno = request.getParameter("stdrollno");
if ( stdname != null && stdname.length() > 0 )
{
if ( stdrollno != null && stdrollno.length() > 0 )
{
/* Creating a bean instance.*/
course = home.create(stdname,stdrollno);
} } %>
<H1>University Registration Application</h1>
<p>Welcome <%=stdname%> !!!</p>
<p> Please a Course Subject
<select name=ch size=1>
<option>C, C++</option> <option>Core Java</option>
<option>J2EE</option> <option>VB.NET</option>
<option>C#.NET</option> <option>ASP.NET</option>
<option>Oracle</option> <option selected value="--">
Select a Course</option>
</select> <br>
<% int i=1;
String choice=request.getParameter("ch");
if(choice!=null)
{
if(!choice.equals("--"))
{
String str=course.addCourse(choice); %>
<p> <%=str%>
<% } }
String rmcourse=request.getParameter("c");
if(rmcourse!=null)
{
course.removeCourse(rmcourse);
}
Vector courseList = new Vector();
courseList = course.getSelectedCourse();
Enumeration enumer = courseList.elements(); %>
<form method="get" name="f2">
<p><p> <table border=1>
<th> Course Name </th>
<th> Select Course to remove </th>
<% while (enumer.hasMoreElements())
{
String title = (String) enumer.nextElement();
if (title!=null)
{
%>
<tr> <td> <%=title%> </td>
<td><input type=radio name=c value='<%=title%>' > </td>
</tr>

88
Middleware and Enterprise Integration Technologies

<% }
} %>
</table>
<input type="hidden" name="stdname" size="25"
value=<%=stdname%>>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
</body>
</html>

14. Right Click on MyCourseWeb  Build Project


15. Right Click on MyCourseWeb  Run Project
16. Following page is Welcome Page of Web Application using Stateful Session
Bean

17. Enter Name of Student : John -> and Roll No. : 101 -> Click on Submit Button

18. Above page will display Welcome message followed by Name of Student
Now you are ready to select or remove any course.
Select any Course (Core Java)-> Click on Submit

89
Middleware and Enterprise Integration Technologies

Your Selected Course Will display in your Course Cart


Select other Course (J2EE)-> Click on Submit Button.

Select same (Which already in Course Cart) for e.g. J2EE -> Click on Submit
“You have already selected this course” will be displayed.

90
Middleware and Enterprise Integration Technologies

Now click on any radio button to remove the course.

Your checked course is remove from Course Cart

91
Middleware and Enterprise Integration Technologies

------------

Chapter 6

CORBA

Component- based software development promotes reuse and fast integration of enterprise software with
legacy system and databases. Middleware promotes component technology to be developed and integrated
into new applications. Enterprise information systems cannot be tied up with a single vendor as they are
technologically diversified. Hence Common Object Request Broker Architecture (CORBA) is preferred.

6.1 Introduction and Concepts

CORBA is a standard for distributed object middleware created by Object Management Group (OMG).
The object management Group, INC. is an international organization supported by over 800 members,
including information system vendors, software developers and users. Founded in 1989, primary goals of
OMG are the reusability, portability and interoperability of object-based software in distributed,
heterogeneous environment. OMG’s objective is to foster the growth of object technology by establishing
the Object Management Architecture (OMA). It describes objects as immutable whose services are
exposed through interfaces. It consists of two parts, namely, OMG Object Model and OMG Reference
Model.

92
Middleware and Enterprise Integration Technologies

The OMG Object Model

The OMG Object Model is based on objects, operations, types and subtyping. It provides a standard,
commonly understood set of terms to describe a service’s behavior. The standard of OMG object model is
CORBA. It includes support for object-oriented concepts such as objects, classes, encapsulation,
inheritance and polymorphism. The OMG Object Model consists of the following parts:

1. Object: It is an encapsulated entity that provides services to the clients.

2. Request: It is an action created by a client directed to a target object that includes information on
the operation to be performed.

3. Object Creation and Destruction: Based on the client’s request object are created or deleted

4. Types: It is an identifiable entity with values.

5. Interface: It is the specification of operations that a client can request from an object.

6. Operation: It is an identifiable entity that defines what a client can request from the object.

The OMG Reference Model

The OMG Reference Model consist of the following components

1. Object Request Broker: It facilitates communication between clients and objects. It enables
objects to transparently send/receive requests/ responses in a distributed environment. It also
achieves interoperability between applications in a heterogeneous environment. ORB provides
uniform access to services and uniform discovery of resources through common RPC and naming
mechanisms. It also provides facilities for uniform error handling, security policies, and
integration to legacy applications.
2. Object Services: It is a collection of services (interfaces and objects) that support basic functions
for using and implementing objects. Services are independent of application domains.

93
Middleware and Enterprise Integration Technologies

Fig. 6.1 OMG Reference Model

The syntax used to specify the interfaces is the OMG Interface Definition Language (OMG IDL).
Services are designed to be generic in nature, independent of the client. The design of each object
service uses and builds on the following CORBA concepts:

• Clear separation of interface from implementation,


• Dependency of clients on interfaces and not implementations,
• Multiple inheritances of interfaces to promotes extension and evolutions of functionalities.
• Assuring quality ORB and object service.

3. Common Facilities: It is a collection of services that many applications can share, but is not as
fundamental as the object services. A system management or electronic mail facility is a common
facility.
4. Domain Interfaces: These interfaces fill role similar to object services and common facilities but
are oriented towards specific application domains.
5. Application Interfaces: These are interfaces developed specifically for a given application. They
are user-defined, application-specific and have proprietary interfaces.

6.2 CORBA Components

The OMG architecture is appropriate for defining, developing and deploying flexible distributed systems.
OMG provides specification to encapsulate application data and business logic within objects that can be
used in distributed environment. These objects are called distributed components. A component
represents a significant portion of overall system, yet it is small enough to enable efficient and flexible
assembly with other components to form full-fledged applications. The process of mapping real world
application to components is called componentization.

94
Middleware and Enterprise Integration Technologies

A CORBA component or simply a CORBA object is a reusable entity just like a conventional object and
provides inheritance, polymorphism, and encapsulation. Unlike conventional object it is independent of
the programming language, operating system, hardware, location and network.

A component that implements a particular behavior exposes its capabilities through its interfaces. It is a
set of semantically related operations that a components client can use to access its capabilities. It hides
the underlying implementation details for the client. Some of the entities involved in components
interaction are as follows:

1. Interoperable object reference (IOR): It defines the CORBA component. The client uses IOR
to access the functionalities of components. It is analogous to the C++ pointer.
2. Request: A client makes a request for CORBA object's services using its IOR. It results on an
operation call in target CORBA object.
3. Operation: It denotes a component's service requested by client. It is like a conventional object's
member function.
4. Client: It is an application that uses the services of CORBA component. It is transparent to the
implementation of component.
5. Server: It is an application that creates CORBA components, publishes IORs of the components
and provides services to the clients. It is hosts the component implementation. Following figure
shows a CORBA component hosted in server receiving a request from client.

Fig.6.2 A component receiving a request.

The characteristics of a CORBA component are as follows:

1. Independent development: Components can be developed independently of other components.


Interfaces between components define contract between them that facilitates independent
development.
2. Independent business entity: componentization aims at partitioning a complex application
system into smaller and simpler self-contained business entities.
3. Packagable: Components can be packaged in a variety of ways, which provides great flexibility
for deployment.
4. Buildable: A variety of tools, techniques and design methods are used to implement components.
5. Rapid development: components can be used in different combinations to form applications.
Hence they can be used in rapid application development.
6. Extensible: Componentized development facilities extensibility by facilitating new components
to be added to the existing system in an organized and modular manner.
7. Configurable: Different implementation of the same logical component can be interchanged at
run time, provided the interfaces are not changed. Hence the operations are configurable.
8. Scalable: Components can be distributed in different nodes or available in same machine to
facilitates scalability and load balancing.

95
Middleware and Enterprise Integration Technologies

9. Flexible: Components can communicate with one another across hardware, platform, networks
and languages.
10. Extended objects: A component may support different services such as transaction, security,
persistence etc.

6.3 Architectural Features (Dec 2010) (10 Marks)

CORBA defines a standard framework from which an information system implementer or


software developer can easily and quickly integrate network resident software modules and
applications to create powerful applications. It is structured to allow integration of a wide variety
of object systems. CORBA ORBs deliver client requests to servants (server objects) and return
responses to clients. CORBA automates many common network programming tasks such as
objects registration, location and activation, request demultiplexing, error-handling, parameter
marshalling and demarshalling and operation dispatching. It allows applications to communicate
with one another in a uniform way, transparent to the object location, hardware, operating system,
programming language and communication protocol.

The core of the CORBA architecture is the ORB that acts as the object bus over which objects
transparently interact with other objects located locally or remotely. An interface defined in an
IDL file serves as a contact between a server and it clients.

The main components of CORBA as shown in figure are as follows:

1 Object Request Broker (ORB): ORB provides the communication and activation infrastructure
for distributed object applications. To make a request, the client specifies the target object by using an
object reference (OR).

ORB core facilitates the following transparencies in client-server communication:

• Object Location: Here the client has no knowledge of weather the target object is in-process or
out-process i.e. the target object is running current program. Also, client is unaware of whether
the target object is in the same machine or a different machine.

• Object implementation: Here the client does not know the language, platform of hardware in
which object is implemented. Client only knows what operations are possible.

• Object execution state: Here the client does not know whether the object active or inactive. ORB
transparently activates object when required by client.

• Object communication mechanism: ORB can use memory, RPC and TCP/IP for
communication.

96
Middleware and Enterprise Integration Technologies

2 OMG Interface Definition language (OMG IDL): An object’s interface specifies the operation
and types that the object supports. Hence it defines the requests that can be made on the object. Since
OMG IDL is a declarative language and not a programming language, it forces a clear separation of
interfaces from object implementations. OMG IDL is a language in which only classes (i.e. modules)
interfaces and methods can be declared.

Fig. 6.3 Common Object Request Broker Architecture

3 Interface Repository (IFR): The CORBA IFR allows the IDL-type system to be accessed and
written programmatically at run-time. So it is used in dynamic object invocation.

4 Stubs and Skeletons: OMG IDL language compilers generate programming language type
interfaces, client-side stubs and server-side skeletons. A stub is a mechanism that effectively creates and
issues requests on behalf of a client, while a skeleton is a mechanism that delivers requests to the CORBA
object implementation. As they are interface-specific, dispatching through stubs and skeletons is called
static invocation.

5 IDL Compiler: It is a tool which generates static stubs (Static Invocation Interface (SII)) and
skeletons (Static Skeleton Interface (SSI)) from the interface definition.

6 Dynamic Interface Invocation (DII): The DII allows clients to generate requests at run-time. It
is useful when an application has no compile-time knowledge of the interface it accesses.

7 Object Adepter (OA): It serves as the glue between CORBA object implementations and the
ORB. It is an object that adapts the interface of an object to the interface expected by a caller. OAs
provide services such as object registration, generation and interpretation of object references, method

97
Middleware and Enterprise Integration Technologies

invocation. There are two categories of OA: Basic Object Adepter (BOA) and Portable Object Adepter
(POA).BOA defines an object adepter which can be used for most conventional object implementations.
The POA specifications provide portability for CORBA server code.

8 Inter-ORB Protocols: To support interoperability, CORBA proposes General Interoperable


Protocol (GIOP) and Interoperable OR(IOR). It describes a Common/Character Data Representation
(CDR) format and message formats for sending requests and responses between ORBs. GIOP is defined
independently of any particular transport protocol in order to accommodate a wide range of networking
infrastructures. Internet Interoperable protocol (IIOP) provides full-duplex, connection-oriented
communication channel through the TCP/IP protocol. IOR is a representation of a CORBA object.

9 ORB Interface: To decouple applications from implementation details, the CORBA specification
defines an interface to the ORB. This ORB interface provides standard operations to initialize and
shutdown the ORB, convert object references to strings and back, and create argument lists for requests
made through the DII.

10 Implementation Repository (IMR): IMR contains the information that allows an ORB to
activate servers on demand.

Table 6.1 BOA Vs POA (June 2010)(10 Marks)

Features BOA POA


Acronym for Basic Object Adapter Portable Object Adapter
Complete Specification No, since the BOA deal with Yes, since the POA deals with
servers and completely ignore servants, their activation and
the subject of servants deactivation but completely
ignores the handling of servers
and processes
Provision of Default servant Its application can’t provide a Its application can provide a
default servant default servant
ORB Synchronization No Yes
Scalability No Yes
Flexibility No Yes
Persistency No Yes
Implementation Repository Yes No

6.4 Method Invocations

The invocation of the remote CORBA object is done as follows (Fig. 6.4)
1. The remote CORBA object registers itself in the CORBA naming server. It provides a
mapping for the remote object name and IOR.

2. The client refers the CORBA naming service using the object name.

3. The CORBA naming service returns the IOR of the remote object.

98
Middleware and Enterprise Integration Technologies

4. Client procedure calls client stub using a local procedure call. Conceptually, a client stub
contains a set of functions with the same name as the remote function. Stubs can be
generated automatically using the IDL compilers and are included in code during
compilation.

5. The client stub calls the network routines using system calls.

6. In this step, the local kernel sends the message to the remote kernel.

7. Once the message is successfully received by the remote kernel, it is transferred to the
OA.

8. OA then transfers the call to the server skeleton.

9. Once the control is handed to the server skeleton, it unpacks the parameters and calls the
server procedure. This process is called as unmarshalling.

10. Server does the work and returns the result to the skeleton.
11. The skeleton then packs the results in a message to OA.
12. OA contacts the RPC layer protocol (ORB core).
13. ORB then transmits the results to the client.
14. The client’s kernel gives the results to the client stub.
15. The client stub unpacks the results and returns them to the client procedure.

99
Middleware and Enterprise Integration Technologies

Fig. 6.4 Remote Method Invocation in CORBA

6.5 Static and Dynamic CORBA

CORBA provides two different interfaces for clients to communicate with servers:

1. Static Invocation Interface (SII) – is provided by static stubs generated by a CORBA IDL
compiler and is useful when client applications know the interface offered by the server at
compile-time.

2. Dynamic Invocation Interface (DII) – is provided by an ORB’s dynamic messaging


mechanism and is useful when client applications do not have compile-time knowledge of the
interfaces offered by servers.

Many distributed applications can be written using CORBA’s SII. However, there is an important
class of applications (such as network management MIB browsers, configuration management
tools and distributed visualization tools and debuggers) that are easier to develop using CORBA’s

100
Middleware and Enterprise Integration Technologies

DII. The DII enables applications to construct and invoke CORBA requests at run-time by
querying the Interface Repository of a server.

In addition, the DII is required for applications that use CORBA’s deferred synchronous model of
operation invocation. Although all operation invocations in CORBA are synchronous, there are
three models of invocation:

a. Twoway synchronous – which is the typical request/ response model associated


with RPC toolkits, where the client blocks after sending the request until the
response arrives from the server;

b. Oneway synchronous – which is a “request-only” messaging model where the


client does not receive a response;

c. Deferred synchronous – this model of two way call decouples the request from
the response so that other client processing can occur until the server sends the
response.

The DII supports all three forms of invocation semantics, whereas the SII stubs only support
twoway and oneway synchronous calls. Note that neither oneway nor deferred synchronous
CORBA calls are asynchronous since the CORBA specification permits the ORB to block while
sending a oneway call (e.g., if the underlying transport layer connection is flow controlled).

Components of Dynamic CORBA

Dynamic CORBA consists of the following components:


1. TypeCode, which provides a structural type representation,

101
Middleware and Enterprise Integration Technologies

Fig.6.5 (a) Portion of IDL showing declaration of the structure “bar” and (b) TypeCode
format for structure “bar”.

2. Any, which represents a value in dynamic CORBA applications,

.
Fig. 6.6 Any

3. NamedValue/NVList, which provide a dynamic representation of operation arguments


and signatures,

102
Middleware and Enterprise Integration Technologies

Fig. 6.7 NamedValue

Fig.6.8 NVList
4. Dynamic Invocation Interface (DII), which defines the client-side interface for
dynamic CORBA applications,
5. Dynamic Skeleton Interface (DSI), which is the server-side counterpart to the DII,
6. TypeCodeFactory, which is used to create types dynamically,
7. Dynamic Any, which is used to create and examine values in dynamic CORBA
applications,
8. Interface Repository (IFR), which is a distributed service that provides run-time access
to CORBA type information, and
9. IFR loader, which populates the Interface Repository with entries that correspond to IDL
declarations.

Working of Dynamic CORBA

103
Middleware and Enterprise Integration Technologies

Fig. 6.9 Working of Dynamic CORBA

The working of dynamic invocation in CORBA using the components described is explained as follows:

1. Registering IFR in the naming service.

2. IFR loader gets the interface details from the IDL file & stores it in IFR.

3. IFR loader gets the operation details from the IDL file & stores it in IFR.

4. Client looks up & identifies the location of IFR.

5. Client looks up for the interfaces details from IFR.

6. Client looks up for the operation details from IFR.

7. Client gets argument types details from IFR.

8. IFR creates TypeCode using TypeCodeFactory.

9. Client returns the TypeCode to the client.

10. The following sequence of actions is performed at the client side.

A. Client uses DynamicAnyFactory to create DynamicAny type.

B. Client stores the inout values in this type & forms the Any type.

104
Middleware and Enterprise Integration Technologies

C. The DIIRequestObject is formed by the client.

D. The Any type parameters are stored in the RequestObject.

E. The target object is now invoked using this RequestObject.

11. The response is now sent by the target object to the client.

12. The DIIRequestObject receives this response & returns the result to the client.

6.5 Interface Definition Language

The CORBA Interface Definition Language (IDL) is used to define interfaces to objects in your network.
Now we introduce the features of CORBA IDL and illustrate the syntax used to describe interfaces.
The first step in developing a CORBA application is to define the interfaces to the objects required in
your distributed system. To define these interfaces, you use CORBA IDL.
IDL allows you to define interfaces to objects without specifying the implementation of those interfaces.

To implement an IDL interface you must:


1. Define a Java class that can be accessed through the IDL interface.
2. Create objects of that class within an Orbix Java server application.

You can implement IDL interfaces using any programming language for which an IDL mapping is
available. An IDL mapping specifies how an interface defined in IDL corresponds to an implementation
defined in a programming language. CORBA applications written in different programming languages are
fully interoperable.
CORBA defines standard mappings from IDL to several programming languages, including C++, Java,
and Smalltalk. The Orbix Java IDL compiler converts IDL definitions to corresponding Java definitions,
in accordance with the standard IDL to Java mapping.

IDL Modules and Scoping


An IDL module defines a naming scope for a set of IDL definitions. Modules allow you to group
interface and other IDL type definitions into logical name spaces. When writing IDL definitions, always
use modules to avoid possible name clashes.

The following example illustrates the use of modules in IDL:


// IDL
module finance {
interface account {
...
};
};

The interface account is scoped within the module finance. IDL definitions are available directly within
the scope in which they are defined. In other naming scopes, you must use the scoping operator :: to
access these definitions. For example, the fully scoped name of interface account is finance::account.
IDL modules can be reopened. For example, a module declaration can appear several times in a single
IDL specification if each declaration contains different data types. In most IDL specifications, this feature
of modules is not required.

105
Middleware and Enterprise Integration Technologies

Defining IDL Interfaces


An IDL interface describes the functions that an object supports in a distributed application. Interface
definitions provide all the information that clients need to access the object across a network.
Consider the example of an interface that describes objects that implement bank accounts in a distributed
application.
The IDL interface definition is as follows:
//IDL
module finance {
interface account {
// The account owner and balance.
readonly attribute string owner;
readonly attribute float balance;

// Operations available on the account.


void makeLodgement(in float amount,
out float newBalance);
void makeWithdrawal(in float amount,
out float newBalance);
};
};

Note that each parameter has a qualifier that indicates whether the argument is either in, out or inout. An
out parameter is used to transmit data from the server to the client. An inout argument is used to pass
information from the client to the server as a regular argument (in) but also is used to communicate values
back to the client from the server. The out arguments are used much like passing pointers in C so they
callee can modify the contents of the object. It allows more than one object to returned, avoiding putting
them into a container structure and making this the return type.

The definition of interface account includes both attributes and operations. These are the main elements
of any IDL interface definition.

Raising Exceptions in IDL Operations


IDL operations can raise exceptions to indicate the occurrence of an error. CORBA defines two types of
exceptions:
• System exceptions

These are a set of standard exceptions defined by CORBA.

• User-defined exceptions

These are exceptions that you define in your IDL specification.

All IDL operations can implicitly raise any of the CORBA system exceptions. No reference to system
exceptions appears in an IDL specification

An IDL exception is a data structure that contains member fields.

106
Middleware and Enterprise Integration Technologies

When defining an IDL operation, you can specify that the operation should receive the client mapping for
particular identifiers as an implicit part of the operation call. To do this, add a context clause to the
operation definition.

Consider the example of an account object, where each client maintains a set of identifiers, such
as sys_time and sys_location, that map to information that the operation makeLodgement() logs for each
lodgement received.

To ensure that this information is passed with every operation call, extend the definition
of makeLodgement() as follows:
// IDL
module finance {
interface account {
void makeLodgement(in float amount,
out float newBalance)
context("sys_time", "sys_location");
...
};
};
A context clause includes the identifiers for which the operation expects to receive mappings. IDL
contexts are rarely used in practice.

Inheritance of IDL Interfaces

IDL supports inheritance of interfaces. An IDL interface can inherit all the elements of one or more other
interfaces.
For example, the following IDL definition illustrates two interfaces
called checkingAccount and savingsAccount. Both of these inherit from an interface named account:

// IDL
module finance {
interface account {
...
};

interface checkingAccount : account {


readonly attribute overdraftLimit;
boolean orderChequeBook ();
};

interface savingsAccount : account {


float calculateInterest ();
};
};

Interfaces checkingAccount and savingsAccount implicitly include all elements of interface account.
An object that implements checkingAccount can accept calls on any of the attributes and operations of
this interface, and also on any of the elements of interface account. However, a checkingAccount object
may provide different implementations of the elements of interface account to an object that
implements account only.

107
Middleware and Enterprise Integration Technologies

The following IDL definition shows how to define an interface that inherits
both checkingAccount and savingsAccount:
// IDL
module finance {
interface account {
...
};

interface checkingAccount : account {


...
};

interface savingsAccount : account {


...
};

interface premiumAccount :
checkingAccount, savingsAccount {
};
};

Interface premiumAccount is an example of multiple inheritance in IDL illustrates the inheritance


hierarchy for this interface.

Fig.6.10 Multiple Inheritance of IDL Interfaces

If you define an interface that inherits from other interfaces containing a constant, type, or exception
definition of the same name, you must fully scope that name when using the constant, type, or exception.

The Object Interface Type

IDL includes the pre-defined interface Object, which all user-defined interfaces inherit implicitly. The
operations defined in this interface are described in the Orbix Programmer's Reference Java
Edition. While interface Object is never defined explicitly in your IDL specification, the operations of this
interface are available through all your interface types. In addition, you can use Object as an attribute or
operation parameter type to indicate that the attribute or operation accepts any interface type, for example:

108
Middleware and Enterprise Integration Technologies

// IDL
interface ObjectLocator {
void getAnyObject (out Object obj);
};

It is not legal IDL syntax to explicitly inherit interface Object.

Forward Declaration of IDL Interfaces

In IDL, you must declare an IDL interface before you reference it. A forward declaration declares the
name of an interface without defining it. This feature of IDL allows you to define interfaces that mutually
reference each other.

For example, IDL interface account could include an attribute of IDL interface type bank, to indicate that
an account stores a reference to a bankobject. If the definition of interface bank follows the definition of
interface account, you would make a forward declaration for the bank interface as follows:

// IDL
module finance {
// Forward declaration of bank.
interface bank;
interface account {
readonly attribute bank branch;
...
};

// Full definition of bank.


interface bank {
...
};
};

The syntax for a forward declaration is the keyword interface followed by the interface identifier.
The following IDL definition, for example, is not permitted:

//IDL
module finance{
//Forward declaration of bank.
interface bank;

interface account Bigbank:bank{


...
}

Overview of the IDL Data Types

In addition to IDL module, interface, and exception types, there are four main categories of data type in
IDL:
• Basic types
• Constructed types

109
Middleware and Enterprise Integration Technologies

• Template types
• Pseudo object types
This section examines each IDL data type in turn, and describes how you can define new data type names,
arrays, and constants in IDL.

IDL Basic Types

Table 6.2 The basic types supported in IDL.


IDL Type Range of Values
short -2 15...2 15-1 (16-bit)
unsigned short 0...2 16-1 (16-bit)
long -2 31...2 31-1 (32-bit)
unsigned long 0...2 32-1 (32-bit)
long long -2 63...2 63-1 (64-bit)
unsigned long 0...2 63-1 (64-bit)
long
float IEEE single-precision floating point numbers.
double IEEE double-precision floating point numbers.
char An 8-bit value.
wchar A 16-bit value.
boolean TRUE or FALSE.
octet An 8-bit value that is guaranteed not to undergo any conversion during transmission.
any The any type allows the specification of values that can express an arbitrary IDL
type.

The any data type allows you to specify that an attribute value, an operation parameter, or an operation
return value can contain an arbitrary type of value to be determined at runtime.

IDL Constructed Types

IDL provides three constructed data types:


• enum
• struct
• union

Enum
An enumerated type allows you to assign identifiers to the members of a set of values, for example:

// IDL
module finance {
enum currency {pound, dollar, yen, franc};

interface account {
readonly attribute float balance;
readonly attribute currency balanceCurrency;

110
Middleware and Enterprise Integration Technologies

...
};
};
In this example, attribute balanceCurrency in interface account can take any one of the
values pound, dollar, yen, or franc to indicate the currency associated with the attribute balance.

Struct
A struct data type allows you to package a set of named members of various types, for example:

// IDL
module finance {
struct customerDetails {
string name;
short age;
};

interface bank {
customerDetails getCustomerDetails(
in string name);
...
};
};

In this example, the struct customerDetails has two members: name and age. The
operation getCustomerDetails() returns a struct of typecustomerDetails that includes values for the
customer name and age.

Union
A union data type allows you to define a structure that can contain only one of several alternative
members at any given time. A union saves memory space, because the amount of storage required for a
union is the amount necessary to store its largest member.
All IDL unions are discriminated. This means that they associate a label value with each member. The
value of the label indicates which member of the union currently stores a value.
For example, consider the following IDL union definition:

// IDL
struct DateStructure {
short Day;
short Month;
short Year;
};

union Date switch (short) {


case 1: string stringFormat;;
case 2: long digitalFormat;
default: DateStructure structFormat;
};
The union type Date is discriminated by a short value. For example, if this short value is 1, the union
member stringFormat stores a date value as an IDL string. The default label associated with the

111
Middleware and Enterprise Integration Technologies

member structFormat indicates that if the short value is not 1 or 2, the structFormat member stores a date
value as an IDL struct.
The type specified in parentheses after the switch keyword must be an integer, char, boolean or enum type
and the value of each case label must be compatible with this type.

Arrays
In IDL, you can declare an array of any IDL data type. IDL arrays can be multidimensional and always
have a fixed size. For example, you can define an IDL struct with an array member as follows:

// IDL
module finance {
interface account {
...
};

struct customerAccountInfo {
string name;
account accounts[3];
};

interface bank {
getCustomerAccountInfo (in string name,
out customerAccountInfo accounts);
...
};
};

In this example, struct customerAccountInfo provides access to an array of account objects for a bank
customer, where each customer can have a maximum of three accounts.
As with sequences, an array must be named by an IDL typedef declaration before it can be used as the
type of an IDL attribute or operation parameter. The following code illustrates this:

// IDL
module finance {
interface account {
...
};
typedef account accountArray[100];

interface bank {
readonly attribute accountArray accounts;
...
};
};

6.6 Interface Repository

The Interface Repository is the component of the ORB that provides persistent storage of interface
definitions—it manages and provides access to a collection of object definitions specified in OMG IDL.

112
Middleware and Enterprise Integration Technologies

An ORB provides distributed access to a collection of objects using the objects’ publicly defined
interfaces specified in OMG IDL. The Interface Repository provides for the storage, distribution, and
management of a collection of related objects’ interface definitions.
For an ORB to correctly process requests, it must have access to the definitions of the objects it is
handling. Object definitions can be made available to an ORB in one of two forms:
1. By incorporating the information procedurally into stub routines (e.g., as code that maps C language
subroutines into communication protocols).
2. As objects accessed through the dynamically accessible Interface Repository (i.e., as interface objects
accessed through OMG IDL-specified interfaces).
In particular, the ORB can use object definitions maintained in the Interface Repository to interpret and
handle the values provided in a request to:

• Provide type-checking of request signatures (whether the request was issued through the DII or
through a stub).
• Assist in checking the correctness of interface inheritance graphs.
• Assist in providing interoperability between different ORB implementations.

As the interface to the object definitions maintained in an Interface Repository is public, the information
maintained in the Repository can also be used by clients and services. For example, the Repository can be
used to:
• Manage the installation and distribution of interface definitions.
• Provide components of a CASE environment (for example, an interface browse
• Provide interface information to language bindings (such as a compiler).
• Provide components of end-user environments (for example, a menu bar constructor).

Interface definitions are maintained in the Interface Repository as a set of objects that are accessible
through a set of OMG IDL-specified interface definitions. An interface definition contains a description
of the operations it supports, including the types of the parameters, exceptions it may raise, and context
information it may use.

In addition, the interface repository stores constant values, which might be used in other interface and
value definitions or might simply be defined for programmer convenience and it stores TypeCodes.

The Interface Repository consists of a set of interface repository objects that represent the information in
it. There are operations that operate on this apparent object structure. It is an implementation’s choice
whether these objects exist persistently or are created when referenced in an operation on the repository.
There are also operations that extract information in an efficient form, obtaining a block of information
that describes a whole interface or a whole operation.

An ORB may have access to multiple Interface Repositories. This may occur because
• two ORBs have different requirements for the implementation of the Interface Repository,
• an object implementation (such as an OODB) prefers to provide its own type information, or
• it is desired to have different additional information stored in different repositories.

Some of the entities in an interface repository are:


1. Repository IDs: They uniquely identify modules, interfaces, constants, typedefs, exceptions, attributes,
and operations.
2. TypeCodes: It determines the complete structure of the type.

113
Middleware and Enterprise Integration Technologies

3. Interface Repository Objects (IRO): They determine the IDL definitions. Some examples of interface
repository objects are RepositoryDef, ModuleDef, InterfaceDef, ValueDef, OperationDef, TypedefDef,
ConstantDef.

Fig. 6.11 Interface Repository Containment Hierarchy

6.7 Building an Application using CORBA

Step1: Writing an IDL for the remote object

IDL has a syntax similar to C++ and can be used to define modules, interfaces, data structures, and more.
The IDL can be mapped to a variety of programming languages. The following code is written in the
OMG IDL, and describes a CORBA object whose sayHello() operation returns a string and whose
shutdown() method shuts down the ORB.

//Hello.idl
module HelloApp
{
interface Hello
{
string sayHello();
oneway void shutdown();
};
};

Step 2: Implementing the Server (HelloServer.java)

The example server consists of two classes, the servant and the server. The servant, HelloImpl, is the
implementation of the Hello IDL interface; each Hello instance is implemented by a HelloImpl instance.
The servant is a subclass of HelloPOA, which is generated by the idlj compiler from the example IDL.

114
Middleware and Enterprise Integration Technologies

The servant contains one method for each IDL operation, in this example, the sayHello() and shutdown()
methods. Servant methods are just like ordinary Java methods; the extra code to deal with the ORB, with
marshaling arguments and results, and so on, is provided by the skeleton.

The HelloServer class has the server's main() method, which:

• Creates and initializes an ORB instance


• Gets a reference to the root POA and activates the POAManager
• Creates a servant instance (the implementation of one CORBA Hello object) and tells the ORB
about it
• Gets a CORBA object reference for a naming context in which to register the new CORBA object
• Gets the root naming context
• Registers the new object in the naming context under the name "Hello"
• Waits for invocations of the new object from the client

This example provides an example of a transient object server.

// HelloServer.java

import HelloApp.*;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*;
import org.omg.PortableServer.*;
import org.omg.PortableServer.POA;

import java.util.Properties;

class HelloImpl extends HelloPOA {


private ORB orb;

public void setORB(ORB orb_val) {


orb = orb_val;
}

// implement sayHello() method


public String sayHello() {
return "\nHello world !!\n";
}

// implement shutdown() method


public void shutdown() {
orb.shutdown(false);
}
}

public class HelloServer {

public static void main(String args[]) {


try{
// create and initialize the ORB
ORB orb = ORB.init(args, null);

115
Middleware and Enterprise Integration Technologies

// get reference to rootpoa & activate the POAManager


POA rootpoa =
POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
rootpoa.the_POAManager().activate();

// create servant and register it with the ORB


HelloImpl helloImpl = new HelloImpl();
helloImpl.setORB(orb);

// get object reference from the servant


org.omg.CORBA.Object ref = rootpoa.servant_to_reference(helloImpl);
Hello href = HelloHelper.narrow(ref);

// get the root naming context


// NameService invokes the name service
org.omg.CORBA.Object objRef =
orb.resolve_initial_references("NameService");
// Use NamingContextExt which is part of the Interoperable
// Naming Service (INS) specification.
NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);

// bind the Object Reference in Naming


String name = "Hello";
NameComponent path[] = ncRef.to_name( name );
ncRef.rebind(path, href);

System.out.println("HelloServer ready and waiting ...");

// wait for invocations from clients


orb.run();
}

catch (Exception e) {
System.err.println("ERROR: " + e);
e.printStackTrace(System.out);
}

System.out.println("HelloServer Exiting ...");

}
}

Step 3: Implementing the Client Application (HelloClient.java)


The example application client that follows:
• Creates and initializes an ORB
• Obtains a reference to the root naming context
• Looks up "Hello" in the naming context and receives a reference to that CORBA object
• Invokes the object's sayHello() and shutdown() operations and prints the result

// HelloClient.java

import HelloApp.*;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*;

116
Middleware and Enterprise Integration Technologies

public class HelloClient


{
static Hello helloImpl;

public static void main(String args[])


{
try{
// create and initialize the ORB
ORB orb = ORB.init(args, null);

// get the root naming context


org.omg.CORBA.Object objRef =
orb.resolve_initial_references("NameService");
// Use NamingContextExt instead of NamingContext. This is
// part of the Interoperable naming Service.
NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);

// resolve the Object Reference in Naming


String name = "Hello";
helloImpl = HelloHelper.narrow(ncRef.resolve_str(name));

System.out.println("Obtained a handle on server object: " +


helloImpl);
System.out.println(helloImpl.sayHello());
helloImpl.shutdown();

} catch (Exception e) {
System.out.println("ERROR : " + e) ;
e.printStackTrace(System.out);
}
}

Step 4: To run this client-server application on your development machine:


1. Change to the directory that contains the file Hello.idl.
2. Run the IDL-to-Java compiler, idlj, on the IDL file to create stubs and skeletons. This step
assumes that you have included the path to the java/bin directory in your path.
3. idlj -fall Hello.idl
You must use the -fall option with the idlj compiler to generate both client and server-side bindings.
This command line will generate the default server-side bindings, which assumes the POA
Inheritance server-side model.
The idlj compiler generates a number of files. The actual number of files generated depends on the
options selected when the IDL file is compiled. The generated files provide standard functionality, so
you can ignore them until it is time to deploy and run your program. The files generated by the idlj
compiler for Hello.idl, with the -fall command line option, are:

• HelloPOA.java

This abstract class is the stream-based server skeleton, providing basic CORBA functionality for
the server. It extends org.omg.PortableServer.Serva nt , and implements the InvokeHandler
interface and the HelloOperations interface. The server class HelloImpl extends HelloPOA.

117
Middleware and Enterprise Integration Technologies

• _HelloStub.java

This class is the client stub, providing CORBA functionality for the client. It extends
org.omg.CORBA.portable.ObjectImpl and implements the Hello.java interface.

• Hello.java

This interface contains the Java version of our IDL interface. The Hello.java interface extends
org.omg.CORBA.Object, providing standard CORBA object functionality. It also extends the
HelloOperations interface and org.omg.CORBA.portable.IDLEntity.

• HelloHelper.java

This class provides auxiliary functionality, notably the narrow() method required to cast CORBA
object references to their proper types.The Helper class is responsible for reading and writing
the data type to CORBA streams, and inserting and extracting the data type from Anys. The
Holder class delegates to the methods in the Helper class for reading and writing.

• HelloHolder.java

This final class holds a public instance member of type Hello. Whenever the IDL type is an out or
an inout parameter, the Holder class is used. It provides operations for
org.omg.CORBA.portable.OutputStream and org.omg.CORBA.portable.InputStream arguments,
which CORBA allows, but which do not map easily to Java's semantics. The Holder class
delegates to the methods in the Helper class for reading and writing. It implements
org.omg.CORBA.portable.Streamable.

• HelloOperations.java

This interface contains the methods sayHello() and shutdown(). The IDL-to-Java mapping puts all
of the operations defined on the IDL interface into this file, which is shared by both the stubs
and skeletons.

Step 5: Compile the .java files, including the stubs and skeletons (which are in the directory
HelloApp). This step assumes the java/bin directory is included in your path.

javac *.java HelloApp/*.java

Step 6: Start orbd.

To start orbd from a UNIX command shell, enter:

orbd -ORBInitialPort 1050&

From an MS-DOS system prompt (Windows), enter:

start orbd -ORBInitialPort 1050

118
Middleware and Enterprise Integration Technologies

Note that 1050 is the port on which you want the name server to run. The -ORBInitialPort argument is a
required command-line argument. Note that when using Solaris software, you must become root to
start a process on a port under 1024. For this reason, we recommend that you use a port number
greater than or equal to 1024.

Step 7: Start the Hello server:

To start the Hello server from a UNIX command shell, enter:

java HelloServer -ORBInitialPort 1050 -ORBInitialHost localhost&

From an MS-DOS system prompt (Windows), enter:

start java HelloServer -ORBInitialPort 1050 -ORBInitialHost localhost

Step 8: Run the client application:

java HelloClient -ORBInitialPort 1050 -ORBInitialHost localhost

Note: With similar steps you can execute the following codes in Lab Experiments

Lab Experiments
1. WEATHER FORECAST INFORMATION USING CORBA

Weather.idl :

module WeatherForecast{
interface Weather{
double get_celsius(in string symbol);
};
};

WeatherForecastImpl.java :

import org.omg.CORBA.*;
import WeatherForecast.*;
public class WeatherForecastImpl extends _WeatherImplBase {
public double get_celsius(String symbol) {
double celsius = Double.parseDouble(symbol);
double fahrenheit = 1.8 * celsius+32;
return fahrenheit;
}
public WeatherForecastImpl()
{super();}
}

119
Middleware and Enterprise Integration Technologies

WeatherForecastClient.java :

import org.omg.CORBA.*;
import org.omg.CosNaming.*;
import WeatherForecast.*;
import java.io.*;
public class WeatherForecastClient{
public static void main(String args[]) {
try{
ORB orb=ORB.init(args,null);
NamingContext ncRef =
NamingContextHelper.narrow(orb.resolve_initial_references("NameService"));
NameComponent path[]={new NameComponent("FORECAST","")};
Weather weather = WeatherHelper.narrow(ncRef.resolve(path));
System.out.println("Enter the celsius");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String cel = br.readLine();
System.out.println("Temperature of my city in Fahrenheit is " +
weather.get_celsius(cel));
}
catch(Exception e){ e.printStackTrace(); }
}
}

WeatherForecastServer.java :

import org.omg.CORBA.*;
import org.omg.CosNaming.*;
import WeatherForecast.*;
public class WeatherForecastServer{
public static void main(String args[]){
try{
ORB orb = ORB.init(args,null);
WeatherForecastImpl weatherForecastImpl = new WeatherForecastImpl();
orb.connect(weatherForecastImpl);
org.omg.CORBA.Object objRef =
orb.resolve_initial_references("NameService");
NamingContext ncRef = NamingContextHelper.narrow(objRef);
NameComponent nc=new NameComponent("FORECAST","");
NameComponent path[]={nc};
ncRef.rebind(path,weatherForecastImpl);
System.out.println("The WeatherForecast Server is up and ready..");
Thread.currentThread().join();
}
catch(Exception e) {e.printStackTrace();}
}
}

120
Middleware and Enterprise Integration Technologies

Step 1: save all the programs in C:\j2sdk1.4.1_01\bin or set path as >path=c:\j2sdk1.4.1_01\bin


Step 2: open one command prompt
Step 3: C:\J2SDK1~1.1_0\bin>set classpath=;.
Step 4: C:\J2SDK1~1.1_0\bin>idlj -oldImplBase -fall Weather.idl
Folder WeatherForecast is created
Step 5: C:\J2SDK1~1.1_0\bin>set classpath=%classpath%;.
Step 6: C:\J2SDK1~1.1_0\bin>javac WeatherForecastImpl.java
Step 7: C:\J2SDK1~1.1_0\bin>javac WeatherForecastServer.java
Step 8: C:\J2SDK1~1.1_0\bin>tnameserv
Initial Naming Context:
IOR:000000000000002b49444c3a6f6d672e6f72672f436f734e616d696e672f4e616d696e67436f
6e746578744578743a312e300000000000010000000000000084000102000000000f3133322e3134
372e3137312e333300000384000000000035afabcb0000000020a209fcb600000001000000000000
00010000000d544e616d65536572766963650000000000000004000000000a000000000000010000
0001000000200000000000010001000000020501000100010020000101090000000100010100
TransientNameServer: setting port for initial object references to: 900
Ready.
Folder orb.db is created
Step 9: open another command prompt2
Step 10: C:\j2sdk1.4.1_01\bin>set classpath=;.
Step 11: C:\j2sdk1.4.1_01\bin>java WeatherForecastServer
The WeatherForecast Server is up and ready..
Step 12: open another command prompt3
Step 13: C:\J2SDK1~1.1_0\bin>set classpath=;.
Step 14: C:\J2SDK1~1.1_0\bin>javac WeatherForecastClient.java
Step 15: C:\J2SDK1~1.1_0\bin>java WeatherForecastClient
Enter the Celsius 36.9
Temperature of my city in Fahrenheit is 98.42

2. Code for Program for calculating area of a circle on server side, when a client sends
request along with given radius and then displaying result on client side in Java
----------------------------------------------------------------------------------
IDL: Circle.idl
----------------------------------------------------------------------------------
module CircleApp
{
interface Circle
{
float area(in float val);
oneway void shutdown();
};
};

-------------------------------------------------------------------------------------------------
Server: CircleServer.java
-------------------------------------------------------------------------------------------------

import CircleApp.*;

121
Middleware and Enterprise Integration Technologies

import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*;
import org.omg.PortableServer.*;
import org.omg.PortableServer.POA;

import java.util.Properties;

class CircleImpl extends CirclePOA


{
private ORB orb;

publicvoid setORB(ORB orb_val)


{
orb = orb_val;
}

publicfloat area(float val)


{
float res = (float)( Math.PI * val * val );
return res;
}
publicvoid shutdown()
{
orb.shutdown(false);
}
}

public class CircleServer


{

Public static void main(String args[])


{
try
{
ORB orb = ORB.init(args, null);
POA rootpoa = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
rootpoa.the_POAManager().activate();

CircleImpl circleImpl = new CircleImpl();


circleImpl.setORB(orb);

org.omg.CORBA.Object ref = rootpoa.servant_to_reference(circleImpl);


Circle href = CircleHelper.narrow(ref);

org.omg.CORBA.Object objRef =orb.resolve_initial_references("NameService");


NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);

String name = "Circle";


NameComponent path[] = ncRef.to_name( name );

122
Middleware and Enterprise Integration Technologies

ncRef.rebind(path, href);

System.out.println("CircleServer ready and waiting ...");

orb.run();
}

catch (Exception e)
{
System.err.println("ERROR: " + e);
e.printStackTrace(System.out);
}

System.out.println("CircleServer Exiting ...");


}
}

-------------------------------------------------------------------------------------------------
Client: CircleClient.java
-------------------------------------------------------------------------------------------------

import CircleApp.*;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*;
import java.io.*;

public class CircleClient


{
public float getValue() throws IOException
{
float val = 0;
try
{
System.out.print("Enter the value : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s=br.readLine();
val = Float.parseFloat (s);
}
catch (IOException e)
{
System.out.println(e);
}
return val;
}

public static void main(String args[])


{
Circle circleImpl=null;
CircleClient cc = new CircleClient();

123
Middleware and Enterprise Integration Technologies

try
{
ORB orb = ORB.init(args, null);
org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService");
NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);
String name = "Circle";
circleImpl = CircleHelper.narrow(ncRef.resolve_str(name));

float val = 0, res = 0;


val = cc.getValue();
res=circleImpl.area(val);
System.out.println("Result : " + res);

circleImpl.shutdown();

}
catch (Exception e)
{
System.out.println("ERROR : " + e) ;
e.printStackTrace(System.out);
}
}

-------------------------------------------------------------------------------------------------
Output
-------------------------------------------------------------------------------------------------

Enter the value : 2


Result : 12.566371

3. Code for Develop a simple calculator with addition, subtraction, multiplication and
division capabilities, data collection from client side, executed on server in Java

----------------------------------------------------------------------------------
IDL: Calc.idl
----------------------------------------------------------------------------------
module CalcApp
{
interface Calc
{
float add(in float value1,in float value2);
float sub(in float value1,in float value2);
float multi(in float value1,in float value2);
float div(in float value1,in float value2);
oneway void shutdown();
};

};

124
Middleware and Enterprise Integration Technologies

----------------------------------------------------------------------------------
Server: CalcServer.java
----------------------------------------------------------------------------------
import CalcApp.*;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*;
import org.omg.PortableServer.*;
import org.omg.PortableServer.POA;

import java.util.Properties;

class CalcImpl extends CalcPOA


{
private ORB orb;

public void setORB(ORB orb_val)


{
orb = orb_val;
}
public float add(float val1, float val2)
{
float res = val1 + val2;
return res;
}
public float sub(float val1, float val2)
{
float res = val1 - val2;
return res;
}
public float multi(float val1, float val2)
{
float res = val1 * val2;
return res;
}
public float div(float val1, float val2)
{
float res = val1 / val2;
return res;
}
public void shutdown()
{
orb.shutdown(false);
}
}

public class CalcServer


{

public static void main(String args[])

125
Middleware and Enterprise Integration Technologies

{
try
{

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

POA rootpoa = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));


rootpoa.the_POAManager().activate();
CalcImpl calcImpl = new CalcImpl();
calcImpl.setORB(orb);
org.omg.CORBA.Object ref = rootpoa.servant_to_reference(calcImpl);
Calc href = CalcHelper.narrow(ref);
org.omg.CORBA.Object objRef =
orb.resolve_initial_references("NameService");
NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);
String name = "Calc";
NameComponent path[] = ncRef.to_name( name );
ncRef.rebind(path, href);

System.out.println("Calculator Server ready and waiting ...");

orb.run();
}

catch (Exception e)
{
System.err.println("ERROR: " + e);
e.printStackTrace(System.out);
}

System.out.println("Calculator Server Exiting ...");


}
}

-------------------------------------------------------------------------------------------------
Client: CalcClient.java
-------------------------------------------------------------------------------------------------

import CalcApp.*;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*;
import java.io.*;

publicclass CalcClient
{
publicvoid showMenu()
{
System.out.println("----------------------------------");
System.out.println("0.Exit");

126
Middleware and Enterprise Integration Technologies

System.out.println("1.Addition");
System.out.println("2.Subtraction");
System.out.println("3.Multiplication");
System.out.println("4.Division");
System.out.println("----------------------------------");
System.out.print("Enter your choice : ");

}
publicfloat getValue() throws IOException
{
float val=0;
try
{
System.out.print("Enter the value : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
val = Float.parseFloat(s);
}
catch (IOException e)
{
System.out.println(e);
}
return val;
}
publicint getChoice() throws IOException
{
int val=0;
try
{

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));


val = Integer.parseInt(br.readLine());
System.out.println("----------------------------------");
}
catch (IOException e)
{
System.out.println(e);
}
return val;
}

publicstaticvoid main(String args[])


{

Calc calcImpl = null;


CalcClient cc = new CalcClient();

try
{

127
Middleware and Enterprise Integration Technologies

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


org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService");
NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);
String name = "Calc";
calcImpl = CalcHelper.narrow(ncRef.resolve_str(name));
float val1 = 0;
float val2 = 0;
float res = 0;
int ch = 1;

while (ch != 0 )
{
cc.showMenu();
ch = cc.getChoice();

val1 = cc.getValue();
val2 = cc.getValue();

switch (ch)
{
case 1:
res = calcImpl.add(val1, val2);
break;
case 2:
res = calcImpl.sub(val1, val2);
break;
case 3:
res = calcImpl.multi(val1, val2);
break;
case 4:
res = calcImpl.div(val1, val2);
break;
case 0:
exit(0);
}
System.out.println("----------------------------------");
System.out.println("Result : "+res);
System.out.println("----------------------------------");
}

calcImpl.shutdown();
}
catch (Exception e)
{
System.out.println("ERROR : " + e) ;
e.printStackTrace(System.out);
}
}

128
Middleware and Enterprise Integration Technologies

-------------------------------------------------------------------------------------------------
Output
-------------------------------------------------------------------------------------------------

----------------------------------
0.Exit
1.Addition
2.Subtraction
3.Multiplicatin
4.Division
----------------------------------
Enter your choice : 2
----------------------------------
Enter the value : 20.5
Enter the value : 10.2
----------------------------------
Result : 10.3
----------------------------------
----------------------------------
0.Exit
1.Addition
2.Subtraction
3.Multiplication
4.Division
----------------------------------
Enter your choice : 0

4. Write a program for CORBA IDL and server class to calculate interest:

Input parameters: principal amount, rate and no. of years

Output parameter: interest value (May 2010)(10 Marks)

//Interest.idl
module InterestApp
{
interface Interest
{
float calc(in float value1,in float value2,in float value3 );
oneway void shutdown();
};
};

//InterestServer.java
import InterestApp.*;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*;
import org.omg.PortableServer.*;

129
Middleware and Enterprise Integration Technologies

import org.omg.PortableServer.POA;

import java.util.Properties;

class InterestImpl extends InterestPOA


{
private ORB orb;

public void setORB(ORB orb_val)


{
orb = orb_val;
}

public float calc(float val1, float val2,float val3)


{
float res = (float)( val1 * val2 * val3 / 100 );
return res;
}
public void shutdown()
{
orb.shutdown(false);
}
}

public class InterestServer


{

public static void main(String args[])


{
try
{
ORB orb = ORB.init(args, null);
POA rootpoa = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
rootpoa.the_POAManager().activate();

InterestImpl interestImpl = new InterestImpl();


interestImpl.setORB(orb);

org.omg.CORBA.Object ref = rootpoa.servant_to_reference(interestImpl);


Interest href = InterestHelper.narrow(ref);

org.omg.CORBA.Object objRef =orb.resolve_initial_references("NameService");


NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);

String name = "Interest";


NameComponent path[] = ncRef.to_name( name );
ncRef.rebind(path, href);

System.out.println("Interest Server ready and waiting ...");

130
Middleware and Enterprise Integration Technologies

orb.run();
}

catch (Exception e)
{
System.err.println("ERROR: " + e);
e.printStackTrace(System.out);
}

System.out.println("Interest Server Exiting ...");


}
}

//InterestClient.java
import InterestApp.*;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*;
import java.io.*;

public class InterestClient


{
public float getValue() throws IOException
{
float val = 0;
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s=br.readLine();
val = Float.parseFloat (s);
}
catch (IOException e)
{
System.out.println(e);
}
return val;
}

public static void main(String args[])


{

System.out.print("Enter P,N,R : ");


Interest interestImpl=null;
InterestClient cc = new InterestClient();

try
{
ORB orb = ORB.init(args, null);
org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService");
NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);
String name = "Interest";

131
Middleware and Enterprise Integration Technologies

interestImpl = InterestHelper.narrow(ncRef.resolve_str(name));

float val1 = 0;
float val2 = 0;
float val3 = 0;
float res = 0;

val1 = cc.getValue();
val2 = cc.getValue();
val3 = cc.getValue();
res=interestImpl.calc(val1, val2, val3);
System.out.println("Interest : " + res);

interestImpl.shutdown();

}
catch (Exception e)
{
System.out.println("ERROR : " + e) ;
e.printStackTrace(System.out);
}
}

Output:

C:\Program Files\Java\jdk1.7.0\bin>idlj -fall Interest.idl


C:\Program Files\Java\jdk1.7.0\bin>javac InterestApp/*.java
C:\Program Files\Java\jdk1.7.0\bin>javac InterestServer.java
C:\Program Files\Java\jdk1.7.0\bin>javac InterestClient.java
C:\Program Files\Java\jdk1.7.0\bin>start orbd
C:\Program Files\Java\jdk1.7.0\bin>java InterestServer
Interest Server ready and waiting ...
C:\Program Files\Java\jdk1.7.0\bin>java InterestClient
Enter P,N,R : 4500
6
9.5
Interest : 2565.0

------------------
University Questions
1. Write a program for CORBA IDL and server class to calculate interest:

Input parameters: principal amount, rate and no. of years

Output parameter: interest value (June 2010)

2. Compare POA and BOA in CORBA. (June 2010)

132
Middleware and Enterprise Integration Technologies

3. What is CORBA? Explain its architecture and various services provided by it. (Dec 2010)

Chapter 7

Advanced CORBA

7.1 Overview of CORBA Services (June 2010, Dec 2010)(10 Marks)

Collections of system-level services packaged with IDL-specified interfaces are called CORBA
services. They are used to augment and complement the functionality of the ORB. OMG has
published standards for sixteen object services:

• The Life Cycle Service defines operations for creating, copying, moving and deleting
components on the bus.

• The Persistence Service provides a single interface for storing components persistently
on a variety of storage servers, including Object Databases (ODBMS), Relational
Databases (RDBMSs), and simple files.

• The Naming Service components on the bus to locate other components by name; it also
supports federated naming contexts. The service also allows objects of be bound to
existing network directories or naming contexts, including ISO's X. 500, OSF's DCE,
Sun's NIS+ etc.

• The Event Service allows components on the bus to dynamically register or unregister
their interest in specific events. The service defines a well-known object called an event
channel that collects and distributes events among components that know nothing of each
other.

• The Concurrency Control Service provides a lock manager that can obtain locks on
behalf of either transactions or threads.

• The Transaction Service provides two-phase commit coordination among recoverable


components using either flat or nested transactions.

• The Relationship Service provides a way to create dynamic associations between


components that know nothing or each other. It also provides mechanisms for traversing
the links that group these components. You can use the service to enforce referential
integrity constraints, track containment relationships, and for any type of linkage among
components.

• The Externalization Service provides a standard way for getting data into and out of a
component using a stream-like mechanism.

133
Middleware and Enterprise Integration Technologies

• The Query Service provides query operations for objects. It is a superset of SQL. It is
base on the upcoming SQL3 specification and the Object Database Management Group's
(ODMG) Object Query Language (OQL).

• The Licensing Service provides operations for metering the use of components to ensure
fair compensation for use. The service supports any model of usage control at any point
in a component's life cycle. It supports charging per session, per node, per instance
creation and per site.

• The Properties Service provides operations that let developers associate named values (or
properties) with any components. Using this service, the properties can be associated with
a component's state, e. g. a title or date.

• The Time Service provides interface for synchronizing time in a distributed object
environment. It also provides operations for defining and managing time-triggered
events.

• The Security Service provides a complete framework for distributed object security. It
supports authentication, access control lists, confidentiality and non-repudiation. It also
manages the delegation of credentials between objects.

• The Trader Service provides a "Yellow Pages" for objects; it allows objects to publicize
their services and bid for jobs.

• The Collection Service provides CORBA interfaces to generically create and manipulate
the most common collections.

• The Startup Service enables requests to automatically start up when an ORB is invoked.

7.2 Object Location Services

Naming Service

The client can retrieve the OR using the name of the object via this service. CORBA provides two standard
mechanisms for enabling client programs to obtain servant references: Interoperable Object References
(IORs) and the COS naming service.

The CORBA naming service is a registry of (name, IOR) pairs of CORBA objects to which clients can
connect. The advantage of using this service is that it allows the application software to delegate the
management of the object references to a separate service. An IOR contains the following information
required for a client ORB to connect to a CORBA object or servant.

1. IIOP Version: It describes the IIOP version implemented by the ORB.


2. Host: It identifies the TCP/IP address of the ORB’s host machine.
3. Port: It specifies the TPC/IP port number where the ORB is listening for client requests.
4. Key: It is a value that uniquely identifies the servant to the ORB exporting the servant.

134
Middleware and Enterprise Integration Technologies

5. Components: It is a sequence that contains additional information applicable to object method


invocations, such as supported ORB services and proprietary protocol support.

When a client wishes to access a particular named object, it presents the name of the object to its ORB. The
ORB, in turn, contacts a naming service to query it for the IOR of that object. If the naming service finds
the name, it returns the object’s IOR, at which point the client ORB can than make contact with this remote
object. The design of the naming service is based on the following principles:

1. The naming service should support distributed, heterogeneous implementation and administration
of names and name contexts.
2. Naming service client need not be aware of the physical site of name servers in a distributed
environment.
3. Naming service is a fundamental object service with no dependencies on other interfaces.
4. Existing name and directory services employed in different network computing environments can
be transparently encapsulated using name contexts.

Trading Service

While the naming service facilities lookup for objects based on names, the trading service facilities lookup
based on properties of objects. The client then performs a lookup by specifying the properties for the object.
Trader is an object through which other objects can advertise their capabilities. The trader evaluates this
lookup query and returns a set of matching objects.

There are three basic operations in trading service as follows,

1. Adding service_types: Trading service type, which specifies attributes, associated with the service.
The administrator of trading service has right to define and add new services to the trader.

2. Exporting a Service: Once a service type is defined the servers publish objects of this type along
with the object reference to the trader. This is called exporting a service. A service offer is the
information asserted by an exporter about the service it is advertising. it contains:

• The service type name,


• A reference to the interface that provides the services,
• Zero or more property value for the services.

3. Query: A collection of service offers exported by the servers to a trader is called a trading space. A
query permits the client lookup for objects in the trading space. Clients specify the service type, the
properties and the evaluation criterion. The trading service then evaluates this criterion and returns
a matching set of objects. It contains the object references and a sequence of name-value pairs for
the requested properties.

Administrator add_type

Trading service
Server
add_type()
135
export()

Client
Middleware and Enterprise Integration Technologies

export

query

Fig. 7.1 Components of CORBA Trading Service

7.3 Messaging Service

The basic invocation mechanism in CORBA is tightly coupled and synchronous in nature. In this type of
mechanism, the client is attached to a particular target object and waits for a response from the remote
object after the request.

Invocation Mechanisms in CORBA

The basic communication model of CORBA has the following types of invocations:

Synchronous Two-way invocation

Here a client sends a request to a target object and waits for the object to return the response. The client is
blocked and cannot continue with its tasks. The client is blocked for a long period of time which reduces the
throughput of the system.

One-way Invocation

It has only a request message with no response. One-way request have no return values.

Deferred Synchronous Invocation

The client sends a request to a target object and continues to do its own processing. As DII is tedious to use
and is not type safe, CORBA messaging specification is used. It allows deferred synchronous calls using
static stubs. It includes asynchronous method invocation (AMI), time-independent invocation ( TII) and
messaging quality of service (QoS) policies:

1. Asynchronous Method Invocation (AMI): AMI in CORBA messaging is achieved using the
following models:

• Polling model: In this model, the AMI returns a new IDL type called the “Poller”. The
client uses the Poller’s method to obtain the status of the request and the value of the reply
from the server.

• Callback model: When the server responds, the client ORB receives the response and
invokes the ReplyHandler callback object to handle the reply. The callback model is more
efficient than the polling model because the client need not poll for results.

2. Time-Independent Invocations (TII): TII is a specialization of AMI that supports “store-and-


forward” semantics. They are useful for applications like email, which require guaranteed delivery

136
Middleware and Enterprise Integration Technologies

of requests to target objects that may not be connected to a network at the time a message is sent.
To support TII, the CORBA messaging specification defines a standard Interoperable Routing
Protocol (IRP) based on the General Inter-ORB Protocol (GIOP). The IRP provides a standard way
for time-independent requests to travel between store-and forward routers.

3. Messaging Quality of Service (Qos): The CORBA messaging specification QOS framework
supports both asynchronous and synchronous method invocation.

7.4 CORBA Component Model

The CORBA Component Model (CCM) is a specification for creating server-side scalable, language-
neutral, transactional, multi-user and secure enterprise-level applications. It provides a consistent
component architecture framework for creating distributed n-tier middleware.

A typical CCM Architecture consists of

• CCM Containers,
• CORBA components that run in these containers,
• the Portable Object Adapter (POA),
• the Object Request Broker (ORB)
• other CORBA object services like CORBA Transactions, CORBA Security, CORBA Persistence,
CORBA Events, etc...

In a typical development and deployment scenario, there will be an Application server provider who
creates and sells an Application server along with CCM containers that will run on these servers. Then
there will be the CCM providers-people responsible for developing CORBA components and the
Application assemblers-people that use pre-built CORBA components to build their applications.

Fig. 7.2 CCM Components

137
Middleware and Enterprise Integration Technologies

Application Servers :

These provide the system services like a raw execution environment, multiprocessing, load-balancing,
device access, provide naming and transaction services and make containers visible.

CCM Containers :

These act as the interface between a CORBA component and the outside world. A CCM client never
accesses a CORBA component directly. Any component access is done through container-generated
methods which in turn invoke the component's methods. There are basically two basic types of
containers. They are transient containers that may contain transient, non-persistent components whose
states are not saved at all and persistent containers that contain persistent components whose states
are saved between invocations. Depending upon the types of components that they can execute, CCM
Containers may be divided into:
• Service containers,
• Session containers,
• Entity containers, and
• Other containers

CCM Clients :

These make use of the CCM components for their operations. They find the CCM container that contains
the component through COSNaming and create, or obtain a reference to the component's container
through the component's Home Interface. They then make use of the CCM Container to invoke the
component methods.

CCM Components:

CCM components can expose multiple interfaces. While defining the IDL for each component, the
interfaces that it provides and the interfaces that it uses have to be specified. Similarly, the events that it
emits (or publishes) and the events that it consumes have to be defined in the IDL. The interfaces that it
provides are called facets. The ability to use an interface is facilitated by declaring it as a receptacle.
Event emission and publication declarations are used to define an event source. Event consumption
declarations are used to describe event sinks. Facets, receptacles, event sources and event sinks are
collectively called Ports.

There are four types of CCM components. They are:

• Service components,
• Session components,
• Process components and
• Entity components

Service Components:

Each Service component is usually associated with one CCM Client and it's lifetime is restricted to that of
one single operation request (or a single method call) . Each Service component is created and

138
Middleware and Enterprise Integration Technologies

destroyed by the particular CCM Client that it is associated with. Service components do not survive a
System shutdown.

Session Components:

Each Session component is usually associated with one CCM Client. Each Session component is created
and destroyed by the particular CCM Client that it is associated with. A Session component can either
have states or they can be stateless. However, Session components do not survive a System shutdown.
A Session component is very similar to a Session EJB.

Process Components:

Process components always have states. Each Process component may however be shared by multiple
CCM Clients. Their states can be persisted and stored across multiple invocations. Hence they can
survive System Shutdowns.

Entity Components:

Entity components always have states. Each Entity component may however be shared by multiple CCM
Clients. Their states can be persisted and stored across multiple invocations. Hence they can survive
System Shutdowns. Each Entity component can be uniquely identified by its Primary Key. An Entity
component is very similar to an Entity EJB.

One of the major differences between Process and Entity components are that while the Entity
component has a Primary Key to uniquely be identified by the client, a Process component does not
expose its identity to the client except through user-defined operations. While Entity Components are
used to represent entities like customers or accounts, Process components represent business processes
like applying for a loan or creating a work order, etc.

Servers have a right to manage their working set and they sometimes achieve this using Persistence.
They may either use CORBA persistence or a user-defined persistence mechanism. Passivation is the
process by which the state of a component is saved to persistent storage and then is swapped out.
Activation is the process by which the state of a component is restored by swapping it in from persistent
storage.

There are two types of Session Components. They are:

• Stateless Session Components and


• Stateful Session Components

Stateless Session Components:

These types of components have no internal state. Since they do not have any states, they need not be
passivated. Because of the fact that they are stateless, they can be pooled in to service multiple clients
(remember MTS components and Stateless Session EJBs?)

Stateful Session Components:

139
Middleware and Enterprise Integration Technologies

These types of components possess internal states. Hence they need to handle Persistence. These types
of components can be saved and restored across client sessions.

Persistence in Entity and Process components is of two types. They are:

• Container-managed persistence
• Component-managed persistence

Container-managed persistence:

Here, the CCM container is responsible for saving the component's state. Since it is container-managed,
the implementation is independent of the data source. Persistence is automatically handled by the
container.

Component-managed persistence:

Here, the Entity component is directly responsible for saving its own state. The container does not need
to generate any database calls. Hence the implementation is less adaptable than the previous one as the
persistence needs to be hard-coded into the component.

Interfaces between the Application Server and CCM Containers:

The CCM specification defines a standard way to implement the container API through CORBA object
services. Therefore, the interfaces between the Server and the container are well specified. In fact, since
EJB is a subset of CCM, vendors can now implement the EJB container API through CORBA object
services.

Packaging and Deployment:

CCM uses XML descriptors for specifying information about packaging and deployment just like EJB.
However, additionally, CCM has an assembly descriptor, which contains metadata about how two or
more CCM components are wired together.

Benefits of CCM

• Its architecture is based on OMG MDA (Model Driven Architecture) and ensures
standard CORBA 3.0 compliance.
• It helps you to extend your CORBA 2.x infrastructure to CORBA 3.0 and thus leverage
your existing asset.
• It enables reuse by extending proprietary implementations of C++ components or legacy
CORBA-based Java components to the standard OMG CORBA Component Model(CCM).
• It allows containers to span machines for load-balancing purposes and also allows
dynamic clustering for enhanced scalability & high performance.

140
Middleware and Enterprise Integration Technologies

• The K2 CCM container manages component instances' life cycle (creation and
destruction) and resource control (activation and passivation), and provides
infrastructure services including state persistence and transactionality via standardized
interfaces.
• Inter-working between CCMs and EJBs, allows them to call each other through a bridge
(extremely thin & efficient). This is achieved effectively due to the commonality of the
EJB model with basic CORBA component model.
• Allow non-intrusive maintenance and upgrade.
• Enhanced and guaranteed QoS(Quality of Service) levels to support large-scale Web
OLTP traffic (scalability, availability, integrity and manageability).
• Using the component technology of CORBA (i.e. CCM), enterprise can build complex
systems faster than many packaged applications.
• CCM based application development is easy to develop and manage. Programmers need
not know low-level programming details.
• Cost of ownership reduces by 40%.

--------------------
1. Write Short Note on: CORBA Services (June 2010, Dec 2010)

Chapter 8

COM and .NET

8.1 Evolution of DCOM

Over the last several decades, computer scientists have worked on improving overall computer
performance by using distributed component technology. The distributed component object
model (DCOM) was created by Microsoft® to enable the distribution of Microsoft® software
components across multiple computer servers. This technology enables servers to be clustered
in a company, which creates large company-wide scalability.

Clipboard was used as the fundamental method of sharing data between applications on
Windows. By using clipboards, the user can copy data from the provider end onto the consumer
application which could then be manipulated by the consumer. The data has to be edited using
appropriate editor since consumer has no idea of data source. Only the consumers’ copy of data
could be changed.

One of the first methods of interprocess communication in Windows was Dynamic Data
Exchange (DDE), first introduced in 1987, that allowed sending and receiving messages in so-
called "conversations" between applications.

141
Middleware and Enterprise Integration Technologies

Antony Williams, one of the most notable thinkers involved in the creation of the COM
architecture, later distributed two internal papers in Microsoft that embraced the concept of
software components: Object Architecture: Dealing With the Unknown – or – Type Safety in a
Dynamically Extensible Class Library in 1988 and On Inheritance: What It Means and How To Use
It in 1990. These provided the foundation of many of the ideas behind COM.

Object Linking and Embedding (OLE), Microsoft's first object-based framework, was built on top
of DDE and designed specifically for compound documents. It was introduced with Word for
Windows and Excel in 1991, and was later included with Windows, starting with version 3.1 in
1992.

An example of a compound document is a spreadsheet embedded in a Word for Windows


document: as changes are made to the spreadsheet within Excel, they appear automatically
inside the Word document.

In 1991, Microsoft introduced Visual Basic Extensions (VBX) with Visual Basic 1.0. A VBX is a
packaged extension in the form of a dynamic-link library (DLL) that allowed objects to be
graphically placed in a form and manipulated by properties and methods. These were later
adapted for use by other languages such as Visual C++.

In 1993, when version 3.1 of Windows was released, Microsoft released OLE 2 with its
underlying object model. The COM Application binary interface (ABI) was the same as the MAPI
ABI, which was released in 1992. While OLE 1 was focused on compound documents, COM and
OLE 2 were designed to address software components in general. Text conversations and
Windows messages had proved not to be flexible enough to allow sharing application features in
a robust and extensible way, so COM was created as a new foundation, and OLE changed to
OLE2.

In 1994 OLE custom controls (OCXs) were introduced as the successor to VBX controls. At the
same time, Microsoft stated that OLE 2 would just be known as "OLE", and that OLE was no
longer an acronym, but a name for all of the company's component technologies.

In early 1996, Microsoft found a new use for OLE Custom Controls, expanding their Web
browser's capability to present content, renamed some parts of OLE relating to the Internet
ActiveX, and gradually renamed all OLE technologies to ActiveX, except the compound
document technology that was used in Microsoft Office. Later that year, DCOM was introduced
as an answer to CORBA.

Distributed component object model was first introduced with Windows® NT operating system
in the late 1990s. This technology was a progressive addition to the standard common object
model (COM) framework that is used in most Microsoft® software applications. While the COM
framework provided a method to access multiple applications from one machine, it did not work
with external machines on a company network.

Sharing components and software services are standard practices today on the Internet. Some
examples are seen on trip reservation sites that connect to hotels, airlines, and car rental
agencies. This technology makes it possible for computers to share software applications across

142
Middleware and Enterprise Integration Technologies

multiple networks. The distributed component object model is the technology that makes many
Microsoft® applications work across a network.

8.2 Introduction to COM

Component Object Model (COM) is a binary-interface standard for software componentry introduced
by Microsoft in 1993. It is used to enable interprocess communication and dynamic object creation in a
large range of programming languages. The term COM is often used in the Microsoft software
development industry as an umbrella term that encompasses the OLE, OLE Automation, ActiveX, COM+
and DCOM technologies.

The essence of COM is a language-neutral way of implementing objects that can be used in environments
different from the one in which they were created, even across machine boundaries. For well-authored
components, COM allows reuse of objects with no knowledge of their internal implementation, as it
forces component implementers to provide well-defined interfaces that are separate from the
implementation. The different allocation semantics of languages are accommodated by making objects
responsible for their own creation and destruction through reference-counting. Casting between different
interfaces of an object is achieved through the QueryInterface() function. The preferred method of
inheritance within COM is the creation of sub-objects to which method calls are delegated.

Features of COM/DCOM

COM/ DCOM makes it easy to write a distributed application that


• Scales from the smallest single computer environment to the biggest pool of server
machines.
• Provides rich, symmetric communication between components.
• Can be robustly expanded to meet new functional requirements.
• Takes advantage of existing custom and off-the-shelf components.
• Integrates teams proficient in any programming language and development tool.
• Uses network bandwidth carefully, while providing great response times for end-users.
• Is inherently secure.
• Provides a smooth migration path to sophisticate load-balancing and fault-tolerance
features.
• Can be efficiently deployed and administered.
• Can be used with any network protocol and integrated into any hardware platform.
• Can seamlessly take advantage of other Internet standards and protocols.
• Separation of Interface from the Implementation: Both DCOM and CORBA define an
Interface Definition Language (IDL) for use by component developers to specify a
component's interface independent of a programming language.
• Component Object Services: In addition to transparent invocation of requests both
DCOM and CORBA come with a complementary set of fundamental component
services.
• Uniform Exception Handling schema: For any object which runs on a heterogeneous
distributed environment, a uniform, descriptive, elaborate Exception Handling
mechanism is necessary. In DCOM, each method call returns a well-defined "flat"
structure whose bit settings encode the return status.

143
Middleware and Enterprise Integration Technologies

8.3 COM Clients and Servers

A critical aspect of COM is how clients and servers interact. A COM client is whatever code or object gets
a pointer to a COM server and uses its services by calling the methods of its interfaces. A COM server is
any object that provides services to clients; these services are in the form of COM interface
implementations that can be called by any client that is able to get a pointer to one of the interfaces on
the server object.

COM Servers are classified as follows:

• In-Process Server: If the component is local and designed to be in-process server, the client
instantiates it and communicates with it using COM. E.g. ActiveX

• Out-of-process Server: If the component is local and designed to be local, out-of-process server,
the client instantiates it and communicates with it using COM proxies and registry. E.g. Excel
• Out-of-process remote server: If the component is remote, client communicate with it using
DCOM
• In-process remote server: If the remote component has been written to take advantage of MTS,
clients communicate with it using DCOM.

Fig. 8.1 Types of COM Servers

Architecture of DCOM

• DCOM is just COM with a longer wire


• DCOM extends COM to support communication among objects on different computers

144
Middleware and Enterprise Integration Technologies

• In DCOM, the client stub is referred to as proxy and server stub is referred to as stub.

Fig. 8.2 Architecture of DCOM

The architecture of DCOM consists of three layers: top, middle and bottom layer.

1. Top Layer: It is the basic programming architecture.


• It describes the client’s requests and creation of object instances in the server.
• This mechanism is called activation mechanism.
• Creation of remote objects requires server name and CLSID.
• Then SCM in COM libraries on client machine connects to SCM on server machine and request
creation of the remote object.
• Class factory creates instances of a COM class.
• The SCM then return the pointer to the interface of the object.
• Using this, the client communicates with the object.

2. Middle Layer: It consists of remoting architecture.


• It takes care of sending data across different address spaces using processes such as marshalling
and unmarshalling.

• Marshalling : It packs a method call’s parameters or return values into standard form for
transmission.

• Unmarshalling: It unpacks standard form into an appropriate data representation in the address
space of a receiving process.

145
Middleware and Enterprise Integration Technologies

3. Bottom Layer: It is the wire protocol architecture

• It is based on OSF DCE RPC specification.

• It provides pinging to enable the server object to collect remote object references when a client
abnormally terminates.

• When the server is started by the server-side SCM, it is assigned an object export identifier
(OXID).
• An object reference (OBJREF) is created to represent the interface pointer.
• OBJREF contains IID, OXID, and address of OXID resolver.

Working of DCOM (May 2010) (10 Marks)

Fig.8.3 COM/DCOM Working

1. The COM API: CoCreateInstance() is called with two identifiers (IDs) whether the object is
remote or local. One ID is used to instantiate the COM class (CLSID) and the other is used to
instantiate the DLL or EXE file which hosts the COM class.
2. The DLL’s or EXE’s ID is converted to a filename by scanning through the system registry.
3. Once the filename is obtained, COM loads the required DLL or proxy/stub DLL using the
LoadLibrary() API call or starts the desired EXE using the RPC API.
4. COM then instructs the DLL or EXE to instantiate the required class using the CLSID specified
in CoCreateInstance().
5. CoCreateInstance() returns a pointer to the created object.
6. Once the pointer is obtained, the remote method is invoked. DLL methods are called like any
other class methods. EXE methods calls are serialized by COM using RPC and a proxy object.
7. When the client releases the COM object, the COM API decrements the object’s reference count
by one. When the count becomes zero, the object is released.
8. When all the objects in the DLL/EXE for the application are destroyed, COM unloads the DLL or
stops the EXE.

8.4 COM IDL

Type libraries contain metadata that represent COM types. However, these types must first be
described using Microsoft Interface Definition Language.
This is the common practice in the development of a COM component, i.e. to start with the
definition of types using IDL. An IDL file is what COM provides that allows developers to define

146
Middleware and Enterprise Integration Technologies

object-oriented classes, interfaces, structures, enumerations and other user-defined types in a


language independent manner. COM IDL is similar in appearance to C/C++ declarations with the
addition of keywords such as "interface" and "library" for defining interfaces and collections of
classes, respectively. IDL also requires the use of bracketed attributes before declarations to
provide additional information, such as the GUIDs of interfaces and the relationships between
pointer parameters and length fields.
The IDL file is compiled by the MIDL compiler into a pair of forms for consumption from
various languages. For C/C++, the MIDL compiler generates a compiler-independent header file
containing struct definitions to match the vtbls of the declared interfaces and a C file containing
declarations of the interface GUIDs. C++ source code for a proxy module can also be generated
by the MIDL compiler. This proxy contains method stubs for converting COM calls into Remote
Procedure Calls, thus enabling DCOM.
An IDL file may also be compiled by the MIDL compiler into a type library (.TLB file). The
binary metadata contained within the type library is meant to be processed by language compilers
and runtime environments (e.g. VB, Delphi, the .NET CLR etc.). The end result of such TLB
processing is that language-specific constructs are produced that represent the COM class defined
in the .TLB (and ultimately that which was defined in the originating IDL file).

8.5 COM Interfaces

IUnknown Interface
• All COM interfaces derive from the IUnknown interface, and all COM objects must
implement this interface.
• The IUnknown interface performs two tasks: it controls object lifetime and provides
runtime type support.
• It is through the IUnknown interface that clients maintain a reference on an object while it
is in use—leaving the actual lifetime management to the object itself.
• Object lifetime is controlled with two methods, AddRef and Release, and an internal
reference counter. Every object must have an implementation of IUnknown to control its
own lifetime. Anytime an interface pointer is created or duplicated, the AddRef method is
called, and when the client no longer requires this pointer, the corresponding Release
method is called. When the reference count reaches zero, the object destroys itself.
• Clients also use IUnknown to acquire other interfaces on an object. QueryInterface is the
method that a client calls when another interface on the object is required.
• When a client calls QueryInterface, the object provides an interface and calls AddRef. In
fact, it is the responsibility of any COM method that returns an interface to increment the
reference count for the object on behalf of the caller.
• The client must call the Release method when the interface is no longer needed. The
client calls AddRef explicitly only when an interface is duplicated.
• The method QueryInterface is often referred to by the abbreviation QI.
• When developing a COM object, the developer must obey the rules of QueryInterface.
These rules dictate that interfaces for an object are symmetrical, transitive, and reflexive
and are always available for the lifetime of an object.

147
Middleware and Enterprise Integration Technologies

• For the client this means that, given a valid interface to an object, it is always valid to ask
the object, via a call to QueryInterface, for any other interface on that object including
itself.
• It is not possible to support an interface and later deny access to that interface, perhaps
because of time or security constraints. Other mechanisms must be used to provide this
level of functionality.
• Some classes support the concept of optional interfaces. Depending on the coclass, they
may optionally implement an interface; this does not break this rule since the interface is
either always available or always not available on the class.

Fig. 8.4 Interface Properties

• The rules of QueryInterface dictate that interfaces of an object are reflexive, symmetrical,
and transitive. It is always possible, holding a valid interface pointer on an object, to get
any other interface on that object.
• When requested for a particular interface, the QueryInterface method can return an
already assigned piece of memory for that requested interface, or it can allocate a new
piece of memory and return that.
• The only case when the same piece of memory must be returned is when the IUnknown
interface is requested.
• When comparing two interface pointers to see if they point to the same object, it is
important that a simple comparison not be performed.
• To correctly compare two interface pointers to see if they are for the same object, they
both must be queried for their IUnknown interface, and the comparison must be
performed on the IUnknown pointers.
• In this way, the IUnknown interface is said to define a COM object's identity.

IDispatch Interface
• IDispatch is the interface that exposes the OLE Automation protocol. It is one of the
standard interfaces that can be exposed by COM objects.
• The I in IDispatch refers to interface. COM distinguishes between three interface types:
custom, dispatch and dual interfaces.

148
Middleware and Enterprise Integration Technologies

• IDispatch derives from IUnknown and extends its set of three methods (AddRef, Release
and QueryInterface) with an additional four methods – GetTypeInfoCount, GetTypeInfo,
GetIDsOfNames and Invoke.
GetTypeInfoCount returns the number of type descriptions for the object. For objects
that support IDispatch, the type information count is always one.
GetTypeInfo retrieves a description of the object's programmable interface.
GetIDsOfNames maps the name of a method or property to a DISPID, which is later
used to invoke the method or property.
Invoke calls one of the object's methods, or gets or sets one of its properties.
• The Automation (IDispatch) interface allows a client application to find out what
properties and methods are supported by an object at run-time.
• It also provides the information necessary to invoke these properties and methods. Client
applications do not need to be aware of the object members when they are compiled.
• Each property and method implemented by an object that supports the IDispatch interface
has what is called a Dispatch ID, which is often abbreviated DISPID.
• The DISPID is the primary means of identifying a property or method and must be
supplied to the Invoke function for a property or method to be invoked, along with an
array of Variants containing the parameters.
• The GetIDsOfNames function can be used to get the appropriate DISPID from a property
or method name that is in string format.

IClassFactory Interface
• The IClassFactory interface manages the creation of new objects. This interface is
supported by class objects associated with CLSIDs.
• Implement this interface for every object definition so objects of that type can be created.
• After calling the CoGetClassObject function to get an IClassFactory interface pointer to
the class object, call the CreateInstance method of this interface to create an object.
• It is not, however, always necessary to go through this process to create an object. To
create a single object, you can, instead, just call CoCreateInstance.
• Call the LockServer method to keep the object server in memory and enhance
performance only if you intend to create more than one object of the specified class.
• The IClassFactory interface inherits from the IUnknown interface. It has two methods :
CreateInstance() and LockServer()
• CreateInstance() method creates an uninitialized object.
• LockServer() method locks an object application open in memory.

8.6 COM Threading Models (May 2010)(10 Marks)

Before we proceed, let me tell you what threads are. Every application when started on your operating
system is a process. Now, that process can have many threads being executed under it. Let me give you an
example. Say you start Microsoft Word on your computer. You have just started a process. After starting
it you just gave the print command for a few pages. That's a thread under that process. While the pages
print, you start browsing the clipart wizard in search of some clip art images. That's another thread under
the same process.

149
Middleware and Enterprise Integration Technologies

Threads can also have priorities. A thread may be of high priority or low priority. A thread with high
priority may interrupt a thread with low priority. Applications can be single threaded or multi threaded.

Every process on a computer can have more than one task or thread running under it. This wasn't true in
the "olden days". Applications used to be single threaded during the Windows 3.1 days. This meant that
only one task could be performed at one time, and that all other tasks would have to wait until that task
finished executing.

Many a time, large applications would just make the CPU freeze or make you wait for a long period of
time until their task finished executing. Microsoft then introduced multi threading in Windows 95 and
Windows NT. You could now perform more than one task at once without waiting for the other tasks to
complete first.

Let's take a look at the threading models in COM.

The STA (Single Threaded Apartment) Model

The first version of COM supported something called the STA (Single Threaded Apartment) model. In
this model COM allowed us to have just one thread in an apartment, however it also allowed us to have
multiple apartments under one process.

It allowed clients to create multiple apartments. One thread was created in an apartment. All the data,
which was transferred from one apartment to another, was marshaled through a proxy. In this threading
model, COM serialized execution of threads through a message queue.

The order of execution of threads was picked up serially from the queue so that there was only one active
call made to the client at one time. This meant that users could issue multiple commands (or threads) at
the same time, which would all be assembled serially in a queue.

However, only one command (or thread) would be executed at any one time. They would be executed in
the order that they were issued. So, the STA (Single Threaded Apartment) model made a users life a lot
easier by letting that user issue more than one command at a time.

The MTA (Multi Threaded Apartment) Model

Windows NT introduced multi-threading. They introduced a new threading model, which was called the
MTA (Multi-Threaded Apartment) model. Even COM supported this model. In the MTA (Multi-
Threaded Apartment) model, COM does not synchronize the execution of the threads. You as a developer
have to provide the synchronization code for you component. In this model only one apartment is created.
However, that one component can hold any number of threads in it (unlike the STA (Single-Threaded
Apartment) model which had any number of apartments but could hold only one thread per apartment).

150
Middleware and Enterprise Integration Technologies

This model was a lot more advanced than the STA (Single-Threaded Apartment) model. Whenever these
threads (which were part of one apartment), needed to share data, the data didn't have to be marshaled via
a proxy, as all of the threads were part of one apartment itself. No message queue was maintained by
COM.

Execution was a lot faster, however it was the developer's responsibility for ensuring that two threads do
not have access to the same COM object at one time. All of the synchronization code had to be
programmed by the developer himself and maybe that was the only drawback of the MTA (Multi-
Threaded Apartment) model.

The MTA model provides us developers with a lot of flexibility, but at the same time gives us a lot of
responsibility too, as inefficient thread synchronization code would really affect the performance of the
application. An efficient coder could do wonders to the application performance if using the MTA model
instead of the STA model.

The Mixed Threading Model

There was another threading model introduced in COM called the Mixed-Threading model. This model
was just a combination of the STA (Single-Threaded Apartment) model and the MTA (Multi-Threaded
Apartment) model. You could have any number of single threaded apartments storing one thread in them.
You could also simultaneously have a multi-threading apartment storing any number of threads in it. It
solely depended upon the coder as to which threading model was used when coding a COM component.

The ATL COM object wizard supports the following threading options:
• Single: Similar to single threading, which existed during the Windows 3.1 days. It permitted
creation of only one thread at a time.
• Apartment: Similar to the STA (Single-Threaded Apartment) model.
• Both: Similar to the Mixed-Threading model.

151
Middleware and Enterprise Integration Technologies

• Free: Similar to the MTA (Multi-Threaded Apartment) model.

8.7 Marshalling Techniques in COM

The issue of passing parameters in DCOM is a major area of concern and is called marshalling.
Marshalling is a process of packaging method calls and their parameters into a packet & transmitting
them over the network.COM offers three types of marshalling – Standard, custom and type library
marshalling .Standard marshalling is in fact, a type of custom marshalling; and type library marshalling is
type of standard marshalling.

Fig.8.5 Relationship between different types of marshalling

Custom Marshalling

It is a fundamental marshalling in COM. This method allows the client to gain a complete control over
the marshalling process. As it is difficult to implement and is more generic, standard marshalling
mechanism is used. In custom marshalling, COM has no support for transmission of data between proxy
and stub .Programmer can choose IPC mechanism. However, no stub DLL is created in the component
address space. The client can directly communicate with component.
Custom marshalling is used in situation to generate customized proxies to improve speed of
transmission, reduce the network traffic, improve security etc. It is used in image processing application
to improve the speed of multimedia file transmission by compressing the code to be transmitted. Custom
marshalling makes use of IMarshal interface. It marshals interface pointer into a stream object and back.
It has the following functionalities:
1. MarshalInterface: It is used to marshal an interface pointer into a stream object.
2. UnMarshalInterface: It is used to unmarshal the stream object into interface pointer at the client
side.
3. ReleaseMarshalData: It is used to free the data stored in the marshalling packet.
4. DisconnectObject: It is used to disconnect clients that maintain pointers to the object.
5. GetUnmarshalClass: It is used to fetch the unmarshal class.
6. GetMarshalSizeMax: It is used to fetch the size of marshal buffer.

152
Middleware and Enterprise Integration Technologies

Fig.8.6 Custom Marshalling Process

Standard Marshalling
It is used when an object does not implement the marshalling interface but generates it using user defined
interfaces for the objects. It standard marshalling, COM generic proxy and stub communication using
RPCs. These custom interfaces are compiled by MIDL compiler to generate standard marshalling code.
MIDL compiler generates the following files:
1. A header file in the programming Language for the interface definitions in COM format.
2. A file containing definition for IID and CLSID.
3. A file containing the marshalling code.
4. A type library file.
5. DLL entry points for marshalling code.

These files are compiled and linked to produce the stub/proxy DLL to marshal the interface. This
stub/proxy must be registered. A Stub manager is a COM object that has a unique OID and is connected
with one COM object. It maintains a reference count for the COM object. When it becomes Zero, the
stub manager is also destroyed. To handle OR PC, interface stub are used. It is helper method, using
which the signature of methods in the interface is known. It is identified using interface pointer ID (IPID)
and holds a pointer to the object.
The client calls the Query Interface to obtain the interface to the remote object using the proxy object.
The interface proxy is a part of the proxy manager. It communicates with the component through the
IRpcChannel Buffer interface implemented by COM. On the server side, the channel communicates with
the interface stub through IRpcStub Buffer interface which in turn calls the COM object (Figure 15).
Standard marshalling has four interfaces:
1. IP Factory Buffer that is used to instantiate IRpcProxy Buffer in the server and
IRpcStub Buffer object in the client address space.
2. IRpcProxy Buffer that has the connect method to connect to the stub.
3. IRpcStub Buffer that has the invoke method to instantiate the stub code.
4. IRpcChannel Buffer that is used for communication between stub and proxy object.

153
Middleware and Enterprise Integration Technologies

Parameters RMI CORBA DCOM

Fig.8.7 Standard marshalling process

Type Library Marshalling

It uses Idispatch (automation) marshaller. COM has a built-in marshaller for this interface as automation
marshaller is generic, it is not as efficient as marshalling code generated. Owing to type library look up
more time is consumed, but is more flexible and is easy to use. No proxy/stub needs to be built and
registered. It is available in windows.

Handler Marshalling
It is between standard and full custom marshalling. It is useful for objects that perform work in clients
address space, making remote calls only when necessary. These objects support IstdMarshalInfo interface
that retrieves the CLSID of the handler object to be loaded in clients address space and load it.

8.8 Comparison of RMI, CORBA and DCOM (May 2010, Dec 2010)(10 Marks)

Table 8.1

154
Middleware and Enterprise Integration Technologies

Programming language Language independent Language independent Language independent

Platform Independent Yes Yes No

Interface Java IDL MIDL

Object Identification Object and Interface Object and Interface CLSID, IID

Object Reference URL based object reference OBJREF Reference pointers

Protocols IIOP/JRMP IIOP/GIOP ORPC

ORB or Implementation
Storage RMI Registry Registry
Registry

Statically- SSI/SII Statically-IUnknown


Invocation Stubs and Skeletons
Dynamically-DII/DSI dynamically-IDispatch

Inheritance Yes Yes Yes

Trading Services No Yes No

Naming Service Yes Yes Yes

Concurrency Service Yes Yes Yes

Security Service Yes Yes Yes

Component Models EJB CCM COM/MTS

Modularity Objects Java Obj CORBA Obj COM Obj

Flag Transactions No Yes Yes

Replication and recovery No Yes No

Mitigation service Yes Yes No

Persistence reference Yes Yes No

Nested transactions No Yes Yes


Uni-bidirectional and Bidirectional and Bidirectional and
Binding
symmetric symmetric symmetric
Predictability No Yes No

155
Middleware and Enterprise Integration Technologies

Communication
JRMP GIOP ORPC
transparency
Network data format Java object serialization CDR NDR

Security Java security Four models of security Windows NT security

Garbage Collection Available Implementation dependent Available

IDE Support Good Poor Poor

Cluster Yes Yes Yes

Capsules Yes Yes Yes

Operation interface Yes Yes Yes

Stream interface Yes Yes Yes

Signal interface No No No

8.9 .NET Framework Architecture (May 2010)(10 Marks)

Microsoft .NET is a vision and set of Microsoft software technologies for connecting information, people,
systems, and devices. Integrated across the Microsoft platform, .NET technology provides the ability to
quickly build, deploy, manage, and use connected, security-enhanced solutions with Web services.

The .NET-connected solutions enable businesses to integrate their systems more rapidly and in a more
agile manner and help them realize the promise of information anytime, anywhere, on any device. To start
learning about developing applications for .Net Languages, it is important to first get a tour and an
understanding of the .NET Framework that provides underlying platform, libraries, and run time services.

The major benefits of .NET are:


• Faster development (less to do, the system handles more)
• Lots of built-in functionality through a rich object model
• A variety of ways to interface and integrate with the outside world
• More reuse
• Easy to integrate different languages into one system
• Easier deployment

156
Middleware and Enterprise Integration Technologies

• Scalability
• Easy to build sophisticated development tools
• Interfaces well to existing software

Fig. 8.8 .NET Framework Architecture


The major components of .NET framework are:

• Common Language Specification (CLS) is a set of basic language features that .Net Languages
needed to develop Applications and Services, which are compatible with the .Net Framework.
When there is a situation to communicate objects written in different .Net Complaint languages,
those objects must expose the features that are common to all the languages. Common
Language Specification (CLS) ensures complete interoperability among applications, regardless
of the language used to create the application.

• The .NET Framework introduces a Common Type System (CTS). The CTS specification defines
all possible data types and programming constructs supported by the CLR and how they may or
may not interact with each other conforming to the Common Language Infrastructure (CLI)
specification. Because of this feature, the .NET Framework supports the exchange of types and
object instances between libraries and applications written using any conforming .NET language.

• The .Net Framework class library (FCL) provides the core functionality of .Net
Framework architecture. The .Net Framework Class Library (FCL) includes a huge

157
Middleware and Enterprise Integration Technologies

collection of reusable classes, interfaces, and value types that expedite and optimize the
development process and provide access to system functionality.

The .Net Framework class library (FCL) organized in a hierarchical tree structure and it is
divided into Namespaces. Namespaces is a logical grouping of types for the purpose of
identification. Framework class library (FCL) provides the consistent base types that are
used across all .NET enabled languages. The Classes are accessed by namespaces, which
reside within Assemblies. The System Namespace is the root for types in the .NET
Framework. The .Net Framework class library (FCL) classes are managed classes that
provide access to System Services. The .Net Framework class library (FCL) classes are
object oriented and easy to use in program developments. Moreover, third-party
components can integrate with the classes in the .NET Framework.

• The Common Language Runtime (CLR) is the execution engine of the .NET Framework. All
.NET programs execute under the supervision of the CLR, guaranteeing certain properties and
behaviors in the areas of memory management, security, and exception handling.

• Standard System Services like ADO.NET and XML are made universally available and
standardized across Standard System Services languages by bringing them under the control of
the .NET framework.

• User and Program Interfaces include Windows forms based on Windows Foundation Classes
(WFC) for desktop applications and Web forms that provide powerful user interface (UI) for the
web.

8.10 .NET Remoting (May 2010)(10 Marks)

The .NET remoting infrastructure is an abstract approach to interprocess communication. Much of the
system functions without drawing attention to itself. For example, objects that can be passed by value, or
copied, are automatically passed between applications in different application domains or on different
computers. You only need to mark your custom classes as serializable to make this work.

The real strength of the remoting system, however, resides in its ability to enable communication between
objects in different application domains or processes using different transportation protocols, serialization
formats, object lifetime schemes, and modes of object creation. In addition, remoting makes it possible to
intervene in almost any stage of the communication process, for any reason.

Whether you have implemented a number of distributed applications or are simply interested in moving
components to other computers to increase the scalability of your program, it is easiest to understand the
remoting system as a generic system of interprocess communication with some default implementations
that easily handle most scenarios. The following discussion begins with the basics of interprocess
communication using remoting.

Using object references to communicate between server objects and clients is the heart of remoting. The
remoting architecture, however, provides the programmer with an even simpler procedure. If you
configure the client properly, you need only create a new instance of the remote object using new (or the
instance creation function from your managed programming language). Your client receives a reference
to the server object, and you can then call its methods as though the object were in your process rather
than running on a separate computer. The remoting system uses proxy objects to create the impression

158
Middleware and Enterprise Integration Technologies

that the server object is in the client's process. Proxies are stand-in objects that present themselves as
some other object. When your client creates an instance of the remote type, the remoting infrastructure
creates a proxy object that looks exactly like the remote type to your client. Your client calls a method on
that proxy, and the remoting system receives the call, routes it to the server process, invokes the server
object, and returns the return value to the client proxy, which returns the result to the client.

Remote calls must be conveyed in some way between the client and the server process. If you were
building a remoting system yourself, you might start by learning network programming and a wide array
of protocols and serialization format specifications. In the .NET remoting system, the combination of
underlying technologies required to open a network connection and use a particular protocol to send the
bytes to the receiving application are represented as a transport channel.

A channel is a type that takes a stream of data, creates a package according to a particular network
protocol, and sends the package to another computer. Some channels can only receive information, others
can only send information, and still others, such as the default TcpChannel and HttpChannel classes, can
be used in either direction.

Although the server process knows everything about each unique type, the client knows only that it wants
a reference to an object in another application domain, perhaps on another computer. From the world
outside the server application domain, a URL locates the object. The URLs that represent unique types to
the outside world are activation URLs, which ensure that your remote call is made to the proper type.

Complete Remoting System Design

Suppose you have an application running on one computer, and you want to use the functionality
exposed by a type that is stored on another computer. The following illustration shows the
general remoting process.

Fig. 8.9 .NET Remoting

If both sides of the relationship are configured properly, a client merely creates a new instance of
the server class. The remoting system creates a proxy object that represents the class and returns
to the client object a reference to the proxy. When a client calls a method, the remoting
infrastructure handles the call, checks the type information, and sends the call over the channel to
the server process. A listening channel picks up the request and forwards it to the server
remoting system, which locates (or creates, if necessary) and calls the requested object. The
process is then reversed, as the server remoting system bundles the response into a message that
the server channel sends to the client channel. Finally, the client remoting system returns the
result of the call to the client object through the proxy.
159
Middleware and Enterprise Integration Technologies

Lab Experiments
Steps for writing programs
1. Select Microsoft Visual Studio 2008
2. Go to File Menu Select New Project  Other Languages  Visual C# Console Application
3. Give name of the project and click OK.
4. You will get console window
5. Write the following Codes in that console and save it with <classname>.cs
6. Click (Green Color) to run the project.

1. To print Welcome

using System;

namespace MyFirstPrograms
{
class Program
{
static void Main(string[] args)
{
string name;
Console.Write("What is your name: ");
name = System.Console.ReadLine();

Console.WriteLine("Welcome " + name + " to Your First C#


Program!");
Console.ReadLine();
}
}
}

Output:

160
Middleware and Enterprise Integration Technologies

2. To print Simple Interest

using System;
namespace Interest
{
class Program
{
static void Main(string[] args)
{
int year;
double princ_amt, rate, interest, total_amt;
Console.Write("Enter The Principle Amount : ");
princ_amt = Convert.ToDouble(Console.ReadLine());

Console.Write("Enter The Term : ");


year = Convert.ToInt16(Console.ReadLine());

Console.Write("Enter The Rate Of interest : ");


rate = Convert.ToDouble(Console.ReadLine());

interest = princ_amt * year * rate / 100;


total_amt = princ_amt + interest;

Console.WriteLine("\n----------------------------------------");
Console.WriteLine("Interest : {0} Total Amount : {1}", interest,
total_amt);
Console.WriteLine("----------------------------------------");
Console.ReadLine();

}
}
}

161
Middleware and Enterprise Integration Technologies

3. Matrix Opertaions

/* Simple C sharp program for adding, subtracting and multiplyilng two


matrices.
The program takes inputs for rows and columns of the two matrices seperately
and then calculates the following :

1. Addition
2. Subtraction
3. Multiplication.

Functions have been created for addition, subtraction, multiplication and


display of the matrices. The program using OOPs is posted seperately. The
Functions and variables have to be declared static.

*/

using System;

namespace Array_Pgm
{

class MatrixCalc
{
static int i, j;

static void addMatrix(int[,] A, int[,] B, int m, int n)


{
int[,] C = new int[10, 10];
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
C[i, j] = A[i, j] + B[i, j];
}
display(C, m, n);
}

static void subMatrix(int[,] A, int[,] B, int m, int n)


{
int[,] C = new int[10, 10];
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
C[i, j] = A[i, j] - B[i, j];
}
display(C, m, n);
}

static void display(int[,] A, int m, int n)


{
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
Console.Write(A[i, j] + "\t");
Console.WriteLine();
}

162
Middleware and Enterprise Integration Technologies

static void mulMatrix(int[,]A,int [,]B,int m,int n)


{
int [,]C = new int[10,10];
for(i=0;i< m;i++)
{
for(j=0;j< n;j++)
{
C[i,j] = 0;
for(int k=0;k< n;k++)
{
C[i,j] = C[i,j] + A[i,k] * B[k,j];
}
}
}
display(C, m, n);
}

public static void Main(string[] args)


{
// Input First Matrix say A;
int m, n;
Console.Write("Enter No Of Roes And Columns Of Matrix A : ");
m =Convert.ToInt16(Console.ReadLine());
n =Convert.ToInt16(Console.ReadLine());
int[,] A = new int[10, 10];
Console.Write("\nEnter The First MNatrix : ");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
A[i, j] =Convert.ToInt16(Console.ReadLine());
}

// Input Second Matrix say B;


int p, q;
Console.Write("Enter No Of Rows And Columns Of Matrix B :");
p =Convert.ToInt16(Console.ReadLine());
q =Convert.ToInt16(Console.ReadLine());
int[,] B = new int[10, 10];
Console.Write("\nEnter The Second Matrix:");
for (i = 0; i < p; i++)
{
for (j = 0; j < q; j++)
B[i, j] = Convert.ToInt16(Console.ReadLine());
}
Console.Clear();

// Display The Two Matrixes

Console.WriteLine("\nMatrix A : ");
display(A, m, n);

Console.WriteLine("\nMatrix B: ");
display(B, p, q);

// Menu

163
Middleware and Enterprise Integration Technologies

Console.WriteLine("**** MENU For Matrix Opearations *****");


Console.WriteLine(" 1. Addition");
Console.WriteLine(" 2. Subtraction");
Console.WriteLine(" 3. Multiplication");
Console.WriteLine(" 4. Exit");
Console.WriteLine("Enter Your option");
int choice = Convert.ToInt16(Console.ReadLine());

switch (choice)
{
case 1:
if (m == p && n == q)
{
Console.WriteLine("Addition ");
addMatrix(A, B, m, n);
}
else
Console.WriteLine("ERROR !!!!!! Rows and Columns Of Both martixes should be
same");
Console.ReadLine();
break;

case 2:
if (m == p && n == q)
{
Console.WriteLine("Subtraction ");
subMatrix(A, B, m, n);
}
else
Console.WriteLine("ERROR !!!!!! Rows and Columns Of Both martixes should be
same");
Console.ReadLine();
break;

case 3:
if (n == p)
{
Console.WriteLine("Multiplication: ");
mulMatrix(A, B, m, q);
}
else
Console.WriteLine("ERROR !!!!!! Column of First matrix and Row Of Second
Matrix should be same");
Console.ReadLine();
break;

case 4:
Console.Beep(1000, 1000);
Console.ReadLine();
break;
/* default:
Console.WriteLine("Error");*/
}
}
}
}

164
Middleware and Enterprise Integration Technologies

-----------------

University Questions

1. Compare RMI, CORBA and DCOM. (May 2010, Dec 2010)

2. Explain working of DCOM. (Dec 2010)

165
Middleware and Enterprise Integration Technologies

3. Write short note on: DCOM Apartments (May 2010)

4. Write short note on: .NET Architecture (May 2010)

5. Elaborately explain the .NET framework remoting architecture with neat diagram. (May 2010 )

Chapter 9

Service Oriented Architecture (SOA) Fundamentals


9.1 Defining SOA

A system architecture in which application functions are built as components (services) that are
loosely coupled and well-defined to support interoperability and to improve flexibility and
reuse is called as Service Oriented Architecture (SOA).

Elements of SOA:

166
Middleware and Enterprise Integration Technologies

Fig. 9.1 Elements of SOA

1. Application frontends: These are active elements of the SOA, delivering the value of SOA to the
end users.
• They initiate and control all activity of the enterprise system.
• Web application, application with GUI, or a batch application.
2. Service: It is a software component that encapsulates a high level business concept.
3. Contract: It provides a specification of the purpose, functionality, constraints, and usage of
services.
4. Interface: This functionality of the service is exposed to the clients that are connected to the
service.
5. Implementation: The service implementation provides the required business logic and
appropriate data. It contains one or more of the artifacts: programs, configuration, data and
databases.
6. Business logic: It is the business process represented by the service.
7. Data: It is the data represented in the service/ used by the service.
8. Service repository: It registers the services and their attributes to facilitate the discovery of
services; operation, access rights, owner, qualities, etc.
9. (Enterprise) Service Bus (ESB): It is a flexible infrastructure for integrating applications and
services by routing messages, transforming protocols between requestor and service, handling
business events and delivering them, providing QoS, mediation and security, and managing the
interaction among services.

9.2 Business Value of SOA

SOA moves companies from an "old world" systems architecture based on independent applications,
tightly coupled together by custom messages or processes, to a new type of architecture based on
independent services tied together by a standards-based messaging. SOA moves IT infrastructure from an

167
Middleware and Enterprise Integration Technologies

inefficient, inflexible model - with vertical, siloed applications - to a less expensive, enterprise-wide
model that delivers a reusable suite of interoperable services.
Although the idea of SOA has been around well over a decade, a new generation of infrastructure
software technology is emerging that is addressing the cost and complexity shortcomings that were not
possible in earlier generations. Previously disparate technologies are now pre- integrated into a consistent
enterprise application platform, while also conforming to a best-practice service-oriented architecture for
IT. In this new environment, the SOA is natively built on industry standards, promotes reuse and, for the
first time, allows non-specialist developers to rapidly become productive developers.
Companies can now realistically achieve their business goals by implementing a best-practice service-
oriented IT architecture as the foundation of their future success. Now, more than ever, IT can be a
strategic business asset, alongside other key assets such as employees and intellectual property. In SOA-
enabled environments, enterprises can begin to bridge the fundamental gap that has existed between
business requirements and IT capabilities.
How else is SOA helping facilitate strategic value? Let me count the ways!
• Faster time to market - The core philosophy of SOA inherently promotes reuse for development
and integration teams. With reuse of services and components, new applications can be quickly
assembled to respond to changing market conditions or business demand. With the shortening of
project time frames comes a faster response rate to changing business requirements.
• Operational efficiencies - Most packaged enterprise applications perform well in streamlining
processes related to standard tasks. However, the performance rapidly deteriorates while
automating and streamlining customized processes that encompass multiple enterprise
applications. The process is difficult, time-consuming and expensive to implement and maintain.
SOA virtually eliminates these inter-application complexity barriers. It allows IT to more rapidly
change to the needs of the business so that IT can create a culture and an infrastructure of
business adaptability. In other words, SOA enables "IT that fits the business."
• Faster, less expensive application integration and B2B integration - Implementing a traditional
packaged application integration solution is expensive and complex, often requiring extensive
manual coding for deployment purposes. An SOA framework provides native support for runtime
deployment of services across the network and it dramatically reduces the overall costs of
application integration and deployment by automating these time-consuming processes. It also
allows extension of integration across business boundaries.
A SOA enables the definition of any process in any network configuration, even spanning multiple
enterprise boundaries. This is done through peer-to-peer messaging infrastructure with distributed security
mechanisms that allow efficient intercompany data exchanges, while enabling each enterprise to enforce
its own security policies. This allows SOA to increase operational efficiency across the entire value chain.
• Easier application development and deployment. - In the traditional software development
process, translating requirements into working distributed systems is both time-consuming and
difficult, requiring several stages of manual development and deployment. This complex, error-
prone task can be effectively streamlined using a SOA-based development environment.
Processes can be more easily translated into distributed services, which are easier to develop,
manipulate, and debug; and the services are easily composed into implementation-level data
flows. Further, the implementation-level services can run on any machine across the network by
virtue of the built-in dynamic deployment support SOA provides. The combination of service-
oriented tools for both design time and runtime dramatically reduces the time to implement and
deliver working processes.
• Leverage existing investments - Organizations have spent time and money developing their
existing infrastructure. Today's dynamic environment demands new uses of systems and
processes information to help enable more efficient processing and cost effective business
operations. Extending the lifetimes and ROI of legacy applications by repurposing systems,
processes and data from existing systems provides one means of managing cost. Exposing legacy

168
Middleware and Enterprise Integration Technologies

systems as services also creates an environment that shares information and processes from
systems that were previously isolated or integrated via point solutions.
• Risk mitigation - SOA-based efforts increase the level of project success of an implementation.
Through reuse of core services and processes that have been previously developed, tested and
thoroughly understood, potential bug introduction is reduced. Those project team members with a
stronger business background can focus on orchestration, the assembling of services into
processes, workflows or applications. Others with a stronger technical background can manage
the design and development of the services and underlying infrastructure. Risk management is
improved from an organizational perspective with this separation of skills that enables effective
allocation of resources to efficiently deliver development tasks.
• Continuous improvement - The implementation of services and interfaces is encapsulated? and
invisible to the requestor. This abstraction of the underlying implementation provides an
opportunity for continually improving and optimizing the underlying code base without affecting
the use of the service.
• Increased user acceptance - This is due to the consistent look and feel among various Web
services.
• Fewer support calls - This is due to the fact that the enhanced, consistent services user interface
is easier to understand than the potentially dozens of other applications a user might need to
know to perform equivalent tasks.
• Improved ROI for the overall enterprise - via 1) less duplication of functionality than typically
exists in the usual collection of diverse systems in an enterprise; 2) offloading to industry-
standard servers the hosting of its portal and Web services activities, typically performed by a
high-cost infrastructure, has improved performance and reduced hardware costs; and better use of
developers, who no longer require training on proprietary tools and APIs and can readily transfer
to other projects.
The increasing implementation of SOAs is leading a shift in how computing is deployed and delivered to
users. It is helping to integrate IT more closely to line of business objectives and processes. The capability
to bridge traditional business silos by quickly and cost-effectively mixing and matching services,
regardless of source, is the ultimate business value.

9.3 Characteristics of SOA

1. Loosely coupled: It minimizes dependencies between services.


2. Contractual: It adheres to agreement on service descriptions.
3. Autonomous: It controls the business logic they encapsulate.
4. Abstract: It hides the business logic from the service consumers.
5. Reusable: It divides business logic into reusable services.

6. Composable: It facilitates the assembly of composite services.

7. Stateless: It minimizes retained information specific to an activity.

8. Discoverable: It is self-described so that they can be found and assessed.

9. Interoperable: SOA services offer platform, hardware, communication and programming


language transparency. Hence they are interoperable.

10. Self-contained and Modular: It provides a higher degree of modularity by grouping the set of
functionality of a set of components. Hence independent and self-contained.

169
Middleware and Enterprise Integration Technologies

9.4 Concept of a Service

A service is defined as a unit of work to be performed on behalf of some computing entity, such as a
human user or another program. A service can be invoked remotely. It cannot assume that the client of the
service is operating in the same environment.
A service has a well-defined interface described in an implementation-independent manner. This interface
description should not just describe the API to the service, but should include all details necessary for a
client to invoke the service. Such details include protocol bindings and transport details. A service is self-
contained, that is, it can be used independently of any other services. Notice that this does not preclude
the composition of services built on top of other services. However, it does preclude an implicit sharing of
state between services, where the client would be required to understand such internal behavior in order to
use the service.
A service performs a specific task. The task performed is typically a business task (for example,
validating a credit card number).A service is loosely coupled. This characteristic covers a number of
issues, including:
• The use of document passing in preference to Remote Procedure Calls (RPCs): This also implies
that the services should be course-grained, as opposed to fine-grained. For example, a course-
grained service might accept a document containing all the details required to apply for a loan.
On the other hand, a fine-grained RPC API might provide separate operations to set data such as
customer details, the loan amount, and the purpose of loan.
• Asynchronous message exchange (as opposed to synchronous systems), where in client demands
that the service is available to handle its request immediately.

Characteristics of Service

1. Loosely coupled: It minimizes dependencies between services.


2. Contractual: It adheres to agreement on service descriptions.
3. Autonomous: It controls the business logic they encapsulate.
4. Abstract: It hides the business logic from the service consumers.
5. Reusable: It divides business logic into reusable services.

6. Composable: It facilitates the assembly of composite services.

7. Stateless: It minimizes retained information specific to an activity.

8. Discoverable: It is self-described so that they can be found and assessed.

9. Interoperable: SOA services offer platform, hardware, communication and programming


language transparency. Hence they are interoperable.

10. Self-contained and Modular: It provides a higher degree of modularity by grouping the set of
functionality of a set of components. Hence independent and self-contained.

9.5 Components of SOA

170
Middleware and Enterprise Integration Technologies

Fig. 9.2 Components of SOA

The above figure shows a service model, it consists of:

Service: a software entity designed to support the characteristics of Web Service Architecture (WSA).
It’s a software entity that has an interface(s). It uses SOAP messages (maybe asynchronously also) in its
interactions. A service is an abstraction made concrete by developing a software agent.

Service Provider: The software entity that implements a service specification or description.

Service Consumer: Also called requestor, it’s the software entity client that calls a service provider to
use a service. This can be a user application or another service.

Service Directory/ Registry – A software entity that acts a service locator. It implements the discovery
and order functions for the requestor for a specific service, and where new services are published and
delivered.

Service Broker – A special service that can pass service requests to other service providers.

The service provider, consumer (requestor), and registry are the main roles in an SOA.

In addition, SOA implements three operations, these operations define the contracts between roles.

• Publish: Is an operation that acts as service registration or advertisement. Its operated between
the service registry and service provider.

• Find (Discover): Its the complementary operation of Bind, because services are published so they
can be found. It's the contract between a service requestor and service registry. The find
operation is executed on the registry according to a search criteria specified by the requestor. A
search criteria might be the type of service, QoS (Quality of Service), etc...

• Bind: This operation binds both the service provider and requestor in a client server like
relationship. This relationship can be dynamic or static. Dynamic such as dynamic generation of
client side proxy. While static, the developer hand codes the way of invoking the service to the
client.

171
Middleware and Enterprise Integration Technologies

Fig. 9.3 SOA Operations

9.6 SOA Lifecycle

SOA is characterized by a dynamic life cycle. Inherent in it is the possibility of continuous improvement
of the processes, which, associated with the loose coupling enforced with the SOA, allows processes to
improve as easily as disassembling and reassembling the building blocks (services in this case) without
rework. This improves time to market and alignment of business and IT.

A famous diagram of the SOA life cycle includes the four interconnected hexagonal figures representing
the four stages of SOA. As visible in the diagram in Fig. 9.4, the four stages form a closed loop,
representing the continuous cycle of monitoring and improvement.

Fig. 9.4 SOA Lifecycle

Model stage

172
Middleware and Enterprise Integration Technologies

The model phase includes business analysis and requirements gathering, which are then followed by
modeling and optimizing the business process. The model helps lay a common understanding of the
process, its objectives, and outcomes. It also makes sure that the design meets the business requirement
and provides a baseline to measure the performance later on.

Assemble stage

During this phase, existing assets—such as enterprise resource planning (ERP), financial systems, IBM
CICS® applications, and so on)—that are needed in the modeled processes are wrapped as services, while
non-existing needed functionalities are implemented and tested. After all services are available, they can
be orchestrated to implement the business process.

Deploy stage

During the deployment phase, the runtime environment can be configured to meet the required quality-of-
service levels and security requirements. The environment can be scaled and optimized to be capable of
reliably running the mission-critical processes, and at the same time providing flexibility to make updates
dynamically in case of change.

Manage stage

During this phase, several aspects are managed and monitored, such as the services assets, services
availability and response times, and version control over services. An important role in this phase is
monitoring the key performance indicators (KPIs) of the processes. This helps to prevent or isolate and
diagnose emerging problems in real time as well as provide feedback on the business process
performance and bottlenecks to help improve it. This feedback is sent to the model phase, the first step,
helping improve the process.

Benefits of SOA

SOA's benefits to the business include:

• Increasing the responsiveness of the business to market changes and improving agility in the
organization.

• Bypassing organizational boundaries and synergizing with the existing assets.

• Helping reduce development time.

• Exposing inefficiencies in business processes.

• Ensuring the alignment of IT resources to business strategy and goals.

173
Middleware and Enterprise Integration Technologies

• Decreasing the cost of compliance and security with standards enforcement.

• Making it easier for partners and customers to find you and making it easier for you to find them.

• Granting more consistent processes.

• Providing a different choice of suppliers because of the standards enforcement.

• Enabling asset reuse.

• Reducing the cost of integration.

• Easing upgrades and mergers.

SOA's benefits to the IT strategy include:

• Architecting systems to effectively use standards and services to gain the benefits they promise
the business.

• Allowing various communication mechanisms to be used.

• Allowing flexible and reliable security systems to be incorporated to ensure security.

• Providing a service bus where the flow of messages and messages themselves can be managed
providing another dimension to flexibility and adaptability of the system.

• Easing integration with modular, componentized services and a connecting services bus.

• Being built on standards and protocols that are widely supported to enable interoperability, a goal
of SOA since its start.

• Promoting reuse with a services repository and mediation modules.

• Boosting connectivity using the ESB, which takes connectivity to its highest peak. The ESB is
responsible for mediation of protocols, data, and formats to ensure compatibility.

Challenges in SOA Adoption (Dec 2010) (10 Marks)

1. Managing services metadata: Service Oriented Architecture SOA-based environments can


include many services which exchange messages to perform tasks. Depending on the design,
a single application may generate millions of messages. Managing and providing information
on how services interact is a complicated task.

174
Middleware and Enterprise Integration Technologies

2. Security: Security model built into an application may no longer be appropriate when the
capabilities of the application are exposed as services that can be used by other applications.
That is, application-managed security is not the right model for securing services. A number
of new technologies and standards are emerging to provide more appropriate models for
security in Service Oriented Architecture SOA.

3. Shortage of skilled people: As Service Oriented Architecture SOA and the WS-*
specifications are constantly being expanded, updated and refined, there is a shortage of
skilled people to work on SOA based systems, including the integration of services and
construction of services infrastructure.

4. Interoperability: Interoperability is another important aspect in the Service Oriented


Architecture SOA implementations. The WS-I organization has developed Basic Profile (BP)
and Basic Security Profile (BSP) to enforce compatibility. Testing tools have been designed
by WS-I to help assess whether web services are conformant with WS-I profile guidelines.
Additionally, another Charter has been established to work on the Reliable Secure Profile.

5. Vendor hype: There is significant vendor hype concerning Service Oriented Architecture
SOA that can create expectations that may not be fulfilled. Product stacks are still evolving as
early adopters test the development and runtime products with real world problems. SOA
does not guarantee reduced IT costs, improved systems agility or faster time to market.
Successful SOA implementations may realize some or all of these benefits depending on the
quality and relevance of the system architecture and design.

9.7 Enterprise Service Bus (ESB) (Dec 2010) (10 Marks)

The enterprise service bus (ESB) is a software infrastructure that facilitates application integration. An
ESB is valuable to the implementation of a service-oriented architecture (SOA) because it exchanges
messages, executes transactions, orchestrates services, and performs publish and subscribe functions
between disparate and distributed applications.
An ESB brings flow-related concepts such as transformation and routing to a Service-Oriented
Architecture. An ESB can also provide an abstraction for endpoints. This promotes flexibility in the
transport layer and enables loose coupling and easy connection between services.

175
Middleware and Enterprise Integration Technologies

Fig. 9.5 ESB

Characteristics of ESB

An ESB is expected to exhibit the following characteristics:


• general agnosticism to operating-systems and programming-languages; for example, it should
enable interoperability between Java and .NET applications
• general use of XML as the standard communication language
• support for web-services standards
• support for various MEPs (Message Exchange Patterns) (for example: synchronous
request/response, asynchronous request/response, send-and-forget, publish/subscribe)
• adapters for supporting integration with legacy systems, possibly based on standards such as JCA
• a standardized security-model to authorize, authenticate and audit use of the ESB
• facilitation of the transformation of data formats and values, including transformation services
(often via XSLT or XQuery) between the formats of the sending application and the receiving
application
• validation against schemas for sending and receiving messages
• the ability to apply business rules uniformly
• enriching messages from other sources
• the splitting and combining of multiple messages and the handling of exceptions
• the provision of a unified abstraction across multiple layers
• routing or transforming messages conditionally, based on a non-centralized policy (without the
need for a central rules-engine)
• queuing, holding messages if applications temporarily become unavailable

Functions of ESB

1. Routing - A service provider offers a service at an endpoint. Consequently the service requests
need to be routed from the consumer to the provider's end point.
2. Transformation - A service request might need to be transformed from one format to another. It
might be XML to XML transformation using XSLT.
3. Adaptation - Messages in an ESB most of the times follow standard SOAP format. However
some application may not support SOAP format and might need some kind of adapter to
transform the message.
4. Messaging - Provides asynchronous reliable messaging transport.
5. Orchestration - An integration scenario might require state information to be managed by an
orchestration engine that orchestrates the flow of control from one service to another.
6. UDDI Registry - The services are registered in the registry for applications to discover them. A
registry will be used at design time to find out details about the service using a WSDL file. It will
also be used at run time to locate the valid endpoint for the service.

7. Security: Authentication and authorization of entities making the service calls using ESB
infrastructure.

8. Consumer Integration - Ability for consumers to lookup the endpoint and direct the service
requests to that endpoint.

9. Service Integration - Validating the service requests and enforcing policies to enable secure
service invocation.

176
Middleware and Enterprise Integration Technologies

10. Metrics and Management - Monitoring the ESB infrastructure to measure the key performance
variables.

Architecture of ESB

The architecture of an ESB as its name suggests is centered on a bus. Message delivery services are
provided by the ESB based on standards like SOAP, HTTP and Java™ Messaging Service (JMS).
Typically designed for high throughput, an ESB promises guaranteed message delivery to a variety of
service providers and consumers. The use of multiple protocols such as synchronous and asynchronous
are enabled and aid in performing transformation and routing of service requests. Supporting different
standards such as SOAP, XML, WSDL, JMS, J2EE, JAX-RPC etc, the ESB enables services to interact
with each other.

Fig. 9.6 Architecture of ESB

The component types that can connect to an ESB are:


• Custom applications, based on standards like J2EE and Struts, which plug into the
ESB to provide a user interface to enterprise services
• Service orchestration engine, which hosts long running business processes, based on
standards like Business Process Execution Language (BPEL).
• Adapters, typically built to the Java Connector Architecture (JCA) specification,
enable integration with a wide variety of enterprise applications.
• Presentation and portals enable the creation of personalized portals that aggregate
services from multiple sources.
• Data services which provides real time view of data from heterogeneous data sources.
• Web Services provides a standard means of connectivity to legacy and proprietary
integration technologies.

177
Middleware and Enterprise Integration Technologies

Benefits of ESB

• Faster and cheaper accommodation of existing systems.


• Increased flexibility; easier to change as requirements change.
• Standards-based
• Scales from point-solutions to enterprise-wide deployment (distributed bus).
• Predefined ready-for-use service types.
• More configuration rather than integration coding.
• No central rules-engine, no central broker.
• Incremental patching with zero down-time; enterprise becomes "refactorable".

Disadvantages of ESB

• Usually requires an Enterprise Message Model, resulting in additional management overhead.


Potential difficulties integrating many disparate systems to collaborate via message standards.
• Requires ongoing management of message versions to ensure the intended benefit of loose
coupling. Incorrect, insufficient, or incomplete management of message versions can result in
tight coupling instead of the intended loose coupling.
• It normally requires more hardware than simple point-to-point messaging.
• Middleware analysis skills needed to configure, manage, and operate an ESB.
• Extra overhead and increased latency caused by messages traversing the extra ESB layer,
especially as compared to point-to-point communications. The increased latency also results from
additional XML processing (the ESB normally uses XML as the communication language).
• Though ESB systems can require a significant effort to implement, they produce no commercial
value without the subsequent development of SOA services for the ESB.

9.8 SOA enterprise Software Models

Layer 1: Operational systems layer. This consists of existing custom built applications, otherwise called
legacy systems, including existing CRM and ERP packaged applications, and older object-oriented
system implementations, as well as business intelligence applications. The composite layered architecture
of an SOA can leverage existing systems and integrate them using service-oriented integration techniques.

Layer 2: Enterprise components layer. This is the layer of enterprise components that are responsible
for realizing functionality and maintaining the QoS of the exposed services. These special components are
a managed, governed set of enterprise assets that are funded at the enterprise or the business unit level. As
enterprise-scale assets, they are responsible for ensuring conformance to SLAs through the application of
architectural best practices. This layer typically uses container-based technologies such as application
servers to implement the components, workload management, high-availability, and load balancing.

178
Middleware and Enterprise Integration Technologies

Fig. 9.7 Architectural Layers of SOA

Layer 3: Services layer. The services the business chooses to fund and expose reside in this layer. They
can be discovered or be statically bound and then invoked, or possibly, choreographed into a composite
service. This service exposure layer also provides for the mechanism to take enterprise scale components,
business unit specific components, and in some cases, project-specific components, and externalizes a
subset of their interfaces in the form of service descriptions. Thus, the enterprise components provide
service realization at runtime using the functionality provided by their interfaces. The interfaces get
exported out as service descriptions in this layer, where they are exposed for use. They can exist in
isolation or as a composite service.

Layer 4: Business process composition or choreography layer. Compositions and choreographies of


services exposed in Layer 3 are defined in this layer. Services are bundled into a flow through
orchestration or choreography, and thus act together as a single application. These applications support
specific use cases and business processes. Here, visual flow composition tools, such as IBM®
WebSphere® Business Integration Modeler or Websphere Application Developer Integration Edition, can
be used for the design of application flow.

Layer 5: Access or presentation layer. Although this layer is usually out of scope for discussions
around a SOA, it is gradually becoming more relevant. I depict it here because there is an increasing
convergence of standards, such as Web Services for Remote Portlets Version 2.0 and other technologies,
that seek to leverage Web services at the application interface or presentation level. You can think of it as
a future layer that you need to take into account for future solutions. It is also important to note that SOA
decouples the user interface from the components, and that you ultimately need to provide an end-to-end
solution from an access channel to a service or composition of services.

Layer 6: Integration (ESB). This layer enables the integration of services through the introduction of a
reliable set of capabilities, such as intelligent routing, protocol mediation, and other transformation
mechanisms, often described as the ESB. Web Services Description Language (WSDL) specifies a
binding, which implies a location where the service is provided. On the other hand, an ESB provides a
location independent mechanism for integration.

Layer 7: QoS. This layer provides the capabilities required to monitor, manage, and maintain QoS such
as security, performance, and availability. This is a background process through sense-and-respond
mechanisms and tools that monitor the health of SOA applications, including the all important standards

179
Middleware and Enterprise Integration Technologies

implementations of WS-Management and other relevant protocols and standards that implement quality
of service for a SOA.

----------------------
University Questions
1. What are the functions of Enterprise Service Bus? State its advantages and disadvantages.
(Dec 2010)
2. What are the challenges in SOA? (Dec 2010)

Chapter 10
Web Services Technologies

180
Middleware and Enterprise Integration Technologies

10.1 XML Technologies (Dec 2010)(10 Marks)

XML stands for eXtensible Markup Language. As the name suggests, XML is a markup language. The
XML specification was created by the World Wide Web Consortium (W3C), the body that sets
standards for the web.

Features/Benefits of XML

XML has been widely adopted since its creation and with good reason. Some of the key features and
benefits of XML include:

• Easy data exchange - One of the great things about XML is that it can allow easy sharing of data
between different applications - even if these applications are written in different languages and
reside on different platforms.
• Self-describing data - When you look at an XML document, it is very easy to figure out what's
going on.
• Create your own languages - XML allows you to specify your own markup language for your
own specific purpose. Some existing XML based languages include Banking Industry
Technology Secretariat (BITS), Bank Internet Payment System (BIPS), Financial Exchange (IFX)
and many more.

What Does XML Look Like?

The following example demonstrates what the contents of a typical XML document could look
like.

<?xml version="1.0" encoding="UTF-8"?>


<tutorials>
<tutorial>
<name>XML Tutorial</name>
<url>http://www.rgit.com/xml/tutorial</url>
</tutorial>
<tutorial>
<name>HTML Tutorial</name>
<url>http://www.rgit.com/html/tutorial</url>
</tutorial>
</tutorials>

Difference Between XML and HTML

If you're familiar with HTML, you might notice that XML looks similar to HTML. Like XML,
HTML is also a markup language. In fact, HTML stands for Hypertext Markup Language.
Markup languages are used for describing how a document's contents should be interpreted.

HTML

181
Middleware and Enterprise Integration Technologies

HTML includes over 100 pre-defined tags to allow the author to specify how each piece of
content should be presented to the end user. For example, if you surround some content with
<b></b> tags, the user agent/browser will render that content using a bold typeface.

XML

XML allows you to create your own tags to describe the data between them. You're not
particularly interested in how the data will be presented. Your main focus is ensuring that the data
is well organized within descriptive tags (or elements). This is because XML is primarily used for
data storage and transfer purposes - not for presentation purposes.

XML Documents

Similar to an HTML document, XML documents consist of stuff at the top of the document,
followed by the content.
Consider the following XML example:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<!DOCTYPE document system "tutorials.dtd">

<!-- Here is a comment -->

<?xml-stylesheet type="text/css" href="myStyles.css"?>

<tutorials>

<tutorial>

<name>XML Tutorial</name>

<url>http://www.quackit.com/xml/tutorial</url>

</tutorial>

<tutorial>

<name>HTML Tutorial</name>

<url>http://www.quackit.com/html/tutorial</url>

</tutorial>

</tutorials>

182
Middleware and Enterprise Integration Technologies

The following table provides an explanation of each part of the XML document in the above
example:
<?xml version="1.0" encoding="UTF-8"
XML Declaration
standalone="no"?>

Document Type
<!doctype document system "tutorials.dtd">
Definition (DTD)
Prolog
(optional) Comment <!-- Here is a comment -->

Processing <?xml-stylesheet type="text/css"


Instructions href="myStyles.css"?>

White Space

Root element
<tutorials>
opening tag

<tutorial>

<name>XML Tutorial</name>

<url>http://www.rgit.com/xml/tutorial</url>

Elements & </tutorial>


Child elements
Content <tutorial>
and content
(required)
<name>HTML Tutorial</name>

<url>http://www.rgit.com/html/tutorial</url
>

</tutorial>

Root element
</tutorials>
closing tag

183
Middleware and Enterprise Integration Technologies

Here's a more detailed explanation of each part:

Prolog

Right at the top of the document, we have a prolog (also spelt prologue). A prolog is optional, but
if it is included, it should become at the beginning of the document. The prolog can contain things
such as the XML declaration, comments, processing instructions, white space, and document type
declarations. Although the prolog (and everything in it) is optional, it's recommended that you
include the XML declaration in your XML documents.

XML Declaration

The XML declaration indicates that the document is written in XML and specifies which version
of XML. The XML declaration, if included, must be on the first line of the document.
The XML declaration can also specify the language encoding for the document (optional) and if
the application refers to external entities (optional). In our example, we specify that the document
uses UTF-8 encoding (although we don't really need to as UTF-8 is the default), and we specify
that the document refers to external entities by using standalone="no". This is not a standalone
document as it relies on an external resource (i.e. the DTD).
Although the XML declaration is optional, the W3C recommends that you include it in your
XML documents. In any case, you'll need the XML declaration to successfully validate your
document.

Document Type Definition (DTD)

The DTD defines the rules of your XML document. Although XML itself has rules, the rules
defined in a DTD are specific to your own needs. More specifically, the DTD allows you to
specify the names of the elements that are allowed in the document, which elements are allowed
to be nested inside other elements, and which elements can only contain data.
The DTD is used when you validate your XML document. Any application that uses the
document must stop processing if the document doesn't adhere to the DTD.
DTDs can be internal (i.e. specified within the document) or external (i.e. specified in an external
file). In our example, the DTD is external.

Comments

XML comments begin with <!-- and end with -->. Similar to HTML comments, XML comments
allow you to write stuff within your document without it being parsed by the processor. You
normally write comments as an explanatory note to yourself or another programmer. Comments
can appear anywhere within your document.

Processing Instructions

184
Middleware and Enterprise Integration Technologies

Processing instructions begin with <? and end with ?>. Processing instructions are instructions for
the XML processor. Processing instructions are not built into the XML recommendation. Rather,
they are processor-dependant so not all processors understand all processing instructions. Our
example is a common processing instruction that many processors understand. The instruction to
the processor is to use an external style sheet.

White Space

White space is simply blank space created by carriage returns, line feeds, tabs, and/or spaces.
White space doesn't affect the processing of the document, so you can choose to include
whitespace or not.
Technically speaking, the XML recommendation specifies that XML documents use the UNIX
convention for line endings. This means that you should use a linefeed character only (ASCII
code 10) to indicate the end of a line.
Speaking of white space, there is a special attribute (xml:whitespace) that you can use to preserve
whitespace within your elements (but we won't concern ourselves with that just now).

Elements & Content

This is where the document's content goes. It consists of one or more elements, nested within a
single root element.

Root Element Opening Tag

All XML documents must have one (and only one) root element. All other elements must be
nested inside this root element. In other words, the root element must contain all other elements
within the document. Therefore, the first tag in the document will always be the opening tag of
the root element (the closing tag will always be at the bottom of the document).

Child Elements and Content

These are the elements that are contained within the root element. Elements are usually
represented by an opening and closing tag. Data and other elements reside between the opening
and closing tag of an element.
Although most elements contain an opening and closing tag, XML allows you to use empty
elements. An empty element is one without a closing tag. You might be familiar with some empty
elements used in HTML such as the <img> element or the <br> element. In XML, you must close
empty elements with a forward slash before the > symbol. For example, <br />.
Elements can also contain one or more attributes. An attribute is a name/value pair, that you place
within an opening tag, which allows you to provide extra information about an element. You may
be familiar with attributes in HTML. For example, the HTML img tag requires the src attribute
which specifies the location of an image (eg, <img src="myImage.gif" />).

Root Element Closing Tag

185
Middleware and Enterprise Integration Technologies

The last tag of the document will always be the closing tag of the root element. This is because all
other elements are nested inside the root element.

Uses of XML

• XML Separates Data from HTML

– Allow you to modify data without affecting the layout or to modify the layout without
affecting the data.

• XML Simplifies Data Sharing / Transport

– XML data is stored in plain text format. This provides a software and hardware-
independent way of storing data

– With XML, data can easily be exchanged between incompatible systems.

• XML is Used to Create New Internet Languages

– XHTML, the latest version of HTML

– WSDL, describing Web services and how to access them

– SOAP, a format for sending and receiving messages to web services

XML Syntax

XML syntax refers to the rules that determine how an XML application can be written. The XML syntax
is very straight forward, and this makes XML very easy to learn. Below are the main points to remember
when creating XML documents.

Well-formedness

The W3C specifies that all XML documents must be well-formed. Specifically, a textual object is a well-
formed XML document if:

• Taken as a whole, it matches the production labeled document

• It meets all the well-formedness constraints given the XML specification

• Each of the parsed entities which is referenced directly or indirectly within the document is well-
formed

XML Declaration

If you include an XML declaration, it must be the first item in your document. The XML declaration uses
the <?xml?> element.

Example:

186
Middleware and Enterprise Integration Technologies

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

One Root Element Only

Each XML document must have one root element and no more. All other elements must be contained
within the root element.

Example:

<root>
<child>Data</child>
<child>More Data</child>
</root>

XML Markup

Generally speaking, an XML document consists of markup and data. Markup is provided in the form of
tags and attributes. Data is the text that goes in between the tags or is provided within their attributes.

XML Elements

XML elements are represented by tags. Elements usually consist of an opening tag and a closing tag, but
they can consist of just one tag. Opening tags consist of <, followed by the element name, and ending
with >. Closing tags are the same but have a forward slash inserted between the less than symbol and the
element name.

Example:

<tag>Data</tag>

Empty elements are closed by inserting a forward slash before the greater than symbol.

Example of empty tag:

<tag />

The following syntax rules are important to note, especially if you're used to working with HTML where
you don't usually need to worry about these rules.

All Elements Must Be Closed Properly

If you're familiar with HTML, you will know that some HTML tags don't need to be closed. In XML
however, you must close all tags. This is usually done in the form of a closing tag where you repeat the
opening tag, but place a forward slash before the element name (i.e. </child>). If you are using an empty
element (i.e. one with no closing tag), you need to place a forward slash before the greater than symbol at
the end of the tag (i.e. <child />).

Example for opening/closing tags:

187
Middleware and Enterprise Integration Technologies

<child>Data</child>

Example for empty elements:

<child attribute="value" />

Tags Are Case Sensitive

All tags must be written using the correct case. XML sees <tutorial> as a different tag to <Tutorial>

Wrong:

<Tutorial>XML</tutorial>

Right:

<Tutorial>XML</Tutorial>
<tutorial>XML</tutorial>
<TUTORIAL>XML</TUTORIAL>
Elements Must Be Nested Properly

You can place elements inside other elements but you need to ensure each element's closing tag doesn't
overlap with any other tags.

Wrong:

<tutorial>
<name>XML</tutorial>
</name>
Right:

<tutorial>
<name>XML</name>
</tutorial>

Element Names

You can use any name you like for your elements as long as they adhere to the following rules:

• Element names can contain any character (including letters and numbers)
• Element names must not contain spaces
• Element names must not begin with a number or punctuation character (for example a comma or
semi-colon etc)
• Element names must not start with the letters xml (whether lowercase, uppercase, or mixed case)

You shouldn't use a colon (:) in your element names, as this is reserved for another purpose.

XML Attributes

188
Middleware and Enterprise Integration Technologies

XML elements can also contain attributes. You use attributes within your elements to provide more
information about the element. These are represented as name/value pairs.

Example:

<tag attribute="value">Data</tag>

It's important to remember the following syntax rules when using attributes.

Quotes

You must place quotation marks around the attribute's value.

Wrong:

<tutorials type=Web>
<tutorial>
<name>XML</name>
</tutorial>
</tutorials>

Right:

<tutorials type="Web">
<tutorial>
<name>XML</name>
</tutorial>
</tutorials>

XML Namespace

In XML, a namespace is used to prevent any conflicts with element names.

Because XML allows you to create your own element names, there's always the possibility of naming an
element exactly the same as one in another XML document. This might be OK if you never use both
documents together. But what if you need to combine the content of both documents? You would have a
name conflict. You would have two different elements, with different purposes, both with the same name.

Example Name Conflict

Imagine we have an XML document containing a list of books. Something like this:

<books>
<book>
<title>The Dream Saga</title>
<author>Matthew Mason</author>
</book>
...
</books>
And imagine we want to combine it with the following HTML page:

189
Middleware and Enterprise Integration Technologies

<html>
<head>
<title>Cool Books</title>
</head>
<body>
<p>Here's a list of cool books...</p>

(XML content goes here)

</body>
</html>
We will encounter a problem if we try to combine the above documents. This is because they both have
an element called title. One is the title of the book, the other is the title of the HTML page. We have a
name conflict.
What we can do to prevent this name conflict is, create a namespace for the XML document.

Example Namespace

Using the above example, we could change the XML document to look something like this:

<bk:books xmlns:bk="http://somebooksite.com/book_spec">
<bk:book>
<bk:title>The Dream Saga</bk:title>
<bk:author>Matthew Mason</bk:author>
</bk:book>
...
</bk:books>

We have added the xmlns:{prefix} attribute to the root element. We have assigned this attribute a unique
value. This unique value is usually in the form of a Uniform Resource Identifier (URI). This defines the
namespace.
And, now that the namespace has been defined, we have added a bk prefix to our element names.

Now, when we combine the two documents, the XML processor will see two different element names:
bk:title (from the XML document) and title (from the HTML document).

Note: If you have defined your tags and attributes in a DTD, you will need to update your DTD in order
to make the new element names legal.

XML Entities

XML entities allow you to use text to refer to a data item, instead of using the data item itself.

You can use entities to represent:

• Characters that would otherwise cause problems for the XML processor
• Large blocks of data that need to be repeated throughout the document
• Characters that you can't type on your keyboard (i.e. ©)

190
Middleware and Enterprise Integration Technologies

Problematic Characters

Some characters have a special meaning in XML. For example, the less than sign (<) marks the beginning
of a tag. And, of course, the greater than sign (>) marks the end of the tag. When the XML processor
parses the document, it looks for these characters (and others) to determine how to interpret the document.

This is fine, as long as your data doesn't contain any of these characters. But what if it does? What if your
data contains say, a less than sign?

Imagine you had the following text within an element: 10 < 5. When the XML processor encounters the
<, it will assume it's the start of an opening tag. Problem is, it's not.

In order to include characters such as < and & etc, you need to use their entity reference instead of the
character itself.

Entity Syntax

You start an entity reference using the & character and close it using the ; character.

Example:

&lt;

The above entity reference represents the following character: <

Predefined Entity References

There are 5 predefined entity references in XML. These are:

Entity Reference Character


&lt; <
&gt; >
&amp; &
&quot; "
&apos; '

XML Creating Entities

To create your own entity, you simply define the entity in your DTD. Once you've defined the entity in
your DTD, you are ready to use it within your XML document.

Defining Your Entity

You define your entity using the <!ENTITY> element using the following syntax:

<!ENTITY name definition>

191
Middleware and Enterprise Integration Technologies

Here, name is the entity's name. definition is the entity's definition.

Using Your Entity

Whenever you need to use your entity, you simply write the entity's name, surrounded by an ampersand
(&) and a semi-colon (;).

&entity_name;

Example

Imagine you have some text that you want to repeat at the bottom of all your documents. Let's say the text
goes something like "Thank you, please come again!".

Instead of typing all that text out every time you need to use it, you could create an entity called say,
"footer". That way, you just need to include &footer; whenever you want to include that text. Now, if you
ever need to change the text you only need to change it in one place - the definition.

<?xml version="1.0"?>
<!DOCTYPE tutorials [
<!ENTITY footer "Thank you, please come again!">
<]>
<tutorials>
<tutorial>
<name>XML Tutorial</name>
<url>http://www.quackit.com/xml/tutorial</url>
<footer>&footer;</footer>
</tutorial>
<tutorial>
<name>HTML Tutorial</name>
<url>http://www.quackit.com/html/tutorial</url>
<footer>&footer;</footer>
</tutorial>
</tutorials>

XML CDATA

In XML, a CDATA section is used to escape a block of text that would otherwise be parsed as markup.

Why Are CDATA Sections Useful?

You might occasionally find that your data contains large blocks of text with lots of potentially
problematic characters. For example, your data could contain a programming script. Many progamming
scripts contain characters such as less than/greater than signs, ampersands etc, which would cause
problems for the XML processor.

CDATA allows you to escape the whole block of text. This eliminates the need to go through the whole
script, individually replacing all the potentially problematic characters. The XML processor knows to
escape all data between the CDATA tags.

192
Middleware and Enterprise Integration Technologies

CDATA Syntax

You declare a CDATA section using <![CDATA[ as the opening tag, and ]]> as the closing tag.

Example:

<root>

<child>

<![CDATA[

Text you want to escape goes here...

]]>

</child>

</root>

CDATA Section Example

In this example, we have a block of JavaScript code inside an XHTML document. If you've been involved
in web development, you'll probably know how common JavaScript is on the web. You might also know
that any block of JavaScript code could contain all sorts of potentially problematic characters.

W3C has recommended that all scripts within an XHTML document be escaped using CDATA sections.

<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Displaying the Time</title>

<script type="text/javascript">
<![CDATA[
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()

var suffix = "AM";


if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}

if (minutes < 10)

193
Middleware and Enterprise Integration Technologies

minutes = "0" + minutes

document.write("<b>" + hours + ":" + minutes + " " + suffix + "</b>")


]]>
</script>

</head>
<body>
<h1>Displaying the Time</h1>
</body>
</html>

10.1.1 DTD Introduction

DTD stands for Document Type Definition. A DTD allows you to create rules for the elements within
your XML documents. Although XML itself has rules, the rules defined in a DTD are specific to your
own needs.

So, for an XML document to be well-formed, it needs to use correct XML syntax, and it needs to conform
to its DTD or schema (we'll cover XML schemas later).

The DTD is declared at the top of your XML document. The actual contents of the DTD can be included
within your XML document or included in another document and linked to (or both).

Do I Need to Create a DTD?

If you have created your own XML elements, attributes, and/or entities, then you should create a DTD.

If you are creating an XML document using pre-defined elements/attributes/entities (i.e. ones that have
been created by someone else), then a DTD should already exist. All you need to do is link to that DTD
using the DOCTYPE declaration. (We'll cover DOCTYPE soon).

What's in a DTD?

A DTD consists of a list of syntax definitions for each element in your XML document.

When you create a DTD, you are creating the syntax rules for any XML document that uses the DTD.
You are specifying which element names can be included in the document, the attributes that each
element can have, whether or not these are required or optional, and more.

Example DTD

The following example demonstrates what a DTD could look like:

<!ELEMENT tutorials (tutorial)+>


<!ELEMENT tutorial (name,url)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT url (#PCDATA)>
<!ATTLIST tutorials type CDATA #REQUIRED>

194
Middleware and Enterprise Integration Technologies

DTD <!DOCTYPE>
If you've viewed the source code of a (valid) XHTML file, you may have seen a line like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
The purpose of this line is to declare the Document Type Definition (DTD). Actually, we even used the
DOCTYPE declaration in a previous lesson to define an entity.

Internal DTD

Whether you use an external or internal DTD, the actual syntax for the DTD is the same - the same code
could just as easily be part of an internal DTD or an external one. The only difference between internal
and external is in the way it's declared with DOCTYPE.
Using an internal DTD, the code is placed between the DOCTYPE tags (i.e. <!DOCTYPE tutorials [ and
]>.

Example Internal DTD

This is an example of an internal DTD. It's internal because the DTD is included in the target XML
document:
<?xml version="1.0" standalone="yes"?>
<!DOCTYPE tutorials [
<!ELEMENT tutorials (tutorial)+>
<!ELEMENT tutorial (name,url)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT url (#PCDATA)>
<!ATTLIST tutorials type CDATA #REQUIRED>
]>
<tutorials>
<tutorial>
<name>XML Tutorial</name>
<url>http://www.rgit.com/xml/tutorial</url>
</tutorial>
<tutorial>
<name>HTML Tutorial</name>
<url>http://www.rgit.com/html/tutorial</url>
</tutorial>
</tutorials>

External DTD

195
Middleware and Enterprise Integration Technologies

An external DTD is one that resides in a separate document. To use the DTD, you need to link to it from
your XML document by providing the URI of the DTD file. This URI is typically in the form of a URL.
The URL can point to a local file using a relative reference, or a remote one (i.e. using HTTP) using an
absolute reference.

Example External DTD

Here's an example of an XML document that uses an external DTD. Note that the "standalone" attribute is
set to "no". This is because the document relies on an external resource (the DTD):

<?xml version="1.0" standalone="no"?>


<!DOCTYPE tutorials SYSTEM "tutorials.dtd">
<tutorials>
<tutorial>
<name>XML Tutorial</name>
<url>http://www.rgit.com/xml/tutorial</url>
</tutorial>
<tutorial>
<name>HTML Tutorial</name>
<url>http://www.rgit.com/html/tutorial</url>
</tutorial>
</tutorials>

And, using the above XML document as an example, here's an example of what "tutorials.dtd" (the
external DTD file) could look like. Note that the external DTD file doesn't need the DOCTYPE
declaration - it is already on the XML file that is using this DTD:

<!ELEMENT tutorials (tutorial)+>


<!ELEMENT tutorial (name,url)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT url (#PCDATA)>
<!ATTLIST tutorials type CDATA #REQUIRED>

Combined DTD

You can use both an internal DTD and an external one at the same time. This could be useful if you need
to adhere to a common DTD, but also need to define your own definitions locally.

Example

This is an example of using both an external DTD and an internal one for the same XML document. The
external DTD resides in "tutorials.dtd" and is called first in the DOCTYPE declaration. The internal DTD
follows the external one but still resides within the DOCTYPE declaration:

196
Middleware and Enterprise Integration Technologies

Here, I've added a new element called "summary". This element must be present under the "tutorial"
element. Because this element hasn't been defined in the external DTD, I need to define it internally.
Once again, we're setting the "standalone" attribute to "no" because we rely on an external resource.
<?xml version="1.0" standalone="no"?>
<!DOCTYPE tutorials SYSTEM "tutorials.dtd" [
<!ELEMENT tutorial (summary)>
<!ELEMENT summary (#PCDATA)>
]>
<tutorials>
<tutorial>
<name>XML Tutorial</name>
<url>http://www.rgit.com/xml/tutorial</url>
<summary>Best XML tutorial on the web!</summary>
</tutorial>
<tutorial>
<name>HTML Tutorial</name>
<url>http://www.rgit.com/html/tutorial</url>
<summary>Best HTML tutorial on the web!</summary>
</tutorial>
</tutorials>

DTD Elements

Creating a DTD is quite straight forward. It's really just a matter of defining your elements, attributes,
and/or entities. Over the next few lessons, I'll explain how to define your elements, attributes, and entities.

To define an element in your DTD, you use the <!ELEMENT> declaration. The actual contents of your
<!ELEMENT> declaration will depend on the syntax rules you need to apply to your element.

Basic Syntax

The <!ELEMENT> declaration has the following syntax:


<!ELEMENT element_name content_model>
Here, element_name is the name of the element you're defining. The content model could indicate a
specific rule, data or another element.
• If it specifies a rule, it will be set to either ANY or EMPTY.
• If specifies data or another element, the data type/element name needs to be surrounded by
brackets (i.e. (tutorial) or (#PCDATA)).
The following examples show you how to use this syntax for defining your elements.

Plain Text

If an element should contain plain text, you define the element using #PCDATA. PCDATA stands for
Parsed Character Data and is the way you specify non-markup text in your DTDs.
Using this example - <name>XML Tutorial</name> - the "XML Tutorial" part is the PCDATA. The
other part consists of markup.
Syntax:

197
Middleware and Enterprise Integration Technologies

<!ELEMENT element_name (#PCDATA)>


Example:
<!ELEMENT name (#PCDATA)>
The above line in your DTD allows the "name" element to contain non-markup data in your XML
document:
<name>XML Tutorial</name>

Unrestricted Elements

If it doesn't matter what your element contains, you can create an element using the content_model of
ANY. Note that doing this removes all syntax checking, so you should avoid using this if possible. You're
better off defining a specific content model.
Syntax:
<!ELEMENT element_name ANY>
Example:
<!ELEMENT tutorials ANY>

Empty Elements

You might remember that an empty element is one without a closing tag. For example, in XHTML, the
<br /> and <img /> tags are empty elements. Here's how you define an empty element:
Syntax:
<!ELEMENT element_name EMPTY>
Example:
<!ELEMENT header EMPTY>
The above line in your DTD defines the following empty element for your XML document:
<header />

Child Elements

You can specify that an element must contain another element, by providing the name of the element it
must contain. Here's how you do that:
Syntax:
<!ELEMENT element_name (child_element_name)>
Example:
<!ELEMENT tutorials (tutorial)>
The above line in your DTD allows the "tutorials" element to contain one instance of the "tutorial"
element in your XML document:
<tutorials>
<tutorial></tutorial>
</tutorials>

Multiple Child Elements (Sequences)

You can also provide a comma separated list of elements if it needs to contain more than one element.
This is referred to as a "sequence". The XML document must contain the tags in the same order that
they're specified in the sequence.
Syntax:
<!ELEMENT element_name (child_element_name, child_element_name,...)>
Example:
<!ELEMENT tutorial (name, url)>

198
Middleware and Enterprise Integration Technologies

The above line in your DTD allows the "tutorial" element to contain one instance of the "name" element
and one instance of the "url" element in your XML document:
<tutorials>
<tutorial>
<name></name>
<url></url>
</tutorial>
</tutorials>

DTD Attributes

Just as you need to define all elements in your DTD, you also need to define any attributes they use. You
use the <!ATTLIST> declaration to define attributes in your DTD.

Syntax

You use a single <!ATTLIST> declaration to declare all attributes for a given element. In other words, for
each element (that contains attributes), you only need one <!ATTLIST> declaration.
The <!ATTLIST> declaration has the following syntax:

<!ATTLIST element_name
attribute_name TYPE DEFAULT_VALUE
attribute_name TYPE DEFAULT_VALUE
attribute_name TYPE DEFAULT_VALUE
...>
Here, element_name refers to the element that you're defining attributes for, attribute_name is the name
of the attribute that you're declaring, TYPE is the attribute type, and DEFAULT_VALUE is it's default
value.

Example

<!ATTLIST tutorial
published CDATA "No">

Here, we are defining an attribute called "published" for the "tutorial" element. The attribute's type is
CDATA and it's default value is "No".

DTD General Entities

Syntax
The <!ENTITY> declaration for general entities has the following syntax:
<!ENTITY name definition>
You can also declare external general entities. This enables you to use an entity from a remote file. You
declare external general entities using the following syntax:
Private:
<!ENTITY name SYSTEM uri>
Public:
<!ENTITY name PUBLIC FPI uri>

Example
<!ENTITY author "Homer Flinstone">

199
Middleware and Enterprise Integration Technologies

After declaring the entity named "author", we can now use it in our XML document:
<books>
<book>
<name>Life as a cartoon character</name>
<author>&author;</author>
</book>
</book>

Examples
1. Write an internal DTD to validate the XML document sample below

<PARTS>
<TITLE>Computer Parts</TITLE>
<PART>
<ITEM>Motherboard</ITEM>
<MANUFACTURER>ASUS</MANUFACTURER>
<MODEL>P6T</MODEL>
<COST>2000</COST>
</PART>
<PART>
<ITEM>24 inch Monitor</ITEM>
<MANUFACTURER>Samsung</MANUFACTURER>
<MODEL>XL2370</MODEL>
<COST>3000</COST>
</PART>
</PARTS>

Solution:
<!DOCTYPE PARTS [
<!ELEMENT PARTS (TITLE, PART*)>
<!ELEMENT TITLE (#PCDATA)>
<!ELEMENT PART (ITEM, MANUFACTURER, MODEL, COST)>
<!ELEMENT ITEM (#PCDATA)>
<!ELEMENT MANUFACTURER (#PCDATA)>
<!ELEMENT MODEL (#PCDATA)>
<!ELEMENT COST (#PCDATA)>
]>

2. Write a valid XML document that will pass the following DTD.

<!DOCTYPE TVSCHEDULE [
<!ELEMENT TVSCHEDULE (CHANNEL+)>
<!ELEMENT CHANNEL (BANNER,DAY+)>
<!ELEMENT BANNER (#PCDATA)>
<!ELEMENT DAY (DATE,(HOLIDAY|PROGRAMSLOT+)+)>
<!ELEMENT HOLIDAY (#PCDATA)>
<!ELEMENT DATE (#PCDATA)>
<!ELEMENT PROGRAMSLOT (TIME,TITLE,DESCRIPTION?)>
<!ELEMENT TIME (#PCDATA)>
<!ELEMENT TITLE (#PCDATA)>
<!ELEMENT DESCRIPTION (#PCDATA)>

200
Middleware and Enterprise Integration Technologies

<!ATTLIST TVSCHEDULE NAME CDATA #REQUIRED>


<!ATTLIST CHANNEL CHAN CDATA #REQUIRED>
<!ATTLIST PROGRAMSLOT VTR CDATA #IMPLIED>
<!ATTLIST TITLE RATING CDATA #IMPLIED>
<!ATTLIST TITLE LANGUAGE CDATA #IMPLIED>
]>
Solution:
<TVSCHEDULE NAME="tvb">
<CHANNEL CHAN="1">
<BANNER>TVB pearl</BANNER>
<DAY>
<DATE>2009-10-1</DATE>
<HOLIDAY>National Day</HOLIDAY>
</DAY>
</CHANNEL>
</TVSCHEDULE>

10.1.2 XML Schema

• XML Schema is an XML-based alternative to DTD.


• An XML schema describes the structure of an XML document.
• The XML Schema language is also referred to as XML Schema Definition (XSD)

Advantage of XML Schema over DTD

– XML Schema are written in XML.


– XML Schema supports more data types. e.g. integer, date ……
– XML Schema is extensible.
– XML Schema supports namespaces.

XML Schema Basics

• A schema and its associated XML document are stored in separate files.
• The schema itself is a XML document that is written according to the rules given in the W3C XML
Schema specification.
• A particular XML document that conforms to the structures of a schema is known as an instance
document of that schema.
• An instance document is considered to be valid with respect to the schema, just as a document that
contains a DTD and conforms to the DTD's declaration is considered valid with respect to its DTD.

minOccurs and maxOccurs in XML Schema

• minOccurs attribute specify the minimum number of times the element should appear.
• maxOccurs attribute specify the maximum number of times the element can appear, you can set it to
"unbounded" if the element can appear unlimited number of times.
• The default value for minOccurs is "1".
• The default value for maxOccurs is "1".
• Therefore

<xsd:element ref="Title" minOccurs="1" maxOccurs="1"/>

201
Middleware and Enterprise Integration Technologies

Is equivalent to
<xsd:element ref="Title"/>

Example:

1. Convert the following DTD into XML Schema, name it juicers.xsd.


<!ELEMENT juicers (juicer)*>
<!ELEMENT juicer (name, image, description, warranty?, weight?, cost+, retailer)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT image (#PCDATA)>
<!ELEMENT description (#PCDATA)>
<!ELEMENT warranty (#PCDATA)>
<!ELEMENT weight (#PCDATA)>
<!ELEMENT cost (#PCDATA)>
<!ELEMENT retailer (#PCDATA)>

Solution:
<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="juicers">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="juicer" minOccurs="0" maxOccurs="unbounded">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="name" type="xsd:string"/>
<xsd:element name="image" type="xsd:string"/>
<xsd:element name="description" type="xsd:string"/>
<xsd:element name="warranty" type="xsd:string" minOccurs="0"/>
<xsd:element name="weight" type="xsd:string" minOccurs="0"/>
<xsd:element name="cost" type="xsd:string" maxOccurs="unbounded"/>
<xsd:element name="retailer" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>

2. The following XML document “monitors.xml” is an instance of “monitors.xsd”.


(a) Create XML schema “monitors.xsd” for the below XML document. Each monitor has a
unique model no. and up to 3 features.

(b) The value of the attribute can only be “LED”, “LCD” or “CRT”. Modify the schema to add
this constraint. (June 2010)(10 Marks)

(c) The smallest monitor is 10" while the largest monitor is 30". Modify the schema so that it can
validate the size range. (Create a new type and call it SizeType)

202
Middleware and Enterprise Integration Technologies

(d) The value of the element ratio must either be "4:3" or "16:9" or "16:10". Modify the schema
to add this constraint.

<?xml version="1.0"?>
<monitors xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="monitors.xsd">
<monitor type="LED" modelNo="m0010">
<size>24</size>
<ratio>16:9</ratio>
<launchDate>2009-09-10</launchDate>
<feature>100% sRGB color space</feature>
<feature>High contrast ratio</feature>
<price>7000</price>
</monitor>
<monitor type="LCD" modelNo="m0101">
<size>20</size>
<ratio>16:10</ratio>
<launchDate>2008-09-10</launchDate>
<feature>Tilt, Swivel, Pivot, height adjustment</feature>
<price>200.5</price>
</monitor>
<monitor type="CRT" modelNo="c0120">
<size>15</size>
<ratio>4:3</ratio>
<launchDate>2002-09-10</launchDate>
<price>500</price>
</monitor>
</monitors>

Solution:

(a)

<?xml version="1.0"?>

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<xsd:element name="monitors">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="monitor" maxOccurs="unbounded">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="size" type="xsd:integer"/>
<xsd:element name="ratio" type="xsd:string"/>
<xsd:element name="launchDate" type="xsd:date"/>
<xsd:element name="feature" type="xsd:string" minOccurs="0" maxOccurs="3"/>
<xsd:element name="price" type="xsd:decimal"/>
</xsd:sequence>
<xsd:attribute name="modelNo" use="required" type="xsd:ID"/>

203
Middleware and Enterprise Integration Technologies

<xsd:attribute name="type" use="required" type="xsd:string"/>


</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>

(b)

<xsd:simpleType name="MonitorType">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="LED"/>
<xsd:enumeration value="LCD"/>
<xsd:enumeration value="CRT"/>
</xsd:restriction>
</xsd:simpleType>

(c)
<xsd:simpleType name="SizeType">
<xsd:restriction base="xsd:integer">
<xsd:minInclusive value="10"/>
<xsd:maxInclusive value="30"/>
</xsd:restriction>
</xsd:simpleType>

(d)
<xsd:simpleType name="RatioType">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="4:3"/>
<xsd:enumeration value="16:9"/>
<xsd:enumeration value="16:10"/>
</xsd:restriction>
</xsd:simpleType>

10.1.3 XSLT Introduction

We can use a language called Extensible Styles Language XSL to format our XML documents. XSL
actually comes in two parts - a transformation language (XSLT) and a formatting language using
formatting objects.

XSLT, which stands for Extensible Styles Language Transformations, enables you to transform XML
documents into another form. For example, you can take your XML document, combine it with
HTML/CSS, and it will look completely different when viewing it in your user agent/browser.

XSLT Documents
An XSLT document is a valid XML document. An XSLT document consists of a number of
elements/tags/attributes. These can be XSL elements or elements from another language (such as HTML).
When you look at an XSLT document, you will notice that it is constructed like any other XML
document.

204
Middleware and Enterprise Integration Technologies

Processing a Transformation
A transformation can take place in one of three locations:
• On the server
• On the client (for example, your web browser)
• With a standalone program

XSLT Example

Here's an example of an XML document that has been transformed using XSLT.
Before...
We can take a raw XML file that looks something like this:

After...
...and apply XSLT so that it looks something like this:

205
Middleware and Enterprise Integration Technologies

You might have noticed that the "After" shot contains more than the raw XML file. It contains a heading
("Cool Tutorials") and some text ("Hey, check out these tutorials!"). This is one of the benefits of XSLT.
The following lessons explain XSLT in more detail, and demonstrate how to apply XSLT to an XML
document.

How to Do This?

Instead of linking to a CSS file, this time we link to a XSL file.

Step 1 (XML file): Create an XML file with the following content and save it.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>


<?xml-stylesheet type="text/xsl" href="tutorials.xsl"?>
<tutorials>
<tutorial>
<name>XML Tutorial</name>
<url>http://www.quackit.com/xml/tutorial</url>
</tutorial>
<tutorial>
<name>HTML Tutorial</name>
<url>http://www.quackit.com/html/tutorial</url>
</tutorial>
</tutorials>

Step 2 (XSL file): Create a file with the following content and save it as tutorials.xsl into the same
directory as the XML file.

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">

206
Middleware and Enterprise Integration Technologies

<html>
<head>
<title>XML XSL Example</title>
<style type="text/css">
body
{
margin:10px;
background-color:#ccff00;
font-family:verdana,helvetica,sans-serif;
}

.tutorial-name
{
display:block;
font-weight:bold;
}

.tutorial-url
{
display:block;
color:#636363;
font-size:small;
font-style:italic;
}
</style>
</head>
<body>
<h2>Cool Tutorials</h2>
<p>Hey, check out these tutorials!</p>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>

<xsl:template match="tutorial">
<span class="tutorial-name"><xsl:value-of select="name"/></span>
<span class="tutorial-url"><xsl:value-of select="url"/></span>
</xsl:template>

</xsl:stylesheet>

This XSL file contains XSL markup, HTML markup, and CSS.

XSLT Syntax

All XSLT documents need to be well-formed and valid XML documents, so you need to follow the same
syntax rules that apply to any other XML document.
As well as ensuring that your XSLT documents are valid XML, you need to ensure they are valid XSLT
documents. Here's what you need to remember when creating XSLT documents.

207
Middleware and Enterprise Integration Technologies

XML Version

XSL documents are also XML documents and so we should include the XML version in the document's
prolog. We should also set the standalone attribute to "no" as we now rely on an external resource (i.e. the
external XSL file).
<?xml version="1.0" standalone="no"?>

XSL Root Element

Then we open the root element - xsl:stylesheet. The root element needs to include the XSL version as well
as the XSL namespace (hence the xsl prefix and the xmlns... part).
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

XSL Namespace Prefix

All XSL elements in your XSLT document must include the XSL prefix.
Syntax:
<xsl:element_name>
Example:
<xsl:template match="/">
....
</xsl:template>

XSLT <template> Element

XSLT is all about being able to select one or more nodes from your XML document and transforming or
replacing its content with something else. A node could be any of the following: elements, attributes, text,
namespaces, processing-instructions, and comments.
The <xsl:template> element is what you use to select a node from your XML document and transform its
contents.
To select an element, you use the match attribute. To transform its contents, you simply place the new
content between the opening (<xsl:template>) and closing (</xsl:template>) tags.

Example

In this case, I'm selecting the root node (i.e. tutorials). By selecting this node, the template element tells
the XSLT processor how to transform the output. What I'm doing here is telling the processor to replace
the root node (i.e. the whole XML document) with what I've written between the <xsl:template> tags.
In this case, I have written the contents of an HTML document inside the <xsl:template> tags. When a
user views any XML document that uses this XSL document, they will simply see the line "New
content..." and the browser's title bar will read "My XSLT Example".
<xsl:template match="tutorials">
<html>
<head>
<title>My XSLT Example</title>
</head>
<body>
<p>New content...</p>
</body>
</html>

208
Middleware and Enterprise Integration Technologies

</xsl:template>

Selecting the Root Node

In the example above, we selected the "tutorials" node which happens to be the root node of our XML
document. Another way of selecting the root node is to use a forward slash in place of the node's name.
The following example results in the same output as the above example.
Example:
<xsl:template match="/">
<html>
<head>
<title>My XSLT Example</title>
</head>
<body>
<p>New content...</p>
</body>
</html>
</xsl:template>

Example:

Write a XSL file to convert the above XML to HTML code. The resulting HTML code should look like
the following figure when displayed in a browser. (Using <xsl:for-each> XSL element).

Solution:
<?xml version='1.0'?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>

209
Middleware and Enterprise Integration Technologies

<body>
<h2>Netbooks</h2>
<table border="1" cellpadding="10">
<tr bgcolor="#9acd32">
<th>Image</th>
<th>Model</th>
<th>Weight</th>
<th>Description</th>
</tr>
<xsl:for-each select="computer/netbook">
<tr>
<td><xsl:value-of select="image"/></td>
<td width="150"><xsl:value-of select="model"/></td>
<td width="70"><xsl:value-of select="weight"/></td>
<td width="400"><xsl:value-of select="description"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
10.1.4 XPath Introduction

XPath is a language that enables you to navigate, and find data, within your XML documents. Using
XPath, you can select one or more nodes in order to retrieve the data they contain.

XPath is used quite extensively with XSLT.

XPath Purpose

Since XPath is used for finding data within XML documents, this enables you to write applications that
make use of the data within an XML document.
In fact, in order to use XSLT (to transform the contents of your XML documents), you need to use XPath.

Other XML based languages such as XQuery and XPointer also rely on XPath expressions, so XPath
really does play an important role when writing XML applications.

Consider the following XML document:


<albums>
<rock>
<title>Machine Head</title>
<artist>Deep Purple</artist>
</rock>
<blues>
<title>Greens From The Garden</title>
<artist>Cory Harris</artist>
</blues>
<country>
<title>The Ranch</title>
<artist>The Ranch</artist>

210
Middleware and Enterprise Integration Technologies

</country>
</albums>

What are some of the things we might be interested in when writing an application? We might need to
extract the title of all albums for example. Or, we might only be interested in the artists. Or, we might
only be interested in albums and artists from a specific niche, such as rock.
XPath allows us to select only the nodes we're interested in.

XPath Location Path

XPath programming consists of writing expressions to select the node/s you need to work with. Often,
you're selecting the data within the nodes, but you could also be applying some programming logic in
order to modify the output of your XML document.
To select a node (or set of nodes) in XPath, you use a location path. A location path is used to specify the
exact path to the node you need to select. It's a bit like using the HTML <img src=""> tag to specify the
location of an image - only, XPath is more powerful.

Location Path Example

For example, here's a simple XPath expression to select the "title" node which is a child of the "rock"
node, which in turn is a child of the "albums" node:
albums/rock/title
The above expression could be applied against the following XML document:
<albums>
<rock>
<title>Machine Head</title>
<artist>Deep Purple</artist>
</rock>
<blues>
<title>Greens From The Garden</title>
<artist>Cory Harris</artist>
</blues>
<country>
<title>The Ranch</title>
<artist>The Ranch</artist>
</country>
</albums>

Another Example
If we wanted to select the artist instead, we would use this location path:
albums/rock/artist

The above expression would select the artist node instead:


<albums>
<rock>
<title>Machine Head</title>
<artist>Deep Purple</artist>
</rock>
<blues>
<title>Greens From The Garden</title>
<artist>Cory Harris</artist>

211
Middleware and Enterprise Integration Technologies

</blues>
<country>
<title>The Ranch</title>
<artist>The Ranch</artist>
</country>
</albums>

XPath Location Step

A location path consists of one or more location steps. The location steps are separated by either one
forward slash (/) or two forward slashes (//) depending on the node you're trying to select.
Absolute Location Path
Your location path can be absolute or relative. If your location path starts with the root node or a forward
slash (/) you are using an absolute location path - your location path begins from the root node.
Relative Location Path
If your location path begins with the name of a descendant, you're using a relative location path. This
node is referred to as the context node.

XPath Location Path - Absolute


As described earlier, a location path specifies the path through the XML document's hierarchy that you'd
like to work with.
Your location path can be absolute or relative. If your location path starts with the root node or a forward
slash (/) you are using an absolute location path - your location path begins from the root node.
If your location path begins with the name of a descendant, you're using a relative location path. This
node is referred to as the context node.

Example of an Absolute Location Path

Consider the following XML document:


<albums>
<rock>
<title>Machine Head</title>
<artist>Deep Purple</artist>
</rock>
<blues>
<title>Greens From The Garden</title>
<artist>Cory Harris</artist>
</blues>
<country>
<title>The Ranch</title>
<artist>The Ranch</artist>
</country>
</albums>

If we wanted to select the "title" node of all albums, we could use the following (absolute) location paths:

albums/rock/title
albums/blues/title
albums/country/title

The Result

212
Middleware and Enterprise Integration Technologies

Here are the nodes that are selected using the above location path.
<albums>
<rock>
<title>Machine Head</title>
<artist>Deep Purple</artist>
</rock>
<blues>
<title>Greens From The Garden</title>
<artist>Cory Harris</artist>
</blues>
<country>
<title>The Ranch</title>
<artist>The Ranch</artist>
</country>
</albums>

The Root Node

If we wanted to select the root node, we could use either the node's name or a forward slash. Both of these
options are absolute location paths and select the root node.

Option 1 - use the root node's name:


albums
Option 2 - use a forward slash:
/

XPath Location Path - Relative

A relative location path is one where the path starts from the node of your choosing - it doesn't need to
start from the root node. This can reduce the amount of code you need to write - especially if you need to
select many nodes that share the same name.

Example of a Relative Location Path

Consider the following XML document:


<albums>
<rock>
<title>Machine Head</title>
<artist>Deep Purple</artist>
</rock>
<blues>
<title>Greens From The Garden</title>
<artist>Cory Harris</artist>
</blues>
<country>
<title>The Ranch</title>
<artist>The Ranch</artist>
</country>
</albums>

213
Middleware and Enterprise Integration Technologies

If we wanted to select the "title" node of all albums, we could use the following (relative) location path:
title

The Result

This single line of code has exactly the same result as the example in the previous lesson. The only
difference is that, in the previous lesson, we needed 3 lines of code to provide the same result.
So to just to make sure you understand what this line of code is doing, it is selecting all title nodes within
our XML document. We don't need to provide the full path - just the name of the node we need to work
with. This makes our like easier and keeps our code nice and clean.

<albums>
<rock>
<title>Machine Head</title>
<artist>Deep Purple</artist>
</rock>
<blues>
<title>Greens From The Garden</title>
<artist>Cory Harris</artist>
</blues>
<country>
<title>The Ranch</title>
<artist>The Ranch</artist>
</country>
</albums>

Children

We can also select a node's children using relative location paths.

Example 1 - Selecting the two children of the "rock" node ("title" and "artist"). The context node is
"rock", because that's where our relative path starts:
rock/title
rock/artist

Example 2 - Using a wildcard to select all children of the "rock" node. This (single line of code) has the
same result as the above two lines of code. Further, if another node was added to the XML document
under the "rock" node, it would be automatically included using the wildcard:
rock/*

About the Wildcard

If you don't know what I mean by "wildcard", it is represented by the asterisk (*). The wildcard represents
any node that would be located where the wildcard is positioned. Therefore, using our example, it is
representing any node that comes under the "rock" node.
Wildcards don't have to appear at the end of a location path - they can also appear in the middle of a
location path. We aren't limited to just one either - we could use as many as we like within a location
path.

XPath Attributes

214
Middleware and Enterprise Integration Technologies

To select an attribute using XPath, you prefix the attribute's name with a @ symbol.

Example of Selecting an Attribute


Consider the following XML document. Note that the "artist" node now has an attribute called "status":
<albums>
<rock>
<title>Machine Head</title>
<artist status="active">Deep Purple</artist>
</rock>
<blues>
<title>Greens From The Garden</title>
<artist status="active">Cory Harris</artist>
</blues>
<country>
<title>The Ranch</title>
<artist status="disbanded">The Ranch</artist>
</country>
</albums>

If we wanted to select the "status" attribute of the "artist" node under the "rock" node, we could use the
following expression:

albums/rock/artist/@status
Example

1. Give the XPath expressions to select the information requested in part (a) to (e) from the XML
document class1.xml.
a. All the students’ name.
b. The name of the students with conduct over 70.
c. The average conduct of all the students.
d. The name of the last student.
e. The conduct of "mary".

215
Middleware and Enterprise Integration Technologies

Solution:
a. /class/student/name
b. /class/student[conduct>70]/name
c. avg(/class/student/conduct)
d. /class/student[last()]
e. /class/student[name="mary"]/conduct

2. Give the XPath expressions to select the information requested in part (a) to (k) from the
XML document class3.xml.

a. The conduct score of "john".

b. The average conduct of all the students.

c. The name of the student(s) who score more than 50 in "English".

d. The highest mark scored in the module "Chinese".

e. The average module score of "mary".

f. The name of the student(s) who have score in "Computer"

g. The name of the student(s) who have average module score > 50.

h. The name of the student(s) who have average score > 50 (including conduct).

i. The name of the student(s) who got the highest conduct score.

j. The name of the module that "Peter" scored highest.

k. The name of the student(s) who have at least one module scored higher than his conduct.

216
Middleware and Enterprise Integration Technologies

Solution:
a. /class/student[@name="john"]/conduct
b. avg(/class/student/conduct)
c. /class/student/module[name="English" and score>50]/../@name
d. max(/class/student/module[name="Chinese"]/score)
e. avg(/class/student[@name="mary"]/module/score)
f. /class/student/module[name="Computer"]/../@name
g. /class/student[avg(module/score)>50]/@name
h. /class/student[avg(module/score|conduct)>50]/@name
i. /class/student[conduct=max(/class/student/conduct)]/@name
j. /class/student[@name="peter"]/module[score=max(../module/score)]/name

217
Middleware and Enterprise Integration Technologies

k. /class/student[max(module/score)>conduct]/@name

10.2 Web Services and SOA (May 2010) (10 Marks)

A Web service is a method of communication between two electronic devices over a network. A
Web service is a software system designed to support interoperable machine-to-machine
interaction over a network. It has an interface described in a machine-processable format
(specifically Web Services Description Language WSDL). Other systems interact with the Web
service in a manner prescribed by its description using SOAP messages, typically conveyed using
HTTP with an XML serialization in conjunction with other Web-related standards. The following
are the characteristics of Web Services-
•Web services are application components
•Web services communicate using open protocols
•Web services are self-contained and self-describing
•Web services can be discovered using UDDI
•Web services can be used by other applications
•XML is the basis for Web services

Fig. 10.1 Web Service Communication

We can identify two major classes of Web services, REST-


compliant Web services, in which the primary purpose of
the service is to manipulate XML representations of Web
resources using a uniform set of "stateless" operations; and arbitrary Web services, in which the service
may expose an arbitrary set of operations. Web Services can be categorized as Simple and Complex Web
Services.
1. Simple Web Service: It provides a request/response type of functionality and does not support
transactions. It has the following characteristics:
1. Point to point

218
Middleware and Enterprise Integration Technologies

2. RPC and messaging based: It involves calling of a remote procedure and uses XML
messaging.
3. Non-transactional: It involves a simple request followed by a response to the client.
4. Web security
2. Complex Web Service: It provides the framework for business-to-business collaborations and
business process management. It acquires the following characteristics:
1. Multi-party: It involves multiple business partners.
2. Collaboration and workflow
3. Transactional: All services run under transactional control spanning servers.
4. Sophisticated security: It uses digital signatures for authentication and access control.
5. Conversation state: It maintains a conversation state with the client, obtains the context,
and shares it with collaborators.

• Service Oriented Architecture:

Fig. 10.2 SOA

Web services can also be used to implement architecture according to service-oriented architecture (SOA)
concepts, where the basic unit of communication is a message, rather than an operation. This is often
referred to as "message-oriented" services. SOA Web services are supported by most major software
vendors and industry analysts. Unlike RPC Web services, loose coupling is more likely, because the focus
is on the "contract" that WSDL provides, rather than the underlying implementation details. Middleware
analysts use enterprise service buses that combine message-oriented processing and Web services to
create an event-driven SOA. One example of an open-source ESB is Mule, another one is Open ESB.

10.3 WSDL (May 2010, Dec 2010) (10 Marks)

219
Middleware and Enterprise Integration Technologies

WSDL is an XML-based language for describing Web services and how to access them.

• WSDL stands for Web Services Description Language


• WSDL is written in XML
• WSDL is an XML document
• WSDL is used to describe Web services
• WSDL is also used to locate Web services
• WSDL is a W3C recommendation
• A WSDL document describes a web service using these major elements:

Element Defines
<types> The data types used by the web service
<message> The messages used by the web service
<portType> The operations performed by the web service
<binding> The communication protocols used by the web service

Fig. 10.3 WSDL Document Structure

The main structure of a WSDL document looks like this:

<definitions>
<types>
definition of types........

220
Middleware and Enterprise Integration Technologies

</types>
<message>
definition of a message....
</message>
<portType>
definition of a port.......
</portType>
<binding>
definition of a binding....
</binding>
</definitions>

A WSDL document can also contain other elements, like extension elements, and a service element that
makes it possible to group together the definitions of several web services in one single WSDL
document.

WSDL Ports

The <portType> element is the most important WSDL element.

It describes a web service, the operations that can be performed, and the messages that are involved.

The <portType> element can be compared to a function library (or a module, or a class) in a traditional
programming language.

WSDL Messages

The <message> element defines the data elements of an operation.

Each message can consist of one or more parts. The parts can be compared to the parameters of a
function call in a traditional programming language.

WSDL Types

The <types> element defines the data types that are used by the web service.

For maximum platform neutrality, WSDL uses XML Schema syntax to define data types.

WSDL Bindings

The <binding> element defines the message format and protocol details for each port.

WSDL Example

This is a simplified fraction of a WSDL document:

<message name="getTermRequest">
<part name="term" type="xs:string"/>

221
Middleware and Enterprise Integration Technologies

</message>

<message name="getTermResponse">
<part name="value" type="xs:string"/>
</message>

<portType name="glossaryTerms">
<operation name="getTerm">
<input message="getTermRequest"/>
<output message="getTermResponse"/>
</operation>
</portType>

In this example the <portType> element defines "glossaryTerms" as the name of a port, and "getTerm"
as the name of an operation.

The "getTerm" operation has an input message called "getTermRequest" and an output message called
"getTermResponse".

The <message> elements define the parts of each message and the associated data types.

Compared to traditional programming, glossaryTerms is a function library, "getTerm" is a function with


"getTermRequest" as the input parameter, and getTermResponse as the return parameter.

10.4 SOAP (May 2010, Dec 2010) (10 Marks)

• SOAP stands for Simple Object Access Protocol


• SOAP is a communication protocol
• SOAP is for communication between applications
• SOAP is a format for sending messages
• SOAP communicates via Internet
• SOAP is platform independent
• SOAP is language independent
• SOAP is based on XML
• SOAP is simple and extensible
• SOAP allows you to get around firewalls
• SOAP is a W3C recommendation

Why SOAP?

It is important for application development to allow Internet communication between programs.

Today's applications communicate using Remote Procedure Calls (RPC) between objects like DCOM and
CORBA, but HTTP was not designed for this. RPC represents a compatibility and security problem;
firewalls and proxy servers will normally block this kind of traffic.

222
Middleware and Enterprise Integration Technologies

A better way to communicate between applications is over HTTP, because HTTP is supported by all
Internet browsers and servers. SOAP was created to accomplish this.

SOAP provides a way to communicate between applications running on different operating systems,
with different technologies and programming languages.

SOAP Building Blocks

A SOAP message is an ordinary XML document containing the following elements:

• An Envelope element that identifies the XML document as a SOAP message


• A Header element that contains header information
• A Body element that contains call and response information
• A Fault element containing errors and status information

Syntax Rules

Here are some important syntax rules:

• A SOAP message MUST be encoded using XML


• A SOAP message MUST use the SOAP Envelope namespace
• A SOAP message MUST use the SOAP Encoding namespace
• A SOAP message must NOT contain a DTD reference
• A SOAP message must NOT contain XML Processing Instructions

Skeleton SOAP Message

<?xml version="1.0"?>

<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Header>
...
</soap:Header>
<soap:Body>
...
<soap:Fault>
...
</soap:Fault>
</soap:Body>
</soap:Envelope>

The SOAP Envelope Element

223
Middleware and Enterprise Integration Technologies

The required SOAP Envelope element is the root element of a SOAP message. This element defines the
XML document as a SOAP message.

Example
<?xml version="1.0"?>

<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
...
Message information goes here

...
</soap:Envelope>

The xmlns:soap Namespace

Notice the xmlns:soap namespace in the example above. It should always have the value of:
"http://www.w3.org/2001/12/soap-envelope".

The namespace defines the Envelope as a SOAP Envelope.

If a different namespace is used, the application generates an error and discards the message.

The encodingStyle Attribute

The encodingStyle attribute is used to define the data types used in the document. This attribute may
appear on any SOAP element, and applies to the element's contents and all child elements.

A SOAP message has no default encoding.

Syntax
soap:encodingStyle="URI"

Example
<?xml version="1.0"?>

<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
Message information goes here…

</soap:Envelope>

10.5 UDDI (Dec 2010) (10 Marks)

224
Middleware and Enterprise Integration Technologies

Universal Description, Discovery and Integration (UDDI) is a directory service where businesses can
register and search for Web services.

UDDI is a platform-independent framework for describing services, discovering businesses, and


integrating business services by using the Internet.
• UDDI stands for Universal Description, Discovery and Integration
• UDDI is a directory for storing information about web services
• UDDI is a directory of web service interfaces described by WSDL
• UDDI communicates via SOAP
• UDDI is built into the Microsoft .NET platform
• UDDI uses World Wide Web Consortium (W3C) and Internet Engineering Task Force (IETF)
Internet standards such as XML, HTTP, and DNS protocols.
• UDDI uses WSDL to describe interfaces to web services
• Additionally, cross platform programming features are addressed by adopting SOAP, known as
XML Protocol messaging specifications found at the W3C Web site.

Any industry or businesses of all sizes can benefit from UDDI.

Before UDDI, there was no Internet standard for businesses to reach their customers and partners with
information about their products and services. Nor was there a method of how to integrate into each
other's systems and processes.

Problems the UDDI specification can help to solve:


• Making it possible to discover the right business from the millions currently online
• Defining how to enable commerce once the preferred business is discovered
• Reaching new customers and increasing access to current customers
• Expanding offerings and extending market reach
• Solving customer-driven need to remove barriers to allow for rapid participation in the global
Internet economy
• Describing services and business processes programmatically in a single, open, and secure
environment
• UDDI is a cross-industry effort driven by all major platform and software providers like Dell,
Fujitsu, HP, Hitachi, IBM, Intel, Microsoft, Oracle, SAP, and Sun, as well as a large community
of marketplace operators, and e-business leaders.
• Over 220 companies are members of the UDDI community.

A UDDI business registration consists of three components:


• White Pages — address, contact, and known identifiers;
• Yellow Pages — industrial categorizations based on standard taxonomies;
• Green Pages — technical information about services exposed by the business.

White Pages

White pages give information about the business supplying the service. This includes the name of the
business and a description of the business - potentially in multiple languages. Using this information, it is
possible to find a service about which some information is already known (for example, locating a service
based on the provider's name).

Contact information for the business is also provided - for example the businesses address and phone
number; and other information such as the Dun & Bradstreet Universal Numbering System number.

225
Middleware and Enterprise Integration Technologies

Yellow Pages

Yellow pages provide a classification of the service or business, based on standard taxonomies. These
include the Standard Industrial Classification (SIC), the North American Industry Classification System
(NAICS), or the United Nations Standard Products and Services Code (UNSPSC) .

Because a single business may provide a number of services, there may be several Yellow Pages (each
describing a service) associated with one White Page (giving general information about the business).

Green Pages

Green pages are used to describe how to access a Web Service, with information on the service bindings.
Some of the information is related to the Web Service - such as the address of the service and the
parameters, and references to specifications of interfaces. Other information is not related directly to the
Web Service - this includes e-mail, FTP, CORBA and telephone details for the service. Because a Web
Service may have multiple bindings (as defined in its WSDL description), a service may have multiple
Green Pages, as each binding will need to be accessed differently.

10.6 Service Oriented Enterprise (SOE)

Services Paradigm Adoption (SPA)


Services orientation presents an ideal vision of a world in which resources are cleanly partitioned and
consistently represented in terms of services. Therefore the Services Paradigm has to be adopted by the
Enterprise to structure the Enterprise in terms of Services. So the Enterprise aspect areas of Business,
Information, Information-Systems and the Technology Infrastructure have to be decomposed in terms of
functional Services. Doing that at a consistent and consequent matter will deliver loosely coupled
functional services that can be outsourced or insourced or brought together in so called shared services
centers.

226
Middleware and Enterprise Integration Technologies

Services Oriented Enterprise (SOE)


A service-oriented enterprise is really connecting business processes in a much more horizontal fashion.
It's having an Enterprise infrastructure that provides an enterprise architecture and security foundation to
be able to run these services consistently across your enterprise.
Service Oriented Architecture (SOA)
Service-orientation presents an ideal vision of a world in which resources are cleanly partitioned and
consistently represented. When applied to IT architecture, service-orientation establishes a universal
model in which automation logic and even business logic conform to this vision. This model applies
equally to a task, a solution, an enterprise, a community, and beyond.

Services Oriented Computing (SOC)


There has been an increase in interest recently within the service oriented community towards "Service
Oriented'' Computing. Services are often seen as a natural progression from component based software
development, and as a means to integrate different component development frameworks. A service in this
context may be defined as a behavior that is provided by a component for use by any other component
based on a network-addressable interface contract (generally identifying some capability provided by the
service). A service stresses interoperability and may be dynamically discovered and used.

10.6 BPEL4WS (Dec 2010) (10 Marks)

• BPEL4WS stands for Business Process Execution Language for Web Services.
• It is an XML-based language designed to enable task-sharing for a distributed computing or grid
computing environment - even across multiple organizations - using a combination of Web
services.
• Using BPEL4WS, a programmer formally describes a business process that will take place across
the Web in such a way that any cooperating entity can perform one or more steps in the process
the same way.

227
Middleware and Enterprise Integration Technologies

• BPEL4WS provides a language for the formal specification of business processes and business
interaction protocols. By doing so, it extends the Web Services interaction model and enables it to
support business transactions.
• BPEL4WS defines an interoperable integration model that should facilitate the expansion of
automated process integration in both the intra-corporate and the business-to-business spaces.
Business processes can be described in two ways:
• Orchestration: Executable business processes model actual behavior of a participant in a
business interaction.
• Choreography: Business protocols, in contrast, use process descriptions that specify the
mutually visible message exchange behavior of each of the parties involved in the protocol,
without revealing their internal behavior. The process descriptions for business protocols are
called abstract processes.
BPEL is used to model the behavior of both executable and abstract processes. The scope includes:
• Sequencing of process activities, especially Web Service interactions
• Correlation of messages and process instances
• Recovery behavior in case of failures and exceptional conditions
• Bilateral Web Service based relationships between process roles
A BPEL process consists of steps. Each step is called an activity. BPEL supports primitive and structure
activities. Primitive activities represent basic constructs and are used for common tasks, such as those
listed below:
• Invoking other web services, using <invoke>
• Waiting for the client to invoke the business process through sending a message, using <receive>
(receiving a request)
• Generating a response for synchronous operations, using <reply>
• Manipulating data variables, using <assign>
• Indicating faults and exceptions, using <throw>
• Waiting for some time, using <wait>
• Terminating the entire process, using <terminate>, etc.
Each BPEL process will also declare variables, using <variable>, and define partner links, using
<partnerLink>.
A BPEL process can be synchronous or asynchronous. A synchronous BPEL process blocks the client
(the one which is using the process) until the process finishes and returns a result to the client. An
asynchronous process does not block the client. Rather it uses a callback to return the result (if any).
Usually we use asynchronous processes for longer-lasting processes and synchronous for processes that
return a result in a relatively short time. If a BPEL process uses asynchronous web services, the process
itself is usually also asynchronous (although this is not necessary).
For its clients a BPEL process looks like any other web service. When we define a BPEL process, we
actually define a new web service that is a composition of existing services. The interface of the new
BPEL composite web service uses a set of port types, through which it provides operations like any other
web service. To invoke a business process described in BPEL, we have to invoke the resulting composite
web service. The figure below shows a schematic view of a BPEL process:

228
Middleware and Enterprise Integration Technologies

Fig. 10.4 BPEL4WS

BPEL calls the links to all parties it interacts with partner links. Partner links can be links to web services
that are invoked by the BPEL process. Partner links can also be links to clients which invoke the BPEL
process. Each BPEL process has at least one client partner link, because there has to be a client that
invokes the BPEL process.

-----------------
University Questions

1. Explain the role of XML in Web Services. (Dec 2010)


2. The following XML document “monitors.xml” is an instance of “monitors.xsd”.
(a) Create XML schema “monitors.xsd” for the below XML document. Each monitor has a
unique model no. and up to 3 features.

(b) The value of the attribute can only be “LED”, “LCD” or “CRT”. Modify the schema to add
this constraint. (May 2010)(10 Marks)

<?xml version="1.0"?>
<monitors xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="monitors.xsd">
<monitor type="LED" modelNo="m0010">
<size>24</size>
<ratio>16:9</ratio>
<launchDate>2009-09-10</launchDate>
<feature>100% sRGB color space</feature>
<feature>High contrast ratio</feature>
<price>7000</price>
</monitor>
<monitor type="LCD" modelNo="m0101">
<size>20</size>
<ratio>16:10</ratio>
<launchDate>2008-09-10</launchDate>

229
Middleware and Enterprise Integration Technologies

<feature>Tilt, Swivel, Pivot, height adjustment</feature>


<price>200.5</price>
</monitor>
<monitor type="CRT" modelNo="c0120">
<size>15</size>
<ratio>4:3</ratio>
<launchDate>2002-09-10</launchDate>
<price>500</price>
</monitor>
</monitors>

3. What is a Web Service? Explain different types of Web Services. (May 2010)
4. Explain the structure of WSDL document and its constituent elements with neat diagram.
(May 2010)
5. Describe the structure of WSDL file. State the importance of UDDI. (Dec 2010)
6. Describe SOAP Messages. How are they processed? (May 2010)
7. Write short note on: Simple Object Access Protocol. (Dec 2010)
8. Write short note on: BPEL for Web Services. (Dec 2010)

230

You might also like