0% found this document useful (0 votes)
23 views

Java Full PDF

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Java Full PDF

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 182

TRINITY COLLEGE FOR WOMEN(ARTS AND SCIENCE)

TRINITY NAGAR, MOHANUR ROAD, NAMAKKAL – 637 002, TAMILNADU


(Permanently affiliated to Periyar University, Salem & 2f and 12b status
Granted by UGC-New Delhi)

Accredited With NAAC A+

DEPARTMENT OF COMPUTER SCIENCE

COURSE FILE

Staff Name : Mrs.A.VIJAYASARATHI

Class : M.Sc-Computer Science

Paper Code : 23PCS06 / II SEMESTER

Paper Name : ADVANCED JAVA PROGRAMMING


PERIYAR UNIVERSITY

PERIYAR PALKALAI NAGAR

SALEM 636 011

MASTER OF SCIENCE IN COMPUTER SCIENCE

SEMESTER PATTERN

Under Choice Based Credit System

REGULATIONS AND SYLLABUS

FOR AFFILIATED COLLEGES

(Effective from the Academic year 2023 - 2024 onwards)


ADVANCED JAVA PROGRAMMING I MSC-CS

ADVANCED JAVA PROGRAMMING

Trinity College For Women, Namakkal


Department of Computer Science
I M.Sc Computer Science
Subject Code: 23PCSC06
Subject Name: Advanced Java Programming

Syllabus

Unit I BASICS OF JAVA


Java Basics Review: Components and event handling – Threading concepts – Networking features –
Media techniques.
Unit II REMOTE METHOD INVOCATION
Remote Method Invocation-Distributed Application Architecture- Creating stubs and skeletons-
Defining Remote objects- Remote Object Activation-Object Serialization-Java Spaces.
Unit III DATABASE
Java in Databases- JDBC principles – database access- Interacting- database search – Creating
multimedia databases – Database support in web applications
Unit IV SERVLETS
Java Servlets: Java Servlet and CGI programming- A simple java Servlet-Anatomy of a java Servlet-
Reading data from a client-Reading http request header-sending data to a client and writing the http
response header-working with cookies
Java Server Pages: JSP Overview-Installation-JSP tags-Components of a JSP page-Expressions-
Scriptlets-Directives-Declarations-A complete example
Unit V ADVANCED TECHNIQUES
JAR file format creation – Internationalization – Swing Programming – Advanced java Techniques
Unit VI Contemporary Issues
Expert lectures, online seminars – webinars

Text Book:
1. Jamie Jaworski, “Java Unleashed”, SAMS Techmedia Publications,1999.
2. Campione, Walrath and Huml, “The Java Tutorial”, AddisonWesley,1999.

Reference Book:
1.Jim Keogh,” The Complete Reference J2EE”, Tata McGrawHill Publishing Company Ltd,2010.
2. David Sawyer McFarland, “JavaScript And JQuery- The Missing Manual”, Oreilly Publications, 3rd
Edition,2011.
3. Deitel and Deitel, “Java How to Program”, Third Edition, PHI/Pearson Education Asia

Website Link:
1.https://www.javatpoint.com/servlet-tutorial
2. https://www.tutorialspoint.com/java/index.htm
3. https://onlinecourses.nptel.ac.in/noc19_cs84/preview

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 1


ADVANCED JAVA PROGRAMMING I MSC-CS

Review of Java Fundamentals:


Java programming language was originally developed by Sun Microsystems which was initiated by
James Gosling and released in 1995 as core component of Sun Microsystems' Java platform (Java 1.0
[J2SE]).
The latest release of the Java Standard Edition is Java SE 8. With the advancement of Java and its
widespread popularity, multiple configurations were built to suit various types of platforms. For
example: J2EE for Enterprise Applications, J2ME for Mobile Applications.
The new J2 versions were renamed as Java SE, Java EE, and Java ME respectively. Java is guaranteed
to be Write Once, Run Anywhere.
Java is −
 Object Oriented − In Java, everything is an Object. Java can be easily extended since it is
based on the Object model.
 Platform Independent − Unlike many other programming languages including C and C++,
when Java is compiled, it is not compiled into platform specific machine, rather into platform
independent byte code. This byte code is distributed over the web and interpreted by the Virtual
Machine (JVM) on whichever platform it is being run on.
 Simple − Java is designed to be easy to learn. If you understand the basic concept of OOP Java,
it would be easy to master.
 Secure − With Java's secure feature it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on public-key encryption.
 Architecture-neutral − Java compiler generates an architecture-neutral object file format,
which makes the compiled code executable on many processors, with the presence of Java
runtime system.
 Portable − Being architecture-neutral and having no implementation dependent aspects of the
specification makes Java portable. Compiler in Java is written in ANSI C with a clean
portability boundary, which is a POSIX subset.
 Robust − Java makes an effort to eliminate error prone situations by emphasizing mainly on
compile time error checking and runtime checking.
 Multithreaded − With Java's multithreaded feature it is possible to write programs that can
perform many tasks simultaneously. This design feature allows the developers to construct
interactive applications that can run smoothly.
 Interpreted − Java byte code is translated on the fly to native machine instructions and is not
stored anywhere. The development process is more rapid and analytical since the linking is an
incremental and light-weight process.
 High Performance − with the use of Just-In-Time compilers, Java enables high performance.
 Distributed − Java is designed for the distributed environment of the internet.
 Dynamic − Java is considered to be more dynamic than C or C++ since it is designed to adapt
to an evolving environment. Java programs can carry extensive amount of run-time information
that can be used to verify and resolve accesses to objects on run-time.

Hello World using Java Programming.


Just to give you a little excitement about Java programming, I'm going to give you a small
conventional C Programming Hello World program, You can try it using Demo link.

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 2


ADVANCED JAVA PROGRAMMING I MSC-CS

Public class MyFirstJavaProgram


{

/* This is my first java program.


* This will print 'Hello World' as the output
*/

Public static void main(String []args)


{
System.out.println("Hello World"); // prints Hello World
}
}

History of Java
James Gosling initiated Java language project in June 1991 for use in one of his many set-top box
projects. The language, initially called 'Oak' after an oak tree that stood outside Gosling's office, also
went by the name 'Green' and ended up later being renamed as Java, from a list of random words.
Sun released the first public implementation as Java 1.0 in 1995. It promised Write Once, Run
Anywhere (WORA), providing no-cost run-times on popular platforms.
On 13 November, 2006, Sun released much of Java as free and open source software under the terms
of the GNU General Public License (GPL).
On 8 May, 2007, Sun finished the process, making all of Java's core code free and open-source, aside
from a small portion of code to which Sun did not hold the copyright.

Tools You Will Need


For performing the examples discussed in this tutorial, you will need a Pentium 200-MHz computer
with a minimum of 64 MB of RAM (128 MB of RAM recommended).
You will also need the following softwares −
 Linux 7.1 or Windows xp/7/8 operating system
 Java JDK 8
 Microsoft Notepad or any other text editor

Popular Java Editors


To write Java programs, you need a text editor. There are even more sophisticated IDEs available in
the market. The most popular ones are briefly described below −
 Notepad − On Windows machine, you can use any simple text editor like Notepad
(recommended for this tutorial) or WordPad. Notepad++ is also a free text editor which
enhanced facilities.
 Netbeans − It is a Java IDE that is open-source and free which can be downloaded
from www.netbeans.org/index.html.
 Eclipse − It is also a Java IDE developed by the Eclipse open-source community and can be
downloaded from www.eclipse.org.
IDE or Integrated Development Environment, provides all common tools and facilities to aid in
programming, such as source code editor, build tools and debuggers etc.

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 3


ADVANCED JAVA PROGRAMMING I MSC-CS

Basics of Java Programming

Java Syntax
Every programming language has certain rules and regulations that a programmer needs to
follow while writing programs. The respective language compiler checks your program for syntax
rules and validation. Java also has lots of constructs and components that make it easier for
programmers to write quality programs.

The “Hello, World” program in the previous tutorial gave you an idea about the basic structure
of a Java program in detail. Now let’s go to the other constructs/components that a Java program will
include.

Java Conventions
Given below are some of the conventions that a Java programmer needs to follow while programming
in Java.

(i) Class names: In Java, the first letter of class name for every class should be uppercase. For
example, a class salary will be named as per the convention as “Salary”.
If you have a class name that is combined using more than one word then each letter of the first word
will be an uppercase letter.

For example, class MyHelloWorld.


(ii) Method name: All method names in Java start with a lowercase letter. If the method name
comprises more than one word, then the first letter of each of these inner words will be uppercase.
Example: display (), myMethod () => these are valid method names in Java.
(iii) Program file name: The filename of the Java program should be the same as the name of the
public class with an extension “.java”.
For example, if the public class name is “MyFirstClass”, then you save this code in the file named
“MyFirstClass.java”.
Note that a java source code may not have any public class. In that case, you can have your name for
the source file.

(iv) Case sensitive: Java programming language is case-sensitive. This means ‘Hi’ and ‘hi’ are two
different parameters.
(v) Main method: The method ‘main’ is the starting point of execution and is a compulsory method in
all Java programs.
Java Identifiers
Identifiers are the names given to various program components like methods, classes, variables,
objects, etc.

A Java programmer has to follow the below rules for identifiers:


TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 4
ADVANCED JAVA PROGRAMMING I MSC-CS

 An identifier should always start with letters (A-Z/a-z) or an underscore character (_) or
currency character ($).
 The identifier cannot have the same name as a Java reserved Keyword.
 Beyond the first character, an identifier can have any combination of characters.
 In Java, like other language syntax, identifiers are also case-sensitive.
Hence as per the above rules, the following identifiers are valid.

myVar, _salary, $sum


The following identifiers are not valid.

123var, *mult, int.


Java Modifiers
Modifiers change the accessibility of variables, methods, etc.

There are two types of modifiers in Java:


 Access modifiers: There are four access modifiers in Java namely, public, protected, private,
and default. These are used to define accessibility for packages, classes, class members, etc.
 Non-access modifiers: Java supports non-access modifiers namely – final, abstract, and
strictfp. These are mainly used to define inheritance, polymorphism style, etc.
Data Types
Any variable that holds the value needs to have a type of the value which it is going to hold i.e.
whether a variable is going to hold a numeric or string or character. This is called the data type of the
variable.

Java has various data types as depicted in the below diagram.

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 5


ADVANCED JAVA PROGRAMMING I MSC-CS

Variables
Java supports the following three types of variables:
 Class or static variables: This type of variable can be accessed without an object.
 Non-static or instance variables: These variables are member variables which are accessed
with the help of a class object.
 Local variables: Local variables are local to a particular block of code and cease to exist out of
this block.
Keywords
There are certain words reserved in Java language for its own use and cannot be used as variable or
identifier names.

The following table gives the list of these words known as “Keywords”.
abstract double int super
assert else interface switch
boolean enum long synchronized
break extends native this
byte final new throw
case finally package throws
catch float private transient
char for protected try
class goto public void
const if return volatile
continue implements short while
default import static
do instance of strictfp
Comments
Comments are the statements that are ignored by the compiler. You can provide comments for your
code to make the code more readable and easy to understand.

Java supports three types of comments:


 Single line comments denoted by ‘//’
 Multi-line comments represented by ‘/*… */’
 Documentation comments denoted by ‘/** ******/
You will learn more about these comments in our subsequent tutorials.

PRIMITIVE DATA TYPES

 int (16-bit)
 float (32-bit)
 double (64-bit
 boolean (true/false)

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 6


ADVANCED JAVA PROGRAMMING I MSC-CS

 char (16-bit unicode)

Operators
Operators are symbols that perform logical and mathematical operations on variables or identifiers.
These variables or identifiers are called Operands.

Java supports various operators as shown in the below diagram:

Decision Making
Also called as control statements. These statements change or control the program execution based on
a particular condition. If the condition is true, a block of code following this condition is executed, else
a different block is executed.

Java has the following control/decision making statements.

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 7


ADVANCED JAVA PROGRAMMING I MSC-CS

Loops
In programming languages, looping is included to repeatedly execute a block of code. The looping
usually starts with a test and the block of code is executed repeatedly for a fixed number of times
called iterations or till a condition is fulfilled.

In Java, you have the following loop constructs.

ARRAYS

Arrays are nothing but a data structure that is used to hold the data elements of the same type
sequentially.
Java arrays are also similar to arrays in C/C++ and other programming languages.

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 8


ADVANCED JAVA PROGRAMMING I MSC-CS

int[] array = new int[5]; // one-dimensional array

it may also be declared as:

int[] array = {1, 2, 3, 4, 5}; // it is initialized and declared at the same time.

Arrays can be of any primitive data type or object. Arrays have an instance variable "length" that we
can access to find out how big the array is. Remember that an Array can throw an
IndexOutOfBoundsException. Make use of it to make your code safe.

VECTORS

Must import java.util.*;

Unlike arrays, vectors can only hold objects, no primitive data types are allowed. Vectors can grow big
and unbounded. You may want to specify the capacity of the vector but you dont need to. The default
capacity is 10 and it doubles in size every time the capacity is reached.

Just like arrays have the "length" instance variable, Vectors have a .size() method that returns the
current size of the vector.

 void .addElement(Object obj)


 void .setElementAt(Object obj, int index)
 Object .elementAt(int index)
 void .insertElementAt(Object obj, int index)
 void .removeElementAt(Object obj, int index)

ENUMERATION

This is an iterator and it is very important concept in data structures for ICS211. An Enumeration lets
us visit every element of a Vector one by one.

Vector v = new Vector();

Enumeration e = v.elements();

While(e.hasMoreElements()){

Object o = e.nextElement;

// we do something with each element.

Java supports:

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 9


ADVANCED JAVA PROGRAMMING I MSC-CS

 Single-dimensional arrays: A sequence of elements of the same type and can be accessed
using an array name.
 Multi-dimensional array: Elements are arranged in the form of rows and columns i.e. in a
matrix form.
Java Class & OOPS
A class is a blueprint of any real-life entity, for example, a car. A class in Java consists of data
variables and the methods or functions that operate on these data.
Data variables or member variables and methods depict the behavior of objects which are instances of
the class. This means the state of the entity represented by a class at any given instant is defined by an
object.

Java Interfaces An interface in Java is a collection of method signatures and fields. An interface does
not have an implementation of methods. A class can inherit from the interface and then implement the
interface methods.
Java Packages
Classes and interfaces that have similar functionality or dependency are grouped to form a package.
The package makes modularization of code easier in Java.

Types of Java programs


Using Java, you can develop the following applications.
1. Java Application: Executed on the client computer
2. Java Applet: Runs in a web browser
3. Java Swing application: Application with a GUI
4. JAR (Java Archive): Packaged application
5. Servlet: Executes on a web server
6. EJB (Enterprise Java Beans): Used to develop websites and runs on a web server.

Components & Event Handling


Normally, a user interacts with an application’s GUI to indicate the tasks that the
application should perform. For example, when you write an e-mail in an e-mail application,
clicking the Send button tells the application to send the e-mail to the specified e-mail addresses.
GUIs are event driven.
When the user interacts with a GUI component, the interaction—known as an event—
drives the program to perform a task. Some common user interactions that cause an application
to perform a task include clicking a button, typing in a text field, selecting an item from a menu,
closing a window and moving the mouse. The code that performs a task in response to an event
is called an event handler, and the overall process of responding to events is known as event
handling.
Event handling is fundamental to Java programming because it is integral to the creation of
many kinds of applications, including applets and other types of GUI-based programs.
Furthermore, any program that uses a graphical user interface, such as a Java application written

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 10


ADVANCED JAVA PROGRAMMING I MSC-CS

for Windows, is event driven.


Events are supported by a number of packages, including java.util, java.awt, and
java.awt.event. Most events to which your program will respond are generated when the user
interacts with a GUI-based program.
Event: Change in the state of an object is known as event i.e. event describes the change in state
of source. Events are generated as result of user interaction with the graphical user interface
components. For example, clicking on a button, moving the mouse, entering a character through
keyboard, selecting an item from list, scrolling the page are the activities that causes an event to
happen.
 Foreground Events - Those events which require the direct interaction of user. They are
generated as consequences of a person interacting with the graphical components in
Graphical User Interface. For example, clicking on a button, moving the mouse, entering
a character through keyboard, selecting an item from list, scrolling the page etc.
 Background Events - Those events that require the interaction of end user are known as
background events. Operating system interrupts, hardware or software failure, timer
expires, an operation completion are the example of background events.
Event Handling: is the mechanism that controls the event and decides what should happen if an
event occurs. This mechanism have the code which is known as event handler that is executed
when an event occurs.

Two Event Handling Mechanisms

The way in which events are handled changed significantly between the original version of Java
(1.0) and all subsequent versions of Java, beginning with version 1.1.

The Delegation Event Model

The modern approach to handling events is based on the delegation event model, which
defines standard and consistent mechanisms to generate and process events. Its concept is quite
simple: a source generates an event and sends it to one or more listeners. In this scheme, the
listener simply waits until it receives an event. Once an event is received, the listener processes
the event and then returns.

The advantage of this design is that the application logic that processes events is cleanly
separated from the user interface logic that generates those events. A user interface element is
able to “delegate” the processing of an event to a separate piece of code.
In the delegation event model, listeners must register with a source in order to receive an
event notification. This provides an important benefit: notifications are sent only to listeners that
want to receive them. This is a more efficient way to handle events than the design used by the
original Java 1.0 approach. Previously, an event was propagated up the containment hierarchy
until it was handled by a component. This required components to receive events that they did

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 11


ADVANCED JAVA PROGRAMMING I MSC-CS

not process, and it wasted valuable time. The delegation event model eliminates this overhead.

Events

 In the delegation model, an event is an object that describes a state change in a source.
 Among other causes, an event can be generated as a consequence of a person interacting
with the elements in a graphical user interface.
 Some of the activities that cause events to be generated are pressing a button, entering a
character via the keyboard, selecting an item in a list, and clicking the mouse.
 Events may also occur that are not directly caused by interactions with a user interface.

Event Sources

 A source is an object that generates an event. This occurs when the internal state of that
object changes in some way. Sources may generate more than one type of event.
 A source must register listeners in order for the listeners to receive notifications about a
specific type of event.
 Each type of event has its own registration method. Here is the general form:

public void addTypeListener (TypeListener el )

Here, Type is the name of the event, and el is a reference to the event listener. For example,
the method that registers a keyboard event listener is called addKeyListener( ). The method
that registers a mouse motion listener is called addMouseMotionListener( ).

 When an event occurs, all registered listeners are notified and receive a copy of the event
object. This is known as multicasting the event. In all cases, notifications are sent only
to listeners that register to receive them.
 Some sources may allow only one listener to register. The general form of such a method
is this:

public void addTypeListener(TypeListener el )

Here, Type is the name of the event, and el is a reference to the event listener.
When such an event occurs, the registered listener is notified. This is known as

unicasting the event.

 A source must also provide a method that allows a listener to unregister an interest in a
specific type of event. The general form of such a method is this:

public void removeTypeListener(TypeListener el )

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 12


ADVANCED JAVA PROGRAMMING I MSC-CS

Here, Type is the name of the event, and el is a reference to the event listener. For
example, to remove a keyboard listener, you would call removeKeyListener( ).
 The methods that add or remove listeners are provided by the source that generates
events. For example, the Component class provides methods to add and remove
keyboard and mouse event listeners.

Event Listeners

 A listener is an object that is notified when an event occurs. It has two major
requirements. First, it must have been registered with one or more sources to receive
notifications about specific types of events. Second, it must implement methods to
receive and process these notifications.
 The methods that receive and process events are defined in a set of interfaces, such as
those found in java.awt.event. For example, the MouseMotionListener interface
defines two methods to receive notifications when the mouse is dragged or moved. Any
object may receive and process one or both of these events if it provides an
implementation of this interface.

Event Classes

The classes that represent events are at the core of Java’s event handling mechanism. Widely
used Event classes are those defined by AWT and those defined by Swing.
 At the root of the Java event class hierarchy is EventObject, which is in java.util. It is
the superclass for all events. Its one constructor is shown here:

EventObject(Object src)

Here, src is the object that generates this event.


 EventObject defines two methods: getSource( ) and toString( ). The getSource( )
method returns the source of the event. Its general form is shown here:

Object getSource( )

 As expected, toString( ) returns the string equivalent of the event.


 The class AWTEvent, defined within the java.awt package, is a subclass of
EventObject. It is the superclass (either directly or indirectly) of all AWT-based events
used by the delegation event model. Its getID( ) method can be used to determine the
type of the event. The signature of this method is shown here:

int getID( )

To summarize:

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 13


ADVANCED JAVA PROGRAMMING I MSC-CS

• EventObject is a superclass of all events.


• AWTEvent is a superclass of all AWT events that are handled by the delegation event
model.
• AWT Event Classes:
Following is the list of commonly used event classes.

Sr. Control & Description


No.
1 AWTEvent
It is the root event class for all AWT events. This class and its subclasses
supercede the original java.awt.Event class.
2 ActionEvent
The ActionEvent is generated when button is clicked or the item of a list is double
clicked.
3 InputEvent
The InputEvent class is root event class for all component-level input events.

4 KeyEvent
On entering the character the Key event is generated.

5 MouseEvent
This event indicates a mouse action occurred in a component.
6 TextEvent
The object of this class represents the text events.
7 WindowEvent
The object of this class represents the change in state of a window.
8 AdjustmentEvent
The object of this class represents the adjustment event emitted by Adjustable
objects.
9 ComponentEvent
The object of this class represents the change in state of a window.
10 ContainerEvent
The object of this class represents the change in state of a window.

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 14


ADVANCED JAVA PROGRAMMING I MSC-CS

11 MouseMotionEvent
The object of this class represents the change in state of a window.
12 PaintEvent
The object of this class represents the change in state of a window.
Event handling has three main components:

 Events : An event is a change in state of an object.


 Events Source : Event source is an object that generates an event.
 Listeners : A listener is an object that listens to the event. A listener gets notified when an
event occurs.

Simply Event Handling includes : Actionà EventàListener

 Action: What user does is known as action. Example, a click over button. Here, click is the
action performed by the user.
 Event: The action done by the component when the user’s action takes place is known
as event. That is, event is generated (not seen, it is software) against action.
 Listener: It is an interface that handles the event. That is, the event is caught by the listener
and when caught, immediately executes some method filled up with code. Other way, the
method called gives life to the user action.

For more clarity,

 Action by user: Mouse click over a button


 Event generated: ActionEvnet
 Listener that handles ActionEvent: ActionListener
 Method called implicitly: actionPerformed() method.
The code of actionPerformed() contains the actions of what is to be done
(like user name and password validation etc.) when the user clicks a
button.

Steps involved in event handling( in above case)

 The User clicks the button and the event is generated.

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 15


ADVANCED JAVA PROGRAMMING I MSC-CS

 Now the object of concerned event class is created automatically and information about the
source and the event get populated with in same object.
 Event object is forwarded to the method of registered listener class.
 The method is now get executed and returns.

The KeyEvent Class

® A KeyEvent is generated when keyboard input occurs.


® There are three types of key events, which are identified by these integer constants:
KEY_PRESSED, KEY_RELEASED, and KEY_TYPED. The first two events are
generated when any key is pressed or released. The last event occurs only when a
character is generated. Remember, not all keypresses result in characters. For example,
pressing shift does not generate a character.
® There are many other integer constants that are defined by KeyEvent. For example,
VK_0 through VK_9 and VK_A through VK_Z define the ASCII equivalents of the
numbers and letters. Here are some others:

The VK constants specify virtual key codes and are independent of any modifiers, such
as control, shift, or alt.
® KeyEvent is a subclass of InputEvent. Here is one of its constructors:

KeyEvent(Component src, int type, long when, int modifiers, int code, char ch)

Here, src is a reference to the component that generated the event. The type of the event
is specified by type. The system time at which the key was pressed is passed in when.
The modifiers argument indicates which modifiers were pressed when this key event
occurred. The virtual key code, such as VK_UP, VK_A, and so forth, is passed in code.
The character equivalent (if one exists) is passed in ch. If no valid character exists, then
ch contains CHAR_UNDEFINED.
For KEY_TYPED events, code will contain VK_UNDEFINED.

® The KeyEvent class defines several methods, but probably the most commonly used
ones are getKeyChar( ), which returns the character that was entered, and
getKeyCode(), which returns the key code. Their general forms are shown here:

char getKeyChar( ) int


getKeyCode( )

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 16


ADVANCED JAVA PROGRAMMING I MSC-CS

If no valid character is available, then getKeyChar( ) returns CHAR_UNDEFINED. When a


KEY_TYPED event occurs, getKeyCode( ) returns VK_UNDEFINED.

The MouseEvent Class

® There are eight types of mouse events. The MouseEvent class defines the following
integer constants that can be used to identify them:

® MouseEvent is a subclass of InputEvent. Here is one of its constructors:

Here, src is a reference to the component that generated the event. The type of the event is
specified by type. The system time at which the mouse event occurred is passed in when. The
modifiers argument indicates which modifiers were pressed when a mouse event occurred. The
coordinates of the mouse are passed in x and y. The click count is passed in clicks. The
triggersPopup flag indicates if this event causes a pop-up menu to appear on this platform.
® Two commonly used methods in this class are getX( ) and getY( ). These return the X
and Y coordinates of the mouse within the component when the event occurred. Their
forms are shown here:

int getX( ) int getY(


)

Alternatively, you can use the getPoint( ) method to obtain the coordinates of the mouse.
It is shown here:

Point getPoint( )

It returns a Point object that contains the X,Y coordinates in its integer members: x and y.
TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 17
ADVANCED JAVA PROGRAMMING I MSC-CS

® The translatePoint( ) method changes the location of the event. Its form is shown here:

void translatePoint(int x, int y)

Here, the arguments x and y are added to the coordinates of the event.
® The getClickCount( ) method obtains the number of mouse clicks for this event. Its
signature is shown here: int getClickCount( )
® The isPopupTrigger( ) method tests if this event causes a pop-up menu to appear on this
platform. Its form is shown here:

boolean isPopupTrigger( )

® Also available is the getButton( ) method, shown here:

int getButton( )

It returns a value that represents the button that caused the event. For most cases, the
return value will be one of these constants defined by MouseEvent:

NOBUTTON, BUTTON1, BUTTON2 and BUTTON3

The NOBUTTON value indicates that no button was pressed or released.


® Also available are three methods that obtain the coordinates of the mouse relative to the
screen rather than the component. They are shown here:

Point getLocationOnScreen( ) int


getXOnScreen( )

int getYOnScreen( )
The getLocationOnScreen( ) method returns a Point object that contains both the X and Y
coordinate. The other two methods return the indicated coordinate.

The TextEvent Class

® Instances of this class describe text events. These are generated by text fields and text
areas when characters are entered by a user or program.
® TextEvent defines the integer constant TEXT_VALUE_CHANGED.

® The one constructor for this class is shown here:

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 18


ADVANCED JAVA PROGRAMMING I MSC-CS

TextEvent(Object src, int type)

Here, src is a reference to the object that generated this event. The type of the event is
specified by type.
® The TextEvent object does not include the characters currently in the text component
that generated the event. Instead, your program must use other methods associated with
the text component to retrieve that information. This operation differs from other event
objects discussed in this section. Think of a text event notification as a signal to a listener
that it should retrieve information from a specific text component.

The WindowEvent Class

 There are ten types of window events. The WindowEvent class defines integer constants
that can be used to identify them. The constants and their meanings are shown here:

® WindowEvent is a subclass of ComponentEvent. It defines several constructors. The


first is

WindowEvent(Window src, int type)

Here, src is a reference to the object that generated this event. The type of the event is type. The
next three constructors offer more detailed control:

WindowEvent(Window src, int type, Window other) WindowEvent(Window src, int type,
int fromState, int toState)

WindowEvent(Window src, int type, Window other, int fromState, int toState)
TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 19
ADVANCED JAVA PROGRAMMING I MSC-CS

Here, other specifies the opposite window when a focus or activation event occurs. The
fromState specifies the prior state of the window, and toState specifies the new state that the
window will have when a window state change occurs.
® A commonly used method in this class is getWindow( ). It returns the Window object
that generated the event. Its general form is shown here:

Window getWindow( )

® WindowEvent also defines methods that return the opposite window (when a focus or
activation event has occurred), the previous window state, and the current window state.
These methods are shown here:
Window getOppositeWindow( )
int getOldState( )
int getNewState( )

Sources of Events

® Objects from which events are generated are source of events .

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 20


ADVANCED JAVA PROGRAMMING I MSC-CS

Event Listener Interfaces

As explained, the delegation event model has two parts: sources and listeners. Listeners are
created by implementing one or more of the interfaces defined by the java.awt.event package.
When an event occurs, the event source invokes the appropriate method defined by the listener
and provides an event object as its argument. Following table lists several commonly used
listener interfaces and provides a brief description of the methods that they define.

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 21


ADVANCED JAVA PROGRAMMING I MSC-CS

The ActionListener Interface

This interface defines the actionPerformed( ) method that is invoked when an action event
occurs. Its general form is shown here:

void actionPerformed(ActionEvent ae)

The ContainerListener Interface

This interface contains two methods. When a component is added to a container,


componentAdded( ) is invoked. When a component is removed from a container,
componentRemoved( ) is invoked. Their general forms are shown here:

void componentAdded(ContainerEvent ce) void


componentRemoved(ContainerEvent ce)

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 22


ADVANCED JAVA PROGRAMMING I MSC-CS

The MouseListener Interface

This interface defines five methods. If the mouse is pressed and released at the same point,
mouseClicked( ) is invoked. When the mouse enters a component, the mouseEntered( ) method
is called. When it leaves, mouseExited( ) is called. The mousePressed( ) and mouseReleased( )
methods are invoked when the mouse is pressed and released, respectively.

The general forms of these methods are shown here:

void mouseClicked(MouseEvent me) void


mouseEntered(MouseEvent me) void
mouseExited(MouseEvent me) void
mousePressed(MouseEvent me) void
mouseReleased(MouseEvent me)

The WindowListener Interface

This interface defines seven methods. The windowActivated( ) and windowDeactivated( )


methods are invoked when a window is activated or deactivated, respectively. If a window is
iconified, the windowIconified( ) method is called. When a window is deiconified, the
windowDeiconified( ) method is called. When a window is opened or closed, the
windowOpened( ) or windowClosed( ) methods are called, respectively. The windowClosing( )
method is called when a window is being closed. The general forms of these methods are

void windowActivated(WindowEvent we) void


windowClosed(WindowEvent we) void
windowClosing(WindowEvent we)

void windowDeactivated(WindowEvent we) void


windowDeiconified(WindowEvent we) void
windowIconified(WindowEvent we) void
windowOpened(WindowEvent we)

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 23


ADVANCED JAVA PROGRAMMING I MSC-CS

Using the Delegation Event Model

Using the delegation event model is actually quite easy. Just follow these two steps:
1. Implement the appropriate interface in the listener so that it can receive the type of event
desired.
2. Implement code to register and unregister (if necessary) the listener as a recipient for the
event notifications.
Remember that a source may generate several types of events. Each event must be registered
separately. Also, an object may register to receive several types of events, but it must implement
all of the interfaces that are required to receive these events.

So, before an application can respond to an event for a particular GUI component, you
must:

1. Create a class that represents the event handler and implements an appropriate interface—
known as an event-listener interface.
2. Indicate that an object of the class from Step 1 should be notified when the event occurs—
known as registering the event handler.

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 24


ADVANCED JAVA PROGRAMMING I MSC-CS

Points to remember about listener

 In order to design a listener class we have to implement some listener interfaces. These Listener
interfaces forecast some public abstract callback methods which must be implemented by the
listener class.
 If you do not implement the any if the predefined interfaces then your class can not act as a
listener class for a source object.

Where to put event handling codes?

We can put the event handling code into one of the following places:

 Within class
 Other class
 Inner Class / Anonymous inner class
Example of event handling within a class import
javax.swing.*;
import java.awt.event.*;
class EventDemo extends JFrame implements ActionListener{ JTextField tf;
EventDemo(){
//create components tf=new JTextField();
tf.setBounds(60,50,170,20);
JButton b=new JButton("click me"); b.setBounds(100,120,80,30);
//register listener b.addActionListener(this);//passing current instance
//add components and set size, layout and visibility add(b);add(tf);
setSize(300,300); setLayout(null);
setVisible(true);

public void actionPerformed(ActionEvent e){ tf.setText("Welcome");


}
public static void main(String args[]){ new EventDemo();
}

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 25


ADVANCED JAVA PROGRAMMING I MSC-CS

Example of event handling by Outer Class (other class)


package eventhandlingpackage; import javax.swing.*;
class AE2 extends JFrame{ JTextField tf;
AE2(){
//create components tf=new JTextField();
tf.setBounds(60,50,170,20); JButton b=new
JButton("click me"); b.setBounds(100,120,80,30);
//register listener Outer o=new Outer(this);
b.addActionListener(o);//passing outer class instance
//add components and set size, layout and visibility
add(b);add(tf); setSize(300,300);
setLayout(null); setVisible(true);
}
public static void main(String args[]){ new AE2();
}

package eventhandlingpackage;
import java.awt.event.*;

class Outer implements ActionListener{ AE2 obj;


Outer(AE2 obj){ this.obj=obj;
}
public void actionPerformed(ActionEvent e){ obj.tf.setText("welcome");

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 26


ADVANCED JAVA PROGRAMMING I MSC-CS

}
}

Example of Event handling by Inner class(Anonymous Class)


import javax.swing.*; import
java.awt.event.*; class AE3 extends JFrame{
JTextField tf;
AE3(){
tf=new JTextField(); tf.setBounds(60,50,170,20);
JButton b=new JButton("click");
b.setBounds(50,120,80,30); ActionListener ac;
ac = new ActionListener(){
public void actionPerformed(ActionEvent e){ tf.setText("hello");
}

};

b.addActionListener(ac); add(b);add(tf);
setSize(300,300); setLayout(null);
setVisible(true);
}
public static void main(String args[]){ new AE3();
}
}

Important Event Classes and Interface

Event Classes Description Listener Interface

ActionEvent generated when button is pressed, menu- ActionListener


item is selected, list-item is double clicked

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 27


ADVANCED JAVA PROGRAMMING I MSC-CS

MouseEvent generated when mouse is dragged, MouseListener


moved,clicked,pressed or released and
also when it enters or exit a component

KeyEvent generated when input is received from KeyListener


keyboard

ItemEvent generated when check-box or list item is ItemListener


clicked

TextEvent generated when value of textarea or TextListener


textfield is changed
MouseWheelEvent generated when mouse wheel is moved MouseWheelListener

WindowEvent generated when window is activated, WindowListener


deactivated, deiconified, iconified, opened
or closed

ComponentEvent generated when component is hidden, ComponentEventListener


moved, resized or set visible

ContainerEvent generated when component is added or ContainerListener


removed from container

AdjustmentEvent generated when scroll bar is manipulated AdjustmentListener

FocusEvent generated when component gains or loses FocusListener


keyboard focus

Handling Mouse Events

To handle mouse events, you must implement the MouseListener and the

MouseMotionListener interfaces

Handling Keyboard Events

To handle keyboard events, you use the same general architecture as that shown in the mouse event
example in the preceding section. The difference, of course, is that you will be implementing the
KeyListener interface. Before looking at an example, it is useful to review how key events are
generated.
® When a key is pressed, a KEY_PRESSED event is generated. This results in a call to the
keyPressed( ) event handler. When the key is released, a KEY_RELEASED event is generated and

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 28


ADVANCED JAVA PROGRAMMING I MSC-CS

the keyReleased( ) handler is executed. If a character is generated by the keystroke, then a


KEY_TYPED event is sent and the keyTyped( ) handler is invoked.

Thus, each time the user presses a key, at least two and often three events are generated. If all you care
about are actual characters, then you can ignore the information passed by the key press and release
events. However, if your program needs to handle special keys, such as the arrow or function keys,
then it must watch for them through the keyPressed( ) handler.

Adapter Classes

Java provides a special feature, called an adapter class, that can simplify the creation of event handlers
in certain situations. An adapter class provides an empty implementation of all methods in an event
listener interface. Adapter classes are useful when you want to receive and process only some of the
events that are handled by a particular event listener interface. You can define a new class to act as an
event listener by extending one of the adapter classes and implementing only those events in which you
are interested.

What is the problem with listener interfaces?

Actually problem does not occur with every listener, but occurs with a few. A few listeners contain
more than one abstract method. For example, WindowListener, used for frame closing, comes with 7
abstract methods. We are interested in only one abstract method to close the frame, but being
WindowListener is an interface, we are forced to override remaining 6 methods also, just at least with
empty body. This is the only problem, else fine. Some listeners
like ActionListener comes with only one abstract method and with them no problem at all.
® Java adapter classes provide the default implementation of listener interfaces. If you inherit the
adapter class, you will not be forced to provide the implementation of all the methods of listener
interfaces. So it saves code.
® Adapters are replacement to listeners. The advantage with adapter is we can override any number of
methods we would like and not all. For example, if we
use WindowAdapter(instead of WindowListener), we can override only one method to close
the frame.

® Adapters make event handling simple. Any listener has more than one abstract method has got a
corresponding adapter class. For example, MouseListener with 5 abstract methods has got a
corresponding adapter known as MouseAdapter.
But ActionListener and ItemListener do not have corresponding adapter class as they contain
only one abstract method.

® Adapters are abstract classes introduced from JDK 1.1.


The adapter classes are found in java.awt.event, java.awt.dnd and javax.swing.event packages. The
Adapter classes with their corresponding listener interfaces are given below.

java.awt.event Adapter classes

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 29


ADVANCED JAVA PROGRAMMING I MSC-CS

Adapter class Listener interface

WindowAdapter WindowListener

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

FocusAdapter FocusListener

ComponentAdapter ComponentListener

ContainerAdapter ContainerListener

Listener Interfaces vs Adapter Classes

Any class which handles events must implement a listener interface for the event type it wishes
to handle. A class can implement any number of listener interfaces.
An adapter class is a class that already implements all the methods in its corresponding interface. Your
class must extend the adapter class by inheritance so you can extend only one adapter class in your
class (Java does not support multiple inheritance). Here are the Java adapter classes and the listener
interfaces they implement.

LISTENER INTERFACE CORRESPONDING ADAPTER

WindowListener (7) WindowAdapter


MouseListener (5) MouseAdapter

MouseMotionListener (2) MouseMotionAdapter

KeyListener (3) KeyAdapter

FocusListener (2) FocusAdapter

Inner Classes

® An inner class is a class defined within another class, or even within an expression.
® Listener classes are generally designed with just one purpose in mind: the creation of the listener
object for some GUI object (e.g., a button, window, checkbox, etc...). Given this relationship,

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 30


ADVANCED JAVA PROGRAMMING I MSC-CS

separating the code for the Listener class from the code for the class of the related GUI object
seems to, in a certain sense, work against the notion of the benefits of code encapsulation.
® Fortunately, in Java, within the scope of one class, we are allowed to define one or
more inner classes(or nested classes). (Technically, the compiler turns an inner class into a
regular class file named: OuterClassName$InnerClassName.class.
® Such inner classes can be defined inside the framing class, but outside its methods -- or it may
even be defined inside a method, and they can reference data and methods defined in the outer
class in which it nests.
Multithreading

Difference between Multiprocessing and Multithreading

There are two distinct types of multitasking: Process-based and Thread-based. It is


important to understand the difference between two. The Program in execution is defined as
Process. Thus, the process based multi tasking is the feature that allows your computer to run
two or more programs concurrently. For example we are able to use the java compiler and text
editor at the same time. Another example is, we are able to hear the music and also able to get the
print outs from the printer.

In the thread-based multitasking environment, the thread is the smallest unit of


dispatchable code. This means that the single program can contain two or more parts, each part of
the program is called, Thread. Although the Java programs make use of the process-based multi
tasking environments, but the process-based multi tasking is not under the control of java, Where
as the thread-based multitasking is under the control of Java.

Process-Based Multitasking Thread-Based Multitasking


This deals with "Big Picture" This deals with Details
These are Heavyweight tasks These are Lightweight tasks
Inter-process communication is expensive Inter-Thread communication is inexpensive.
and
limited
Context switching from one process to another Context switching is low cost in terms of
is memory,
costly in terms of memory because they run on the same address space
This is not under the control of Java This is controlled by Java

Advantage of the Multithreading

 It enables you to write very efficient programs that maximizes the CPU utilization and
reduces the idle time.
 Most I/O devices such as network ports, disk drives or the keyboard are much slower than CPU

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 31


ADVANCED JAVA PROGRAMMING I MSC-CS

 A program will spend much of it time just send and receive the information to or
from the devices, which in turn wastes the CPU valuable time.
 By using the multithreading, your program can perform another task during this idle time.
 For example, while one part of the program is sending a file over the internet, another
part can read the input from the keyboard, while other part can buffer the next block to
send.
 It is possible to run two or more threads in multiprocessor or multi core systems
simultaneously.

The States of the Thread

A thread can be in one of the several states. In general terms, a thread can running. It can
be ready to run as soon as it gets the CPU time. A running thread can be suspended, which is a
temporary halt to its execution. It can later be resumed. A thread can be blocked when waiting
for the resource. A thread can be terminated.

Single Threaded Program

A Thread is similar to simple program that contains single flow of control. It has
beginning, body, and ending. The statements in the body are executed in sequence.

class ABC //Begining

//Body

} //ending

Multithreaded Program

A unique property of the java is that it supports the multithreading. Java enables us the
multiple flows of control in developing the program. Each separate flow of control is thought
as tiny programknown as "thread" that runs in parallel with other threads. In the following
example when the main thread is executing, it may call thread A, as the Thread A is in execution
again a call is mad for Thread B. Now the processor is switched from Thread A to Thread B.
After the task is finished the flow of controlcomes back to the Thread A. The ability of the
language that supports multiple threads is called "Concurrency". Since threads in the java are

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 32


ADVANCED JAVA PROGRAMMING I MSC-CS

small sub programs of the main program and share the same address space, they are called
"light weight processes".

Main
thread

Start
Start
Start
switch
Thread A
Thread B switch Thread C

The Main Thread


When a Java program starts up, one thread begins running immediately. This is usually called the
main thread of your program, because it is the one that is executed when your program begins.
The main thread is important for two reasons:
• It is the thread from which other “child” threads will be spawned.
• Often, it must be the last thread to finish execution because it performs various
shutdown actions.
Although the main thread is created automatically when your program is started, it can be
controlled through a Thread object. To do so, you must obtain a reference to it by calling the
method currentThread( ), which is a public static member of Thread. Its general form is
shown here:

static Thread.currentThread( )

This method returns a reference to the thread in which it is called. Once you have a reference
to the main thread, you can control it just like any other thread.
Let’s begin by reviewing the following example:

CurrentThreadDemo.java

// Controlling the main Thread.


class CurrentThreadDemo

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 33


ADVANCED JAVA PROGRAMMING I MSC-CS

public static void main(String args[])

Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);

// change the name of the thread


t.setName("My Thread");

System.out.println("After name change: " + t);


try

for(int n = 5; n > 0; n--)

System.out.println(n);
Thread.sleep(1000);

catch (InterruptedException e)

System.out.println("Main thread interrupted");

Output

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 34


ADVANCED JAVA PROGRAMMING I MSC-CS

Creation of Thread

Creating the threads in the Java is simple. The threads can be implemented in the form of
object that contains a method "run()". The "run()" method is the heart and soul of any thread. It
makes up the entire body of the thread and is the only method in which the thread behavior can be
implemented.

There are two ways to create thread.


1. Declare a class that implements the Runnable interface which contains the run() method .
2. Declare a class that extends the Thread class and override the run() method.
1. Implementing the Runnable Interface
The Runnable interface contains the run() method that is required for implementing the
threads in our program. To do this we must perform the following steps:

I. Declare a class as implementing the Runnable interface


II. Implement the run() method
III. Create a Thread by defining an object that is instantiated from this "runnable" class as
the target of the thread
IV. Call the thread's start() method to run the thread.

Example program: Runnable.java

class x implements Runnable

{ //1 STEP

public void run()

{ //2 STEP

for(int i=0;i<=5;i++)
System.out.println("The Thread x

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 35


ADVANCED JAVA PROGRAMMING I MSC-CS

is:"+i); System.out.println("End of the


Thread x");

}
}

class RunnableTest
{

public static void main(String args[])


{

x r=new x();
Thread threadx=new
Thread(r); threadx.start();

System.out.println("The end of the main thread");


}
}
Output:

2. Extending the thread class


We can make our thread by extending the Thread class of java.lang.Thread class. This
gives us access to all the methods of the Thread. It includes the following steps:

I. Declare the class as Extending the Thread class.


II. Override the "run()" method that is responsible for running the thread.
TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 36
ADVANCED JAVA PROGRAMMING I MSC-CS

III. Create a thread and call the "start()" method to instantiate the Thread Execution.
Declaring the class

TheThread class can be declared as


follows: class MyThread extends
Thread

Overriding the method run()


The run() is the method of the Thread. We can override this as
follows: public void run()

}
Starting the new Thread
To actually to create and run an instance of the thread class, we must write the following:

MyThread a=new MyThread(); // creating the


Thread a.start(); // Starting the
Thread

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 37


ADVANCED JAVA PROGRAMMING I MSC-CS

Example program:

import java.io.*; import java.lang.*;

class A extends Thread

ThreadTest.java

public void run()

for(int i=1;i<=5;i++)

System.out.println("From Threaad A :i="+i);

System.out.println("Exit from Thread A");


}

class B extends Thread

public void run()

for(int j=1;j<=5;j++)

System.out.println("From Threaad B :j="+j);

System.out.println("Exit from Thread B");

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 38


ADVANCED JAVA PROGRAMMING I MSC-CS

class C extends Thread

public void run()

for(int k=1;k<=5;k++)

System.out.println("From Threaad C :k="+k);

System.out.println("Exit from Thread C");


}

class ThreadTest

public static void main(String args[])

System.out.println("main thread
started");

A a=new A();
a.start();
B b=new B();
b.start();

C c=new
C();
c.start();

System.out.println("main thread ended");

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 39


ADVANCED JAVA PROGRAMMING I MSC-CS

} FIRST RUN

Second Run: Produces different out put in the second run, because of the processor switching
from onethread to other.

Creating Multiple Threads

So far, you have been using only two threads: the main thread and one child thread. However,
TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 40
ADVANCED JAVA PROGRAMMING I MSC-CS

your program can spawn as many threads as it needs. For example, the following program
creates three child threads:

// Create multiple threads.

class NewThread implements Runnable


{
String name; // name of thread

Thread t;
NewThread(String threadname)
{
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}

// This is the entry point for thread.

public void run()


{
try
{
for(int i = 5; i > 0; i--)
{
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e)
{
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");

} //end of run method

} //end of NewThread

class MultiThreadDemo
{
public static void main(String args[])
{
new NewThread("One"); // start threads

new NewThread("Two");

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 41


ADVANCED JAVA PROGRAMMING I MSC-CS

new NewThread("Three");
try
{
// wait for other threads to end
Thread.sleep(10000);
}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}

When a Thread is ended

It is often very important to know which thread is ended. This helps to prevent the main from
terminating before the child Thread is terminating. To address this problem "Thread" class
provides two methods: 1) Thread.isAlive() 2) Thread.join().

The general form of the "isAlive()" method is as follows:

final boolean isAlive();

This method returns the either "TRUE" or "FALSE" . It returns "TRUE" if the thread is alive,
returns "FALSE" otherwise.
While isAlive( ) is occasionally useful, the method that you will more commonly use to wait for
a thread to finish is called join( ), shown here:

final void join( ) throws InterruptedException

This method waits until the thread on which it is called terminates. Its name comes from the
concept of the calling thread waiting until the specified thread joins it. Additional forms of join(
) allow you to specify a maximum amount of time that you want to wait for the specified thread
to terminate.

Example Program:

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 42


ADVANCED JAVA PROGRAMMING I MSC-CS

// Using join() to wait for threads to finish.


class NewThread implements Runnable
{
String name; // name of thread
Thread t;
NewThread(String threadname)
{
name = threadname;
t = new Thread( name);
System.out.println("New thread: " +
t.getName());t.start(); // Start the thread

// This is the entry point for thread.

public void run()


{
try
{
for(int i = 5; i > 0; i--)
{
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
}

class DemoJoin
{
public static void main(String args[])
{
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
NewThread ob3 = new NewThread("Three");
System.out.println("Thread One is alive: "+ ob1.t.isAlive());
System.out.println("Thread Two is alive: " + ob2.t.isAlive());
System.out.println("Thread Three is alive: " + ob3.t.isAlive());

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 43


ADVANCED JAVA PROGRAMMING I MSC-CS

// wait for threads to finish


try {
System.out.println("Waiting for threads to finish.");
ob1.t.join();

ob2.t.join();

ob3.t.join();

}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
System.out.println("Thread One is alive: "+ ob1.t.isAlive());
System.out.println("Thread Two is alive: "+ ob2.t.isAlive());
System.out.println("Thread Three is alive: "+ ob3.t.isAlive());
System.out.println("Main thread exiting.");
}
}

The Thread Priorities

Thread priorities are used by the thread scheduler to decide when and which thread should be
allowed to run. In theory, higher-priority threads get more CPU time than lower-priority
threads. In practice, the amount of CPU time that a thread gets often depends on several factors
besides its priority. A higher-priority thread can also preempt a lower-priority one. For instance,
when a lower-priority thread is running and a higher-priority thread resumes (from sleeping or
waiting on I/O, for example), it will preempt the lower priority thread.

To set a thread’s priority, use the setPriority( ) method, which is a member of Thread.
This is its general form:

final void setPriority(int level)

The value of level must be within the range MIN_PRIORITY and MAX_PRIORITY.
Currently, these values are 1 and 10, respectively. To return a thread to default priority, specify
NORM_PRIORITY, which is currently 5. These priorities are defined as static final variables
within Thread.
You can obtain the current priority setting by calling the getPriority( ) method of Thread,
shown here:

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 44


ADVANCED JAVA PROGRAMMING I MSC-CS

final int getPriority( )

Example Program:

//setting the priorities for thethread


class PThread1 extends Thread
{
public void run()
{
System.out.println(" Child 1 is started");
}
}
class PThread2 extends Thread
{
public void run()
{
System.out.println(" Child 2 is started");
}
}
class PThread3 extends Thread
{
public void run()
{
System.out.println(" Child 3 is started");
}
}

class PTest
{
public static void main(String args[])
{

//setting the priorities to the thread using the setPriority() method

PThread1 pt1=new PThread1();


pt1.setPriority(1); PThread2
pt2=new PThread2();
pt2.setPriority(9);
PThread3 pt3=new PThread3();
pt3.setPriority(6);
pt1.start();
pt2.start();
pt3.start();

//getting the priority

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 45


ADVANCED JAVA PROGRAMMING I MSC-CS

System.out.println("The pt1 thread priority is :"+pt1.getPriority());


}
}

Synchronization

When two or more threads need access to a shared resource, they need some way to
ensure that the resource will be used by only one thread at a time. The process by which this is
achieved is called synchronization.

Key to synchronization is the concept of the monitor (also called a semaphore). A


monitor is an object that is used as a mutually exclusive lock, or mutex. Only one thread can own
a monitor at a given time. When a thread acquires a lock, it is said to have entered the monitor.
All other threads attempting to enter the locked monitor will be suspended until the first thread
exits the monitor. These other threads are said to be waiting for the monitor. A thread that owns a
monitor can reenter the same monitor if it so desires.

Here, in the following example to threads are accessing the same resource (object) to print the
Table. The Table class contains one method, printTable(int ), which actually prints the table. We
are creating two Threads, Thread1 and Thread2, which are using the same instance of the Table
Resource (object), to print the table. When one thread is using the resource, no other thread is
allowed to access the same resource Table to print the table.

Example without the synchronization:

Class Table
{

void printTable(int n)

{ //method not synchronized


for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try{
Thread.sleep(400);
}
catch(InterruptedException ie)
{

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 46


ADVANCED JAVA PROGRAMMING I MSC-CS

System.out.println("The Exception is :"+ie);


}
}
} //end of the printTable() method
}

class MyThread1 extends Thread

{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
} //end of the Thread1

class MyThread2 extends Thread


{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 47


ADVANCED JAVA PROGRAMMING I MSC-CS

} //end of Thread2

class TestSynchronization1

{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
The output for the above program will be as follow:
Output: 5

100

10

200

15

300

20

400

25
500
In the above output, it can be observed that both the threads are simultaneously accessing the
Table object to print the table. Thread1 prints one line and goes to sleep, 400 milliseconds, and
Thread1 prints its task.

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 48


ADVANCED JAVA PROGRAMMING I MSC-CS

Using the Java synchronized method

If you declare any method as synchronized, it is known as synchronized method. Synchronized


method is used to lock an object for any shared resource. When a thread invokes a synchronized
method, it automatically acquires the lock for that object and releases it when the thread
completes its task.
The general form of the synchronized method is:
synchronized type method_name(para_list)

{
//body of the method
}
where synchronized is the keyword, method contains the type, and method_name represents the
name of the method, and para_list indicate the list of the parameters.

Example using the synchronized method

Class Table
{

synchronized void printTable(int n)

{ //method not synchronized


for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try{
Thread.sleep(400);
}

catch(InterruptedException ie)

System.out.println("The Exception is :"+ie);


}
}
} //end of the printTable() method

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 49


ADVANCED JAVA PROGRAMMING I MSC-CS

class MyThread1 extends Thread


{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}

} //end of the Thread1

class MyThread2 extends Thread

{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
} //end of Thread2

class TestSynchronization1
{
public static void main(String args[])
TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 50
ADVANCED JAVA PROGRAMMING I MSC-CS

Table obj = new Table();//only one object


MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();

t2.start();
}
}
Output: 5

10

15

20

25

100

200

300

400

500

In the above output it can be observed that when Thread1 is accessing the Table object,
Thread2 is not allowed to access it. Thread1 preempts the Thread2 from accessing the
printTable() method.

Inter-Thread Communication

If two or more Threads are communicating with each other, it is called "inter thread"
communication. Using the synchronized method, two or more threads can communicate
indirectly. Through, synchronized method, each thread always competes for the resource. This
way of competing is called polling. The polling wastes the much of the CPU valuable time. The
better solution to this problem is, just notify other threads for the resource, when the current
thread has finished its task. This is explicit communication between the threads.

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 51


ADVANCED JAVA PROGRAMMING I MSC-CS

Java addresses this polling problem, using via wait(), notify(), and notifyAll() methods. These
methods are implemented as final methods in Object, so all classes have them. All three
methods can be called only from within a synchronized context.

wait( ) tells the calling thread to give up the monitor and go to sleep until some
other thread enters the same monitor and calls notify( ).
notify( ) wakes up a thread that called wait( ) on the same object.
notifyAll( ) wakes up all the threads that called wait( ) on the same object. One of
the threads will be granted access.

These methods are declared within Object, as shown here:

final void wait( ) throws InterruptedException


final void notify( )
final void notifyAll( )
Additional forms of wait( ) exist that allow you to specify a period of time to wait.

Although wait( ) normally waits until notify( ) or notifyAll( ) is called, there is a


possibility that in very rare cases the waiting thread could be awakened due to a spurious
wakeup. In this case, a waiting thread resumes without notify( ) or notifyAll( ) having been
called. (In essence, the thread resumes for no apparent reason.) Because of this remote
possibility, Sun recommends that calls to wait( ) should take place within a loop that checks the
condition on which the thread is waiting. The following example shows this technique.

Example program for producer and consumer problem

class Q

{
int n;
boolean valueSet = false;

synchronized int get()

{
while(!valueSet)
try {
wait();
}
catch(InterruptedException e)
{
System.out.println("InterruptedException caught");

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 52


ADVANCED JAVA PROGRAMMING I MSC-CS

}
System.out.println("Got: " + n);
valueSet = false;
notify()
;return
n;

} //end of the get() method


synchronized void put(int n)

{
while(valueSet)
try {
wait();
}
catch(InterruptedException e)
{
System.out.println("InterruptedException caught");
}
this.n = n; valueSet = true;
System.out.println("Put: " + n);
notify();

} //end of the put method

} //end of the class Q

Suspending, Blocking and Stopping Threads

Whenever we want stop a thread we can stop from running using "stop()" method of
threadclass. It's general form will be as follows:

Thread.stop();

This method causes a thread to move from running to dead state. A thread will also
move todead state automatically when it reaches the end of its method.

Blocking Thread

A thread can be temporarily suspended or blocked from entering into the runnable and
running state by using the following methods:

sleep() —blocked for specified time

suspend() ----blocked until further orders

wait() --blocked until certain condition occurs

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 53


ADVANCED JAVA PROGRAMMING I MSC-CS

These methods cause the thread to go into the blocked state. The thread will return to
the runnable state when the specified time is elapsed in the case of sleep(), the resume()
method is invokedin the case of suspend(), and the notify() method is called in the case of
wait().

Example program:

The following program demonstrates these methods:

// Using suspend() and resume().

class NewThread implements Runnable


{
String name; // name of thread
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}

// This is the entry point for thread.

public void run()


{
try
{
for(int i = 15; i > 0; i--)
{
System.out.println(name + ": " + i);
Thread.sleep(200);
}
}

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 54


ADVANCED JAVA PROGRAMMING I MSC-CS

catch (InterruptedException e)
{
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
}
class SuspendResume
{
public static void main(String args[])
{
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
try
{
Thread.sleep(1000); ob1.t.suspend();
System.out.println("Suspending thread One");
Thread.sleep(1000);
ob1.t.resume();
System.out.println("Resuming thread One");
ob2.t.suspend();
System.out.println("Suspending thread Two");
Thread.sleep(1000);
ob2.t.resume();
System.out.println("Resuming thread Two");
}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
// wait for threads to finish
try
{
System.out.println("Waiting for threads to finish.");
ob1.t.join();
ob2.t.join();
}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 55


ADVANCED JAVA PROGRAMMING I MSC-CS

Life Cycle of a Thread

During the life time of the thread, there are many states it can enter. They include the following:
Newborn state
Runnable State
Running State
Blocked state
Dead state
A thread can always in any one of the five states. It can move from one state to other via
variety ofways as shown in the fig.
Newborn state Stop

Start

Stop Dead State

Running Runnable
Fig: Life State State
Cycle of Yield
Thread Stop

suspend() resume()
sleep() notify()
wait()

Blocked State

Newborn State: When we create a thread it is said to be in the new born state. At this state we
can do the following:
 schedule it for running using the start() method.
 Kill it using stop() method.

Runnable State: A runnable state means that a thread is ready for execution and waiting for the
availability of the processor. That is the thread has joined the queue of the threads for execution.
If all the threads have equal priority, then they are given time slots for execution in the round
rabin fashion, first-come, first-serve manner. The thread that relinquishes the control will join
the queue at the end and again waits for its turn. This is known as time slicing.

Running State:

Running state: Running state means that the processor has given its time to the thread for it
execution. The thread runs until it relinquishes the control or it is preempted by the other higher

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 56


ADVANCED JAVA PROGRAMMING I MSC-CS

priority thread. As shown in the fig. a running thread can be preempted using the suspen(), or
wait(), or sleep() methods.

Blocked state: A thread is said to be in the blocked state when it is prevented from entering into
runnable state and subsequently the running state.

Dead state: Every thread has a life cycle. A running thread ends its life when it has completed
execution. It is a natural death. However we also can kill the thread by sending the stop() message
to it at any time.

The Thread Methods:

Sl No Method Name Description


1 run() Used to write the body of the thread
2 start() Used to start the thread
3 sleep() Used to make the thread sleep for milliseconds
4 suspend() Used to suspend a running thread
5 wait() Waits until further ordered
6 yield Used to give control to other thread before it turn comes
7 Stop() Used to stop the thread
8 resume() Used to start the blocked thread
9 notify() Used to notify the waiting thread
10 notifyAll() Used to notify theall waiting threads

Thread Exceptions

Note that a call to the sleep() method is always enclosed in try/ catch block. This is necessary
because the sleep() method throws an exception, which should be caught. If we fail to catch the
exception the program will not compile.

try
{

Thread.sleep(1000);

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 57


ADVANCED JAVA PROGRAMMING I MSC-CS

catch(Exception e)
{

Deadlock

Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a thread is
waiting for an object lock, that is acquired by another thread and second thread is waiting for an
object lock that is acquired by first thread. Since, both threads are waiting for each other to
release the lock, the condition is called deadlock.

Thread Thread
1 2
Y

Here, in the above figure, the resource X is held by Thread1, and at the same time the Thread1 is
trying to access the resource which is held by the Thread2. This is causing the circular
dependency between two Threads. This is called, Deadlock.

public class TestDead


{
public static void main(String[] args)
{
final String resource1 = "John Gardner";
final String resource2 = "James Gosling";
// t1 tries to lock resource1 then resource2

Thread t1 = new Thread()


{
public void run()
{
synchronized (resource1)
{
System.out.println("Thread 1: locked resource 1");

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 58


ADVANCED JAVA PROGRAMMING I MSC-CS
try {

Thread.sleep(100);catchException()
{
System.out.println(e);
}
synchronized (resource2)
{
System.out.println("Thread 1: locked resource 2");
}
}
} //end of run()
}; //end of t1

// t2 tries to lock resource2 then resource1


Thread t2 = new Thread()
{
public void run()
{
synchronized (resource2)
{
System.out.println("Thread 2: locked resource 2");

try { Thread.sleep(100);} catch (Exception e) {}

synchronized (resource1)
{
System.out.println("Thread 2: locked resource 1");
}
}
}//end of run()
}; //end of t2
t1.start();
t2.start();}}

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 59


ADVANCED JAVA PROGRAMMING I MSC-CS
NETWORKING

 InetAddress
 TCP/ IP client sockets
 TCP/ IP server sockets
 URL
 URL Connection
 Datagrams
 Client/ Server application using RMI.

Networking Basics
 In Java Networking is a concept of connecting two or more computing devices together so that
we can share resources.
 Java socket programming provides facility to share data between different computing devices.

Advantage of Java Networking

1. Sharing resources
2. Centralize software management

Java Networking Terminology

 The widely used java networking terminologies are given below:


1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket

1) IP Address

 IP address is a unique number assigned to a node of a network e.g. 192.168.0.1.


 It is composed of octets that range from 0 to 255.
 It is a logical address that can be changed.

2) Protocol

 A protocol is a set of rules basically that is followed for communication.


 For example: TCP, FTP, Telnet, SMTP, POP etc.

3) Port Number

 The port number is used to uniquely identify different applications.


 It acts as a communication endpoint between applications.
 The port number is associated with the IP address for communication between two applications.

4) MAC (Media Access Control) Address

 MAC Address is a unique identifier of NIC (Network Interface Controller).


 A network node can have multiple NIC but each with unique MAC.

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 60


ADVANCED JAVA PROGRAMMING I MSC-CS
5) Connection-oriented and Connection-less protocol

 In connection-oriented protocol, acknowledgement is sent by the receiver. So it is reliable but


slow. The example of connection-oriented protocol is TCP.
 But, in connection-less protocol, acknowledgement is not sent by the receiver. So it is not
reliable but fast. The example of connection-less protocol is UDP.

6) Socket

 A socket is an endpoint between two way communication.

java.net package

 The java.net package provides many classes to deal with networking applications in Java.
 A list of these classes is given below:

o Authenticator CacheRequest CacheResponse


o ContentHandler CookieHandler CookieManager
o DatagramPacket DatagramSocket DatagramSocketImpl
o InterfaceAddress JarURLConnection MulticastSocket
o InetSocketAddress InetAddress Inet4Address
o Inet6Address IDN HttpURLConnection
o HttpCookie NetPermission NetworkInterface
o PasswordAuthentication Proxy ProxySelector
o ResponseCache SecureCacheResponse ServerSocket
o Socket SocketAddress SocketImpl
o SocketPermission URI StandardSocketOptions
o URL URLClassLoader URLConnection
o URLDecoder URLEncoder URLStreamHandler

InetAddress class

 InetAddress class represents an IP address.


 The java.net.InetAddress class provides methods to get the IP of any host name for example
www.javatpoint.com, www.google.com, www.facebook.com, etc.
 An IP address is represented by 32-bit or 128-bit unsigned number.
 An instance of InetAddress represents the IP address with its corresponding host name.
 There are two types of address types:
 Unicast
 Multicast.
 The Unicast is an identifier for a single interface whereas Multicast is an identifier for a set of
interfaces.
 Moreover, InetAddress has a cache mechanism to store successful and unsuccessful host name
resolutions.

Methods of InetAddress class


TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 61
ADVANCED JAVA PROGRAMMING I MSC-CS

Method Description
public static InetAddress getByName(String host) it returns the instance of InetAddress
throws UnknownHostException containing LocalHost IP and name.
public static InetAddress getLocalHost() throws it returns the instance of InetAdddress
UnknownHostException containing local host name and address.
public String getHostName() it returns the host name of the IP address.
public String getHostAddress() it returns the IP address in string format.

Example of InetAddress class

import java.io.*; import


java.net.*; public class
InetDemo{

public static void main(String[] args){

try{

InetAddress ip=InetAddress.getByName("www.javatpoint.com");
System.out.println("Host Name: "+ip.getHostName());
System.out.println("IP Address: "+ip.getHostAddress());
}catch(Exception e){System.out.println(e);}
}
}

Output:

Host Name: www.javatpoint.com


IP Address: 206.51.231.148

Socket Programming

 Java Socket programming is used for communication between the applications running on
different JRE.
 Java Socket programming can be connection-oriented or connection-less.
 Socket and ServerSocket classes are used for connection-oriented socket programming
 DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.
 The client in socket programming must know two information:

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 62


ADVANCED JAVA PROGRAMMING I MSC-CS
1. IP Address of Server
2. Port number

 Here, we are going to make one-way client and server communication.


 In this application, client sends a message to the server, server reads the message and prints it.
Here, two classes are being used: Socket and ServerSocket.
 The Socket class is used to communicate client and server. Through this class, we can read and
write message.
 The ServerSocket class is used at server-side.
 The accept() method of ServerSocket class blocks the console until the client is connected.
 After the successful connection of client, it returns the instance of Socket at server-side.

TCP/IP Client
Socket Socket class

 A socket is simply an endpoint for communications between the machines.


 The Socket class can be used to create a socket.

Methods:

Metho Descriptio
d n
1) public InputStream getInputStream() returns the InputStream attached with this socket.
2) public OutputStream returns the OutputStream attached with this
getOutputStream() socket.
3) public synchronized void close() closes this socket

TCP/IP Server Socket


ServerSocket class

 The ServerSocket class can be used to create a server socket. This object is used to establish
communication with the clients.

Methods:

Method Description
1) public Socket accept() returns the socket and establish a connection
between server and client.
2) public synchronized void close() closes the server socket.
TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 63
ADVANCED JAVA PROGRAMMING I MSC-CS

Creating Server:

 To create the server application, we need to create the instance of ServerSocket class.
 Here, we are using 6666 port number for the communication between the client and server.
 You may also choose any other port number.
 The accept() method waits for the client. If clients connects with the given port number, it
returns an instance of Socket.
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection and waits for the client

Creating Client:

 To create the client application, we need to create the instance of Socket class.
 Here, we need to pass the IP address or hostname of the Server and a port number.
 Here, we are using "localhost" because our server is running on same system.
Socket s=new Socket("localhost",6666);

URL

 The Java URL class represents an URL.


 URL is an acronym for Uniform Resource Locator. It points to a resource on the World Wide
Web.
 For example: https://www.javatpoint.com/java-tutorial

 A URL contains four information:

1. Protocol: In this case, http is the protocol.


2. Server name or IP Address: In this case, www.javatpoint.com is the server name.
3. Port Number: It is an optional attribute. If we write
http//ww.javatpoint.com:80/sonoojaiswal/ , 80 is the port number. If port number is not mentioned
in the URL, it returns -1.
4. File Name or directory name: In this case, index.jsp is the file name.

Constructors of URL class

 URL(String spec)
 Creates an instance of a URL from the String representation.
 URL(String protocol, String host, int port, String file)
 Creates an instance of a URL from the given protocol, host, port number, and file.
 URL(String protocol, String host, int port, String file, URLStreamHandler handler)
 Creates an instance of a URL from the given protocol, host, port number, file, and
handler.
 URL(String protocol, String host, String file)
 Creates an instance of a URL from the given protocol name, host name, and file name.
TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 64
ADVANCED JAVA PROGRAMMING I MSC-CS
 URL(URL context, String spec)
 Creates an instance of a URL by parsing the given spec within a specified context.
 URL(URL context, String spec, URLStreamHandler handler)
 Creates an instance of a URL by parsing the given spec with the specified handler
within a given context.

Methods of URL class

 The java.net.URL class provides many methods. The important methods of URL class are
given below.

Method Description
public String getProtocol() It returns the protocol of the URL.
public String getHost() It returns the host name of the URL.
public String getPort() It returns the Port Number of the URL.
public String getFile() It returns the file name of the URL.
public String getAuthority() It returns the authority of the URL.
public String toString() It returns the string representation of the URL.
public String getQuery() It returns the query string of the URL.
public String getDefaultPort() It returns the default port of the URL.
public URLConnection openConnection() It returns the instance of URLConnection i.e.
associated with this URL.
public boolean equals(Object obj) It compares the URL with the given object.
public Object getContent() It returns the content of the URL.
public String getRef() It returns the anchor or reference of the URL.

public URI toURI() It returns a URI of the URL.

Example of URL class

//URLDemo.java import
java.net.*; public class
URLDemo{

public static void main(String[] args){

try{ URL url=new URL("http://www.javatpoint.com/java-tutorial");


System.out.println("Protocol: "+url.getProtocol()); System.out.println("Host
Name: "+url.getHost()); System.out.println("Port Number: "+url.getPort());
System.out.println("File Name: "+url.getFile());
TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 65
ADVANCED JAVA PROGRAMMING I MSC-CS
}catch(Exception e){System.out.println(e);}
}
}

Output:

Protocol: http
Host Name: www.javatpoint.com
Port Number: -1
File Name: /java-tutorial

URLConnection class

 The Java URLConnection class represents a communication link between the URL and the
application.
 This class can be used to read and write data to the specified resource referred by the URL.

Object of URLConnection class


 The openConnection() method of URL class returns the object of URLConnection class.
Syntax:public URLConnection openConnection()throws IOException{}

 The URLConnection class provides many methods, we can display all the data of a webpage by
using the getInputStream() method.
 The getInputStream() method returns all the data of the specified URL in the stream that can be
read and displayed.
Example of URLConnection class
import java.io.*;

import java.net.*;

public class URLConnectionExample {


public static void main(String[] args){
try{

URL url=new URL("http://www.javatpoint.com/java-tutorial");


URLConnection urlcon=url.openConnection();
InputStream stream=urlcon.getInputStream();
int i; while((i=stream.read())!=-
1){ System.out.print((char)i);

}
}catch(Exception e){System.out.println(e);}
}
}

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 66


ADVANCED JAVA PROGRAMMING I MSC-CS
HttpURLConnection class

The Java HttpURLConnection class is http specific URLConnection. It works for HTTP
protocol only.
By the help of HttpURLConnection class, you can information of any HTTP URL such as
header information, status code, response code etc.
The java.net.HttpURLConnection is subclass of URLConnection class.

Object of HttpURLConnection class

The openConnection() method of URL class returns the object of URLConnection class.
Syntax:public URLConnection openConnection()throws IOException{}

You can typecast it to HttpURLConnection type as given below.

URL url=new URL("http://www.javatpoint.com/java-tutorial");


HttpURLConnection huc=(HttpURLConnection)url.openConnection();
HttpURLConnecton Example
import java.io.*;

import java.net.*;

public class HttpURLConnectionDemo{


public static void main(String[] args){
try{

URL url=new URL("http://www.javatpoint.com/java-tutorial");


HttpURLConnection huc=(HttpURLConnection)url.openConnection();
for(int i=1;i<=8;i++)
{
System.out.println(huc.getHeaderFieldKey(i)+" = "
+huc.getHeaderField(i));
}
huc.disconnect();
}catch(Exception e){System.out.println(e);}
}
}

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 67


ADVANCED JAVA PROGRAMMING I MSC-CS

Output:

Date = Wed, 10 Dec 2014 19:31:14 GMT


Set-Cookie = JSESSIONID=D70B87DBB832820CACA5998C90939D48; Path=/
Content-Type = text/html
Cache-Control = max-
age=2592000 Expires = Fri, 09 Jan
2015 19:31:14 GMT Vary =
Accept-Encoding,User-Agent
Datagrams
 Datagrams
Connection = closeare bundles of information passed between machines.
Transfer-Encoding = chunked
 Java DatagramSocket and DatagramPacket classes are used for connection-
less socket programming.

DatagramSocket class

 Java DatagramSocket class represents a connection-less socket for sending


and receiving datagram packets.
 A datagram is basically an information but there is no guarantee of its
content, arrival or arrival time.

Constructors of DatagramSocket class

 DatagramSocket() throws SocketEeption: it creates a datagram socket and


binds it with the available Port Number on the localhost machine.
 DatagramSocket(int port) throws SocketEeption: it creates a datagram
socket and binds it with the given Port Number.
 DatagramSocket(int port, InetAddress address) throws SocketEeption: it
creates a datagram socket and binds it with the specified port number and host
address.

DatagramPacket class

 Java DatagramPacket is a message that can be sent or received. If you send


multiple packet, it may arrive in any order. Additionally, packet delivery is not
guaranteed

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 68


ADVANCED JAVA PROGRAMMING I MSC-CS

Constructors of DatagramPacket class

 DatagramPacket(byte[] barr, int length): it creates a datagram packet. This


constructor is used to receive the packets.
 DatagramPacket(byte[] barr, int length, InetAddress address, int port): it
creates a datagram packet. This constructor is used to send the packets.

Example of Sending DatagramPacket by DatagramSocket

//DSen
der.jav
a
import
java.ne
t.*;

public
class
DSend
er{

public static void main(String[] args) throws Exception

DatagramSocket ds = new
DatagramSocket(); String str =
"Welcome java";
InetAddress ip = InetAddress.getByName("127.0.0.1");

DatagramPacket dp = new DatagramPacket(str.getBytes(),


str.length(), ip, 3000); ds.send(dp);
ds.close();
}
}

Example of Receiving DatagramPacket by DatagramSocket

//DRec
eiver.ja
va

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 69


ADVANCED JAVA PROGRAMMING I MSC-CS

import
java.ne
t.*;
public
class
DRecei
ver{

public static void main(String[] args)


throws Exception { DatagramSocket ds =
new DatagramSocket(3000); byte[] buf =
new byte[1024];

DatagramPacket dp = new
DatagramPacket(buf, 1024);
ds.receive(dp);
String str = new String(dp.getData(), 0,
dp.getLength()); System.out.println(str);
ds.close();
}
}
The Java Media Techniques
There are a number of APIs that fall within the purview of media and
communications. These, and what they enable in the Java platform, include:

Java 2D -- 2D graphics and image manipulation

Java 3D -- 3D graphics runtime

Java Media Framework -- playback of synchronized media

Java Sound -- software sound processor and MIDI synthesizer

Java Speech -- speech recognition and synthesis

Java Telephony -- computer and telephony integration

Sun has also discussed several less well-defined Media APIs, both at JavaOne in March 1998
and in previous public forums:

Java Advanced Imaging -- advanced 2D image processing.

Java Animation -- 2D Animation.

Java Collaboration -- media data sharing.

Image basics

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 70


ADVANCED JAVA PROGRAMMING I MSC-CS

Java is popular because it has the promise of creating rich graphical experiences. Java has a
number of classes designed to deal with images and image manipulation. Java follows both
JPEG (Joint Photographic Expert Group) and GIF (Graphics Interchange Format ) as the
formats for image data. In general , JPEG images are better suited to natural color images
such as photo graphs, and GIF images are best for graphical logos, rules, and button images.

There are five types of objects that one will need to deal with or at least understand
when dealing with Images. These are :
Image
ImageObserver
ImageProducer
ImageConsumer
ImageFilter

These are basics, all of them defined in java.awt package, and many more also related
to image manipulation.
Image class: With this class one can load an image object that obtains its pixel data from a
specific URL. The most common way to do this is through the use of the getImage() method
of the java.applet.Applet class, which has the following two forms :

public Image getImage (URL url ) - returns an Image object given a URL.
public Image getImage (URL url, String name )- returns an Image object given a ba
se URL and file name.

Illustration 9.3 // Draw an Image //

import java.applet.*;
import java.awt.*;
public class ImageTest extends Applet {
Image mona;
public void init ( ) {
mona = getImage (getDocumentBase ( ), "monalisa.gif ");
}

public void point (Graphics g ) {


g.drawImage (mona, 0, 0, this);
}
}

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 71


ADVANCED JAVA PROGRAMMING I MSC-CS

In the above mentioned applet, first init() method loads the image object from the
specified URL and file name. The paint() method uses drawImage() method ( it is defined in
Component class); it has the form as below :
public abstract boolean drawImage ( Image imageName, int x, int y, ImageObserver
imgObs );
imageName is the image reference that has to be drawn, the x, y coordinates to paint
at, and imgObs is the ImageObserver that can monitors an image while it loads, we will learn
more about it during the subsequent discussion. In the example Illustration 9.3, this represents
the default ImageObserver.
When this applet runs, it starts loading "monalisa.gif " in the init() method. On screen
you can see the image as it loads from the Network ( or local machine), because the default
ImageObserver interface calls paint() method every time more image data arrives from the
source.
ImageObserver class :ImageObserver is an abstract interface used to get notification as an
image is being generated. As we have seen in the last example, the drawImage() method
takes both an Image object and an ImageObserver object. In the case of an ImageObserver
object, because ImageObserver is an interface, we need to pass a reference to an instance of a
class that implements the ImageObserver interface. Classes that implements the
ImageObserver interface are required to have an imageUpdate() method as follows :
public abstract boolean imageUpdate (Image img, int status , int x, int y, int width, int
height);
Before going to know the use of this method in an applet, let us see about the various
arguments in it :
Image img - the Image object references that has to be drawn on the applet.
int status - this gives us the status information of the image "img" being processed. The "
status" integer is tested bit wise against the value of one or more flags. The available flags
and the information they provide are listed in Table 9.1
int (x, y, width, height )- is a configuration for rectangle that reports different information
about the image under loading.

The use of the imageUpdate() method can be summarized as stated below :


When an Image object is referred, the imageUpdate() of this object will call repaint() method
which will cause the paint() method to eventually call again. The drawImage() is thus again
called, and it again draws all the pixel data it has loaded so far, which at this point should be
more than had been loaded the last time drawImage() was called. The partial image is again
drawn, and this time, because more pixel data has been loaded, more of the image is drawn
and appears on the screen. When more pixel data is loaded, imageUpdate() is again called,
and the cycle repeats itself, until all the pixel data has been loaded and the complete image
has been drawn.
Table 9.1

Bits Indicator
WIDTH The width of the base image is now available and can be taken from
the width argument.

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 72


ADVANCED JAVA PROGRAMMING I MSC-CS

HEIGHT The height of the base image is now available and can be taken from
the height argument
PROPERTIES The properties of the image are now available. One can access the properties
with img.properties.
SOMEBITS More pixels needed for drawing a scaled variation of the image are available.
The bounding box of the new pixels can be taken from the x, y, width,
and height argu ments.
FRAMEBITS Another complete frame of a multiple frame image, which was previously
drawn, is now available to be redrawn. The x, y, height, and width arguments
should be ignored.
ALLBITS The image being drawn is now complete and can be drawn again in its final
form. The x , y, width, and height arguments are no longer meaningful.
ERROR An image that was being tracked has encountered an error. No further image
informa tion will be available and drawing the image will fail.
ABORT An image that was being tracked was aborted before production was complete.
No more image information will become available.
Now let us look at an example that uses ImageObserver to see how many scan lines of the
image have been processed and then prints the progress to the console.

Illustration 9.4 // Use of ImageObserver //

import java.applet.*;
import java.awt.*;
import java.awt. image.*;
public class ImageLoadTest extends Applet implement ImageObserver {
image mona;
Dimension d;
int progress;
boolean loaded;
public void init ( ) {
mona = getImage ( getDocumentBase ( ), "monalisa.gif " );
loaded = false;
progress = 0;
}
public void paint (Graphics g ) {
d = this.size;

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 73


ADVANCED JAVA PROGRAMMING I MSC-CS

loaded = g.drawImage (mona, 0, 0, this );


}
public boolean imageUpdate (Image img, int info, int x, int y, int width, int heig
ht ) {
if (( info & ALLBITS ) != 1) {
if (progress < d.height )
progress = progress + height;
System.out.println( progress + "/" + d.height);
return true;
} else { return false; }
}
public void start( ) {
mover = new Thread (this);
mover.start( );
}
public void stop( ) {
mover.stop( );
}
public void run( ) {
mover.setPriority (Thread.MIN_PRIORITY);
while (!loaded ) {
repaint( );
try mover.sleep( 200 );
catch (Exception e);
}
}
}

This applet, loads an image just as in Illustration 9.3. The difference in this example is that
we are implementing our own imageUpdate() method over the default one. The
imageUpdate() method processes the status of the image load. A summary of the status is
passed in through info, against which the static variable ALLBITS is tested. If we have not
yet received all of the bits in our image, we add the height value to the total number of scan

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 74


ADVANCED JAVA PROGRAMMING I MSC-CS

line processed which will be printed to the system console. The run() method repaints the
applet five times a second (every 200 milliseconds) while the image "mona" is not loaded.
How long the status monitor will run depends on how quickly the Network connection can
deliver the image date.
ImageProducer class :ImageProducer is an abstract interface for objects that want to
produce data for Images. An object that implements the ImageProducer interface will supply
integer or byte arrays that represent image data. The createImage() method (will be discussed
shortly ) takes an ImageProducer object and returns an Image object.
We will examine a valuable class called MemoryImageSource that implements
ImageProducer. We will create a new Image object from data generated by this producer.
MemoryImageSource : It is a class used to create a new Image from an array of pixels. Here
is a constructor used to create a MemoryImageSource object :
public ImageProducer MemoryImageSource (int width, int height, int pixel[ ],int offset,
int scan linewidth);
The MemoryImageSource object is constructed out of an array of integers pixel[ ], in the
default RGB color model to produce data for an image object. The constructor for
MemoryImageSource also takes the width and height of the result, the offset into the pixel
array, and the width of a scan line, This constructor returns an ImageProducer object which is
used with createImage() to result in a usable image. Following is an illustration of
ImageProducer.

Illustration 9.5 // Image Production //

Import java.applet.*;
import java.awt.*;
import java.awt.image.*;
public class MemoryImageProduce extends Applet {
Image art;
Dimension d;
public void init ( ) {
generateImage ( );
}

public void generateImage ( ) {


int pixels[ ] = new int [ d.width * d.height ];
int i = 0;

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 75


ADVANCED JAVA PROGRAMMING I MSC-CS

int r, g, b;
for (int y = 0 ; y < d.height; y++ ) { // Create a set of pixels
for (int x = 0, x < d.width; x++ ) {
r = (x ^ y ) & 0xff;
g = ( x * 2 ^ y * 2 ) & 0xff ;
b = ( x* 4 ^ y * 4 ) 0xff ;
pixels [ i++ ] = (255< 24 ) | (r < 16 ) | (g < 8) | b;

}
}
art = createImage( new MemoryImageSource( d.width, pixels, 0,
d.width ));
}
public void paint( Graphics g )
g.drawImage (art, 0, 0, this ));
}
}

Here, the data for the new MemoryImageSource is created in the generateImage() method.
An array of integers is created to hold pixel values; Then integer array elements get shifted
into a pixel in the pixel array. Finally, we call createImage() to create a new Image from the
'pixels' array with MemoryImageSource.

Audio basics

To play an audio data, it requires a specific format that the working platform can support.
Java can play back audio data over a wide range of platforms. According to Java convention,
all audio data should come from a URL ( Universal Resource Locator ) in a .au audio file. In
order to use existing sounds in formats such as .wav or .aiff, one need to convert these to .au
using a sound program that supports audio conversion. If one try to use .wav then Java is
unable to support it and throws an InvalidAudioFormatException, which will not play the
audio. The .au file refers to an 8-bit, 8Khz encoded audio file. This format doesn't represent
the state of the art in audio fidelity, but is adequate for most sound clips.
There are two ways to play a sound file from an applet. The first way to play a sound is
through the play() method and the other through the AudioClip of the Applet class object.
Using play() method :This method comes in two versions, both of which take a URL for a
sound file, load the file into the memory, and then play the sound for one time. The play()
method is as follows :

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 76


ADVANCED JAVA PROGRAMMING I MSC-CS

public void play (URL url ) - plays an audio clip if the audio clip referred to by the
URL is found.
public void play (URL url, String name) - same as the previous method, but uses a b
ase URL and file name to locate the audio file.

Following is the Illustration 9.1 to play a sound when a button is pressed.

Illustration 9.1 // Playing an audio clip //

import java.applet.*;
import java.awt.*;
public class AudioPlayTest extends Applet {
public void init ( ) { // To Place a Play button in
the applet
setLayout (new FlowLayout (FlowLayout. CENTER ));
Button playButton = new Button ("Play" );
add (playButton );
}

public boolean action (Event e, object button) {


if ("Play".equals (button)) {
play (getDocumentBase ( ), "audio\bell.au" );
return true;
}
}
}

This applet simply plays the audio file bell.au which is located in the audio sub directory of
the directory of the HTML file that loaded the applet. The audio file is cached in memory
before playing it.
Note : URL actually a source of an object in Internet site. A typical URL which is actually
having various component may look like as below :

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 77


ADVANCED JAVA PROGRAMMING I MSC-CS

Here, we have specified an audio file "music.au" which is available in the sub directory
"audio" at the server node "sun".
There are two methods defined in Applet class, getDocumentBase() and getCodeBase()
which are very useful to load data from the directory that had the HTML file that started the
applet(document base), and the directory that the class file was loaded from (code base ).
These two methods return a URL object.
Using Audio clip object :The disadvantage of using the play() method is that the first time
you call it with a given audio file, it will have to down load the file if it hasn't been used
before. This can happen responsiveness in cases like the previous example, where we want to
play the sound in response to a user action, and the user ends up waiting for the sound to load
in response to hitting a button. Also, the play() method is present only in the applet, which
means that to use it from a component, or from within a thread, we need to have a reference
to the applet. Last, the play() method plays a sound only once and must be called again if one
wants to play the sound next.
The AudioClip object solves many of these limitations. To obtain an AudioClip object, one
has to call the Applet's getAudioClip() method, which is defined as follows :

public AudioClip getAudioClip (URL url ) - returns an AudioClip object. This meth
od will not return until the AudioClip has been loaded from the specified URL, so one should
consider placing it in a separate thread if the file is expected to take a while to down load.

public AudioClip getAudioClip (URL url, String name ) - same as the previous met
hod, but finds the audio file using the base URL and file name.

The AudioClip object specifies three methods which are stated below :

public abstract void loop( ) - plays the clip in a continuous loop.


public abstract void play( ) - starts playing the clip from its beginning.
public abstract void stop( ) - stops the clip if it is currently playing.

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 78


ADVANCED JAVA PROGRAMMING I MSC-CS

Here, audio played by the AudioClip() is asynchronous play that can be possible with the abo
ve three methods. Following is the Illustration 9.2 of an applet that plays a sound as long as th
e applet is on - screen or until the 'Stop' button is clicked :

Illustration 9.2 // Play audio through Audio clip //

import java.applet.*;
import java.awt.*;
public class AudioClipTest extends Applet {
AudioClip flute ;
AudioClip piano ;
public void init ( ) { // applet initialize
setLayout (new FlowLayout (FlowLayout.CENTER ));
Button testButton = new Button ( "Start" );
add(testButton);
testButton = new Button( "Continue");
add(testButton);
testButton = new Button ( "Stop");
add(testButton);
flute = getAudioClip( getDocumentBase( ), "flute.au");
piano = getAudioClip( getDocumentBase( ), "piano.au");
}
public void start( ) { // Continue the play of Piano
piano.loop( );
}
public void stop( ) { // Stop the Piano play
piano.stop( );
}
public boolean action( Event e, Object button) {
if( "Start".equals(button) )
flute.play( );
if( "Continue".quals(button) )

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 79


ADVANCED JAVA PROGRAMMING I MSC-CS

piano.loop( );
if ( "Stop".equals(button) )
piano.stop( );
return true;
}
}

In the above illustration, applet loads two audio clips vide its init() method. First is "flute.au"
and the second is "piano.au". The init() method will not finish until the sounds have been
loaded. When the applet's start() is called, it starts the "piano.au". The thread of an event
driven method action() is started, thus, if user hit "Start" button the "flute.au" audio clip will
come into play. Note that, two audio clips will then come into play simultaneously. Thus,
using AudioClip object multiple audio can be played, provided that the working platform
supports multiple audio channel. The play will continue until the applet is closed.

AUDIO SUPPORT IN JAVA

An essential element to any multimedia experience is the inclusion of


sounds. The Java Applet class provides the necessary methods, which
allow programmers to load and play sound files [7]. The current level of
the JDK supports only the Sun ".AU" audio file format.

In most cases, this evasion seems to be sufficient except for the MIDI
(Musical Instrument Digital Interface) file format. A MIDI audio file is
sufficiently different than the others in that it is not an actual recording as AU
or WAV files are. MIDI files are computer programs, which instruct a
synthesizer to produce sounds. Therefore, one cannot rely on utility
programs to convert MIDI files to AU files. JavaSoft has addressed MIDI in
its recently released Java Media API.

PLAYING AN AUDIO CLIP FROM A JAVA


The first audio-enabled Java applet presented here will play an audio clip.
The source code for this applet is presented below. It takes only one line of
Java code to create a simple Java applet, which plays a predefined audio clip.
Although this is an oversimplified example, it provides a compelling reason
for programmers to investigate Java for multimedia programming.

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

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 80


ADVANCED JAVA PROGRAMMING I MSC-CS

public class Sound1 extends Applet

public void init()

play(getCodeBase(),"spacemusic.au");

PLAYING AN AUDIO CLIP USING A MORE SOPHISTICATED APPROACH


In the first Java audio example, the program loaded and played the audio clip
using the play method of the applet class. Although that applet was trivial to
write, it is not very useful for a practical solution since it does not provide a
means to replay the audio clip. It simply plays the audio clip once and does
nothing after that.

Most applications that utilize audio provide the user with a mechanism to
play the audio clip when they are ready to hear it. They also allow the user to
replay the audio clip if they want to hear it again. The second Java audio
example adds a “play” button to the applet. The output screen for the Sound2
applet is displayed in Figure.

Figure 14. Output of the Sound2 Java applet.

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 81


ADVANCED JAVA PROGRAMMING I MSC-CS

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

public class Sound2 extends Applet

Butto play;
AudioClip aclip;

public void init( )

aclip = getAudioClip(getCodeBase( ), "spacemusic.au");

play = new
Button("Play");add(play);

public boolean action(Event evt, Object arg)

if(evt.target instanceof Button)

if(arg.equals("Play"))

if(aclip == null)

} // end of action
}

The audio clip is loaded at initialization time using the following Java statement:

aclip = getAudioClip(getCodeBase( ), "spacemusic.au");

When the “play” pushbutton is pressed, the Sound2 applet will gain control
in its action method. The audio clip will be played using the play method of
the AudioClip class. If the audio clip has not been successfully loaded, the
action method will print a message out accordingly.

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 82


ADVANCED JAVA PROGRAMMING I MSC-CS

PLAYING AND STOPPING AN AUDIO CLIP


In the next audio example, Sound3, the program allows the user to start and
stop playing the audio clip via the user interface. The output screen from the
Sound3 Java applet is displayed in Figure 16.

Two pushbuttons are provided. When the user presses the “Loop”
pushbutton, the audio clip is played using the loop method of the AudioClip
class. This method differs from the play method in that it will continuously
play the audio clip in a loop. The stop method of the AudioClip class is used
to stop playing the clip. The source code for this final Java audio example is
given in Figure 17.

VIDEO SUPPORT IN JAVA

Similar to MIDI support, the base Java classes in the latest level of the JDK
do not support video playback. This is most probably due to the fact that
there are numerous non-Java video solutions available for the Internet today.

There are two primary approaches to delivering video on the Internet:


downloading stored files vs. "streaming" video (and audio). Each presents
special challenges and opportunities for bandwidth allocation.

STANDARD VIDEO

Downloading and playing stored video files over the Internet is the older of the
two available video playback approaches. Here, digital video files are stored on a
server (typically in MPEG1or QuickTime Movie format) and, when someone
wants to access the video, they must download it in full before viewing

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 83


ADVANCED JAVA PROGRAMMING I MSC-CS

Button loop;
Button stop;

loopClip.loop();

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 84


ADVANCED JAVA PROGRAMMING I MSC-CS

STREAMING VIDEO
Streaming video (and audio) represents a second and more complex area of
video on the Internet. Streaming involves the delivery of video or audio "in
real time" through a number of techniques, including some that place several
frames of video into a buffer on the client's hard drive, and then begin
playing the video, as more files are placed into the buffer

Each streaming video solution defines its own proprietary movie file format
with a corresponding encoder utility that converts a standard movie file such
as AVI or MPEG to their own native format.

In trying to obtain all available information on this subject, it appears that


JavaSoft’s future support for video and all multimedia support will be
defined by the Java Media API. JavaSoft has been working with a group of
industry-leading companies to establish the standards for Java Media:
Adobe®, Apple, Intel, Macromedia, Netscape, SGI, and Sun Microsystems.

JAVA MEDIA API

The Java Media API defines a set of multimedia classes which support a
wide range of rich, interactive media on and off the Web, including audio,
video, 2D, 3D, animation, telephony, and collaboration
The Java Media API is composed of several distinct components, each
associated with either a specific type of media (audio, video, 2D, 3D), or a
media-related activity (animation, collaboration, telephony). Collectively,
these interfaces provide Java Language programmers with the ability to
handle a wide variety of different media types within their applications and
applets.

The Java Media API is highly extensible. The API accommodates today's
large and ever- changing suite of media transports, containers, and encoding
formats, and allows the addition of new media-related functionality as they
become available.

The components of the Java Media APIs are as follows:

 Java 2D API - Provides graphics and imaging capabilities beyond those


available with the Java Applet API. The 2D API allows the creation of
high quality, platform-independent graphics including line art, text, and
images in a single model that uniformly addresses color, spatial
transforms and compositing.

 Java Media Framework API - Handles traditional time-critical media,


such as audio, video, and MIDI. The framework provides a common
model for timing, synchronization, and composition, which can be
applied to media components to allow them to interoperate. It is designed

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 85


ADVANCED JAVA PROGRAMMING I MSC-CS

to handle streaming data, live or stored, compressed or raw, as well as


from sampled audio and video streams.

 Video API - Accommodates both streaming and stored video sources.


It defines basic data formats and control interfaces.

 Audio API - Supports sampled and synthesized audio. It includes a


specification for 3D spatial audio, and accommodates both streaming and
stored audio sources.

 MIDI API - Provides support for timed-event streams. It uses the Media
Framework for synchronization with other activities, and for an
extensibility mechanism for new synthesizers and effects.

 Java Animation API - Supports traditional 2D animation of sprites, with


stacking order control. It makes use of 2D interfaces for compositing and
the Media Framework for synchronization, composition, and timing.

 Java Share API - Provides the basic abstraction for live, two-way, multi-
party communication between objects over a variety of networks and
transport protocols. The API enables synchronization and session
management, and allows sharing of both "collaboration-aware" and
"collaboration-unaware" applets.

 Java Telephony API - Unifies computer/telephony integration. It


provides basic functionality for control of phone calls: 1st-party call
control (simple desktop phone), 3rd- party call control (phone call
distribution center), teleconferencing, call transfer, caller ID, and DTMF
decode/encode.

 Java 3D API - Provides high-performance, interactive, 3D graphics


support. It supports VRML, and has a high-level specification of
behavior and control of 3D objects. The 3D API simplifies 3D-
application programming and provides access to lower level interfaces
for performance.

******************* END OF UNIT I *******************

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 86


Advanced java programming I Msc (cs)

UNIT –II

RMI (Remote Method Invocation)

Client Server Application using RMI (Remote Method Invocation)

 The RMI (Remote Method Invocation) is an API that provides a mechanism to create distributed
application in java.
 The RMI allows an object to invoke methods on an object running in another JVM.
 The RMI provides remote communication between the applications using two objects 
stub and skeleton.
 RMI uses stub and skeleton object for communication with the remote object.
Remote object is an object whose method can be invoked from another JVM.

Defining Remote objects:

RMI stands for Remote Method Invocation. It is a mechanism that allows


an residing in one system (JVM) to access/invoke an object running on another JVM.
RMI is used to build distributed applications; it provides remote communication between
Java programs. It is provided in the package java.rmi.

Architecture of an RMI Application


• In an RMI application, we write two programs, a server program (resides on the
server) and a client program (resides on the client).
• Inside the server program, a remote object is created and reference of that object is
made available for the client (using the registry).
• The client program requests the remote objects on the server and tries to invoke its
methods.

Figure 1.17 Architecture of an RMI

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 86


Advanced java programming I Msc (cs)

Components of an RMI Architecture


• Transport Layer − This layer connects the client and the server. It manages the
existing connection and also sets up new connections.
• Stub − A stub is a representation (proxy) of the remote object at client. It resides in
the client system; it acts as a gateway for the client program.
• Skeleton − This is the object which resides on the server side. stub communicates
with this skeleton to pass request to the remote object.
• RRL(Remote Reference Layer) − It is the layer which manages the references made
by the client to the remote object.

Working of an RMI Application:


• When the client makes a call to the remote object, it is received by the stub which
eventually passes this request to the RRL.
• When the client-side RRL receives the request, it invokes a method called invoke() of
the object remoteRef. It passes the request to the RRL on the server side.
• The RRL on the server side passes the request to the Skeleton (proxy on the server)
which finally invokes the required object on the server.
• The result is passed all the way back to the client.

Serialization and Deserialization in Java:


• Serialization is a mechanism of converting the state of an object into a byte stream.
• Deserialization is the reverse process where the byte stream is used to recreate the
actual Java object in memory.
• This mechanism is used to persist the object.

Figure 1.18 Serialization and Deserialization

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 87


Advanced java programming I Msc (cs)

Marshalling and Unmarshalling


• Whenever a client invokes a method that accepts parameters on a remote object, the
parameters are bundled into a message before being sent over the network. These
parameters may be of primitive type or objects. In case of primitive type, the
parameters are put together and a header is attached to it. In case the parameters are
objects, then they are serialized. This process is known as marshaling.
• At the server side, the packed parameters are unbundled and then the required method
is invoked. This process is known as unmarshalling.

RMI Registry
• RMI registry is a namespace on which all server objects are placed. Each time the
server creates an object, it registers this object with the RMIregistry
(using bind() or reBind() methods). These are registered using a unique name known
as bind name.
• To invoke a remote object, the client needs a reference of that object. At that time, the
client fetches the object from the registry using its bind name
(using lookup() method).

Figure 1.19 RMI Registry

Goals of RMI
• To minimize the complexity of the application.
• To preserve type safety.
• Distributed garbage collection.
• Minimize the difference between working with local and remote objects.

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 88


Advanced java programming I Msc (cs)

Java implementation of RMI


• Define the remote interface
• Develop the implementation class (remote object)
• Develop the server program
• Develop the client program
• Compile the application
• Execute the application
Stub
 The stub is an object, acts as a gateway for the client side.
 All the outgoing requests are routed through it.
 It resides at the client side and represents the remote object.
 When the caller invokes method on the stub object, it does the following tasks:

1. It initiates a connection with remote Virtual Machine (JVM),


2. It writes and transmits (marshals) the parameters to the remote Virtual Machine (JVM),
3. It waits for the result
4. It reads (unmarshals) the return value or exception, and
5. It finally, returns the value to the caller.

Skeleton
 The skeleton is an object, acts as a gateway for the server side object.
 All the incoming requests are routed through it.
 When the skeleton receives the incoming request, it does the following tasks:
1. It reads the parameter for the remote method
2. It invokes the method on the actual remote object, and
3. It writes and transmits (marshals) the result to the caller.

In the Java 2 SDK, an stub protocol was introduced that eliminates the need for skeletons. 
 If any application performs these tasks, it can be distributed application. 

1. The application need to locate the remote method


2. It need to provide the communication with the remote objects, and
3. The application need to load the class definitions for the objects.

The RMI application has all these features, so it is called the distributed application.

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 89


Advanced java programming I Msc (cs)

RMI Example
The following 6 steps given are to write the RMI program:

1. Create the remote interface


2. Provide the implementation of the remote interface

3. Compile the implementation class and create the stub and skeleton objects using
thermic tool
4. Start the registry service by rmiregistry tool

5. Create and start the remote application

6. Create and start the client application

 In this example, we have followed all the 6 steps to create and run the rmi application. 
 The client application need only two files, remote interface and client application.
 In the rmi application, both client and server interacts with the remote interface.
 The client application invokes methods on the proxy object, RMI sends the request to
theremote JVM. 
 The return value is sent back to the proxy object and then to the client application.

1) Create the remote interface

 For creating the remote interface, extend the Remote interface and declare the
RemoteException with all the methods of the remote interface.
 Here, we are creating a remote interface that extends the Remote interface.
 There is only one method named add() and it declares RemoteException.

import java.rmi.*;
public interface Adder extends Remote
{
public int add(int x,int y)throws RemoteException;
}

2) Provide the implementation of the remote interface

 Now provide the implementation of the remote interface. For providing the
implementation of the Remote interface, we need to
o Either extend the UnicastRemoteObject class, (or)
o Use the exportObject() method of the UnicastRemoteObject class
 In case, you extend the UnicastRemoteObject class, you must define a constructor that
declares RemoteException.

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 90


Advanced java programming I Msc (cs)

import java.rmi.*;
import java.rmi.server.*;
public class AdderRemote extends UnicastRemoteObject implements
Adder{ AdderRemote()throws RemoteException{
super();
}
public int add(int x,int y){return x+y;}
}

3) Create the stub and skeleton objects using the rmic tool

 Next step is to create stub and skeleton objects using the rmi compiler.
 The rmic tool invokes the RMI compiler and creates stub and skeleton objects.

rmic AdderRemote

4) Start the registry service by the rmiregistry tool

public static java.rmi.Remote lookup(java.lang.String) throws It returns the reference of


java.rmi.NotBoundException, java.net.MalformedURLException, the remote object.
java.rmi.RemoteException;
public static void bind(java.lang.String, java.rmi.Remote) throws It binds the remote object
java.rmi.AlreadyBoundException, with the given name.
java.net.MalformedURLException, java.rmi.RemoteException;
public static void unbind(java.lang.String) throws It destroys the remote
java.rmi.RemoteException, object which is bound
java.rmi.NotBoundExceptio with the given name.
n,java.net.MalformedURLException;

public static void rebind(java.lang.String, It binds the


java.rmi.Remote) throws remote object to
java.rmi.RemoteException, the new name.
java.net.MalformedURLException;
public static java.lang.String[] list(java.lang.String) It returns an array of the
throws java.rmi.RemoteException, names of the remote
java.net.MalformedURLException; objects bound in the
registry.

 Now start the registry service by using the rmiregistry tool.


 If you don't specify the port number, it uses a default port number.
 In this example, we are using the port number 5000.

rmiregistry 5000
TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 91
Advanced java programming I Msc (cs)

5) Create and run the server application

 Now rmi services need to be hosted in a server process.


 The Naming class provides methods to get and store the remote object.
 The Naming class provides 5 methods.

In this example, we are binding the remote object by the name sonoo.

import java.rmi.*;
import java.rmi.registry.*;
public class MyServer{
public static void main(String args[]){
try{
Adder stub=new AdderRemote();
Naming.rebind("rmi://localhost:5000/sonoo",stub);
}catch(Exception e){System.out.println(e);}
}
}

6) Create and run the client application

 At the client we are getting the stub object by the lookup() method of the Naming class
and invoking the method on this object.

 In this example, we are running the server and client applications, in the same machine
so we are using localhost.
 If you want to access the remote object from another machine, change the localhost to
the host name (or IP address) where the remote object is located.

import java.rmi.*;
public class MyClient{
public static void main(String args[]){
try{
Adder stub=(Adder)Naming.lookup("rmi://localhost:5000/sonoo");
System.out.println(stub.add(34,4));

}catch(Exception e){}
}
}

For running this rmi example,


1. Compile all the java files: javac *.java
2. Create stub and skeleton object by rmic tool: rmic AdderRemote

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 92


Advanced java programming I Msc (cs)

3. Start rmi registry in one command prompt: rmiregistry 5000


4. Start the server in another command prompt: java MyServer
5. Start the client application in another command prompt: java MyClient
6. Display the Output

Remote Method Activation


The Activatable class

• With the introduction of the class java.rmi.activation.Activatableand the RMI daemon,


rmid, programs can be written to register information about remote object
implementations that should be created and execute "on demand“, rather than running all
the time

• The RMI daemon, rmid, provides a Java virtual machine from which other
JVM instances may be spawned
The Remote Interface

import java.rmi.*;

public interface MyRemoteInterface extends Remote


{

public Object callMeRemotely() throws RemoteException;


}

The Remote Interface Implementation

• There are four steps to create an implementation class

• Make the appropriate imports in the implementation class

• Extend your class from

java.rmi.activation.Activatable

• Declare a two-argument constructor in the implementation class

• Implement the remote interface methods


TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 93
Advanced java programming I Msc (cs)

The Remote Interface Implementation

import java.rmi.*;
import java.rmi.activation.*;

public class ActivatableImplementation extends Activatable implements MyRemoteInterface


{

public ActivatableImplementation(ActivationID id, MarshalledObject data) throws


RemoteException {
super(id, 0);
}

public Object callMeRemotely() throws RemoteException { return "Success";

The “Setup” Class

• The job of the "setup" class is to create all the information necessary for the
activatable class, without necessarily creating an instance of the remote object

• The setup class passes the information about the activatable class to rmid, registers
a remote reference (an instance of the activatable class's stub class) and an

• identifier (name) with the rmiregistry, and then the setup class may exit

• There are seven steps to create a setup class:

• Make the appropriate imports

• Install a security manager

• Create an ActivationGroupinstance

• Create an ActivationDescinstance

• Declare an instance of your remote interface and register with


rmid

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 94


Advanced java programming I Msc (cs)

• Bind the stub to a name in the rmiregistry

• Quit the setup application

Class Summary
The Activatable class provides support for
remote objects that require persistent access
Activatable
over time and that can be activated by the
system.
An activation descriptor contains the
ActivationDesc
information necessary to activate an object:
An ActivationGroup is responsible for creating
new instances of "activatable" objects in its
ActivationGroup
group, informing its ActivationMonitor when
either:
ActivationGroup_Stub is a stub class for the
subclasses
ActivationGroup_Stub of java.rmi.activation.ActivationGroup that are
exported as
a java.rmi.server.UnicastRemoteObject.
An activation group descriptor contains the
ActivationGroupDesc information necessary to create/recreate an
activation group in which to activate objects.
Startup options for ActivationGroup
ActivationGroupDesc.CommandEnvironment
implementations.
The identifier for a registered activation group
ActivationGroupID serves several purposes: identifies the group
uniquely within the activation system,
Activation makes use of special identifiers to
ActivationID denote remote objects that can be activated
over time.

Package java.rmi.activation

Provides support for RMI Object Activation.

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 95


Advanced java programming I Msc (cs)

Interface Summary
An ActivationInstantiator is responsible for creating instances of
ActivationInstantiator
"activatable" objects.
An ActivationMonitor is specific to an ActivationGroup and is
ActivationMonitor obtained when a group is reported active via a call
to ActivationSystem.activeGroup (this is done internally).
The ActivationSystem provides a means for registering groups
ActivationSystem
and "activatable" objects to be activated within those groups.
Activator The Activator facilitates remote object activation.

Exception Summary
This exception is thrown by the RMI runtime when activation fails
ActivateFailedException
during a remote call to an activatable object.
ActivationException General exception used by the activation interfaces.
An UnknownGroupException is thrown by methods of classes and
interfaces in the java.rmi.activation package when
UnknownGroupException
the ActivationGroupID parameter to the method is determined to be
invalid, i.e., not known by the ActivationSystem.
An UnknownObjectException is thrown by methods of classes and
interfaces in the java.rmi.activation package when
UnknownObjectException
the ActivationID parameter to the method is determined to be
invalid.

Serialization in Java:
It is a mechanism of writing the state of an object into a byte-stream. It is mainly used in
Hibernate, RMI, JPA, EJB and JMS technologies.
The reverse operation of serialization is called deserialization where byte-stream is converted into an
object. The serialization and deserialization process is platform-independent, it means you can
serialize an object on one platform and deserialize it on a different platform.
For serializing the bject ,wec all the writeObject() method of ObjectOutputStream class, and
for deserialization we call the readObject() method of ObjectInputStream class.

Advantages of Java Serialization


It is mainly used to travel object's state on the network (that is known as marshalling).

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 96


Advanced java programming I Msc (cs)

java.io.Serializable interface
Serializable is a marker interface (has no data member and method). It is used to "mark" Java classes
so that the objects of these classes may get a certain capability. The Cloneable and Remote are also
marker interfaces.
The Serializable interface must be implemented by the class whose object needs to be persisted.
The String class and all the wrapper classes implement the java.io.Serializable interface by default.
Let's see the example given below:

Student.java
import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}

In the above example, Student class implements Serializable interface. Now its objects can be
converted into stream. The main class implementation of is showed in the next code.

ObjectOutputStream class
The ObjectOutputStream class is used to write primitive data types, and Java objects to an
OutputStream. Only objects that support the java.io.Serializable interface can be written to streams.
Building distributed applications is difficult because you must take into account several issues, such as
partial failure, increased latency, distributed persistence, and language compatibility.

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 97


Advanced java programming I Msc (cs)

Java Spaces
The JavaSpaces technology is a simple and powerful high-level tool for building distributed
and collaborative applications. Based on the concept of shared network -based space that serves as
both object storage and exchange area, it provides a simple API that is easy to learn and yet expressive
for building sophisticated distributed applications.

Distributed Computing

Distributed computing is about building network-based applications as a set of processes that


are distributed across a network of computing nodes (or hosts) that work together to solve a problem.
The advantages of building applications using this approach are many, including performance,
resource sharing, scalability, and fault tolerance.
The most obvious complexity is the varied architecture of machines. Other issues that have
significant impact on designing and implementing distributed applications include latency,
synchronization, and partial failure.
The JavaSpaces technology model is different in that it provides persistent object exchange
areas (or spaces) through which remote Java technology processes coordinate actions and exchange
data.

The JavaSpaces Technology

The JavaSpaces technology is a high-level tool for building distributed applications, and it can
also be used as a coordination tool. A marked departure from classic distributed models that rely on
message passing or RMI, the JavaSpaces model views a distributed application as a collection of
processes that cooperate through the flow of objects into and out of one or more spaces.

 It should provide a platform that simplifies the design and implementation of distributed computing
systems.
 The client side should have few classes, both to keep the client simple and to speed the
downloading of client classes.
 The client side should have a small footprint because it will run on computers with limited local
memory.
 A variety of implementations should be possible.
 It should be possible to create a replicated JavaSpaces service.

JavaSpaces Technology vs. Databases

The data you can store there is persistent and later searchable. But a JavaSpaces service is not a
relational or object database. JavaSpaces services are not used primarily as data repositories. They are
designed for a different purpose than either relational or object databases.
Although a JavaSpaces service functions somewhat like a file system and somewhat like a
database, it is neither. The key differences between JavaSpaces technology and databases are the
TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 98
Advanced java programming I Msc (cs)

following:
 Relational databases understand the data they store and manipulate it directly through query
languages such as SQL. JavaSpaces services, on the other hand, store entries that they understand
only by type and the serialized form of each field. As a result, there are no general queries in the
JavaSpaces application design, only "exact match" or "don't care" for a given field.
 Object databases provide an object-oriented image of stored data that can be modified and used,
almost as if it were transient memory. JavaSpaces systems do not provide a nearly transparent
persistent or transient layer, and they work only on copies of entries.

JavaSpaces Services and Operations

Application components (or processes) use the persistent storage of a space to store objects and to
communicate. The components coordinate actions by exchanging objects through spaces; the objects
do not communicate directly. Processes interact with a space through a simple set of operations.
You can invoke four primary operations on a JavaSpaces service:
 write(): Writes new objects into a space
 take(): Retrieves objects from a space
 read(): Makes a copy of objects in a space
 notify: Notifies a specified object when entries that match the given template are written into
a space
Both the read() and take() methods have variants: readIfExists() and takeIfExists(). If they are
called with a zero timeout, then they are equivalent to their counterpart. The timeout parameter comes
into effect only when a transaction is used.
Each operation has parameters that are entries. Some are templates, which are a kind of
entry. The write() operation is a store operation. The read() and take() operations are a combination of
search and fetch operations. The notify method sets up repeated search operations as entries are
written to the space. If a take() or read() operation doesn't find an object, the process can wait until an
object arrives.
Unlike conventional object stores, objects are passive data. Therefore, processes do not modify
objects in the space or invoke their methods directly. In order to modify an object, a process must
explicitly remove, update, and reinsert it into the space.

The JavaSpaces Technology Application Model

A JavaSpaces service holds entries, each of which is a typed group of objects expressed in a
class that implements the interface net.jini.core.entry.Entry. Once an entry is written into a JavaSpaces
service, it can be used in future look-up operations. Looking up entries is performed using templates,
which are entry objects that have some or all of their fields set to specified values that must be
matched exactly. All remaining fields, which are not used in the lookup, are left as wildcards.
There are two look-up operations: read() and take(). The read() method returns either an entry
that matches the template or an indication that no match was found. The take() method operates
like read(), but if a match is found, the entry is removed from the space.
TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 99
Advanced java programming I Msc (cs)

Using JavaSpaces technology, distributed applications are modeled as a flow of objects


between participants, which is different from classic distributed models such as RMIs. Figure 1
indicates what a JavaSpaces technology-based application looks like.

Figure 1: A Typical JavaSpaces Technology Application


Clients perform operations that map entries to templates onto JavaSpaces services. Such
operations can be singleton or contained in a transaction so that all or none of the operations take
place. Notifications go to event catches, which can be either clients or proxies for clients.
All the messages that make up the discussion are written to a space that acts as a chat area.
Participants write message objects into the space, while other members wait for new message objects
to appear, then read them out and display their contents. The list of participants can be kept in the
space and updated whenever someone joins or leaves the discussion. But by using JavaSpaces
technology, you need only one interface.

The JavaSpaces Technology Programming Model

All operations are invoked on an object that implements the net.jini.space.JavaSpace interface. A
space stores entries, each of which is a collection of typed objects that implements the Entry interface.
Code Sample 1 shows a MessageEntry that contains one field: content, which is null by default.
Information on how to compile and run the sample application appears later in this article.

Code Sample 1: MessageEntry.java


Copy
Copied to Clipboard
Error: Could not Copy
import net.jini.core.entry.*;
public class MessageEntry implements Entry {
TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 100
Advanced java programming I Msc (cs)

public String content;


public MessageEntry() {
}
public MessageEntry(String content) {
this.content = content;
}
public String toString() {
return "MessageContent: " + content;
}
}
MessageEntryspace
Copy
Copied to Clipboard
Error: Could not Copy
JavaSpace space = getSpace();
MessageEntry msg = new MessageEntry();
msg.content = "Hello there";
space.write(msg, null, Lease.FOREVER);
nullTransaction

The write() operation places a copy of an entry into the given JavaSpace service, and
the Entry passed is not affected by the operation. Each write() operation places a new Entry into the
space even if the same Entry object is used in more than one write().
If you like, you can change the lease (when the write() operation is invoked) to one hour as follows: >
space.write(msg, null, 60 * 60 * 1000);
write()Lease
Once the entry exists in the space, any process with access to the space can perform a read() on
it. To read an entry, a template is used, which is an entry that may have one or more of its fields set
to null. An entry matches a template if (a) the entry has the same type as or is a subtype of the
template and (b) if for every specified non- null field in the template, their fields match exactly.
The null fields act as wildcards and match any value. The following code segment shows how to
create a template and perform a read() on the space:

MessageEntry template = new MessageEntry();


MessageEntry output = (MessageEntry) space.read(template, null, Long.MAX_VALUE);
null MessageEntry Long.MAX_VALUE read() take() readIfExists()
Code Sample 2 shows the client that discovers the JavaSpace service, writes a message into the
space, and then reads it.

Code Sample 2: SpaceClient.java


import net.jini.space.JavaSpace;
public class SpaceClient {

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 101


Advanced java programming I Msc (cs)

public static void main(String argv[]) {


try {
MessageEntry msg = new MessageEntry();
msg.content = "Hello there";
System.out.println("Searching for a JavaSpace...");
Lookup finder = new Lookup(JavaSpace.class);
JavaSpace space = (JavaSpace) finder.getService();
System.out.println("A JavaSpace has been discovered.");
System.out.println("Writing a message into the space...");
space.write(msg, null, 60*60*1000);
MessageEntry template = new MessageEntry();
System.out.println("Reading a message from the space...");
MessageEntry result = (MessageEntry) space.read(template, null, Long.MAX_VALUE);
System.out.println("The message read is: "+result.content);
} catch(Exception e) {
e.printStackTrace();
}
}
}

Transactions

The JavaSpaces API uses the package net.jini.core.transaction to provide basic atomic
transactions that group multiple operations across multiple JavaSpaces services into a bundle that acts
as a single atomic operation. Either all modifications within the transactions will be applied or none
will, regardless of whether the transaction spans one or more operations or one or more JavaSpaces
services.
A read(), write(), or take() operation that has a null transaction acts as if it were in a committed
transaction that contained that operation. As an example, a take() with a null transaction parameter
performs as if a transaction was created, the take() was performed under that transaction, and then the
transaction was committed.

The Jini Outrigger JavaSpaces Service

The Jini Technology Starter Kit comes with the package com.sun.jini.outrigger, which provides an
implementation of a JavaSpaces technology-enabled service. You can run it two ways:
 As a transient space that loses its state between executions:
Use com.sun.jini.outrigger.TransientOutriggerImpl.
 As a persistent space that maintains state between executions:
Use com.sun.jini.outrigger.PersistentOutriggerImpl.
TransientOutriggerImplPersistentOutriggerImpl

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 102


Advanced java programming I Msc (cs)

Compiling and Running the SpaceClient Application

To compile and run the sample application in this article, do the following:
1. Compile the code in Code Sample 1 ( MessageEntry.java) using javac as follows:
prompt> javac -classpath <pathToJiniInstallation\lib\jini-ext.jar> MessageEntry.java
Note that you need to include the JAR file jini-ext.jar in your classpath. This JAR file comes with the
starter kit and is in the lib directory of your installation.
2. Compile the code in Code Sample 2 ( SpaceClient.java). Note that this code makes use of a utility
class called Lookup to locate or discover a JavaSpace space. Therefore, before you
compile SpaceClient.java, you should download Lookup.java and then compile both classes
using javac as shown in step 2. Note that you should include the directory that
contains MessageEntry.class in your classpath when compiling SpaceClient.java.
3. Run Launch-All, which is in the installverify directory of your Jini installation directory. This will
start a service browser (as shown in Figure 2) and six contributed Jini network technology services,
one of which is the JavaSpace service.

Figure 2: Jini Network Technology Service Browser


4. Finally, run the SpaceClient application using the java command as follows. Here I assume that your
Jini installation directory is C:\Jini2_1beta and that the classes you compiled earlier are
at C:\Jini2_1beta\myclasses.
5. C:\Jini2_1beta\myclasses> java -classpath .\;
..\lib\jini-ext.jar;..\lib\reggie.jar;..\lib\outrigger.jar SpaceClient
If all goes well, you will see the output shown in Figure 3.

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 103


Advanced java programming I Msc (cs)

Figure 3: SpaceClient Sample Output

**************END OF UNIT II*************

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 104


ADVANCED JAVA PROGRAMMING I- MSC(CS)

UNIT III
DATABASE
JDBC - Introduction
JDBC stands for Java Database Connectivity, which is a standard Java API for database-
independent connectivity between the Java programming language and a wide range of databases.
The JDBC library includes APIs for each of the tasks mentioned below that are commonly associated
with database usage.
 Making a connection to a database.
 Creating SQL or MySQL statements.
 Executing SQL or MySQL queries in the database.
 Viewing & Modifying the resulting records.
Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for portable
access to an underlying database. Java can be used to write different types of executables, such as −
 Java Applications
 Java Applets
 Java Servlets
 Java ServerPages (JSPs)
 Enterprise JavaBeans (EJBs).
All of these different executables are able to use a JDBC driver to access a database, and take advantage
of the stored data.
• Database Vendor: Provides a set of APIs for accessing data managed by database
server. Eg. Oracle, Sybase etc
• Client applications: written in C/C++ can use these vendor specific APIs
• JDBC Driver: A Middleware layer that translates the JDBC calls to vendor Specific
APIs
• Packages: java.sql --- J2SE
javax.sql---J2EE

JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database access but in general,
JDBC Architecture consists of two layers –

 JDBC API − This provides the application-to-JDBC Manager connection.


 JDBC Driver API − This supports the JDBC Manager-to-Driver Connection.
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.
Following is the architectural diagram, which shows the location of the driver manager with respect to
the JDBC drivers and the Java application −

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 105


ADVANCED JAVA PROGRAMMING I- MSC(CS)

Common JDBC Components


The JDBC API provides the following interfaces and classes −
 DriverManager − This class manages a list of database drivers. Matches connection requests from
the java application with the proper database driver using communication sub protocol. The first driver
that recognizes a certain subprotocol under JDBC will be used to establish a database Connection.

 Driver − This interface handles the communications with the database server. You will interact directly with
Driver objects very rarely. Instead, you use DriverManager objects, which manages objects of this type.
It also abstracts the details associated with working with Driver objects.
 Connection − This interface with all methods for contacting a database. The connection object
represents communication context, i.e., all communication with database is through connection object only.
 Statement − You use objects created from this interface to submit the SQL statements to the database.
Some derived interfaces accept parameters in addition to executing stored procedures.
 ResultSet − These objects hold data retrieved from a database after you execute an SQL query using
Statement objects. It acts as an iterator to allow you to move through its data.
 SQLException − This class handles any errors that occur in a database application.
JDBC Driver Types
• JDBC Driver is a software component that enables java application to interact with
the database.
• There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)
Type 1-JDBC-ODBC bridge driver
• The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The
JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function
calls. This is now discouraged because of thin driver.
• In Java 8 and later versions, the JDBC-ODBC Bridge has been removed.
TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 106
ADVANCED JAVA PROGRAMMING I- MSC(CS)

• Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends
that you use JDBC drivers provided by the vendor of your database instead of the
JDBC-ODBC Bridge.
JDBC-ODBC architecture

Type 2-Native-API driver(Part Java, Part Native Driver)

• The Native API driver uses the client-side libraries of the database. The driver
converts JDBC method calls into native calls of the database API. It is not written
entirely in java.
Native API Driver Architecture

Figure 1:25 Native API Driver Architecture


Advantages and Drawbacks of Type 2 driver
Advantage:
• performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 107


ADVANCED JAVA PROGRAMMING I- MSC(CS)

• The Native driver needs to be installed on the each client machine.


• The Vendor client library needs to be installed on client machine.
Type 3- Network Protocol driver(Intermediate Database Access Server)
• The Network Protocol driver uses middleware (application server) that converts
JDBC calls directly or indirectly into the vendor-specific database protocol. It is fully
written in java.
Type 3 Drive Architecture
Figure 1:26 Type 3 Drive Architecture

Type 3: Advantages and Drawbacks


Advantage:
• No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.
Disadvantages:
• Network support is required on client machine.
• Requires database-specific coding to be done in the middle tier.
• Maintenance of Network Protocol driver becomes costly because it requires database-
specific coding to be done in the middle tier.
Type 4- Thin driver (Pure Java Driver)
• The thin driver converts JDBC calls directly into the vendor-specific database
protocol.That is why it is known as thin driver.

• It is fully written in Java language.

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 108


ADVANCED JAVA PROGRAMMING I- MSC(CS)

Advantage:
• Better performance than all other drivers.
• No software is required at client side or server side.
Disadvantage:
• Drivers depend on the Database.
Java.sql package
• Class groups based on functionalities
• Connection Management
• Database Access
• Data Types
• Database MetaData
• Exceptions and Warnings

Database Access in Java:

Step1 –Import the Packages


Step2 –Load the drivers using the forName() method
Step3 –Register the drivers using DriverManager
Step4 –Establish a connection using the Connectionclassobject
Step5 –Create a statement
Step6 –Execute the query
Step7 – Close the connections

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 109


ADVANCED JAVA PROGRAMMING I- MSC(CS)

Connection management classes/interfaces of java.sql Package:


To establish connection to database

Table: 1.1 Connection management classes/interfaces of java.sql Package


Database Access: classes/interfaces of java.sql Package:
To send SQL statement to database for execution and getting results

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 110


ADVANCED JAVA PROGRAMMING I- MSC(CS)

Table: 1.2 Database Access: classes/interfaces of java.sql Package


Data Types java.sql Package:
For programming the database

Table: 1.3 Data Types java.sql Package


Metadata: java.sql Package: To obtain metadata about database, statements,resultsets

Table: 1.4 Metadata: java.sql Package


JDBC Steps
TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 111
ADVANCED JAVA PROGRAMMING I- MSC(CS)

• Register the Driver class


• Create connection
• Create statement
• Execute queries
• Close connection

Figure 1:28 JDBC Steps


Step 1: Register the driver class
• The forName() method of Class class is used to register the driver class. This method
is used to dynamically load the driver class.
• Syntax:

• Example:
• Class.forName("com.mysql.jdbc.Driver");
DriverManager class
• can manage multiple drivers
• Each driver has to register with DriverManager class
• In JDBC we load database driver using java.lang.Class loader object
• At runtime classloader locates and loads the driver from the class path using bootstrap
class loader
Step 2: Create the connection object
• The getConnection() method of DriverManager class is used to establish connection
with the database.
• Syntax:
1) public static Connection getConnection(String url)throws SQLException
TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 112
ADVANCED JAVA PROGRAMMING I- MSC(CS)

2) public static Connection getConnection(String url,String name,String password) throws


SQLException
Example
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/stud","root","");

Establishing a Connection: java.sql.Connection interface:

Table: 1.5 Establishing a Connection: java.sql.Connection interface

Step 3-Create the Statement object:


The createStatement() method of Connection interface is used to create statement. The object
of statement is responsible to execute queries with the database.
• Syntax:
• Example: Statement st=con.createStatement();

Creating and Executing SQL statement

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 113


ADVANCED JAVA PROGRAMMING I- MSC(CS)

Table: 1.6 Creating and Executing SQL statement


Statement interface Methods

Step 4: Execute the query


• The executeQuery() method of Statement interface is used to execute queries to the
database. This method returns the object of ResultSet that can be used to get all the
records of a table.
• Syntax: public ResultSet executeQuery(String sql)throws SQLException
Querying the database: The ResultSet interface

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 114


ADVANCED JAVA PROGRAMMING I- MSC(CS)

• Execute():
– Syntax:public boolean execute(String sql) throws SQLException
• ExecuteQuery():
– Syntax:public ResultSet executeQuery(String sql) throws SQLException
Methods to retrieve data
• getArray()
• getBlob()
• getBoolean()
• getInt()
• getDate()
• getByte()
• getLong()
• getString()
• getDouble()
getObject()
getTime
Step 5 :Close the connection object
• By closing connection object statement and ResultSet will be closed automatically.
• The close() method of Connection interface is used to close the connection.
• Syntax: public void close()throws SQLException
• Example: con.close()
JDBC Connectivity using Type 1 – JDBC ODBC
DriverCreate a database

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 115


ADVANCED JAVA PROGRAMMING I- MSC(CS)

Figure 1:29 Create a database Student


JDBC Connectivity using Type 1 – JDBC ODBC DriverCreate Table stud

Figure 1:30 JDBC ODBC Driver Create Table stud

JDBC Connectivity using Type 1 – JDBC ODBC DriverCreate new data source

Figure 1:31 – JDBC ODBC DriverCreate new data source

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 116


ADVANCED JAVA PROGRAMMING I- MSC(CS)

Figure 1:32 – JDBC ODBC DriverCreate new data source

Figure 1:33 – JDBC ODBC DriverCreate new data source

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 117


ADVANCED JAVA PROGRAMMING I- MSC(CS)

Output window after Java code execution

Database table update after the Java code execution

Figure 1:34 Data Base

Prepared statements
• Creating parameterized statement such that data for parameters can be substituted
dynamically
• Creating statement involving data values that can always be represented as character
strings

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 118


ADVANCED JAVA PROGRAMMING I- MSC(CS)

• Pre-compiling SQL statement to avoid repeated compiling of same SQL statement


• Eg. Select * from <tab> where user_id=?
• If the value is not known then it is replaced by ‘?’ during runtime
• A PreparedStatement object can hold precompiled SQL statements

Syntax:
public PreparedStatement prepareStatement(String query)throws SQLException{}

Table: 1.8 Prepared statements

Create a table
create table emp(id number(10),name varchar2(50));
Insert the records using PreparedStatement

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 119


ADVANCED JAVA PROGRAMMING I- MSC(CS)

Multimedia Databases
The multimedia databases are used to store multimedia data such as images,
animation, audio, video along with text. This data is stored in the form of multiple file types
like .txt(text), .jpg(images), .swf(videos), .mp3(audio) etc.

Contents of the Multimedia Database


The multimedia database stored the multimedia data and information related to it. This is
given in detail as follows −
Media data
This is the multimedia data that is stored in the database such as images, videos, audios,
animation etc.
Media format data
The Media format data contains the formatting information related to the media data such as
sampling rate, frame rate, encoding scheme etc.
Media keyword data
This contains the keyword data related to the media in the database. For an image the

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 120


ADVANCED JAVA PROGRAMMING I- MSC(CS)

keyword data can be date and time of the image, description of the image etc.

Media feature data


Th Media feature data describes the features of the media data. For an image, feature data can
be colours of the image, textures in the image etc.

Applications of Multimedia Database

These are various applications of multimedia database

Documents and record management

Multimedia databases are used in industries that require a large set of documentation and
records, such as the insurance claim industry.

Education

Multimedia data provides an interactive way to represent data. It makes multimedia databases
effective knowledge dissemination tools. Examples are multimedia datasets in digital
libraries and computer-aided learning software.

Marketing and Entertainment

Multimedia databases act as data providers for entertainment applications like video-on-
demand apps and news-on-demand apps. They can provide multimedia data for
advertisements and digital marketing processes.

Real-time Monitoring

When combined with various software tools, multimedia databases can be used to monitor
and manage multimedia data in real-time. For example, a geographic information system
(GIS) makes use of multimedia databases to analyze and visualize geographical multimedia
data in real-time.

Challenges of Multimedia Database


There are many challenges to implement a multimedia database. Some of these are:
 Multimedia databases contains data in a large type of formats such as .txt(text),
.jpg(images), .swf(videos), .mp3(audio) etc. It is difficult to convert one type of data
format to another.
 The multimedia database requires a large size as the multimedia data is quite large
and needs to be stored successfully in the database.
 It takes a lot of time to process multimedia data so multimedia database is slow.

Database Support in Web Applications


Data is very important in Web App Development. Database plays a critical role in web app
development. It is one of the most important aspects of building an application. It is necessary that you
have a piece of good knowledge of databases before using them in your application.

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 121


ADVANCED JAVA PROGRAMMING I- MSC(CS)

Database design plays a key role in the operation of your website and provides you with
information regarding transactions, data integrity, and security issues. In this article, you will learn the role
of databases in web application development.

Database
Data is the foundation of a web application. It is used to store user information, session data, and
other application data. The database is the central repository for all of this data. Web applications use a
variety of databases to store data such as flat files, relational databases, object-relational databases, and
NoSQL databases.
A database is a collection of data and information that is stored in an organized manner for easy
retrieval. The primary purpose of a database is to store, retrieve, and update information. A database can
be used to store data related to any aspect of business operations.
Databases can be very large, containing millions of records, or very small, containing just a few
records or even a single record. They may be stored on hard disks or other media, or they may exist only
in memory. In the early days of computing, databases were stored on tape drives or punch cards. Today
they're stored on hard drives, flash memory cards, and other media.
Databases are designed to ensure that the data they contain is organized and easily retrievable. A
database management system (DBMS) is the software used to create and maintain a database.

Role of Database in Web Application


The role of databases in web application development has increased over time. As a result, a
number of developers create applications that use databases. A database is nothing but an organized
collection of data that helps us, whether creating or modifying any program.

The database is used to store all the information that the user needs to store. For example, if you
are developing a shopping cart website then it will contain product details, customer details, order details,
etc. In this case, you need to store this information in a database so that we can use them later on.

Need for Web App Developers for a Database


The first thing one should know when it comes to databases is the need. There are huge numbers
of businesses out there, whose revenue depends on the success and future of their database. You see, a
database is extremely important for online companies and businesses as well. These days databases are
used for various purposes like managing financial records, setting up customer profiles, keeping
inventory and ordering information, etc.
Most modern web applications are based on a database. The database stores information about
the users, products, orders, and more. A database is an important component of any web application
because it provides a central location for storing user information and business logic. In addition to this, it
allows you to store complex data structures with minimal effort.
Databases are used by businesses to collect and store customer information, financial records,
and inventory data. They're also used in research projects to store information about experiments or tests.
For example, if you were conducting a survey on the habits of people who eat cereal for breakfast, you
might use a database to keep track of your results.
Databases are also used by government agencies to store public records like birth certificates and
marriage licenses. Databases are also used by medical researchers who need to record the medical history
of patients in order to determine how effective certain treatments may be for different diseases or
conditions.

Web Application Databases Offer Benefits


Web applications are becoming more and more popular because they allow users to access
information from different devices at the same time. A web application database offers benefits such as:

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 122


ADVANCED JAVA PROGRAMMING I- MSC(CS)

Security
A web application database provides security features such as encryption and password protection. If a
user’s password becomes lost or compromised, it will not be possible for someone else to access the
information stored in the database.
Accessibility
Users can access their data from any internet-enabled device, which includes smartphones and tablets as
well as laptops and desktops. This means that users do not have to worry about losing their valuable data
because it is stored on another device.
Reliability and scalability
Web applications are usually accessed by many users simultaneously, unlike traditional desktop
applications that are accessed by one person at a time, so web apps need to be able to handle more
requests simultaneously than their desktop counterparts. Web application databases use distributed
architecture (multiple servers) to scale up quickly when demand increases, so they can handle large
numbers of simultaneous requests without slowing down or crashing.
Ease of maintenance for IT staff
Because web application databases use distributed architecture, problems can be isolated and fixed
quickly, which reduces downtime for the end user and reduces costs for IT staffs responsible for
maintaining the system. Also, with database automation tools we can make database tasks easier and
safer.

Types of Databases in Web Application


There are two types of databases: relational and non-relational. Relational databases are built on
the principles of tabular data, which means there has to be a one-to-one relationship between the columns
and rows in the table. A non-Relational Database is also known as NoSQL Database.

Relational
A database is a large collection of structured data, which can be accessed to find specific information.
Relational databases are famous for their structure and have been used by programmers for years.

A relational database is data storage that maintains a relationship between two or more entities. It is used
whenever you want to store information in a way that it can be retrieved by your application. In general,
we can say that a relational database is a data storage structure where each tuple on its own occupies one
record and consists of values of attributes.

Advantages
The main advantages of relational databases include:
 Data integrity. A correctly implemented relational database ensures that all data entered remains
accurate, complete, and consistent over time. This helps ensure that all users have access to the most up-
to-date data possible at any given moment without having to worry about whether it will still be there
when they need it later on down the line.
 They're easy to use. Relational databases are designed to be easy to understand and use. The
relationships between all the tables and data elements are clearly defined, making it easy to understand
how they work together.

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 123


ADVANCED JAVA PROGRAMMING I- MSC(CS)

 Scalability. Relational databases scale easily from small applications up to large enterprise systems. You
can add more disk space and memory resources when needed without taking down your application or
disrupting end users. This makes relational databases ideal for large-scale applications, such as data
warehouses or customer relationship management systems.
 High availability and disaster recovery capabilities. Relational databases provide automated backup
capabilities that allow you to recover quickly from hardware failures or other disasters without requiring
human intervention or manual restoration procedures.

Disadvantages
 Not suitable for real-time data analysis. Relational databases can't be used for real-time data analysis
because they don't store the data in such a way that it can be queried quickly. This means that if you want
to analyze your data in real-time, you need a technology other than Relational databases.
 The inability to store documents or graphs in their native format. This means that you need to
transform your data into tabular format before storing it. This can be very inconvenient if you want to
query your data in a different way
 Not very good at storing sparse data (i.e., large empty spaces). For example, if you want to store all
email addresses from your customers and only non-empty addresses are stored, then this will take up a lot
of space compared to storing every single email address even if it's empty
 Relational databases have a fixed schema. You cannot change the structure of the database during its
lifetime, this is called fixed schema. For example, if you want to add a new column for an existing table
in a relational database, you will have to re-write all queries .

Non-Relational
Non-relational databases (sometimes called object-oriented databases) are very different from
Relational databases. The term non-relational (or NoSQL) database describes any kind of database in
which there is no strict distinction between relations, rows, and columns. The term non-relational comes
from the fact that the objects stored within the databases are not based on relationships (also called joins),
but rather are based on an implicit, often unstructured structure.
Non-relational databases (or NoSQL) is a class of database management systems that were
designed to be more flexible than a relational database. The main reason is that they are disconnected
from the original data structure and don't use the traditional relationships between tables in database
design.

Advantages
 Speed. The most obvious advantage of non-relational databases is that they can be extremely fast. Non-
relational databases can do things that would take too long in a relational database, such as searching
every record or even all records on disk, without having to query the database first.
 Simplicity. Non-relational databases are generally easier to understand and use than relational ones,
making them ideal for smaller projects where there aren't many users or developers working with the data
at any given time. NoSQL databases might not be ideal for complex projects.
 Scalability. Because they are not constrained by the schema, non-relational databases can scale more
easily than relational databases. You can add more hardware and therefore more nodes, which increases
the overall performance of the system. This is particularly useful when you need to perform complex
computations on large amounts of data.
 Data can be stored in any format necessary for the application. For example, if your application
requires XML documents, then you can store them in an XML column instead of forcing them into a
table schema.
 The processing time for queries is faster in some cases because there is no need to traverse through
multiple tables or join across multiple databases like with relational databases.

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 124


ADVANCED JAVA PROGRAMMING I- MSC(CS)

Disadvantages
 No standardization. Each vendor has its own APIs and features, making it challenging to implement
cross-platform applications.
 Some non-relational databases (especially those used for big data) have problems dealing with
large amounts of data at once because they don't have good query optimization algorithms built into
them as relational databases do.
 A non-relational database doesn't have a fixed structure like a relational database, so you'll need to
write code that can handle the unexpected — for example, you might have to write code that handles
different field lengths depending on what kind of data is being stored.

 The biggest disadvantage of non-relational databases is that they don't support ACID
transactions. In other words, to update data in a non-relational database, you need to perform multiple
queries and then combine them together.

Graph Databases (NoSQL)


Graph databases are a relatively new type of database that is able to store and query complex
relationships between entities. Graph databases have been around for many years, but have recently
become popular as large-scale applications like Facebook and LinkedIn have adopted them.

Graph-based database management systems provide a way to model relationships between objects as
nodes connected by edges (lines). Graphs can be used to represent complex relationships among people,
places, and things in your world such as connections between people on social media sites like Facebook.

Advantages
 Easy to model real-world situations: The structure of a graph database allows you to model any type of
relationship that exists in your real-world business problem — not just the ones that fit into a traditional
table
 Efficient for traversing linked data: Graphs are particularly useful for traversing linked data because
they allow you to follow links between objects as easily as searching within an object. You can easily
find all records related to a particular item or set of items by following related links between those
records.
 Graph databases also allow you to query data on both nodes and edges at the same time, so they're
great for analyzing relationships between entities no matter how deep those relationships may go!

Disadvantages
 Performance. Graphs are not known for their fast performance. They do not perform well when there
are multiple levels of nesting or loops in the graph structure. This means that they can be slow when
dealing with large amounts of data or graphs with high-degree vertices
 Scalability. Graphs are not scalable in an easy way like tables are in relational databases. Because graphs
are implemented as networks and each vertex can have multiple edges linking it to other vertices, adding
more vertices and edges to a graph makes it more difficult to manage efficiently.
 They are relatively new. Many organizations have already invested heavily in relational or document-
oriented databases and may not want to throw away all that investment.

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 125


ADVANCED JAVA PROGRAMMING I- MSC(CS)

List of Popular Web App Databases

MySQL (Relational)
MySQL is a relational database management system (RDBMS) based on SQL. It is a popular
database server, and a multi-user, multi-threaded SQL database. MySQL is developed by Oracle
Corporation. MySQL database is often used for data storage, especially in web applications, and it is also
widely used for creating and maintaining relational database tables.
MySQL is owned by Oracle Corporation and was developed by a Swedish company called
MySQL AB, which was bought by Sun Microsystems in 2008. As of 2009, the project is managed by
Oracle Corporation.

PostgreSQL (Relational)
An object-relational database management system that supports SQL-based queries, similar to
those used by other RDBMS systems such as MySQL or Oracle Database. PostgreSQL is developed and
maintained by PostgreSQL Global Development Group, which is made up of several companies and
individuals who have contributed code to the project over time.The software is distributed under an ISC
license, which allows anyone to use it for any purpose without paying royalties or fees.
MongoDB (Non-Relational)
MongoDB is an open-source document-oriented database developed by MongoDB Inc.
(formerly 10gen). The first version was released in 2009. It is written in C++ and provides a document-
oriented data model that can be queried using a JSON-like query language.
A document can be thought of as a virtual "sheet" or "document" in a spreadsheet application
such as Microsoft Excel or Google Sheets. A document contains multiple fields that may be similar to
cells in an Excel spreadsheet or cells in an Access database table. These fields can have different types:
text, numbers, dates, and so on.
.
Cassandra (Non-Relational)
Cassandra is an open-source database management system that runs on many servers, making it
well-suited for handling large amounts of data. It offers fast performance and can scale up to a petabyte of
data across multiple servers, making it useful for applications with high write-throughput requirements.
The technology was developed at Facebook and released as an Apache Incubator project in
2009. It graduated from incubation in June 2010 and became an Apache Top-level Project (TLP) in
January 2012.
It aims to provide high availability by making it easy to deploy multiple copies of the data across
many hosts while tolerating failures at any one host. Cassandra is a key-value store, but it has flexible data
models, so you can use it to store virtually any kind of data. You can also use Cassandra for full-text
search, or even for storing graph data

Neo4j (Graph database)


Neo4j is an open-source graph database management system that stores data in a native graph
database format. It's designed to store data and query it very quickly, making it ideal for applications that
involve complex relationships between entities. It uses the native graph data model to provide ACID
transactions, high availability, and indexing.
This makes it easier to build applications that model real-world problems such as social networks
or product recommendations. You can create multiple nodes for the same entity without duplicating data
or having to use foreign keys.

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 126


ADVANCED JAVA PROGRAMMING I- MSC(CS)

MariaDB (Relational)
MariaDB is a fork of the MySQL relational database management system intended to remain
free under the GNU GPL. MariaDB was forked in 2009 by some of the original developers of MySQL
when Oracle announced that it would no longer fully support the community-developed version of
MySQL in favor of a paid enterprise product.
The original developers of MySQL created MariaDB to provide a better development environment and
more robust performance. MariaDB strives to be compatible with MySQL and includes most of its
storage engines.

MSSQL (Relational)
MSSQL databases are the core of Microsoft SQL Server. It is a relational database management
system (RDBMS), a special type of database software that is used to create, store and manipulate data in
an organized manner.
MSSQL can be used to build enterprise-level business solutions and applications. Regardless of the
platform or device your users are using, you can use MSSQL to create a centralized data store with a
single version of the truth.

Connecting Database to Web Application


Connecting a database to a web application is an important step in your development process. By
connecting your database to your web application, you can easily add new data, modify existing data,
delete data, and more.

There are a few ways to do it. The simplest way is to use a direct query to get the value you need.
This is not recommended because it will severely limit your flexibility .
Another approach is to use a stored procedure that returns the value. This can be done in SQL
Server, MySQL server, or other RDBMSs. If your web application needs more than one value from the
database, You would need to issue multiple queries or use another method.
The most common way to connect a database to an application is by using an Object Relational
Mapper (ORM). This technology connects your program to the database and allows you to use it like a
normal object. Eg:Active Record (AR).

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 127


ADVANCED JAVA PROGRAMMING I-MSC(CS)

UNIT IV
SERVLETS

Java Servlet and CGI:


Servlet is a Java class that is used to extend the capabilities of servers that host
applications accessed by means of a request-response model.
Servlets are mainly used to extend the applications hosted by web servers, however,
they can respond to other types of requests too. For such applications, HTTP-specific servlet
classes are defined by Java Servlet technology.
All the programs of Servlets are written in JAVA and they get to run on JAVA Virtual
Machine. The following image describes how a request from clients is served with the help of
threads:

CommonGateway Interface(CGI):

The Common Gateway Interface (CGI) provides the middleware between WWW
servers and external databases and information sources.
The World Wide Web Consortium (W3C) defined the Common Gateway Interface (CGI) and
also defined how a program interacts with a HyperText Transfer Protocol (HTTP) server. The
Web server typically passes the form information to a small application program that
processes the data and may send back a confirmation message.
This process or convention for passing data back and forth between the server and the
application is called the common gateway interface (CGI). The following image describes
how a web server acts as an intermediate between the CGI program and the client browser.

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 128


ADVANCED JAVA PROGRAMMING I-MSC(CS)

The following table explains the difference between the servlet and CGI:
Basis Servlet CGI

It is thread based i.e. for every


It is process-based i.e. for every new
Approach new request new thread is
request new process is created.
created.

The codes are written in


Language The codes are written any programming
JAVA programming
Used language.
language.

Since codes are written in Since codes are written in any language,
Object- Java, it is object oriented and all the languages are not object-oriented
Oriented the user will get the benefits thread-based. So, the user will not get
of OOPs the benefits of OOPs

Portability It is portable. It is not portable.

It remains in the memory until It is removed from the memory after the
Persistence
it is not explicitly destroyed. completion of the process-basedrequest.

Server It can use any of the web- It can use the web-server that supports
Independent server. it.

Data Sharing Data sharing is possible. Data sharing is not possible.

It does not link the web server directly


Link It links directly to the server.
to the server.

It can read and set HTTP It can neither read nor set HTTP
HTTP server
servers. servers.

Construction and destruction Construction and destruction of the new


Cost
of new threads are not costly. processes are costly.

Speed Its can speed is slower. It can speed is faster.

Platform It can be Platform


It can be Platform dependent.
dependency Independent

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 129


ADVANCED JAVA PROGRAMMING I-MSC(CS)

A simple java Servlet:


Servlets are Java classes which service HTTP requests and implement
the javax.servlet.Servlet interface. Web application developers typically write servlets that
extend javax.servlet.http.HttpServlet, an abstract class that implements the Servlet interface
and is specially designed to handle HTTP requests.
Sample Code
Following is the sample source code structure of a servlet example to show Hello World −
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


public class HelloWorld extends HttpServlet {

private String message;

public void init() throws ServletException {


// Do required initialization
message = "Hello World";
}

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Set response content type


response.setContentType("text/html");

// Actual logic goes here.


PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}

public void destroy() {


// do nothing.
}
}

Compiling a Servlet
Let us create a file with name HelloWorld.java with the code shown above. Place this
file at C:\ServletDevel (in Windows) or at /usr/ServletDevel (in Unix). This path location
must be added to CLASSPATH before proceeding further.
Assuming your environment is setup properly, go in ServletDevel directory and
compile HelloWorld.java as follows –

$ javac HelloWorld.java
This command line uses the built-in javac compiler that comes with the Sun
Microsystems Java Software Development Kit (JDK). For this command to work properly,

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 130


ADVANCED JAVA PROGRAMMING I-MSC(CS)

you have to include the location of the Java SDK that you are using in the PATH
environment variable.
If everything goes fine, above compilation would produce HelloWorld.class file in the same
directory.

Servlet Deployment
A servlet application is located at the path <Tomcat-
installationdirectory>/webapps/ROOT and the class file would reside in <Tomcat-
installationdirectory>/webapps/ROOT/WEB-INF/classes.
If you have a fully qualified class name of com.myorg.MyServlet, then this servlet
class must be located in WEB-INF/classes/com/myorg/MyServlet.class.
For now, let us copy HelloWorld.class into <Tomcat-
installationdirectory>/webapps/ROOT/WEB-INF/classes and create following entries
in web.xml file located in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/

<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>

Above entries to be created inside <web-app>...</web-app> tags available in web.xml


file. There could be various entries in this table already available, but never mind.
You are almost done, now let us start tomcat server using <Tomcat-
installationdirectory>\bin\startup.bat (on Windows) or <Tomcat-
installationdirectory>/bin/startup.sh (on Linux/Solaris etc.) and finally
type http://localhost:8080/HelloWorld in the browser's address box. If everything goes fine,
you would get the following result

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 131


ADVANCED JAVA PROGRAMMING I-MSC(CS)

Anatomy of a java Servlet


Life Cycle of a Servlet (Servlet Life Cycle)
1. Life Cycle of a Servlet
1. Servlet class is loaded
2. Servlet instance is created
3. init method is invoked
4. service method is invoked
5. destroy method is invoked
The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the
servlet:
1. Servlet class is loaded.
2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.

As displayed in the above diagram, there are three states of a servlet: new, ready and end. The
servlet is in new state if servlet instance is created. After invoking the init() method, Servlet
comes in the ready state. In the ready state, servlet performs all the tasks. When the web
container invokes the destroy() method, it shifts to the end state.

1) Servlet class is loaded


The classloader is responsible to load the servlet class. The servlet class is loaded when the
first request for the servlet is received by the web container.

2) Servlet instance is created


The web container creates the instance of a servlet after loading the servlet class. The servlet
instance is created only once in the servlet life cycle.

3) init method is invoked

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 132


ADVANCED JAVA PROGRAMMING I-MSC(CS)

The web container calls the init method only once after creating the servlet instance.
The init method is used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet
interface. Syntax of the init method is given below:
public void init(ServletConfig config) throws ServletException

4) service method is invoked


The web container calls the service method each time when request for the servlet is
received. If servlet is not initialized, it follows the first three steps as described above then
calls the service method. If servlet is initialized, it calls the service method. Notice that
servlet is initialized only once. The syntax of the service method of the Servlet interface is
given below:
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException

5) destroy method is invoked


The web container calls the destroy method before removing the servlet instance from
the service. It gives the servlet an opportunity to clean up any resource for example memory,
thread etc. The syntax of the destroy method of the Servlet interface is given below:
public void destroy()

Reading data from a client


The browser uses two methods to pass this information to web server. These methods
are GET Method and POST Method.

GET Method
The GET method sends the encoded user information appended to the page request.
The page and the encoded information are separated by the ? (question mark) symbol as
follows −
http://www.test.com/hello?key1 = value1&key2 = value2
The GET method is the default method to pass information from browser to web
server and it produces a long string that appears in your browser's Location:box. Never use
the GET method if you have password or other sensitive information to pass to the server.
The GET method has size limitation: only 1024 characters can be used in a request string.
This information is passed using QUERY_STRING header and will be accessible
through QUERY_STRING environment variable and Servlet handles this type of requests
using doGet() method.

POST Method
A generally more reliable method of passing information to a backend program is the
POST method. This packages the information in exactly the same way as GET method, but
instead of sending it as a text string after a ? (question mark) in the URL it sends it as a
separate message. This message comes to the backend program in the form of the standard
input which you can parse and use for your processing. Servlet handles this type of requests
using doPost() method.

Reading Form Data using Servlet


Servlets handles form data parsing automatically using the following methods depending on
the situation −
 getParameter() − You call request.getParameter() method to get the value of a form
parameter.

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 133


ADVANCED JAVA PROGRAMMING I-MSC(CS)

 getParameterValues() − Call this method if the parameter appears more than once
and returns multiple values, for example checkbox.
 getParameterNames() − Call this method if you want a complete list of all
parameters in the current request.

GET Method Example using URL
Here is a simple URL which will pass two values to HelloForm program using GET
method.
http://localhost:8080/HelloForm?first_name = ZARA&last_name = ALI
Given below is the HelloForm.java servlet program to handle input given by web browser.
We are going to use getParameter() method which makes it very easy to access passed
information
Assuming your environment is set up properly, compile HelloForm.java as follows −
$ javacHelloForm.java
If everything goes fine, above compilation would produce HelloForm.class file. Next
you would have to copy this class file in <Tomcat-
installationdirectory>/webapps/ROOT/WEB-INF/classes and create following entries
in web.xml file located in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/
<servlet>
<servlet-name>HelloForm</servlet-name>
<servlet-class>HelloForm</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>HelloForm</servlet-name>
<url-pattern>/HelloForm</url-pattern>
</servlet-mapping>
Now type http://localhost:8080/HelloForm?first_name=ZARA&last_name
=ALI in your browser's Location:box and make sure you already started tomcat server, before
firing above command in the browser. This would generate following result
Using GET Method to Read Form Data
 First Name: ZARA
 Last Name: ALI

GET Method Example Using Form


Here is a simple example which passes two values using HTML FORM and submit button.
We are going to use same Servlet HelloForm to handle this input.
<html>
<body>
<formaction="HelloForm"method="GET">
First Name: <inputtype="text"name="first_name">
<br/>
Last Name: <inputtype="text"name="last_name"/>
<inputtype="submit"value="Submit"/>
</form>
</body>
</html>

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 134


ADVANCED JAVA PROGRAMMING I-MSC(CS)

Keep this HTML in a file Hello.htm and put it in <Tomcat-


installationdirectory>/webapps/ROOT directory. When you would
access http://localhost:8080/Hello.htm, here is the actual output of the above form.

First Name: Last Name:

Try to enter First Name and Last Name and then click submit button
to see the result on your local machine where tomcat is running. Based on the input provided,
it will generate similar result as mentioned in the above example.
POST Method Example Using Form
Let us do little modification in the above servlet, so that it can handle GET as well as POST
methods. Below is HelloForm.java servlet program to handle input given by web browser
using GET or POST methods.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


publicclassHelloFormextendsHttpServlet{

// Method to handle GET method request.


publicvoid doGet(HttpServletRequest request,HttpServletResponse response)
throwsServletException,IOException{

// Set response content type


response.setContentType("text/html");

PrintWriterout=response.getWriter();
String title ="Using GET Method to Read Form Data";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 "+
"transitional//en\">\n";

out.println(docType +
"<html>\n"+
"<head><title>"+ title +"</title></head>\n"+
"<body bgcolor = \"#f0f0f0\">\n"+
"<h1 align = \"center\">"+ title +"</h1>\n"+
"<ul>\n"+
" <li><b>First Name</b>: "
+request.getParameter("first_name")+"\n"+
" <li><b>Last Name</b>: "
+request.getParameter("last_name")+"\n"+
"</ul>\n"+
"</body>"
"</html>"
);
}

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 135


ADVANCED JAVA PROGRAMMING I-MSC(CS)

// Method to handle POST method request.


publicvoid doPost(HttpServletRequest request,HttpServletResponse response)
throwsServletException,IOException{

doGet(request, response);
}
}
Now compile and deploy the above Servlet and test it using Hello.htm with the POST method
as follows −
<html>
<body>
<formaction="HelloForm"method="POST">
First Name: <inputtype="text"name="first_name">
<br/>
Last Name: <inputtype="text"name="last_name"/>
<inputtype="submit"value="Submit"/>
</form>
</body>
</html>
Here is the actual output of the above form, Try to enter First and Last Name and then click
submit button to see the result on your local machine where tomcat is running.

First Name: Last Name:

Based on the input provided, it would generate similar result as mentioned in the above
examples.

Reading http request header


Servlets - Client HTTP Request
When a browser requests for a web page, it sends lot of information to the web server
which cannot be read directly because this information travel as a part of header of HTTP
request. You can check HTTP Protocol for more information on this.
Following is the important header information which comes from browser side and
you would use very frequently in web programming −

Sr.No. Header & Description

Accept
This header specifies the MIME types that the browser or other clients can
1
handle. Values of image/png or image/jpeg are the two most common
possibilities.

Accept-Charset
2 This header specifies the character sets the browser can use to display the
information. For example ISO-8859-1.

3 Accept-Encoding

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 136


ADVANCED JAVA PROGRAMMING I-MSC(CS)

This header specifies the types of encodings that the browser knows how to
handle. Values of gzip or compress are the two most common possibilities.

Accept-Language
4 This header specifies the client's preferred languages in case the servlet can
produce results in more than one language. For example en, en-us, ru, etc

Authorization
5 This header is used by clients to identify themselves when accessing
password-protected Web pages.

Connection
This header indicates whether the client can handle persistent HTTP
6 connections. Persistent connections permit the client or other browser to
retrieve multiple files with a single request. A value of Keep-Alive means
that persistent connections should be used.

Content-Length
7 This header is applicable only to POST requests and gives the size of the
POST data in bytes.

Cookie
8 This header returns cookies to servers that previously sent them to the
browser.

Host
9
This header specifies the host and port as given in the original URL.

Methods to read HTTP Header


There are following methods which can be used to read HTTP header in your servlet
program. These methods are available with HttpServletRequest object
Sr.No. Method & Description

Cookie[] getCookies()
1 Returns an array containing all of the Cookie objects the client sent with this
request.

Enumeration getAttributeNames()
2 Returns an Enumeration containing the names of the attributes available to
this request.

Enumeration getHeaderNames()
3
Returns an enumeration of all the header names this request contains.

Enumeration getParameterNames()
4 Returns an Enumeration of String objects containing the names of the
parameters contained in this request

HttpSession getSession()
5
Returns the current session associated with this request, or if the request does

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 137


ADVANCED JAVA PROGRAMMING I-MSC(CS)

not have a session, creates one.

HttpSession getSession(boolean create)


6 Returns the current HttpSession associated with this request or, if if there is
no current session and value of create is true, returns a new session.
HTTP Header Request Example
Following is the example which uses getHeaderNames() method of
HttpServletRequest to read the HTTP header information. This method returns an
Enumeration that contains the header information associated with the current HTTP request.
Once we have an Enumeration, we can loop down the Enumeration in the standard manner,
using hasMoreElements() method to determine when to stop and using nextElement() method
to get each parameter name
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

// Extend HttpServlet class


publicclassDisplayHeaderextendsHttpServlet{

// Method to handle GET method request.


publicvoid doGet(HttpServletRequest request,HttpServletResponse response)
throwsServletException,IOException{

// Set response content type


response.setContentType("text/html");

PrintWriterout=response.getWriter();
String title ="HTTP Header Request Example";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 "+"transitional//en\">\n";

out.println(docType +
"<html>\n"+
"<head><title>"+ title +"</title></head>\n"+
"<body bgcolor = \"#f0f0f0\">\n"+
"<h1 align = \"center\">"+ title +"</h1>\n"+
"<table width = \"100%\" border = \"1\" align = \"center\">\n"+
"<tr bgcolor = \"#949494\">\n"+
"<th>Header Name</th><th>Header Value(s)</th>\n"+
"</tr>\n"
);

Enumeration headerNames =request.getHeaderNames();

while(headerNames.hasMoreElements()){
String paramName =(String)headerNames.nextElement();
out.print("<tr><td>"+ paramName +"</td>\n");

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 138


ADVANCED JAVA PROGRAMMING I-MSC(CS)

String paramValue =request.getHeader(paramName);


out.println("<td> "+ paramValue +"</td></tr>\n");
}
out.println("</table>\n</body></html>");
}

// Method to handle POST method request.


publicvoid doPost(HttpServletRequest request,HttpServletResponse response)
throwsServletException,IOException{

doGet(request, response);
}
}
Now calling the above servlet would generate the following result −
HTTP Header Request Example

Header Name Header Value(s)

accept */*

accept-language en-us

Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1;


user-agent
Trident/4.0; InfoPath.2; MS-RTC LM 8)

accept-encoding gzip, deflate

host localhost:8080

connection Keep-Alive

cache-control no-cache

Sending data to a client and writing the http response header:


Servlets - Server HTTP Response
when a Web server responds to an HTTP request, the response typically consists of a status
line, some response headers, a blank line, and the document. A typical response looks like
this −
HTTP/1.1 200 OK
Content-Type: text/html
Header2: ...
...
HeaderN: ...
(Blank Line)
<!doctype ...>
<html>
<head>...</head>
<body>

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 139


ADVANCED JAVA PROGRAMMING I-MSC(CS)

...
</body>
</html>
The status line consists of the HTTP version (HTTP/1.1 in the example), a status code (200 in
the example), and a very short message corresponding to the status code (OK in the
example).
Following is a summary of the most useful HTTP 1.1 response headers which go back to the
browser from web server side and you would use them very frequently in web programming

Sr.No. Header & Description

Allow
1 This header specifies the request methods (GET, POST, etc.) that the server
supports.

Cache-Control
This header specifies the circumstances in which the response document can
safely be cached. It can have values public, private or no-cache etc. Public
2
means document is cacheable, Private means document is for a single user
and can only be stored in private (non-shared) caches and nocache means
document should never be cached.

Connection
This header instructs the browser whether to use persistent in HTTP
3
connections or not. A value of close instructs the browser not to use persistent
HTTP connections and keepalive means using persistent connections.

Content-Disposition
4 This header lets you request that the browser ask the user to save the response
to disk in a file of the given name.

Content-Encoding
5 This header specifies the way in which the page was encoded during
transmission.

Content-Language
6 This header signifies the language in which the document is written. For
example en, en-us, ru, etc

Content-Length
This header indicates the number of bytes in the response. This information is
7
needed only if the browser is using a persistent (keep-alive) HTTP
connection.

Content-Type
8 This header gives the MIME (Multipurpose Internet Mail Extension) type of
the response document.

Expires
9
This header specifies the time at which the content should be considered out-

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 140


ADVANCED JAVA PROGRAMMING I-MSC(CS)

of-date and thus no longer be cached.

Last-Modified
This header indicates when the document was last changed. The client can
10
then cache the document and supply a date by an If-Modified-Since request
header in later requests.

Location
This header should be included with all responses that have a status code in
11
the 300s. This notifies the browser of the document address. The browser
automatically reconnects to this location and retrieves the new document.

Refresh
This header specifies how soon the browser should ask for an updated page.
12
You can specify time in number of seconds after which a page would be
refreshed.

Retry-After
13 This header can be used in conjunction with a 503 (Service Unavailable)
response to tell the client how soon it can repeat its request.

Set-Cookie
14 This header specifies a cookie associated with the page.

Methods to Set HTTP Response Header


There are following methods which can be used to set HTTP response header in your
servlet program. These methods are available with HttpServletResponse object.
Sr.No. Method & Description

String encodeRedirectURL(String url)


1 Encodes the specified URL for use in the sendRedirect method or, if encoding
is not needed, returns the URL unchanged.

String encodeURL(String url)


2 Encodes the specified URL by including the session ID in it, or, if encoding is
not needed, returns the URL unchanged.

boolean containsHeader(String name)


3 Returns a Boolean indicating whether the named response header has already
been set.

boolean isCommitted()
4
Returns a Boolean indicating if the response has been committed.

void addCookie(Cookie cookie)


5
Adds the specified cookie to the response.

void addDateHeader(String name, long date)


6
Adds a response header with the given name and date-value.

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 141


ADVANCED JAVA PROGRAMMING I-MSC(CS)

void addHeader(String name, String value)


7
Adds a response header with the given name and value.

void addIntHeader(String name, int value)


8
Adds a response header with the given name and integer value.

void flushBuffer()
9
Forces any content in the buffer to be written to the client.

void reset()
10
Clears any data that exists in the buffer as well as the status code and headers.

void resetBuffer()
11 Clears the content of the underlying buffer in the response without clearing
headers or status code.

void sendError(int sc)


12 Sends an error response to the client using the specified status code and
clearing the buffer.

void sendError(int sc, String msg)


13
Sends an error response to the client using the specified status.

void sendRedirect(String location)


14 Sends a temporary redirect response to the client using the specified redirect
location URL.

void setBufferSize(int size)


15
Sets the preferred buffer size for the body of the response.
HTTP Header Response Example
We already have seen setContentType() method working in previous examples and
following example would also use same method, additionally we would
use setIntHeader() method to set Refresh header.
Now calling the above servlet would display current system time after every 5 seconds as
follows. Just run the servlet and wait to see the result –

Auto Refresh Header Setting


Current Time is: 9:44:50 PM

Working with cookies


Cookies in Servlet
A cookie is a small piece of information that is persisted between the multiple client
requests.
A cookie has a name, a single value, and optional attributes such as a comment, path
and domain qualifiers, a maximum age, and a version number.
How Cookie works
By default, each request is considered as a new request. In cookies technique, we add
cookie with response from the servlet. So cookie is stored in the cache of the browser. After

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 142


ADVANCED JAVA PROGRAMMING I-MSC(CS)

that if request is sent by the user, cookie is added with request by default. Thus, we recognize
the user as the old user.

Types of Cookie
There are 2 types of cookies in servlets.
1. Non-persistent cookie
2. Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.
Persistent cookie
It is valid for multiple session . It is not removed each time when user closes the browser. It
is removed only if user logout or signout.

Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.

Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.

Cookie class
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot
of useful methods for cookies.

Constructor of Cookie class

Constructor Description

Cookie() constructs a cookie.

Cookie(String name, String value) constructs a cookie with a specified name and value.

Useful Methods of Cookie class


There are given some commonly used methods of the Cookie class.
Method Description

public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds.

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 143


ADVANCED JAVA PROGRAMMING I-MSC(CS)

public String getName() Returns the name of the cookie. The name cannot be
changed after creation.

public String getValue() Returns the value of the cookie.

public void setName(String name) changes the name of the cookie.

public void setValue(String value) changes the value of the cookie.


Other methods required for using Cookies

For adding cookie or getting the value from the cookie, we need some methods provided by other
interfaces. They are:
1. public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add
cookie in response object.
2. public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the
cookies from the browser.

create Cookies
Let's see the simple code to create cookie.
1. Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object
2. response.addCookie(ck);//adding cookie in the response

Delete Cookies
Let's see the simple code to delete cookie. It is mainly used to logout or signout the user.
1. Cookie ck=new Cookie("user","");//deleting value of cookie
2. ck.setMaxAge(0);//changing the maximum age to 0 seconds
3. response.addCookie(ck);//adding cookie in the response

Getting Cookies
Let's see the simple code to get all the cookies.
1. Cookie ck[]=request.getCookies();
2. for(int i=0;i<ck.length;i++){
3. out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of cookie

4. }

Simple example of Servlet Cookies


In this example, we are storing the name of the user in the cookie object and accessing
it in another servlet. As we know well that session corresponds to the particular user. So if
you access it from too many browsers with different values, you will get the different value.

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 144


ADVANCED JAVA PROGRAMMING I-MSC(CS)

Java Server Pages


JSP - Overview
JavaServer Pages (JSP) is a technology for developing Webpages that supports
dynamic content. This helps developers insert java code in HTML pages by making use of
special JSP tags, most of which start with <% and end with %>.
A JavaServer Pages component is a type of Java servlet that is designed to fulfill the
role of a user interface for a Java web application. Web developers write JSPs as text files
that combine HTML or XHTML code, XML elements, and embedded JSP actions and
commands.
Using JSP, you can collect input from users through Webpage forms, present records
from a database or another source, and create Webpages dynamically.
JSP tags can be used for a variety of purposes, such as retrieving information from a
database or registering user preferences, accessing JavaBeans components, passing control
between pages, and sharing information between requests, pages etc.

Why Use JSP?


JavaServer Pages often serve the same purpose as programs implemented using
the Common Gateway Interface (CGI). But JSP offers several advantages in comparison
with the CGI.
 Performance is significantly better because JSP allows embedding Dynamic Elements
in HTML Pages itself instead of having separate CGI files.
 JSP are always compiled before they are processed by the server unlike CGI/Perl
which requires the server to load an interpreter and the target script each time the page
is requested.
 JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also
has access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB,
JAXP, etc.
 JSP pages can be used in combination with servlets that handle the business logic, the
model supported by Java servlet template engines.
Finally, JSP is an integral part of Java EE, a complete platform for enterprise class
applications. This means that JSP can play a part in the simplest applications to the most
complex and demanding.

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 145


ADVANCED JAVA PROGRAMMING I-MSC(CS)

Advantages of JSP

Following table lists out the other advantages of using JSP over other technologies −
vs. Active Server Pages (ASP)
The advantages of JSP are twofold. First, the dynamic part is written in Java, not
Visual Basic or other MS specific language, so it is more powerful and easier to use. Second,
it is portable to other operating systems and non-Microsoft Web servers.
vs. Pure Servlets
It is more convenient to write (and to modify!) regular HTML than to have plenty of
println statements that generate the HTML.
vs. Server-Side Includes (SSI)
SSI is really only intended for simple inclusions, not for "real" programs that use form
data, make database connections, and the like.
vs. JavaScript
JavaScript can generate HTML dynamically on the client but can hardly interact with
the web server to perform complex tasks like database access and image processing etc.
vs. Static HTML
Regular HTML, of course, cannot contain dynamic information.
JSP - Environment Setup
A development environment is where you would develop your JSP programs, test
them and finally run them.

Setting up Java Development Kit


This step involves downloading an implementation of the Java Software Development
Kit (SDK) and setting up the PATH environment variable appropriately.
You can download SDK from Oracle's Java site − Java SE Downloads.
Once you download your Java implementation, follow the given instructions to install
and configure the setup. Finally set the PATH and JAVA_HOME environment variables to
refer to the directory that contains java and javac,
typically java_install_dir/bin and java_install_dir respectively.
If you are running Windows and install the SDK in C:\jdk1.5.0_20, you need to add
the following line in your C:\autoexec.bat file.

set PATH = C:\jdk1.5.0_20\bin;%PATH%


set JAVA_HOME = C:\jdk1.5.0_20

Alternatively, on Windows NT/2000/XP, you can also right-click on My Computer,


select Properties, then Advanced, followed by Environment Variables. Then, you would
update the PATH value and press the OK button.
On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and
you use the C shell, you will put the following into your .cshrc file.

setenv PATH /usr/local/jdk1.5.0_20/bin:$PATH


setenv JAVA_HOME /usr/local/jdk1.5.0_20

Alternatively,ifyouuse an Integrated Development Environment


(IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run
a simple program to confirm that the IDE knows where you installed Java.

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 146


ADVANCED JAVA PROGRAMMING I-MSC(CS)

Setting up Web Server: Tomcat


A number of Web Servers that support JavaServer Pages and Servlets development
are available in the market. Some web servers can be downloaded for free and Tomcat is one
of them.
Apache Tomcat is an open source software implementation of the JavaServer Pages and
Servlet technologies and can act as a standalone server for testing JSP and Servlets, and can
be integrated with the Apache Web Server. Here are the steps to set up Tomcat on your
machine −
 Download the latest version of Tomcat from https://tomcat.apache.org/.
 Once you downloaded the installation, unpack the binary distribution into a
convenient location. For example, in C:\apache-tomcat-5.5.29 on windows, or
/usr/local/apache-tomcat-5.5.29 onLinux/Unixand
 create CATALINA_HOME environment variable pointing to these locations.

Tomcat can be started by executing the following commands on the Windows machine –

%CATALINA_HOME%\bin\startup.bat

or

C:\apache-tomcat-5.5.29\bin\startup.bat

Tomcat can be started by executing the following commands on the Unix (Solaris, Linux,
etc.) machine –

$CATALINA_HOME/bin/startup.sh

or

/usr/local/apache-tomcat-5.5.29/bin/startup.sh

After a successful startup, the default web-applications included with Tomcat will be
available by visiting http://localhost:8080/.

Upon execution, you will receive the following output −

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 147


ADVANCED JAVA PROGRAMMING I-MSC(CS)

Further information about configuring and running Tomcat can be found in the
documentation included here, as well as on the Tomcat web site − https://tomcat.apache.org/.

Tomcat can be stopped by executing the following commands on the Windows machine –

%CATALINA_HOME%\bin\shutdown
or

C:\apache-tomcat-5.5.29\bin\shutdown

Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.)
machine –

$CATALINA_HOME/bin/shutdown.sh

or

/usr/local/apache-tomcat-5.5.29/bin/shutdown.sh

Setting up CLASSPATH
Since servlets are not part of the Java Platform, Standard Edition, you must identify
the servlet classes to the compiler.
If you are running Windows, you need to put the following lines in
your C:\autoexec.bat file.

set CATALINA = C:\apache-tomcat-5.5.29


set CLASSPATH = %CATALINA%\common\lib\jsp-api.jar;%CLASSPATH%

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 148


ADVANCED JAVA PROGRAMMING I-MSC(CS)

Alternatively, on Windows NT/2000/XP, you can also right-click on My Computer,


select Properties, then Advanced, then Environment Variables. Then, you would update
the CLASSPATH value and press the OK button.
On Unix (Solaris, Linux, etc.), if you are using the C shell, you would put the following lines
into your .cshrc file.
setenv CATALINA = /usr/local/apache-tomcat-5.5.29
setenv CLASSPATH $CATALINA/common/lib/jsp-api.jar:$CLASSPATH

JSP Scriptlet tag (Scripting elements)


1. Scripting elements
2. JSP scriptlet tag
3. Simple Example of JSP scriptlet tag
4. Example of JSP scriptlet tag that prints the user name

In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's see what are
the scripting elements first.
JSP Scripting elements
The scripting elements provides the ability to insert java code inside the jsp. There are three
types of scripting elements:
o scriptlet tag
o expression tag
o declaration tag
JSP scriptlet tag

A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:

1. <% java source code %>


Example of JSP scriptlet tag
In this example, we are displaying a welcome message.
1. <html>
2. <body>
3. <% out.print("welcome to jsp"); %>
4. </body>
5. </html>
Example of JSP scriptlet tag that prints the user name
In this example, we have created two files index.html and welcome.jsp. The index.html file
gets the username from the user and the welcome.jsp file prints the username with the
welcome message.

File: index.html
1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 149


ADVANCED JAVA PROGRAMMING I-MSC(CS)

File: welcome.jsp
1. <html>
2. <body>
3. <%
4. String name=request.getParameter("uname");
5. out.print("welcome "+name);
6. %>
7. </form>
8. </body>
9. </html>

JSP expression tag:


The code placed within JSP expression tag is written to the output stream of the response.
So you need not write out.print() to write data. It is mainly used to print the values of variable
or method.

Syntax of JSP expression tag


1. <%= statement %>

Example of JSP expression tag


In this example of jsp expression tag, we are simply displaying a welcome message.
1. <html>
2. <body>
3. <%= "welcome to jsp" %>
4. </body>
5. </html>

Example of JSP expression tag that prints current time


To display the current time, we have used the getTime() method of Calendar class.
The getTime() is an instance method of Calendar class, so we have called it after getting the
instance of Calendar class by the getInstance() method.
index.jsp
1. <html>
2. <body>
3. Current Time: <%= java.util.Calendar.getInstance().getTime() %>
4. </body>
5. </html>

Scriptlets
JavaServer Pages often present dynamically generated content as part of an XHTML
document sent to the client in response to a request. In some cases, the content is static, but is
output only if certain conditions are met during a request (such as providing values in a form
that submits a request). JSP programmers can insert Java code and logic in a JSP using
scripting.

Scripting Components
JSP scripting components include scriptlets, comments, expressions, declarations and
escape sequences. This section describes each of these scripting components. Many of these
scripting components are demonstrated in Fig. 10.4 .

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 150


ADVANCED JAVA PROGRAMMING I-MSC(CS)

Scriptlets are blocks of code delimited by <% and %>. They contain Java statements
that the container places in method _jspService at translation time.
JSPs support three comment styles: JSP comments, XHTML comments and
comments from the scripting language. JSP comments are delimited by <%-- and --%>. Such
comments can be placed throughout a JSP, but not inside scriptlets. XHTML comments are
delimited with <!-- and -->. These comments can be placed throughout a JSP, but not inside
scriptlets.
Scripting language comments are currently Java comments, because Java is the only
JSP scripting language at the present time. Scriptlets can use Java’s single-line comments
(delimited by/ and /) and multiline comments (delimited by /* and */).JSP comments and
scripting-language comments are ignored and do not appear in the response to a client.
When clients view the source code of a JSP response, they will see only the XHTML
comments in the source code. The different comment styles are useful for separating
comments that the user should be able to see from comments that document logic
processed on the server.
A JSP expression, delimited by <%= and %>, contains a Java expression that is
evaluated when a client requests the JSP containing the expression. The container converts
the result of a JSP expression to a String object, then outputs the String as part of the
response to the client.
Declarations (delimited by <%! and %>) enable a JSP programmer to define variables
and methods. Variables become instance variables of the servlet class that represents the
translated JSP. Similarly, methods become members of the class that represents the translated
JSP. Declarations of variables and methods in a JSP use Java syntax. Thus, a variable
declaration must end in a semicolon, as in

<%! int counter = 0; %>

Special characters or character sequences that the JSP container normally uses to
delimit JSP code can be included in a JSP as literal characters in scripting elements, fixed
template data and attribute values using escape sequences. Figure 10.3 shows the literal
character or characters and the corresponding escape sequences and discusses where to use
the escape sequences.

Scripting Example
The JSP of Fig. 10.4 demonstrates basic scripting capabilities by responding to get
requests. The JSP enables the user to input a first name, then outputs that name as part of the
response. Using scripting, the JSP determines whether a firstName parameter was passed to
the JSP as part of the request; if not, the JSP returns an XHTML document containing a form
through which the user can input a first name. Otherwise, the JSP obtains the firstName value
and uses it as part of an XHTML document that welcomes the user to JavaServer Pages.

Literal Escape sequence Description


<% <\% The character sequence <% normally indicates the beginning
of a scriptlet. The <\% escape sequence places the literal
characters <% in the response to the client.
%> %\> The character sequence %> normally indicates the end of a
scriptlet. The %\> escape sequence places the literal characters
%> in the response to the client.

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 151


ADVANCED JAVA PROGRAMMING I-MSC(CS)

Directives
Directives are messages to the JSP container that enable the programmer to specify
page settings (such as the error page), to include content from other resources and to specify
custom- tag libraries for use in a JSP. Directives (delimited by <%@ and %>) are processed
at translation time.
Thus, directives do not produce any immediate output, because they are processed
before the JSP accepts any requests. Figure 10.26 summarizes the three directive types. These
directives are discussed in the next several subsections.

Page Directive
The page directive specifies global settings for the JSP in the JSP container. There can
be many page directives, provided that there is only one occurrence of each attribute. The
only exception to this rule is the import attribute, which can be used repeatedly to import Java
packages used in the JSP. Figure 10.27 summarizes the attributes of the page directive.
Directive Description
page Defines page settings for the JSP container to process.
include Causes the JSP container to perform a translation-time insertion of
another resource’s content. As the JSP is translated into a servlet and
compiled, the referenced file replaces the include directive and is
translated as if it were originally part of the JSP.
taglib Allows programmers to include their own new tags in the form of tag
libraries. These libraries can be used to encapsulate functionality and
simplify the coding of a JSP.

include Directive
The include directive includes the content of another resource once, at JSP translation
time. The include directive has only one attribute—file—that specifies the URL of the page
to include. The difference between directive include and action <jsp:include> is noticeable
only if the included content changes.
For example, if the definition of an XHTML document changes after it is included
with directive include, future invocations of the JSP will show the original content of the
XHTML document, not the new content. In contrast, action <jsp:include> is processed in
each request to the JSP.
Therefore, changes to included content would be apparent in the next request to the
JSP that uses action <jsp:include>. JavaServer Page includeDirective.jsp (Fig. 10.28)
reimplements JavaServer Page include.jsp (Fig. 10.10) using include directives. To test
includeDirective. jsp in Tomcat, copy includeDirective.jsp into the jsp directory created in
Section 10.3. Open your Web browser and enter the following URL to test include-
Directive.jsp:
http://localhost:8080/advjhtp1/jsp/includeDirective.jsp

JSP Declaration Tag


1. JSP declaration tag
2. Difference between JSP scriptlet tag and JSP declaration tag
3. Example of JSP declaration tag that declares field
4. Example of JSP declaration tag that declares method

The JSP declaration tag is used to declare fields and methods.

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 152


ADVANCED JAVA PROGRAMMING I-MSC(CS)

The code written inside the jsp declaration tag is placed outside the service() method of auto
generated servlet.
So it doesn't get memory at each request.
Syntax of JSP declaration tag

The syntax of the declaration tag is as follows:


1. <%! field or method declaration %>
Difference between JSP Scriptlet tag and Declaration tag

Jsp Scriptlet Tag Jsp Declaration Tag

The jsp scriptlet tag can only declare variables The jsp declaration tag can declare variables as
not methods. well as methods.

The declaration of scriptlet tag is placed inside The declaration of jsp declaration tag is placed
the _jspService() method. outside the _jspService() method.

Example of JSP declaration tag that declares field


In this example of JSP declaration tag, we are declaring the field and printing the value of the
declared field using the jsp expression tag.

index.jsp
1. <html>
2. <body>
3. <%! int data=50; %>
4. <%= "Value of the variable is:"+data %>
5. </body>
6. </html>

Example of JSP declaration tag that declares method


In this example of JSP declaration tag, we are defining the method which returns the cube of
given number and calling this method from the jsp expression tag. But we can also use jsp
scriptlet tag to call the declared method.

index.jsp
1. <html>
2. <body>
3. <%!
4. int cube(int n){
5. return n*n*n*;
6. }
7. %>
8. <%= "Cube of 3 is:"+cube(3) %>
9. </body>
</html>

TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 153


ADVANCED JAVA PROGRAMMING I-MSC-CS

UNIT V
ADVANCED TECHNIQUES

JAR file format creation


Jar Files creation

 In Java, JAR stands for Java ARchive, whose format is based on the zip format.
 The JAR files format is mainly used to aggregate a collection of files into a single one.
 It is a single cross-platform archive format that handles images, audio, and class files.
 With the existing applet code, it is backward-compatible. In Java, Jar files are
completely written in the Java programming language.
We can either download the JAR files from the browser or can write our own JAR files
using Eclipse IDE.
The steps to bundle the source code, i.e., .java files, into a JAR are given below.
In the first step, we will open Eclipse IDE and select the Export option from the File When we
select the Export option, the Jar File wizard opens with the following screen:

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 154


ADVANCED JAVA PROGRAMMING I-MSC-CS

From the open wizard, we select the Java JAR file and click on the Next. The Next button opens
JAR Export for JAR File Specification.

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 155


ADVANCED JAVA PROGRAMMING I-MSC-CS

1. Now, from the JAR File Specification page, we select the resources needed for exporting in
the Select the resources to export.

After that, we enter the JAR file name and folder. By default, the Export
generated class files and resources checkbox is checked. We also check the Export

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 156


ADVANCED JAVA PROGRAMMING I-MSC-CS
Java source files and resources checkbox to export the source code.

If there are other Java files or resources which we want to include and which are
available in the open project, browse to their location and ensure the file or resource is
checked in the window on the right.

2. On the same page, there are three more checkboxes, i.e., Compress the content of the JAR
file, Add directory entries, and Overwrite existing files without warning. By default,
the Compress content of the JAR file checkbox is checked.

3. Now, we have two options for proceeding next, i.e., Finish and Next. If we click on the Next,
it willimmediately create a JAR file to that location which we defined in the Select the export
destination.

4. If we click on the Next button, it will open the Jar Packaging Option wizard for creating a
JAR description, setting the advance option, or changing the default manifest.

5. For now, we skip the Next and click on the Finish button.

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 157


ADVANCED JAVA PROGRAMMING I-MSC-CS
5.

6. Now, we go to the specified location, which we defined in the Select the export destination,
to ensure that the JAR file is created successfully or not.

7.

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 158


ADVANCED JAVA PROGRAMMING I-MSC-CS

Java Interntionalization – Overview

Internationalization
Internalization or I18N refers to the capability of an Application to be able to serve users in
multiple and different languages. Java has in-built support for Internationalization. Java also provides
formatting of numbers, currencies and adjustment of date and time accordingly.
Java Internationalization helps to make a java application handle different languages, number
formats, currencies, region specific time formatting.

Localization
Localization or L10N is the adaptability of an application that is how an application adapts
itself with a specific language, number formats, date and time settings etc.
A java application should be internationalized in order to be able to localize itself.
Culturally Dependent Information

Following information items often varies with different time zones or cultures.
 Messages
 Date
 Time
 Number
 Currency
 Measurements
 Phone Numbers
 Postal Addresses
 GUI labels

Internationalization Classes
Java has a set of built-in classes which help in internationalization of an application. These
classes are following:

Sr.No. Class & Description

Locale
1
Represents a language along with country/region.

ResourceBundle
2
Contains localized text or objects.

NumberFormat
3
Use to format numbers/currencies as per the locale.

DecimalFormat
4
Use to format numbers as per customized format and as per locale.

DateFormat
5
Use to format dates as per locale.

SimpleDateFormat
6
Use to format dates as per customized format and as per locale.

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 159


ADVANCED JAVA PROGRAMMING I-MSC-CS

Java Swing
o Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create
window-based applications.

o It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in
java.
 Unlike AWT, Java Swing provides platform-independent and lightweight components.
 The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Difference between AWT and Swing

There are many differences between java awt and swing that are given below.

No. Java AWT Java Swing

1) AWT components are platform-dependent. Java swing components are platform-


independent.

2) AWT components are heavyweight. Swing components are lightweight.

3) AWT doesn't support pluggable look and feel. Swing supports pluggable look and
feel.

4) AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser, tabbedpane
etc.

5) AWT doesn't follows MVC(Model View Controller) Swing follows MVC.


where model represents data, view represents
presentation and controller acts as an interface between
model and view.

Hierarchy of Java Swing classes

The hierarchy of java swing API is given below.

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 160


ADVANCED JAVA PROGRAMMING I-MSC-CS

Commonly used Methods of Component class

The methods of Component class are widely used in java swing that are given below.

Method Description

public void add(Component c) add a component on another component.

public void setSize(int width,int height) sets size of the component.

public void setLayout(LayoutManager m) sets the layout manager for the component.

public void setVisible(boolean b) sets the visibility of the component. It is by default false.

Java Swing Examples

There are two ways to create a frame:


o By creating the object of Frame class (association)
o By extending Frame class (inheritance)
We can write the code of swing inside the main(), constructor or any other method.

Simple Java Swing Example

Let's see a simple swing example where we are creating one button and adding it on the
JFrame object inside the main() method.

File: FirstSwingExample.java
1. import javax.swing.*;
2. public class FirstSwingExample

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 161


ADVANCED JAVA PROGRAMMING I-MSC-CS
3. {
4. public static void main(String[] args) {
5. JFrame f=new JFrame();//creating instance of JFrame
6.
7. JButton b=new JButton("click");//creating instance of JButton
8. b.setBounds(130,100,100, 40);//x axis, y axis, width, height
9.
10. f.add(b);//adding button in JFrame
11.
12. f.setSize(400,500);//400 width and 500 height
13. f.setLayout(null);//using no layout managers
14. f.setVisible(true);//making the frame visible
15. }
16. }

Components and Containers:

A Swing GUI consists of two key items: components and containers.

A component is an independent visual control, such as a push button or slider. A


container holds a group of components. Thus, a container is a special type of component that
is designed to hold other components.
Furthermore, in order for a component to be displayed, it must be held within a
container. Thus, all Swing GUIs will have at least one container. Because containers are
components, a container can also hold other containers.

Components:
In general, Swing components are derived from the JComponent class. JComponent provides
the functionality that is common to all components. The following figure shows hierarchy of classes
of javax.swing

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 162


ADVANCED JAVA PROGRAMMING I-MSC-CS
.

Containers:

Swing defines two types of containers.


1. Top-level containers/ Root containers: JFrame, JApplet,JWindow, and JDialog.
Whenever we create a top level container four sub-level containers are
automatically created:
 Glass pane (JGlass)
 Root pane (JRootPane)
 Layered pane (JLayeredPane)
 Content pane

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 163


ADVANCED JAVA PROGRAMMING I-MSC-CS

Glass pane: This is the first pane and is very close to the monitor’s screen. Any
components to be displayed in the foreground are attached to this glass pane.
Root Pane: This pane is below the glass pane. Any components to be displayed in the
background are displayed in this frame.
Layered pane: This pane is below the root pane. When we want to take several
components as a group, we attach them in the layered pane.
Conent pane: This is bottom most of all, Individual components are attached to this
pane. To reach this pane, we can call getContentPane() method of JFrame class
which returns Container class object.

2. Lightweight containers – containers do inherit JComponent. An example of a


lightweight container is JPanel, which is a general-purpose container. Lightweight
containers are often used to organize and manage groups of related components.

JFrame:

Frame represents a window with a title bar and borders. Frame becomes the basis for
creating the GUIs for an application because all the components go into the frame.
To create a frame, we have to create an object to JFrame class in swing as
JFrame jf=new JFrame(); // create a frame without title
JFrame jf=new JFrame(“title”); // create a frame with title
To close the frame, use setDefaultCloseOperation() method of JFrame class
setDefaultCloseOperation(constant)
where constant values are

This closes the application upon clicking the


JFrame.EXIT_ON_CLOSE
close button
This closes the application upon clicking the
JFrame.DISPOSE_ON_CLOSE
close button
This will not perform any operation upon
JFrame.DO_NOTHING_ON_CLOSE
clicking close button
This hides the frame upon clicking close
JFrame.HIDE_ON_CLOSE
button

Example:
import javax.swing.*;
class FrameDemo
{
public static void main(String arg[])
{
JFrame jf=new JFrame("PVPSIT");
jf.setSize(200,200);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE );

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 164


ADVANCED JAVA PROGRAMMING I-MSC-CS
}
}
Example: To set the background
import javax.swing.*;
import java.awt.*;

class FrameDemo
{
public static void main(String arg[])
{
JFrame jf=new JFrame("PVPSIT");
jf.setSize(200,200);
jf.setVisible(true);
Container c=jf.getContentPane();
c.setBackground(Color.green);
}
}

JApplet:

Fundamental to Swing is the JApplet class, which extends Applet. Applets that use
Swing must be subclasses of JApplet. JApplet is rich with functionality that is not found in
Applet. For example, JApplet supports various “panes,” such as the content pane, the glass
pane, and the root pane.
One difference between Applet and JApplet is, When adding a component to an
instance of JApplet, do not invoke the add( ) method of the applet. Instead, call add( ) for
the content pane of the JApplet object.

The content pane can be obtained via the method shown here:
Container getContentPane( )
The add( ) method of Container can be used to add a component to a content pane.
Its form is shown here:
void add(comp)

Here, comp is the component to be added to the content pane.

JComponent:
The class JComponent is the base class for all Swing components except top-level
containers. To use a component that inherits from JComponent, you must place the
component in a containment hierarchy whose root is a top-level SWING container.

Constructor: JComponent();

The following are the JComponent class's methods to manipulate the appearance of
the component.

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 165


ADVANCED JAVA PROGRAMMING I-MSC-CS

Returns the current width of this component


public int getWidth ()
in pixel.
Returns the current height of this component
public int getHeight ()
in pixel.
Returns the current x coordinate of the
public int getX()
component's top-left corner.
Returns the current y coordinate of the
public int getY ()
component's top-left corner.
Returns this component's Graphics object
public java.awt.Graphics getGraphics() you can draw on. This is useful if you want
to change the appearance of a component.
public void setBackground (java.awt.Color bg) Sets this component's background color.
Sets whether or not this component is
public void setEnabled (boolean enabled)
enabled.
Set the font used to print text on this
public void setFont (java.awt.Font font)
component.
public void setForeground (java.awt.Color fg) Set this component's foreground color.
public void setToolTipText(java.lang.String text) Sets the tool tip text.
Sets whether or not this component is
public void setVisible (boolean visible)
visible.

JLabel:

• Jlabel is used to display a text


– JLabel(string str)
– JLabel(Icon i)
– JLabel(String s, Icon i, int align)
• CENTER, LEFT, RIGHT, LEADING, TRAILING
• Icon – is an interface
– The easiest way to obtain icon is to use ImageIcon class. ImageIcon class
implements Icon interface.
Important Methods:
Icon getIcon()
String getText()

void setIcon(Icon icon)


void setText(String s)

JText Fields
The Swing text field is encapsulated by the JTextComponent class, which extends
JComponent. It provides functionality that is common to Swing text components. One of its
subclasses is JTextField, which allows you to edit one line of text. Some of its constructors

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 166


ADVANCED JAVA PROGRAMMING I-MSC-CS
are shown here:
JTextField( )
JTextField(int cols)
JTextField(String s, int cols)
JTextField(String s)

Here, s is the string to be presented, and cols is the number of columns in the text
field.
The following example illustrates how to create a text field. The applet begins by
getting its content pane, and then a flow layout is assigned as its layout manager. Next, a
JTextField object is created and is added to the content pane.
Example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class MyFrame extends JFrame implements ActionListener
{
JLabel jl, jl2;
JTextField jtf;
MyFrame()
{
setLayout(new FlowLayout());
jl=new JLabel("Enter your name");
jl2=new JLabel();
jtf=new JTextField("PVPSIT",15);

add(jl);
add(jtf);
add(jl2);
jtf.addActionListener(this);
}

public void actionPerformed(ActionEvent ae)


{
jl2.setText(jtf.getText());
}
}
class FrameDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
f.setTitle("Welcome to Swings");
f.setSize(500,500);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 167


ADVANCED JAVA PROGRAMMING I-MSC-CS

The JButton Class

The JButton class provides the functionality of a push button. JButton allows an
icon, a string, or both to be associated with the push button. Some of its constructors are
shown here:
JButton(Icon i)
JButton(String s)
JButton(String s, Icon i)
Here, s and i are the string and icon used for the button.
Example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class MyFrame extends JFrame implements ActionListener
{
JButton jb,jb1,jb2;
JLabel jl;
MyFrame()
{
setLayout(new FlowLayout());
jl=new JLabel();
jb=new JButton("VRSEC");
ImageIcon ii=new ImageIcon("pvp.JPG");
jb1=new JButton("PVPSIT",ii);

ImageIcon ii2=new ImageIcon("bec.JPG");


jb2=new JButton("BEC", ii2);

add(jb); add(jb1); add(jb2); add(jl);

jb.addActionListener(this);
jb1.addActionListener(this);
jb2.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
jl.setText("You Pressed: "+ae.getActionCommand());
}
}
class FrameDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
f.setTitle("Welcome to Swings");
f.setSize(500,500);
f.setVisible(true);

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 168


ADVANCED JAVA PROGRAMMING I-MSC-CS

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

JCheckBox:
The JCheckBox class, which provides the functionality of a check box, is a concrete
implementation of AbstractButton. Its immediate super class is JToggleButton, which
provides support for two-state buttons (true or false). Some of its constructors are shown here:
JCheckBox(Icon i)
JCheckBox(Icon i, boolean state)
JCheckBox(String s)
JCheckBox(String s, boolean state)
JCheckBox(String s, Icon i)
JCheckBox(String s, Icon i, boolean state)
Here, i is the icon for the button. The text is specified by s. If state is true, the check
box is initially selected. Otherwise, it is not.
The state of the check box can be changed via the following method:
void setSelected(boolean state)
Here, state is true if the check box should be checked.
When a check box is selected or deselected, an item event is generated. This is
handled by itemStateChanged( ). Inside itemStateChanged( ), the getItem( ) method gets

the JCheckBox object that generated the event. The getText( ) method gets the text for that
check box and uses it to set the text inside the text field.
Example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class MyFrame extends JFrame implements ItemListener
{
JCheckBox jcb,jcb1,jcb2;
JLabel jl;
MyFrame()
{
setLayout(new FlowLayout());
jl=new JLabel();

jcb=new JCheckBox("VRSEC");
jcb1=new JCheckBox("PVPSIT");
jcb2=new JCheckBox("BEC" );

add(jcb); add(jcb1); add(jcb2); add(jl);

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 169


ADVANCED JAVA PROGRAMMING I-MSC-CS

jcb.addItemListener(this);
jcb1.addItemListener(this);
jcb2.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
JCheckBox jc=(JCheckBox)ie.getItem();
jl.setText("You Selected :"+jc.getText() );
}
}
class FrameDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
f.setTitle("Welcome to Swings");
f.setSize(500,500);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
JRadioButton:
Radio buttons are supported by the JRadioButton class, which is a concrete
implementation of AbstractButton. Its immediate superclass is JToggleButton, which
provides support for two-state buttons. Some of its constructors are shown here:
JRadioButton(Icon i)
JRadioButton(Icon i, boolean state)
JRadioButton(String s)
JRadioButton(String s, boolean state)
JRadioButton(String s, Icon i)
JRadioButton(String s, Icon i, boolean state)
Here, i is the icon for the button. The text is specified by s. If state is true, the button
is initially selected. Otherwise, it is not.
Radio buttons must be configured into a group. Only one of the buttons in that group
can be selected at any time. For example, if a user presses a radio button that is in a group,
any previously selected button in that group is automatically deselected. The ButtonGroup
class is instantiated to create a button group. Its default constructor is invoked for this
purpose. Elements are then added to the button group via the following method:
void add(AbstractButton ab)
Here, ab is a reference to the button to be added to the group.
Radio button presses generate action events that are handled by actionPerformed( ).
The getActionCommand( ) method returns the text that is associated with a radio button and
uses it to set the text field.
TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 170
ADVANCED JAVA PROGRAMMING I-MSC-CS

Example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class MyFrame extends JFrame implements ActionListener
{
JRadioButton jrb,jrb1,jrb2;
JLabel jl;
MyFrame()
{
setLayout(new FlowLayout());
jl=new JLabel();

jrb=new JRadioButton("VRSEC");
jrb1=new JRadioButton("PVPSIT");
jrb2=new JRadioButton("BEC" );

add(jrb); add(jrb1); add(jrb2); add(jl);

ButtonGroup bg=new ButtonGroup();


bg.add(jrb); bg.add(jrb1); bg.add(jrb2);
jrb.addActionListener(this);
jrb1.addActionListener(this);
jrb2.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
jl.setText("You Selected :"+ae.getActionCommand());
}
}
class FrameDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
f.setTitle("Welcome to Swings");
f.setSize(500,500);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 171


ADVANCED JAVA PROGRAMMING I-MSC-CS

JComboBox :

Swing provides a combo box (a combination of a text field and a drop-down list)
through the JComboBox class, which extends JComponent.

A combo box normally displays one entry. However, it can also display a drop-down
list that allows a user to select a different entry. You can also type your selection into the text
field.
Two of JComboBox’s constructors are shown here:
JComboBox( )
JComboBox(Vector v)

Here, v is a vector that initializes the combo box. Items are added to the list of choices
via the addItem( ) method, whose signature is shown here:
void addItem(Object obj)
Here, obj is the object to be added to the combo box.

By default, a JComboBox component is created in read-only mode, which means the


user can only pick one item from the fixed options in the drop-down list. If we want to allow
the user to provide his own option, we can simply use the setEditable() method to make the
combo box editable.
Example:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyFrame extends JFrame implements ItemListener
{
JComboBox jcb;
MyFrame()
{
setLayout(new FlowLayout());
String cities[]={"Amaravati","Guntur","Vijayawada","Vizag","Kurnool"};

jcb=new JComboBox(cities);
jcb.addItem("Tirupati");
jcb.setEditable(true);
add(jcb);
jcb.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
JOptionPane.showMessageDialog(null,jcb.getSelectedItem());
}
}
public class JComboBoxDemo
{
public static void main(String[] args)

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 172


ADVANCED JAVA PROGRAMMING I-MSC-CS

{
MyFrame jf = new MyFrame();
jf.setSize(500,500);
jf.setVisible(true);
jf.setTitle("Frame Example");
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 173


ADVANCED JAVA PROGRAMMING I-MSC(CS)

JList:
• JList class is useful to create a list which displays a list of items and allows the user toselect
one or more items.
– Constructors
• JList()
• JList(Object arr[])
• JList(Vector v)
– Methods
• getSelectedIndex() – returns selected item index
• getSelectedValue() – to know which item is selected in the list
• getSelectedIndices() – returns selected items into an array
• getSelectedValues() – returns selected items names into an array
• JList generates ListSelectionEvent
– ListSelectionListener
• void valueChanged(ListSelectionEvent)
– Package is javax.swing.event.*;

Example:
import javax.swing.*; import
javax.swing.event.*; import
java.awt.*;
import java.awt.event.*;

class MyFrame extends JFrame implements ListSelectionListener


{
JLabel jl; JList j;
MyFrame()
{
setLayout(new FlowLayout());
jl=new JLabel("Choose one college..");

String arr[]={"BEC", "PVPSIT","RVR&JC", "VRSEC"};

j=new JList(arr);
add(jl);
add(j);
j.setToolTipText("I am PVPSIT");
j.addListSelectionListener(this);
}
public void valueChanged(ListSelectionEvent le)

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 174


ADVANCED JAVA PROGRAMMING I-MSC(CS)
{
JOptionPane.showMessageDialog(null, j.getSelectedValue());
}
}
class FrameDemo2
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
f.setTitle("Welcome to Swings");
f.setSize(500,500); f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Advanced java Techniques

Introduction

 Core Java (J2SE) and Advanced Java are the two components that make up the Java
programming language (JEE).
 The foundations of the Java programming language, including its data types, functions,
operators, loops, threads, and exception handling.
 It is used in the process of developing apps for widespread usage. Whereas Intermediate
Java focuses on more advanced topics, such as database connection, networking, Servlet, web
services, and so on,
 Advanced Java addresses more fundamental ideas.

Advanced java

Everything that is beyond Core Java is known as Advanced Java. This includes the application
programming interfaces (APIs) that are specified in Java Enterprise Edition, as well as Servlet programming,
Web Services, the API, and so on.

1. Java Enterprise Edition (Java EE):


Java Enterprise Edition (Java EE), now known as Jakarta EE, it’s an remarkable component of
Advanced Java programming. It gives Scalability for Big-League applications, that provides a smooth
pattern to create applications that could grow seamlessly as your user base expands. Basically, it’s
designed to help developers create powerful, scalable, and robust enterprise-level applications

a. Java Servlets
It’s used to create dynamic and interactive web pages. Servlets create web dynamic pages, have the
great feature for User Interaction that quickly creates responses that match your actions.
Servlets act as a fast messenger between your web browser and servlet. Servlet manages users
request and response, as the servlet receives users request, it processes and sends back a tailored response.

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 175


ADVANCED JAVA PROGRAMMING I-MSC(CS)

b. JavaServer Pages (JSP)


JSP stands for “JavaServer Pages” which is used to build web applications that make your online
experience more interesting. JSP creates the web pages that can change and adapt as per the user command
like what user is giving input and dynamically adjust according to the user input that renders the dynamic
content.
JSP efficiently integrates Java into HTML pages, where you have an option to convert any pre-
existing HTML pages by modifying its extension to “.jsp” instead of “.html” JPS reduces the length of
your code, and makes it easy to maintain without having the need of redeployment and recompilation as
it’s platform independent.

c. JavaServer Faces (JSF)


stands for “JavaServer Faces” that encompasses a collection of APIs (Application Programming
Interfaces) that simplify and streamline web pages user-friendly, and interactive. JSF uses a building block
method, where developers can pick and arrange UI components like buttons, forms, and tables to create
complete web pages.
JSP abstracts the complexities of web development by encapsulating the intricate behaviours, and
allowing developers to focus on combining UI components.

d. Enterprise JavaBeans (EJB)


Enterprise JavaBeans (EJB) are the specialised components that handle complex business logics
and processes in Advanced Java. They manage scalability, secure transactions, and efficient data
processing that could tackle complex business tasks.
EJB ensures that your data is saved correctly, and if something goes wrong it undo the
modification to maintain overall consistency, also EJB executes tasks in the correct sequence. EJB works
in a unified system as it allows applications to distribute among different computers.
EJB manages complex logic, handles transactions, and ensures scalability. By using EJB, it creates
powerful business software.

2. Concurrency
Concurrency having the ability in Advanced Java to execute multiple tasks simultaneously, that
runs independently and concurrently by allowing different programs.
Concurrency plays an important role as it maximises the performance, enhances responsiveness, in
simpler terms concurrency implements multiple tasks at once, it has the synchronisation that prevents the
data corruption and race conditions, and deadlocks.
is vital in modern software development where Java provides thread-safe collections like
ConcurrentMap and ConcurrentQueue that are accessed by multiple threads concurrently.

Example: Ticket Booking

3. Multithreading
Multithreading is the process of having several tasks running together parallelly. Multithreading has
Java API features that creates and manages thread easily. In Advanced Java by using multithreading in
applications developers can create more fast, secure, responsive, and capable, so that could handle complex
tasks efficiently.

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 176


ADVANCED JAVA PROGRAMMING I-MSC(CS)
4. JDBC
JDBC stands for “Java Database Connectivity” which is a very essential component in Advanced
Java for interacting with databases. JDBC connects with various relational databases that executes the
queries, and manipulates the data with the help of Java APIs .JDBC allows the Java program to interact
with the databases to retrieve information, store the data, and update the data. In order to overcome the
problems by using JDBC directly,Spring framework has provided one abstraction layer on top of existing
JDBC technology, we used to call this layer as Spring-JDBC.

Following are the step-by-step connection of JDBC (Java Database Connectivity):

1. Load the JDBC driver


2. Establish a Connection
3. Creating a Statement
4. Execute SQL Queries
5. Process Results
6. Close Resources
7. Handle Exceptions

5. Java Persistence API (JPA)

Java Persistence API is a collection of classes and methods to persist or store the vast amount of
data into a database. JPA is a specification to store or manage Java objects or classes into the databases,
which use Object-Relational Mapping (ORM) as implementation internally to persist the database. JPA
Persistence framework needs to follow:
 Spring Data JPA: Spring Data JPA provides a higher-level abstraction layer on the top of JPA that
reduces the amount of boilerplate code needed for common database operations.
 Spring Repository: It is a JPA specific extension for Repository, it has full API CRUD Repository
also the Paging and Sorting Repository. So basically, the JPA repository contains APIs for basic CRUD
operations, the APIs for pagination and the APIs for Sorting.

6. Spring Framework

1. IT is a popular non-standard open-source framework developed by Interface21 INC.


2. Aims to overcome the application problems by enabling the use of simple Java Beans(POJO-Plain Old
Java Objects) to implement the business logic.
3. Enables the developers to create and test the application very easily.
4. Aims to minimise the dependency of application code on its framework.
5. Enables the use of simplicity and ease of testability in standard application.
6. The Spring Framework has a layered architecture made up of several well defined modules.

Features of Spring Framework:

1. Pluggability
 It allows us to associate and remove business layer objects of with each other
.2. Dependency Injection
 It allows you to lose coupling by creating the business layer objects based on the description in the
spring configuration file.

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 177


ADVANCED JAVA PROGRAMMING I-MSC(CS)
3. Container
 The spring framework is a container that holds all the application objects.
 It is responsible for managing the life cycle and configuration of all the application objects.
.
4. Lightweight
 Spring is a lightweight framework that makes it easy to configure and create complex applications.
 It consists of several well-defined modules,built upon the concept of DI

7. Hibernate
Hibernate is a Java Persistence Framework. Persistence is the availability of the object/data even
after the process that created it,is terminated.

There are 4 layers in the hibernate architecture:


1. Java application layer
2. Hibernate framework layer
3. Backend API layer
4. Database layer
For creating the first application, we need to know the elements of hibernate architecture, they are
as follows:
1.SessionFactory: The SessionFactory is a factory of session and client of ConnectionProvider.It
holds a second level cache(optional) of data.

2. Session: The session object provides an interface between the application and data stored into the
database.

8. Java Messaging Service (JMS)


Java Messaging Service (JSM) is an important component in Advanced Java that enables efficient
communication between various software components using a messaging paradigm.
.JMS is built on the concept of a messaging system where components can send and receive
messages; this operates independently. P2P communication, messages are being sent from one producer to
one consumer, each message is consumed by only one consumer. JMS enables asynchronous
communications, it provides decoupling where components can communicate with each other.

9. Java Security
The term ‘Security’ means to ensure that your application is secured, and it checks for valid users if
they login, it may login successfully if the user is authorised, but if the user is invalid then it is denied
access to the application. So basically, it works on two scenarios i.e. Authentication, and Authorization.
Java supports secure communication through protocoles like SSL/TLS, that enables encrypted data
exchange over the network. independent(no session management), or Single-Sign-On (SSO) and manages
authorization to control access to specific functionalities.

10. Java Design Patterns


Java Design Patterns are the reusable solutions to common problems that frequently arise during
the software designing and development phase. It provides methods and recommendations for structuring
and organising code to attain quality and to achieve maintainability, scalability, and flexibility.

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 178


ADVANCED JAVA PROGRAMMING I-MSC(CS)

Some commonly used Java Design Pattern: Creational Patterns


1. Singleton
2. Factory Method
3. Abstract Factory
4. Builder
5. Prototype
Some commonly used Java Design Pattern: Structural Patterns:
1. Adaptor
2. Bridge
3. Composite
4. Decorator
5. Facade
6. Flyweight
Some commonly used Java Design Pattern: Behavioural Patterns:
1. Observer
2. Strategy
3. Chain of Responsibility
4. Command
5. Interpreter
6. Iterator
7. Mediator
8. State
9. Template Method
10. Visitor

TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 179

You might also like