0% found this document useful (0 votes)
25 views260 pages

DMC1936

This document provides instructions for setting up a home wireless network in 4 steps: 1. Choose wireless equipment like a broadband modem, wireless router, and wireless network adapters. 2. Connect the wireless router to the modem and turn the devices on. 3. Temporarily connect a computer to the router using an ethernet cable and access the router's configuration page in a web browser. 4. Configure the wireless settings on the router like the network name (SSID) and security settings and then disconnect the ethernet cable to use the network wirelessly.
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)
25 views260 pages

DMC1936

This document provides instructions for setting up a home wireless network in 4 steps: 1. Choose wireless equipment like a broadband modem, wireless router, and wireless network adapters. 2. Connect the wireless router to the modem and turn the devices on. 3. Temporarily connect a computer to the router using an ethernet cable and access the router's configuration page in a web browser. 4. Configure the wireless settings on the router like the network name (SSID) and security settings and then disconnect the ethernet cable to use the network wirelessly.
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/ 260

MCA

(DISTANCE MODE)

DMC 1936

Web Programming Lab

III Semester
LAB MANUAL

Centre for Distance Education


Anna University Chennai
Chennai – 600 025
Author

Mr.K.P.Mani Anand
Lecturer
Ramanujan Computing Centre
Anna University
Chennai – 600 025

Reviewer

Dr.S.Abirami
Lecturer
Department of Information Science and Technology
Anna University
Chennai – 600 025

Copyrights Reserved
(For Private Circulation Only)

-2-
-3-
-4-
DMC 1936 WEB PROGRAMMING LAB

1. Studying internet connection procedures


2. Sending and receiving mails from one or more email clients
3. Video Conferencing demonstration
4. Downloading and installing softwares (Example: Java) and setting up path and class
path
5. Using FTP
6. Creation of web site with forms, frames, links, tables etc with any web page editors
and using images and audio files as part of web pages
7. Writing Java programs by making use of class, interface, package, etc for the
following
# Different types of inheritance study
# Uses of ‘this’ keyword
# Polymorphism
# Creation of user specific packages
# Creation of jar files and using them
# User specific exception handling
8. Writing window based GUI applications using frames and applets such as Calculator
application, Fahrenheit to Centigrade conversion etc
9. Application of threads examples
10. Reading and writing text files
11. Reading image files and manipulating them with image related classes and methods
12. writing an RMI application to access a remote method
13. Writing a Servlet program with database connectivity for a web based application
such as students result status checking, PNR number enquiry etc
14. Creation and usage of Java bean

-5-
-6-
TABLE OF CONTENTS
Chapter. No. Title Page Number

1 STUDYING INTERNET CONNECTION PROCEDURES 7


2 13
SENDING AND RECEIVING MAILS FROM ONE OR MORE EMAIL
CLIENT

3 VIDEO CONFERENCING DEMONSTRATION 21


4 DOWNLOADING AND INSTALLING SOFTWARES (EXAMPLE: JAVA) 33
AND SETTING UP PATH AND CLASS PATH
5 Using FTP 43
6 CREATION OF WEB SITE WITH FORMS, FRAMES, LINKS, TABLES etc 49
WITH ANY WEB PAGE EDITORS AND USING IMAGE AND AUDIO FILES
AS PART OF WEB PAGE
7 WRITING JAVA PROGRAMS BY MAKING USE OF CLASS, INTERFACE, 75
PACKAGE, ETC
8 WRITING WINDOWS BASED GUI 97
APPLICATION USING FRAMES AND APPLETS
SUCH AS CALCULATOR APPLICATION, FAHRENHEIT TO CENTOGRADE
CONVERSION
9 APPLICATION OF THREADS EXAMPLES 120
10 READING AND WRITING TEXT FILES 162
11 READING IMAGE FILES AND MANIPULATING THEM WITH IMAGE 171
RELATED
12 WRITING AN RMI APPLICATION TO ACCESS A REMOTE METHOD 178
13 WRITING A SERVLET PROGRAM WITH DATABASE CONNECTIVITY 212
FOR A WEB BASED APPLICATION SUCH AS STUDENT RESULT
STATUS CHECKING, PNR NUMBER ENQUIRY
14 CREATING AND USAGE OF JAVA BEAN 229

-7-
-8-
Chapter 1

STUDYING INTERNET CONNECTION PROCEDURES


Objectives

ƒ Understanding meaning of wireless network


ƒ Wireless equipment Selection
ƒ Wireless router Connection
ƒ Configure your wireless router
ƒ Connect your computers to the wireless network

Wireless network is a network set up by using radio signal frequency to communicate


among computers and other network devices. Sometimes it’s also referred to as WiFi
network or WLAN.

4 steps to set up your home wireless network


You can use a wireless network to share Internet access, files, printers, and more. Or you
can use it to surf the Web while you're sitting on your couch or in your yard. Plus, it's easier
to install than you think.

Note: For Windows Vista users, we recommend installing Windows Vista Service Pack 1
before setting up your wireless network. For Windows XP users, we recommend installing
Windows XP Service Pack 3. Although the service pack is not required for wireless
networking, it does make things much easier and helps protect you against hackers, worms,
and other Internet intruders.

-9-
STEP 1: CHOOSE YOUR WIRELESS EQUIPMENT

The first step is to make sure that you have the equipment you need. As you're
looking for products in stores or on the Internet, you might notice that you can choose
equipment that supports three different wireless networking technologies: 802.11a, 802.11b,
and 802.11g. We recommend 802.11g, because it offers excellent performance and is
compatible with almost everything.

SHOPPING LIST

• Broadband Internet connection


• Wireless router
• A computer with built-in wireless networking support or a wireless network adapter

A WIRELESS ROUTER

The router converts the signals coming across your Internet connection into a wireless
broadcast, sort of like a cordless phone base station. Be sure to get a wireless router, and not
a wireless access point.

A WIRELESS NETWORK ADAPTER

Network adapters wirelessly connect your computer to your wireless router. If you
have a newer computer you may already have wireless capabilities built in. If this is the case,
then you will not need a wireless network adapter. If you need to purchase an adapter for a
desktop computer, buy a USB wireless network adapter. If you have a laptop, buy a PC card-
based network adapter. Make sure that you have one adapter for every computer on your
network.

-10-
STEP 2: CONNECT YOUR WIRELESS ROUTER

Since you'll be temporarily disconnected from the Internet, print these instructions
before you go any further.

First, locate your cable modem or DSL modem and unplug it to turn it off.

Next, connect your wireless router to your modem. Your modem should stay
connected directly to the Internet. Later, after you've hooked everything up, your computer
will wirelessly connect to your router, and the router will send communications through your
modem to the Internet.

Next, connect your router to your modem:

Note: The instructions below apply to a Linksys wireless router. The ports on your router
may be labeled differently, and the images may look different on your router. Check the
documentation that came with your equipment for additional assistance.

ƒ If you currently have your computer connected directly to your modem: Unplug
the network cable from the back of your computer, and plug it into the port labeled
Internet, WAN, or WLAN on the back of your router.

• If you do not currently have a computer connected to the Internet: Plug one end
of a network cable (included with your router) into your modem, and plug the other
end of the network cable into the Internet, WAN, or WLAN port on your wireless
router.

-11-
• If you currently have your computer connected to a router: Unplug the network
cable connected to the Internet, WAN, or WLAN port from your current router, and
plug this end of the cable into the Internet, WAN, or WLAN port on your wireless
router. Then, unplug any other network cables, and plug them into the available ports
on your wireless router. You no longer need your original router, because your new
wireless router replaces it.

Next, plug in and turn on your cable or DSL modem. Wait a few minutes to give it
time to connect to the Internet, and then plug in and turn on your wireless router. After a
minute, the Internet, WAN, or WLAN light on your wireless router should light up,
indicating that it has successfully connected to your modem.

STEP 3: CONFIGURE YOUR WIRELESS ROUTER

-12-
Using the network cable that came with your wireless router, you should temporarily
connect your computer to one of the open network ports on your wireless router (any port
that isn't labeled Internet, WAN, or WLAN). If you need to, turn your computer on. It should
automatically connect to your router.

Next, open Internet Explorer and type in the address to configure your router.

You might be prompted for a password. The address and password you use will vary
depending on what type of router you have, so refer to the instructions included with your
router.
As a quick reference, this table shows the default addresses, usernames, and
passwords for some common router manufacturers.

Router Address Username Password


3Com http://192.168.1.1 admin Admin
D-Link http://192.168.0.1 admin
Linksys http://192.168.1.1 admin Admin
Microsoft Broadband http://192.168.2.1 admin Admin
Netgear http://192.168.0.1 admin Password

Internet Explorer will show your router's configuration page. Most of the default settings
should be fine, but you should configure three things:

1. Your wireless network name, known as the SSID. This name identifies your
network. You should choose something unique that none of your neighbors will be
using.

2. Wireless encryption (WEP) or Wi-Fi Protected Access (WPA), which help


protect your wireless network. For most routers, you will provide a passphrase that
your router uses to generate several keys. Make sure your passphrase is unique and
long (you don't need to memorize it).

-13-
3. Your administrative password, which controls your wireless network. Just like
any other password, it should not be a word that you can find in the dictionary, and it
should be a combination of letters, numbers, and symbols. Be sure you can remember
this password, because you'll need it if you ever have to change your router's settings.

The exact steps you follow to configure these settings will vary depending on the type of
router you have. After each configuration setting, be sure to click Save Settings, Apply, or
OK to save your changes.

Now, you should disconnect the network cable from your computer.

STEP 4: CONNECT YOUR COMPUTERS TO THE WIRELESS


NETWORK

ƒ Windows 7
ƒ Windows Vista

If your computer does not have wireless network support built in, plug your network
adapter into your USB port, and place the antenna on top of your computer (in the case of a
desktop computer), or insert the network adapter into an empty PC card slot (in the case of a
laptop). Windows will automatically detect the new adapter, and may prompt you to insert
the CD that came with your adapter. The on-screen instructions will guide you through the
configuration process.

REVIEW QUESTIONS:

1. What are the steps required to establish the wireless network?


2. What are the configuration steps in wireless router?
3. List out default addresses, usernames, and passwords for some common router
manufacturers?
4. Explain how to setup wireless router with internet?

-14-
Chapter 2
SENDING AND RECEIVING MAILS FROM ONE OR MORE
EMAIL CLIENT

Objectives

ƒ Process of POP and activate POP in Gmail.


ƒ Steps involved in outlook express
ƒ ISP in POP ans SMTP mail servers

GENERAL INTRODUCTION FOR SENDING AND RECEIVING


EMAILS

This section explains how to compose, forward, and reply-to emails. It also covers a
number of options for customising some settings when emails are sent.

ƒ Compose and send a New Email


ƒ Sending Email
ƒ Replying to an Email
ƒ Forwarding an Email
ƒ Saving a Draft Email

COMPOSE AND SEND A NEW EMAIL

By default Outlook uses Word as the email editor when you create each email. Using
Word for creating emails provides all the functionality of Word including grammar and spell
check as you type. You can change font, colours, use bold and italic and even insert pictures
into your emails.Click on the new button from the Standard Toolbar. By default it will be set
to New Mail Message. To see what each button does on the Standard Toolbar you can place
your mouse cursor over each button and a quick description will pop up.

-15-
You will see the new Mail Message window open. The steps in order to create and send an
email are shown below.

1. This is the To field type the recipient's email address here.


2. This is the Carbon copy field which allows you to send a copy of this email to other
people.
3. Place your email subject here.
4. This is the message body. Type your message here.
5. When you've finished your email click on the Send button.

SENDING EMAIL

Once you have written your email, and are ready to send it you simply click on the
Send button. By default Outlook will save a copy of all emails you send in a folder called
Sent Items.

-16-
REPLYING TO AN EMAIL

To reply to an email you can either just highlight the email in your INBOX and then
click on either Reply or Reply to All (below) depending on whether you want to send a reply
only to the sender of the email or to the sender and all other recipients of the original email.

You can also reply to an email by choosing the Reply or Reply to All buttons when
you have opened the email in a separate window.

When you select Reply, a new window will open similar to if you were creating a
brand new email, in which the sender's details and the original content of the received email
will already be included by default.

FORWARDING AN EMAIL

To forward an email, highlight it in your INBOX and click on the Forward button
(below) in the row of icons across the top of the screen. This will then open a new window
similar to when you are creating a new email but it will include the content of the email you
are forwarding. You can now enter the address of the person you want to forward the email
to in the To box and click on Send.

SAVING A DRAFT EMAIL

To save a message that you are currently composing you have two options.
To save it to the Drafts folder within Outlook, click on the Disk icon (Save). You can now
locate this draft email by going into the Drafts Folder within Outlook. You can also save a
copy of the email to a place on your computer by going to File | Save as, navigating to where
you want to save it, give the draft a file name and then click on Save.

-17-
How do I resend a message in the sent folder?
To resend a message that you have sent previously go to your Sent Items folder.

Highlight the email that you want to send and click on the Forward button on the
main toolbar.This will open a new window similar to creating a new email, only the content
of the email you have selected will already be present in the email. Enter the intended
recipient's email address in the To box or alternatively click the To button and select an
address from your Contacts or the Global Address List.

VIA OUTLOOK EXPRESS

If you use Gmail, Google’s Web-based email service, it is possible for you to
download and read your messages offline (rather than using your Web browser to visit
www.gmail.com), via POP3 (post office protocol version 3).POP3 is a technology that lets
your computer connect to and communicate with a mail server (e.g., Cox). Your email client
(e.g., Outlook Express) may then download messages from the external mail server to your
computer’s hard drive, where the messages appear in your email client’s inbox. Because the
messages are stored on your computer rather than on a distant mail server, you can read,
compose, and edit messages even when you are not logged in to your Gmail account or when
you do not have an active Internet connection. You only need to connect to the Internet when
you are ready to send or receive messages. To use POP3 with Gmail, you will need a

-18-
compatible email client. Currently, Google supports Outlook Express, Outlook, Entourage,
Eudora, and Eudora for Macs, Netscape Mail, Apple Mail, Mozilla, and Thunderbird.

You can retrieve your Gmail messages with a client that supports POP, e.g., Outlook
Express
.
TO ENABLE POP IN GMAIL:

1. Sign in to Gmail (www.gmail.com) using your Username and password.


2. Click Settings at the top of any Gmail page.
3. Click Forwarding and POP/IMAP.
4. In the Forwarding field, select Disable forwarding.
5. In the Pop Download field, select Enable POP for all mail or Enable POP for mail
that arrives from now on. Choose the action you'd like your Gmail messages to take
after they are accessed with POP.
6. Click on Save Changes.
7. Close your Gmail windows.

To set up your Outlook Express client to work with Gmail:

1. Open Outlook Express.


2. Click the Tools menu, and select Accounts.
3. Click Add, and then click Mail.
4. Enter your name in the Display name: field, and click Next.
5. Enter your full Gmail email address ([email protected]) in the Email address:
field, and click Next.
6. Enter pop.gmail.com in the Incoming mail (POP3, IMAP or HTTP) server: field.
7. Enter smtp.gmail.com in the Outgoing mail (SMTP) server: field.
8. Click Next.
9. Enter your full email address (including '@gmail.com') in the Account name: field.
Enter your email password in the Password: field, and click Next.

-19-
10. Click Finish.
11. Highlight pop.gmail.com under Account, and click Properties.
12. Click the Advanced tab.
13. Fill in the following information:

ƒ Under Outgoing Mail (SMTP). Simple Mail Transfer Protocol, check the box
next to this server requires a secure connection (SSL).
ƒ Enter 465 in the Outgoing mail (SMTP): field.
ƒ Under Incoming mail (POP3), check the box next to This server requires a
secure connection (SSL). The port will automatically change to 995.
ƒ Click Apply.
15. Return to the Servers tab, and check the box next to My server requires
authentication.
15. Click OK.
16. Click Close.

You're done configuring your Outlook Express client to send and retrieve Gmail
messages.

POP3 SMTP Mail Servers available for popular Internet Service Providers:

ƒ Ameritech (SBC Yahoo!) incoming mail server: pop.ameritech.yahoo.com


ƒ Ameritech (SBC Yahoo!) outgoing mail server: mailhost.det.ameritech.net
ƒ AT&T WorldNet incoming mail server: postoffice.worldnet.att.net
ƒ AT&T WorldNet outgoing mail server: mailhost.worldnet.att.net
ƒ AOL outgoing mail server: smtp.aol.com
ƒ BlueLight incoming mail server: mail.bluelight.net
ƒ BlueLight outgoing mail server: smtp.bluelight.net
ƒ Charter incoming mail server: pop.charter.net
ƒ Charter outgoing mail server: smtp.charter.net
ƒ Comcast incoming mail server: mail.comcast.net
ƒ Compaq.net outgoing mail server: smtp.compaq.net

-20-
ƒ Compuserve incoming mail server: pop.compuserve.com
ƒ Compuserve outgoing mail server: smtp.compuserve.com
ƒ Cox West incoming mail server: pop.west.cox.net
ƒ Cox West outgoing mail server: smtp.west.cox.net
ƒ Earthlink incoming mail server: pop.earthlink.net
ƒ Earthlink outgoing mail server: mail.earthlink.net, smtpauth.earthlink.net
ƒ GoDaddy incoming mail server: mail.godaddy.com
ƒ GoDaddy outgoing mail server: use your ISP's SMTP mail server
ƒ Google GMail incoming mail server: pop.gmail.com
ƒ Google GMail outgoing mail server: smtp.gmail.com
ƒ Internet America incoming mail server: pop3.airmail.net
ƒ Internet America outgoing mail server: mail.airmail.net
ƒ Juno incoming mail server: pop.juno.com
ƒ (cannot send pop3 email from other domains)
ƒ Netscape incoming mail server: pop3.isp.netscape.com
ƒ Netscape outgoing mail server: smtp.isp.netscape.com
ƒ NetZero incoming mail server: pop.netzero.net
ƒ NetZero outgoing mail server: smtp.netzero.net
ƒ PeoplePC incoming mail server: pop.peoplepc.com
ƒ PeoplePC outgoing mail server: smtpauth.peoplepc.com
ƒ Prodigy incoming mail server: pop.prodigy.net
ƒ Prodigy outgoing mail server: smtp.prodigy.net
ƒ SprintPCS incoming mail server: pop.sprintpcs.com
ƒ SprintPCS outgoing mail server: smtp.sprintpcs.com
ƒ USA.net incoming mail server: pop.netaddress.com
ƒ USA.net outgoing mail server: smtp.postoffice.net
ƒ Verizon incoming mail server: incoming.verizon.net
ƒ Verizon outgoing mail server: outgoing.verizon.net
ƒ Yahoo incoming mail server: pop.mail.yahoo.com
ƒ Yahoo outgoing mail server: smtp.mail.yahoo.com

-21-
REVIEW QUESTIONS:

1. What are the steps required to enable the POP in Gmail?


2. How you setup your outlook express client to work with Gmail?
3. List out some ISP which is supported by POP3 SMTP mailservers?

-22-
Chapter 3
VIDEO CONFERENCING DEMONSTRATION
Objectives

ƒ Understanding video conferencing


ƒ Technology used
ƒ Multipoint video conferencing
ƒ Problems and solution
ƒ Sign language communication and Video Interpreter (V.I.)

A video conference (also known as a video teleconference) is a set of interactive


telecommunication technologies which allows two or more locations to interact via two-way
video and audio transmissions simultaneously. It has also been called as 'visual collaboration'
and it is a type of groupware.

Videoconferencing differs from videophone calls in that it's designed to serve a


conference rather than individuals. It is an intermediate form of videotelephony, first
deployed commercially by AT&T during the early 1970s using their Picturephone
technology.

-23-
Videoconferencing uses telecommunications of audio and video to bring people at
different sites together for a meeting. This can be as simple as a conversation between two
people in private offices (point-to-point) or involve several sites (multi-point) with more than
one person in large rooms at different sites. Besides the audio and visual transmission of
meeting activities, videoconferencing can be used to share documents, computer-displayed
information, and whiteboards.Simple analog videoconferences could be established as early
as the invention of the television. Such videoconferencing systems usually consisted of two
closed-circuit television systems connected via cable. An example of that was the German
Reich Postzentralamt (Post Office) network set up in Berlin and several other cities from
1936 to 1940.

During the first manned space flights, NASA used two radiofrequency (UHF or VHF)
links, one in each direction. TV channels routinely use this kind of videoconferencing when
reporting from distant locations, for instance. Then mobile links to satellites using specially
equipped trucks became rather common.

Videoconferencing first demonstrated in 1968

This technique was very expensive, though, and could not be used for applications
such as telemedicine, distance education, and business meetings. Attempts at using normal
telephony networks to transmit slow-scan video, such as the first systems developed by
AT&T, failed mostly due to the poor picture quality and the lack of efficient video
compression techniques. The greater 1 MHz bandwidth and 6 Mbit/s bit rate of Picturephone
in the 1970s also did not cause the service to prosper.

-24-
It was only in the 1980s that digital telephony transmission networks became
possible, such as ISDN, assuring a minimum bit rate (usually 128 kilobits/s) for compressed
video and audio transmission. The first dedicated systems started to appear in the market as
ISDN networks were expanding throughout the world. Video teleconference systems
throughout the 1990s rapidly evolved from highly expensive proprietary equipment, software
and network requirements to standards based technology that is readily available to the
general public at a reasonable cost.

Finally, in the 1990s, IP (Internet Protocol) based videoconferencing became possible


and more efficient video compression technologies were developed, permitting desktop, or
personal computer (PC)-based videoconferencing. In 1992 CU-See Me was developed at
Cornell by Tim Dorcey et al. In the 2000s, VTC finally arrived for the masses via free
services, web plug-in and on-line telecommunication programs which brought cheap, albeit
low-quality, videoconferencing to almost every home with an Internet connection.

TECHNOLOGY:

Dual display Polycom VSX 7000 camera used for videoconferencing with two displays for
simultaneous broadcast from separate locations

-25-
The core technology used in a videoteleconference (VTC) system is digital
compression of audio and video streams in real time. The hardware or software that performs
compression is called a codec (coder/decoder). Compression rates of up to 1:500 can be
achieved. The resulting digital stream of 1s and 0s is subdivided into labelled packets, which
are then transmitted through a digital network of some kind (usually ISDN or IP). The use of
audio modems in the transmission line allow for the use of POTS, or the Plain Old Telephone
System, in some low-speed applications, such as videotelephony, because they convert the
digital pulses to/from analog waves in the audio spectrum range.

The other components required for a VTC system include:

ƒ Video input : video camera or webcam


ƒ Video output: computer monitor , television or projector
ƒ Audio input: microphones, CD/DVD player, cassette player, or any other source of
PreAmp audio outlet.
ƒ Audio output: usually loudspeakers associated with the display device or telephone
ƒ Data transfer: analog or digital telephone network, LAN or Internet

There are basically two kinds of VTC systems:

1. Dedicated systems have all required components packaged into a single piece of
equipment, usually a console with a high quality remote controlled video camera.
These cameras can be controlled at a distance to pan left and right, tilt up and down,
and zoom. They became known as PTZ cameras. The console contains all electrical
interfaces, the control computer, and the software or hardware-based codec. Omni
directional microphones are connected to the console, as well as a TV monitor with
loudspeakers and/or a video projector. There are several types of dedicated VTC
devices:
2. Large group VTC are non-portable, large, more expensive devices used for large
rooms and auditoriums.
3. Small group VTC are non-portable or portable, smaller, less expensive devices used
for small meeting rooms.

-26-
4. Individual VTC are usually portable devices, meant for single users, have fixed
cameras, microphones and loudspeakers integrated into the console.
5. Desktop systems are add-ons (hardware boards, usually) to normal PCs, transforming
them into VTC devices. A range of different cameras and microphones can be used
with the board, which contains the necessary codec and transmission interfaces. Most
of the desktops systems work with the H.323 standard. Videoconferences carried out
via dispersed PCs are also known as e-meetings.

ECHO CANCELLATION

A fundamental feature of professional VTC systems is acoustic echo cancellation (AEC).


Echo can be defined as the reflected source wave interference with new wave created by
source. AEC is an algorithm which is able to detect when sounds or utterances reenter the
audio input of the VTC codec, which came from the audio output of the same system, after
some time delay.

If unchecked, this can lead to several problems including:

1. The remote party hearing their own voice coming back at them (usually significantly
delayed)
2. Strong reverberation, rendering the voice channel useless as it becomes hard to
understand and
3. Howling created by feedback. Echo cancellation is a processor-intensive task that
usually works over a narrow range of sound delays.

MULTIPOINT VIDEOCONFERENCING

Simultaneous videoconferencing among three or more remote points is possible by


means of a Multipoint Control Unit (MCU). This is a bridge that interconnects calls from
several sources (in a similar way to the audio conference call). All parties call the MCU unit,
or the MCU unit can also call the parties which are going to participate, in sequence. There
are MCU bridges for IP and ISDN-based videoconferencing. There are MCUs which are pure
software, and others which are a combination of hardware and software. An MCU is

-27-
characterized according to the number of simultaneous calls it can handle, its ability to
conduct transposing of data rates and protocols, and features such as Continuous Presence, in
which multiple parties can be seen onscreen at once. MCUs can be stand-alone hardware
devices, or they can be embedded into dedicated VTC units.

Some systems are capable of multipoint conferencing with no MCU, stand-alone,


embedded or otherwise. These use a standards-based H.323 technique known as
"decentralized multipoint", where each station in a multipoint call exchanges video and audio
directly with the other stations with no central "manager" or other bottleneck. The advantages
of this technique are that the video and audio will generally be of higher quality because they
don't have to be relayed through a central point. Also, users can make ad-hoc multipoint calls
without any concern for the availability or control of an MCU. This added convenience and
quality comes at the expense of some increased network bandwidth, because every station
must transmit to every other station directly.

PROBLEMS:

Some observers argue that two outstanding issues are preventing videoconferencing
from becoming a standard form of communication, despite the ubiquity of
videoconferencing-capable systems.

These issues are:

1. Eye Contact: It is known that eye contact plays a large role in conversational turn-
taking, perceived attention and intent, and other aspects of group communication.
While traditional telephone conversations give no eye contact cues,
videoconferencing systems are arguably worse in that they provide an incorrect
impression that the remote interlocutor is avoiding eye contact. Telepresence systems
have cameras located in the screens that reduce the amount of parallax observed by
the users. This issue is also being addressed through research that generates a
synthetic image with eye contact using stereo reconstruction. Bell Communications
Research owns a patent for eye-to-eye video conferencing using rear projection

-28-
screens with a camera behind it. This technique eliminates the need for special
cameras or image processing.

2. Appearance Consciousness: A second problem with videoconferencing is being on


camera, with the video stream possibly even being recorded. The burden of
presenting an acceptable on-screen appearance is not present in audio-only
communication. Early studies by Alphonse Chapanis found that the addition of video
actually impaired communication, possibly because of the consciousness of being on
camera.

The issue of eye-contact may be solved with advancing technology, and presumably the issue
of appearance consciousness will fade as people become accustomed to videoconferencing.

STANDARDS:

The Tandberg E20 is an example of a SIP only device. Such devices need to route
calls through a Video Communication Server to be able to reach H.323 systems, a process
known as "interworking".

The International Telecommunications Union (ITU) (formerly: Consultative Committee


on International Telegraphy and Telephony (CCITT)) has three umbrellas of standards for
VTC.

-29-
1. ITU H.320 is known as the standard for public switched telephone networks (PSTN)
or VTC over integrated services digital networks ([[it is accessible to anyone with a
high speed Internet connection, such as DSL.

H.264 SVC (Scalable Video Coding) is a compression standard that enables video
conferencing systems to achieve highly error resilient IP video transmission over the public
Internet without quality of service enhanced lines. This standard has enabled wide scale
deployment of high definition desktop video conferencing and made possible new
architectures which reduce latency between transmitting source and receiver, resulting in
fluid communication without pauses.

In addition, an attractive factor for IP VTC is that it is easier to set-up for use with a live
VTC call along with web conferencing for use in data collaboration. These combined
technologies enable users to have a much richer multimedia environment for live meetings,
collaboration and presentations.

ITU V.80: videoconferencing is generally compatibilized with H.324 standard point-to-


point video telephony over regular phone lines.

IMPACT ON THE GENERAL PUBLIC:


High speed Internet connectivity has become more widely available at a reasonable
cost and the cost of video capture and display technology has decreased. Consequently
personal video teleconference systems based on a webcam, personal computer system,
software compression and broadband Internet connectivity have become affordable for the
general public. Also, the hardware used for this technology has continued to improve in
quality, and prices have dropped dramatically. The availability of freeware (often as part of
chat programs) has made software based videoconferencing accessible to many.

For many years, futurists have envisioned a future where telephone conversations will
take place as actual face-to-face encounters with video as well as audio. Sometimes it is
simply not possible or practical to have a face-to-face meeting with two or more people.

-30-
Sometimes a telephone conversation or conference call is adequate. Other times, an email
exchange is adequate.

Videoconferencing adds another possible alternative, and can be considered when:

ƒ a live conversation is needed;


ƒ visual information is an important component of the conversation;
ƒ the parties of the conversation can't physically come to the same location; or
ƒ the expense or time of travel is a consideration.

Deaf, hard-of-hearing and mute individuals have a particular interest in the development
of affordable high-quality videoconferencing as a means of communicating with each other
in sign language. Unlike Video Relay Service, which is intended to support communication
between a caller using sign language and another party using spoken language,
videoconferencing can be used between two signers.

Mass adoption and use of video conferencing is still relatively low, with the following
often claimed as causes:

ƒ Complexity of systems. Most users are not technical and want a simple interface. In
hardware systems an unplugged cord or a flat battery in a remote control is seen as
failure, contributing to perceived unreliability which drives users back to traditional
meetings. Successful systems are backed by support teams who can pro-actively
support and provide fast assistance when required.

ƒ Perceived lack of interoperability: not all systems can readily interconnect, for
example ISDN and IP systems require a gateway. Popular software solutions cannot
easily connect to hardware systems. Some systems use different standards, features
and qualities which can require additional configuration when connecting to dis-
similar systems.

-31-
ƒ Bandwidth and quality of service: In some countries it is difficult or expensive to get
a high quality connection that is fast enough for good-quality video conferencing.
Technologies such as ADSL have limited upload speeds and cannot upload and
download simultaneously at full speed. As Internet speeds increase higher quality and
high definition video conferencing will become more readily available.

ƒ Expense of commercial systems - a well designed system requires a specially


designed room and can cost hundreds of thousands of dollars to fit out the room with
codecs, integration equipment and furniture.

ƒ Participants being self-conscious about being on camera, especially new users and
older generations.

ƒ Lack of eye contact (as mentioned in Problems)

For these reasons many hardware systems are often used for internal corporate use only,
as they are less likely to run into problems and lose a sale. An alternative is companies that
hire out video conferencing equipped meeting rooms in cities around the world. Customers
simply book the rooms and turn up for the meeting - everything else is arranged and support
is readily available if anything should go wrong.

Sign language communications via videoconferencing

Video Interpreter sign used at VRS/VRI service locations

One of the first demonstrations of the ability for telecommunications to help sign
language users communicate with each other occurred when AT&T's videophone
(trademarked as the 'Picturephone') was introduced to the public at the 1964 New York
World's Fair –two deaf users were able to freely communicate with each other between the
fair and another city. Various other organizations have also conducted research on signing
via videotelephony.

-32-
A deaf or hard-of-hearing person at his workplace using a VRS to communicate
with a hearing person in London. Using such video equipment, the deaf, hard-of-hearing
and speech-impaired can communicate between themselves and with hearing individuals
using sign language. The United States and several other countries compensate companies to
provide 'Video Relay Services' (VRS). Telecommunication equipment can be used to talk to
others via a sign language interpreter, who uses a conventional telephone at the same time to
communicate with the deaf person's party. Video equipment is also used to do on-site sign
language translation via Video Remote Interpreting (VRI). The relative low cost and
widespread availability of 3G mobile phone technology with video calling capabilities have
given deaf and speech-impaired users a greater ability to communicate with the same ease as
others. Some wireless operators have even started free sign language gateways.

Sign language interpretation services via VRS or by VRI are useful in the present-day
where one of the parties is deaf, hard-of-hearing or speech-impaired (mute). In such cases the
interpretation flow is normally within the same principal language, such as French Sign
Language (FSL) to spoken French, Spanish Sign Language (SSL) to spoken Spanish, British
Sign Language (BSL) to spoken English, and American Sign Language (ASL) also to spoken
English (since BSL and ASL are completely distinct), etc... Multilingual sign language
interpreters, who can also translate as well across principal languages (such as to and from
SSL, to and from spoken English), are also available, albeit less frequently. Such activities
involve considerable effort on the part of the translator, since sign languages are distinct
natural languages with their own construction, semantics and syntax, different from the aural
version of the same principal language.

A VIDEO INTERPRETER (V.I.) ASSISTING AN ON-SCREEN CLIENT.


With video interpreting, sign language interpreters work remotely with live video and
audio feeds, so that the interpreter can see the deaf or mute party, and converse with the
hearing party, and vice versa. Much like telephone interpreting, video interpreting can be
used for situations in which no on-site interpreters are available. However, video interpreting
cannot be used for situations in which all parties are speaking via telephone alone. VRI and
VRS interpretation requires all parties to have the necessary equipment. Some advanced

-33-
equipment enables interpreters to remotely control the video camera, in order to zoom in and
out or to point the camera toward the party that is signing.

REVIEW QUESTIONS:

1. What is video conferencing?


2. What are the technologies used in video conferencing?
3. Explain Multipoint video conference?
4. What are the problems in video conferencing?
5. Explain sign language communication in video confrerencing?

-34-
Chapter 4

DOWNLOADING AND INSTALLING SOFTWARES (EXAMPLE:


JAVA) AND SETTING UP PATH AND CLASS PATH

Objectives

ƒ Process of software downloading


ƒ Software installation process
ƒ Path variable and Class Path variables setting
ƒ Class path setting through command prompt
ƒ System path setting
ƒ Handling JARs on the class path

Java was developed at Sun Microsystems Inc and there is a big web site devoted to Java.
It contains news, tutorials, and the software needed to develop and run Java program:

http://java.sun.com/

If you want to set up your computer with the software needed to compile and run Java
programs go the java.sun.com site and click on the J2SE 1.5 SDK link in the Popular
Downloads box on the right of the screen. Don't worry if the numbers are different. That just

means it is a newer version.

DOWNLOADING TEXTPAD:

The other thing you need to develop programs at home is a text editor. Any text editor
will do but there is one in particular, called TextPad that can also be used to compile and run
Java programs assuming that you have installed a Java SDK. It is shareware and can be
downloaded from the following site:

http://www.textpad.com

-35-
Shareware is not free. You can download it and test-drive it

What is the meaning of PATH and CLASSPATH? How it is set in environment


variable?

SIGNIFICANCE OF SEARCHING CLASS PATH

Java is an OOP language. In java programming language for compiling the program
we use the compiler that converts the source code into the byte code after that, that byte code
is interpreted by JVM that converts the bytecode into the machine independent code. In java
how the Java compiler and the JVM use the class search path to locate classes when they are
referenced by other Java code. Searching class path is important for all Java
developers.Many development tools have their own ways of manipulating the class path,
which vary from product to product.For doing this we will use only simple command-line
tools to carry out the compile operations. No difference, between the way that the Java
compiler searches for classes, and the way that the JVM does it at run time. The compiler has
the ability to compile classes from source code, where the JVM does not. We will use the
compiler, but similar issues apply at run time.

SEARCHING OF MULTIPLE CLASS DIRECTORIES

ƒ Javac (compiler) search the files in only one directory at a time.

ƒ But, class search path will contain numerous directories and JAR archives. The -class
path option to javac and java allows multiple entries to be specified, but the syntax is
different for Unix and Windows systems.

For UNIX : javac -classpath dir1:dir2:dir3…


For Windows : javac -classpath dir1; dir2; dir3…

-36-
The difference is that Windows uses the colon (:) character as part of a filename, so it
can't be used as a filename separator. Naturally the directory separator character is different
as well: forward slash (/) for UNIX and backslash (\) for Windows.

For running a simple program we need to set the java path on command prompt(for
temporary )& in Environment variable using PATH variable & CLASSPATH variable :

PATH VARIABLE:

In JDK the PATH variable contains directories where binary files (e.g. EXE files in
Windows) will be looked for. We set the PATH variables like this i.e path
C:\Java\jdk1.6.0_03\bin

(I) On command prompt


C:\>set path=%path;C:\Java\jdk1.6.0_03\bin%

When you open a command prompt and type "javac", you're supposed to have the "bin"
directory of your sdk into the PATH, otherwise you'll get an infamous "Command not found"
error message.

CLASSPATH:

In JDK the CLASSPATH contains directories (or JAR files), from where your java
compiler/runtime will look for .class files (and some others). e.g., "java Hello. Class" will not
work unless you set the directory (or JAR file) Hello. Class is in, into your CLASSPATH.
i.e.classpath C:\Java\jdk1.6.0_03\lib

For setting CLASSPATH using command prompt

Java class path can be set using either the -class path option when calling an SDK tool
(the preferred method) or by setting the CLASSPATH environment variable. The -class path
option is preferred because you can set it individually for each application without affecting
other applications and without other applications modifying its value.

-37-
(ii) On command prompt

C:\>set classpath=%classpath;C:\Java\jdk1.6.0_03\lib%

JARs on the class path

Java compiler and run-time can search for classes not only in separate files, but also
in `JAR' archives. A JAR file can maintain its own directory structure, and Java follows
exactly the same rules as for searching in ordinary directories. Specifically, `directory name
= package name'. Because a JAR is itself a directory, to include a JAR file in the class search
path, the path must reference the JAR itself, not the directory that contains the JAR. This is a
very common error. Suppose I have a JAR jarclasses.jar in directory /jarclasses. The Java
compiler look for classes in this jar, we need to specify:

javac -classpath /jarclasses/jarclasses.jar ...

And not merely the directory jarclasses.

For the CLASSPATH use CLASSPATH Environment Variable

In java programming language we use the following packages such as java.io.*; java.
util.*; These packages are just a set of classes, you will want to store them in one place,
separate from the directory where you are developing your program. Sometimes these
libraries have a set of files stored in a single jar file (with a .jar extension). From where the
Java compiler and run programs must be able to find any of these. This is done for command
line use of Java and for some editors and IDEs by setting an environment variable called
CLASSPATH. For Windows, the CLASSPATH environment variable should look like this:

c:\MyJavaLib;c:\MyJavaLib\myutils.jar;c:\MyJavaLib\blackboxclasses.jar;.

-38-
At the end “.” Includes the current directory in the search for classes.

ƒ Suppose we have a directory MyJavaLib on the C-drive that contains some utility
classes or the directories that correspond to some packages. This is the part before the
first semi-colon.

ƒ Second part indicates that we have some classes stored in a file myutils.jar

ƒ Third part indicates that we have a jar file blackboxclasses.jar.

Finally, after the last semi-colon we have the period (.), indicating that the current
directory is on the CLASSPATH. If some things are stored in directories that are
subdirectories, the complete path, starting with "c:\" should be in the CLASSPATH.

(2) For setting CLASSPATH & PATH variable in environment variable by using the
following steps:

i. Right click on my computer icon on desktop

ii. Click on properties

iii. Click on advanced

iv. Click on Environment variables

-39-
v. System variables click on new

vi.

ƒ In (variable name) write ----- path


ƒ in (variable value) paste the path till bin directory i.e.------- c:\java\jdk1.6.0_03\bin
ƒ click on ok

-40-
vii. In system variables again click on new

-41-
viii. in ( variable name) write ----- classpath

in (variable value) paste the path till lib directory i.e.------- c:\java\jdk1.6.0_03\lib
click on ok

ix. after finished click on ok

-42-
x. Finished click on ok

How to set System Class path:

Java class path is set for including the various files during program execution &
compilation. After setting class search path on the javac command line, we set `system' class
path. This class path will be used by both the Java compiler and the JVM . In both Unix and
Windows systems, this is done by setting an environment variable.

For example, in Linux with the bash shell

CLASSPATH=/jarclasses/jarclasses.jar;export CLASSPATH

For Windows:
set CLASSPATH=c:\jarclasses\jarclasses.jar

-43-
We use this procedure for setting short-term changes to the system CLASSPATH, but
if you want these changes to be persistent you will need to arrange this yourself. For different
- 2 system this path is different . On a Linux system, we put the commands in the file .bashrc
in my home directory. On Windows 2000/NT there is a `Control Panel' page for this. Setting
the system CLASSPATH is a useful procedure if you have JARs full of classes that you use
all the time.

REVIEW QUESTION:

1. Explain process of software downloading?

2. How do you install downloaded software?

3. How do you set Path and Class Path variables?

4. Explain CLASSPATH & PATH variable setting via system property?

5. Explain how we can handle JAR files in classpath and path variables?

-44-
Chapter 5
Using FTP

Objectives

ƒ Understanding FTP
ƒ FTP and their directory commands
ƒ FTP used in Telnet

Ftp (File Transfer Protocol) is a method for transferring files between two computers
on a network. The two computers must be on the Internet. Examples of Ftp use are: to
transfer files between your computer and your web space on a large computer, to transfer
software or files to your computer from known Internet sites.

Ftp has two parts: the client and the server. The ftp client is a program on the
computer you are using logged in to. The ftp server is a program on a remote computer that
you want to connect to.

This handout describes the general capabilities of most ftp clients and servers.
However, not all ftp programs are alike and you may find that your ftp client or the server
you are connected to has slightly different behavior. In particular, the commands in this
handout are presented in command line format, like that used on many large computers. IBM
PC and Macintosh client software, such as WS-FTP or Fetch, present a graphical, window-
oriented interface.

STARTING YOUR FTP CLIENT:

On most large computers, type the ftp command to start the ftp client program:
ƒ ftp

-45-
Ftp commands:

When the ftp client is started, it is ready to accept commands. Most ftp clients will
prompt you for a command like this:
ƒ ftp>

Use the quit command to terminate your ftp client:


ƒ ftp> quit

Most ftp client programs will also respond with a list of available commands if you
enter a "?":
ƒ ftp> ?

CONNECTING TO A REMOTE COMPUTER:

Use the open command to connect to a remote computer. For example, to connect to
CIRCA's Grove system:
ƒ ftp> open grove.ufl.edu

You will be asked for a user id and password for the remote computer. If you have an
account on the remote computer and want to transfer your files, enter your user id and
password.

Many computers will accept an "anonymous" ftp log in. This means that the
managers of that computer will allow anyone to make an ftp connection to the computer to
retrieve some public files. When asked for a username, enter anonymous. When asked for a
password, it is customary to enter your electronic mail address, and some servers may require
it. Using anonymous to log in is commonly called anonymous ftp.

-46-
DIRECTORY COMMANDS:

Use the ls and dir commands to display the names of the files in the directory on the
remote computer:
ƒ ftp> ls
ƒ ftp> dir

The ls command will send back a list of the file names. The dir command will supply
expanded information, such as the date and size of the file. The format of the information
depends on the type of computer the ftp server is running on.

Use the cd command to change to a different directory on the remote computer. For
example, to change to the subdirectory pub/micro:

ƒ ftp> cd pub/micro

The syntax of the subdirectory might need to be in the format normally used on the
remote computer. For example, for some VMS computers, you might need to enter the cd
command this way:

ƒ ftp> cd [.public]

Use the lcd command to change your "local" directory. That's the current directory on
your computer. You must specify the new directory in the form normally expected on your
computer. For example, if you are running the ftp client program on a PC, this command will
change to the root directory on diskette drive A:

ƒ ftp>lcd a:\

-47-
Commands to retrieve a file:
Use the get command to transfer a file from the remote computer to your computer.
For example, to get the file readme.txt from the remote computer, enter this command:

ƒ ftp> get install.txt

Some computers have file systems with case-sensitive names, so make sure you enter
the name of the file using the correct case.

When you get a file you can give it a new name. The name of the file on the remote
computer might not be compatible with your computer or you might prefer a different name.
The new name is specified on the get command. For example, this get command specifies
the new name readme.txt for the file being retrieved:

ƒ ftp> get read_me_first.txt readme.txt

Use the mget command to get a group of files. This command will get all the files
ending in ".c":
ƒ ftp> mget *.c

Your ftp client may prompt you before it retrieves each file that matches. If you want
it to transfer the file, enter "Y" or "YES".

Files can be transferred as either ascii or binary. An ascii file is a file containing only
printable characters. A binary file can contain printable and unprintable characters. Examples
of binary files are executable files or files compressed to save space.

To transfer a file in binary mode, enter the binary command before the get command:

ƒ ftp> binary
ƒ ftp> get foo.zip

WARNING: some ftp clients go back to ascii mode when you enter an ls or dir command.
To be safe, always use the binary command before getting a binary file.

-48-
Commands to send a file:

Use the put command to transfer a file from your computer to the remote computer.
For example, this command transfers the file prog1.pas to the remote computer:

ƒ ftp> put prog1.pas

You can specify a new name for the file when it is transferred to the remote
computer. For example, this put command specifies the new name prog1.p:

ƒ ftp> put prog1.pas prog1.p

If you are transferring a binary file, use the binary command before the put
command:
ƒ ftp> binary

ƒ ftp> put test.exe

Use the mput command to transfer a group of files. For example, to transfer all files
ending in "TXT" to the remote computer, enter this:

ƒ ftp> mput *.txt

Using ftp with CUTCP telnet:

Telnet is a program used to interactively log in to a remote computer. CUTCP telnet is a


program that runs on a PC and is used in CIRCA labs and elsewhere on campus to log in to
remote computers. This program can also function as an ftp server when you are logged in to
a remote host. This means that you can use the host's ftp client to connect back to yourself.
Here's how you do it:

1. First use telnet to log in to the remote host.

2. Press Alt/T. This will generate an ftp command with the proper network address and
start the ftp client program on the interactive host.

-49-
3. When it asks for a name, enter anything.

4. When it asks for a password, press Alt/W. This will provide a hidden password to
authenticate the connection.

Remember that when you have completed this connection, your PC is an ftp server, and
the interactive host is running an ftp client. To transfer a file from the interactive host to your
PC, use the put command. To transfer a file from the PC to the interactive host, use the get
command.

Review Questions:

1. What is mean by FTP?

2. Explain FTP commands?

3. Explain FTP Directory commands?

4. Using FTP with CUTCP telnet, explain?

5. What is Telnet?

6. Why CUTCP?

-50-
Chapter 6

CREATION OF WEB SITE WITH FORMS, FRAMES, LINKS,


TABLES etc WITH ANY WEB PAGE EDITORS AND USING IMAGE
AND AUDIO FILES AS PART OF WEB PAGE

Objectives

ƒ Understanding Forms, Frames, Links and Tables


ƒ Commonly used input types and commands
ƒ Working with image tags and source attributes
ƒ Working with tables and their tags
ƒ Audio files embed in web page

The Hyper Text Markup Language (HTML) is a markup language


used to create Hypertext documents that are platform independent.
So most of what we see in the Internet web pages is made of html
document.HTML Code was originally developed by Tim Berners-Lee while at
CERN, and popularized by the Mosaic browser developed at NCSA
It is called markup language because users can mark up their documents by representing
structural, presentational, and semantic information alongside content.

-51-
BASIC TAGS IN HTML:

-52-
Forms:
A form is an area that can contain form elements.Form elements are elements that
allow the user to enter information (like text fields, textarea fields, drop-down menus, radio
buttons, checkboxes, etc.) in a form.A form is defined with the <form> tag.

<form>
.
input elements
.
</form>

Input:

The most used form tag is the <input> tag. The type of input is specified with the type
attribute. The most commonly used input types are explained below.

Attributes for INPUT TAG:

The primary tag used in HTML forms is the <input /> tag. The input tag prompts your
readers to input data to your Web server.

There are ten specific types of <input /> tag:

1. button
2. checkbox
3. file
4. hidden
5. image
6. password
7. radio
8. reset
9. submit
10. text

-53-
You choose which type of input tag you would like by placing it in the type=""
attribute of the tag. For example:
<input type="text" />
Button
<input type="button" value="button" name="button" />

The button input type allows you to create custom input buttons that do not have the
default effects of the submit and reset buttons. It is most commonly used with JavaScript
forms with the onClick attribute so that data is not sent to the Web server until the JavaScript
has processed it. This field is blank by default. If you want it to say something, use the
VALUE="" attribute.

Checkbox
<input type="checkbox" />

With a checkbox element, you can give your readers a list of items to choose from.
They can choose more than one in the list. Or it can be used as a "yes/no" toggle, when there
is only one option. If you have a group of checkboxes, link them all together by giving them
the same name. The values will all be sent to the form separately.

File
<input type="file" />

The file input type allows your readers to upload a file to your Web server. If you
read my article on CGIs and File Upload, you can learn more about how to use the file input
type.

-54-
Hidden
<input type="hidden" />

Hidden fields are used to "save state" within an HTML form. They are most often
used in forms that have multiple pages and information that needs to be carried from one
page to the next. They are not shown on the Web page, but the information is sent along with
other form input fields.

Image

<input type="image" src="ABCbuttn.gif" width="88"


height="31" alt="About.com - image courtesy About.com"
border="0" />

With the image input type, you have yet another option for a button on your forms.
The image shown here happens to look like a button, but you can use any image as a button
on your forms. One thing to note, images as submit buttons don't allow for the tab key to
move the focus to it, and this makes them less accessible for people with no mouse.

Password
<input type="password" />

The password field looks almost identical to the text field. However, when you type
in it, the letters are hidden. This allows you to have a little more security for passwords on
your forms. Remember, however, that the passwords are not sent encrypted in any way. So
don't rely on this to secure truly important secret information.

Radio
<input type="radio" />

Radio buttons give readers a "one of many" choice combination. Like the checkbox
input type, radio button groupings all have the same NAME, and each value is different. If a
reader chooses one value, all the other values will be deselected.

-55-
Reset, Submit, and Text Input Tags

Text Fields
Text fields are used when you want the user to type letters, numbers, etc. in a form.

<form>
First name:
<input type="text" name="firstname" />
<br />
Last name:
<input type="text" name="lastname" />
</form>

How it looks in a browser:

First name:

Last name:

Note that the form itself is not visible. Also note that in most browsers, the width of
the text field is 20 characters by default.

Radio Buttons:

Radio Buttons are used when you want the user to select one of a limited number of
choices.

<form>
<input type="radio" name="sex" value="male" /> Male
<br />
<input type="radio" name="sex" value="female" /> Female
</form>

How it looks in a browser: Top of Form

-56-
Male

Female

Note that only one option can be chosen.

Checkboxes:
Check boxes are used when you want the user to select one or more options of a
limited number of choices.

<form>
I have a bike:
<input type="checkbox" name="vehicle" value="Bike" />
<br />
I have a car:
<input type="checkbox" name="vehicle" value="Car" />
<br />
I have an airplane:
<input type="checkbox" name="vehicle" value="Airplane" />
</form>

How it looks in a browser:

I have a bike:
I have a car:
I have an airplane:

The Form's Action Attribute and the Submit Button:


When the user clicks on the "Submit" button, the content of the form is sent to the server.
The form's action attribute defines the name of the file to send the content to. The file defined
in the action attribute usually does something with the received input.

<form name="input" action="html_form_submit.asp" method="get">


Username:
<input type="text" name="user" />
<input type="submit" value="Submit" />
</form>

-57-
How it looks in a browser:

Submit
Username:

If you type some characters in the text field above, and click the "Submit" button, the
browser will send your input to a page called "html_form_submit.asp". The page will show
you the received input.

Hyperlinks, Anchors, and Links:

In web terms, a hyperlink is a reference (an address) to a resource on the web.

Hyperlinks can point to any resource on the web: an HTML page, an image, a sound
file, a movie, etc.

An anchor is a term used to define a hyperlink destination inside a document.


The HTML anchor element <a>, is used to define both hyperlinks and anchors.

We will use the term HTML link when the <a> element points to a resource, and the
term HTML anchor when the <a> elements defines an address inside a document..

An HTML Link

Link syntax:

<a href="url">Link text</a>

The start tag contains attributes about the link.

The element content (Link text) defines the part to be displayed.

Note: The element content doesn't have to be text. You can link from an image or any other
HTML element.

The href Attribute

-58-
The href attribute defines the link "address".

This <a> element defines a link to Annauniv:

<a href="http://www.annauniv.com/">Visit Annauniv!</a>

The code above will display like this in a browser:

Visit Annauniv!

The target Attribute

The target attribute defines where the linked document will be opened.

The name Attribute

When the name attribute is used, the <a> element defines a named anchor inside a HTML
document.

Named anchor are not displayed in any special way. They are invisible to the reader.

Named anchor syntax:

<a name="label">Any content</a>

The link syntax to a named anchor:

<a href="#label">Any content</a>

The # in the href attribute defines a link to a named anchor.

Example:

A named anchor inside an HTML document:

<a name="tips">Useful Tips Section</a>

-59-
A link to the Useful Tips Section from the same document:

<a href="#tips">
Jump to the Useful Tips Section</a>

A link to the Useful Tips Section from another document:

<a href="http://www.annauniv.com/html_tutorial.htm#tips">
Jump to the Useful Tips Section</a>

ORDERING AND NUMBERING:

In HTML, you have the choice of designing with "ordered lists" that are numbered or
using unordered lists, which use bullet points to get your, um, point across.

Ordered Lists:

Ordered lists require some kind of marker denoting a specific order. You can use
numbers (1,2,3), letters, (A, B, C), or Roman numerals (I, II, III) if you want to get really
swanky. Ordered lists are made to be used when listed information is displayed in order of
importance or as directions.

The two tags that you will use in your ordered lists are:
<OL> and <LI>

<OL> stands for "ordered list", and is used to start a list.

<LI> stands for "list item", and is used to start any item in your list.

The list will automatically number itself.

To make a list that reads:


1. Get up
2. Turn off alarm
3. Go back to sleep
4. You would enter in the following code:

-60-
<OL>
<LI> Get up </LI>
<LI> Turn off alarm </LI>
<LI> Go back to sleep </LI>
</OL>

Notice that I have indented the <LI> tags. Its not really necessary that you do so, but
Ive done it for a reason. In a minute, the lists will get a bit more complicated and visual
organization is important. Also take note that Ive closed the <OL> tag. This is very
important; otherwise your browser will assume that everything after this list is also part of
the list.

NESTED LISTS

What if you want a list that says:


1. Get up
2. Eat food
a. Open mouth
b. Insert food
3. Go back to bed

You have basically got two lists here, right? One list contains "get up", "eat food", and
"go back to bed". The other list contains "open mouth" and "insert food". The "open mouth,
insert food" list will be built directly inside of the larger list.

When a list is built inside of another list it is said to be "nested". Actually, when any
HTML code is built inside of code of the same type, the code is said to be nested. "Nested" is
a pretty important term; youll see it more often later on.

-61-
To build the above "get up", "eat food", and "go back to bed" list with its nested sub-set:

<OL>
<LI> Get up </LI>

<LI> Eat food </LI>

<OL>

<LI> Open mouth </LI>

<LI> Insert food </LI>

</OL>

<LI> Go back to bed </LI>

</OL>

Notice that the "open mouth, insert food" subset is a completely different list. It has
its own <OL> and </OL>. Closing each list is important. If you forgot to close the "open
mouth, insert food" subset, the last point of the main list, "goes back to bed", would be
included in the sub-set.

You dont have to tell the sub-set to use a different numbering style, it knows all on its
own. Again, the indenting is done to keep track of where you are in the list, not because its
required.

Sub-sets can have sub-sets, too. You can have as many sub-sets as you feel like.

Can you build the following list?:

1. Take a web design course


2. Feel really proud
3. Get high paying job at www.Lists.com
a. Buy Porsche
b. Retire

-62-
Heres what the list would look like:
<OL>
<LI> Take web design course </LI>

<LI> Feel really proud </LI>

<LI> Get high paying job at www.Lists.com </LI>

<OL>

<LI> Buy Porsche </LI>

<LI> Retire </LI>

</OL>
</OL>

Dont forget to close the main list!

Try to build some lists on your own.

Changing the Way Lists are Numbered

"But Im proud of my Italian ancestry." You say, "Id rather use roman numerals."
Never fear. You can make a list with numbers, letters, or roman numerals. You simply add a
TYPE="modifier" to the <OL> tag. For example:

<OL TYPE= "a"> (standard lettering, lowercase)

<OL TYPE= "A"> (standard lettering, uppercase)

<OL TYPE= "i"> (roman numerals, lowercase)

<OL TYPE= "I"> (roman numerals, uppercase)

<OL TYPE= "1"> (standard numbers)

-63-
Remember that when you close <OL TYPE= "I"> you only have to use </OL>

Can you make a list that looks like:

1. First Point

a. Sub-Point

UNORDERED (BULLETED) LISTS

Bulleted list are used when points are important, but in no specific order. HTML
capitalizes on the fact that bulleted lists are in no specific order, and calls them "unordered
lists". The tag for ordered list was <OL>. What do you think the tag for an unordered list is
UL.

<UL>

Other than the difference between <OL> and <UL> ordered and unordered lists work
exactly the same way. Nesting is available in an unordered list. You can even nest an
unordered list in an ordered list.

Go ahead and build this list:

1. First thing.

Bulleted sub-point

In HTML it would look like:

<OL>
<LI> First thing. </LI>
<UL>
<LI> Bulleted sub-point </LI>
</UL>
</OL>

-64-
Frames:

With frames, you can display more than one HTML document in the same browser
window. Each HTML document is called a frame, and each frame is independent of the
others.

The disadvantages of using frames are:

ƒ The web developer must keep track of more HTML documents


ƒ It is difficult to print the entire page

The Frameset Tag

ƒ The <frameset> tag defines how to divide the window into frames
ƒ Each frameset defines a set of rows or columns
ƒ The values of the rows/columns indicate the amount of screen area each
row/column will occupy.

The Frame Tag

ƒ The <frame> tag defines what HTML document to put into each frame

In the example below we have a frameset with two columns. The first column is set to
25% of the width of the browser window. The second column is set to 75% of the width of
the browser window. The HTML document "frame_a.htm" is put into the first column, and
the HTML document "frame_b.htm" is put into the second column:

<frameset cols=”25%,75%”>
<frame src="frame_a.htm">
<frame src="frame_b.htm">
</frameset>

-65-
Note: The frameset column size value can also be set in pixels (cols="200,500"), and one of
the columns can be set to use the remaining space (cols="25%,*").

If a frame has visible borders, the user can resize it by dragging the border. To
prevent a user from doing this, you can add noresize="noresize" to the <frame> tag.

Add the <noframes> tag for browsers that do not support frames.

Important: You cannot use the <body></body> tags together with the
<frameset></frameset> tags! However, if you add a <noframes> tag containing some text for
browsers that do not support frames, you will have to enclose the text in <body></body>
tags.

More Examples

How to use the <no frames> tag

This example demonstrates how to use the <no frames> tag.

Mixed frameset

This example demonstrates how to make a frameset with three documents, and how
to mix them in rows and columns.

Frameset with noresize="noresize"

This example demonstrates the noresize attribute. The frames are not resizable. Move
the mouse over the borders between the frames and notice that you can not move the borders.

-66-
Navigation frame

This example demonstrates how to make a navigation frame. The navigation frame
contains a list of links with the second frame as the target. The file called
"tryhtml_contents.htm" contains three links. The source code of the links:
<a href ="frame_a.htm" target ="showframe">Frame a</a><br> <a href ="frame_b.htm"
target "showframe">Frame b</a><br> <a href ="frame_c.htm" target ="showframe"> Frame
c</a>

The second frame will show the linked document.

Frame Tags

Tag Description

<frameset> Defines a set of frames

<frame> Defines a sub window (a frame)

<noframes> Defines a noframe section for browsers that do not handle frames

<iframe> Defines an inline sub window (frame)

Tables:

Tables are defined with the <table> tag. A table is divided into rows (with the <tr>
tag), and each row is divided into data cells (with the <td> tag). The letters td stands for
"table data," which is the content of a data cell. A data cell can contain text, images, lists,
paragraphs, forms, horizontal rules, tables, etc.

-67-
<table border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>

How it looks in a browser:

row 1, cell 1 row 1, cell 2

row 2, cell 1 row 2, cell 2

Tables and the Border Attribute:

If you do not specify a border attribute the table will be displayed without any
borders. Sometimes this can be useful, but most of the time, you want the borders to show.

To display a table with borders, you will have to use the border attribute:

<table border="1">
<tr>
<td>Row 1, cell 1</td>
<td>Row 1, cell 2</td>
</tr>
</table>

-68-
Headings in a Table:

Headings in a table are defined with the <th> tag.<table border="1">


<tr>
<th>Heading</th>
<th>Another Heading</th>
</tr>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>

How it looks in a browser:

Heading Another Heading

row 1, cell 1 row 1, cell 2

row 2, cell 1 row 2, cell 2

-69-
Empty Cells in a Table:

Table cells with no content are not displayed very well in most browsers.

<table border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td></td>
</tr>
</table>

How it looks in a browser:

row 1, cell 1 row 1, cell 2

row 2, cell 1

Note that the borders around the empty table cell are missing (NB! Mozilla Firefox
displays the border).

To avoid this, add a non-breaking space (&nbsp;) to empty data cells, to make the
borders visible:

<table border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>

-70-
<td>row 2, cell 1</td>
<td>&nbsp;</td>
</tr>
</table>

How it looks in a browser:

row 1, cell 1 row 1, cell 2

row 2, cell 1

The Image Tag and the Src Attribute:

In HTML, images are defined with the <img> tag.

The <img> tag is empty, which means that it contains attributes only and it has no
closing tag.

To display an image on a page, you need to use the src attribute. Src stands for
"source". The value of the src attribute is the URL of the image you want to display on your
page.

The syntax of defining an image:

<img src="url" />

The URL points to the location where the image is stored. An image named "boat.gif"
located in the directory "images" on "www.annauniv.com" has the URL:
http://www.annauniv.com/images/boat.gif.

The browser puts the image where the image tag occurs in the document. If you put
an image tag between two paragraphs, the browser shows the first paragraph, then the image,
and then the second paragraph.

-71-
Image Attributes:

Required Attributes

Src is used to specify the location of the image file.

alt is used to specify the alternative text of the image, which should be a short
description.

Optional Attributes
ƒ longdesc can be used to specify the location (in the form of a URI) of a
description of the image.

ƒ height can be used to define the height of the image (in pixels). This can also be
done with CSS.

ƒ width can be used to define the width of the image (in pixels). This can also be
done with CSS.

The Alt Attribute:


The alt attribute is used to define an "alternate text" for an image. The value of the alt
attribute is an author-defined text:

<img src="boat.gif" alt="Big Boat" />

The "alt" attribute tells the reader what he or she is missing on a page if the browser
can't load images. The browser will then display the alternate text instead of the image. It is a
good practice to include the "alt" attribute for each image on a page, to improve the display
and usefulness of your document for people who have text-only browsers.

-72-
Basic Notes - Useful Tips:

If an HTML file contains ten images - eleven files are required to display the page
right. Loading images take time, so my best advice is: Use images carefully.

Image Tags:

Tag Description

<img> Defines an image

<map> Defines an image map

<area> Defines a clickable area inside an image map

Here is how to use an <EMBED> tag:

<EMBED SRC=your_file.mid AUTOSTART=true WIDTH=144 HEIGHT=60


LOOP=1>

AUTOSTART=true means automatically play sound when document is loaded. This


way, the sound will play as a background sound. You can also set the value to false. The
sound will play when the "play" button is clicked.

LOOP=n This tells browser how many times to play sound. n could be an integer,
true, or false. Setting LOOP=true, browser will continue playing your sound until the stop
button on the console is clicked.

WIDTH and HEIGHT This is how the sound control (console) will be displayed.
Setting them as the given numbers, browsers will display a full console. Setting the width=0
and height=2, the console will not displayed by the browsers. Other values that too small will
cause the browsers display uncompleted image. You might also hide it by placing
HIDDEN=true like this: <EMBED SRC=your_file.mid AUTOSTART=true HIDDEN=true
LOOP=1>

-73-
It's a good idea to give an alternative to people who using browsers that do not
support the embedded sound. Here is what I did on this page:
<embed src="bgsound.mid" hidden="true" autostart="true" loop="1">
<noembed>Your browser doesn't support EMBED, but you can still listen to the background
sound of this page by<a href="bgsound.mid"> clicking here.</a></noembed>

Browsers that do not support EMBED will display the link inside <noembed> tag.

Here is how to use <BGSOUND> tag:

<BGSOUND SRC=your_file.mid LOOP=1>

LOOP can be specified as any positive number, infinite, or -1 which equals infinite.

Tips:

The differences of two browsers brought headaches to us. I would like to correct what
I described here in last version of this page. You'd better use both <EMBED> and
<BGSOUND> tags to make sure that visitors get background sound.

Internet Explorer does not support <EMBED> tag directly, but it does support plugins
that installed by Netscape. The users of Internet Explorer 3.0 or higher will hear the sound
from <EMBED> if they also have Netscape 3.0 installed in their machine. In this case, If
there are both tags in the documents, Explorer take <BGSOUND> tag active but will report
the error of cannot playing sound that resides in the <EMBED> tag. This is a disadvantage of
putting both tags together.

The error tag will be something like:

DEBUG
Unable to start midi
OK

Or

-74-
Midi Error
Unable to start playing midi sound
OK
Anyway, these boxes are not a big deal, users can click "OK" to process to the next
step. I recommend using both tags to make sure that your visitors will surely hear
background sound. If you're planning for giving the option for users to click from the sound
console to hear sound, you only have one alternative -- using <EMBED> tag.

What file formats can I include in my pages?

The <EMBED> tag plays audio files in WAV, AIFF, AU, and MIDI formats.

ƒ MIDI (.mid) format give you a high quality of digital sound.

ƒ WAV (.wav) format was developed for used with Microsoft's Window. You
can record .wav using Windows. The sound quality is not as good as MIDI,
but the file is smaller.

ƒ AU (.au) was developed by Sun. The sound quality is poor, but the file is quite
small, used for recording short speech.

ƒ AIFF (.aiff) was developed by Apple for music and high quality sound.

The most popular is MIDI for music and WAV for short message. If you own a PC
running Windows, you are ready to plug a microphone and start recording.

MIDI Sources:

There are many sources to get MIDI. I would recommend you go to XG Song
Library. This site has many great MIDI songs developed by people at Yamaha Corp., Japan.

Sound Tools:
If you are seriously to put sound on your page, or you're maybe thinking about
developing music site. Here are the tools and the place to visit.

-75-
ƒ RealAudio - RealAudio plays sound before the total file completely loaded.
So, it's fast, but the speed compensates for the moderate sound quality. If you
want to put a sample of song on your web pages, or even audio broadcasting,
RealAudio is a very popular tool.

ƒ Cakewalk Pro Audio 6.0- Professional MIDI editing

ƒ Liquefier Pro- Provides a professional mastering environment to optimally


prepare audio for Internet.

Review Questios:
1. Explain forms and form actions with example?

2. What are the default input commands with example program?

3. Expalin with example:


a. Frames
b. Tables
c. Links
d. Image tags

4. How do you embed sound in your web page?

5. Explain MIDI?

-76-
Chapter 7
WRITING JAVA PROGRAMS BY MAKING USE OF CLASS,
INTERFACE, PACKAGE, ETC FOR THE FOLLOWING

Objectives

ƒ Inheritance and its type


ƒ Understanding Java Package
ƒ Accessing the class members in a Package
ƒ Package Implementation
ƒ Need for Interface
ƒ Java Interface
ƒ Separation of Interface from Implementation
ƒ Using Interface as Type

Inheritance:
Inheritance is the process by which one object acquires the properties of another
object.This is important because it supports the concept of hierarchical classification. As
mentioned earlier, most knowledge is made manageable by hierarchical (that is, topdown)
classifications. For example, a Golden Retriever is part of the classification dog, which in
turn is part of the mammal class, which is under the larger class animal. Without the use of
hierarchies, each object would need to define all of its characteristics explicitly. However, by
use of inheritance, an object need only define those qualities that make it unique within its
class. It can inherit its general attributes from its parent. Thus, it is the inheritance mechanism
that makes it possible for one object to be a specific instance of a more general case. Let's
take a closer look at this process. Most people naturally view the world as made up of objects
that are related to each other in a hierarchical way, such as animals, mammals, and dogs. If
you wanted to describe animals in an abstract way, you would say they have some attributes,
such as size, intelligence, and type of skeletal system. Animals also have certain behavioral

-77-
aspects; they eat, breathe, and sleep. This description of attributes and behavior is the class
definition for animals.

If you wanted to describe a more specific class of animals, such as mammals, they
would have more specific attributes, such as type of teeth, and mammary glands. This is
known as a subclass of animals, where animals are referred to as mammals' superclass. Since
mammals are simply more precisely specified animals, they inherit all of the attributes from
animals. A deeply inherited subclass inherits all of the attributes from each of its ancestors in
the class hierarchy.

Inheritance Basics

To inherit a class, you simply incorporate the definition of one class into another by
using the extends keyword. To see how, let's begin with a short example. The following
program creates a superclass called A and a subclass called B. Notice how the keyword
extends is used to create a subclass of A.

// A simple example of inheritance.// Create a superclass.


class A
{
int i, j;

void showij ()

System.out.println("i and j: " + i + " " + j);


}
}

-78-
// Create a subclass by extending class A.

class B extends A
{
int k;

void showk()

System.out.println("k: " + k);

void sum()
{
System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance
{
public static void main (String args[])
{
A superOb = new A ();
B subOb = new B ();
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
/* The subclass has access to all public members of
its superclass. */
subOb.i = 7;
subOb.j = 8;

-79-
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}

The output from this program is shown here:


Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9
Sum of i, j and k in subOb:
i+j+k: 24

As you can see, the subclass B includes all of the members of its superclass, A. This
is

why subOb can access i and j and call showij( ). Also, inside sum( ), i and j can be
referred to directly, as if they were part of B. Even though A is a superclass for B, it is also a
completely independent, stand-alone class. Being a superclass for a subclass does not mean
that the superclass cannot be used by itself. Further, a subclass can be a superclass for
another subclass.The general form of a class declaration that inherits a superclass is shown
here:

-80-
class subclass-name extends superclass-name
{
// body of class

You can only specify one superclass for any subclass that you create. Java does not
support the inheritance of multiple superclasses into a single subclass. (This differs from
C++, in which you can inherit multiple base classes.) You can, as stated, create a hierarchy of
inheritance in which a subclass becomes a superclass of another subclass. However, no class
can be a superclass of itself.

Member Access and Inheritance

Although a subclass includes all of the members of its superclass, it cannot access
those members of the superclass that have been declared as private. For example, consider
the following simple class hierarchy:

/* In a class hierarchy, private members remain


private to their class.
This program contains an error and will not
compile.
*/
// Create a superclass.
class A
{
int i; // public by default
private int j; // private to A
void setij(int x, int y)
{
i = x;
j = y;
}
}

-81-
// A's j is not accessible here.

class B extends A
{
int total;
void sum()
{
total = i + j; // ERROR, j is not accessible here
}
}

class Access
{
public static void main(String args[])
{
B subOb = new B();
subOb.setij(10, 12);
subOb.sum();
System.out.println("Total is " + subOb.total);
}
}

This program will not compile because the reference to j inside the sum( ) method of
B causes an access violation. Since j is declared as private, it is only accessible by other
members of its own class. Subclasses have no access to it.

-82-
PACKAGE:

In the preceding chapters, the name of each example class was taken from the same
name space. This means that a unique name had to be used for each class to avoid name
collisions. After a while, without some way to manage the name space, you could run out of
convenient, descriptive names for individual classes. You also need some way to be assured
that the name you choose for a class will be reasonably unique and not collide with class
names chosen by other programmers. (Imagine a small group of programmers fighting over
who gets to use the name "Foobar" as a class name. Or, imagine the entire Internet
community arguing over who first named a class "Espresso.") Thankfully, Java provides a
mechanism for partitioning the class name space into more manageable chunks. This
mechanism is the package. The package is both a naming and a visibility control mechanism.
You can define classes inside a package that are not accessible by code outside that package.
You can also define class members that are only exposed to other members of the same
package. This allows your classes to have intimate knowledge of each other, but not expose
that knowledge to the rest of the world.

Defining a Package:

To create a package is quite easy: simply include a package command as the first
statement in a Java source file. Any classes declared within that file will belong to the
specified package. The package statement defines a name space in which classes are stored.
If you omit the package statement, the class names are put into the default package, which
has no name. (This is why you haven't had to worry about packages before now.) While the
default package is fine for short, sample programs, it is inadequate for real applications. Most
of the time, you will define a package for your code.

This is the general form of the package statement:

package pkg;

Here, pkg is the name of the package. For example, the following statement creates a

package called MyPackage.

-83-
package MyPackage;

Java uses file system directories to store packages. For example, the .class files for
any classes you declare to be part of MyPackage must be stored in a directory called
MyPackage. Remember that case is significant, and the directory name must match the
package name exactly. More than one file can include the same package statement. The
package statement simply specifies to which package the classes defined in a file belong. It
does not exclude other classes in other files from being part of that same package. Most real-
world packages are spread across many files. You can create a hierarchy of packages. To do
so, simply separate each package name from the one above it by use of a period. The general
form of a multileveled package statement is shown here:

package pkg1[.pkg2[.pkg3]];
A package hierarchy must be reflected in the file system of your Java development

system. For example, a package declared as

package java.awt.image;

Needs to be stored in java/awt/image, java\\awt\\image, or java:awt:image on your


UNIX, Windows, or Macintosh file system, respectively. Be sure to choose your package
names carefully. You cannot rename a package without renaming the directory in which the
classes are stored.

Package Example:

Keeping the preceding discussion in mind, you can try this simple package:
// A simple package
package MyPack;

-84-
class Balance
{
String name;
double bal;
Balance(String n, double b)
{
name = n;
bal = b;
}
void show()
{
if(bal<0)
System.out.print("—> ");
System.out.println(name + ": $" + bal);
}
}
class AccountBalance
{
public static void main(String args[])
{
Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for(int i=0; i<3; i++) current[i].show();
}
}

Call this file AccountBalance.java, and put it in a directory called MyPack.Next,


compile the file. Make sure that the resulting .class file is also in the MyPack directory.
Then try executing the AccountBalance class, using the following command line:

-85-
java MyPack.AccountBalance

Remember, you will need to be in the directory above MyPack when you execute
this command, or to have your CLASSPATH environmental variable set appropriately. As
explained, AccountBalance is now part of the package MyPack. This means that it cannot
be executed by itself. That is, you cannot use this command line: java AccountBalance

AccountBalance must be qualified with its package name.

Importing package:

Given that packages exist and are a good mechanism for compartmentalizing diverse
classes from each other, it is easy to see why all of the built-in Java classes are stored in
packages. There are no core Java classes in the unnamed default package; all of the standard
classes are stored in some named package. Since classes within packages must be fully
qualified with their package name or names, it could become tedious to type in the long dot-
separated package path name for every class you want to use. For this reason, Java includes
the import statement to bring certain classes, or entire packages, into visibility. Once
imported, a class can be referred to directly, using only its name. The import statement is a
convenience to the programmer and is not technically needed to write a complete Java
program. If you are going to refer to a few dozen classes in your application, however, the
import statement will save a lot of typing. In a Java source file, import statements occur
immediately following the package statement (if it exists) and before any class definitions.
This is the general form of the import statement:

import pkg1[.pkg2].(classname|*);

Here, pkg1 is the name of a top-level package, and pkg2 is the name of a subordinate
package inside the outer package separated by a dot (.). There is no practical limit on the
depth of a package hierarchy, except that imposed by the file system. Finally, you specify
either an explicit classname or a star (*), which indicates that the Java compiler should
import the entire package. This code fragment shows both forms in use:

-86-
import java.util.Date;

import java.io.*;

The stasr form may increase compilation time—especially if you import several large
packages. For this reason it is a good idea to explicitly name the classes that you want to use
rather than importing whole packages. However, the star form has absolutely no effect on the
run-time performance or size of your classes.

import java.lang.*;

If a class with the same name exists in two different packages that you import using
the star form, the compiler will remain silent, unless you try to use one of the classes. In that
case, you will get a compile-time error and have to explicitly name the class specifying its
package. Any place you use a class name, you can use its fully qualified name, which
includes its full package hierarchy. For example, this fragment uses an import statement:

import java.util.*;

class MyDate extends Date


{

The same example without the import statement looks like this:

class MyDate extends java.util.Date


{

-87-
package MyPack;

/* Now, the Balance class, its constructor, and its


show() method are public. This means that they can
be used by non-subclass code outside their package.*/

public class Balance


{
String name;
Double balance;
public Balance(String n, double b)
{
name = n;
bal = b;
}
public void show()
{
if(bal<0)
System.out.print("—> ");
System.out.println(name + ": $" + bal);
}
}

As you can see, the Balance class is now public. Also, its constructor and its show( )
method are public, too. This means that they can be accessed by any type of code outside the
MyPack package. For example, here TestBalance imports MyPack and is then able to make
use of the Balance class:

-88-
import MyPack.*;
class TestBalance
{
public static void main(String args[])
{
/* Because Balance is public, you may use Balance
class and call its constructor. */
Balance test = new Balance("J. J. Jaspers", 99.88);
test.show(); // you may also call show()
}
}
As an experiment, remove the public specifier from the Balance class and then try
compiling TestBalance. As explained, errors will result.

Exception Handling:

Overview

Java has a powerful concept for exception and error handling. An exception is an
error that occurs at runtime. It is either generated by the Java Virtual Machine (VM) in
response to an unexpected condition or it is generated by your code as a result of executing a
throw statement.

Understanding Exceptions

Exceptions generated from runtime are called unchecked exceptions, since it is not
possible for the compiler to determine that your code will handle the exception. Exception
classes that descend from RuntimeException and Error classes are unchecked exceptions.
Examples for RuntimeException are illegal cast operation, inappropriate use of a null pointer,
referencing an out of bounds array element. Error exception classes signal critical problems
that typically cannot be handled by your application. Examples are out of memory error,
stack overflow, failure of the Java VM.

-89-
Thrown exceptions are referred to as checked exceptions. The compiler will confirm
at compile time that the method includes code that might throw an exception. Moreover the
compiler requires the code that calls such a method to include this call within a try block,
and provide an appropriate catch block to catch the exception.

java.lang.Object

|
+--java.lang.Throwable
|
+--java.lang.Exception
| |
| +--java.lang.ClassNotFoundException
| |
| +--java.io.IOException
| | |
| | +--java.io.FileNotFoundException
| |
| +--java.lang.RuntimeException
| |
| +--java.lang.NullPointerException
| |
| +--java.lang.IndexOutOfBoundsException
| |
| +--java.lang.ArrayIndexOutOfBoundsException
|
+--java.lang.Error
|
+--java.lang.VirtualMachineError
|
+--java.lang.OutOfMemoryError

When an (either checked or unchecked) exception is thrown, execution will attempt


to immediately branch to the first catch block whose associated exception class matches the
class or a superclass of the thrown exception. If the exception does not occur within a try
block or the thrown exception is not caught in a matching catch block, execution of the
method immediately terminates and control returns to the invoker of the method, where this
process is repeated. The result is that the exception chain is escalated until a matching catch
block is found. If not, the thread containing the thrown exception is terminated.

-90-
First Example
The following Demo1 class demonstrates the behaviour of exceptions and
applications.
import java.io.*;
class Demo1
{
public static FileInputStream f1(String fileName)
throws FileNotFoundException
{
ileInputStream fis = new FileInputStream(fileName);
System.out.println("f1: File input stream created");
return fis;
}
public static FileInputStream f2(String fileName)
{
FileInputStream fis = null;
try
{
is = new FileInputStream(fileName);
}
catch (FileNotFoundException ex)
{
System.out.println("f2: Oops, FileNotFoundException caught");
}
finally
{
System.out.println("f2: finally block");
}
System.out.println("f2: Returning from f2");
return fis;\
}

-91-
public static void main(String args[])
{
ileInputStream fis1 = null;
FileInputStream fis2 = null;
String fileName = "foo.bar";
// String fileName = null;
System.out.println( "main: Starting " + Demo1.class.getName()
+ " with file name = " + fileName);
// get file input stream 1
try {
fis1 = f1(fileName);
}
catch (FileNotFoundException ex)
{
System.out.println("main: Oops, FileNotFoundException caught");
}
catch (Exception ex)
{
System.out.println("main: Oops, genreal exception caught");
}
// get file input stream 2
fis2 = f2(fileName);
System.out.println("main: " + Demo1.class.getName() + " ended");
}
}

-92-
Compile and run the Demo1 class will generate output as follows (assuming that the
file foo.bar does not exist):

Main : Starting Demo1 with file name = foo.bar


main : Oops, FileNotFoundException caught
f2 : Oops, FileNotFoundException caught
f2 : finally block
f2 : Returning from f2
main : Demo1 ended

The example program tries to create two file input streams. Therefore two methods f1
and f2 are implemented. First, the main program calls f1 method. Because the constructor of
the FileInputStream throws a FileNotFoundException the method f1 must be defined with the
throws FileNotFoundException in the method definition. The thrown exception is not
handled in the method but forwarded to the invoker. Note, that the system output before the
return statement is never executed.

So the invoker, in our example the main program, must catch this exception. The
method f1 is called in a try block. The following catch blocks catch either a
FileNotFoundException or a general Exception. In our example, the exception is caught in
the first catch block and the system output is generated. Since the exception in f1 is caught
and handled, the execution of the program is not terminated.

Second, the example program creates another FileInputStream invoking the f2


method. This method catches the FileNotFoundException, so this exception must not be
forwarded to the invoker. The try ... catch statement is followed by a finally block. This
block is always executed, regardless whether or not an exception occurs within the try block.
This generates the system output in our example. Again, the exception is caught and the
program executes, this generates the system output in f2 and main.

-93-
This was a straight forward example with caught exceptions. What happens with
uncaught exceptions? Change the fileName assignment in the main method: Comment out the
first assignment and activate the second String fileName = null; then compile and execute
Demo1 again. The generated output is:

Main : Starting Demo1 with file name = null


main : Oops, genreal exception caught
f2 : finally block
java.lang.NullPointerException
java.io.FileInputStream Demo1.f2(java.lang.String)
void Demo1.main(java.lang.String[])
Exception in thread main

This time, we try to create two FileInputStream objects using null instead of a file
name. Invoking f1 will generate a NullPointerException which is caught in the main
program. Next f2 is called which could handle only the FileNotFoundException but not a
NullPointerException. Nevertheless the finally block is executed and then the control returns
to the main program. Because there is no try ... catch statement around the call to f2 and no
matching catch block is found, the thread is terminated. Note, that f2 and main can not
execute the system output statements any more.

Second Example

The second example will show some special behaviour in catch and finally blocks:
import java.io.*;
class Demo2 {
public static FileInputStream f1(String fileName)
{
FileInputStream fis = null;
try
{
fis = new FileInputStream(fileName);

-94-
}
catch (FileNotFoundException ex)
{
System.out.println("f1: Oops, FileNotFoundException caught");
throw new Error("f1: File not found");
}
System.out.println("f1: File input stream created");
return fis;
}
public static FileInputStream f2(String fileName)
{
FileInputStream fis = null;
try
{
fis = new FileInputStream(fileName);
}
catch (FileNotFoundException ex)
{
System.out.println("f2: Oops, FileNotFoundException caught");
return fis;
}
finally
{
System.out.println("f2: finally block");
return fis;
}
// Compiler error: statement not reacheable
// System.out.println("f2: Returning from f2");
// return fis;
}

-95-
public static void main(String args[])
{
FileInputStream fis1 = null;
FileInputStream fis2 = null;
String fileName = "foo.bar";
// String fileName = null;
System.out.println( "main: Starting " + Demo2.class.getName()
+ " with file name = " + fileName);
// get file input stream 1
try {
fis1 = f1(fileName);
}
catch (Exception ex)
{
System.out.println("main: Oops, general exception caught");
}
catch (Throwable th)
{
System.out.println("main: Oops, throwable object caught");
}
// get file input stream 2
fis2 = f2(fileName);
System.out.println("main: " + Demo2.class.getName() + " ended");
}
}
}

Compile and run Demo2 will generate the following output:

Main : Starting Demo2 with file name = foo.bar


f1 : Oops, FileNotFoundException caught
main : Oops, throwable object caught

-96-
f2 : Oops, FileNotFoundException caught
f2 : finally block
main : Demo2 ended
Again f1 is called to get a new FileInputStream with a given file name. The thrown
FileNotFoundException in f1 is caught in the following catch block. But this time an Error is
thrown so that the method is terminated immediately. Because Error is not a subclass of
Exception the first catch block does not match. But the second catch block matches all
throwable objects.

Calling f2 method will generate a FileNotFoundException too. This exception is


caught in f2 and the method returns directly from the catch block. Remember, that the finally
block is executed regardless whether an exception is caught or not.

In both methods f1 and f2, the FileNotFoundException is caught and handled, so the
program can terminate normally. Change again the fileName assignment in the main method
and compile and run Demo2 again:

Main : Starting Demo2 with file name = null


main : Oops, general exception caught
f2 : finally block
main: Demo2 ended

The NullPointerException thrown in f1 is not caught, so the exception is forwarded to


the invoker. The main program catches Exception, which is a superclass of the thrown
exception.

The call to f2 method seems to work fine even the thrown NullPointerException is not
caught directly. Note, that the finally block is executed regardless whether an exception is
caught or not. Since the finally block terminates with a return statement, the program
executes without failure. So be careful returning within finally blocks, this breaks the
exception chaining to the invoker and it simulates error free program execution.

-97-
Summary
ƒ Normal program execution is immediately branched when an exception is
thrown.

ƒ Checked exceptions must be caught or forwarded. This can be done in a try ...
catch statement or by defining the exception in the method definition.

ƒ The exception is caught by the first catch block whose associated exception
class matches the class or a superclass of the thrown exception.

ƒ If no matching catch block is found in the exception chain, the thread


containing the thrown exception is terminated.

ƒ The finally block after a try ... catch statement is executed regardless whether
an exception is caught or not.

ƒ Returning within a finally block breaks the exception chain to the invoker
even for uncaught exceptions.

Review Questions:
1. Explain inheritance?
2. Types of inheritance with example?
3. Explain polymorphism?
4. Explain Overloading and overridding with example?
5. Explain use of package with example?
6. How do you create Jar file?
7. How do you Extracting the Contents of a JAR File?
8. Exceptions in java and its type?
9. Write a java program for users define exceptions?

-98-
Chapter 8
WRITING WINDOWS BASED GUI APPLICATION USING
FRAMES AND APPLETS SUCH AS CALCULATOR APPLICATION,
FAHRENHEIT TO CENTOGRADE CONVERSION

Objectives

ƒ Applet basics and need for Applet


ƒ Understand JDK process
ƒ Using Frames and Menu in Applet
ƒ Studying AWT

Applet:

What is Java Applet:

ƒ Java is a general purpose programming language.

ƒ A Java program is created as a text file with .java extension.

ƒ It is compiled into one or more files of bytecodes with .class extension.

ƒ Bytecodes are a set of instructions similar to machine code of a specific machine


but it can be run on any machine that has a Java Virtual Machine (JVM). JVM
interprets bytecodes.

ƒ JVM was first implemented on Sparc/Solaris and PC/Win32. Now ported to many
other platforms.

ƒ Java applets are Java programs that are retrieved and executed by web browsers
through the JVM under tight secure environment.

ƒ Web browsers retrieve Java applets according to following tags in the web pages:

-99-
<applet code=ResPlotApplet.class width=600 height=500> deprecated or the new more\
general,
<object codetype="application/java" classid="java:ResPlotApplet.class" width=600
height=500>
ƒ <param> are used to specify parameters for the applet. For example,

<APPLET CODE="Animator.class"

WIDTH="aNumber" -- the width (in pixels) of the widest frame

HEIGHT="aNumber"> -- the height (in pixels) of the tallest frame

<PARAM NAME="IMAGESOURCE"

VALUE="aDirectory"> -- the directory that has the animation frames (gif, jpg)

ƒ All other types of java programs are called Java applications.

ƒ Examples:

ƒ Network Restoration Applet: User specifies two end node of a failed link. The
applet retrieves the simulation results of two network restoration algorithms
(twoprong and rreact) in two corresponding files at original web server site, and
plot the results.

ƒ SUN Java demos:


o MoleculeViewer
o SimpleGraph
o SortDemo
o BarChart
o Animator
o JumpingBox

-100-
ƒ When a Java applet is downloaded, the bytecode verifier of the JVM verifies tosee
if it contains bytecodes that open, read, write to local disk.
ƒ Java applet can open new window but they have Java log to prevent them from
being disguised as system window (for stealing password).
ƒ Java applet is not allowed to connect back to other servers except that hosts itself.
ƒ This secure execution environment is called sand box model.
ƒ JDK 1.1 extends this tight security with digitally signed applet using jar file.
ƒ More detailed fine grained security levels are planned for future release.

Basic Steps:

ƒ All Applet source code starts with

import java.applet.*;
and other import statements for packages used in the applet such as
import java.awt.*; import java.io.*; import java.lang.*; import java.net.*; import
java.util.*;

ƒ It then starts with a class definition like:

public class Chart extends java.applet.Applet


{
// followed by a list of variables or objects declaration //
Button b1 = new Button("play");
Button b2 = new Button("stop");
Button b3 = new Button("resume");
TextField tf = new TextField("Message here", 50);
TextArea ta = new TextArea("please wait...", 10, 40);
}

ƒ The main class contains four basic Applet methods:

-101-
public void init()
{
// for any initialization code performed during loading time of the applet
// such as loading graphics, initialize variables, creating objects
// add() is used to insert the objects into the area allocated for the applet
add(b1); add(b2); add(b3); add(tf); add(ta);
}
public void start()
{
// implement the main action of the applet behavior
// it is also called by browser to restart after it was stopped.
}
public void stop()
{
// stop an applet's execution but leaves resources intact so it can restart.
}
public void destroy()
{
// release all its resources
// typically happens when the user leaves the page containing the applet.
}
ƒ Many Applet only needs to implement init()

ƒ For control and user input, Button, TextField, TextArea, Canvas objects are
created in init() and special method action() is called when event happens

-102-
public boolean action(Event e, Object o)
{
if (e.target instanceof Button)
{
String s = (String) o;
if (s.equals("play") {
tf.setText("play button is pushed");
}
else if (s.equal("stop")
{
ta.setText("stop button is pushed");
}
else
{
ta.appendText("resume button is pushed");
}
return true;
}
return false;
}
ƒ Try this basic example.

Abstract Window Toolkit (AWT):

Using AWT Components:


http://owl.uccs.edu/~cs301/java/awt/oldui/components/using.html
Layout the Components in a container:
http://owl.uccs.edu/~cs301/java/awt/oldui/layout/index.html

-103-
Note that there are new GUI packages such swing and Java 2D graphics
recommended by Netscape. They are great for making Java applications with GUI, but there
are still a lot of browsers do not support that. They require JDK1.2 compatible viewer or Java
plug in.

"Java Plug-in software enables enterprise customers to direct Java applets or


JavaBeansTM components on their intranet web pages to run using Sun's Java Runtime
Environment (JRE), instead of the browser's default Java runtime. This enables an enterprise
to deploy Java applets that take full advantage of the latest capabilities and features of the
Java platform and be assured that they will run reliably and consistently.

Using JFC/SWING to create GUI

The swing components in Java Foundation Classes (JFC) are the new package in JDK1.1
and JDK1.2 for supporting GUI design in Java applications and applets.

It provides much more features to those of AWT. For examples,

ƒ allow images on buttons/labels,

ƒ dynamically change of borders,

ƒ component can be round,

ƒ specify look and feels (Java, Windows, CDE/Motif).

ƒ wider selection of components

ƒ not using native code (more portable).

-104-
Example programs using java class and predefined methods:

In this program we will show you how to draw the different types of colorful
shapes.This example show the different types of colorful shapes like line, circle and the
rectangle. It also displays the different - different colors such as red, magenta and yellow to
be used in those shapes.In this program there are several types of methods have been used to
fill or set the color of line, text, circle background and rectangle background. These are given
just ahead :

Graphics.setColor():

This is the setColor() method which is the Graphics class method imported by the
java.awt.*; package. This method sets the color for the object by specified color. Here is the
syntax of the setColor() method :

g.setColor(Color.color_name);

Graphics.fillOval():

This is the fillOval() method used to fill the color inside the oval by specified color.
Here is the syntax of the fillColor() method :

g.fillColor(Color.color_name);

Graphics.fillRect():

This is the fillRect() method used to fill the color inside the rectangle by specified
color. Here is the syntax of the fillRect() method :

g.fillRect(int X_coordinate, int Y_coordinate, int Wdth, int height)

-105-
Here is the java code of the program:

import java.applet.*;
import java.awt.*;

public class ShapColor extends Applet


{
int x=300,y=100,r=50;

public void paint(Graphics g)


{
g.setColor(Color.red); //Drawing line color is red
g.drawLine(3,300,200,10);
g.setColor(Color.magenta);
g.drawString("Line",100,100);

g.drawOval(x-r,y-r,100,100);
g.setColor(Color.yellow); //Fill the yellow color in circle
g.fillOval( x-r,y-r, 100, 100 );
g.setColor(Color.magenta);
g.drawString("Circle",275,100);

g.drawRect(400,50,200,100);
g.setColor(Color.yellow); //Fill the yellow color in rectangel
g.fillRect( 400, 50, 200, 100 );
g.setColor(Color.magenta);
g.drawString("Rectangel",450,100);
}
}

-106-
Here is the HTML code of the program:
<HTML>
<HEAD>
</HEAD>
<BODY>
<div align="center">
<APPLET ALIGN = "CENTER" CODE = "ShapColor.class" WIDTH = "800">
HEIGHT = "500">\
</APPLET>
</div>
</BODY>
</HTML>

Exmaple Programs:

Calculator Application:

import java.util.StringTokenizer;
import java.util.Hashtable;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Panel;
import java.awt.Frame;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;

-107-
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
import java.applet.Applet;

// Converts the Calculator application to run either as an application


// or as an applet by creating a "shared" panel -- a panel that will
// be shared by the application's Frame and by the Applet. The panel
// will be the first component placed on each. All other components are
// placed on the shared panel.

public class CalculatorE extends Applet


{
private boolean isApplet = false;
private boolean lastKeyWasFunction = true;
private double displayHold = 0;
private Frame f;
private Hashtable theKeys = new Hashtable();
private Label display;
private Panel pMain;
private String lastFunction = "";
private Toolkit tk = null;
private KeyListener keyListener = new KeyListener();

public static void main(String[] args)


{
CalculatorE calc = new CalculatorE();
calc.isApplet = false;
calc.tk = Toolkit.getDefaultToolkit();
calc.f = new Frame("Calculator");
// add Window closer
calc.f.addWindowListener(new WindowAdapter() {

-108-
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
// close anon inner class
}
);

// add Key Listener to frame


calc.f.addKeyListener(calc.keyListener);
// create panel which will be shared by Frame and Applet
calc.pMain = new Panel();
calc.pMain.setLayout(new BorderLayout());
calc.pMain.setBackground(Color.lightGray);
calc.pMain.addKeyListener(calc.keyListener);
// add shared panel to Frame
calc.f.add(calc.pMain, BorderLayout.CENTER);
calc.makeGUI();
}

public void init()


{
isApplet = true;
setLayout(new BorderLayout());
setBackground(Color.lightGray);
this.addKeyListener(keyListener);
// create the shared panel
pMain = new Panel();
pMain.setLayout(new BorderLayout());
pMain.setBackground(Color.lightGray);
pMain.addKeyListener(keyListener);
// add the shared panel to the applet

-109-
add(pMain, BorderLayout.CENTER);
makeGUI();
}

private void makeGUI()


{
// add display
display = new Label("0", Label.RIGHT);
pMain.add(display, BorderLayout.NORTH);
Panel numPanel = new Panel();
numPanel.setBackground(pMain.getBackground());
numPanel.addKeyListener(keyListener);
numPanel.setLayout(new GridLayout(4, 3));
Panel funcPanel = new Panel();
funcPanel.setBackground(numPanel.getBackground());
funcPanel.addKeyListener(keyListener);
funcPanel.setLayout(new GridLayout(4, 2));
// create number buttons
if (true)
{
ButtonListener bl = new ButtonListener(0);
for (int i = 0; i < 12; i++) {
Button b = new Button("" + i);
b.setForeground(Color.blue);
b.addActionListener(bl);
b.addKeyListener(keyListener);
// handle blank and '.' buttons
if (i == 10)
{
b.setLabel("+/-");
}

-110-
if (i == 11)
{
b.setLabel(".");
}
theKeys.put(b.getLabel(), b);
}
}

// create function keys


if (true)
{
ButtonListener bl = new ButtonListener(1);
StringTokenizer st = new StringTokenizer("/ C * CE + none - =", " ");
while (st.hasMoreTokens())
{
Button b = new Button(st.nextToken());
b.setForeground(Color.red);
b.addActionListener(bl);
b.addKeyListener(keyListener);
// disable unneded 'b' key
if (b.getLabel().equals("none"))
{
b.setVisible(false);
}
// add the key to theKeys array
theKeys.put(b.getLabel(), b);
// add the key to the function panel
funcPanel.add(b);
}
}

-111-
// place number buttons on numPanel
for (int i = 1; i <= 9; i++)
{
numPanel.add((Button)theKeys.get("" + i));
}
numPanel.add((Button)theKeys.get("+/-"));
numPanel.add((Button)theKeys.get("0"));
numPanel.add((Button)theKeys.get("."));
pMain.add(numPanel, BorderLayout.CENTER);
pMain.add(funcPanel, BorderLayout.EAST);

if (!isApplet)
{
f.pack();
Dimension screensize = tk.getScreenSize();
// set size
f.setSize(screensize.width / 5, screensize.height / 4);
// center form
f.setLocation((screensize.width - f.getWidth()) / 2,
screensize.height - f.getHeight()) / 2);
f.setResizable(false);
}
pMain.setVisible(true);
setVisible(true);

if (isApplet == false)
{
f.setVisible(true);
}
}

-112-
private double getDisplayValue()
{
double d = 0.0;
String s = display.getText();
try
{
// Double.parseDouble doesn't work in 1.1v applets
d = Double.valueOf(s).doubleValue();
}
catch (NumberFormatException e)
{
d = 0.0;
}
return d;
}

private void handleFuncKey(Button b)


{
String lbl = b.getLabel();

if ("=CCE".indexOf(lbl) > -1)


{
if (lbl.equals("C"))
{
displayHold = 0d;
lastFunction = "";
display.setText("0");
}
if (lbl.equals("CE"))
{
display.setText("0");

-113-
lastKeyWasFunction = true;
return;
}
if (lbl.equals("=")) {}
}
if (lastFunction.equals("+"))
{
display.setText("" + (displayHold + getDisplayValue()));
}
if (lastFunction.equals("-"))
{
display.setText("" + (displayHold - getDisplayValue()));
}
if (lastFunction.equals("*"))
{
display.setText("" + (displayHold * getDisplayValue()));
}
if (lastFunction.equals("/"))
{
String r;
try
{
r = "" + (displayHold / getDisplayValue());
}
catch (ArithmeticException ae)
{
r = "divison error";
displayHold = 0d;
}
display.setText(r);
}

-114-
lastKeyWasFunction = true;
lastFunction = lbl;
displayHold = getDisplayValue();
}

private void handleNumKey(Button b)


{
String lbl = b.getLabel();

if (lastKeyWasFunction)
{
display.setText("");
}

if (lbl.equals(".") || lbl.equals("+/-"))
{
if (lbl.equals("."))
{
if (display.getText().indexOf(".") == -1)
{
display.setText(display.getText() + ".");
}
}
else
{
display.setText("" + getDisplayValue() * -1);
}
}

-115-
else
{
display.setText(display.getText() + lbl);
}
lastKeyWasFunction = false;
}

private class ButtonListener implements ActionListener


{
// buttonType == 0 : number key listener
// buttonType == 1 : function key listener
private int listenerType = 0;

ButtonListener(int listenerType)
{
this.listenerType = listenerType;
}

public void actionPerformed(ActionEvent e)


{
Button b = (Button)e.getSource();

if (listenerType == 0)
{
handleNumKey(b);
}
else
{
handleFuncKey(b);
}
}
}

-116-
private class KeyListener extends KeyAdapter
{
// better to use Keystroke class, but it's not supported in v1.1
private String lastKey = "";

public void keyPressed(KeyEvent e)


{
Button b = null;
String targ = "NUMPAD";
String key = e.getKeyText(e.getKeyCode());
key = key.toUpperCase();
if (key.indexOf(targ) > -1)
{
key = key.substring(key.indexOf(targ) + 1 + targ.length());
}

// handle SHIFTed keys


if (lastKey.equals("SHIFT"))
{
if (key.equals("8"))
{
key = "*";
}
if (key.equals("="))
{
key = "+";
}
}

-117-
if (key.equals("ENTER"))
{
key = "=";
}
if (key.equals("MINUS"))
{
key = "-";
}
b = (Button)theKeys.get(key);
if (b != null)
{
if ("0123456789.".indexOf(key) > -1)
{
handleNumKey(b);
}
else
{
handleFuncKey(b);
}
}
lastKey = key;
}
}
}

-118-
Fahrenheit to Celsius Conversion:

package temperature;
import java.util.Scanner;
/**
* An application

which will convert from Fahrenheit to Celsius or from Celsius


* to Fahrenheit.*/

public class Converter


{
/**
* The entry point of the application.
* @param args No arguments expected.*/

public static void main(String[] args)


{
int choice;
int temp1;
int temp2;
String from;
String to;
Scanner kb = new Scanner(System.in);
do\
{
choice = -1;
System.out.println("\nConvert temperature:\n");
System.out.println("\t1 - Convert from Fahrenheit to Celsius");
System.out.println("\t2 - Convert from Celsius to Fahrenheit");
System.out.println("\t3 - Exit");
choice = kb.nextInt();

-119-
switch (choice)
{
case 1:
System.out.println("\nEnter the temperature in Fahrenheit:");
temp1 = kb.nextInt();
temp2 = convertToCelsius(temp1);
from = "Fahrenheit";
to = "Celsius";
break;

case 2:
System.out.println("\nEnter the temperature in Celsius:");
temp1 = kb.nextInt();
temp2 = convertToFahrenheit(temp1);
from = "Celsius";
to = "Fahrenheit";
break;
default:
continue; // no input, no output
}
System.out.print("\n");
System.out.print(temp1);
System.out.print(' ');
System.out.print(from);
System.out.print(" = ");
System.out.print(temp2);
System.out.print(' ');
System.out.print(to);
System.out.print('\n');
}

-120-
while (choice != 3);
}
/**
* Converts from Fahrenheit to Celsius
* @param temp The temperature in Fahrenheit
* @return The temperature in Celsius
*/
private static int convertToCelsius(int temp)
{
return (temp - 32) / 9 * 5;
}

/**
* Converts from Celsius to Fahrenheit
* @param temp The temperature in Celsius
* @return The temperature in Fahrenheit
*/
private static int convertToFahrenheit(int temp)
{
return (9 * temp) / 5 + 32;
}
}
Review Questions:
1. Explain Applet in java?

2. What are the basic steps for using Applet?

3. Use of Applet in java?

4. Explain JDK?

5. Explain AWT?

-121-
Chapter 9
APPLICATION OF THREADS EXAMPLES

Objectives

ƒ Understanding Threads
ƒ Thread_Ex Class
ƒ Synchronization
ƒ Locks and Grained Locks
ƒ Semaphores

Overview of Threads

Process

A process is an instance of a computer program that is executed sequentially. It is a


collection of instructions which are executed simultaneously at the rum time. Thus several
processes may be associated with the same program. For example, to check the spelling is a
single process in the Word Processor program and you can also use other processes like
printing, formatting, drawing, etc. associated with this program.

Thread

A thread is a lightweight process which exists within a program and executed to


perform a special task. Several threads of execution may be associated with a single process.
Thus a process that has only one thread is referred to as a single-threaded process, while a
process with multiple threads is referred to as a multi-threaded process.

In Java Programming language, thread is a sequential path of code execution within a


program. Each thread has its own local variables, program counter and lifetime. In single
threaded runtime environment, operations are executes sequentially i.e. next operation can
execute only when the previous one is complete. It exists in a common memory space and

-122-
can share both data and code of a program. Threading concept is very important in Java
through which we can increase the speed of any application. You can see diagram shown
below in which a thread is executed along with its several operations with in a single
process.

Main Thread

When any standalone application is running, it firstly execute the main() method runs
in a one thread, called the main thread. If no other threads are created by the main thread,
then program terminates when the main() method complete its execution. The main thread
creates some other threads called child threads. The main() method execution can finish, but
the program will keep running until the all threads have complete its execution.

Life Cycle of A Thread

When you are programming with threads, understanding the life cycle of thread is
very valuable. While a thread is alive, it is in one of several states. By invoking
start () method, it doesn’t mean that the thread has access to CPU and start
executing straight away. Several factors determine how it will proceed.

-123-
Different states of a thread are :

New state – After the creations of Thread instance the thread is in this state but
before the start() method invocation. At this point, the thread is considered not alive.

Runnable (Ready-to-run) state – A thread start its life from Runnable state. A
thread first enters runnable state after the invoking of start() method but a thread can return to
this state after either running, waiting, sleeping or coming back from blocked state also. On
this state a thread is waiting for a turn on the processor.
Running state – A thread is in running state that means the thread is currently
executing. There are several ways to enter in Runnable state but there is only one way to
enter in Running state: the scheduler select a thread from runnable pool.

Dead state – A thread can be considered dead when its run() method completes. If
any thread comes on this state that means it cannot ever run again.

Blocked - A thread can enter in this state because of waiting the resources that are
hold by another thread.

-124-
Different states implementing Multiple-Threads are:

As we have seen different states that may be occur with the single thread. A running
thread can enter to any non-runnable state, depending on the circumstances. A thread cannot
enters directly to the running state from non-runnable state, firstly it goes to runnable state.
Now lets understand the some non-runnable states which may be occur handling the
multithreads.

Sleeping – On this state, the thread is still alive but it is not runnable, it might be
return to runnable state later, if a particular event occurs. On this state a thread sleeps for a
specified amount of time. You can use the method sleep( ) to stop the running state of a
thread.

static void sleep(long millisecond) throws InterruptedException

Waiting for Notification – A thread waits for notification from another thread. The
thread sends back to runnable state after sending notification from another thread.

final void wait(long timeout) throws InterruptedException


final void wait(long timeout, int nanos) throws InterruptedException
final void wait() throws InterruptedException

-125-
Blocked on I/O – The thread waits for completion of blocking operation. A thread
can enteron this state because of waiting I/O resource. In that case the thread sends back to
runnable state after availability of resources.

Blocked for joint completion – The thread can come on this state because of waiting
the completion of another thread.

Blocked for lock acquisition – The thread can come on this state because of waiting
to acquire the lock of an object.

Methods that can be applied apply on a Thread:


Some Important Methods defined in java.lang.Thread are shown in the table:

Method Return Type Description


currentThread( Returns an object reference to the thread in
Thread
) which it is invoked.
Retrieve the name of the thread object or
getName( ) String
instance.
start( ) void Start the thread by calling its run method.
This method is the entry point to execute thread,
run( ) void
like the main method for applications.
Suspends a thread for a specified amount of time
sleep( ) void
(in milliseconds).
This method is used to determine the thread is
isAlive( ) boolean
running or not.
This method returns the number of active
activeCount( ) int threads in a particular thread group and all its
subgroups.
The method interrupt the threads on which it is
interrupt( ) void
invoked.

-126-
By invoking this method the current thread
yield( ) void pause its execution temporarily and allow other
threads to execute.
This method and join(long millisec) Throws
InterruptedException. These two methods are
join( ) Void invoked on a thread. These are not returned until
either the thread has completed or it is timed out
respectively.

Thread Creation

In Java, an object of the Thread class can represent a thread. Thread can be
implemented through any one of two ways:

Extending the java.lang.Thread Class

Implementing the java.lang.Runnable Interface

I. Extending the java.lang.Thread Class

For creating a thread a class have to extend the Thread Class. For creating a thread by
this procedure you have to follow these steps:

-127-
Extend the java.lang.Thread Class.

Override the run( ) method in the subclass from the Thread class to define the code
executed by the thread.

Create an instance of this subclass. This subclass may call a Thread class constructor
by subclass constructor.

Invoke the start( ) method on the instance of the class to make the thread eligible for
running.

The following program demonstrates a single thread creation extending the "Thread"
Class:

class MyThread extends Thread{

String s=null;

MyThread(String s1){
s=s1;
start();
}
public void run(){
System.out.println(s);
}
}
public class RunThread{
public static void main(String args[]){

MyThread m1=new MyThread("Thread started....");


}
}

-128-
Output of the Program is :

C:\j2se6\thread>javac
RunThread.java

C:\j2se6\thread>java
RunThread
Thread started....

II. Implementing the java.lang.Runnable Interface

The procedure for creating threads by implementing the Runnable Interface is as


follows:

A Class implements the Runnable Interface, override the run() method to define the
code executed by thread. An object of this class is Runnable Object.

Create an object of Thread Class by passing a Runnable object as argument.

Invoke the start( ) method on the instance of the Thread class.

The following program demonstrates the thread creation implenting the Runnable
interface:
class MyThread1 implements Runnable{
Thread t;
String s=null;

MyThread1(String s1){
s=s1;
t=new Thread(this);
t.start();
}

-129-
public void run()
{
System.out.println(s);
}
}
public class RunableThread{
public static void main(String args[]){
MyThread1 m1=new MyThread1("Thread started....");
}
}

However, this program returns the output same as of the output generated through the
previous program.

Output of the Program is:

C:\j2se6\thread>javac
RunableThread.java

C:\j2se6\thread>java
RunableThread
Thread started....

There are two reasons for implementing a Runnable interface preferable to extending
the Thread Class:

If you extend the Thread Class, that means that subclass cannot extend any other
Class, but if you implement Runnable interface then you can do this.

The class implementing the Runnable interface can avoid the full overhead of
Thread class which can be excessive.

-130-
join() & isAlive() methods:
The following program demonstrates the join() & isAlive() methods:

class DemoAlive extends Thread {


int value;

public DemoAlive(String str){


super(str);
value=0;
start();
}

public void run(){


try{
while (value < 5){
System.out.println(getName() + ": " + (value++));
Thread.sleep(250);
}
} catch (Exception e) {}
System.out.println("Exit from thread: " + getName());
}
}

public class DemoJoin{

public static void main(String[] args){


DemoAlive da = new DemoAlive("Thread a");
DemoAlive db = new DemoAlive("Thread b");
try{
System.out.println("Wait for the child threads to finish.");
da.join();

if (!da.isAlive())
System.out.println("Thread A not alive.");

db.join();

if (!db.isAlive())
System.out.println("Thread B not alive.");
} catch (Exception e) { }
System.out.println("Exit from Main Thread.");
}
}

-131-
Output of this program is:

C:\j2se6\thread>javac
DemoJoin.java

C:\j2se6\thread>java
DemoJoin
Wait for the child
threads to finish.
Thread a: 0
Thread b: 0
Thread a: 1
Thread b: 1
Thread a: 2
Thread b: 2
Thread a: 3
Thread b: 3
Thread a: 4
Thread b: 4
Exit from thread: Thread
a
Thread A not alive.
Exit from thread: Thread
b
Thread B not alive.
Exit from Main Thread.

Thread Constructors
Several constructors are available for creating new Thread instances.

Thread()
Thread(String)
Thread(Runnable)
Thread(Runnable,String)
Thread(ThreadGroup,String)

-132-
Thread(ThreadGroup,Runnable)

Thread(ThreadGroup,Runnable,String)

Thread(ThreadGroup, Runnable, String, long)

ThreadGroup– All threads belongs to an instance of the ThreadGroup Class.


ThreadGroup is used to represent a group of threads. ThreadGroups can be shown in a
hierarchical manner. There is only one root ThreadGroup that contains all other thread and
groups and each subgroups can contain other groups and threads. All thread have only one
thread group. And all thread groups (except the root thread group) belongs to exactly one
parent thread group. Threads can access only belonging thread group.

When a new ThreadGroup is created, it is added as a member of existing


ThreadGroup.

If a thread x in group1, and executes the code:

ThreadGroup group2=new ThreadGroup(“group2”);

Then the newly formed group2 comes under group1. If you want a parent group
other than default then you have to specify the parent group at the time of creation.

ThreadGroup group2=new ThreadGroup(group2,“group3”);

Then newly formed group3 comes under the group2.

Some important methods are:

getName() – This method is used to retrieve the name of particular group.

ThreadGroup g=new
ThreadGroup(“RoseIndia”);
String gname=g.getName();

-133-
getParent() – This method is used to retrieve the name of parent threadgroup of sub group.

ThreadGroup
group=group3.getParent();

activeGroupCount() – This method returns the number of active thread group in a particular
thread group and all its subgroups.

int
size=group.activeGroupCount();

getThreadGroup() – This method is used to know the thread is belong to which thread
group.

ThreadGroup
group=threadx.getThreadGroup();

Multithreading in Java
Introduction

So far you have learned about a single thread. Lets us know about the concept of
multithreading and learn the implementation of it. But before that, lets be aware from the
multitasking.

Multitasking:
Multitasking allow to execute more than one tasks at the same time, a task being a
program. In multitasking only one CPU is involved but it can switches from one program to
another program so quickly that's why it gives the appearance of executing all of the
programs at the same time. Multitasking allow processes (i.e. programs) to run concurrently
on the program. For Example running the spreadsheet program and you are working with
word processor also.Multitasking is running heavyweight processes by a single OS.

-134-
Multithreading :

Multithreading is a technique that allows a program or a process to execute many


tasks concurrently (at the same time and parallel). It allows a process to run its tasks in
parallel mode on a single processor system

In the multithreading concept, several multiple lightweight processes are run in a


single process/task or program by a single processor. For Example, When you use a word
processor you perform a many different tasks such as printing, spell checking and so on.
Multithreaded software treats each process as a separate program.
In Java, the Java Virtual Machine (JVM) allows an application to have multiple
threads of execution running concurrently. It allows a program to be more responsible
to the user. When a program contains multiple threads then the CPU can
switch between the two threads to execute them at the same time.
For example, look at the diagram shown as:

In this diagram, two threads are being executed having more than one task. The task
of each thread is switched to the task of another thread.

-135-
Advantages of multithreading over multitasking:

Reduces the computation time.

Improves performance of an application.

Threads share the same address space so it saves the memory.

Context switching between threads is usually less expensive than between


processes.

Cost of communication between threads is relatively low.

Different states implementing Multiple-Threads are:

As we have seen different states that may be occur with the single thread. A running
thread can enter to any non-runnable state, depending on the circumstances. A thread cannot
enters directly to the running state from non-runnable state, firstly it goes to runnable state.
Now lets understand the some non-runnable states which may be occur handling the
multithreads.

Sleeping – On this state, the thread is still alive but it is not runnable, it might be
return to runnable state later, if a particular event occurs. On this state a thread sleeps for a
specified amount of time. You can use the method sleep( ) to stop the running state of a
thread.

-136-
Static void sleep(long millisecond) throws InterruptedException

Waiting for Notification – A thread waits for notification from another thread. The
thread sends back to runnable state after sending notification from another thread.

final void wait(long timeout) throws InterruptedException


final void wait(long timeout, int nanos) throws InterruptedException
final void wait() throws InterruptedException

Blocked on I/O – The thread waits for completion of blocking operation. A thread
can enter on this state because of waiting I/O resource. In that case the thread sends back to
runnable state after availability of resources.

Blocked for joint completion – The thread can come on this state because of waiting
the completion of another thread.

Blocked for lock acquisition – The thread can come on this state because of waiting
to acquire the lock of an object.

Creation of Multiple Threads

Like creation of a single thread, You can also create more than one thread
(multithreads) in a program using class Thread or implementing interface Runnable.

Lets see an example having the implementation of the multithreads by extending


Thread Class:

-137-
class MyThread extends Thread{
MyThread(String s){
super(s);
start();
}
public void run(){
for(int i=0;i<5;i++){
System.out.println("Thread Name :"
+Thread.currentThread().getName());
try{
Thread.sleep(1000);
}catch(Exception e){}
}
}
}
public class MultiThread1{
public static void main(String args[]){
System.out.println("Thread Name :"
+Thread.currentThread().getName());
MyThread m1=new MyThread("My Thread 1");
MyThread m2=new MyThread("My Thread 2");
}
}

-138-
Output of the Program
C:\nisha>javac
MultiThread1.java

C:\nisha>java
MultiThread1
Thread Name :main
Thread Name :My Thread
1
Thread Name :My Thread
2
Thread Name :My Thread
1
Thread Name :My Thread
2
Thread Name :My Thread
1
Thread Name :My Thread
2
Thread Name :My Thread
1
Thread Name :My Thread
2
Thread Name :My Thread
1
Thread Name :My Thread
2

-139-
In this program, two threads are created along with the "main" thread. The
currentThread() method of the Thread class returns a reference to the currently executing
thread and the getName( ) method returns the name of the thread. The sleep( ) method
pauses execution of the current thread for 1000 milliseconds(1 second) and switches to the
another threads to execute it. At the time of execution of the program, both threads are
registered with the thread scheduler and the CPU scheduler executes them one by one.

-140-
Now, lets create the same program implenting the Runnable interface:

class MyThread1 implements Runnable{


Thread t;
MyThread1(String s) {
t=new Thread(this,s);
t.start();
}

public void run() {


for(int i=0;i<5;i++) {
System.out.println("Thread Name :"+Thread.currentThread().getName());
try {
Thread.sleep(1000);
}catch(Exception e){}
}
}
}

public class RunnableThread1{


public static void main(String args[]) {
System.out.println("Thread Name :"+Thread.currentThread().getName());
MyThread1 m1=new MyThread1("My Thread 1");
MyThread1 m2=new MyThread1("My Thread 2");
}
}

-141-
Output of the program:

C:\nisha>javac RunnableThread1.java

C:\nisha>java RunnableThread1
Thread Name :main
Thread Name :My Thread 1
Thread Name :My Thread 2
Thread Name :My Thread 1
Thread Name :My Thread 2
Thread Name :My Thread 2
Thread Name :My Thread 1
Thread Name :My Thread 2
Thread Name :My Thread 1
Thread Name :My Thread 2
Thread Name :My Thread 1

Note that, this program gives the same output as the output of the previous example.
It means, you can use either class Thread or interface Runnable to implement thread in your
program.

Thread Priorities

In Java, thread scheduler can use the thread priorities in the form of integer value to
each of its thread to determine the execution schedule of threads . Thread gets the ready-to-
run state according to their priorities. The thread scheduler provides the CPU time to thread
of highest priority during ready-to-run state.

Priorities are integer values from 1 (lowest priority given by the constant
Thread.MIN_PRIORITY) to 10 (highest priority given by the constant
Thread.MAX_PRIORITY). The default priority is 5(Thread.NORM_PRIORITY).

-142-
Constant Description
The maximum priority of any
Thread.MIN_PRIORITY
thread (an int value of 10)
The minimum priority of any
Thread.MAX_PRIORITY
thread (an int value of 1)
The normal priority of any
Thread.NORM_PRIORITY
thread (an int value of 5)

The methods that are used to set the priority of thread shown as:

Method Description

This is method is used to set the priority


setPriority()
of thread.

This method is used to get the priority


getPriority()
of thread.

When a Java thread is created, it inherits its priority from the thread that created it. At any
given time, when multiple threads are ready to be executed, the runtime system chooses the
runnable thread with the highest priority for execution. In Java runtime system, preemptive
scheduling algorithm is applied. If at the execution time a thread with a higher priority and
all other threads are runnable then the runtime system chooses the new higher priority
thread for execution. On the other hand, if two threads of the same priority are waiting to be
executed by the CPU then the round-robin algorithm is applied in which the scheduler
chooses one of them to run according to their round of time-slice.

Thread Scheduler

In the implementation of threading scheduler usually applies one of the two following
strategies:

-143-
Preemptive scheduling – If the new thread has a higher priority then current running thread
leaves the runnable state and higher priority thread enter to the runnable state.

Time-Sliced (Round-Robin) Scheduling – A running thread is allowed to be execute for the


fixed time, after completion the time, current thread indicates to the another thread to enter it
in the runnable state.

You can also set a thread's priority at any time after its creation using the setPriority
method. Lets see, how to set and get the priority of a thread.

class MyThread1 extends Thread


{
MyThread1(String s)
{
super(s);
start();
}
public void run()
{
for(int i=0;i<3;i++)
{
Thread cur=Thread.currentThread();
cur.setPriority(Thread.MIN_PRIORITY);
int p=cur.getPriority();
System.out.println("Thread Name :"+Thread.currentThread().getName());
System.out.println("Thread Priority :"+cur);
}
}
}

class MyThread2 extends Thread


{
MyThread2(String s)
{
super(s);
start();
}

-144-
public void run()
{
for(int i=0;i<3;i++)
{
Thread cur=Thread.currentThread();
cur.setPriority(Thread.MAX_PRIORITY);
int p=cur.getPriority();
System.out.println("Thread Name :"+Thread.currentThread().getName());
System.out.println("Thread Priority :"+cur);
}
}
}
public class ThreadPriority
{
public static void main(String args[])
{
MyThread1 m1=new MyThread1("My Thread 1");
MyThread2 m2=new MyThread2("My Thread 2");
}
}

-145-
Output of the Program:
C:\nisha>javac
ThreadPriority.java

C:\nisha>java ThreadPriority
Thread Name :My Thread 1
Thread Name :My Thread 2
Thread Priority :Thread[My
Thread 2,10,main]
Thread Name :My Thread 2
Thread Priority :Thread[My
Thread 2,10,main]
Thread Name :My Thread 2
Thread Priority :Thread[My
Thread 2,10,main]
Thread Priority :Thread[My
Thread 1,1,main]
Thread Name :My Thread 1
Thread Priority :Thread[My
Thread 1,1,main]
Thread Name :My Thread 1
Thread Priority :Thread[My
Thread 1,1,main]

In this program two threads are created. We have set up maximum priority for the
first thread "MyThread2" and minimum priority for the first thread "MyThread1" i.e. the
after executing the program, the first thread is executed only once and the second thread
"MyThread2" started to run until either it gets end or another thread of the equal priority
gets ready to run state.

-146-
Synchronized Threads

In Java, the threads are executed independently to each other. These types of threads are
called as asynchronous threads. But there are two problems may be occur with
asynchronous threads.

ƒ Two or more threads share the same resource (variable or method) while only one
of them can access the resource at one time.

ƒ If the producer and the consumer are sharing the same kind of data in a program
then either producer may produce the data faster or consumer may retrieve an
order of data and process it without its existing.

Suppose, we have created two methods as increment( ) and decrement( ). which


increases or decreases value of the variable "count" by 1 respectively shown as:

public void increment( )


{
count++;
}

public void decrement( )


{
count--;
}
public int value()
{
return count;
}

When the two threads are executed to access these methods (one for increment(
),another for decrement( )) then both will share the variable "count". in that case, we can't
be sure that what value will be returned of variable "count".
We can see this problem in the diagram shown below:

-147-
To avoid this problem, Java uses monitor also known as “semaphore” to prevent
data from being corrupted by multiple threads by a keyword synchronized to synchronize
them and intercommunicate to each other. It is basically a mechanism which allows two or
more threads to share all the available resources in a sequential manner. Java's synchronized
is used to ensure that only one thread is in a critical region. critical region is a lock area
where only one thread is run (or lock) at a time. Once the thread is in its critical section, no
other thread can enter to that critical region. In that case, another thread will has to wait until
the current thread leaves its critical section.

General form of the synchronized statement is as:

synchronized(object)
{

// statements to be
synchronized

Lock:

Lock term refers to the access granted to a particular thread that can access the shared
resources. At any given time, only one thread can hold the lock and thereby have access to
the shared resource. Every object in Java has build-in lock that only comes in action when
the object has synchronized method code. By associating a shared resource with a Java object
and its lock, the object can act as a guard, ensuring synchronized access to the resource. Only
one thread at a time can access the shared resource guarded by the object lock.

-148-
Since there is one lock per object, if one thread has acquired the lock, no other thread can
acquire the lock until the lock is not released by first thread. Acquire the lock means the
thread currently in synchronized method and released the lock means exits the synchronized
method.
Remember the following points related to lock and synchronization:

ƒ Only methods (or blocks) can be synchronized, Classes and variable cannot be
synchronized.

ƒ Each object has just one lock.

ƒ All methods in a class need not to be synchronized. A class can have both
synchronized and non-synchronized methods.

ƒ If two threads wants to execute a synchronized method in a class, and both


threads are using the same instance of the class to invoke the method then only
one thread can execute the method at a time.

ƒ If a class has both synchronized and non-synchronized methods, multiple threads


can still access the class's non-synchronized methods. If you have methods that
don't access the data you're trying to protect, then you don't need to synchronize
them. Synchronization can cause a hit in some cases (or even deadlock if used
incorrectly), so you should be careful not to overuse it.

ƒ If a thread goes to sleep, it holds any locks it has—it doesn't release them.

ƒ A thread can acquire more than one lock. For example, a thread can enter a
synchronized method, thus acquiring a lock, and then immediately invoke a
synchronized method on a different object, thus acquiring that lock as well. As the
stack unwinds, locks are released again.

ƒ You can synchronize a block of code rather than a method.


ƒ Constructors cannot be synchronized

-149-
There are two ways to synchronized the execution of code:

1. Synchronized Methods

2. Synchronized Blocks (Statements)

Synchronized Methods:

Any method is specified with the keyword synchronized is only executed by one thread
at a time. If any thread want to execute the synchronized method, firstly it has to obtain the
objects lock. If the lock is already held by another thread, then calling thread has to wait.

Synchronized methods are useful in those situations where methods are executed
concurrently, so that these can be intercommunicate manipulate the state of an object in ways
that can corrupt the state if . Stack implementations usually define the two operations push
and pop of elements as synchronized, that’s why pushing and popping are mutually exclusive
operations. For Example if several threads were sharing a stack, if one thread is popping the
element on the stack then another thread would not be able to pushing the element on the
stack.

The following program demonstrates the synchronized method:

class Share extends Thread{


static String msg[]={"This", "is", "a", "synchronized", "variable"};
Share(String threadname){
super(threadname);
}
public void run(){
display(getName());
}
public synchronized void display(String threadN)
{
for(int i=0;i<=4;i++)

-150-
System.out.println(threadN+msg[i]);
try
{
this.sleep(1000);
}
catch(Exception e){}
}
}
public class SynThread1
{
public static void main(String[] args)
{
Share t1=new Share("Thread One: ");
t1.start();
Share t2=new Share("Thread Two: ");
t2.start();
}
}

-151-
Output of the program is:

C:\nisha>javac
SynThread.java

C:\nisha>java
SynThread
Thread One: This
Thread One: is
Thread One: a
Thread One:
synchronized
Thread One: variable
Thread Two: This
Thread Two: is
Thread two: a
Thread Two:
synchronized
Thread Two: variable

In this program, the method "display( )" is synchronized that will be shared by both
thread's objects at the time of program execution. Thus only one thread can access that
method and process it until all statements of the method are executed.

Synchronized Blocks (Statements)

Another way of handling synchronization is Synchronized Blocks (Statements).


Synchronized statements must specify the object that provides the native lock. The
synchronized block allows execution of arbitrary code to be synchronized on the lock of an
arbitrary object.General form of synchronized block is:

-152-
synchronized (object reference
expression)
{
// statements to be
synchronized
}

The following program demonstrates the synchronized block that shows the same output
as the output of the previous example:

class Share extends Thread


{
static String msg[]={"This", "is", "a", "synchronized", "variable"};
Share(String threadname)
{
super(threadname);
}
public void run()
{
display(getName());
}
public void display(String threadN)
{
synchronized(this)
{
for(int i=0;i<=4;i++)
System.out.println(threadN+msg[i]);
try
{
this.sleep(1000);
}

-153-
catch(Exception e)
{
}
}
}
public class SynStatement
{
public static void main(String[] args)
{
Share t1=new Share("Thread One: ");
t1.start();
Share t2=new Share("Thread Two: ");
t2.start();
}
}

-154-
Output of the Program
C:\nisha>javac
SynStatement.java

C:\nisha>java
SynStatement
Thread One: This
Thread One: is
Thread One: a
Thread One:
synchronized
Thread One: variable
Thread Two: This
Thread Two: is
Thread Two: a
Thread Two:
synchronized
Thread Two: variable

Inter-Thread Communication
Java provides a very efficient way through which multiple-threads can communicate with
each-other. This way reduces the CPU’s idle time i.e. A process where, a thread is paused
running in its critical region and another thread is allowed to enter (or lock) in the same
critical section to be executed. This technique is known as Interthread communication which
is implemented by some methods. These methods are defined in "java.lang" package and can
only be called within synchronized code shown as:

-155-
Method Description
It indicates the calling thread to give up the monitor and go
wait( ) to sleep until some other thread enters the same monitor and
calls method notify() or notifyAll().
It wakes up the first thread that called wait() on the same
notify( )
object.
notifyAll( Wakes up (Unloack) all the threads that called wait( ) on the
) same object. The highest priority thread will run first.

All these methods must be called within a try-catch block.

Lets see an example implementing these methods :

-156-
class Shared
{
int num=0;
boolean value = false;

synchronized int get()


{
if (value==false)
try
{
wait();
}
catch (InterruptedException e)
{
System.out.println("InterruptedException caught");
}
System.out.println("consume: " + num);
value=false;
notify();
return num;
}
synchronized void put(int num)
{
if (value==true)
try
{
wait();
}
catch (InterruptedException e)
{
System.out.println("InterruptedException caught");

-157-
}
this.num=num;
System.out.println("Produce: " + num);
value=false;
notify();
}
}
class Producer extends Thread
{
Shared s;

Producer(Shared s)
{
this.s=s;
this.start(); }

public void run()


{
int i=0;
s.put(++i);
}
}

class Consumer extends Thread


{
Shared s;
Consumer(Shared s)
{
this.s=s;
this.start();
}

-158-
public void run()
{
s.get();
}
}

public class InterThread


{
public static void main(String[] args)
{
Shared s=new Shared();
new Producer(s);
new Consumer(s);
}
}

Output of the Program:

C:\nisha>javac
InterThread.java

C:\nisha>java
InterThread
Produce: 1
consume: 1

-159-
In this program, two threads "Producer" and "Consumer" share the synchronized
methods of the class "Shared". At time of program execution, the "put( )" method is
invoked through the "Producer" class which increments the variable "num" by 1. After
producing 1 by the producer, the method "get( )" is invoked by through the "Consumer"
class which retrieves the produced number and returns it to the output. Thus the Consumer
can't retrieve the number without producing of it.

Another program demonstrates the uses of wait() & notify() methods:

public class DemoWait extends Thread


{
int val=20;
public static void main(String args[])
{
DemoWait d=new DemoWait();
d.start();
new Demo1(d);
}
public void run()
{
try
{
synchronized(this)
{
wait();
System.out.println("value is :"+val);
}
}

-160-
catch(Exception e)
{
}
}
public void valchange(int val)
{
this.val=val;
try
{
synchronized(this)
{
notifyAll();
}
}
catch(Exception e)
{

}
}
}
class Demo1 extends Thread
{
DemoWait d;
Demo1(DemoWait d)
{
this.d=d;
start();
}

-161-
public void run()
{
try
{
System.out.println("Demo1 value is"+d.val);
d.valchange(40);
}
catch(Exception e)
{
}
}
}

Output of the program is:

C:\j2se6\thread>javac
DemoWait.java

C:\j2se6\thread>java
DemoWait
Demo1 value is20
value is :40

C:\j2se6\thread>

-162-
Review Questions:

1. What is threaded programming and when is it used?


2. What is a thread?
3. How do Java threads make the environment asynchronous?
4. Threads and runnable types
5. What's the difference between Thread and Runnable types?
6. What is a Runnable object and a Runnable argument?
7. How does the run() method in Runnable work?
8. A Thread is runnable, how does that work?
9. Do Thread and Runnable types have their own run() methods?
10. Why not override Thread to make a Runnable?

11. When could I adapt the Thread class though?

-163-
Chapter 10
READING AND WRITING TEXT FILES

Objectives

ƒ Need for Text file handling


ƒ Text file reading and writing classes

Java.io package:

Classes related to input and output are present in the JavaTM language package java.io .
Java technology uses "streams" as a general mechanism of handling data. Input streams act as
a source of data. Output streams act as a destination of data.

File class:

The file class is used to store the path and name of a directory or file. The
file object can be used to create, rename, or delete the file or directory it represents. The File
class has the following constructors – File (String pathname); // pathname could be file or a
directory name Fil e(String dirPathname, String filename); File (File directory, String
filename);

The File class provides the getName() method which returns the name of the file
excluding the directory name.

String getName ();

Byte Streams:

The package java in provies two set of class hierarchies – one for handling reading
and writing of bytes, and another for handling readint and writing of characters.
The abstract classes InputStream and OutputStream are the root of inheritance
hierarchies handling reading and writing of bytes respectively.

-164-
Figure: InputStream class hierarchy (partial)

-165-
Figure:OutputStream class hierarchy (partial)

Read and write methods:

InputStream class defines the following methods for reading bytes –

int read() throws IOException


int read(byte b[]) throws IOException
int read(byte b[], int offset, int length) throws IOException

Subclasses of InputStream implement the above mentioned methods.

OutputStream class defines the following methods for writing bytes –

void write(int b) throws IOException


void write(byte b[]) throws IOException
void write(byte b[], int offset, int length) throws IOException

Subclasses of OutputStream implement the above mentioned methods.

The example below illustrates code to read a character.

-166-
//First create an object of type FileInputStream type using the name of the file.

FileInputStream inp = new FileInputStream("filename.ext");

//Create an object of type DataInputStream using inp.

DataInputStream dataInp = new DataInputStream(inp);


int i = dataInp.readInt();

Reader and Writer classes:

Similar to the InputStream and OutputStream class hierarchies for reading and
writing bytes, Java technology provides class hierarchies rooted at Reader and Writer classes
for reading and writing characters.

A character encoding is a scheme for internal representation of characters. Java


programs use 16 bit Unicode character encoding to represent characters internally. Other
platforms may use a different character set (for example ASCII) to represent characters. The
reader classes support conversions of Unicode characters to internal character shortage.
Every platform has a default character encoding. Besides using default encoding, Reader and
Writer classes can also specify which encoding scheme to use.
The Reader class hierarchy is illustrated below.

-167-
The Writer class hierarchy is illustrated below.

The table below gives a brief overview of key Reader classes.

CharArrayReader The class supports reading of characters from a character array.


The class supports reading of characters from a byte input
InputStreamReader
stream. A character encoding may also be specified.
The class supports reading of characters from a file using
FileReader
default character encoding.

The table below gives a brief overview of key Writer classes.

The class supports writing of characters from a character


CharArrayWriter
array.
The class supports writing of characters from a byte output
OutputStreamReader
stream. A character encoding may also be specified.
The class supports writing of characters from a file using
FileWriter
default character encoding.

-168-
The example below illustrates reading of characters using the FileReader class.

//Create a FileReader class from the file name.

FileReader fr = new FileReader("filename.txt");


int i = fr.read(); //Read a character

Class DataInputStream:

A data input stream is use to read primitive Java data types from an underlying input
stream in a machine-independent way. An application uses a data output stream to write data
that can later be read by a data input stream.

Data input streams and data output streams represent Unicode strings in a format that
is a slight modification of UTF-8. (For more information, see X/Open Company Ltd., "File
System Safe UCS Transformation Format (FSS_UTF)", X/Open Preliminary Specification,
Document Number: P316. This information also appears in ISO/IEC 10646, Annex P.) Note
that in the following tables, the most significant bit appears in the far left-hand column.

BufferedReader

Read text from a character-input stream, buffering characters so as to provide for the
efficient reading of characters, arrays, and lines.The buffer size may be specified, or the
default size may be used. The default is large enough for most purposes.

In general, each read request made of a Reader causes a corresponding read request to
be made of the underlying character or byte stream. It is therefore advisable to wrap a
BufferedReader around any Reader whose read() operations may be costly, such as
FileReaders and InputStreamReaders. For example,

BufferedReader in = new BufferedReader(new FileReader("foo.in"));

-169-
will buffer the input from the specified file. Without buffering, each invocation of read() or
readLine() could cause bytes to be read from the file, converted into characters, and then
returned, which can be very inefficient.

Programs that use DataInputStreams for textual input can be localized by replacing each
DataInputStream with an appropriate BufferedReader.

Write To a File:
Class FileWriter

The FileWriter is a class used for writing character files. The constructors of this class
assume that the default character encoding and the default byte-buffer size are acceptable. To
specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.

BufferedWrite

The BufferWriter class is used to write text to a character-output stream, buffering


characters so as to provide for the efficient writing of single characters, arrays, and strings.

Here is the code of java program to write text to a file:

Import java.io.*;
class FileWrite
{
public static void main(String args[])
{ try
{
// Create file
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java");
//Close the output stream

-170-
out.close();
}
catch (Exception e)
{
//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}

Example Programs:

Java program to Read text File Line by Line:

Import java.io.*;
class FileRead
{
public static void main(String args[])
{
try
{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line

-171-
while ((strLine = br.readLine()) != null)
{
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}
catch (Exception e)
{
//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}

-172-
Chapter 11
READING IMAGE FILES AND MANIPULATING THEM WITH
IMAGE RELATED

Objectives

ƒ Image file handling in java


ƒ Image storing and retrieving
ƒ Image formats and their andvantages

Working with Images


There are a number of common tasks when working with images.

ƒ Loading an external GIF, PNG JPEG image format file into Java 2D™'s internal
image representation.

ƒ Directly creating a Java 2D image and rendering to it.

ƒ Drawing the contents of a Java 2D image on to a drawing surface.

ƒ Saving the contents of a Java 2D image to an external GIF, PNG, or JPEG image
file.

This lesson teaches you the basics of loading, displaying, and saving images.

-173-
There are two main classes that you must learn about to work with images:

• The java.awt.Image class is the superclass that represents graphical images as


rectangular arrays of pixels.
• The java.awt.image.BufferedImage class, which extends the Image class to allow the
application to operate directly with image data (for example, retrieving or setting up the
pixel color). Applications can directly construct instances of this class.

The BufferedImage class is a cornerstone of the Java 2D immediate-mode imaging API.


It manages the image in memory and provides methods for storing, interpreting, and
obtaining pixel data. Since BufferedImage is a subclass of Image it can be rendered by the
Graphics and Graphics2D methods that accept an Image parameter.

A BufferedImage is essentially an Image with an accessible data buffer. It is therefore


more efficient to work directly with BufferedImage. A BufferedImage has a ColorModel
and a Raster of image data. The ColorModel provides a color interpretation of the image's
pixel data.

The Raster performs the following functions:

ƒ Represents the rectangular coordinates of the image

ƒ Maintains image data in memory

ƒ Provides a mechanism for creating multiple subimages from a single image data
buffer

ƒ Provides methods for accessing specific pixels within the image

The basic operations with images are represented in the following sections:

-174-
Reading/Loading an image

This section explains how to load an image from an external image format into a Java
application using the Image I/O API

Drawing an image

This section teaches how to display images using the drawImage method of the
Graphics and Graphics2D classes.

Reading/Loading an Image

Java 2D™ supports loading these external image formats into its BufferedImage
format using its Image I/O API which is in the javax.imageio package. Image I/O has built-in
support for GIF, PNG, JPEG, BMP, and WBMP. Image I/O is also extensible so that
developers or administrators can "plug-in" support for additional formats. For example, plug-
ins for TIFF and JPEG 2000 are separately available.

To load an image from a specific file uses the following code:

BufferedImage img = null;


try
{
img = ImageIO.read(new File("strawberry.jpg"));
}
catch (IOException e)
{

Image I/O recognises the contents of the file as a JPEG format image, and decodes it
into a BufferedImage which can be directly used by Java 2D.

LoadImageApp.java shows how to display this image.

-175-
If the code is running in an applet, then its just as easy to obtain the image from the
applet codebase :
try
{
URL url = new URL(getCodeBase(), "strawberry.jpg");
img = ImageIO.read(url);
}
catch (IOException e)
{
}

The getCodeBase method used in this example returns the URL of the directory
containing this applet.

Note: If you don't see the applet running, you need to install release 6 of the Java SE
Development Kit (JDK).

LoadImageApp.java contains the complete code for this example and this applet
requires the strawberry.jpg image file. In addition to reading from files or URLS, Image I/O
can read from other sources, such as an InputStream.

ImageIO.read() is the most straightforward convenience API for most applications,


but the javax.imageio.ImageIO provides many more static methods for more advanced
usages of the Image I/O API. The collection of methods on this class represent just a subset
of the rich set of APIs for discovering information about the images and for controlling the
image decoding (reading) process.

-176-
Writing/Saving an Image

The Image I/O class provides a simple way to save images in a variety of image
formats in the following example:

static boolean ImageIO.write(RenderedImage im,


String formatName,
File output) throws IOException
Note: the BufferedImage class implements the RenderedImage interface.

The formatName parameter selects the image format in which to save the
BufferedImage.
try
{
BufferedImage bi = getMyImage(); // retrieve image
File outputfile = new File("saved.png");
ImageIO.write(bi, "png", outputfile);
}
catch (IOException e)
{ ...
}

The ImageIO.write method calls the code that implements PNG writing a “PNG
writer plug-in”. The term plug-in is used since Image I/O is extensible and can support a
wide range of formats.

But the following standard image format plugins : JPEG, PNG, GIF, BMP and
WBMP are always be present.

Each image format has its advantages and disadvantages:

-177-
Plus Minus

Supports animation, and


GIF Supports only 256 colors and no translucency
transparent pixels

Better alternative than GIF or JPG


PNG for high colour lossless images, Doesn't support animation
supports translucency

Loss of compression, not good for text,


JPG Great for photographic images screenshots, or any application where the
original image must be preserved exactly

For most applications it is sufficient to use one of these standard plugins. They have
the advantage of being readily available. The Image I/O class provides a way to plug in
support for additional formats which can be used, and many such plug-ins exist. If you are
interested in what file formats are available to load or save in your system, you may use the
getReaderFormatNames and getWriterFormatNames methods of the ImageIO class. These

methods return an array of strings listing all of the formats supported in this JRE.

String writerNames[] = ImageIO.getWriterFormatNames();

The returned array of names will include any additional plug-ins that are installed and
any of these names may be used as a format name to select an image writer. The following
code example is a simple version of a complete image edit/touch up program which uses a
revised version of the ImageDrawingApplet.java sample program which can be used as
follows :

ƒ An image is first loaded via Image I/O

ƒ The user selects a filter from the drop down list and a new updated image is
drawn

ƒ The user selects a save format from the drop down list

-178-
ƒ Next a file chooser appears and the user selects where to save the image

ƒ The modified image can now be viewed by other desktop applications

Review Questions:
1. Explain Image files handling in java?

2. Write code for Reading/Loading an image?

3. Write code for Writing/Saving an image?

4. ExplainType of images formats and their advantages?

-179-
Chapter 12
WRITING AN RMI APPLICATION TO ACCESS A REMOTE
METHOD

Objectives

ƒ Need for RMI


ƒ Understanding remote object implementation
ƒ RMI runtime Architecture
ƒ RMI Object services
ƒ Creating stub and skeleton
ƒ Remote object implementation
ƒ Advantages of RMI

Overview of RMI Applications:

RMI applications often comprise two separate programs, a server and a client. A
typical server program creates some remote objects, makes references to these objects
accessible, and waits for clients to invoke methods on these objects. A typical client program
obtains a remote reference to one or more remote objects on a server and then invokes
methods on them. RMI provides the mechanism by which the server and the client
communicate and pass information back and forth. Such an application is sometimes referred
to as a distributed object application.

Distributed object applications need to do the following:

Locate remote objects. Applications can use various mechanisms to obtain


references to remote objects. For example, an application can register its remote objects with
RMI's simple naming facility, the RMI registry. Alternatively, an application can pass and
return remote object references as part of other remote invocations.

-180-
Communicate with remote objects. Details of communication between remote
objects are handled by RMI. To the programmer, remote communication looks similar to
regular Java method invocations.

Load class definitions for objects that are passed around. Because RMI enables
objects to be passed back and forth, it provides mechanisms for loading an object's class
definitions as well as for transmitting an object's data.

The following illustration depicts an RMI distributed application that uses the RMI
registry to obtain a reference to a remote object. The server calls the registry to associate (or
bind) a name with a remote object. The client looks up the remote object by its name in the
server's registry and then invokes a method on it. The illustration also shows that the RMI
system uses an existing web server to load class definitions, from server to client and from
client to server, for objects when needed.

Advantages of Dynamic Code Loading:

One of the central and unique features of RMI is its ability to download the definition
of an object's class if the class is not defined in the receiver's Java virtual machine. All of the
types and behavior of an object, previously available only in a single Java virtual machine,
can be transmitted to another, possibly remote, Java virtual machine. RMI passes objects by
their actual classes, so the behavior of the objects is not changed when they are sent to
another Java virtual machine. This capability enables new types and behaviors to be
introduced into a remote Java virtual machine, thus dynamically extending the behavior of an

-181-
application. The compute engine example in this trail uses this capability to introduce new
behavior to a distributed program.

Remote Interfaces, Objects, and Methods:

Like any other Java application, a distributed application built by using Java RMI is
made up of interfaces and classes. The interfaces declare methods. The classes implement the
methods declared in the interfaces and, perhaps, declare additional methods as well. In a
distributed application, some implementations might reside in some Java virtual machines
but not others. Objects with methods that can be invoked across Java virtual machines are
called remote objects. An object becomes remote by implementing a remote interface, which
has the following characteristics: A remote interface extends the interface java.rmi.Remote.

Each method of the interface declares java.rmi.RemoteException in its throws clause,


in addition to any application-specific exceptions.

RMI treats a remote object differently from a non-remote object when the object is
passed from one Java virtual machine to another Java virtual machine. Rather than making a
copy of the implementation object in the receiving Java virtual machine, RMI passes a
remote stub for a remote object. The stub acts as the local representative, or proxy, for the
remote object and basically is, to the client, the remote reference. The client invokes a
method on the local stub, which is responsible for carrying out the method invocation on the
remote object.

A stub for a remote object implements the same set of remote interfaces that the
remote object implements. This property enables a stub to be cast to any of the interfaces that
the remote object implements. However, only those methods defined in a remote interface are
available to be called from the receiving Java virtual machine.

-182-
Creating Distributed Applications by Using RMI:

Using RMI to develop a distributed application involves these general steps:

1. Designing and implementing the components of your distributed application.

2. Compiling sources.

3. Making classes network accessible.

4. Starting the application.

Designing and Implementing the Application Components:

First, determine your application architecture, including which components are local
objects and which components are remotely accessible. This step includes:

Defining the remote interfaces. A remote interface specifies the methods that can be
invoked remotely by a client. Clients program to remote interfaces, not to the implementation
classes of those interfaces. The design of such interfaces includes the determination of the
types of objects that will be used as the parameters and return values for these methods. If
any of these interfaces or classes do not yet exist, you need to define them as well.

Implementing the remote objects. Remote objects must implement one or more
remote interfaces. The remote object class may include implementations of other interfaces
and methods that are available only locally. If any local classes are to be used for parameters
or return values of any of these methods, they must be implemented as well.

Implementing the clients. Clients that use remote objects can be implemented at any
time after the remote interfaces are defined, including after the remote objects have been
deployed.

-183-
Compiling Sources:

As with any Java program, you use the javac compiler to compile the source files.
The source files contain the declarations of the remote interfaces, their implementations, any
other server classes, and the client classes.

Making Classes Network Accessible:

In this step, you make certain class definitions network accessible, such as the
definitions for the remote interfaces and their associated types, and the definitions for classes
that need to be downloaded to the clients or servers. Classes definitions are typically made
network accessible through a web server.

Starting the Application:

Starting the application includes running the RMI remote object registry, the server,
and the client. The rest of this section walks through the steps used to create a compute
engine.

Building a Generic Compute Engine:

This trail focuses on a simple, yet powerful, distributed application called a compute
engine. The compute engine is a remote object on the server that takes tasks from clients,
runs the tasks, and returns any results. The tasks are run on the machine where the server is
running. This type of distributed application can enable a number of client machines to make
use of a particularly powerful machine or a machine that has specialized hardware.

The novel aspect of the compute engine is that the tasks it runs do not need to be
defined when the compute engine is written or started. New kinds of tasks can be created at
any time and then given to the compute engine to be run. The only requirement of a task is
that its class implement a particular interface. The code needed to accomplish the task can be
downloaded by the RMI system to the compute engine. Then, the compute engine runs the
task, using the resources on the machine on which the compute engine is running.

-184-
The ability to perform arbitrary tasks is enabled by the dynamic nature of the Java
platform, which is extended to the network by RMI. RMI dynamically loads the task code
into the compute engine's Java virtual machine and runs the task without prior knowledge of
the class that implements the task. Such an application, which has the ability to download
code dynamically, is often called a behavior-based application. Such applications usually
require full agent-enabled infrastructures. With RMI, such applications are part of the basic
mechanisms for distributed computing on the Java platform.

Writing an RMI Server:

The compute engine server accepts tasks from clients, runs the tasks, and returns any
results. The server code consists of an interface and a class. The interface defines the
methods that can be invoked from the client. Essentially, the interface defines the client's
view of the remote object. The class provides the implementation.

Designing a Remote Interface:

This section explains the Compute interface, which provides the connection between
the client and the server. You will also learn about the RMI API, which supports this
communication.

Implementing a Remote Interface :

This section explores the class that implements the Compute interface, thereby
implementing a remote object. This class also provides the rest of the code that makes up the
server program, including a main method that creates an instance of the remote object,
registers it with the RMI registry, and sets up a security manager.

-185-
1. Designing a Remote Interface:

At the core of the compute engine is a protocol that enables tasks to be submitted to
the compute engine, the compute engine to run those tasks, and the results of those tasks to
be returned to the client. This protocol is expressed in the interfaces that are supported by the
compute engine. The remote communication for this protocol is illustrated in the following
figure.

Each interface contains a single method. The compute engine's remote interface,
Compute, enables tasks to be submitted to the engine. The client interface, Task, defines how
the compute engine executes a submitted task.

The compute.Compute interface defines the remotely accessible part, the compute
engine itself. Here is the source code for the Compute interface:

package compute;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Compute extends Remote
{
<T> T executeTask(Task<T> t) throws RemoteException;
}

By extending the interface java.rmi.Remote, the Compute interface identifies itself as


an interface whose methods can be invoked from another Java virtual machine. Any object
that implements this interface can be a remote object.

-186-
As a member of a remote interface, the executeTask method is a remote method.
Therefore, this method must be defined as being capable of throwing a
java.rmi.RemoteException. This exception is thrown by the RMI system from a remote
method invocation to indicate that either a communication failure or a protocol error has
occurred. A RemoteException is a checked exception, so any code invoking a remote method
needs to handle this exception by either catching it or declaring it in its throws clause.

The second interface needed for the compute engine is the Task interface, which is
the type of the parameter to the executeTask method in the Compute interface. The
compute.Task interface defines the interface between the compute engine and the work that it
needs to do, providing the way to start the work. Here is the source code for the Task
interface:

package compute;

public interface Task<T>


{
T execute();
}

The Task interface defines a single method, execute, which has no parameters and
throws no exceptions. Because the interface does not extend Remote, the method in this
interface doesn't need to list java.rmi.RemoteException in its throws clause. The Task
interface has a type parameter, T, which represents the result type of the task's computation.
This interface's execute method returns the result of the computation and thus its return type
is T. The Compute interface's executeTask method, in turn, returns the result of the execution
of the Task instance passed to it. Thus, the executeTask method has its own type parameter,
T, that associates its own return type with the result type of the passed Task instance. RMI
uses the Java object serialization mechanism to transport objects by value between Java
virtual machines. For an object to be considered serializable, its class must implement the
java.io.Serializable marker interface. Therefore, classes that implement the Task interface
must also implement Serializable, as must the classes of objects used for task results.

-187-
Different kinds of tasks can be run by a Compute object as long as they are
implementations of the Task type. The classes that implement this interface can contain any
data needed for the computation of the task and any other methods needed for the
computation. Here is how RMI makes this simple compute engine possible. Because RMI
can assume that the Task objects are written in the Java programming language,
implementations of the Task object that were previously unknown to the compute engine are
downloaded by RMI into the compute engine's Java virtual machine as needed. This
capability enables clients of the compute engine to define new kinds of tasks to be run on the
server machine without needing the code to be explicitly installed on that machine.

The compute engine, implemented by the ComputeEngine class, implements the


Compute interface, enabling different tasks to be submitted to it by calls to its executeTask
method. These tasks are run using the task's implementation of the execute method and the
results, are returned to the remote client.

Creating a Client Program:

The compute engine is a relatively simple program: it runs tasks that are handed to it.
The clients for the compute engine are more complex. A client needs to call the compute
engine, but it also has to define the task to be performed by the compute engine. Two
separate classes make up the client in our example. The first class, ComputePi, looks up and
invokes a Compute object. The second class, Pi, implements the Task interface and defines
the work to be done by the compute engine. The job of the Pi class is to compute the value of
to some number of decimal places.

The non-remote Task interface is defined as follows:

package compute;

public interface Task<T>


{
T execute();
}

-188-
The code that invokes a Compute object's methods must obtain a reference to that
object, create a Task object, and then request that the task be executed. The definition of the
task class Pi is shown later. A Pi object is constructed with a single argument, the desired
precision of the result. The result of the task execution is a java.math.BigDecimal
representing calculated to the specified precision.

Here is the source code for client.ComputePi, the main client class:
package client;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.math.BigDecimal;
import compute.Compute;

public class ComputePi


{
public static void main(String args[])
{
if (System.getSecurityManager() == null)
{
System.setSecurityManager(new SecurityManager());
}
try
{
String name = "Compute";
Registry registry = LocateRegistry.getRegistry(args[0]);
Compute comp = (Compute) registry.lookup(name);
Pi task = new Pi(Integer.parseInt(args[1]));
BigDecimal pi = comp.executeTask(task);
System.out.println(pi);
}

-189-
catch (Exception e)
{
System.err.println("ComputePi exception:");
e.printStackTrace();
}
}
}

Like the ComputeEngine server, the client begins by installing a security manager.
This step is necessary because the process of receiving the server remote object's stub could
require downloading class definitions from the server. For RMI to download classes, a
security manager must be in force.

After installing a security manager, the client constructs a name to use to look up a
Compute remote object, using the same name used by ComputeEngine to bind its remote
object. Also, the client uses the LocateRegistry.getRegistry API to synthesize a remote
reference to the registry on the server's host. The value of the first command-line argument,
args[0], is the name of the remote host on which the Compute object runs. The client then
invokes the lookup method on the registry to look up the remote object by name in the server
host's registry. The particular overload of LocateRegistry.getRegistry used, which has a
single String parameter, returns a reference to a registry at the named host and the default
registry port, 1099. You must use an overload that has an int parameter if the registry is
created on a port other than 1099.

Next, the client creates a new Pi object, passing to the Pi constructor the value of the
second command-line argument, args[1], parsed as an integer. This argument indicates the
number of decimal places to use in the calculation. Finally, the client invokes the
executeTask method of the Compute remote object. The object passed into the executeTask
invocation returns an object of type BigDecimal, which the program stores in the variable
result. Finally, the program prints the result. The following figure depicts the flow of
messages among the ComputePi client, the rmiregistry, and the ComputeEngine.

-190-
The Pi class implements the Task interface and computes the value of to a specified
number of decimal places. For this example, the actual algorithm is unimportant. What is
important is that the algorithm is computationally expensive, meaning that you would want to
have it executed on a capable server.

Here is the source code for client.Pi, the class that implements the Task interface:

package client;

import compute.Task;
import java.io.Serializable;
import java.math.BigDecimal;

public class Pi implements Task<BigDecimal>, Serializable


{
private static final long serialVersionUID = 227L;
/** constants used in pi computation */
private static final BigDecimal FOUR =
BigDecimal.valueOf(4);
/** rounding mode to use during pi computation */
private static final int roundingMode =
BigDecimal.ROUND_HALF_EVEN;
/** digits of precision after the decimal point */
private final int digits;
/**
* Construct a task to calculate pi to the specified
* precision. */

-191-
public Pi(int digits)
{
this.digits = digits;
}

/** * Calculate pi. */


public BigDecimal execute()
{
return computePi(digits);
}

/**

* Compute the value of pi to the specified number of

* digits after the decimal point. The value is

* computed using Machin's formula:

* pi/4 = 4*arctan(1/5) - arctan(1/239)

* and a power series expansion of arctan(x) to

* sufficient precision. */

public static BigDecimal computePi(int digits)

int scale = digits + 5;

BigDecimal arctan1_5 = arctan(5, scale);

BigDecimal arctan1_239 = arctan(239, scale);

BigDecimal pi = arctan1_5.multiply(FOUR).subtract
(
arctan1_239).multiply(FOUR);

return pi.setScale(digits,

-192-
BigDecimal.ROUND_HALF_UP);
}

/** * Compute the value, in radians, of the arctangent of


* the inverse of the supplied integer to the specified
* number of digits after the decimal point. The value
* is computed using the power series expansion for the
* arc tangent:
*
* arctan(x) = x - (x^3)/3 + (x^5)/5 - (x^7)/7 + * (x^9)/9 ... */

public static BigDecimal arctan(int inverseX, int scale)

BigDecimal result, numer, term;

BigDecimal invX = BigDecimal.valueOf(inverseX);

BigDecimal invX2 =

BigDecimal.valueOf(inverseX * inverseX);

numer = BigDecimal.ONE.divide(invX,

scale, roundingMode);
result = numer;

int i = 1;

do
{
numer =
numer.divide(invX2, scale, roundingMode);
int denom = 2 * i + 1;
term =
numer.divide(BigDecimal.valueOf(denom),
scale, roundingMode);

-193-
if ((i % 2) != 0)
{
result = result.subtract(term);
}
else
{
result = result.add(term);
}
i++;
}
while (term.compareTo(BigDecimal.ZERO) != 0);
return result;
}
}
Note that all serializable classes, whether they implement the Serializable interface
directly or indirectly, must declare a private static final field named serialVersionUID to
guarantee serialization compatibility between versions. If no previous version of the class has
been released, then the value of this field can be any long value, similar to the 227L used by
Pi, as long as the value is used consistently in future versions. If a previous version of the
class has been released without an explicit serialVersionUID declaration, but serialization
compatibility with that version is important, then the default implicitly computed value for
the previous version must be used for the value of the new version's explicit declaration. The
serialver tool can be run against the previous version to determine the default computed value
for it.

The most interesting feature of this example is that the Compute implementation
object never needs the Pi class's definition until a Pi object is passed in as an argument to the
executeTask method. At that point, the code for the class is loaded by RMI into the Compute
object's Java virtual machine, the execute method is invoked, and the task's code is executed.
The result, which in the case of the Pi task is a BigDecimal object, is handed back to the
calling client, where it is used to print the result of the computation.

-194-
The fact that the supplied Task object computes the value of Pi is irrelevant to the
ComputeEngine object. You could also implement a task that, for example, generates a
random prime number by using a probabilistic algorithm. That task would also be
computationally intensive and therefore a good candidate for passing to the ComputeEngine,
but it would require very different code. This code could also be downloaded when the Task
object is passed to a Compute object. In just the way that the algorithm for computing is
brought in when needed, the code that generates the random prime number would be brought
in when needed. The Compute object knows only that each object it receives implements the
execute method. The Compute object does not know, and does not need to know, what the
implementation does.

Compiling the Example Programs:

In a real-world scenario in which a service such as the compute engine is deployed, a


developer would likely create a Java Archive (JAR) file that contains the Compute and Task
interfaces for server classes to implement and client programs to use. Next, a developer,
perhaps the same developer of the interface JAR file, would write an implementation of the
Compute interface and deploy that service on a machine available to clients. Developers of
client programs can use the Compute and the Task interfaces, contained in the JAR file, and
independently develop a task and client program that uses a Compute service.

In this section, you learn how to set up the JAR file, server classes, and client classes.
You will see that the client's Pi class will be downloaded to the server at runtime. Also, the
Compute and Task interfaces will be downloaded from the server to the registry at runtime.

This example separates the interfaces, remote object implementation, and client code
into three packages:
compute – Compute and Task interfaces
engine – ComputeEngine implementation class
client – ComputePi client code and Pi task implementation

First, you need to build the interface JAR file to provide to server and client
developers.

-195-
Building a JAR File of Interface Classes

First, you need to compile the interface source files in the compute package and then
build a JAR file that contains their class files. Assume that user waldo has written these
interfaces and placed the source files in the directory c:\home\waldo\src\compute on
Windows or the directory /home/waldo/src/compute on Solaris OS or Linux. Given these
paths, you can use the following commands to compile the interfaces and create the JAR file:

Microsoft Windows:

cd c:\home\waldo\src

javac compute\Compute.java compute\Task.java

jar cvf compute.jar compute\*.class

Solaris OS or Linux:

cd /home/waldo/src

javac compute/Compute.java compute/Task.java

jar cvf compute.jar compute/*.class

The jar command displays the following output due to the -v option:
added manifest

adding: compute/Compute.class(in = 307) (out= 201)(deflated 34%)

adding: compute/Task.class(in = 217) (out= 149)(deflated 31%)

Now, you can distribute the compute.jar file to developers of server and client
applications so that they can make use of the interfaces.

-196-
After you build either server-side or client-side classes with the javac compiler, if any
of those classes will need to be dynamically downloaded by other Java virtual machines, you
must ensure that their class files are placed in a network-accessible location. In this example,
for Solaris OS or Linux this location is /home/user/public_html/classes because many web
servers allow the accessing of a user's public_html directory through an HTTP URL
constructed as http://host/~user/. If your web server does not support this convention, you
could use a different location in the web server's hierarchy, or you could use a file URL
instead. The file URLs take the form file:/home/user/public_html/classes/ on Solaris OS or
Linux and the form file:/c:/home/user/public_html/classes/ on Windows. You may also select
another type of URL, as appropriate.

The network accessibility of the class files enables the RMI runtime to download
code when needed. Rather than defining its own protocol for code downloading, RMI uses
URL protocols supported by the Java platform (for example, HTTP) to download code. Note
that using a full, heavyweight web server to serve these class files is unnecessary

Building the Server Classes:

The engine package contains only one server-side implementation class,


ComputeEngine, the implementation of the remote interface Compute. Assume that user ann,
the developer of the ComputeEngine class, has placed ComputeEngine.java in the directory
c:\home\ann\src\engine on Windows or the directory /home/ann/src/engine on Solaris OS or
Linux. She is deploying the class files for clients to download in a subdirectory of
her public_html directory, c:\home\ann\public_html\classes on Windows or / home /ann/
public_html/classes on Solaris OS or Linux. This location is accessible through some web
servers as http://host:port/~ann/classes/.

The ComputeEngine class depends on the Compute and Task interfaces, which are
contained in the compute.jar JAR file. Therefore, you need the compute.jar file in your class
path when you build the server classes. Assume that the compute.jar file is located in the
directory c:\home\ann\public_html\classes on Windows or the directory

-197-
/home/ann/public_html/classes on Solaris OS or Linux. Given these paths, you can use the
following commands to build the server classes:

Microsoft Windows:
cd c:\home\ann\src

javac -cp c:\home\ann\public_html\classes\compute.jar

engine\ComputeEngine.java

Solaris OS or Linux:
cd /home/ann/src

javac -cp /home/ann/public_html/classes/compute.jar

engine/ComputeEngine.java

The stub class for ComputeEngine implements the Compute interface, which refers to
the Task interface. So, the class definitions for those two interfaces need to be network-
accessible for the stub to be received by other Java virtual machines such as the registry's
Java virtual machine. The client Java virtual machine will already have these interfaces in its
class path, so it does not actually need to download their definitions. The compute.jar file
under the public_html directory can serve this purpose.

Now, the compute engine is ready to deploy. You could do that now, or you could
wait until after you have built the client.

Building the Client Classes

The client package contains two classes, ComputePi, the main client program, and Pi,
the client's implementation of the Task interface. Assume that user jones, the developer of
the client classes, has placed ComputePi.java and Pi.java in the directory
c:\home\jones\src\client on Windows or the directory /home/jones/src/client on Solaris OS or

-198-
Linux. He is deploying the class files for the compute engine to download in a subdirectory
of his public_html directory, c:\home\jones\public_html\classes on Windows or
/home/jones/public_html/classes on Solaris OS or Linux. This location is accessible through
some web servers as http://host:port/~jones/classes/.

The client classes depend on the Compute and Task interfaces, which are contained in
the compute.jar JAR file. Therefore, you need the compute.jar file in your class path when
you build the client classes. Assume that the compute.jar file is located in the directory
c:\home\jones\public_html\classes on Windows or the directory /home /jones / public_html /
classes on Solaris OS or Linux. Given these paths, you can use the following commands to
build the client classes:

Microsoft Windows:

cd c:\home\jones\src

javac -cp c:\home\jones\public_html\classes\compute.jar

client\ComputePi.java client\Pi.java

mkdir c:\home\jones\public_html\classes\client

cp client\Pi.class

c:\home\jones\public_html\classes\client

Solaris OS or Linux:

cd /home/jones/src

javac -cp /home/jones/public_html/classes/compute.jar

client/ComputePi.java client/Pi.java

mkdir /home/jones/public_html/classes/client

-199-
cp client/Pi.class

/home/jones/public_html/classes/client

Only the Pi class needs to be placed in the directory public_html\classes\client


because only the Pi class needs to be available for downloading to the compute engine's Java
virtual machine. Now, you can run the server and then the client.

Running the Example Programs:

The server and client programs run with a security manager installed. When you run
either program, you need to specify a security policy file so that the code is granted the
security permissions it needs to run. Here is an example policy file to use with the server
program:
grant codeBase "file:/home/ann/src/"
{

permission java.security.AllPermission;
};

Here is an example policy file to use with the client program:

grant codeBase "file:/home/jones/src/"


{

permission java.security.AllPermission;

};

For both example policy files, all permissions are granted to the classes in the
program's local class path, because the local application code is trusted, but no permissions
are granted to code downloaded from other locations. Therefore, the compute engine server
restricts the tasks that it executes (whose code is not known to be trusted and might be

-200-
hostile) from performing any operations that require security permissions. The example
client's Pi task does not require any permissions to execute.

In this example, the policy file for the server program is named server.policy, and the
policy file for the client program is named client.policy.

Starting the Server:

Before starting the compute engine, you need to start the RMI registry. The RMI
registry is a simple server-side bootstrap naming facility that enables remote clients to obtain
a reference to an initial remote object. It can be started with the rmiregistry command. Before
you execute rmiregistry, you must make sure that the shell or window in which you will run
rmiregistry either has no CLASSPATH environment variable set or has a CLASSPATH
environment variable that does not include the path to any classes that you want downloaded
to clients of your remote objects.

To start the registry on the server, execute the rmiregistry command. This command
produces no output and is typically run in the background. For this example, the registry is
started on the host zaphod.

Microsoft Windows (use javaw if start is not available):


start rmiregistry

Solaris OS or Linux:

rmiregistry &

By default, the registry runs on port 1099. To start the registry on a different port,
specify the port number on the command line. Do not forget to unset your CLASSPATH
environment variable.

Microsoft Windows:

start rmiregistry 2001

-201-
Solaris OS or Linux:
rmiregistry 2001 &

Once the registry is started, you can start the server. You need to make sure that both
the compute.jar file and the remote object implementation class are in your class path. When
you start the compute engine, you need to specify, using the java.rmi.server.codebase
property, where the server's classes are network accessible. In this example, the server-side
classes to be made available for downloading are the Compute and Task interfaces, which are
available in the compute.jar file in the public_html\classes directory of user ann. The
compute engine server is started on the host zaphod, the same host on which the registry was
started.

Microsoft Windows:

java -cp c:\home\ann\src;c:\home\ann\public_html\classes\compute.jar

- Djava.rmi.server.codebase=file:/c:/home/ann/public_html/classes/compute.jar

- Djava.rmi.server.hostname=zaphod.east.sun.com

- Djava.security.policy=server.policy

engine.ComputeEngine

Solaris OS or Linux:

java -cp /home/ann/src:/home/ann/public_html/classes/compute.jar

-Djava.rmi.server.codebase=http://zaphod/~ann/classes/compute.jar

-Djava.rmi.server.hostname=zaphod.east.sun.com

-Djava.security.policy=server.policy

engine.ComputeEngine

-202-
The above java command defines the following system properties:

ƒ The java.rmi.server.codebase property specifies the location, a codebase URL,


from which the definitions for classes originating from this server can be
downloaded. If the codebase specifies a directory hierarchy (as opposed to a JAR
file), you must include a trailing slash at the end of the codebase URL.

ƒ The java.rmi.server.hostname property specifies the host name or address to put in


the stubs for remote objects exported in this Java virtual machine. This value is
the host name or address used by clients when they attempt to communicate
remote method invocations. By default, the RMI implementation uses the server's
IP address as indicated by the java.net.InetAddress.getLocalHost API. However,
sometimes, this address is not appropriate for all clients and a fully qualified host
name would be more effective. To ensure that RMI uses a host name (or IP
address) for the server that is routable from all potential clients, set the
java.rmi.server.hostname property.

ƒ The java.security.policy property is used to specify the policy file that contains
the permissions you intend to grant.

Starting the Client:

Once the registry and the compute engine are running, you can start the client, specifying
the following:
ƒ The location where the client serves its classes (the Pi class) by using the
java.rmi.server.codebase property

ƒ The java.security.policy property, which is used to specify the security policy file
that contains the permissions you intend to grant to various pieces of code

ƒ As command-line arguments, the host name of the server (so that the client knows
where to locate the Compute remote object) and the number of decimal places to
use in the calculation

-203-
Start the client on another host (a host named ford, for example) as follows:

Microsoft Windows:

java -cp c:\home\jones\src;c:\home\jones\public_html\classes\compute.jar

-Djava.rmi.server.codebase=file:/c:/home/jones/public_html/classes/

-Djava.security.policy=client.policy

client.ComputePi zaphod.east.sun.com 45

Solaris OS or Linux:

java -cp /home/jones/src:/home/jones/public_html/classes/compute.jar

-Djava.rmi.server.codebase=http://ford/~jones/classes/

-Djava.security.policy=client.policy

client.ComputePi zaphod.east.sun.com 45

Note that the class path is set on the command line so that the interpreter can find the
client classes and the JAR file containing the interfaces. Also note that the value of the
java.rmi.server.codebase property, which specifies a directory hierarchy, ends with a trailing
slash.

After you start the client, the following output is displayed:

3.141592653589793238462643383279502884197169399

The following figure illustrates where the rmiregistry, the ComputeEngine server, and
the ComputePi client obtain classes during program execution.

-204-
When the ComputeEngine server binds its remote object reference in the registry, the
registry downloads the Compute and Task interfaces on which the stub class depends. These
classes are downloaded from either the ComputeEngine server's web server or file system,
depending on the type of codebase URL used when starting the server.

Because the ComputePi client has both the Compute and the Task interfaces available
in its class path, it loads their definitions from its class path, not from the server's codebase.

Finally, the Pi class is loaded into the ComputeEngine server's Java virtual machine
when the Pi object is passed in the executeTask remote call to the ComputeEngine object.
The Pi class is loaded by the server from either the client's web server or file system,
depending on the type of codebase URL used when starting the client.

Example programs:

Remote Object Interface:

RMIExample.java
// Interface for the RMI remote object.
// Note: Interface must extend from java.rmi.Remote
// Methods must throw RemoteExcpetion

-205-
import java.rmi.*;

public interface RMIExample extends Remote


{
public boolean PostMsg(String strMsg) throws RemoteException;
public long Factorial(long lVal) throws RemoteException;
}

Serverside code:

RMIExampleImpl.java
// Implements the remote object
// Note: The object must extend from UnicastRemoteObject
// The object must implement the associated interface

import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
import java.io.*;

public class RMIExampleImpl extends UnicastRemoteObject


implements RMIExample
{
protected static String m_strName;

public RMIExampleImpl() throws RemoteException


{
super(); // call base class constructor
}

public boolean PostMsg(String strMsg) throws RemoteException


{
System.out.println("Server: PostMsg() invoked...");
System.out.println("Server: Message > " + strMsg);
return true;
}

-206-
public long Factorial(long lVal) throws RemoteException
{
long lRes = FactorialEx(lVal);
System.out.println("Server: Factorial() invoked...");
System.out.println("Server: Factorial("+lVal+") = " + lRes);
return lRes;
}
protected long FactorialEx(long lVal)
{
if (lVal <= 1)
return 1;
else
return lVal * FactorialEx(lVal-1);
}
public static void main(String argv[])
{
try
{
m_strName = "TheRMIExample";

System.out.println("Server: Registering RMIExampleImpl as \"" +


m_strName +"\"");

RMIExampleImpl Example = new RMIExampleImpl();

Naming.rebind(m_strName, Example);

System.out.println("Server: Ready...");
}

-207-
catch (Exception e)
{

System.out.println("Server: Failed to register RMIExampleImpl: " + e);

}
}
}

Client side Code:

// RMIClient.java
//
// This sample Java RMI client can perform the
// following operations:
// (1) Send a message to a remote object. This
//is done by using the -m command line switch.
//Example: java RMIClient -m "My message in quotes"
// (2) Calculate the factorial of a given number via
//a method of the remote object.
//Example: java RMIClient -f 5

import java.rmi.*;
I mport java.rmi.server.*;

public class RMIClient


{
public static void main(String argv[])
{
// Validate command line parameters

if (argv.length < 2)
{
System.out.println("Usage: java RMIClient [-m \"MESSAGE\"] [-f INTEGER]");
System.exit(1);
}

-208-
// Command line option flags

boolean bMessage = false;


boolean bFactorial = false;

String strMsg = "No message.";


long lVal = 1;

// Determine data to be processed


for (int i=0; i<argv.length; i++)
{
if (argv[i].equals("-m"))
{
bMessage = true;
strMsg = argv[++i];
}
if (argv[i].equals("-f"))
{
bFactorial = true;
lVal = Long.parseLong(argv[++i]);
}
}

// Install security manager. This is only necessary


// if the remote object's client stub does not reside
// on the client machine (it resides on the server).

System.setSecurityManager(new RMISecurityManager());

// Get a remote reference to the RMIExampleImpl class

String strName = "rmi://wpi.wpi.edu/TheRMIExample";

-209-
System.out.println("Client: Looking up " + strName + "...");

RMIExample RemRMIExample = null;

try
{
RemRMIExample = (RMIExample)Naming.lookup(strName);
}
catch (Exception e)
{
System.out.println("Client: Exception thrown looking up " + strName);
System.exit(1);
}
// Send a messge to the remote object
if (bMessage)
{

try
{
if (!RemRMIExample.PostMsg(strMsg))
System.out.println("Client: Remote PostMsg() call failed.");
}
catch (Exception e)
{
System.out.println("Client: Exception thrown calling PostMsg().");
System.exit(1);
}
}

-210-
// Calculate the factorial

if (bFactorial)
{
try
{
long lRes = RemRMIExample.Factorial(lVal);
System.out.println ("Client: Factorial(" + lVal + ") = " + lRes);
}
catch (Exception e)
{
System.out.println("Client: Excpetion thrown calling Factorial().");
System.exit(1);
}
}
}
}

Interfacing with legacy applications

1. RMI and Native Method calls

By using Java’s Native Interface API, it is possible to wrap existing C or C++ code
with a Java interface and then export this interface remotely through RMI.

Advantage: You’re running Java at both ends of the remote communication and
avoiding use of CORBA, which may be overkill for your application. Using the simpler RMI
may be an advantage.

-211-
2. CORBA

A CORBA object implemented in the same language as the native code (C/C++) is
created and exported on the server. Remote Java clients can get a Java stub to this CORBA
object using JavaIDL.

Advantage: you don’t need Java on the server. Since this is presumably a mainframe,
finding a stable JVM and development kit for the platform may be a problem. If a Java
implementation isn’t available or if installing additional software on the legacy server isn’t
desirable, CORBA is your only option.

3. RMI over IIOP

RMI objects can communicate directly with CORBA objects using IIOP, the CORBA
network interface protocol.

This means that an RMI object using RMI/IIOP can communicate with a remote CORBA
object, regardless of the implementation language of the CORBA object and the CORBA
object can interact with your Java RMI objects directly.

Object Serialization

ƒ To copy an object, you need to convert it into a stream of bytes.

ƒ Object serialization is a scheme that converts objects into a byte stream that is
passed to other machines; these rebuild the original object from the bytes.

ƒ An object you want to serialize must implement the java.io.Serializable interface.

ƒ In RMI, serialization is used to marshal/unmarshal method arguments that are


objects, but that are not remote objects.

ƒ Any object argument to a method on a remote object in RMI must implement the
Serializable interface.

-212-
Review Questions:

1. Explain RMI components?

2. Explain RMI runtime architecture?

3. Explain RMI object services?

4. Describe remote object and implementation?

5. What is mean by stub and skeleton?

6. Explain registry and naming services?

7. RMI advantages?

-213-
Chapter 13
WRITING A SERVLET PROGRAM WITH DATABASE
CONNECTIVITY FOR A WEB BASED APPLICATION SUCH AS
STUDENT RESULT STATUS CHECKING, PNR NUMBER ENQUIRY

Objectives

ƒ Understanding servlet and use of servlet


ƒ Access database from servlet
ƒ Database connectivity and databse access
ƒ Architecture of JDBC

SERVLET:

Servlets are server side components that provide a powerful mechanism for
developing server side programs. Servlets provide component-based, platform-independent
methods for building Web-based applications, without the performance limitations of CGI
programs. Unlike proprietary server extension mechanisms (such as the Netscape Server API
or Apache modules), servlets are server as well as platform-independent. This leaves you free
to select a "best of breed" strategy for your servers, platforms, and tools. Using servlets web
developers can create fast and efficient server side application which can run on any servlet
enabled web server. Servlets run entirely inside the Java Virtual Machine. Since the Servlet
runs at server side so it does not checks the browser for compatibility. Servlets can access the
entire family of Java APIs, including the JDBC API to access enterprise databases. Servlets
can also access a library of HTTP-specific calls, receive all the benefits of the mature java
language including portability, performance, reusability, and crash protection. Today servlets
are the popular choice for building interactive web applications. Third-party servlet
containers are available for Apache Web Server, Microsoft IIS, and others. Servlet containers
are usually the components of web and application servers, such as BEA WebLogic

-214-
Application Server, IBM WebSphere, Sun Java System Web Server, Sun Java System
Application Server and others.Accessing Access Database from Servlet

HTTP Servlet typically used to:

ƒ Priovide dynamic content like getting the results of a database query and returning
to the client.

ƒ Process and/or store the data submitted by the HTML.

ƒ Manage information about the state of a stateless HTTP. e.g. an online shopping
car manages request for multiple concurrent customers.

A Generic servlet contains the following five methods:

1.init()

public void init(ServletConfig config) throws ServletException

The init() method is called only once by the servlet container throughout the life of a
servlet. By this init() method the servlet get to know that it has been placed into service.

The servlet cannot be put into the service if

ƒ The init() method does not return within a fix time set by the web server.

ƒ It throws a ServletException

Paremeters – The init() method takes a ServletConfig object that contains the
initialization parameters and servlet’s configuration and throws a ServletException if an
exception has occurred.
service()
public void service(ServletRequest req, ServletResponse
res) throws ServletException, IOException

-215-
Once the servlet starts getting the requests, the service() method is called by the
servlet container to respond. The servlet services the client's request with the help
of two objects. These two objects javax.servlet.ServletRequest and
javax.servlet.ServletResponse are passed by the servlet container.

The status code of the response always should be set for a servlet that throws or sends
an error.]

Parameters - The service() method takes the ServletRequest object that contains the
client's request and the object ServletResponse contains the servlet's response. The service ()
method throws ServletException and IOExceptions exception.

getServletConfig()

public ServletConfig getServletConfig()

This method contains parameters for initialization and startup of the servlet and
returns a ServletConfig object. This object is then passed to the init method. When this
interface is implemented then it stores the ServletConfig object in order to return it. It is
done by the generic class which implements this inetrface.

Returns - the ServletConfig object

getServletInfo()

public String getServletInfo()

The information about the servlet is returned by this method like version, author etc.
This method returns a string which should be in the form of plain text and not any kind of
markup.

Returns - a string that contains the information about the servlet


destroy()
public void destroy()

-216-
This method is called when we need to close the servlet. That is before removing a
servlet instance from service, the servlet container calls the destroy() method. Once the
servlet container calls the destroy() method, no service methods will be then called . That is
after the exit of all the threads running in the servlet, the destroy() method is called. Hence,
the servlet gets a chance to clean up all the resources like memory, threads etc which are
being held.

JDBC ARCHITECTURE:

The JDBC API uses a Driver Manager and database-specific drivers to provide
transparent connectivity to heterogeneous databases. The JDBC driver manager ensures that
the correct driver is used to access each data source. The Driver Manager is capable of
supporting multiple concurrent drivers connected to multiple heterogeneous databases. The
location of the driver manager with respect to the JDBC drivers and the servlet is shown in
Figure1.

Layers of the JDBC Architecture

A JDBC driver translates standard JDBC calls into a network

-217-
or database protocol or into a database library API call that facilitates communication
with the database. This translation layer provides JDBC applications with database
independence. If the back-end database changes, only the JDBC driver need be replaced with
few code modifications required. There are four distinct types of JDBC drivers.

Type 1 JDBC-ODBC Bridge.

Type 1 drivers act as a "bridge" between JDBC and another database connectivity
mechanism such as ODBC. The JDBC- ODBC bridge provides JDBC access using most
standard ODBC drivers. This driver is included in the Java 2 SDK within the sun.jdbc.odbc
package. In this driver the java statements are converted to a jdbc statements. JDBC
statements calls the ODBC by using the JDBC-ODBC Bridge. And finally the query is
executed by the database. This driver has serious limitation for many applications.

Type 1 JDBC Architecture

Type 2 Java to Native API:

Type 2 drivers use the Java Native Interface (JNI) to make calls to a local database
library API. This driver converts the JDBC calls into a database specific call for databases
such as SQL, ORACLE etc. This driver communicates directly with the database server. It
requires some native code to connect to the database. Type 2 drivers are usually faster than
Type 1 drivers. Like Type 1 drivers, Type 2 drivers require native database client libraries to
be installed and configured on the client machine.

-218-
Type 2 JDBC Architecture:

Type 3 Java to Network Protocol Or All- Java Driver.

Type 3 drivers are pure Java drivers that use a proprietary network protocol to
communicate with JDBC middleware on the server. The middleware then translates the
network protocol to database-specific function calls. Type 3 drivers are the most flexible
JDBC solution because they do not require native database libraries on the client and can
connect to many different databases on the back end. Type 3 drivers can be deployed over
the Internet without client installation.

-219-
Type 3 JDBC Architecture

Type 4 Java to Database Protocol:

Type 4 drivers are pure Java drivers that implement a proprietary database protocol
(like Oracle's SQL*Net) to communicate directly with the database. Like Type 3 drivers,
they do not require native database libraries and can be deployed over the Internet without
client installation. One drawback to Type 4 drivers is that they are database specific. Unlike

Type 3 drivers, if your back-end database changes, you may save to purchase and
deploy a new Type 4 driver (some Type 4 drivers are available free of charge from the
database manufacturer). However, because Type drivers communicate directly with the
database engine rather than through middleware or a native library, they are usually the
fastest JDBC drivers available. This driver directly converts the java statements to SQL
statements.

-220-
Type 4 JDBC Architecture

Database Connectivity with Servlet:


1. Create an ODBC data source "emaildb" by selecting "emaildb.mdb" database

2. Compile you emaildb.java file, move emaildb.class file to Java Web Servers servlets
directory and register the servlet. Now open your browser and run the servlet.

import java.io.*;

import java.util.Enumeration;

import javax.servlet.*;

import javax.servlet.http.*;

import java.sql.*;

import java.net.*;

public class emaildb extends HttpServlet

Connection theConnection;

private ServletConfig config;

public void init(ServletConfig config)

throws ServletException

this.config = config;

-221-
public void service(HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException

HttpSession session = req.getSession(true);

res.setContentType("text/html");

PrintWriter out = res.getWriter();

out.println("<HTML><HEAD><TITLE>Emai
List.</TITLE>");

out.println("</HEAD>");

out.println("<BODY bgColor=blanchedalmond text=#008000


topMargin=0>");

out.println("<P align=center><FONT face=Helvetica><FONT


color=fuchsia style=\"BACKGROUND-COLOR:
white\"><BIG><BIG>List of E-mail
addresses.</BIG></BIG></FONT></P>");

out.println("<P align=center>");

out.println("<TABLE align=center border=1 cellPadding=1


cellSpacing=1 width=\"75%\">");

out.println("<TR>");

out.println("<TD>Name</TD>");

out.println("<TD>E-mail</TD>");

out.println("<TD>Website</TD></TR>");

try

//Loading Sun's JDBC ODBC Driver

-222-
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

//Connect to emaildb Data source

theConnection =
DriverManager.getConnection("jdbc:odbc:emaildb", "admin",
"");

Statement theStatement = theConnection.createStatement();

ResultSet theResult = theStatement.executeQuery("select *


from emaillists");

//Select all records from emaillists table.

//Fetch all the records and print in table

while (theResult.next())

out.println();

out.println("<TR>");

out.println("<TD>" + theResult.getString(1) + "</TD>");

out.println("<TD>" + theResult.getString(2) + "</TD>");

String s = theResult.getString(3);

out.println("<TD><a href=" + s + ">" + s + "</a></TD>");

out.println("</TR>");

theResult.close();//Close the result set

theStatement.close();//Close statement

theConnection.close(); //Close database Connection


}

-223-
catch (Exception e)

out.println(e.getMessage());//Print trapped error.

out.println("</TABLE></P>");

out.println("<P>&nbsp;</P></FONT></BODY></HTML>");

public void destroy()

Here we have used Sun's JDBC-ODBC Bridge, but we can easily replace the driver
in order to connect the servlet to another database. For example, we can use the following
code to connect our program to MySQL database.

Example programs 1:

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

-224-
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JDBCServlet extends HttpServlet


{
public void doGet(HttpServletRequest inRequest,
HttpServletResponse outResponse) throws ServletException,
IOException
{
PrintWriter out = null;
Connection connection = null;
Statement statement;
ResultSet rs;
try
{
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager
getConnection("jdbc:mysql://localhost/products");
statement = connection.createStatement();

outResponse.setContentType("test/html");
out = outResponse.getWriter();

rs = statement.executeQuery("SELECT ID, title, price FROM product");

out.println("<HTML><HEAD><TITLE>Products</TITLE></HEAD>");
out.println("<BODY>");
out.println("<UL>");

while (rs.next()) {
out.println("<LI>" + rs.getString("ID") + " "

-225-
+ rs.getString("title") + " " + rs.getString("price"));
}
out.println("</UL>");
out.println("</BODY></HTML>");
}
catch (ClassNotFoundException e)
{
out.println("Driver Error");
}
catch (SQLException e)
{
out.println("SQLException: " + e.getMessage());
}
}

public void doPost(HttpServletRequest inRequest,


HttpServletResponse outResponse) throws ServletException,
IOException
{
doGet(inRequest, outResponse);
}
}

-226-
Example Program 2:

// You can use this sample servlet as a starting point to connect to

// your database included with useractive account.

//// Portions copied from Sun's HelloWorldServlet.java

// You are free to use this code in any way you chose

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.sql.*;

public

class HelloWorldServlet extends HttpServlet

public void doGet (HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException

res.setContentType("text/html");

ServletOutputStream out = res.getOutputStream();

out.println("<html>");

out.println("<head><title>Hello World</title></head>");

out.println("<body>");

-227-
try

// The newInstance() call is a work around for some


// broken Java implementations

out.println("asdf");

Class.forName("org.gjt.mm.mysql.Driver").newInstance();

catch (Exception E)

out.println("Unable to load driver.");

E.printStackTrace();

out.println("<br><hr>");

try

Connection Conn =
DriverManager.getConnection("jdbc:mysql://sql.useractive.com/USERNAME
?user=USERNAME&password=PASSWORD");

// Do something with the Connection

Statement Stmt = Conn.createStatement();

ResultSet RS = Stmt.executeQuery("SELECT * from SOMETABLE");

while (RS.next())
{
out.println(RS.getString(1));
}

-228-
// Clean up after ourselves

RS.close();

Stmt.close();

Conn.close();

catch (SQLException E)

out.println("SQLException: " + E.getMessage());

out.println("SQLState: " + E.getSQLState());

out.println("VendorError: " + E.getErrorCode());

out.println("<h1>Hello World. Sun... 1.4</h1>");

out.println("</body></html>");

public String getServletInfo()

return "Create a page that says <i>Hello World</i> and send it back";

-229-
Review Questions:

1. Explain Servlet programming in java?

2. What are the Servlet methods?

3. Explain Database connectivity in java?

4. Describe JDBC architecture?

5. Write a java program for access the student details from student database with
servlet?

-230-
Chapter 14
CREATING AND USAGE OF JAVA BEAN

Objectives

ƒ Need for EJB


ƒ EJB component model
ƒ EJB component service and categories
ƒ EJB security services

Introduction
As software developers, we are constantly being asked to build applications in less
time and with less money. And, of course, these applications are expected to be better and
faster than ever before. Object-oriented techniques and component software environments
are in wide use now, in the hope that they can help us build applications more quickly.
Development tools like Microsoft's Visual Basic have made it easier to build applications
faster by taking a building-block approach to software development. Such tools provide a
visual programming model that allows you to include software components rapidly in your
applications.

The JavaBeans architecture brings the component development model to Java, and
that's the subject of this book. But before we get started, I want to spend a little time
describing the component model, and follow that with a general overview of JavaBeans.

The Component Model

Components are self-contained elements of software that can be controlled


dynamically and assembled to form applications. But that's not the end of it. These
components must also interoperate according to a set of rules and guidelines. They must
behave in ways that are expected. It's like a society of software citizens. The citizens
(components) bring functionality, while the society (environment) brings structure and order.

-231-
JavaBeans is Java's component model. It allows users to construct applications by
piecing components together either programmatically or visually (or both). Support of visual
programming is paramount to the component model; it's what makes component-based
software development truly powerful.

The model is made up of an architecture and an API (Application Programming


Interface). Together, these elements provide a structure whereby components can be
combined to create an application. This environment provides services and rules, the
framework that allows components to participate properly. This means that components are
provided with the tools necessary to work in the environment, and they exhibit certain
behaviors that identify them as such. One very important aspect of this structure is
containment. A container provides a context in which components can interact. A common
example would be a panel that provides layout management or mediation of interactions for
visual components. Of course, containers themselves can be components.

As mentioned previously, components are expected to exhibit certain behaviors and


characteristics in order to participate in the component structure and to interact with the
environment, as well as with other components. In other words, there are a number of
elements that, when combined, define the component model. These are described in more
detail in the following sections.

Discovery and Registration

Class and interface discovery is the mechanism used to locate a component at run-
time and to determine its supported interfaces so that these interfaces can be used by others.
The component model must also provide a registration process for a component to make
itself and its interfaces known. The component, along with its supported interfaces, can then
be discovered at run-time. Dynamic (or late) binding allows components and applications to
be developed independently. The dependency is limited to the "contract" between each
component and the applications that use it; this contract is defined by interfaces that the
component supports. An application does not have to include a component during the
development process in order to use it at run-time; it only needs to know what the component

-232-
is capable of doing. Dynamic discovery also allows developers to update components
without having to rebuild the applications that use them.

This discovery process can also be used in a design-time environment. In this case, a
development tool may be able to locate a component and make it available for use by the
designer. This is important for visual programming environments, which are discussed later.

Raising and Handling of Events

An event is something of importance that happens at a specific point in time. An


event can take place due to a user action such as a mouse click when the user clicks a mouse
button, an event takes place. Events can also be initiated by other means. Imagine the heating
system in your house. It contains a thermostat that sets the desired comfort temperature,
keeps track of the current ambient temperature, and notifies the boiler when its services are
required. If the thermostat is set to keep the room at 70 degrees Fahrenheit, it will notify the
boiler to start producing heat if the temperature dips below that threshold. Components will
send notifications to other objects when an event takes place in which those objects have
expressed an interest.

Persistence

Generally, all components have state. The thermostat component has state that
represents the comfort temperature. If the thermostat were a software component of a
computer-based heating control system, we would want the value of the comfort temperature
to be stored on a non-volatile storage medium (such as the hard disk). This way if we shut
down the application and brought it back up again, the thermostat control would still be set to
70 degrees. The visual representation and position of the thermostat relative to other
components in the application would be restored as well.

-233-
Components must be able to participate in their container's persistence mechanism so
that all components in the application can provide application-wide persistence in a uniform
way. If every component were to implement its own method of persistence, it would be
impossible for an application container to use components in a general way. This wouldn't be
an issue if reuse weren't the goal. If we were building a monolithic temperature control
system we might create an application-specific mechanism for storing state. But we want to
build the thermostat component so that it can be used again in another application, so we
have to use a standard mechanism for persistence.

Visual Presentation

The component environment allows the individual components to control most of the
aspects of their visual presentation. For example, imagine that our thermostat component
includes a display of the current ambient temperature. We might want to display the
temperature in different fonts or colors depending on whether we are above, below, or at the
comfort temperature. The component is free to choose the characteristics of its own visual
presentation. Many of these characteristics will be properties of the component (a topic that
will be discussed later). Some of these visual properties will be persistent, meaning that they
represent some state of the control that will be saved to, and restored from, persistent storage.

Layout is another important aspect of visual presentation. This concerns the way in
which components are arranged on the screen, how they relate to one another, and the
behavior they exhibit when the user interacts with them. The container object that holds an
assembly of components usually provides some set of services related to the layout of the
component. Let's consider the thermostat and heating control application again. This time,
the user decides to change the size of the application window. The container will interact
with the components in response to this action, possibly changing the size of some of the
components. In turn, changing the size of the thermostat component may cause it to alter its
font size.

-234-
As you can see, the container and the component work together to provide a single
application that presents itself in a uniform fashion. The application appears to be working as
one unit, even though with the component development model, the container and the
components probably have been created separately by different developers.

Support of Visual Programming

Visual programming is a key part of the component model. Components are


represented in toolboxes or palettes. The user can select a component from the toolbox and
place it into a container, choosing its size and position. The properties of the component can
then be edited in order to create the desired behavior. Our thermostat control might present
some type of user interface to the application developer to set the initial comfort temperature.
Likewise, the choice of font and color will be selectable in a similar way. None of these
manipulations require a single line of code to be written by the application developer. In fact,
the application development tool is probably writing the code for you. This is accomplished
through a set of standard interfaces provided by the component environment that allow the
components to publish, or expose, their properties. The development tool can also provide a
means for the developer to manipulate the size and position of components in relation to each
other. The container itself may be a component and allow its properties to be edited in order
to alter its behavior.

The JavaBeans Architecture

JavaBeans is architecture for both using and building components in Java. This
architecture supports the features of software reuse, component models, and object
orientation. One of the most important features of JavaBeans is that it does not alter the
existing Java language. If you know how to write software in Java, you know how to use and
create Beans. The strengths of Java are built upon and extended to create the JavaBeans
component architecture.

-235-
Although Beans are intended to work in a visual application development tool, they
don't necessarily have a visual representation at run-time (although many will). What this
does mean is that Beans must allow their property values to be changed through some type of
visual interface, and their methods and events should be exposed so that the development
tool can write code capable of manipulating the component when the application is executed.

Creating a Bean doesn't require any advanced concepts. So before I go any further,
here is some code that implements a simple Bean:

public class MyBean implements java.io.Serializable


{
protected int theValue;
public MyBean()
{
}
public void setMyValue(int newValue)
{
theValue = newValue;
}

public int getMyValue()


{
return theValue;
}
}

This is a real Bean named MyBean that has state (the variable theValue) that will
automatically be saved and restored by the JavaBeans persistence mechanism, and it has a
property named MyValue that is usable by a visual programming environment. This Bean
doesn't have any visual representation, but that isn't a requirement for a JavaBean component.

-236-
JavaSoft is using the slogan "Write once, use everywhere." Of course "everywhere" means
everywhere the Java run-time environment is available. But this is very important. What it
means is that the entire run-time environment required by JavaBeans is part of the Java
platform. No special libraries or classes have to be distributed with your components. The
JavaBeans class libraries provide a rich set of default behaviors for simple components (such
as the one shown earlier). This means that you don't have to spend your time building a lot of
support for the Beans environment into your code.

The design goals of JavaBeans are discussed in Sun's white paper, "Java Beans: A
Component Architecture for Java." This paper can be found on the JavaSoft web site
at http://splash.javasoft.com/beans/WhitePaper.html. It might be interesting to review these
goals before we move on to the technology itself, to provide a little insight into why certain
aspects of JavaBeans are the way they are.

Compact and Easy

JavaBeans components are simple to create and easy to use. This is an important goal
of the JavaBeans architecture. It doesn't take very much to write a simple Bean, and such a
Bean is lightweight it doesn't have to carry around a lot of inherited baggage just to support
the Beans environment. If a Bean does not require the advanced features of the architecture,
it doesn't get them, nor does it get the code that goes with them. This is an important concept.
The JavaBeans architecture scales upward in complexity, not downward like other
component models. This means it really is easy to create a simple Bean. (The previous
example shows just how simple a Bean can be.)

Portable

Since JavaBeans components are built purely in Java, they are fully portable to any
platform that supports the Java run-time environment. All platform specifics, as well as
support for JavaBeans, are implemented by the Java virtual machine. You can be sure that
when you develop a component using JavaBeans it will be usable on all of the platforms that
support Java (version 1.1 and beyond). These range from workstation applications and web
browsers to servers, and even to devices such as PDAs and set-top boxes.

-237-
Leverages the Strengths of the Java Platform

JavaBeans uses the existing Java class discovery mechanism. This means that there
isn't some new complicated mechanism for registering components with the run-time system.

As shown in the earlier code example, Beans are lightweight components that are
easy to understand. Building a Bean doesn't require the use of complex extensions to the
environment. Many of the Java supporting classes are Beans, such as the windowing
components found in java.awt.

The Java class libraries provide a rich set of default behaviors for components. Use of
Java Object Serialization is one example a component can support the persistence model by
implementing the java.io.Serializable interface. By conforming to a simple set of design
patterns (discussed later in this chapter), you can expose properties without doing anything
more than coding them in a particular style.

Flexible Build-Time Component Editors

Developers are free to create their own custom property sheets and editors for use
with their components if the defaults aren't appropriate for a particular component. It's
possible to create elaborate property editors for changing the value of specific properties, as
well as create sophisticated property sheets to house those editors.

Imagine that you have created a Sound class that is capable of playing various sound
format files. You could create a custom property editor for this class that listed all of the
known system sounds in a list. If you have created a specialized color type
called PrimaryColor, you could create a color picker class to be used as the property editor
for PrimaryColor that presented only primary colors as choices.

The JavaBeans architecture also allows you to associate a custom editor with your
component. If the task of setting the property values and behaviors of your component is
complicated, it may be useful to create a component wizard that guides the user through the
steps. The size and complexity of your component editor is entirely up to you.

-238-
JavaBeans Overview

The JavaBeans white paper defines a Bean as follows:

A Java Bean is a reusable software component that can be manipulated visually in a


builder tool.

Well, if you have to sum it up in one sentence, this is as good as any. But it's pretty
difficult to sum up entire component architecture in one sentence. Beans will range greatly in
their features and capabilities. Some will be very simple and others complex; some will have
a visual aspect and others won't. Therefore, it isn't easy to put all Beans into a single
category. Let's take a look at some of the most important features and issues surrounding
Beans. This should set the stage for the rest of the book, where we will examine the
JavaBeans technology in depth.

Properties, Methods, and Events

Properties are attributes of a Bean that are referenced by name. These properties are
usually read and written by calling methods on the Bean specifically created for that purpose.
A property of the thermostat component mentioned earlier in the chapter could be the
comfort temperature. A programmer would set or get the value of this property through
method calls, while an application developer using a visual development tool would
manipulate the value of this property using a visual property editor.

The methods of a Bean are just the Java methods exposed by the class that
implements the Bean. These methods represent the interface used to access and manipulate
the component. Usually, the set of public methods defined by the class will map directly to
the supported methods for the Bean, although the Bean developer can choose to expose only
a subset of the public methods.

-239-
Events are the mechanism used by one component to send notifications to another.
One component can register its interest in the events generated by another. Whenever the
event occurs, the interested component will be notified by having one of its methods invoked.
The process of registering interest in an event is carried out simply by calling the appropriate
method on the component that is the source of the event. In turn, when an event occurs a
method will be invoked on the component that registered its interest. In most cases, more
than one component can register for event notifications from a single source. The component
that is interested in event notifications is said to be listening for the event.

Introspection

Introspection is the process of exposing the properties, methods, and events that a
JavaBean component supports. This process is used at run-time, as well as by a visual
development tool at design-time. The default behavior of this process allows for the
automatic introspection of any Bean. A low-level reflection mechanism is used to analyze the
Bean's class to determine its methods. Next it applies some simple design patterns to
determine the properties and events that are supported. To take advantage of reflection, you
only need to follow a coding style that matches the design pattern. This is an important
feature of JavaBeans. It means that you don't have to do anything more than code your
methods using a simple convention. If you do, your Beans will automatically support
introspection without you having to write any extra code. Design patterns are explained in
more detail later in the chapter.

This technique may not be sufficient or suitable for every Bean. Instead, you can
choose to implement a BeanInfo class which provides descriptive information about its
associated Bean explicitly. This is obviously more work than using the default behavior, but
it might be necessary to describe a complex Bean properly. It is important to note that the
BeanInfo class is separate from the Bean that it is describing. This is done so that it is not
necessary to carry the baggage of the BeanInfo within the Bean itself.

-240-
If you're writing a development tool, an Introspector class is provided as part of the
Beans class library. You don't have to write the code to accomplish the analysis, and every
tool vendor uses the same technique to analyze a Bean. This is important to us as
programmers because we want to be able to choose our development tools and know that the
properties, methods, and events that are exposed for a given component will always be the
same.

Customization

When you are using a visual development tool to assemble components into
applications, you will be presented with some sort of user interface for customizing Bean
attributes. These attributes may affect the way the Bean operates or the way it looks on the
screen. The application tool you use will be able to determine the properties that a Bean
supports and build a property sheet dynamically. This property sheet will contain editors for
each of the properties supported by the Bean, which you can use to customize the Bean to
your liking. The Beans class library comes with a number of property editors for common
types such as float, boolean, and String. If you are using custom classes for properties, you
will have to create custom property editors to associate with them.

In some cases the default property sheet that is created by the development tool will
not be good enough. You may be working with a Bean that is just too complex to customize
easily using the default sheet. Beans developers have the option of creating a customizer that
can help the user to customize an instance of their Bean. You can even create smart wizards
that guide the user through the customization process.

Customizers are also kept separate from the Bean class so that it is not a burden to the
Bean when it is not being customized. This idea of separation is a common theme in the
JavaBeans architecture. A Bean class only has to implement the functionality it was designed
for; all other supporting features are implemented separately.

-241-
Persistence

It is necessary that Beans support a large variety of storage mechanisms. This way,
Beans can participate in the largest number of applications. The simplest way to support
persistence is to take advantage of Java Object Serialization. This is an automatic mechanism
for saving and restoring the state of an object. Java Object Serialization is the best way to
make sure that your Beans are fully portable, because you take advantage of a standard
feature supported by the core Java platform. This, however, is not always desirable. There
may be cases where you want your Bean to use other file formats or mechanisms to save and
restore state. In the future, JavaBeans will support an alternative externalization mechanism
that will allow the Bean to have complete control of its persistence mechanism.

Design-Time vs. Run-Time

JavaBeans components must be able to operate properly in a running application as


well as inside an application development environment. At design-time the component must
provide the design information necessary to edit its properties and customize its behavior. It
also has to expose its methods and events so that the design tool can write code that interacts
with the Bean at run-time. And, of course, the Bean must support the run-time environment.

Visibility

There is no requirement that a Bean be visible at run-time. It is perfectly reasonable


for a Bean to perform some function that does not require it to present an interface to the
user; the Bean may be controlling access to a specific device or data feed. However, it is still
necessary for this type of component to support the visual application builder. The
component can have properties, methods, and events, have persistent state, and interact with
other Beans in a larger application. An "invisible" run-time Bean may be shown visually in
the application development tool, and may provide custom property editors and customizers.

-242-
Multithreading

The issue of multithreading is no different in JavaBeans than it is in conventional


Java programming. The JavaBeans architecture doesn't introduce any new language
constructs or classes to deal with threading. You have to assume that your code will be used
in a multithreaded application. It is your responsibility to make sure your Beans are thread-
safe. Java makes this easier than in most languages, but it still requires some careful planning
to get it right. Remember, thread-safe means that your Bean has anticipated its use by more
than one thread at a time and has handled the situation properly.

Security

Beans are subjected to the same security model as standard Java programs. You
should assume that your Bean is running in an untrusted applet. You shouldn't make any
design decisions that require your Bean to be run in a trusted environment. Your Bean may
be downloaded from the World Wide Web into your browser as part of someone else's
applet. All of the security restrictions apply to Beans, such as denying access to the local file
system, and limiting socket connections to the host system from which the applet was
downloaded.

If your Bean is intended to run only in a Java application on a single computer, the
Java security constraints do not apply. In this case you might allow your Bean to behave
differently. Be careful, because the assumptions you make about security could render your
Bean useless in a networked environment.

Using Design Patterns

The JavaBeans architecture makes use of patterns that represent standard conventions
for names, and type signatures for collections of methods and interfaces. Using coding
standards is always a good idea because it makes your code easier to understand, and
therefore easier to maintain. It also makes it easier for another programmer to understand the
purpose of the methods and interfaces used by your component. In the JavaBeans
architecture, these patterns have even more significance. A set of simple patterns are used by

-243-
the default introspection mechanism to analyze your Bean and determine the properties,
methods, and events that are supported. These patterns allow the visual development tools to
analyze your Bean and use it in the application being created. The following code fragment
shows one such pattern:

public void setTemperatureColor(Color newColor)


{
...
}

public Color getTemperatureColor()


{
...
}

These two methods together use a pattern that signifies that the Bean contains a
property named TemperatureColor of type Color. No extra development is required to expose
the property. The various patterns that apply to Beans development will be pointed out and
discussed throughout this book. I'll identify each pattern where the associated topic is being
discussed.

NOTE: The use of the term "design pattern" here may be confusing to some readers.
This term is commonly used to describe the practice of documenting a reusable design in
object-oriented software. This is not entirely different than the application of patterns here. In
this case, the design of the component adheres to a particular convention, and this convention
is reused to solve a particular problem.

As mentioned earlier, this convention is not a requirement. You can implement a


specific BeanInfo class that fully describes the properties, methods, and events supported by
your Bean. In this case, you can name your methods anything you please.

-244-
JavaBeans vs. ActiveX

JavaBeans is certainly not the first component architecture to come along. Microsoft's
ActiveX technology is based upon COM, their component object model. ActiveX offers
alternative component architecture for software targeted at the various Windows platforms.
So how do you choose one of these technologies over the other? Organizational, cultural, and
technical issues all come into play when making this decision. ActiveX and JavaBeans are
not mutually exclusive of each other Microsoft has embraced Java technology with products
like Internet Explorer and Visual J++, and Sun seems to have recognized that the desktop is
dominated by Windows and has targeted Win32 as a strategic platform for Java. It is not in
anyone's best interest to choose one technology to the exclusion of another. Both are
powerful component technologies. I think we should choose a technology because it supports
the work we are doing, and does so in a way that meets the needs of the customer.
EJB Component Services and Categories:

EJB is one of the standards for building software components for enterprise
information systems. The EJB specification makes use of numerous standard Java API's to
provide a rich set of services to developers. There are two main kinds of EJB components
called entity beans and session beans.

Persistence Service-Entity Beans:

Many business systems today use a relational database to store data when it is not in
main memory. Entity Beans provide some help in manipulating persistent data. An example
of an entity bean might be a customer, order, student, patient etc..A developer can specify an
entity bean as using container managed persistence (CMP) or bean managed persistence
(BMP). For CMP, the EJB container is responsible for saving/loading the state of the
component i.e., the container implements the database operations (normally referring to a
mapping of attributes to table columns supplied in XML files called deployment descriptors
that are packaged with an EJB). Think of a container as a virtual server running inside the
EJB application server.

-245-
Bean managed persistence (BMP) requires the bean's developer to implement the
database operations (normally using Java's JDBC API). CMP is usually restricted to mapping
a bean’s attributes to columns in a single database table. i.e. each entity bean represents one
row in that table thus avoiding many of the OO to RDBMS mapping issues. Anything more
sophisticated often requires switching to bean managed persistence or using session beans
altogether.

Both for CMP and BMP, EJB provides database connection pooling so you do not
have to worry about pooling database connections yourself. EJB also provides object pooling
for memory-less session beans. Object pooling does not make sense for entity beans since
entity beans require a single client. For example a client may want to create a student entity
bean to create a new student (or acquire an existing student), then the client may use the

Notice that COM+ provide only equivalent of session beans and have no counter part
to entity beans. It is a debatable issue whether entity beans make your life easier or are
counter productive. Supposedly Microsoft pursued an idea similar to entity beans in COM+
(called in memory database - IMDB) but dropped it in the final release due to performance
problems (perhaps that is why the EJB is much slower in benchmarks as compared to COM+
and dot net).

For every entity bean, you must create two different java interfaces (home interface
and remote interface), and implement the component class. The component class implements
the EntityBean interface. The EntityBean interface has methods called:
EjbActivate – called when a bean is used from the object pool.

ejbLoad – When using CMP, ejbLoad is called by container after it has


loaded the bean from database. The code here could be empty
for CMP. For BMP, you provide the code to load it from the
database.

EjbPassivate – called when a bean is released to the object pool.

-246-
EjbRemove – responsible for removing an entity bean from the database. For
CMP, if you want to keep the oject in database, throw a
RemoveException.

ejbStore - In CMP, it is called by container before it stores the bean in the


database. The code here could be empty for CMP. For BMP,
you provide the code to Store it in the database.

SetEntityContext – called by the container when an entity bean is created, the code
stores its context in a local variable.

UnsetEntityContext – called to inform the bean that it is no longer being used by the
container.

When you develop an entity bean class, you also write an ejbCreate method. The code
here creates a new instance of the bean and initializes the attributes of the class from the
database. If you are using BMP, you need to write the code to read the values from the
database and copy them into the class variables.

If you are using BMP, you also write several finder methods for locating the bean.
For CMP, you indicate to the container how to perform queries when you configure the bean.

Steps in Creating an EJB:

There are 5 things that need to be done in creating an EJB.

1. Create the bean class.


2. Create the home interface. This is used to create or find an existing bean.
3. Create the remote interface.
4. Create the deployment descriptor file (all modern EJB servers now require an XML file
instead of the manifest file).
5. Create the jar file.

-247-
The last two steps can be accomplished by a deployment wizard. Finally you need to
deploy the jar file in the application server.

Example – Entity Bean using CMP:

We will create a Student entity bean corresponding to the Students table in the StDb
database.

Step 1: Creating the bean. Create a folder called student. Type the following file
StudentEJB.java in it.

//--- StudentEJB.java --- uses CMP


package student;
import javax.ejb.*;
// A data object representing a student in Students table in stdb database
public class StudentEJB
implements EntityBean, java.io.Serializable
{
public int studentID;
public String firstName;
public String lastName;

-248-
public String address;
public String major;

private EntityContext context;

public StudentEJB()
{

public StudentKey ejbCreate(int ID, String fName, String lName)


throws CreateException
{
if ((ID == 0) || ((fName == null) && (lName == null)))
{
throw new CreateException(
"You must supply at least ID and first or last name");
}
studentID = ID;
firstName = fName;
lastName = lName;
return null;
}

public int getStudentID()


{
return studentID;
}

-249-
public void setStudentID(int ID)
{
studentID = ID;
}

public String getFirstName()


{
return firstName;
}
public void setFirstName(String fName)
{
firstName = fName;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String lName)
{
lastName = lName;
}
public String getAddress()
{
return address;
}
public void setAddress(String addr)
{
address = addr;
}

-250-
public String getMajor()
{
return major;
}
public void setMajor(String maj)
{
major = maj;
}
//--- EntityBean interface methods. For CMP, these could be empty
// except for set/getEntityContext
public void ejbActivate()
{

}
public void ejbPassivate()
{

}
public void ejbLoad()
{
}
public void ejbStore()
{
}
public void ejbRemove()
{
}
public void setEntityContext(EntityContext aContext)
{
context = aContext;
}

-251-
public void unsetEntityContext()
{
context = null;
}
}
Step 2:

Create the Home interface. This is used by the client to either create or locate a bean.
Type the following in a file called StudentHome.java. Note that the Home interface must
contain a create method with the same signature as the ejbCreate method in the bean class
except that the create method throws the RemoteException.
//--- StudentHome.java ---
package student;
import javax.ejb.*;
import java.rmi.RemoteException;
import java.util.*;
public interface StudentHome extends EJBHome
{
public Student create(int ID, String firstName, String lastName)
throws RemoteException, CreateException;

public Student findByPrimaryKey(StudentKey key)


throws FinderException, RemoteException;

public Collection findByLastName(String lastName)


throws FinderException, RemoteException;

public Collection findByFirstName(String firstName)


throws FinderException, RemoteException;

public Collection findByMajor(String major)


throws FinderException, RemoteException;
}

-252-
Step 3:

Creating the remote interface. Create a file called Student.java as shown below. All
the methods in the remote interface should have corresponding methods in the bean class.
Remember the client will interact with the bean using the remote interface (recall the RMI
example).

//---Student.java---- remote interface


package student;

import javax.ejb.EJBObject;
import java.rmi.RemoteException;

public interface Student extends EJBObject


{
public int getStudentID() throws RemoteException;
public void setStudentID(int ID) throws RemoteException;

public String getFirstName() throws RemoteException;


public void setFirstName(String fName) throws RemoteException;

public String getLastName() throws RemoteException;


public void setLastName(String lName) throws RemoteException;

public String getAddress() throws RemoteException;


public void setAddress(String addr)
throws RemoteException;

public String getMajor() throws RemoteException;


public void setMajor(String maj)

throws RemoteException;
}

-253-
Step 4: Creating the deployment descriptor.

Step 5: Creating the jar file.

Step 6: Deploying the EJB.

Creating the Client:

Create a jsp file called StudentClient.jsp as shown below:

<%@ page language="java" import="javax.naming.*,student.*" %>

<%@ page import="javax.rmi.PortableRemoteObject,java.util.*" %>

<html>
<body>
<pre>
<%
try
{
Context initial = new InitialContext();
Object studentRef = initial.lookup("Student");

student.StudentHome home =
(student.StudentHome) PortableRemoteObject.narrow(
studentRef, student.StudentHome.class);

Student stu = home.create(857, "Ausif", "Mahmood");

out.println("Student Created");
}

-254-
catch (Exception exc)
{
exc.printStackTrace(new PrintWriter(out));
}
%>
</pre>
</body>
</html>

Example of an Entity Bean using BMP (Bean Managed Persistence):

When using BMP, you need to write the database code in ejbCreate, ejbLoad,
ejbStore, and ejbRemove methods. You also need to provide some finder methods.

The result is data driven object models (yeuch) or difficulty in implementing a non-
trivial best practice domain object model using entity beans and container managed
persistence. In many cases the proprietary persistence tools offer better solutions. Various
attempts have been made to overcome these shortcomings using the other blend of EJB,
Session beans, in conjunction with a proprietary persistence tool but none of these
approaches are standardized.

Communication services

An enterprise system must manage communications between client machines and


server applications, between server applications on the same machine and on different
machines within an enterprise, and between the servers of multiple enterprises.

EJB's use a number of standard Java API's to provide these services. The JNDI
naming service is used to find remote references to factory objects used to create, retrieve
and delete EJB's. The factory objects are remote objects implementing an EJB's Home
Interface. The only way to invoke an operation on an EJB is via it's Remote Interface. The
RMI over IIOP protocol and API are used for invoking operations on EJB's via their remote

-255-
and home interfaces. Again there is little new here except a standardizing of the use of Home
and Remote interfaces.

The implementation of the standard EJB Home and Remote interfaces pollutes a
Problem Domain class with a large amount of EJB specific code (yeuch - but most
distributed object architectures do similar things). Remote objects also require artificially
large grain operations to avoid large numbers of network calls that result in poor performance
(yeuch - but again most distributed object architectures require the same).

Thankfully J2EE provides the JSP/Servlet API's and services that are an excellent
alternative approach to client/server communications when menu-driven, form-oriented user
interfaces are sufficient.

Transaction services
Probably the biggest advantage gained from using EJB's is its support for declarative
transaction management. It is no longer necessary to program explicit transaction control
using fairly complex API's like OMG's Object Transaction Service, its Java implementation,
JTS or your own API. Instead transactional characteristics of objects are declared in
deployment descriptors. Nothing new again - Microsoft was here first with their MTS
product.

Changing transactional behavior no longer requires changes to source code. Objects


of the same class can be deployed with different transactional characteristics in different
applications. The responsibility for correct transactional behavior now falls to the assembler
or deployer of the EJB's instead of the developer. The developer does need to consider how
her bean might react with different transaction characteristics and code and test
appropriately; adding flexibility always adds to the number of paths that need to be tested.

Declarative transaction management does little to help resolve isolation level and
pessimistic vs optimistic locking issues and these capabilities can vary across application
servers and databases.

-256-
Security Services

Authentication

Critical to any set of security services is the ability of the system to establish the
identity of a user. End-users of enterprise systems like to have a single-sign-on where they
provide confirmation of their identity once. Most enterprise applications however, require a
user to identify themselves each time they start the application. This leads to multiple user ids
and multiple passwords (with different rules about what makes a good password) per user -
inconvenient for the user, a headache for system administrators ... but heaven for that special
breed of data security officer that would prefer people did not use a system at all (thus
keeping the data completely secure) :-)

Authentication is not specified in either the EJB specification or the J2EE client
component specification. This makes this area subject to vendor specifics. A common
approach when using EJB's is to use the JNDI API to provide authenticating information to
access a server or resources on a server. A future version of J2EE may require the use of the
Java Authentication and Authorization Service (JAAS).

Authorization
Authorization is the ability of a system to restrict what each user can see and do.

There are at least three variables in authorization of a non-trivial enterprise


application:

1. user role
2. object ownership
3. object state

-257-
User role based security assigns each user to one or more roles. Each role is given
specific permissions and/or capabilities. EJB's provide a declarative role-based security
mechanism. Each role is granted access to methods of classes by declarations in deployment
descriptors. However, method level is often too granular and an administrative headache
where multiple methods exist to perform the same operation in slightly different ways. In
many cases, a role is allowed to see objects in a class or not, update objects in a class or not
and delete objects in a class or not - but this level of granularity is not supported by EJB's.

More complicated security rules depend on whether or not the user owns an object
(maybe they created it, or they are assigned to a team that created it). It gets even more
complicated when access depends also on the state of the object. For example, once
submitted to a manager, an owner may not be able to update their object anymore.

The only support provided by EJB's for this sort of authorization is a container
supplied method to inquire if a user belongs to a certain role. Many organizations are looking
at business rules engines to help manage these more complex access rules.

Auditing

Recording who did what and when they did it is a common requirement within
business systems especially where financial transactions are involved. EJB's do not provide
any specific help in this area and can be a distinct hindrance given their restrictions on
writing to files. The JMS messaging API can be used to send messages to a logging service.

Performance

A general rule of thumb is, "The more generic a solution, the slower the
performance". EJB's are no exception. The overheads of the EJB container services are
significant.

-258-
Where user numbers and usage patterns benefit from EJB's resource management
capabilities this performance overhead may be offset. Specifically, EJB containers may reuse
instances from pools of objects to reduce the overhead of creating and destroying objects. An
EJB container may also unload (passivate) and reload (activate) beans from/to memory to
reduce memory usage. Obviously different vendors EJB containers and servers perform
differently making the choice of vendor important (and the pain of switching vendor more
likely to be felt).

Design Patterns

Another big issue with EJB's are the restrictions on writing re-entrant code; that is
code from bean A that calls bean B which then calls back on bean A. Call backs are used in
many popular OO design patterns but EJB's currently make it hard to use call backs.

Summary

This has been a very short introduction to each of the enterprise system services
above. I hope to expand on each one in future issues with help from my colleagues at
TogetherSoft and your feedback.

Java's big claim was 'Write Once, Run Anywhere' and today it largely lives up to that
claim. However, EJB's do not! To run Enterprise Java Beans, we are required to have an
application server product written by a third party vendor. The EJB 1.1 specification,
although tighter than 1.0 still allows for numerous variations between different vendors' EJB
Containers and application servers. Anyone who has had to switch application server
products during development knows that it is not straightforward. However, as the standard
matures this problem will hopefully decrease.

Much work remains before EJB's become a generic solution that meet 80% of
developers' needs. The biggest contribution EJB's and J2EE technology are likely to make is
the standardization of the interfaces to these commonly needed services.

-259-
Where it fits, EJB technology is there to be used today but, as always, developers
need to continue to pick the right tool for the job.

Review Questions:
1. Explain java Bean?

2. Explain Java Bean component model?

3. Explain Java Bean Architecture?

4. Describe EJB, EJB Component services and categories?

5. How to create EJB?

6. Explain EJB Services?

7. Explain EJB security services?

-260-

You might also like