DMC1936
DMC1936
(DISTANCE MODE)
DMC 1936
III Semester
LAB MANUAL
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
-5-
-6-
TABLE OF CONTENTS
Chapter. No. Title Page Number
-7-
-8-
Chapter 1
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
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.
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.
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.
-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.
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.
-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.
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:
-14-
Chapter 2
SENDING AND RECEIVING MAILS FROM ONE OR MORE
EMAIL CLIENT
Objectives
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.
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.
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.
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.
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:
-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:
-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:
-22-
Chapter 3
VIDEO CONFERENCING DEMONSTRATION
Objectives
-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.
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.
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.
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
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
-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.
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.
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.
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".
-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.
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.
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.
Participants being self-conscious about being on camera, especially new users and
older generations.
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.
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.
-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:
-34-
Chapter 4
Objectives
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
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
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.
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.
-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
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
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%
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:
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
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:
-39-
v. System variables click on new
vi.
-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
-42-
x. Finished click on ok
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.
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:
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.
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>
Most ftp client programs will also respond with a list of available commands if you
enter a "?":
ftp> ?
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:
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:
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:
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:
If you are transferring a binary file, use the binary command before the put
command:
ftp> binary
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:
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:
5. What is Telnet?
6. Why CUTCP?
-50-
Chapter 6
Objectives
-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.
The primary tag used in HTML forms is the <input /> tag. The input tag prompts your
readers to input data to your Web server.
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
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>
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>
-56-
Male
Female
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>
I have a bike:
I have a car:
I have an airplane:
-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 can point to any resource on the web: an HTML page, an image, a sound
file, a movie, etc.
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:
Note: The element content doesn't have to be text. You can link from an image or any other
HTML element.
-58-
The href attribute defines the link "address".
Visit Annauniv!
The target attribute defines where the linked document will be opened.
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.
Example:
-59-
A link to the Useful Tips Section from the same document:
<a href="#tips">
Jump to the Useful Tips Section</a>
<a href="http://www.annauniv.com/html_tutorial.htm#tips">
Jump to the Useful Tips Section</a>
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>
<LI> stands for "list item", and is used to start any item in your list.
-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
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>
<OL>
</OL>
</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.
-62-
Heres what the list would look like:
<OL>
<LI> Take web design course </LI>
<OL>
</OL>
</OL>
"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:
-63-
Remember that when you close <OL TYPE= "I"> you only have to use </OL>
1. First Point
a. Sub-Point
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.
1. First thing.
Bulleted sub-point
<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 <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 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
Mixed frameset
This example demonstrates how to make a frameset with three documents, and how
to mix them in rows and columns.
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>
Frame Tags
Tag Description
<noframes> Defines a noframe section for browsers that do not handle frames
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>
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:
-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>
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 ( ) 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> </td>
</tr>
</table>
row 2, cell 1
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 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
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 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
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.
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.
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.
The <EMBED> tag plays audio files in WAV, AIFF, AU, and MIDI formats.
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.
Review Questios:
1. Explain forms and form actions with example?
5. Explain MIDI?
-76-
Chapter 7
WRITING JAVA PROGRAMS BY MAKING USE OF CLASS,
INTERFACE, PACKAGE, ETC FOR THE FOLLOWING
Objectives
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.
void showij ()
-78-
// Create a subclass by extending class A.
class B extends A
{
int k;
void showk()
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();
}
}
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.
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:
-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.
package pkg;
Here, pkg is the name of the package. For example, the following statement creates a
-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
package java.awt.image;
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();
}
}
-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
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.*;
The same example without the import statement looks like this:
-87-
package MyPack;
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
-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):
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.
-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:
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");
}
}
}
-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.
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:
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.
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:
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"
<PARAM NAME="IMAGESOURCE"
VALUE="aDirectory"> -- the directory that has the animation frames (gif, jpg)
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.
-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:
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.*;
-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.
-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.
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.
-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 :
-105-
Here is the java code of the program:
import java.applet.*;
import java.awt.*;
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;
-108-
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
// close anon inner class
}
);
-109-
add(pMain, BorderLayout.CENTER);
makeGUI();
}
-110-
if (i == 11)
{
b.setLabel(".");
}
theKeys.put(b.getLabel(), 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;
}
-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();
}
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;
}
ButtonListener(int listenerType)
{
this.listenerType = listenerType;
}
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 = "";
-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
-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?
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
Thread
-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.
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.
Waiting for Notification – A thread waits for notification from another thread. The
thread sends back to runnable state after sending notification from another thread.
-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.
-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:
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:
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[]){
-128-
Output of the Program is :
C:\j2se6\thread>javac
RunThread.java
C:\j2se6\thread>java
RunThread
Thread started....
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.
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.
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:
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)
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 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 :
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:
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.
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.
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.
-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:
-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
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.
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.
-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.
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.
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.
All methods in a class need not to be synchronized. A class can have both
synchronized and non-synchronized methods.
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.
-149-
There are two ways to synchronized the execution of code:
1. Synchronized Methods
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.
-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.
-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:
-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.
-156-
class Shared
{
int num=0;
boolean value = false;
-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(); }
-158-
public void run()
{
s.get();
}
}
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.
-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)
{
}
}
}
C:\j2se6\thread>javac
DemoWait.java
C:\j2se6\thread>java
DemoWait
Demo1 value is20
value is :40
C:\j2se6\thread>
-162-
Review Questions:
-163-
Chapter 10
READING AND WRITING TEXT FILES
Objectives
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.
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)
-166-
//First create an object of type FileInputStream type using the name of the file.
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.
-167-
The Writer class hierarchy is illustrated below.
-168-
The example below illustrates reading of characters using the FileReader class.
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,
-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
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:
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
Loading an external GIF, PNG JPEG image format file into Java 2D™'s internal
image representation.
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:
Provides a mechanism for creating multiple subimages from a single image data
buffer
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.
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.
-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.
-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:
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.
-177-
Plus Minus
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.
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 :
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
Review Questions:
1. Explain Image files handling in java?
-179-
Chapter 12
WRITING AN RMI APPLICATION TO ACCESS A REMOTE
METHOD
Objectives
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.
-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.
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.
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.
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:
2. Compiling sources.
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.
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 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.
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.
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.
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.
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;
}
-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;
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 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.
package compute;
-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;
-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;
-191-
public Pi(int digits)
{
this.digits = digits;
}
/**
* sufficient precision. */
BigDecimal pi = arctan1_5.multiply(FOUR).subtract
(
arctan1_239).multiply(FOUR);
return pi.setScale(digits,
-192-
BigDecimal.ROUND_HALF_UP);
}
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.
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
Solaris OS or Linux:
cd /home/waldo/src
The jar command displays the following output due to the -v option:
added manifest
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
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
engine\ComputeEngine.java
Solaris OS or Linux:
cd /home/ann/src
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.
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
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
client/ComputePi.java client/Pi.java
mkdir /home/jones/public_html/classes/client
-199-
cp client/Pi.class
/home/jones/public_html/classes/client
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;
};
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.
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.
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:
-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:
- 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:
-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.security.policy property is used to specify the policy file that contains
the permissions you intend to grant.
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:
-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:
-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.
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:
RMIExample.java
// Interface for the RMI remote object.
// Note: Interface must extend from java.rmi.Remote
// Methods must throw RemoteExcpetion
-205-
import java.rmi.*;
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.*;
-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";
Naming.rebind(m_strName, Example);
System.out.println("Server: Ready...");
}
-207-
catch (Exception e)
{
}
}
}
// 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.*;
if (argv.length < 2)
{
System.out.println("Usage: java RMIClient [-m \"MESSAGE\"] [-f INTEGER]");
System.exit(1);
}
-208-
// Command line option flags
System.setSecurityManager(new RMISecurityManager());
-209-
System.out.println("Client: Looking up " + strName + "...");
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);
}
}
}
}
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.
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
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.
Any object argument to a method on a remote object in RMI must implement the
Serializable interface.
-212-
Review Questions:
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
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
Priovide dynamic content like getting the results of a database query and returning
to the client.
Manage information about the state of a stateless HTTP. e.g. an online shopping
car manages request for multiple concurrent customers.
1.init()
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 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()
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.
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.
-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.
-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 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 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 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 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
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.*;
Connection theConnection;
throws ServletException
this.config = config;
-221-
public void service(HttpServletRequest req, HttpServletResponse res)
res.setContentType("text/html");
out.println("<HTML><HEAD><TITLE>Emai
List.</TITLE>");
out.println("</HEAD>");
out.println("<P align=center>");
out.println("<TR>");
out.println("<TD>Name</TD>");
out.println("<TD>E-mail</TD>");
out.println("<TD>Website</TD></TR>");
try
-222-
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
theConnection =
DriverManager.getConnection("jdbc:odbc:emaildb", "admin",
"");
while (theResult.next())
out.println();
out.println("<TR>");
String s = theResult.getString(3);
out.println("</TR>");
theStatement.close();//Close statement
-223-
catch (Exception e)
out.println("</TABLE></P>");
out.println("<P> </P></FONT></BODY></HTML>");
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;
outResponse.setContentType("test/html");
out = outResponse.getWriter();
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());
}
}
-226-
Example Program 2:
// 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
res.setContentType("text/html");
out.println("<html>");
out.println("<head><title>Hello World</title></head>");
out.println("<body>");
-227-
try
out.println("asdf");
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
catch (Exception E)
E.printStackTrace();
out.println("<br><hr>");
try
Connection Conn =
DriverManager.getConnection("jdbc:mysql://sql.useractive.com/USERNAME
?user=USERNAME&password=PASSWORD");
while (RS.next())
{
out.println(RS.getString(1));
}
-228-
// Clean up after ourselves
RS.close();
Stmt.close();
Conn.close();
catch (SQLException E)
out.println("</body></html>");
return "Create a page that says <i>Hello World</i> and send it back";
-229-
Review Questions:
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
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.
-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.
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.
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.
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:
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.
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.
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
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 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.
Visibility
-242-
Multithreading
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.
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:
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.
-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.
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.
-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.
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.
-247-
The last two steps can be accomplished by a deployment wizard. Finally you need to
deploy the jar file in the application server.
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.
-248-
public String address;
public String major;
public StudentEJB()
{
-249-
public void setStudentID(int ID)
{
studentID = ID;
}
-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;
-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).
import javax.ejb.EJBObject;
import java.rmi.RemoteException;
throws RemoteException;
}
-253-
Step 4: Creating the deployment descriptor.
<html>
<body>
<pre>
<%
try
{
Context initial = new InitialContext();
Object studentRef = initial.lookup("Student");
student.StudentHome home =
(student.StudentHome) PortableRemoteObject.narrow(
studentRef, student.StudentHome.class);
out.println("Student Created");
}
-254-
catch (Exception exc)
{
exc.printStackTrace(new PrintWriter(out));
}
%>
</pre>
</body>
</html>
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
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.
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.
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?
-260-