You are on page 1of 43

For 2nd Year Regular CS & 3rd Year Extension Cs students

DEBRE TABOR UNIVERSITY


FACULTY OF TECHNOLOGY & RELATED SCIENCES

DEPARTMENT OF COMPUTER SCIENCE

Course module for Advanced Programming(JAVA) (CoSc2084)

Prepared by:
Mr Gizatie D.

Wellcome to advanced java module

DTU
Modified in January, 2015
Set by Gizatie D. DTU, Computer Science department, modified in Junuary, 2015 Page 1
For 2nd Year Regular CS & 3rd Year Extension Cs students

Module Topic: - Advance Programming(Java)


Course Code:- CoSc2084
Credit hour: - 6 hrs (4hrs Lecture, 3hrs lab)
Pre Requisites: - CoSc2082
Course Description
This course covers topics on Java which includes: AWT and Swing, I/O Streams, Multithreading,
Network Programming, Java database connectivity (JDBC), RMI, and Introduction to Servlets.
Course Objectives
At the end of the course, students will be able to:- Carry out design and development of complex elements, such
as
 user interfaces, multiprocessing, and fault-tolerant components;
 Write TCP/IP Client Server applications using Sockets;
 Write Java applications using the JDBC to make database independent queries; and Call methods
remotely.
 apply their java skill in scientific research

Learning outcomes
At the end of the course students will be able to:-
A. Define GUI in java K, L1
B. create a program of GUI and other K,L5
C. Differentiate AWT and SWING .A,L2
D. Design advance programming S,l3

Set by Gizatie D. DTU, Computer Science department, modified in Junuary, 2015 Page 2
For 2nd Year Regular CS & 3rd Year Extension Cs students

UNIT ONE:
AWT And SWING
Unit description
This unit deals with AWT &SWING components with in event handling ,sources and lisneres. To address these
contents Brainstorming, peer & group discussion and gap lecture will be used more. Question & answer, group works
are among the methods to be used.
I. Objectives: At the end of this unit, students will be able to:
 Define AWT&SWING L1(K)
 Compare AWT&SWING L5(K)
 Differentiate the components of awt and swing L3 (A )
II. Contents:
 Definition of AWT& SWING
 Components of the AWT & SWING
 Event handling, sources and listeners

III. Method of Teaching : brain storming , gap lecture, group discussion


1.1 Introduction:
Some Computers Terminologies:
Brian storming: what is GUI, AWT &SWING?
Interactive lecture:
A graphical user interface (GUI) presents a pictorial interface to a program. A GUI (pronounced “ GOO-
EE” ) gives a program a distinctive “ look” and “ feel.” Providing different programs with a consistent set of
intuitive user interface components provides users with a basic level of familiarity with each program before
they ever use it. GUI programming in Java is based on three concepts:
 Components. A component is an object that the user can see on the screen and—in most
cases—interact with.
 Containers. A container is a component that can hold other components.
 Events. An event is an action triggered by the user, such as a key press or mouse click.
Designing a graphical user interface involves creating components, putting them into containers, and arranging
for the program to respond to events.
AWT Overview
 Java’ s Abstract Window Toolkit provides classes and other tools for building programs that
have a graphical user interface.
 The term “ Abstract” refers to the AWT’ s ability to run on multiple platforms.
 Building a GUI involves creating “ abstract” components such as buttons and windows, which
are then mapped to “ concrete” components for a specific platform.
Swing Overview
 Defined in package javax.swing
 Java has a newer library for building graphical user interfaces, known as “ Swing.” Swing is
more powerful and sophisticated than the AWT.
 Original GUI components from AWT in java.awt
 Heavyweight components - rely on local platform's windowing system for look and feel
Set by Gizatie D. DTU, Computer Science department, modified in Junuary, 2015 Page 3
For 2nd Year Regular CS & 3rd Year Extension Cs students

 Swing components are lightweight


 Not weighed down by GUI capabilities of platform
 More portable than heavyweight components
 Swing components allow programmer to specify look and feel
 Can change depending on platform
 Can be same across all platforms
AWT&SWING can be defined as:
 Most GUI class libraries in C++ are platform specific
 Different hardware capabilities
 Subtle differences between the "look-and-feel" of various Windowing operating systems
 Abstract Window Toolkit (AWT) is cross-platform
 Swing can observe various OS look-and-feel conventions
AWT Vs SWING
 AWT is Java’ s original set of classes for building GUIs
o Uses peer components of the OS; heavyweight
o Not truly portable: looks different and lays out inconsistently on different OSs
 Due to OS’ s underlying display management system
 Swing is designed to solve AWT’ s problems
o 99% java; lightweight components
o Lays out consistently on all OSs
o Uses AWT event handling
o Swing is bigger, slower, and more complicated .But much faster than it used to be
o Swing is more flexible and better looking
 Swing and AWT are incompatible--you can use either, but you can’ t mix
Group discussion:
Compare AWT and SWING.

1.2 Graphical Components

Set by Gizatie D. DTU, Computer Science department, modified in Junuary, 2015 Page 4
For 2nd Year Regular CS & 3rd Year Extension Cs students

1.2.1 Menus
Menu
Menu Bar – JMenu( String )
– JMenuBar() – add( JMenuItem )
– add( JMenu
JMenuBar mb = new JMenuBar(); //create a menu bar
JMenu fileMenu = new JMenu (“ File” ); //create a menu
mb.add( fileMenu ); //add menu to menu bar
setMenuBar( mb ); // add a menu bar to frame
fileMenu.setMnemonic( KeyEvent.VK_F ); // add a hotkey to menu
JMenuItem miOpen = new JMenuItem( “ Open...” , KeyEvent.VK_O );
JMenuItem miExit = new JMenuItem( “ Exit” );
fileMenu.add( miOpen ); // add a menu item
fileMenu.addSeparator(); // add a menu separator
fileMenu.add( miExit );
1.2.2 Frame
 Frame is a window that is not contained inside another window. Frame is the basis to
contain other user interface components in Java GUI applications.
 The JFrame class can be used to create windows.
 For Swing GUI programs, use JFrame class to create widows.
1.2.3 Labels
This class is a Component which displays a single line of text.

Set by Gizatie D. DTU, Computer Science department, modified in Junuary, 2015 Page 5
For 2nd Year Regular CS & 3rd Year Extension Cs students

Labels are read-only. That is, the user cannot click on a label to edit the text it
displays.
Text can be aligned within the label
To create Label :-
Label la=new Label(“ Enter password);
La.setAlinment(Label.Right);
Panel.add(la);
1.2.4 Buttons
This class represents a push-button which displays some specified text.
When a button is pressed, it notifies its Listeners. (More about Listeners in the
next chapter).
To be a Listener for a button, an object must implement the ActionListener
Interface.
Panel aPanel = new Panel();
Button okButton = new Button("Ok");
Button cancelButton = new Button("Cancel");
aPanel.add(okButton));
aPanel.add(cancelButton));
okButton.addActionListener(controller2);
cancelButton.addActionListener(controller1);
1.2.5 TextField
This class displays a single line of optionally editable text.
This class inherits several methods from TextComponent.
This is one of the most commonly used Components in the AWT
TextField emailTextField = new TextField();
TextField passwordTextField = new TextField();
passwordTextField.setEchoChar("*");
String userEmail = emailTextField.getText();
String userpassword = passwordTextField.getText();
1.2.6 Checkbox
This class represents a GUI checkbox with a textual label.
The Checkbox maintains a boolean state indicating whether it is checked or not.
If a Checkbox is added to a CheckBoxGroup, it will behave like a radio button.
Checkbox creamCheckbox = new CheckBox("Cream");
Checkbox sugarCheckbox = new CheckBox("Sugar");
if (creamCheckbox.getState())
{
coffee.addCream();
}
JLabel
 Labels
 Provide text instructions on a GUI
 Read-only text
 Programs rarely change a label's contents
 Class JLabel (subclass of JComponent)
 Methods
 Can declare label text in constructor
Set by Gizatie D. DTU, Computer Science department, modified in Junuary, 2015 Page 6
For 2nd Year Regular CS & 3rd Year Extension Cs students

 myLabel.setToolTipText( "Text" )
• Displays "Text" in a tool tip when mouse over label
 myLabel.setText( "Text" )
 myLabel.getText()
JFrame Class
ja v a x .s w in g .J F ra m e
+ JF ra m e() C r e a t e s a d e f a u lt f r a m e w i t h n o ti t le .
+ J F r a m e ( t i t le : S t r i n g ) C r e a t e s a f r a m e w i th th e s p e c i f i e d t it le .
+ s e t S i z e ( w i d t h : i n t , h e i g h t : in t ) : v o i d S p e c i f i e s th e s i z e o f t h e f r a m e .
+ s e t L o c a t i o n ( x : in t, y : i n t ) : v o i d S p e c i f i e s th e u p p e r - le f t c o r n e r lo c a t i o n o f th e f r a m e .
+ s e t V i s ib le ( v i s i b le : b o o l e a n ) : v o i d S e t s t r u e t o d is p la y t h e f r a m e .
+ s e t D e f a u lt C lo s e O p e r a t i o n ( m o d e : in t) : v o i d S p e c i f i e s th e o p e r a ti o n w h e n t h e f r a m e i s c lo s e d .
+ s e t L o c a t i o n R e la t i v e T o ( c : C o m p o n e n t ) : S e t s t h e lo c a t i o n o f th e f r a m e r e la t i v e t o th e s p e c i f i e d c o m p o n e n t .
v o id I f t h e c o m p o n e n t i s n u ll, th e f r a m e i s c e n t e r e d o n t h e s c r e e n .
+ p a c k (): v o id A u t o m a t ic a lly s e t s t h e f r a m e s i z e t o h o ld t h e c o m p o n e n t s i n th e
fra m e.

JCheckBox
• When JCheckBox changes
– ItemEvent generated
• Handled by an ItemListener, which must define
itemStateChanged
– Register handlers with with addItemListener
• Class ItemEvent
– getStateChange
• Returns ItemEvent.SELECTED or ItemEvent.DESELECTED
JRadioButton
• Radio buttons
– Have two states: selected and deselected

Set by Gizatie D. DTU, Computer Science department, modified in Junuary, 2015 Page 7
For 2nd Year Regular CS & 3rd Year Extension Cs students

– Normally appear as a group


• Only one radio button in group selected at time
• Selecting one button forces the other buttons off
– Mutually exclusive options
– ButtonGroup - maintains logical relationship between radio buttons
• Class JRadioButton
– Constructor
• JRadioButton( "Label", selected )
• If selected true, JRadioButton initially selected

JTextField
A text field is an input area where the user can type in characters. Text fields
are useful in that they enable the user to enter in variable data (such as a
name or a description).

The get and set m ethods for these data fields are provided in
the class, but om itted in the UM L diagram for brevity.
javax.sw ing.text.JTextC om ponent
-text: String The text contained in this text com ponent.
-editable: boolean Indicates whether this text com ponent is editable (default: true).

javax.sw ing.JT extField


-colum ns: int The num ber of colum ns in this text field.
-horizontalAlignm ent: int The horizontal alignm ent of this text field (default: LE FT ).
+JTextField() C reates a default em pty text field with num ber of colum ns set to 0.
+JTextField(colum n: int) C reates an em pty text field with specified num ber of colum ns.
+JTextField(text: String) C reates a text field initialized with the specified text.
+JTextField(text: String, colum ns: int) C reates a text field initialized with the specified text and colum ns.

Reading assignment
Please read the all about components of SWING its properties and methods?
SwingorAWT?That’ stheQuestion.
• Why JButton, not Button?
Initially, the GUI classes were bundled in a library known as the Abstract
WindowsToolkit (AWT).
 AWT components are mapped to platform-specific components.
 AWT, however, is not good for developing comprehensive GUIs, and is
prone to platform-specific bugs.
 In Java 2, the AWT components were replaced with Swing.
 Swing is more flexible and robust.
 Swing components are directly painted on canvases using Java code.

Set by Gizatie D. DTU, Computer Science department, modified in Junuary, 2015 Page 8
For 2nd Year Regular CS & 3rd Year Extension Cs students

1.3 Events and Event Handling


 Components (AWT and Swing) generate events in response to user actions
 (button clicks, mouse movement, item selection…)
 different components generate different events
 Buttons generate “ action” events
 Cursor movement generates “ mouse events” ect.
 The program must provide event handlers to catch and
process events
 Unprocessed events are passed up through the event hierarchy
and handled by a default (do nothing) handler
 An event is a signal to the program that something has happened.When an event occurs, a special
piece of code responds to the event.The component on which an event is generated is the
source object.

1.4 Determining the Source of an Event


If two or more buttons are connected to a single listener, its actionPerformed
method will need to determine which button was pressed.
• Ways to solve this problem:
– Compare the source of the event (the component that triggered the
method call) to see which Button object it matches.
– Test the event’ s action command to see which button label it
matches.Degu Atalay second year computer science student comes
from bdr robit kebele

1.5 Listeners
Now, an event is fired; who will be interested in this event?
 A listener is an object interested in the event.
 How can we create a listener object?
 First, the listener object must be an instance of the corresponding event-
listener interface.
For example, the corresponding event-listener interface for ActionEvent is
ActionListener.
• We also need to implement the handler method required by ActionListener.
class OKListener implements ActionListener {Listener handling
void actionPerformed(ActionEvent event) {
System.out.println(“ It is OK.” ); Event handling
}
}
Presentation:
Read the components of AWT & SWING
Read and present in the class about components of AWT & SWING then write one
program
IV. Assessments:
1. What are the components of SWING?
2. Create one Frame after that add the components of swing by using its properties

Set by Gizatie D. DTU, Computer Science department, modified in Junuary, 2015 Page 9
For 2nd Year Regular CS & 3rd Year Extension Cs students

and methods of each components?


Answer
1. JFrame,JButton,JLabel………
2.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Log extends JFrame {
public static void main(String[] args) {
Log frameTabel = new Log();
}
JButton blogin = new JButton("Login");
JPanel panel = new JPanel();
JTextField txuser = new JTextField(15);
JPasswordField pass = new JPasswordField(15);
Log(){
super("Login Autentification");
setSize(300,200);
setLocation(500,280);
panel.setLayout (null);
txuser.setBounds(70,30,150,20);
pass.setBounds(70,65,150,20);
blogin.setBounds(110,100,80,20);
panel.add(blogin);
panel.add(txuser);
panel.add(pass);
getContentPane().add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
actionlogin();
}
public void actionlogin(){
blogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String puname = txuser.getText();
String ppaswd = pass.getText();
if(puname.equals("test") && ppaswd.equals("12345")) {
newframe regFace =new newframe();
regFace.setVisible(true);
dispose();
} else {
JOptionPane.showMessageDialog(null,"Wrong Password / Username");
txuser.setText("");
pass.setText("");

Set by Gizatie D. DTU, Computer Science department, modified in Junuary, 2015 Page 10
For 2nd Year Regular CS & 3rd Year Extension Cs students

txuser.requestFocus();
}
}
});
}

UNIT TWO
Streams and File I/O
Unit description:
In this unit Streams, various stream classes and object streams, File management
contents to be covered. To deliver these contents brain storming and interactive lecture,
Peer teaching, group discussion, presentation and class work methods are used. And the
way of assessment will takes place in the form of questioning and answer, group work,
peer assessment.

I. Objectives: At the end of this unit students will be able to:


 become familiar with the concept of an I/O stream
 understand the difference between binary files and text files
 learn how to save data in a file
 learn how to read data from a file
II. Contents:
 Overview of Streams and File I/O
 Text-File I/OVs Binary File I/O
 Stream classes
 Object I/O with Object Streams
III. Method of Teaching: brain storming, gap lecture, group discussion

2.1 Introduction:
Brian storming: what is the term stream, various stream classes and object streams?
Gap lecture:
Stream, various stream classes and File management:
 Stream: an object that either delivers data to its destination (screen, file, etc.) or that
takes data from a source (keyboard, file, etc.)
– it acts as a buffer between the data source and destination
Set by Gizatie D. DTU, Computer Science department, modified in Junuary, 2015 Page 11
For 2nd Year Regular CS & 3rd Year Extension Cs students

 Streams in JAVA are Objects, of course ! Having - 2 types of streams (text / binary) and
-2 directions (input / output)
 results in 4 base-classes dealing with I/O:
1. Reader: text-input
2. Writer: text-output
3. InputStream: byte-input
4. OutputStream: byte-output
Input stream: a stream that provides input to a program-System.in is an input stream
Output stream: a stream that accepts output from a program-System.out is an output stream
 A stream connects a program to an I/O object
– System.out connects a program to the screen
– System.in connects a program to the keyboard
 I/O: General Scheme
In JAVA:
– Create a stream object and associate it with a disk-file
– Give the stream object the desired functionality
– while there is more information
read(write) next data from(to) the stream
– close the stream.
Binary Versus Text Files
 All data and programs are ultimately just zeros and ones
– each digit can have one of two values, hence binary
– bit is one binary digit
– byte is a group of eight bits
 Text files: the bits represent printable characters
– one byte per character for ASCII, the most common code
– for example, Java source files are text files
– so is any file created with a "text editor"
 Binary files: the bits represent other types of encoded information, such as executable
instructions or numeric data
 these files are easily read by the computer but not humans
 they are not "printable" files
Set by Gizatie D. DTU, Computer Science department, modified in Junuary, 2015 Page 12
For 2nd Year Regular CS & 3rd Year Extension Cs students

• actually, you can print them, but they will be unintelligible


• "printable" means "easily readable by humans when printed"
 Every File Has Two Names
1. the stream name used by Java- outputStream in the example
2. the name used by the operating system-out.txt in the example
 Text File Output-To open a text file for output: connect a text file to a stream for
writing
PrintWriteroutputStream =new PrintWriter(new FileOutputStream("out.txt"));
• Similar to the long way:
FileOutputStream s = new FileOutputStream("out.txt");
PrintWriter outputStream = new PrintWriter(s);
 Goal: create a PrintWriter object-which uses FileOutputStream to open a text file
 FileOutputStream “ connects” PrintWriter to a text file.

Input Text File


 Text File Input-To open a text file for input: connect a text file to a stream for reading
– Goal: a BufferedReader object, which uses FileReader to open a text file
– FileReader “ connects” BufferedReader to the text file
For example:BufferedReader smileyInStream = new BufferedReader(new
FileReader(“ smiley.txt"));
Similarly, the long way:
FileReader s = new FileReader(“ smiley.txt"); BufferedReader smileyInStream = new
BufferedReader(s);

Set by Gizatie D. DTU, Computer Science department, modified in Junuary, 2015 Page 13
For 2nd Year Regular CS & 3rd Year Extension Cs students

2.2 Java File I/O: Stream Classes


 ObjectInputStream and ObjectOutputStream:
 have methods to either read or write data one byte at a time
 automatically convert numbers and characters into binary:-binary-encoded
numeric files (files with numbers) are not readable by a text editor, but
store data more efficiently

File Class [java.io]


 Acts like a wrapper class for file names
 A file name like "numbers.txt" has only String properties
 File has some very useful methods
 exists: tests if a file already exists
 canRead: tests if the OS will let you read a file
 canWrite: tests if the OS will let you write to a file
 delete: deletes the file, returns true if successful
 length: returns the number of bytes in the file
 getName: returns file name, excluding the preceding path
 getPath: returns the path name—the full name
 Remember:
 input means data into a program, not the file
 similarly, output means data out of a program, not the file
 Opening a New Output File
 The file name is given as a String
 file name rules are determined by your operating system

Set by Gizatie D. DTU, Computer Science department, modified in Junuary, 2015 Page 14
For 2nd Year Regular CS & 3rd Year Extension Cs students

 Opening an output file takes two steps


1. Create a FileOutputStream object associated with the file name String
1. Connect the FileOutputStream to an ObjectOutputStream object
Example: Opening an Output File
To open a file named numbers.dat:ObjectOutputStream outputStream =new
ObjectOutputStream(new FileOutputStream("numbers.dat"));
 The constructor for ObjectOutputStream requires a FileOutputStream argument
 The constructor for FileOutputStream requires a String argument
– the String argument is the output file name
 The following two statements are equivalent to the single statement above:
FileOutputStreammiddleman =new FileOutputStream("numbers.dat");
ObjectOutputStreamoutputStream =new ObjectOutputSteam(middleman);

. 2.3 File Objects and Filenames


 FileInputStream and FileOutputStream have constructors that take a File
argument as well as constructors that take a String argument
PrintWriter smileyOutStream = new PrintWriter(new FileOutputStream(“ smiley.txt” ));
File smileyFile = new File(“ smiley.txt” );
if (smileyFile.canWrite())
PrintWriter smileyOutStream = new PrintWriter(new FileOutputStream(smileyFile));
 Alternative with Scanner
• Instead of BufferedReader with FileReader, then StringTokenizer :Use Scanner
with File:
Scanner inFile = new Scanner(new File(“ in.txt” ));Similar to Scanner with System.in:
File input :Scanner keyboard = new Scanner(System.in);
Scanner inFile = new Scanner(new File(“ in.txt” ));
File output : PrintWriter outFile = new PrintWriter(new File(“ out.txt” ));outFile.print(),
println(), format(), flush(), close(),
 Basic Binary File I/O
Important classes for binary file output (to the file)
o ObjectOutputStream
o FileOutputStream

Set by Gizatie D. DTU, Computer Science department, modified in Junuary, 2015 Page 15
For 2nd Year Regular CS & 3rd Year Extension Cs students

Important classes for binary file input (from the file):


o ObjectInputStream
o FileInputStream
Note that FileOutputStream and FileInputStream are used only for their
constructors, which can take file names as arguments.
o ObjectOutputStream and ObjectInputStream cannot take file names as
arguments for their constructors
Assessment

1. Write a program that opening of out File?

UNIT THREE
Multithreading Concept
Unit description
In this unit Multithreading concept, process, thread priorities& schedules, thread synchronization and un
synchronized .To deliver these contents brain Storming and gap lecture, group discussion, demonstration
methods will be used. And the way of assessment will takes place in the form of questioning and answer,
group work, individual assignment, lab assignment, test.
I. Objectives: At the end of this, unit students will be able to:
 Define Multithreading
 Differentiate multithreading and process
 Differentiate thread priorities& schedules
 Differentiate thread synchronization and un synchronized.
II. Contents:

 Multithreading
 Multithreading and process
 Thread priorities& schedules
 Thread synchronization and un synchronized.
III. Method of Teaching : brain storming , gap lecture, group discussion

3.1 Introduction:
Brian storming: what is multithreading?
Mini lecture:
 The human body performs a great variety of operations in parallel—or concurrently.
 Computers, too, can perform operations concurrently Only computers that have multiple processors can
truly execute multiple instructions concurrently .
 Operating systems on single-processor computers create the illusion of concurrent execution by rapidly

Set by Gizatie D. DTU, Computer Science department, modified in Junuary, 2015 Page 16
Course Module of Advanced Java Programming

switching between activities, but on such computers only a single instruction can execute at once Java
makes concurrency available to you through the language and APIs.
 A multithreaded application contains separate threads of execution, where each thread Has its own
method-call stack and program counter execute concurrently with other threads.
 shares application-wide resources such as memory with other threads.
 In single-threaded applications lengthy activities must complete before others can begin which leads to
poor responsiveness.
 In a multithreaded application, threads can be distributed across multiple processors (if available) so that
multiple tasks execute concurrently and the application can operate more efficiently.
 Multithreading can also increase performance on single-processor systems that simulate
concurrency—when one thread cannot proceed (because, for example, it is waiting for the result of an I/O
operation), another can use the processor.
 An application of concurrent programming
o Start playback of an audio clip or a video clip while the clip downloads
o synchronize (coordinate the actions of) the threads so that the player thread doesn’ t begin until
there is a sufficient amount of the clip in memory to keep the player thread busy
 The Java Virtual Machine (JVM) creates threads to run a program, the JVM also may create threads for
performing housekeeping tasks such as garbage collection
 Programming concurrent applications is difficult and error-prone. Follow some simple guidelines
o Use existing classes from the Java API such as the ArrayBlockingQueue class that manage
synchronization for you.
o If you find that you need more custom functionality than that provided in the Java APIs, you should
use the synchronized keyword and Object methods wait, notify and notifyAll
o If you need even more complex capabilities, then you should use the Lock and Condition interfaces
 A program has one or more locus of execution. Each execution is called a thread of execution. The set of
threads comprise a process.
Threads of execution
 Each thread is a portion of a program that can execute concurrently with other threads (multithreading)
 C and C++ are single-threaded
 Gives Java powerful capabilities not found in C and C++
3.2 Thread States: Life Cycle of a Thread
 A thread occupies one of several thread states (Fig. 1)
 A new thread begins its life cycle in the new state.
 When the program starts the thread it enters the runnable state. :-considered to be executing its task
 Runnable thread transitions to the waiting state while it waits for another thread to perform a task
– transitions back to the runnable state only when another thread notifies the waiting thread to
continue executing
 A runnable thread can enter the timed waiting state for a specified interval of time
– transitions back to the runnable state when that time interval expires or when the event it is
waiting for occurs.

Set by Gizatie D. DTU, Computer Science department, Junuary, 2014 Page 17 of 43


Course Module of Advanced Java Programming

Fig. 1 Thread life-cycle UML state diagram


 Timed waiting and waiting threads cannot use a processor, even if one is available.
 A runnable thread can transition to the timed waiting state if it provides an optional wait interval when it
is waiting for another thread to perform a task.
 returns to the runnable state when it is notified by another thread, or the timed interval expires
 A thread also enters the timed waiting state when put to sleep
 remains in the timed waiting state for a designated period of time then returns to the runnable state
 A runnable thread transitions to the blocked state when it attempts to perform a task that cannot be
completed immediately and it must temporarily wait until that task completes.
 A blocked thread cannot use a processor, even if one is available
 A runnable thread enters the terminated state (sometimes called the dead state) when it successfully
completes its task or otherwise terminates (perhaps due to an error).
 At the operating system level, Java’ s runnable state typically encompasses two separate states (Fig.2).
 operating system hides these states from the JVM
 A runnable thread first enters the ready state
 When thread is dispatched by the OS it enters the running state
 When the thread’ s quantum expires, the thread returns to the ready state and the operating system
dispatches another thread
 Transitions between the ready and running states are handled solely by the operating system

Fig. 2 Operating system’ s internal view of Java’ s runnable state.


3.3 Multi-threaded Clients Example : Web Browsers
 Browsers such as IE are multi-threaded

Set by Gizatie D. DTU, Computer Science department, Junuary, 2014 Page 18 of 43


Course Module of Advanced Java Programming

 Such browsers can display data before entire document is downloaded: performs multiple simultaneous
tasks
 Fetch main HTML page, activate separate threads for other parts
 Each thread sets up a separate connection with the server -Uses blocking calls
 Each part (gif image) fetched separately and in parallel
 Advantage: connections can be setup to different sources-Ad server, image server
Multi-threaded Server Example
 Apache web server: pool of pre-spawned worker threads
 Dispatcher thread waits for requests
 For each request, choose an idle worker thread
 Worker thread uses blocking system calls to service web request

.4 Thread Priorities and Thread Scheduling


 Every Java thread has a thread priority that helps the operating system determine the order in which
threads are scheduled
 Priorities range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10)
 By default, every thread is given priority NORM_PRIORITY (a constant of 5)
 Each new thread inherits the priority of the thread that created it
 Every Java thread has a thread priority that helps the operating system determine the order in which
threads are scheduled
Group discussion
Discus thread priorities and schedules?

3.5 Creating and Executing Threads


 The preferred means of creating multithreaded Java applications is by implementing interface
Runnable (of package java.lang).
 Runnable object represents a “task” that can execute concurrently with other tasks
 Interface Runnable declares method run in which you place the code that defines the task to perform.
 The thread executing a Runnable calls method run to perform the task.
 A program will not terminate until its last thread completes execution
 The code in method main executes in the main thread, a thread created by the JVM

Set by Gizatie D. DTU, Computer Science department, Junuary, 2014 Page 19 of 43


Course Module of Advanced Java Programming

Thread Management with the Executor Framework


 Recommended that you use the Executor interface to manage the execution of Runnable objects
 An Executor object creates and manages a thread pool to execute Runnables
 Executor advantages over creating threads yourself
 Reuse existing threads to eliminate new thread overhead
 Improve performance by optimizing the number of threads to ensure that the processor stays busy
 Executor method execute accepts a Runnable as an argument
 Assigns each Runnable it receives to one of the available threads in the thread pool
 If none available, creates a new thread or waits for a thread to become available
 Recommended that you use the Executor interface to manage the execution of Runnable objects
 An Executor object creates and manages a thread pool to execute Runnables
 Executor advantages over creating threads yourself
o Reuse existing threads to eliminate new thread overhead
o Improve performance by optimizing the number of threads to ensure that the processor stays busy
 Executor method execute accepts a Runnable as an argument
o Assigns each Runnable it receives to one of the available threads in the thread pool
o If none available, creates a new thread or waits for a thread to become available

3.6 Thread Synchronization


 When multiple threads share an object and one or more of them modify that object, indeterminate results
may occur unless access to the shared object is managed properly.
 The problem can be solved by giving only one thread at a time exclusive access to code that manipulates the
shared object.
 During that time, other threads desiring to manipulate the object are kept waiting.
 When the thread with exclusive access to the object finishes manipulating it, one of the threads that was
waiting is allowed to proceed.
 This process, called thread synchronization, coordinates access to shared data by multiple concurrent
threads.
 By synchronizing threads, you can ensure that each thread accessing a shared object excludes all other
threads from doing so simultaneously—this is called mutual exclusion.
 Java provides built-in monitors to implement synchronization
 Every object has a monitor and a monitor lock.

Set by Gizatie D. DTU, Computer Science department, Junuary, 2014 Page 20 of 43


Course Module of Advanced Java Programming

 Monitor ensures that its object’ s monitor lock is held by a maximum of only one thread at any time Can be
used to enforce mutual exclusion
To enforce mutual exclusion
 Thread must acquire the lock before it can proceed with its operation
 other threads attempting to perform an operation that requires the same lock will be blocked until the first
thread releases the lock
synchronized statement
Enforces mutual exclusion on a block of code
synchronized ( object )
{
statements
} // end synchronized statement
where object is the object whose monitor lock will be acquired (normally this)
 A synchronized method is equivalent to a synchronized statement that encloses the entire body of a
method

3.6.1 Unsynchronized Data Sharing


 ExecutorService method awaitTermination forces a program to wait for threads to complete execution
 returns control to its caller either when all tasks executing in the ExecutorService complete or when the
specified timeout elapses
 If all tasks complete before awaitTermination times out, returns true; otherwise returns false

3.6.2 Synchronized Data Sharing—Making Operations Atomic


 Simulate atomicity by ensuring that only one thread carries out a set of operations at a time
 Immutable data shared across threads
– declare the corresponding data fields final to indicate that variables’ values will not change after
they are initialized
3.7 Producer/Consumer Relationship without Synchronization
 Multithreaded producer/consumer relationship
– Producer thread generates data and places it in a shared object called a buffer
– Consumer thread reads data from the buffer
 Operations on the buffer data shared by a producer and a consumer are state dependent
– Should proceed only if the buffer is in the correct state
– If in a not-full state, the producer may produce
– If in a not-empty state, the consumer may consume
 Must synchronize access to ensure that data is written to the buffer or read from the buffer only if the
buffer is in the proper state

Set by Gizatie D. DTU, Computer Science department, Junuary, 2014 Page 21 of 43


Course Module of Advanced Java Programming

3.8 Producer/Consumer Relationship with Synchronization


 Can implement a shared using the synchronized keyword and Object methods wait, notify and notifyAll
– can be used with conditions to make threads wait when they cannot perform their tasks
 A thread that cannot continue with its task until some condition is satisfied can call Object method wait
– releases the monitor lock on the object
– thread waits in the waiting state while the other threads try to enter the object’ s synchronized
statement(s) or method(s)
 A thread that completes or satisfies the condition on which another thread may be waiting can call
Object method notify
– allows a waiting thread to transition to the runnable state
– the thread that was transitioned can attempt to reacquire the monitor lock
 If a thread calls notifyAll, all the threads waiting for the monitor lock become eligible to reacquire the
lock
4.9Producer/Consumer Relationship: Bounded Buffers
 Bounded buffer is used to minimize the amount of waiting time for threads that share resources and
operate at the same average speeds
 If the buffer is full, the producer should wait until a consumer consumed a value to free an element in
the buffer.
 If the buffer is empty at any given time, a consumer thread must wait until the producer produces
another value.
 ArrayBlockingQueue is a bounded buffer that handles all of the synchronization details for you
4.10 Producer/Consumer Relationship: The Lock and Condition Interfaces
 Give programmers more precise control over thread synchronization, but are more complicated to use
 Any object can contain a reference to an object that implements the Lock interface (of package
java.util.concurrent.locks)
 A thread calls the Lock’ s lock method to acquire the lock.
 Once a Lock has been obtained by one thread, the Lock object will not allow another thread to obtain the
Lock until the first thread releases the Lock (by calling the Lock’ s unlock method).
 All other threads attempting to obtain that Lock on a locked object are placed in the waiting state
3.10 Producer/Consumer Relationship: The Lock and Condition Interfaces
 Class ReentrantLock (of package java.util.concurrent.locks) is a basic implementation of the Lock
interface.
 ReentrantLock constructor takes a boolean argument that specifies whether the lock has a fairness policy
– If true, the ReentrantLock’ s fairness policy is “ the longest-waiting thread will acquire the lock
when it is available” —prevents starvation
– If false, there is no guarantee as to which waiting thread will acquire the lock when it is available
 A thread that owns a Lock and determines that it cannot continue with its task until some condition is
satisfied can wait on a condition object
 Lock objects allow you to explicitly declare the condition objects on which a thread may need to wait
 Condition objects
– Associated with a specific Lock
– Created by calling a Lock’ s newCondition method
 To wait on a Condition object, call the Condition ’ s await method
– immediately releases the associated Lock and places the thread in the waiting state for that
Condition

Set by Gizatie D. DTU, Computer Science department, Junuary, 2014 Page 22 of 43


Course Module of Advanced Java Programming

 Another thread can call Condition method signal to allow a thread in that Condition’ s waiting state to
return to the runnable state
– Default implementation of Condition signals the longest-waiting thread
 Condition method signalAll transitions all the threads waiting for that condition to the runnable state
 When finished with a shared object, thread must call unlock to release the Lock
 Lock and Condition may be preferable to using the synchronized keyword
– Lock objects allow you to interrupt waiting threads or to specify a timeout for waiting to acquire
a lock
– Lock object is not constrained to be acquired and released in the same block of code
 Condition objects can be used to specify multiple conditions on which threads may wait
– Possible to indicate to waiting threads that a specific condition object is now true
3.11 Deadlock
 Deadlock occurs when a waiting thread (let us call this thread1) cannot proceed because it is waiting
(either directly or indirectly) for another thread (let us call this thread2) to proceed, while simultaneously
thread2 cannot proceed because it is waiting (either directly or indirectly) for thread1 to proceed. The
two threads are waiting for each other, so the actions that would enable each thread to continue
execution can never occur.
IV. Assessments:
1. The keyword -------------indicates that only one thread at a time should execute on an object.
1. Synchronization
2. Create new child of thread.
// Create a new thread.
class NewThread implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}

// This is the entry point for the second thread.


public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}

Set by Gizatie D. DTU, Computer Science department, Junuary, 2014 Page 23 of 43


Course Module of Advanced Java Programming

System.out.println("Exiting child thread.");


}
}

class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(100);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}

UNIT FOUR
Networking in Java
Unit description
In these unit Networking in java, connecting to server, connection client with server, sockets, ports and
URLs be covers, To deliver these contents brain storming and presentation, group discussion, demonstration
methods will be used. And the way of assessment will takes place in the form of questioning and answer,
group work, individual assignment, lab assignment, test
I. Objectives: At the end of this unit, students will be able to:

 To understand Java networking with URLs, sockets and datagrams.


 Differentiate Establishing of server using stream sockets and without sockets
 To implement Java networking applications by using sockets and datagrams.
 To understand how to implement Java clients and servers that communicates with one another.
 .Differentiate sockets, ports and URLs
II. Contents:

 Networking, server and client


 Manipulating of URLs
 Establishing of server using stream sockets and with out sockets

Set by Gizatie D. DTU, Computer Science department, Junuary, 2014 Page 24 of 43


Course Module of Advanced Java Programming

 sockets, ports and URLs


III. Method of Teaching: brain storming, gap lecture, group discussion group presentation.

4.1 Introduction:
Brian storming: what is Networking?
Interactive lecture:
 Java provides:-Stream-based communications
 a process establishes a connection to another process. While the connection is in place, data
flows between the processes
 Connection-based protocol - Uses TCP
 Packet-based communications
 Individual packets transmitted
 Connectionless service - Uses UDP (User Datagram Protocol)
 Client-server relationship
 Client requests some action be performed
 Server performs the action and responds to client
 Request-response model
 Common implementation: Web browsers and Web servers
4.2 Manipulating URLs
 The HTTP protocol uses URIs to locate data on the Internet.
 A URI that represents a document is called a URL
• URL Refer to files, directories and complex objects
 Applet method getAppletContext returns a reference to an AppletContext object that represents the
browser in which the applet is executing.
 AppletContext method showDocument receives a URL as an argument and passes it to the
AppletContext (i.e., the browser), which displays the web resource associated with that URL.
 param tag specifies parameters in HTML document.
 Each parameter has a name and a value and the applet can read these values and use them to customize
itself.
. 4.3 Reading a File on a Web Server
 Swing GUI component JEditorPane Retrieves files from a Web server at a given URI
 JEditorPane method setPage downloads the document specified by its argument and displays it in the
JEditorPane.
 If an HTML document is displayed in a JEditorPane and the user clicks a hyperlink, the JEditorPane
generates a HyperlinkEvent and notifies all registered HyperlinkListeners of the event.
Three event types
 HyperlinkEvent.EventType.ACTIVATED
 HyperlinkEvent.EventType.ENTERED
 HyperlinkEvent.EventType.EXITED
4.4 Establishing a Simple Server Using Stream Sockets
Five steps to create a simple server in Java
Step 1: Create ServerSocket object
– ServerSocket server = new ServerSocket( portNumber, queueLength );
– Register an available port
– Specify a maximum number of clients

Set by Gizatie D. DTU, Computer Science department, Junuary, 2014 Page 25 of 43


Course Module of Advanced Java Programming

– Handshake point
– Binding the server to the port
• Only one client can be bound to a specific port
Step 2: Server listens for client connection
– Server blocks until client connects
– Socket connection = server.accept();
Step 3: Sending and receiving data
– OutputStream to send and InputStream to receive data
• Method getOutputStream returns Socket’ s OutputStream
• Methods getInputstream returns Socket’ s InputStream
Step 4: Process phase
– Server and Client communicate via streams
Step 5: Close streams and connections
– Method close
• Port numbers can be between 0 and 65,535. Most operating systems reserve port numbers below 1024
for system services.
4.5 Establishing a Simple Client Using Stream Sockets
• Four steps to create a simple client in Java
– Step 1: Create a Socket to connect to server
Socket connection = new Socket ( serverAddress, port );
– Step 2: Obtain Socket’ s InputStream and Outputstream
– Step 3: Process information communicated
– Step 4: Close streams and connection
4.6 Client/Server Interaction with Stream Socket Connections
 Client/server chat application
– Uses stream sockets
– Server waits for a client connection attempt
– Client connects to the server
• Send and receive messages
– Client or server terminates the connection
– Server waits for the next client to connect
Software Engineering Observation 24.5
When using an ObjectOutputStream and ObjectInputStream to send and receive data over a network
connection, always create the ObjectOutputStream first and flush the stream so that the client’ s
ObjectInputStream can prepare to receive the data. This is required only for networking applications that
communicate using ObjectOutputStream and ObjectInputStream.
4.7 Connectionless Client/Server Interaction with Datagrams
• Connectionless transmission with datagrams
– No connection maintained with other computer
– Break message into separate pieces and send as packets
– Message arrive in order, out of order or not at all
– Receiver puts messages in order and reads them
Presentation:
 Read more on this chapter and present in the class
IV. Assessments:

Set by Gizatie D. DTU, Computer Science department, Junuary, 2014 Page 26 of 43


Course Module of Advanced Java Programming

1. Create a program the server that run with in two sockets?


Some Possible answers:
import java.net.ServerSocket;
import java.net.Socket;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
class Server{
public static void main(String [] args){
Socket s1, s2;
ExecutorService executor = Executors.newCachedThreadPool();
try{
ServerSocket server = new ServerSocket(40000, 10);
System.out.println(" Server is waiting for connection between DATABASE and Client...");
s1 = server.accept();
s2 = server.accept();
executor.execute(new Client(s1, s2, 1));
executor.execute(new Client(s2, s1, 2));
System.out.println("DATABASE and CLIENT are CONNECTED succefully!!!");
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
}
class Client implements Runnable{
Socket s1, s2;
int count;
public Client(Socket socket1, Socket socket2, int n){
s1 = socket1;
s2 = socket2;
count = n;
}
public void run(){
boolean end = true;
String rcvMsg;
try{
ObjectOutputStream outC2 = new ObjectOutputStream(s2.getOutputStream());
outC2.flush();
ObjectInputStream inC1 = new ObjectInputStream(s1.getInputStream());
while(end){
rcvMsg = inC1.readUTF();
if(rcvMsg.equals("stop"))
System.exit(0);
outC2.writeUTF(rcvMsg);

Set by Gizatie D. DTU, Computer Science department, Junuary, 2014 Page 27 of 43


Course Module of Advanced Java Programming

outC2.flush();
}
outC2.close();
inC1.close();
s2.close();
s1.close();
}
catch(IOException e){
System.out.println(e.getMessage());
}
}
}

UNIT FIVE
Remote Method Invocation (RMI)
Unit description
In this unit RMI, RMI Registry, Remote Interface and Implementing of RMI are contents to be covers, to
deliver these contents brain storming and gap lecture, group discussion, demonstration methods will be used.
And the way of assessment will takes place in the form of questioning and answer, group work, individual
assignment, lab assignment, test
I. Objectives: At the end of this unit students will be able to:
 Explain RMI?
 list the RMI Registry
 Write the program of Remote Interface and Implementation of RMI?
I. Contents:

 RMI
 types of RMI Registry
 RMI Implementation and Remote Interface

Set by Gizatie D. DTU, Computer Science department, Junuary, 2014 Page 28 of 43


Course Module of Advanced Java Programming

I. Method of Teaching : brain storming , gap lecture, group discussion, and Presentation
Brian storming: what is RMI?
5.1 Introduction:
 Remote Method Invocation (RMI) is a Java mechanism similar to RPCs.
 RMI allows a Java program on one machine to invoke a method on a remote object.

 Allows remote method calls

 Objects in different programs can communicate


 Method calls appear same as those in same program

 Based on Remote Procedure Calls (RPC)

 Allows procedural program (like C) to call function on another computer


 Performs networking and marshalling of data (packaging arguments and return
values)
 Not compatible with objects
 Interface Definition Language required - describe functions

 RMI is Java's implementation of RPC

 Register method as remotely accessible


 Client can look up method and receive a reference
 Use reference to call method
 Syntax same as a normal method call

 Marshalling of data

 Can transfer objects as well


 Class ObjectOutputStream converts Serializable object into stream of bytes:-
Transmit across network
 Class ObjectInputStream reconstructs object

Set by Gizatie D. DTU, Computer Science department, Junuary, 2014 Page 29 of 43


Course Module of Advanced Java Programming

Marshalling Parameters

RMI and RPC differs in two ways:

1. RPCs support procedural programming whereby only remote procedures or functions


may be called. RMI is object based: It supports invocation of methods on remote
objects.
2. The parameters to remote procedures are ordinary data structures in RPC; with RMI it is
possible to pass objects as parameters to remote methods.

• If the marshaled parameters are local (non remote) objects, they are passed by copy
using a technique known as object serialization.
– Object serialization allowed the state of an object to be written to a byte stream.

Set by Gizatie D. DTU, Computer Science department, Junuary, 2014 Page 30 of 43


Course Module of Advanced Java Programming

Case Study: Creating a Distributed System with RMI


RMI example
– Downloads weather information from National Weather Service website
http://iwin.nws.noaa.gov/iwin/us/traveler.html
• Note: Format of website changed several times, if example does not work do
the appropriate modifications.
– Store information on a server
• Request information through remote method calls
• Four major steps
– Define remote interface
• Describes client/server communication
– Define server application to implement remote interface
• Same name as remote interface, ends with Impl
– Define client application that uses remote interface reference
• Interacts with server implementation
– Compile and execute server and client

5.2 Defining the Remote Interface


 First step
– Define remote interface that describes remote methods
• Client calls remote methods, server implements them
 To create a remote interface
– Define interface that extends interface Remote (java.rmi)
• Tagging interface - no methods to define
• An object of a class that implements interface Remote directly or indirectly
is a remote object and can be accesses from any JVM.
– Each method in Remote interface must throw RemoteException
• Potential network errors
 Interface TemperatureServer
– Extends Remote
– Describes method getWeatherInfo
5.3 Implementing the Remote Interface
• Define TemperatureServerImpl
– Implements Remote interface TemperatureServer
– Client interacts with TemperatureServerImpl object
– Uses array of WeatherInfo objects to store data
• Copy sent to client when calls getWeatherInfo
Assessment:
Write a program of RMI to create the different interface ?
import java.rmi.*;

Set by Gizatie D. DTU, Computer Science department, Junuary, 2014 Page 31 of 43


Course Module of Advanced Java Programming

import java.util.Vector;

public interface ServerIntf extends Remote


{
public boolean validUser(String user, String pass) throws RemoteException;
public Vector retNotDoneSubList(String sid) throws RemoteException;
public Vector retTakenSubList(String sid) throws RemoteException;
public void regSub(Vector v, String sid) throws RemoteException;
}

UNIT SIX
Accessing Databases with JDBC
Unit description

Set by Gizatie D. DTU, Computer Science department, Junuary, 2014 Page 32 of 43


Course Module of Advanced Java Programming

In this unit Database system and SQL, Basic concepts of JDBC programming ,Installing and setting of JDBC,
Executing of database queries and RowsetInterface contents to be covers, to deliver these contents brain
storming and gap lecture, group discussion, demonstration methods will be used. And the way of assessment
will takes place in the form of questioning and answer, group work, individual assignment, lab assignment, test
II. Objectives: At the end of this unit students will be able to:
 Explain Database system and SQL?
 Explain the basic concepts of JDBC programming?
 To use Prepared Statements to create precompiled SQL statements with parameters.
 Display the database queries?
 To use the RowSet interface from package javax.sql to manipulate databases.
I. Contents:


Database system and SQL

Manipulating of database with JDBC

Basic concepts of JDBC Programming

Database queries

Row Set Interface
I. Method of Teaching : brain storming , gap lecture, group discussion, and Presentation
Brian storming: what is Database system?
6.1 Introduction:
A database is an organized collection of data. There are many different strategies for organizing data to facilitate
easy access and manipulation. A database management system (DBMS) provides mechanisms for storing,
organizing, retrieving and modifying data for many users. Database management systems allow for the access
and storage of data without concern for the internal representation of data.
Today’ s most popular database systems are relational databases, where the data is stored without consideration
of its physical structure. A language called SQL—pronounced “ sequel,” or as its individual letters—is the
international standard language used almost universally with relational databases to perform queries (i.e., to
request information that satisfies given criteria) and to manipulate data.
Information stored in the database is in tables and the language used to query information from the database is
SQL .Using SQL we can query a table based on the requirement.
CRUD OPERATIONS
• CRUD stands for create, read, update, delete.
• Create statement in SQL looks like
– Create table mytab ( mynum number , name varchar2(25));
– READ statement looks like :-Select * from mytab where mynum=25;
– UPDATE statement looks as :-Update mytab set mynum=88 where mynum=25;
– DELETE statement like:-Delete from mytab where mynum=88;

 Programs connect to, and interact with, relational databases via an interface—software that facilitates
communications between a database management system and a program.
 Java programs communicate with databases and manipulate their data using the JDBC API.
 A JDBC driver enables Java applications to connect to a database in a particular DBMS and allows you to
retrieve and manipulate database data.
 Package java.sql contains classes and interfaces for accessing relational databases in Java.

Set by Gizatie D. DTU, Computer Science department, Junuary, 2014 Page 33 of 43


Course Module of Advanced Java Programming

 Using the JDBC API enables developers to change the underlying DBMS without modifying the Java code
that accesses the database.

6.2 Manipulating Databases with JDBC


 The program must load the database driver before connecting to the database.
 The static method forName of class Class is used to load the class for the database driver.
 Class.forName("com.mysql.jdbc.Driver“)
 An object of interface Connection manages the connection between a Java program and a database.
 Method getConnection of class DriverManager attempts to connect to a database specified by its URL
argument. DriverManager.getConnection(URL, userName, password)
 The URL helps the program locate the database. The URL includes the protocol , the subprotocol for
communication and the name of the database.URL = "jdbc:mysql://localhost/books"
 Connection method createStatement creates an object of type Statement which is used to submit SQL
statements to the db.
 Statement method executeQuery executes a query and returns an object of interface ResultSet containing
the query result.
 ResultSet methods enable a program to manipulate query results.
 A ResultSetMetaData object describes a ResultSet’ s contents and can be used to obtain information about
the ResultSet column names and types.
 ResultSet method next() positions the ResultSet cursor to the next row in the ResultSet and returns true if
it is able to position to the next row.
 ResultSet row and column numbers start at 1.
 ResultSetMetaData method getColumnType returns a constant integer from class Types (package java.sql)
indicating the type of the data for a specific column.
 Connection method createStatement has an overloaded version that takes two arguments: the result type
and the result concurrency.

Set by Gizatie D. DTU, Computer Science department, Junuary, 2014 Page 34 of 43


Course Module of Advanced Java Programming

 The result type specifies whether the ResultSet’ s cursor is able to scroll in both directions or forward only
and whether the ResultSet is sensitive to changes.
 The result concurrency specifies whether the ResultSet can be updated with Result-Set’ s update methods.

Notes

 Most major database vendors provide their own JDBC database drivers, and many third-party vendors
provide JDBC drivers as well.
 Initially, a ResultSet cursor is positioned before the first row. Attempting to access a ResultSet’ s contents
before positioning the ResultSet cursor to the first row with method next causes a SQLException.
 Specifying column number 0 when obtaining values from a ResultSet causes a SQLException.
 Each Statement object can open only one ResultSet object at a time. When a Statement returns a new
ResultSet, the Statement closes the prior ResultSet. To use multiple ResultSets in parallel, separate
Statement objects must return the ResultSets.

RDBMS Database URL format


MySQL jdbc:mysql://hostname:portNumber/databaseName

ORACLE jdbc:oracle:thin:@hostname:portNumber:databaseName

DB2 jdbc:db2:hostname:portNumber/databaseName

Java DB/Apache Derby jdbc:derby:dataBaseName (embedded)


jdbc:derby://hostname:portNumber/databaseName (network)

Microsoft SQL Server jdbc:sqlserver://hostname:portNumber;databaseName=dataBaseName

Sybase jdbc:sybase:Tds:hostname:portNumber/databaseName

Popular JDBC database URL formats.

6.3 Displaying query results in JTable


 The JTable can be set up to display any data model which implements the TableModel interface
 The TableModel interface specifies the methods the JTable will use to interrogate a tabular data model.
 TableModel method
 getColumnClass Returns the most specific superclass for all the cell values in the column.
 getColumnCount returns the number of columns in the model.
 getColumnName returns the name of the column in the model
 getRowCount returns the number of rows in the model
 getValueAt returns the Object at a particular row and column of the model’ s underlying ResultSet.
 ResultSetMetaData method

Set by Gizatie D. DTU, Computer Science department, Junuary, 2014 Page 35 of 43


Course Module of Advanced Java Programming

 getColumnClassName obtains the fully qualified class name of the specified column.
 getColumnName obtains the column name from the ResultSet.
 ResultSet method
 absolute positions the ResultSet cursor at a specific row.
 AbstractTableModel method
 fireTableStructureChanged notifies any JTable using a particular TableModel object as its model that
the data in the model has changed.
 Some JDBC drivers do not support scrollable ResultSets. In such cases, the driver typically returns a
ResultSet in which the cursor can move only forward.

ResultSet static
type constant Description

TYPE_FORWARD_ONLY Specifies that a ResultSet’s cursor can move only in the forward
direction (i.e., from the first row to the last row in the ResultSet).
TYPE_SCROLL_INSENSITIVE Specifies that a ResultSet’s cursor can scroll in either direction
and that the changes made to the ResultSet during ResultSet
processing are not reflected in the ResultSet unless the program
queries the database again.
TYPE_SCROLL_SENSITIVE Specifies that a ResultSet’s cursor can scroll in either direction
and that the changes made to the ResultSet during ResultSet
processing are reflected immediately in the ResultSet.

ResultSet constants for specifying ResultSet type


Some JDBC drivers do not support updatable ResultSets. In such cases, the driver typically
returns a read-only ResultSet.
ResultSet static
Description
concurrency constant
CONCUR_READ_ONLY Specifies that a ResultSet cannot be updated (i.e., changes to the ResultSet
contents cannot be reflected in the database with ResultSet’s update methods).
CONCUR_UPDATABLE Specifies that a ResultSet can be updated (i.e., changes to the ResultSet
contents can be reflected in the database with ResultSet’s update methods).

ResultSet constants for specifying result properties.


6.4 RowSet Interface
 Interface RowSet
 Configures the database connection automatically
 Prepares query statements automatically
 Provides set methods to specify the properties needed to establish a connection
 Part of the javax.sql package
 Two types of RowSet
 Connected RowSet :-Connects to database once and remain connected

Set by Gizatie D. DTU, Computer Science department, Junuary, 2014 Page 36 of 43


Course Module of Advanced Java Programming

 Disconnected RowSet :-Connects to database, executes a query and then closes connection
 Package javax.sql.rowset
 JdbcRowSet
• Connected RowSet
• Wrapper around a ResultSet
• Scrollable and updatable by default
 CachedRowSet
• Disconnected RowSet
• Cache the data of ResultSet in memory
• Scrollable and updatable by default
• Serializable :-Can be passed between Java application
• Limitation:-Amount of data that can be stored in memory is limited
 A RowSet can provide scrolling capability for drivers that do not support scrollable ResultSets.
6.5 PreparedStatements
 Program must specify the parameter values by using the PreparedStatement interface’ s set methods.
 For the preceding query, both parameters are strings that can be set with PreparedStatement method
setString as follows:
PreparedStatement pstmt = con.preparestatement(select * from mytab where num=?” );pstmt.setInt(1,” 11” );
PreparedStatement authorBooks = connection.prepareStatement("SELECT lastName, firstName, title " +
"FROM authors INNER JOIN authorISBN " +
"ON authors.authorID=authorISBN.authorID " +
"INNER JOIN titles " +
"ON authorISBN.isbn=titles.isbn " +
"WHERE lastName = ? AND firstName = ?" );
 setString automatically escapes String parameter values as necessary (e.g., the quote in the name O’ Brien)
 More info at java.sun.com/javase/6/docs/api/java/sql/PreparedStatement.html
 PreparedStatements are more efficient than Statements when executing SQL statements multiple times and
with different parameter values.
6.6 Stored Procedures
 Stored procedures
– Store SQL statements in a database
– Invoke SQL statements by programs accessing the database
 JDBC enables programs to invoke stored procedures using objects that implement interface
CallableStatement.
 CallableStatement can specify input parameters, like PreparedStatement.
 In addition, CallableStatement can specify output parameters in which a stored procedure can place
return values.
 The interface CallableStatement provides a uniform interface for specifying input and output parameters
for stored procedures and for invoking stored procedures in different databases.
6.7 Transaction Processing
 Many applications require guarantees that a series of database insertions, updates and deletions executes
properly before the applications continue processing the next database operation
 Enables a program that interacts with a database to treat a database operation (or set of operations) as a
single operation
– Known as an atomic operation or a transaction
– At the end of a transaction, decide to commit or roll back

Set by Gizatie D. DTU, Computer Science department, Junuary, 2014 Page 37 of 43


Course Module of Advanced Java Programming

 Committing a transaction finalizes the database operation(s); all insertions, updates and deletions
performed as part of the transaction cannot be reversed without performing a new database operation
 Rolling back a transaction leaves the database in its state prior to the database operation
Group discussion:
Discuses on SQL statements by giving different sql commands .
III. Assessments:
1. Create apreapared statement that create table
//using prepared statements
import java.sql.*;
import java.util.Scanner;
class CreatgTable{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String title, no;
int credit;
byte addMoreRecord = 1;
try{
Connection con = DriverManager.getConnection(
"jdbc:odbc:student");
Statement stmt = con.createStatement();
String str = "CREATE TABLE t2(Title VARCHAR(30),"
+ "No VARCHAR(12)primary key, Credit int)";
int i = stmt.executeUpdate(str);
PreparedStatement pstmt = con.prepareStatement(
"INSERT INTO t2 (Title, No, Credit)"
+ " VALUES (?, ?, ?)");
do{
System.out.println("Enter course title");
title = sc.nextLine();
System.out.println("Enter course no");
no = sc.nextLine();
System.out.println("Enter credit hour");
credit = sc.nextInt();
pstmt.setString(1, title);
pstmt.setString(2, no);
pstmt.setInt(3, credit);
pstmt.executeUpdate();
System.out.println("Enter 0 to stop,"
+ " 1 to add more record");
addMoreRecord = sc.nextByte();
sc.nextLine();
}while(addMoreRecord !=0);
}
catch(Exception e){System.out.println(e.getClass());}
}
}

Set by Gizatie D. DTU, Computer Science department, Junuary, 2014 Page 38 of 43


Course Module of Advanced Java Programming

Unit Seven
Introduction To Servlets
Unit description
In this unit the Overview of servlets , HTTP requests and application of servlets contents to be covers, to deliver
these contents brain storming and gap lecture, group discussion, demonstration methods will be used. And the
way of assessment will takes place in the form of questioning and answer, group work, individual assignment,
lab assignment, test
II. Objectives: At the end of this unit students will be able to:
 Define Servlets?
 Explain the Basic HTTP requests?
 Explain Application of Servlets?
III. Contents:
 Introduction To Servlets
 HTTP requests
 Application of servlet
I. Method of Teaching : brain storming , gap lecture, group discussion, and Presentation
7.1 Introduction
Brian storming: what is Servlet?
 Servlets
– Analog to applets:-Execute on server's machine, supported by most web servers
– Demonstrate communication via HTTP protocol
• Client sends HTTP request
• Server receives request, servlets process it
• Results returned (HTML document, images, binary data)
 The Servlet API
– Implemented by all servlets
– Many methods invoked automatically by server
• Similar to applets (paint, init, start, etc.)
– abstract classes that implement Servlet
• GenericServlet (javax.servlet)
• HTTPServlet (javax.servlet.http)
– Examples in chapter extend HTTPServlet
• Methods
– void init( ServletConfig config )
• Automatically called, argument provided
• Methods
– ServletConfig getServletConfig()
• Returns reference to object, gives access to config info
– void service ( ServletRequest request, ServletResponse response )
• Key method in all servlets
• Provide access to input and output streams
– Read from and send to client
– void destroy()
• Cleanup method, called when servlet exiting

Set by Gizatie D. DTU, Computer Science department, Junuary, 2014 Page 39 of 43


Course Module of Advanced Java Programming

7.2 Life Cycle of Servlet

HttpServlet Class
• HttpServlet
– Base class for web-based servlets
– Overrides method service
• Request methods:
– GET - retrieve HTML documents or image
– POST - send server data from HTML form
– Methods doGet and doPost respond to GET and POST
• Called by service
• Receive HttpServletRequest and HttpServletResponse (return void) objects
HttpServletRequest Interface
• HttpServletRequest interface
– Object passed to doGet and doPost
– Extends ServletRequest
• Methods
– String getParameter( String name )
• Returns value of parameter name (part of GET or POST)
– Enumeration getParameterNames()
• Returns names of parameters (POST)
– String[] getParameterValues( String name )
• Returns array of strings containing values of a parameter
– Cookie[] getCookies()
• Returns array of Cookie objects, can be used to identify client

Set by Gizatie D. DTU, Computer Science department, Junuary, 2014 Page 40 of 43


Course Module of Advanced Java Programming

HttpServletResponse Interface
• HttpServletResponse
– Object passed to doGet and doPost
– Extends ServletResponse
• Methods
– void addCookie( Cookie cookie )
• Add Cookie to header of response to client
– ServletOutputStream getOutputStream()
• Gets byte-based output stream, send binary data to client
– PrintWriter getWriter()
• Gets character-based output stream, send text to client
– void setContentType( String type )
• Specify MIME type of the response (Multipurpose Internet Mail Extensions)
• MIME type “ text/html” indicates that response is HTML document.
• Helps display data
7.3 Handling HTTP GET Requests
• HTTP GET requests
– Usually gets content of specified URL
• Usually HTML document (web page)
• Example servlet
– Handles HTTP GET requests
– User clicks Get Page button in HTML document
• GET request sent to servlet HTTPGetServlet
– Servlet dynamically creates HTML document displaying "Welcome to Servlets!"
• Running servlets
– Must be running on a server
• Check documentation for how to install servlets
• Tomcat web server
• Apache Tomcat
• Port number
– Where server waits for client (handshake point)
– Client must specify proper port number
• Integers 1 - 65535, 1024 and below usually reserved
– Well-known port numbers
• Web servers - port 80 default
• JSDK/Apache Tomcat 4.0 Webserver- port 8080
• Change in default.cfg (server.port=8080)
Handling HTTP get Requests Containing Data
 Responds to a get request that contains data
7.4 Handling HTTP POST Requests
 HTTP POST
– Used to post data to server-side form handler (i.e. surveys)
– Both GET and POST can supply parameters
 Example servlet
– Survey

Set by Gizatie D. DTU, Computer Science department, Junuary, 2014 Page 41 of 43


Course Module of Advanced Java Programming

• Store results in file on server


– User selects radio button, presses Submit
• Browser sends POST request to servlet
– Servlet updates responses
• Displays cumulative results
Redirecting Requests to Other Resources
 Servlet RedirectServlet
– Redirects the request to a different resource
7.5 Multitier Applications: Using JDBC from a Servlet
 Servlets and databases
– Communicate via JDBC
• Connect to databases in general manner
• Use SQL-based queries
 Three tier distributed applications
– User interface
• Often in HTML, sometimes applets
• HTML preferred, more portable
– Business logic (middle tier)
• Accesses database
– Database access
– Three tiers may be on separate computers
• Web servers for middle tier
 Servlets
– Method init
• Called exactly once, before client requests
• Initialization parameters
– Method destroy
• Called automatically, cleanup method
• Close files, connections to databases, etc.
 Example servlet
– Guest book to register for mailing lists
– HTML document first tier
• Get data from user
– Use servlet as middle tier
• Provides access to database
• Set up connection in init
– Microsoft Access database (third tier)

Assessment
1. Write a servlet program that contains the methods of Handling HTTP get and post
requests ?

Set by Gizatie D. DTU, Computer Science department, Junuary, 2014 Page 42 of 43


Course Module of Advanced Java Programming

Methods of course delivery


 75% of active learning (Brain storming, Group discussion, presentation…) with 25% of interactive
lecture.

Assessment methods
The assessment methods are listed below by considering both domains of education and hierarch of
learning.
Formative Assessments:
 Attendance & class activity .…............. 5 %
 Quiz………………………….………....5 %
 Group assignment (Lab.)......……...........5 %
 Individual assignment …………….........5%
 Test………...…………………….......... 30%
 Project………...……………………....... 20%

Sub Total…………………..................... 70 %
Summative Assessment:
 Final Exam …… ………………...........30 %

Total ……………………..................... 100 %

Set by Gizatie D. DTU, Computer Science department, Junuary, 2014 Page 43 of 43

You might also like