165
T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 1 of 165 INDEX SR.NO TOPIC PAGE NO. From To 1 JFC AND SWINGS 3 55 2 JDBC 56 79

INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

  • Upload
    others

  • View
    12

  • Download
    0

Embed Size (px)

Citation preview

Page 1: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 1 of 165

INDEX

SR.NO TOPIC

PAGE NO.

From To

1 JFC AND SWINGS 3 55

2 JDBC 56 79

Page 2: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 2 of 165

Syllabus

Introduction to JFC and Swing, Features of the Java Foundation Classes, Swing API

Components, JComponent Class, Windows, Dialog Boxes, and Panels, Labels, Buttons, Check

Boxes, Menus, Toolbars, Implementing Action interface, Pane, JScrollPane, Desktop pane,

Scrollbars, Lists and Combo Boxes, Text-Entry Components, Colors and File Choosers, Tables

and Trees, Printing with 2D API and Java Print Service API.

JDBC Introduction, JDBC Architecture, Types of JDBC Drivers, The Connectivity Model, The

java.sql package, Navigating the ResultSet object’s contents, Manipulating records of a ResultSet

object through User Interface , The JDBC Exception classes, Database Connectivity, Data

Manipulation (using Prepared Statements, Joins, Transactions, Stored Procedures), Data

navigation.

Page 3: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 3 of 165

CHAPTER 1: SWINGS

Topic Covered:

Introduction to JFC and Swing, Features of the Java Foundation Classes, Swing API

Components, JComponent Class, Windows, Dialog Boxes, and Panels, Labels, Buttons, Check

Boxes, Menus, Toolbars, Implementing Action interface, Pane, JScrollPane, Desktop pane,

Scrollbars, Lists and Combo Boxes, Text-Entry Components, Colors and File Choosers, Tables

and Trees, Printing with 2D API and Java Print Service API.

Q. What Are the Java Foundation Classes (JFC)?

The Java Foundation Classes (JFC) are a suite of libraries designed to assist programmers in creating enterprise applications with Java. The Swing API is only one of five libraries that make up the JFC. The Java Foundation Classes also consist of the Abstract Window Toolkit (AWT), the Accessibility API, the 2D API, and enhanced support for drag-and-drop capabilities. While the Swing API is the primary focus of this book, here is a brief introduction to the other elements in the JFC:

AWT The Abstract Window Toolkit is the basic GUI toolkit shipped with all versions of the Java

Development Kit. While Swing does not reuse any of the older AWT components, it does build off of the lightweight component facilities introduced in AWT 1.1.

Accessibility The accessibility package provides assistance to users who have trouble with traditional user

interfaces. Accessibility tools can be used in conjunction with devices such as audible text readers or braille keyboards to allow direct access to the Swing components. Accessibility is split into two parts: the Accessibility API, which is shipped with the Swing distribution, and the Accessibility Utilities API, distributed separately. All Swing components contain support for accessibility, so this book dedicates an entire chapter to accessibility design and use.

2D API The 2D API contains classes for implementing various painting styles, complex shapes, fonts,

and colors. This Java package is loosely based on APIs that were licensed from IBM's Taligent division. The 2D API classes are not part of Swing, so they will not be covered in this book.

Drag and Drop Drag and drop is one of the more common metaphors used in graphical interfaces today. The

user is allowed to click and "hold" a GUI object, moving it to another window or frame in the desktop with predictable results. The Drag and Drop API allows users to implement droppable elements that transfer information between Java applications and native applications. Drag and Drop is also not part of Swing, so we will not discuss it here.

Figure 1.1 enumerates the various components of the Java Foundation Classes. Because part of the Accessibility API is shipped with the Swing distribution, we show it overlapping Swing.

Figure 1.1. The five APIs of the Java Foundation Classes

Page 4: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 4 of 165

Introduction to the Swing Set

Swing is a subset of the Java Foundation Classes (JFC)

The name "Swing" is not an acronym

An effort to incorporate many of the features in Netscape's IFC as well as some aspects of IBM stuff

First released in March of 1998 with nearly 250 classes and 80 interfaces

Swing is not a replacement for the AWT. - Needed to support truly architecture independent interfaces - Contains more powerful components

Why bother? - Increased acceptance (many more supported architectures) - AWT based on architecture-specific widgits.

Q. Explain Swing Features?

Pluggable Look and Feel(LnFs) o LnFs are increasingly important o Similar look of underlying environment o LnFs for UNIX, Windows, Apple. (Default is called Metal) o LnFs can be changed at run-time

Lightweight Components o Lightweight - components which are not dependant on native source to render o Heavyweights are unweildy because:

- Equivalent components may act differently on different platforms - LnF is tied to the host environment

Many new Components o Tables o Trees o Sliders o Progress Bars o Internal Frames o Text Components (Very nice)

Tool tips

Support for undo/redo

Support for Multiple Document Interfaces (MDI) with InternalFrames

Page 5: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 5 of 165

Q. Write a short note on JComponent Class?

JComponent Class

The base class for all Swing components except top-level containers.

The root of the Swing component hierarchy. Adds Swing-specific features such as tooltips and

support for double-buffering.

With the exception of top-level containers, all Swing components whose names begin with "J"

descend from the JComponent class. For example, JPanel, JScrollPane, JButton, and JTable all

inherit from JComponent. However, JFrame and JDialog don't because they implement top-level

containers.

The JComponent class extends the Container class, which itself extends Component. The Component class includes everything from providing layout hints to supporting painting and events. The Container class has support for adding components to the container and laying them out. This section's API tables summarize the most often used methods of Component and Container, as well as of JComponent.

JComponent Features

The JComponent class provides the following functionality to its descendants:

Tool tips

Painting and borders

Application-wide pluggable look and feel

Custom properties

Support for layout

Support for accessibility

Support for drag and drop

Page 6: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 6 of 165

Double buffering

Key bindings

Tool tips

By specifying a string with the setToolTipText method, you can provide help to users of a

component. When the cursor pauses over the component, the specified string is displayed in a

small window that appears near the component. See How to Use Tool Tips for more information.

Painting and borders

The setBorder method allows you to specify the border that a component displays around its

edges. To paint the inside of a component, override the paintComponent method. See How to

Use Borders and Performing Custom Painting for details.

Application-wide pluggable look and feel

Behind the scenes, each JComponent object has a corresponding ComponentUI object that

performs all the drawing, event handling, size determination, and so on for that JComponent.

Exactly which ComponentUI object is used depends on the current look and feel, which you can

set using the UIManager.setLookAndFeel method. See How to Set the Look and Feel for details.

Custom properties

You can associate one or more properties (name/object pairs) with any JComponent. For

example, a layout manager might use properties to associate a constraints object with each

JComponent it manages. You put and get properties using the putClientProperty and

getClientProperty methods. For general information about properties, see Properties.

Support for layout

Although the Component class provides layout hint methods such as getPreferredSize and

getAlignmentX, it doesn't provide any way to set these layout hints, short of creating a subclass

and overriding the methods. To give you another way to set layout hints, the JComponent class

adds setter methods — setMinimumSize, setMaximumSize, setAlignmentX, and setAlignmentY.

See Laying Out Components Within a Container for more information.

Support for accessibility

The JComponent class provides API and basic functionality to help assistive technologies such

as screen readers get information from Swing components, For more information about

accessibility, see How to Support Assistive Technologies.

Support for drag and drop

The JComponent class provides API to set a component's transfer handler, which is the basis for

Swing's drag and drop support. See Introduction to DnD for details.

Double buffering

Double buffering smooths on-screen painting. For details, see Performing Custom Painting.

Key bindings

Page 7: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 7 of 165

This feature makes components react when the user presses a key on the keyboard. For

example, in many look and feels when a button has the focus, typing the Space key is equivalent

to a mouse click on the button. The look and feel automatically sets up the bindings between

pressing and releasing the Space key and the resulting effects on the button. For more

information about key bindings, see How to Use Key Bindings.

Windows

Class Window

java.lang.Object

java.awt.Component

java.awt.Container

java.awt.Window All Implemented Interfaces:

Accessible, ImageObserver, MenuContainer, Serializable

Direct Known Subclasses:

BasicToolBarUI.DragWindow, Dialog, Frame, JWindow

public class Window

extends Container

implements Accessible

A Window object is a top-level window with no borders and no menubar. The default layout for a window is BorderLayout.

A window must have either a frame, dialog, or another window defined as its owner when it's constructed.

In a multi-screen environment, you can create a Window on a different screen device by constructing the Window with Window(Window, GraphicsConfiguration). The GraphicsConfiguration object is one of the GraphicsConfiguration objects of the target screen device.

In a virtual device multi-screen environment in which the desktop area could span multiple physical screen devices, the bounds of all configurations are relative to the virtual device coordinate system. The origin of the virtual-coordinate system is at the upper left-hand corner of the primary physical screen. Depending on the location of the primary screen in the virtual device, negative coordinates are possible, as shown in the following figure.

Page 8: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 8 of 165

In such an environment, when calling setLocation, you must pass a virtual coordinate to this method. Similarly, calling getLocationOnScreen on a Window returns virtual device coordinates. Call the getBounds method of a GraphicsConfiguration to find its origin in the virtual coordinate system.

The following code sets the location of a Window at (10, 10) relative to the origin of the physical screen of the corresponding GraphicsConfiguration. If the bounds of the GraphicsConfiguration is not taken into account, the Window location would be set at (10, 10) relative to the virtual-coordinate system and would appear on the primary physical screen, which might be different from the physical screen of the specified GraphicsConfiguration.

Window w = new Window(Window owner, GraphicsConfiguration gc); Rectangle bounds = gc.getBounds(); w.setLocation(10 + bounds.x, 10 + bounds.y);

Windows are capable of generating the following WindowEvents: WindowOpened, WindowClosed, WindowGainedFocus, WindowLostFocus.

The JWindow Class JWindow is an extension of java.awt.Window that uses a JRootPane as its single component. Other than this core distinction, JWindow does not change anything defined by the Window class. In AWT, one common reason for using the Window class was to create a popup menu. Since Swing explicitly provides a JPopupMenu class (see Chapter 14), there is no need to extend JWindow for this purpose. The only time you'll use JWindow is if you've got something that needs to be displayed in its own window without the adornments added by JFrame. Remember, this means that the window can only be moved or closed programmatically (or via the user's platform-specific window manager controls, if available). One possible use for JWindow would be to display a splash screen when an application is starting up. Many programs display such a screen, possibly containing copyright information, resource

loading status, etc. Here's such a program:

The JFrame Class The most common Swing container for Java applications is the JFrame. Like java.awt.Frame, JFrame provides a top-level window with a title, border, and other platform-specific adornments (e.g., minimize, maximize, and close buttons). Because it uses a JRootPane as its only child, working with a JFrame is slightly different than working with an AWT Frame. An empty JFrame is shown in Figure 8.9.

Page 9: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 9 of 165

The primary difference is that calls to add() must be replaced with calls to getContentPane().add(). In fact, the addImpl() method is implemented so that a call made directly to add() throws an Error. Table 1-1 Useful JFrame Constructors and Methods Constructor Description JFrame() Creates a new frame with no title. JFrame(String title) Creates a new frame with the specified title. Method Description void add(Component c) Adds the specified component to the frame. JMenuBar getJMenuBar() Gets the menu for this frame. void pack() Adjusts the size of the frame to fit the components you’ve added to it. void remove(Component c) Removes the specified component from the frame. void Sets the action taken when the user closes the setDefaultCloseOperation frame. You should almost always specify JFrame.EXIT_ON_CLOSE. void setIconImage Sets the icon displayed when the frame is (Icon image) minimized. void setLayout Sets the layout manager used to control how (LayoutManager layout)

components are arranged when the frame is displayed. The default is the BorderLayout manager.

void setLocation Sets the x and y position of the frame on-screen. (int x, int y) The top-left corner of the screen is 0, 0. void setLocationRelativeTo Centers the frame on-screen if the parameter is (Component c) null. void setResizeable Sets whether or not the size of the frame can be (boolean value) changed by the user. The default setting is true (the frame can be resized). void setSize(int width, int height) Sets the size of the frame to the specified width and height. void setJMenuBar(JMenuBar) Sets the menu for this frame. At the minimum, you want to set a title for a new frame, set the frame’s size so it’s large enough to see any components you add to it (by default, the frame is zero pixels wide and zero pixels high, so it isn’t very useful), and call the setVisible method to make the frame visible. One way to do these three things is to create an instance of the JFrame class and set its properties using statements like this:

JFrame frame = new JFrame(“This is the title”); frame.setSize(350, 260); frame.setVisible(true);

However, creating a frame by declaring a class that extends the JFrame class is more common. Then, you call these methods in the constructor, as I describe in the next section. By default, the user can change the size of a frame. If you want to fix the size of your frame so the user can’t change it, just call setResizeable(false). To get you started with Swing, Listing 1-1 shows a Swing version of the classic Hello, World! program, using nothing but a frame. If you run this program, the frame shown in Figure 1-1 is displayed on-screen. As you can see, the frame’s title bar contains the text “Hello, World!” The purpose of this seemingly pointless little program is to illustrate one solution to the first problem you encounter when you work with Swing: The main method is a static method, but Swing frames are objects. So, you have to figure out how to get your program out of a static context. This program does that by creating the application as a class that extends JFrame. Then, the main method calls the class constructor, in effect creating an instance of itself. That’s all the main method does; the real work of this application is done by the constructor.

Page 10: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 10 of 165

LISTING 1-1:THE SWING VERSION OF THE HELLO,WORLD! PROGRAM import javax.swing.*; ➞ 1 public class HelloFrame extends JFrame ➞ 3 { public static void main(String[] args) ➞ 5 { new HelloFrame(); ➞ 7 } public HelloFrame() ➞ 10 { this.setSize(200,100); ➞ 12 this.setDefaultCloseOperation( ➞ 13 JFrame.EXIT_ON_CLOSE); this.setTitle(“Hello World!”); ➞ 15 this.setVisible(true); ➞ 16 } } The following paragraphs describe most of the features of this program: ➞ 1 The program starts with an import statement that imports all the classes in the javax.swing package. Most of the Swing classes are defined in this package. However, you may have to import other classes as well, depending on what GUI features your program uses. ➞ 3 The class for this application, named JFrame, extends a Swing class named JFrame. A class that extends JFrame is often called a frame class. The JFrame class defines a basic frame in which you can display GUI components, such as labels and text boxes. All Swing applications need at least one class that extends JFrame. ➞ 5 Swing applications are still Java applications, and all Java applications need a static main method that starts the application. So the first method listed in this class is the main method. ➞ 7 The first (and only) statement of the main method creates a new instance of the HelloFrame class. Unlike console applications, Swing applications can’t run in a static context. As a result, the main purpose of the static main method in a Swing application is to create an instance of the application’s frame class. ➞10 When an instance of the HelloFrame class is created in line 7, the constructor that starts on this line is executed. The main job of the constructor for a frame class is to set the options for the frame and create any GUI components that are displayed in the frame. ➞12 The first option that this constructor sets is the size of the frame. To do that, it calls the setSize method. The parameters specify that the frame should be 200 pixels wide and 100 pixels high. (A pixel is one of the little dots that makes up the image on a computer screen. Pixel is short for picture element, but that won’t be on the test.) ➞13 The next option this constructor sets is what to do if the user closes the frame by clicking its Close button, which usually appears in the upper-right hand corner of the frame. By default, clicking the Close button hides the frame but doesn’t terminate the application. As a result, the application’s main thread (the one that’s still running in a static context via the main method) keeps running for a while. Eventually, Java figures out that nothing’s happening and shuts the application down. But the application exits more cleanly if you use the setDefaultCloseOperation to set the close operation to JFrame.EXIT_ON_CLOSE. That causes the program to terminate when the frame is closed. ➞15 The next statement uses the setTitle method to set the title of the frame. ➞16 The last statement in the constructor calls the setVisible method with a parameter value of true, which makes the frame visible onscreen. If you leave this statement out, the frame is created but the user never sees it.

Show Dialog Box in Java - Swing Dialogs

Message dialog box is used to display informative messages to the user. In this section we will use JOptionPane class to display the message Dialog box. Our program display "Click Me" button on the

Page 11: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 11 of 165

window and when user clicks on it program displays Message box with "OK" button and message "Roseindia.net".

When you run the program following window will be displayed:

When you click on "Click Me" button, following Message is displayed:

Program description:

JOptionPane Class:

In non-swing application we were using System.in class for input or output some text or numeric values but now in the swing application we can use JOptionPane to show the output or show the message. This way of inputting or outputting works very efficiently in the Swing Applications. The window for showing message for input or output makes your application very innovative.

Page 12: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 12 of 165

JOptionPane class is available in the javax.swing.*; package. This class provide various types of message dialog box as follows:

A simple message dialog box which has only one button i.e. "Ok". This type of message dialog box is used only for showing the appropriate message and user can finish the message dialog box by clicking the "Ok" button.

A message dialog box which has two or three buttons. You can set several values for viewing several message dialog box as follows: 1.) "Yes" and "No" 2.) "Yes", "No" and "Cancel" 3.) "Ok", and "Cancel"

A input dialog box which contains two buttons "Ok" and "Cancel".

The JOptionPane class has three methods as follows:

showMessageDialog(): First is the showMessageDialog() method which is used to display a simple message.

showInputDialog(): Second is the showInputDialog() method which is used to display a prompt for inputting. This method returns a String value which is entered by you.

showConfirmDialog(): And the last or third method is the showConfirmDialog() which asks the user for confirmation (Yes/No) by displaying message. This method return a numeric value either 0 or 1. If you click on the "Yes" button then the method returns 1 otherwise 0.

How program Works:

This program illustrates you how to show a message dialog box when you click on the button.

showMessageDialog(): This method is used to show a message dialog box which contains some text messages. This is being used with two arguments in the program where the first argument is the parent object in which the dialog box opens and another is the message which has to be shown.

Here is the code of the program:

import javax.swing.*;

import java.awt.event.*;

public class ShowDialogBox{

JFrame frame;

public static void main(String[] args){

ShowDialogBox db = new ShowDialogBox();

}

public ShowDialogBox(){

frame = new JFrame("Show Message Dialog");

JButton button = new JButton("Click Me");

button.addActionListener(new MyAction());

frame.add(button);

frame.setSize(400, 400);

frame.setVisible(true);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Page 13: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 13 of 165

}

public class MyAction implements ActionListener{

public void actionPerformed(ActionEvent e){

JOptionPane.showMessageDialog(frame,"Roseindia.net");

}

}

}

Show Message and Confirm Dialog Box - Swing Dialogs

This section show you how to display several types of message box. There are three types of message dialog box that you can use in your swing applications, example of each type of dialog boxes are provided here. When your run the program, it will display a frame with three buttons. Once you click on the first button then the simple message box will open which holds only "Ok" button as shown below:

If you click on the second button then the confirm dialog box will open which asks for "Ok" and "Cancel".

Page 14: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 14 of 165

If you click on the "Ok" button then a message dialog box will open with message "You clicked on "Ok" button" like this

otherwise message dialog box will open with text "You clicked on "Cancel" button like this

If you click on the third button from the main window or frame then a confirm message dialog box will open with three button i.e. the "Yes", "No" and "Cancel" like the following image:

Page 15: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 15 of 165

For this purposes two methods have been used:

showMessageDialog(): Above method shows a simple message dialog box which holds only one button i.e. "Ok" button. This method takes four arguments in which, first is the parent object name, second is the message as string, third is the title of the message dialog box as string and the last is the type of the message dialog box.

showConfirmDialog(): Above method asks from the user by displaying a message dialog box which contains more than one button. Depending on the parameter passed it can be "Ok" and "Cancel" or "Yes", "No" and "Cancel". This method returns the integer value.

In Part II, you saw how to build user interfaces with the AWT classes. Here, we will take a tour of a supercharged alternative called Swing. Swing is a set of classes that provides more powerful and flexible components than are possible with the AWT. In addition to the familiar components, such as buttons, check boxes, and labels, Swing supplies several exciting additions, including tabbed panes, scroll panes, trees, and tables. Even familiar components such as buttons have more capabilities in Swing. For example, a button may have both an image and a text string associated with it. Also, the image can be changed as the state of the button changes. Unlike AWT components, Swing components are not implemented by platform-specific code. Instead, they are written entirely in Java and, therefore, are platform-independent. The term lightweight is used to describe such elements. The number of classes and interfaces in the Swing packages is substantial, and this chapter provides an overview of just a few. Swing is an area that you will want to explore further on your own. The Swing component classes that are used in this book are shown here: Class Description AbstractButton Abstract superclass for Swing buttons. ButtonGroup Encapsulates a mutually exclusive set of buttons. ImageIcon Encapsulates an icon. JApplet The Swing version of Applet. JButton The Swing push button class. JCheckBox The Swing check box class. JComboBox Encapsulates a combo box (an combination of a drop-down list and text field). JLabel The Swing version of a label. JRadioButton The Swing version of a radio button. JScrollPane Encapsulates a scrollable window. JTabbedPane Encapsulates a tabbed window. JTable Encapsulates a table-based control. JTextField The Swing version of a text field. JTree Encapsulates a tree-based control.SOFTWARE DEVELOPMENT USING JAVA The Swing-related classes are contained in javax.swing and its subpackages, such as javax.swing.tree. Many other Swing-related classes and interfaces exist that are not examined in this chapter. The remainder of this chapter examines various Swing components and illustrates them through sample applets. The JMenuBar Class Swing's JMenuBar class supersedes the older AWT MenuBar class. This class creates a horizontal menubar component with zero or more menus attached to it. JMenuBar uses the DefaultSingleSelectionModel as its data model; this is because the user can raise, or activate, only one of its menus at a given time. Once the mouse pointer leaves that menu, the class removes the menu from the screen (or cancels it, in Swing lingo), and all menus again become eligible to be raised. Figure 14.4 shows the class hierarchy for the JMenuBar component.

Page 16: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 16 of 165

You can add JMenu objects from the menubar with the add() method of the JMenuBar class. JMenuBar then assigns an integer index based on the order in which the menus were added. The menubar displays the menus from left to right on the bar according to their assigned index. There is one exception: the help menu. You are allowed to mark one menu as the help menu; the location of the help menu is up to the look-and-feel. Icons and Labels In Swing, icons are encapsulated by the ImageIcon class, which paints an icon from an image. Two of its constructors are shown here: ImageIcon(String filename) ImageIcon(URL url) The first form uses the image in the file named filename. The second form uses the image in the resource identified by url. The ImageIcon class implements the Icon interface that declares the methods shown here: Method Description int getIconHeight( ) Returns the height of the icon in pixels. int getIconWidth( ) Returns the width of the icon in pixels. void paintIcon(Component comp, Graphics g, int x, int y) Paints the icon at position x, y on the graphics context g. Additional information about the paint operation can be provided in comp. Swing labels are instances of the JLabel class, which extends JComponent. It can display text and/or an icon. Some of its constructors are shown here: JLabel(Icon i) Label(String s) JLabel(String s, Icon i, int align) Here, s and i are the text and icon used for the label. The align argument is either LEFT, RIGHT, CENTER, LEADING, or TRAILING. These constants are defined in the SwingConstants interface, along with several others used by the Swing classes. The icon and text associated with the label can be read and written by the following methods: Icon getIcon( ) String getText( ) void setIcon(Icon i) void setText(String s) Here, i and s are the icon and text, respectively. The following example illustrates how to create and display a label containing both an icon and a string. The applet begins by getting its content pane. Next, an ImageIcon object is created for the file france.gif. This is used as the second argument to the JLabel constructor. The first and last arguments for the JLabel constructor are the label text and the alignment. Finally, the label is added to the content pane. import java.awt.*;

Page 17: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 17 of 165

import javax.swing.*; /*G JAVA <applet code="JLabelDemo" width=250 height=150> </applet> */ public class JLabelDemo extends JApplet { public void init() { // Get content pane Container contentPane = getContentPane(); // Create an icon ImageIcon ii = new ImageIcon("france.gif"); // Create a label JLabel jl = new JLabel("France", ii, JLabel.CENTER); // Add label to the content pane contentPane.add(jl); } } Output from this applet is shown here:

Buttons Swing buttons provide features that are not found in the Button class defined by the AWT. For example, you can associate an icon with a Swing button. Swing buttons are subclasses of the AbstractButton class, which extends JComponent. AbstractButton contains many methods that allow you to control the behavior of buttons, check boxes, and radio buttons. For example, you can define different icons that are displayed for the component when it is disabled, pressed, or selected. Another icon can be used as a rollover icon, which is displayed when the mouse is positioned over that component. The following are the methods that control this behavior: void setDisabledIcon(Icon di) void setPressedIcon(Icon pi) void setSelectedIcon(Icon si) void setRolloverIcon(Icon ri) Here, di, pi, si, and ri are the icons to be used for these different conditions. The text associated with a button can be read and written via the following methods:

String getText( ) void setText(String s)

Here, s is the text to be associated with the button. Concrete subclasses of AbstractButton generate action events when they are pressed. Listeners register and unregister for these events via the methods shown here:

void addActionListener(ActionListener al) void removeActionListener(ActionListener al)

Here, al is the action listener. AbstractButton is a superclass for push buttons, check boxes, and radio buttons.

Page 18: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 18 of 165

Each is examined next. 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. The following example displays four push buttons and a text field. Each button displays an icon that represents the flag of a country. When a button is pressed, the name of that country is displayed in the text field. The applet begins by getting its content pane and setting the layout manager of that pane. Four image buttons are created and added to the content pane. Next, the applet is registered to receive action events that are generated by the buttons. A text field is then created and added to the applet. Finally, a handler for action events displays the command string that is associated with the button. The text field is used to present this string. import java.awt.*; import java.awt.event.*; import javax.swing.*; /* <applet code="JButtonDemo" width=250 height=300> </applet> */ public class JButtonDemo extends JApplet implements ActionListener { JTextField jtf; public void init() { // Get content pane Container contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); // Add buttons to content pane ImageIcon france = new ImageIcon("france.gif"); JButton jb = new JButton(france); jb.setActionCommand("France"); jb.addActionListener(this); contentPane.add(jb); ImageIcon germany = new ImageIcon("germany.gif"); jb = new JButton(germany); jb.setActionCommand("Germany"); jb.addActionListener(this); contentPane.add(jb); ImageIcon italy = new ImageIcon("italy.gif"); jb = new JButton(italy); jb.setActionCommand("Italy"); jb.addActionListener(this); contentPane.add(jb); ImageIcon japan = new ImageIcon("japan.gif"); jb = new JButton(japan); jb.setActionCommand("Japan"); jb.addActionListener(this); contentPane.add(jb); // Add text field to content pane jtf = new JTextField(15); contentPane.add(jtf); } public void actionPerformed(ActionEvent ae) { jtf.setText(ae.getActionCommand());

Page 19: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 19 of 165

} } Output from this applet is shown here:

Check Boxes The JCheckBox class, which provides the functionality of a check box, 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: 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. The following example illustrates how to create an applet that displays four check boxes and a text field. When a check box is pressed, its text is displayed in the text field. The content pane for the JApplet object is obtained, and a flow layout is assigned as its layout manager. Next, four check boxes are added to the content pane, and icons are assigned for the normal, rollover, and selected states. The applet is then registered to receive item events. Finally, a text field is added to the content pane. 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. import java.awt.*; import java.awt.event.*; import javax.swing.*; /*

Page 20: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 20 of 165

<applet code="JCheckBoxDemo" width=400 height=50> </applet> */ public class JCheckBoxDemo extends JApplet implements ItemListener { JTextField jtf; public void init() { USING JAVA // Get content pane Container contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); // Create icons ImageIcon normal = new ImageIcon("normal.gif"); ImageIcon rollover = new ImageIcon("rollover.gif"); ImageIcon selected = new ImageIcon("selected.gif"); // Add check boxes to the content pane JCheckBox cb = new JCheckBox("C", normal); cb.setRolloverIcon(rollover); cb.setSelectedIcon(selected); cb.addItemListener(this); contentPane.add(cb); cb = new JCheckBox("C++", normal); cb.setRolloverIcon(rollover); cb.setSelectedIcon(selected); cb.addItemListener(this); contentPane.add(cb); cb = new JCheckBox("Java", normal); cb.setRolloverIcon(rollover); cb.setSelectedIcon(selected); cb.addItemListener(this); contentPane.add(cb); cb = new JCheckBox("Perl", normal); cb.setRolloverIcon(rollover); cb.setSelectedIcon(selected); cb.addItemListener(this); contentPane.add(cb); // Add text field to the content pane jtf = new JTextField(15); contentPane.add(jtf); } public void itemStateChanged(ItemEvent ie) { JCheckBox cb = (JCheckBox)ie.getItem(); jtf.setText(cb.getText()); } } Output from this applet is shown here:

Page 21: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 21 of 165

How to Use Tool Bars

A JToolBar is a container that groups several components — usually buttons with icons — into a row or

column. Often, tool bars provide easy access to functionality that is also in menus. How to Use Actions

describes how to provide the same functionality in menu items and tool bar buttons.

The following images show an application named ToolBarDemo that contains a tool bar above a text area. Click the Launch button to run ToolBarDemo using Java™ Web Start (download JDK 6). Alternatively, to compile and run it yourself, consult the example index.

By default, the user can drag the tool bar to another edge of its container or out into a window of its own. The next figure shows how the application looks after the user has dragged the tool bar to the right edge of its container.

For the drag behavior to work correctly, the tool bar must be in a container that uses the BorderLayout layout manager. The component that the tool bar affects is generally in the center of the container. The tool bar must be the only other component in the container, and it must not be in the center.

The next figure shows how the application looks after the user has dragged the tool bar outside its window.

Page 22: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 22 of 165

The following code creates the tool bar and adds it to a container. You can find the entire program in ToolBarDemo.java.

public class ToolBarDemo extends JPanel implements ActionListener { ... public ToolBarDemo() { super(new BorderLayout()); ... JToolBar toolBar = new JToolBar("Still draggable"); addButtons(toolBar); ... setPreferredSize(new Dimension(450, 130)); add(toolBar, BorderLayout.PAGE_START); add(scrollPane, BorderLayout.CENTER); } ... } This code positions the tool bar above the scroll pane by placing both components in a panel controlled

by a border layout, with the tool bar in the PAGE_START position and the scroll pane in the CENTER

position. Because the scroll pane is in the center and no other components except the tool bar are in the

container, by default the tool bar can be dragged to other edges of the container. The tool bar can also be

dragged out into its own window, in which case the window has the title "Still draggable", as specified by

the JToolBar constructor.

Creating Tool Bar Buttons

The buttons in the tool bar are ordinary JButton instances that use images from the Java Look and Feel

Graphics Repository. Use images from the Java Look and Feel Graphics Repository if your tool bar has

the Java look and feel.

Here is the code that creates the buttons and adds them to the tool bar.

protected void addButtons(JToolBar toolBar) { JButton button = null; //first button button = makeNavigationButton("Back24", PREVIOUS, "Back to previous something-or-other", "Previous"); toolBar.add(button); //second button button = makeNavigationButton("Up24", UP, "Up to something-or-other", "Up"); toolBar.add(button); ...//similar code for creating and adding the third button... } protected JButton makeNavigationButton(String imageName, String actionCommand, String toolTipText, String altText) {

Page 23: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 23 of 165

//Look for the image. String imgLocation = "images/" + imageName + ".gif"; URL imageURL = ToolBarDemo.class.getResource(imgLocation); //Create and initialize the button. JButton button = new JButton(); button.setActionCommand(actionCommand); button.setToolTipText(toolTipText); button.addActionListener(this); if (imageURL != null) { //image found button.setIcon(new ImageIcon(imageURL, altText)); } else { //no image found button.setText(altText); System.err.println("Resource not found: " + imgLocation); } return button; } The first call to makeNavigationButton creates the image for the first button, using the 24x24 "Back"

navigation image in the graphics repository.

Besides finding the image for the button, the makeNavigationButton method also creates the button, sets the strings for its action command and tool tip text, and adds the action listener for the button. If the image is missing, the method prints an error message and adds text to the button, so that the button is still usable.

Note: If any buttons in your tool bar duplicate the functionality of other components, such as menu items,

you should probably create and add the tool bar buttons as described in How to Use Actions.

Customizing Tool Bars

By adding a few lines of code to the preceding example, we can demonstrate some more tool bar features:

Using setFloatable(false) to make a tool bar immovable.

Using setRollover(true) to visually indicate tool bar buttons when the user passes over them with the cursor.

Adding a separator to a tool bar.

Adding a non-button component to a tool bar.

You can see these features by running ToolBarDemo2. Click the Launch button to run ToolBarDemo2

using Java™ Web Start (download JDK 6). Alternatively, to compile and run it yourself, consult the

example index.

You can find the entire code for this program in ToolBarDemo2.java. Below you can see a picture of a

new UI using these customized features.

Page 24: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 24 of 165

Because the tool bar can no longer be dragged, it no longer has bumps at its left edge. Here is the code that turns off dragging:

toolBar.setFloatable(false);

The tool bar is in rollover mode, so the button under the cursor has a visual indicator. The kind of visual indicator depends on the look and feel. For example, the Metal look and feel uses a gradient effect to indicate the button under the cursor while other types of look and feel use borders for this purpose. Here is the code that sets rollover mode:

toolBar.setRollover(true);

Another visible difference in the example above is that the tool bar contains two new components, which are preceded by a blank space called a separator. Here is the code that adds the separator:

toolBar.addSeparator(); Here is the code that adds the new components:

//fourth button button = new JButton("Another button"); ... toolBar.add(button); //fifth component is NOT a button! JTextField textField = new JTextField("A text field"); ... toolBar.add(textField); You can easily make the tool bar components either top-aligned or bottom-aligned instead of centered by

invoking the setAlignmentY method. For example, to align the tops of all the components in a tool bar,

invoke setAlignmentY(TOP_ALIGNMENT) on each component. Similarly, you can use the setAlignmentX

method to specify the alignment of components when the tool bar is vertical. This layout flexibility is

possible because tool bars use BoxLayout to position their components. For more information, see How

to Use BoxLayout.

The Tool Bar API

The following table lists the commonly used JToolBar constructors and methods. Other methods you

might call are listed in the API tables in The JComponent Class.

Method or

Constructor Purpose

JToolBar() Creates a tool bar. The optional int parameter lets you specify the orientation; the

Page 25: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 25 of 165

JToolBar(int)

JToolBar(String)

JToolBar(String, int)

default is HORIZONTAL. The optional String parameter allows you to specify the title

of the tool bar's window if it is dragged outside of its container.

Component

add(Component)

Adds a component to the tool bar.

You can associate a button with an Action using the setAction(Action) method defined by the AbstractButton.

void addSeparator() Adds a separator to the end of the tool bar.

void

setFloatable(boolean)

boolean isFloatable()

The floatable property is true by default, and indicates that the user can drag the tool

bar out into a separate window. To turn off tool bar dragging, use

toolBar.setFloatable(false). Some types of look and feel might ignore this property.

void

setRollover(boolean)

boolean isRollover()

The rollover property is false by default. To make tool bar buttons be indicated visually

when the user passes over them with the cursor, set this property to true. Some types

of look and feel might ignore this property.

Examples That Use Tool Bars

This table lists examples that use JToolBar and points to where those examples are described.

Example Where

Described Notes

ToolBarDemo This page A basic tool bar with icon-only buttons.

ToolBarDemo2 This page Demonstrates a non-floatable tool bar in rollover mode that contains a

separator and a non-button component.

ActionDemo How to Use

Actions

Implements a tool bar using Action objects.

Radio Buttons 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:

Page 26: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 26 of 165

void add(AbstractButton ab) Here, ab is a reference to the button to be added to the group. The following example illustrates how to use radio buttons. Three radio buttons and one text field are created. When a radio button is pressed, its text is displayed in the text field. First, the content pane for the JApplet object is obtained and a flow layout is assigned as its layout manager. Next, three radio buttons are added to the content pane. Then, a button group is defined and the buttons are added to it. Finally, a text field is added to the content pane. Radio button presses generate action events that are handled by actionPerformed( ). The getActionCommand( ) method gets the text that is associated with a radio button and uses it to set the text field. import java.awt.*; import java.awt.event.*; import javax.swing.*; /* <applet code="JRadioButtonDemo" width=300 height=50> </applet> */ public class JRadioButtonDemo extends JApplet implements ActionListener { JTextField tf; public void init() { // Get content pane Container contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); // Add radio buttons to content pane JRadioButton b1 = new JRadioButton("A"); b1.addActionListener(this); contentPane.add(b1); JRadioButton b2 = new JRadioButton("B"); b2.addActionListener(this); contentPane.add(b2); JRadioButton b3 = new JRadioButton("C"); b3.addActionListener(this); contentPane.add(b3); // Define a button group ButtonGroup bg = new ButtonGroup(); bg.add(b1); bg.add(b2); bg.add(b3); // Create a text field and add it // to the content pane tf = new JTextField(5); contentPane.add(tf); } public void actionPerformed(ActionEvent ae) { tf.setText(ae.getActionCommand()); } } Output from this applet is shown here:

Page 27: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 27 of 165

Q. Write a Short note On Lists? List

A list is a graphical component from which the user can select choices. Lists typically display several items at a time, allowing the user to make either a single selection or multiple selections. In the event that the inventory of the list exceeds the component's display, the list is often coupled with a scrollbar to navigate through the entire contents.

AWT limited the contents of its List component to strings. The Swing JList component lifts this restriction. List elements can now be strings, images — any Java component capable of painting itself. Swing offers a wide degree of flexibility with list components; they can be as simple or as complex as the programmer's needs dictate.

Figure 7.1. A simple Swing list

Let's get our feet wet with a simple list. The following example uses the Swing list class, JList, to create a single-selection list composed only of strings. Figure 7.1 shows the result. // SimpleList.java //

import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SimpleList extends JPanel implements ActionListener { String label[] = { "Zero","One","Two","Three","Four","Five","Six", "Seven","Eight","Nine","Ten","Eleven" }; JList list; public SimpleList() { this.setLayout(new BorderLayout()); list = new JList(label); JScrollPane pane = new JScrollPane(list); JButton button = new JButton("Print"); button.addActionListener(this); add(pane, BorderLayout.CENTER); add(button, BorderLayout.SOUTH); } public static void main(String s[]) { JFrame frame = new JFrame("Simple List Example"); frame.addWindowListener(new BasicWindowMonitor()); frame.setContentPane(new SimpleList()); frame.setSize(250, 180); frame.setVisible(true); } public void actionPerformed(ActionEvent e) { int selected[] = list.getSelectedIndices(); System.out.println("Selected Elements: "); for (int i=0; i < selected.length; i++) { String element = (String)list.getModel().getElementAt(selected[i]); System.out.println(" " + element); }

Page 28: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 28 of 165

} }

Take a close look at the source. The first thing you might notice is that we were forced to embed the Swing list inside the viewport of a scroll pane object. Unlike AWT, the Swing JList class does not support scrolling through its data. Instead, it hands off the responsibility to the JScrollPane class. This is a significant design change from its predecessor, java.awt.List, which automatically manages a scrollbar for you. However, making a list the view of a scroll pane object fits better into the overall philosophy of Swing. This allows developers to reuse a customized scrollbar (or scroll pane) with their own lists, instead of simply accepting a default provided with the list component. It also enables autoscrolling support, so you can drag the mouse above or below the list, and its contents will scroll automatically. Try selecting multiple numbers (you can do this by holding down the "Shift" button while clicking). Note that you are only allowed to select one range, or continuous set of numbers, at a time. If you select a number beyond the current selection range, the range is extended to cover everything in between. The first number selected (i.e., the one you didn't have to hold "Shift" down for) becomes the initial endpoint for the range. This endpoint is called the anchor . The most recent selection (which is outlined) forms the second endpoint. This element is called the lead. Together, the anchor and the lead form a range of selections in the list, as shown in Figure 7.2. Figure 7.2. The anchor and lead positions in a single list selection

Finally, the example contains an actionPerformed() method that is called when the user presses the button. This method reports all the items that are currently selected in the list: Selected Elements:

Four Five Six Seven Eight

Q. Write a Short Note on Combo Boxes? Combo Boxes

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.

Page 29: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 29 of 165

The following example contains a combo box and a label. The label displays an icon. The combo box contains entries for “France”, “Germany”, “Italy”, and “Japan”.

When a country is selected, the label is updated to display the flag for that country.SOFTWARE DUSINA

import java.awt.*; import java.awt.event.*; import javax.swing.*; /* <applet code="JComboBoxDemo" width=300 height=100> </applet> */ public class JComboBoxDemo extends JApplet implements ItemListener { JLabel jl; ImageIcon france, germany, italy, japan; public void init() { // Get content pane Container contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); // Create a combo box and add it // to the panel JComboBox jc = new JComboBox(); jc.addItem("France"); jc.addItem("Germany"); jc.addItem("Italy"); jc.addItem("Japan"); jc.addItemListener(this); contentPane.add(jc); // Create label jl = new JLabel(new ImageIcon("france.gif")); contentPane.add(jl); } public void itemStateChanged(ItemEvent ie) { String s = (String)ie.getItem(); jl.setIcon(new ImageIcon(s + ".gif")); } } Output from this applet is shown here:

Q. Explain TabbedPanes And ScrollPanes? Tabbed Panes

A tabbed pane is a component that appears as a group of folders in a file cabinet. Each folder has a title. When a user selects a folder, its contents become visible. Only one of the folders may be selected at a time. Tabbed panes are commonly used for setting configuration options.

Tabbed panes are encapsulated by the JTabbedPane class, which extends

Page 30: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 30 of 165

JComponent. We will use its default constructor. Tabs are defined via the following method: void addTab(String str, Component comp)

Here, str is the title for the tab, and comp is the component that should be added to the tab. Typically, a JPanel or a subclass of it is added.

The general procedure to use a tabbed pane in an applet is outlined here: 1. Create a JTabbedPane object. 2. Call addTab( ) to add a tab to the pane. (The arguments to this method define the title of

the tab and the component it contains.) 3. Repeat step 2 for each tab. 4. Add the tabbed pane to the content pane of the applet.

The following example illustrates how to create a tabbed pane. The first tab is titled “Cities” and contains four buttons. Each button displays the name of a city. The second tab is titled “Colors” and contains three check boxes. Each check box displays the name of a color. The third tab is titled “Flavors” and contains one combo box. This enables the user to select one of three flavors.

import javax.swing.*; /* <applet code="JTabbedPaneDemo" width=400 height=100> </applet> */ public class JTabbedPaneDemo extends JApplet { public void init() { JTabbedPane jtp = new JTabbedPane(); jtp.addTab("Cities", new CitiesPanel()); jtp.addTab("Colors", new ColorsPanel()); jtp.addTab("Flavors", new FlavorsPanel()); getContentPane().add(jtp); } } class CitiesPanel extends JPanel { public CitiesPanel() { JButton b1 = new JButton("New York"); add(b1); JButton b2 = new JButton("London"); add(b2); JButton b3 = new JButton("Hong Kong"); add(b3); JButton b4 = new JButton("Tokyo"); add(b4); } } class ColorsPanel extends JPanel { public ColorsPanel() { JCheckBox cb1 = new JCheckBox("Red"); add(cb1); JCheckBox cb2 = new JCheckBox("Green"); add(cb2); JCheckBox cb3 = new JCheckBox("Blue"); add(cb3); } } class FlavorsPanel extends JPanel { public FlavorsPanel() { JComboBox jcb = new JComboBox(); jcb.addItem("Vanilla"); jcb.addItem("Chocolate"); jcb.addItem("Strawberry");

Page 31: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 31 of 165

add(jcb); } } Output from this applet is shown in the following three illustrations:

Scroll Panes

A scroll pane is a component that presents a rectangular area in which a component may be viewed. Horizontal and/or vertical scroll bars may be provided if necessary.

Scroll panes are implemented in Swing by the JScrollPane class, which extends JComponent. Some of its constructors are shown here:

JScrollPane(Component comp) JScrollPane(int vsb, int hsb) JScrollPane(Component comp, int vsb, int hsb)

Here, comp is the component to be added to the scroll pane. vsb and hsb are int constants that define when vertical and horizontal scroll bars for this scroll pane are shown.

These constants are defined by the ScrollPaneConstants interface. Some examples of these constants are described as follows:

Constant Description HORIZONTAL_SCROLLBAR_ALWAYS Always provide horizontal scroll bar HORIZONTAL_SCROLLBAR_AS_NEEDED Provide horizontal scroll bar, if needed VERTICAL_SCROLLBAR_ALWAYS Always provide vertical scroll bar VERTICAL_SCROLLBAR_AS_NEEDED Provide vertical scroll bar, if needed

Page 32: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 32 of 165

Here are the steps that you should follow to use a scroll pane in an applet: 1. Create a JComponent object. 2. Create a JScrollPane object. (The arguments to the constructor specify the component and the policies for vertical and horizontal scroll bars.)

3. Add the scroll pane to the content pane of the applet. The following example illustrates a scroll pane. First, the content pane of the JApplet object is obtained and a border layout is assigned as its layout manager. Next, a JPanel object is created and four hundred buttons are added to it, arranged into twenty columns. The panel is then added to a scroll pane, and the scroll pane is added to the content pane. This causes vertical and horizontal scroll bars to appear. You can use the scroll bars to scroll the buttons into view. import java.awt.*; import javax.swing.*; /*<applet code="JScrollPaneDemo" width=300 height=250> </applet> */ public class JScrollPaneDemo extends JApplet { public void init() { // Get content pane Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); // Add 400 buttons to a panel JPanel jp = new JPanel(); jp.setLayout(new GridLayout(20, 20)); int b = 0; for(int i = 0; i < 20; i++) { for(int j = 0; j < 20; j++) { jp.add(new JButton("Button " + b)); ++b; } } // Add panel to a scroll pane int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED; JScrollPane jsp = new JScrollPane(jp, v, h); // Add scroll pane to the content pane contentPane.add(jsp, BorderLayout.CENTER); } } Output from this applet is shown here:

Page 33: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 33 of 165

Q. Write a Short Note on Tree? Trees

A tree is a component that presents a hierarchical view of data. A user has the ability to expand or collapse individual subtrees in this display. Trees are implemented in Swing by the JTree class, which extends JComponent. Some of its constructors are shown here: JTree(Hashtable ht) JTree(Object obj[ ]) JTree(TreeNode tn) JTree(Vector v)

The first form creates a tree in which each element of the hash table ht is a child node. Each element of the array obj is a child node in the second form. The tree node tn is the root of

the tree in the third form. Finally, the last form uses the elements of vector v as child nodes. A JTree object generates events when a node is expanded or collapsed. The addTreeExpansionListener( ) and removeTreeExpansionListener( ) methods allow

listeners to register and unregister for these notifications. The signatures of these methods are shown here: void addTreeExpansionListener(TreeExpansionListener tel) void removeTreeExpansionListener(TreeExpansionListener tel)

Here, tel is the listener object. The getPathForLocation( ) method is used to translate a mouse click on a specific point of the tree to a tree path. Its signature is shown here:

TreePath getPathForLocation(int x, int y) Here, x and y are the coordinates at which the mouse is clicked. The return value is a TreePath object that encapsulates information about the tree node that was selected by the user. The TreePath class encapsulates information about a path to a particular node in a tree. It provides several constructors and methods. In this book, only the toString( ) method is used. It returns a string equivalent of the tree path. The TreeNode interface declares methods that obtain information about a tree node. For example, it is possible to obtain a reference to the parent node or an enumeration of the child nodes. The MutableTreeNode interface extends TreeNode. It declares methods that can insert and remove child nodes or change the parent node. The DefaultMutableTreeNode class implements the MutableTreeNode interface. It represents a node in a tree. One of its constructors is shown here:

DefaultMutableTreeNode(Object obj) Here, obj is the object to be enclosed in this tree node. The new tree node doesn’t have a parent or children. To create a hierarchy of tree nodes, the add( ) method of DefaultMutableTreeNode can be used. Its signature is shown here:

void add(MutableTreeNode child) Here, child is a mutable tree node that is to be added as a child to the current node. Tree expansion events are described by the class TreeExpansionEvent in the javax.swing.event package. The getPath( ) method of this class returns a TreePath object that describes the path to the changed node. Its signature is shown here: TreePath getPath( ) The TreeExpansionListener interface provides the following two methods:

void treeCollapsed(TreeExpansionEvent tee) void treeExpanded(TreeExpansionEvent tee)

Here, tee is the tree expansion event. The first method is called when a subtree is hidden, and the second method is called when a subtree becomes visible. Here are the steps that you should follow to use a tree in an applet: 1. Create a JTree object. 2. Create a JScrollPane object. (The arguments to the constructor specify the tree and the policies for vertical and horizontal scroll bars.) 3. Add the tree to the scroll pane. 4. Add the scroll pane to the content pane of the applet.

Page 34: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 34 of 165

The following example illustrates how to create a tree and recognize mouse clicks on it. The init( ) method gets the content pane for the applet. A DefaultMutableTreeNode object labeled “Options” is created. This is the top node of the tree hierarchy. Additional tree nodes are then created, and the add( ) method is called to connect these nodes to the tree. A reference to the top node in the tree is provided as the argument to the JTree constructor. The tree is then provided as the argument to the JScrollPane constructor. This scroll pane is then added to the applet. Next, a text field is created and added to the applet. Information about mouse click events is presented in this text field. To receive mouse events from the tree, the addMouseListener( ) method of the JTree object is called. The argument to this method is an anonymous inner class that extends MouseAdapter and overrides the mouseClicked( ) method.

The doMouseClicked( ) method processes mouse clicks. It calls getPathForLocation( ) to translate the coordinates of the mouse click into a TreePath object. If the mouse is clicked at a point that does not cause a node selection, the return value from this method is null. Otherwise, the tree path can be converted to a string and presented in the text field.

import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.tree.*; /* <applet code="JTreeEvents" width=400 height=200> </applet> */ public class JTreeEvents extends JApplet { JTree tree; JTextField jtf; public void init() { // Get content pane Container contentPane = getContentPane(); // Set layout manager contentPane.setLayout(new BorderLayout()); // Create top node of tree DefaultMutableTreeNode top = new DefaultMutableTreeNode("Options"); // Create subtree of "A" DefaultMutableTreeNode a = new DefaultMutableTreeNode("A"); top.add(a); DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1"); a.add(a1); DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2"); a.add(a2); // Create subtree of "B" DefaultMutableTreeNode b = new DefaultMutableTreeNode("B"); top.add(b); DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1"); b.add(b1); DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2"); b.add(b2); DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("B3"); b.add(b3); // Create tree tree = new JTree(top); // Add tree to a scroll pane int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED; JScrollPane jsp = new JScrollPane(tree, v, h); // Add scroll pane to the content pane contentPane.add(jsp, BorderLayout.CENTER);

Page 35: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 35 of 165

// Add text field to applet jtf = new JTextField("", 20); contentPane.add(jtf, BorderLayout.SOUTH); // Anonymous inner class to handle mouse clicks tree.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent me) { doMouseClicked(me); } }); } void doMouseClicked(MouseEvent me) { TreePath tp = tree.getPathForLocation(me.getX(), me.getY()); if(tp != null) jtf.setText(tp.toString()); else jtf.setText(""); } } Output from this applet is shown here:

The string presented in the text field describes the path from the top tree node to the selected node. Q. Write a short note on Tables? Tables

A table is a component that displays rows and columns of data. You can drag the cursor on column boundaries to resize columns. You can also drag a column to a new position. Tables are implemented by the JTable class, which extends JComponent.

One of its constructors is shown here: JTable(Object data[ ][ ], Object colHeads[ ]) Here, data is a two-dimensional array of the information to be presented, and colHeads is a one-dimensional array with the column headings.

Here are the steps for using a table in an applet: (1) Create a JTable object. (2) Create a JScrollPane object. (The arguments to the constructor specify the table and the

policies for vertical and horizontal scroll bars.) (3) Add the table to the scroll pane. (4) Add the scroll pane to the content pane of the applet. The following example illustrates how to create and use a table. The content pane of the JApplet object is obtained and a border layout is assigned as its layout manager.

A one-dimensional array of strings is created for the column headings. This table has three columns. A two-dimensional array of strings is created for the table cells. You can see that each element in the array is an array of three strings. These arrays are passed to the JTable

Page 36: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 36 of 165

constructor. The table is added to a scroll pane and then the scroll pane is added to the content pane.

import java.awt.*; import javax.swing.*; /* <applet code="JTableDemo" width=400 height=200> </applet> */ public class JTableDemo extends JApplet {VA public void init() { // Get content pane Container contentPane = getContentPane(); // Set layout manager contentPane.setLayout(new BorderLayout()); // Initialize column headings final String[] colHeads = { "Name", "Phone", "Fax" }; // Initialize data final Object[][] data = { { "Gail", "4567", "8675" }, { "Ken", "7566", "5555" }, { "Viviane", "5634", "5887" }, { "Melanie", "7345", "9222" }, { "Anne", "1237", "3333" }, { "John", "5656", "3144" }, { "Matt", "5672", "2176" }, { "Claire", "6741", "4244" }, { "Erwin", "9023", "5159" }, { "Ellen", "1134", "5332" }, { "Jennifer", "5689", "1212" }, { "Ed", "9030", "1313" }, { "Helen", "6751", "1415" } }; // Create the table JTable table = new JTable(data, colHeads); // Add table to a scroll pane int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED; JScrollPane jsp = new JScrollPane(table, v, h); // Add scroll pane to the content pane contentPane.add(jsp, BorderLayout.CENTER); } } Output from this applet is shown here:

Page 37: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 37 of 165

Exploring Swing As mentioned earlier, Swing is a large system, and it has many features that you will want to explore on your own. For example, Swing provides toolbars, tooltips, and progress bars. Also, Swing components can provide a pluggable look and feel, which means that it is easy to substitute another appearance and behavior for an element. This can be done dynamically. You may even design your own look and feel. Frankly, the Swing approach to GUI components might replace the AWT classes sometime in the future, so familiarizing yourself with it now is a good idea. Swing is just one part of the Java Foundation Classes (JFC). You may want to explore other JFC features. The Accessibility API can be used to build programs that are usable by people with disabilities. The Java 2-D API provides advanced capabilities for working with shapes, text, and images. The Drag-and-Drop API allows information to be exchanged between Java and non-Java programs. Q. Explain Action Interface?

The Action Interface An action is defined by the interface it implements, which in this case is javax.swing.Action . Action extends the ActionListener interface from AWT; this forces concrete classes that

implement Action to provide an actionPerformed() method. The programmer uses the actionPerformed() method to implement whatever behavior is desired. For example, if you are creating a Save action, you want to put the code to save the data inside of your actionPerformed() method.

When the action is added to an accepting container, such as JMenu, JPopupMenu, or JToolBar, the container automatically registers the action as an ActionListener of the GUI component it creates. Consequently, if the GUI component is selected by the user, it simply invokes the actionPerformed() method of the action to do its job.

The Action interface defines five constants, which serve as keys for storing standardized Action properties. The method of storage varies from implementer to implementer, but a Hashtable is common. These properties store information such as the name of the action, its description, and a representative icon. Also, the Action interface defines a boolean property that indicates whether the action is enabled or disabled. Recall that the GUI component created for the action registers itself as a PropertyChangeListener. Hence, if any of these properties are modified, the GUI component will be notified and can react accordingly.

Methods public abstract Object getValue(String key) public abstract void putValue(String key, Object value)

Store various keyed properties for the action. A string-based key is used to index the values. Several string constants representing the keys are shown in Table 3.2. When putValue() is

called with any property, and the value passed in is different than what was there previously, the implementing object must fire a PropertyChangeEvent to all registered listeners describing the change. Table 3.2, String-Based Key Constants for the Action Interface Constant Meaning DEFAULT Default setting NAME Name of the action SHORT_DESCRIPTION Short text description of what the action does LONG_DESCRIPTION Long text description of what the action does SMALL_ICON Represents a small icon typically used in a toolbar

public abstract void actionPerformed(ActionEvent e) This method is required by the ActionListener interface (it does not actually exist in the Action

interface). Any concrete class that implements the Action interface must provide an actionPerformed()

method that per-forms whatever task the action is supposed to accomplish. Events

Page 38: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 38 of 165

Objects implementing the Action interface must fire a PropertyChangeEvent when any keyed property is changed, or when the action is enabled or disabled. Containers that accept actions typically listen for these PropertyChangeEvent notifications so they can update their own properties or appearances.

public abstract void addPropertyChangeListener(PropertyChangeListener listener) public abstract void removePropertyChangeListener(PropertyChangeListener listener)

Add or remove the specified PropertyChangeListener from the event listener list.

Q. Explain Text Entry Components In Detail?

Text Entry Components

Class JPasswordField

java.lang.Object o java.awt.Component

java.awt.Container javax.swing.JComponent

javax.swing.text.JTextComponent javax.swing.JTextField

javax.swing.JPasswordField

All Implemented Interfaces: ImageObserver, MenuContainer, Serializable, Accessible, Scrollable, SwingConstants

public class JPasswordField extends JTextField

JPasswordField is a lightweight component that allows the editing of a single line of text where

the view indicates something was typed, but does not show the original characters. You can find

JPasswordField is intended to be source-compatible with java.awt.TextField used with echoChar set. It is provided separately to make it easier to safely change the UI for the JTextField without affecting password entries.

NOTE: By default, JPasswordField disables input methods; otherwise, input characters could be visible while they were composed using input methods. If an application needs the input methods support, please use the inherited method, enableInputMethods(true).

Page 39: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 39 of 165

Text 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 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. import java.awt.*; import javax.swing.*; /* <applet code="JTextFieldDemo" width=300 height=50> </applet> */ public class JTextFieldDemo extends JApplet { JTextField jtf; public void init() { // Get content pane Container contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); // Add text field to content pane jtf = new JTextField(15); contentPane.add(jtf); } } Output from this applet is shown here:

Class JEditorPane

java.lang.Object o java.awt.Component

o java.awt.Container

javax.swing.JComponent javax.swing.text.JTextComponent

javax.swing.JEditorPane

All Implemented Interfaces: ImageObserver, MenuContainer, Serializable, Accessible, Scrollable

Direct Known Subclasses:

JTextPane

Page 40: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 40 of 165

public class JEditorPane extends JTextComponent

A text component to edit various kinds of content. You can find how-to information and examples

of using editor panes in Using Text Components, a section in The Java Tutorial.

This component uses implementations of the EditorKit to accomplish its behavior. It effectively morphs into the proper kind of text editor for the kind of content it is given. The content type that editor is bound to at any given time is determined by the EditorKit currently installed. If the content is set to a new URL, its type is used to determine the EditorKit that should be used to load the content.

By default, the following types of content are known:

text/plain

Plain text, which is the default the type given isn't recognized. The kit used in this case is an

extension of DefaultEditorKit that produces a wrapped plain text view.

text/html

HTML text. The kit used in this case is the class javax.swing.text.html.HTMLEditorKit which

provides HTML 3.2 support.

text/rtf

RTF text. The kit used in this case is the class javax.swing.text.rtf.RTFEditorKit which provides a

limited support of the Rich Text Format.

There are several ways to load content into this component.

1. The setText method can be used to initialize the component from a string. In this case the current EditorKit will be used, and the content type will be expected to be of this type.

2. The read method can be used to initialize the component from a Reader. Note that if the content type is HTML, relative references (e.g. for things like images) can't be resolved unless the <base> tag is used or the Base property on HTMLDocument is set. In this case the current EditorKit will be used, and the content type will be expected to be of this type.

3. The setPage method can be used to initialize the component from a URL. In this case, the content type will be determined from the URL, and the registered EditorKit for that content type will be set.

Some kinds of content may provide hyperlink support by generating hyperlink events. The HTML EditorKit will generate hyperlink events if the JEditorPane is not editable (JEditorPane.setEditable(false); has been called). If HTML frames are embedded in the document, the typical response would be to change a portion of the current document. The following code fragment is a possible hyperlink listener implementation, that treats HTML frame events specially, and simply displays any other activated hyperlinks.

class Hyperactive implements HyperlinkListener { public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {

Page 41: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 41 of 165

JEditorPane pane = (JEditorPane) e.getSource(); if (e instanceof HTMLFrameHyperlinkEvent) { HTMLFrameHyperlinkEvent evt = (HTMLFrameHyperlinkEvent)e; HTMLDocument doc = (HTMLDocument)pane.getDocument(); doc.processHTMLFrameHyperlinkEvent(evt); } else { try { pane.setPage(e.getURL()); } catch (Throwable t) { t.printStackTrace(); } } } } }

For information on customizing how text/html is rendered please see W3C_LENGTH_UNITS and HONOR_DISPLAY_PROPERTIES

Culturally dependent information in some documents is handled through a mechanism called character encoding. Character encoding is an unambiguous mapping of the members of a character set (letters, ideographs, digits, symbols, or control functions) to specific numeric code values. It represents the way the file is stored. Example character encodings are ISO-8859-1, ISO-8859-5, Shift-jis, Euc-jp, and UTF-8. When the file is passed to an user agent (JEditorPane) it is converted to the document character set (ISO-10646 aka Unicode).

There are multiple ways to get a character set mapping to happen with JEditorPane.

1. One way is to specify the character set as a parameter of the MIME type. This will be established by a call to the setContentType method. If the content is loaded by the setPage method the content type will have been set according to the specification of the URL. It the file is loaded directly, the content type would be expected to have been set prior to loading.

2. Another way the character set can be specified is in the document itself. This requires reading the document prior to determining the character set that is desired. To handle this, it is expected that the EditorKit.read operation throw a ChangedCharSetException which will be caught. The read is then restarted with a new Reader that uses the character set specified in the ChangedCharSetException (which is an IOException).

Class JTextPane

java.lang.Object o java.awt.Component

java.awt.Container javax.swing.JComponent

javax.swing.text.JTextComponent javax.swing.JEditorPane

javax.swing.JTextPane

All Implemented Interfaces: ImageObserver, MenuContainer, Serializable, Accessible, Scrollable

public class JTextPane extends JEditorPane

Page 42: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 42 of 165

A text component that can be marked up with attributes that are represented graphically.

This component models paragraphs that are composed of runs of character level attributes. Each paragraph may have a logical style attached to it which contains the default attributes to use if not overridden by attributes set on the paragraph or character run. Components and images may be embedded in the flow of text.

Class JFormattedTextField

java.lang.Object o java.awt.Component

java.awt.Container javax.swing.JComponent

javax.swing.text.JTextComponent javax.swing.JTextField

javax.swing.JFormattedTextField

All Implemented Interfaces: ImageObserver, MenuContainer, Serializable, Accessible, Scrollable, SwingConstants

public class JFormattedTextField extends JTextField

JFormattedTextField extends JTextField adding support for formatting arbitrary values, as well as

retrieving a particular object once the user has edited the text. The following illustrates configuring

a JFormattedTextField to edit dates:

JFormattedTextField ftf = new JFormattedTextField(); ftf.setValue(new Date()); Once a JFormattedTextField has been created, you can listen for editing changes by way of adding a PropertyChangeListener and listening for PropertyChangeEvents with the property name value. JFormattedTextField allows configuring what action should be taken when focus is lost. The possible configurations are:

Value Description

JFormattedTextField.REVERT Revert the display to match that of getValue,

possibly losing the current edit.

JFormattedTextField.COMMIT

Commits the current value. If the value being

edited isn't considered a legal value by the

AbstractFormatter that is, a ParseException is

thrown, then the value will not change, and then

edited value will persist.

JFormattedTextField.COMMIT_OR_REVERT Similar to COMMIT, but if the value isn't legal,

behave like REVERT.

JFormattedTextField.PERSIST Do nothing, don't obtain a new AbstractFormatter,

and don't update the value.

Page 43: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 43 of 165

The default is JFormattedTextField.COMMIT_OR_REVERT, refer to setFocusLostBehavior(int)

for more information on this.

JFormattedTextField allows the focus to leave, even if the currently edited value is invalid. To lock the focus down while the JFormattedTextField is an invalid edit state you can attach an InputVerifier. The following code snippet shows a potential implementation of such an InputVerifier:

public class FormattedTextFieldVerifier extends InputVerifier { public boolean verify(JComponent input) { if (input instanceof JFormattedTextField) { JFormattedTextField ftf = (JFormattedTextField)input; AbstractFormatter formatter = ftf.getFormatter(); if (formatter != null) { String text = ftf.getText(); try { formatter.stringToValue(text); return true; } catch (ParseException pe) { return false; } } } return true; } public boolean shouldYieldFocus(JComponent input) { return verify(input); } } Alternatively, you could invoke commitEdit, which would also commit the value.

JFormattedTextField does not do the formatting it self, rather formatting is done through an instance of JFormattedTextField.AbstractFormatter which is obtained from an instance of JFormattedTextField.AbstractFormatterFactory. Instances of JFormattedTextField.AbstractFormatter are notified when they become active by way of the install method, at which point the JFormattedTextField.AbstractFormatter can install whatever it needs to, typically a DocumentFilter. Similarly when JFormattedTextField no longer needs the AbstractFormatter, it will invoke uninstall.

JFormattedTextField typically queries the AbstractFormatterFactory for an AbstractFormat when it gains or losses focus. Although this can change based on the focus lost policy. If the focus lost policy is JFormattedTextField.PERSIST and the JFormattedTextField has been edited, the AbstractFormatterFactory will not be queried until the value has been commited. Similarly if the focus lost policy is JFormattedTextField.COMMIT and an exception is thrown from stringToValue, the AbstractFormatterFactory will not be querired when focus is lost or gained.

JFormattedTextField.AbstractFormatter is also responsible for determining when values are commited to the JFormattedTextField. Some JFormattedTextField.AbstractFormatters will make new values available on every edit, and others will never commit the value. You can force the current value to be obtained from the current JFormattedTextField.AbstractFormatter by way of invoking commitEdit. commitEdit will be invoked whenever return is pressed in the JFormattedTextField.

Page 44: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 44 of 165

If an AbstractFormatterFactory has not been explicitly set, one will be set based on the Class of the value type after setValue has been invoked (assuming value is non-null). For example, in the following code an appropriate AbstractFormatterFactory and AbstractFormatter will be created to handle formatting of numbers:

JFormattedTextField tf = new JFormattedTextField(); tf.setValue(new Number(100));

Class JTextArea

java.lang.Object o java.awt.Component

java.awt.Container javax.swing.JComponent

javax.swing.text.JTextComponent javax.swing.JTextArea

All Implemented Interfaces: ImageObserver, MenuContainer, Serializable, Accessible, Scrollable

public class JTextArea extends JTextComponent

A JTextArea is a multi-line area that displays plain text. It is intended to be a lightweight

component that provides source compatibility with the java.awt.TextArea class where it can

reasonably do so. You can find information and examples of using all the text components in

Using Text Components, a section in The Java Tutorial.

This component has capabilities not found in the java.awt.TextArea class. The superclass should be consulted for additional capabilities. Alternative multi-line text classes with more capabilities are JTextPane and JEditorPane.

The java.awt.TextArea internally handles scrolling. JTextArea is different in that it doesn't manage scrolling, but implements the swing Scrollable interface. This allows it to be placed inside a JScrollPane if scrolling behavior is desired, and used directly if scrolling is not desired.

The java.awt.TextArea has the ability to do line wrapping. This was controlled by the horizontal scrolling policy. Since scrolling is not done by JTextArea directly, backward compatibility must be provided another way. JTextArea has a bound property for line wrapping that controls whether or not it will wrap lines. By default, the line wrapping property is set to false (not wrapped).

java.awt.TextArea has two properties rows and columns that are used to determine the preferred size. JTextArea uses these properties to indicate the preferred size of the viewport when placed inside a JScrollPane to match the functionality provided by java.awt.TextArea. JTextArea has a preferred size of what is needed to display all of the text, so that it functions properly inside of a JScrollPane. If the value for rows or columns is equal to zero, the preferred size along that axis is used for the viewport preferred size along the same axis.

The java.awt.TextArea could be monitored for changes by adding a TextListener for TextEvents. In the JTextComponent based components, changes are broadcasted from the model via a DocumentEvent to DocumentListeners. The DocumentEvent gives the location of the change and the kind of change if desired. The code fragment might look something like:

Page 45: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 45 of 165

DocumentListener myListener = ??; JTextArea myArea = ??; myArea.getDocument().addDocumentListener(myListener);

COLOR AND FILE CHOOSER :

Figure . Class hierarchy for JFileChooser and JColorChooser

Q. Explain JFileChooser ? The JFileChooser Class Since it plays such an integral role in just about every commercial application, let's look at the file chooser first. The JFileChooser class bundles a directory pane and typical selection buttons into a handy interface. Figure 12.2 shows the dialog window you get when you select the Save option of a simple application. As you might expect, other look-and-feels can also be applied to this chooser. Figure 12.3 shows the Windows and Motif L&Fs.

Figure 12.3. The Windows and Motif look-and-feel for JFileChooser

Page 46: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 46 of 165

Here's the code that generated the application. The application itself only reports which file was chosen to open or save. Our application has a "Pick Directory" button that restricts the chooser to directories. The event handlers for each button do most of the interesting work. In each case, we create a new JFileChooser object, make any changes to the default properties that we need for the particular action, and then show the dialog. As you will see from the constants discussed later, the int returned from the showDialog() method indicates whether the user accepted a file selection or canceled the dialog. If we have a successful selection, we put the name of the file into a display label. For this quick test, we create each file chooser dialog as we need it. You do not have to do this. You can save a reference to these dialogs and reuse them, just as you would other popups. // SimpleFileChooser.java

// A simple file chooser to see what it takes to make one of these work. // import java.awt.*; import java.awt.event.*; import java.io.*; import javax.swing.*; public class SimpleFileChooser extends JFrame { JFrame parent; public SimpleFileChooser() { super("Table Test Frame"); setSize(350, 200); addWindowListener(new BasicWindowMonitor()); parent = this; Container c = getContentPane(); c.setLayout(new FlowLayout()); JButton openButton = new JButton("Open"); JButton saveButton = new JButton("Save");

JButton dirButton = new JButton("Pick Dir"); final JLabel statusbar = new JLabel("Output of your selection will go here"); // Create a file chooser that opens up as an "Open" dialog openButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JFileChooser chooser = new JFileChooser(); int option = chooser.showOpenDialog(parent); if (option == JFileChooser.APPROVE_OPTION) {

Page 47: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 47 of 165

statusbar.setText("You chose " + ((chooser.getSelectedFile()!=null)? ((chooser.getSelectedFile().getName():"nothing")); } else { statusbar.setText("You canceled."); } } }); // Create a file chooser that opens up as a "Save" dialog saveButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JFileChooser chooser = new JFileChooser(); int option = chooser.showSaveDialog(parent); if (option == JFileChooser.APPROVE_OPTION) { statusbar.setText("You saved " + ((chooser.getSelectedFile()!=null)? chooser.getSelectedFile().getName():"nothing")); } else { statusbar.setText("You canceled."); } } }); // Create a file chooser that allows you to pick a directory // rather than a file dirButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int option = chooser.showOpenDialog(parent); if (option == JFileChooser.APPROVE_OPTION) { statusbar.setText("You opened " + ((chooser.getSelectedFile()!=null)? chooser.getSelectedFile().getName():"nothing")); } else { statusbar.setText("You canceled."); } } }); c.add(openButton); c.add(saveButton); c.add(dirButton); c.add(statusbar); } public static void main(String args[]) { SimpleFileChooser sfc = new SimpleFileChooser(); sfc.setVisible(true); } }

Events In addition to the property change events generated like most other Swing components, the JFileChooser also generates action events when the user presses the approve or cancel buttons. The event is fired after the dialog is hidden.

public void addActionListener(ActionListener l) public void removeActionListener(ActionListener l)

If you want to listen directly to the approve or cancel button events, you can add an

Page 48: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 48 of 165

ActionListener to the dialog. The accessory example listened to such events to stop playing any active audio clip.

public void approveSelection() public void cancelSelection()

You can programmatically fire an approval or a cancellation using these methods, simulating pressing the "Ok" or "Cancel" buttons. This can be useful if your accessory provides its own way of saying yes or no to the current selection. Both methods use the fireActionPerformed() method below to send out the events. The APPROVE_SELECTION and CANCEL_SELECTION constants listed later are used for the appropriate command string. protected void fireActionPerformed(String command) This protected method fires off a newly generated ActionEvent with the given command as the actionCommand of the event.

Constructors public JFileChooser()

Creates a file chooser starting at the user's home directory. File choosers do not make a distinction between open and save at creation time. That aspect of a chooser is dictated by the dialogType property, which can be set at any time.

public JFileChooser(File directory) public JFileChooser(String path)

These constructors create new choosers starting at the specified directory. FileFilter Methods The choosableFileFilters property does not have a proper "set" method, but you can modify the set of available filters using these methods.

public void addChoosableFileFilter(FileFilter filter) public void removeChoosableFileFilter(FileFilter filter)

Add or remove filters. The FileFilter class is discussed in detail below. public void resetChoosableFileFilters() Resets the list of choosable file filters to contain only the original "accept all" filter. File Methods The file methods check files to find the appropriate names, descriptions and icons to display in the chooser according to the active FileView and FileFilter objects.

public boolean accept(File f) Returns true if the file f should be displayed.

public void ensureFileIsVisible(File f) Ensures the file f is visible in the chooser, which may mean changing the scroll location of the file list.

public String getDescription(File f) Returns a description of the file f. A common description is simply the file's name.

public Icon getIcon(File f) Returns an icon to display in the chooser for the file f. The icon could change depending on the type of file.

public String getName(File f) Returns the name of the file f. The chooser relies on the active FileView object to decide a file's name. The FileView object could alter the file's name for display, for example, to create an ISO 9660 compliant name.

public String getTypeDescription(File f) Returns a brief description of the type of file f. The details view of a directory might use this information.

public boolean isTraversable(File f) Returns true if the file is a folder and can be opened.

Q. Write a short note on Color Chooser?

The Color Chooser As the name indicates, the JColorChooser component is designed to allow users to pick a color. If your application supports customized environments (like the foreground, background, and highlight

Page 49: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 49 of 165

colors for text) this control might come in handy. You can pick colors from a palette and then look at that color in a preview panel that shows you how your color looks with black and white. The dialog also has an RGB mode that allows you to pick the exact amounts of red, blue, and green using sliders. The standard color chooser window looks like Figure 12.7. Figure 12.7. The default JColorChooser dialog in Swatches (top) and RGB (bottom) modes

The JColorChooser class provides a static method for getting this popup going quickly. Here's the code that produced the screen shots in Figure 12.7: // ColorPicker.java // A quick test of the JColorChooser dialog. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ColorPicker extends JFrame { public ColorPicker() { super("JColorChooser Test Frame"); setSize(200, 100); final JButton go = new JButton("Show JColorChooser"); go.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Color c; c = JColorChooser.showDialog( ((Component)e.getSource()).getParent(), "Demo", Color.blue); go.setBackground(c); } }); getContentPane().add(go); addWindowListener(new BasicWindowMonitor()); } public static void main(String args[]) { ColorPicker cp = new ColorPicker(); cp.setVisible(true); } } One way to get a color out of this dialog is to wait for it to close (the showDialog() method will

Page 50: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 50 of 165

block) and store the result of showDialog(). But you are not limited to a modal dialog that produces a single color. You can create your own color choosers to which you attach a ChangeListener object that can detect any change in the current color property while the popup is active, or even after it has been closed. We'll look at some examples of such custom choosers later in this chapter. The ColorSelectionModel Interface The JColorChooser uses a model to represent the currently selected color. The ColorSelectionModel interface is quite simple, having only one property (the selected color) and support for notifying listeners that the color has changed. Events To indicate the selected color has changed, implementations of ColorSelectionModel should fire a ChangeEvent whenever the selectedColor property changes. Following the standard naming conventions, the following methods are required for managing ChangeEvent listeners:

public void addChangeListener(ChangeListener l) public void removeChangeListener(ChangeListener l)

As you might expect, these methods allow you to add and remove listener objects interested in receiving event notifications.

The DefaultColorSelectionModel Class The DefaultColorSelectionModel class provides a straightforward implementation of the ColorSelectionModel interface. This is the selection model used by default in the JColorChooser class. The JColorChooser Class Properties In addition to the typical UI properties of Swing components, the color chooser has the following properties listed in Table 12.6. The chooserPanels property contains an array of all the chooser panels currently associated with this color chooser. You can get and set the entire array at once or, more commonly, you can add and remove chooser panels using some of the methods described later. The color property contains the currently selected color in the chooser. The previewPanel property contains the JComponent subclass that previews your color choice. (You can see an example of the default preview panel in Figure 12.7.) The selectionModel property dictates which selection model the chooser uses. Constructors public JColorChooser() public JColorChooser(Color initialColor) public JColorChooser(ColorSelectionModel model)

These constructors create new JColorChooser panes. The first two versions use a DefaultColorSelectionModel. In the first two versions, where you do not specify an initial color, Color.white will be used. In the last version, the color is extracted from the model. Dialog Methods public static JDialog createDialog(Component c, String title, boolean modal,JColorChooser chooserPane, ActionListener okListener, ActionListener cancelListener) Creates a (possibly modal) dialog window, with chooserPane as its main component. With this convenience method, you can add your own action listeners for the "Ok" and "Cancel" buttons. public static Color showDialog(Component c, String title, Color initialColor) Creates a modal dialog that waits for the user to press either the "Ok" or the "Cancel" button. If the user chose "Ok," the current color in the chooser is returned, otherwise, null is returned. No errors or exceptions are raised if the user cancels. Chooser Panel Methods public void addChooserPanel(AbstractColorChooserPanel panel) Adds a new tab to the color chooser and places panel on that tab. An example using a custom chooser panel appears later in this chapter. public AbstractColorChooserPanel removeChooserPanel(AbstractColorChooserPanel panel) Removes a panel from the chooser. If panel is found on one of the tabs, it is removed and

Page 51: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 51 of 165

returned. If the panel is not found, null is returned.

Q. Explain How To Do Printing With Java 2D API?

Printing With Java 2D API

The Java Printing API enables applications to:

Print all AWT and Java 2D™ graphics, including composited graphics and images.

Control document-composition functions such as soft collating, reverse order printing, and booklet printing.

Invoke printer-specific functions such as duplex (two-sided) printing and stapling.

Print on all platforms, including Windows and Solaris. This includes printers directly attached to the computer as well as those that the platform software is able to access using network printing protocols.

Not all of these features are supported in the Java™ 2 SDK Printing API and implementation. The API will be extended to support all of these features in future releases. For example, additional printer controls will be added by augmenting the set of named properties of a print job that the application can control. The Java 2 platform offers a clean, compact Printing API. If you've been struggling to get JDK 1.0 or JDK 1.1 to produce nice printed output, you'll be really happy to see the Printing API.[1] The basic concept is very simple: the Printing API can give you a Graphics2D that represents a printer. You can perform the same rendering, regardless of whether the output device is the screen or a printer. Java 2 unleashes the full power of the 2D API is on your printer. Whee! The classes and interfaces involved in printing are neatly tucked away in the java.awt.print package. It's a small package, easy to understand and easy to use. The secret of this simplicity is that an application can use the same code to render on a screen or on a printer. Printing is simply a matter of obtaining a Graphics2D that corresponds to the printer and rendering away. Aside from rendering, there are two issues that are important in printing: Job control It's up to your application to start printing and to display printing dialogs. The 2D API can show the standard print and page setup dialogs for you. Pagination Each page consists of some finite printable area. Your application should break its data into page-sized pieces for printing.

How Printing Works The Printing API uses a callback model, which means that the printing system calls your application when it needs something to be drawn. But it's more complicated than that. The following is a typical sequence of events: 1. The user of your application requests printed output, usually by clicking on a button or choosing a menu item. 2. Your application displays a print dialog box that is appropriate for the underlying operating system. The Windows print dialog is shown in Figure 13.1. From this dialog, users can choose a printer, change the number of copies that will be printed, and fiddle with other options. 3. If the user clicks on the OK button in the print dialog, your application can tell the system to begin a printing job. 4. The system will call back your rendering code at the appropriate time to render your picture on the printer. Figure . The print dialog in Windows

Page 52: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 52 of 165

The Players(Packages) One class and one interface form the crux of the Printing API: java.awt.print.PrinterJob The PrinterJob class controls the printing process. You can use this class to kick off printing or to cancel a job in progress. This class also includes methods for displaying a print dialog and a page setup dialog. [2] Don't confuse this with java.awt.PrintJob, which was part of JDK 1.1's printing solution. java.awt.print.Printable The Printable interface represents something that can be printed. It contains a single method, print(). Let's get something on paper right away to illustrate how PrinterJob and Printable work together. Here's a simple example that displays a print dialog and prints a single page:

import java.awt.*; import java.awt.print.*; public class HelloNurse { public static void main(String[] args) { PrinterJob pj = PrinterJob.getPrinterJob(); pj.setPrintable(new HelloNursePrintable()); if (pj.printDialog()) { try { pj.print(); } catch (PrinterException e) { System.out.println(e); } } } } class HelloNursePrintable implements Printable { public int print(Graphics g, PageFormat pf, int pageIndex) { if (pageIndex != 0) return NO_SUCH_PAGE; Graphics2D g2 = (Graphics2D)g; g2.setFont(new Font("Serif", Font.PLAIN, 36)); g2.setPaint(Color.black); g2.drawString("Hello, nurse!", 144, 144); return PAGE_EXISTS; }

Page 53: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 53 of 165

} Let's look at the sequence of events in this small application: 1. First, a PrinterJob is instantiated by calling the getPrinterJob() factory method:

PrinterJob pj = PrinterJob.getPrinterJob(); 2. The thing to be printed, HelloNursePrintable, is passed to the PrinterJob's

setPrintable() method: pj.setPrintable(new HelloNursePrintable());

3. Then the example shows a print dialog: if (pj.printDialog()) {

4. If the user pressed OK in the print dialog, the printDialog() method returns true. In this case, the printing job is started by calling print():

try { pj.print(); } 5. The job is now in the hands of the Printing API. It calls our Hello-NursePrintable's print() method as appropriate to render the page on the printer. Control is returned to the HelloNurse application once the entire printing job has been sent to the underlying operating system. Since HelloNurse doesn't have anything else to do, it exits right away. Don't worry about the parts of this example that don't make sense yet. I'll cover everything in detail in this chapter. The Printable Interface Let's take a closer look at the Printable interface, which contains one method:

public int print(Graphics g, PageFormat pf, int pageIndex) throws PrinterException This method is called by the Printing API to render a page on a printer. The Graphics object represents the drawing surface of the page. You can cast it to a Graphics2D to take advantage of the 2D API's features. The PageFormat object describes the size and orientation of the paper. I'll describe the PageFormat class in detail later. The pageIndex parameter is the number of the page that will be printed. It is zero-based; that is, the first page is 0. It's possible that this method will be called multiple times to render the same page. Usually this doesn't affect how you write the method — just make sure you're not expecting only one call to print() per page. If your Printable implementation is able to print the requested page, it should do its rendering and return PAGE_EXISTS, a constant in the Printable interface. If the requested page does not exist, return NO_SUCH_PAGE. You don't have to declare that the method throws a PrinterException if you don't plan to throw one yourself. The HelloNursePrintable class, presented above, only prints one page. If any other page index is passed to print(), it returns NO_SUCH_PAGE: public int print(Graphics g, PageFormat pf, int pageIndex) { if (pageIndex != 0) return NO_SUCH_PAGE; Otherwise, HelloNursePrintable goes ahead and renders the page. In this case, it just draws a single string. Having successfully rendered the page, it returns PAGE_EXISTS:

Graphics2D g2 = (Graphics2D)g; g2.setFont(new Font("Serif", Font.PLAIN, 36)); g2.drawString("Hello, nurse!", 144, 144); return PAGE_EXISTS; }

You've probably noticed that the print() method in the Printable interface looks a lot like a paint() method. If you want to render the same thing on the screen and on a printer, you should take advantage of this similarity. Instead of doing any rendering in the print() method, just call a paint() method from the print() method. You'll see examples of this later.

Page 54: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 54 of 165

* The Java Foundation Classes (JFC) are a suite of libraries designed to assist programmers in

creating enterprise applications with Java.

* Swing is a subset of the Java Foundation Classes (JFC).

* The JComponent class extends the Container class, which itself extends Component.

* The Component class includes everything from providing layout hints to supporting painting and events. The Container class has support for adding components to the container and laying them out.

* A Window object is a top-level window with no borders and no menubar. The default layout for a window is BorderLayout.

* JWindow is an extension of java.awt.Window that uses a JRootPane as its single component.

* Swing's JMenuBar class supersedes the older AWT MenuBar class. This class creates a horizontal menubar component with zero or more menus attached to it. JMenuBar uses the DefaultSingleSelectionModel as its data model; this is because the user can raise, or activate, only one of its menus at a given time.

* 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.

* The JCheckBox class, which provides the functionality of a check box, is a concrete implementation of AbstractButton. Its immediate superclass is JToggleButton, which provides support for two-state buttons.

* A list is a graphical component from which the user can select choices. Lists typically display several

items at a time, allowing the user to make either a single selection or multiple selections.

* 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.

* A tabbed pane is a component that appears as a group of folders in a file cabinet. Each folder has a

title. When a user selects a folder, its contents become visible. Only one of the folders may be

selected at a time. Tabbed panes are commonly used for setting configuration options.

* A scroll pane is a component that presents a rectangular area in which a component may be viewed.

Horizontal and/or vertical scroll bars may be provided if necessary. Scroll panes are implemented in

Swing by the JScrollPane class, which extends JComponent.

* An action is defined by the interface it implements, which in this case is javax.swing.Action .

* Action extends the ActionListener interface from AWT; this forces concrete classes that implement

Action to provide an actionPerformed() method. The programmer uses the actionPerformed() method

to implement whatever behavior is desired.

* JPasswordField is a lightweight component that allows the editing of a single line of text where the

view indicates something was typed, but does not show the original characters.

* The JFileChooser class bundles a directory pane and typical selection buttons into a handy interface.

Quick Revision

Page 55: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 55 of 165

IMP Question Set

SR No. Question Reference page No.

1 Q. What Are the Java Foundation Classes (JFC)?

3

2 Q. Write a short note on JComponent Class?

5

3 Q. Write a Short note On Lists?

27

4 Q. Write a Short Note on Combo Boxes?

28

5 Q. Explain TabbedPanes And ScrollPanes?

29

6 Q. Write a Short Note on Tree?

33

7 Q. Write a short note on Tables?

35

8 Q. Explain Action Interface?

37

9 Q. Explain Text Entry Components In Detail?

38

10 Q. Explain How To Do Printing With Java 2D API?

51

Page 56: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 56 of 165

CHAPTER 2: JDBC Topic Covered:

JDBC Introduction, JDBC Architecture, Types of JDBC Drivers, The Connectivity Model, The

java.sql package, Navigating the ResultSet object’s contents, Manipulating records of a ResultSet

object through User Interface , The JDBC Exception classes, Database Connectivity, Data

Manipulation (using Prepared Statements, Joins, Transactions, Stored Procedures), Data

navigation.

Introduction: In the summer of 1996, Sun released the first version of the Java Database Connectivity (JDBC) kit. This package lets programmers connect to a database, query it, or update it, using the Structured Query Language or SQL. (SQL, usually pronounced like "sequel," is an industry standard for database access.) When JDBC was first announced, we considered this one of the most important developments in programming for the Java platform. It is not just that databases are among the most common use of hardware and software today. After all, there are a lot of products running after this market, so why did we think the Java programming language had the potential to make a big splash? The reason that Java and JDBC have an essential advantage over other database programming environments is this: • Programs developed with the Java programming language and JDBC are platform independent and vendor independent. The same database program written in the Java programming language can run on an NT box, a Solaris server, or a database appliance powered by the Java platform. You can move your data from one database to another, for example, from Microsoft SQL Server to Oracle, or even to a tiny database embedded in a device, and the same program can still read your data. This is in sharp contrast to traditional database programming. It is all too common that one writes database applications in a proprietary database language, using a database management system that is available only from a single vendor. The result is that you can run the resulting application only on one or two platforms. We believe that because of their universality, the Java programming language and JDBC will eventually replace proprietary database languages and call level interfaces used by vendors such as Oracle, Informix, and Microsoft for accessing databases.

Page 57: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 57 of 165

Q. Write a note on JDBC Drivers? JDBC drivers are classified into the following types: A type 1 driver translates JDBC to ODBC and relies on an ODBC driver to communicate with the

database. Sun includes one such driver, the JDBC/ODBC bridge, with the JDK. However, the bridge requires deployment and proper configuration of an ODBC driver.

When JDBC was first released, the bridge was handy for testing, but it was never intended for production use. At this point, there are plenty of better drivers available, and we advise against using the JDBC/ODBC bridge.

A type 2 driver is a driver, written partly in the Java programming language and partly in native code, that communicates with the client API of a database. When you use such a driver, you must install some platform-specific code in addition to a Java library.

A type 3 driver is a pure Java client library that uses a database-independent protocol to communicate database requests to a server component, which then translates the requests into a database-specific protocol. The client library is independent of the actual database, thus simplifying deployment.

A type 4 driver is a pure Java library that translates JDBC requests directly to a database-specific protocol.

Most database vendors supply either a type 3 or type 4 driver with their database. Furthermore, a number of third-party companies specialize in producing drivers with better standards conformance, support for more platforms, better performance, or, in some cases, simply better reliability than the drivers that are provided by the database vendors.

In summary, the ultimate goal of the JDBC is to make possible the following: Programmers can write applications in the Java programming language to access any database,

using standard SQL statements—or even specialized extensions of SQL—while still following Java language conventions. (All JDBC drivers must support at least the entry-level version of SQL 92.)

Database vendors and database tool vendors can supply the low-level drivers. Thus, they can optimize their drivers for their specific products.

NOTE If you are curious as to why Sun just didn't adopt the ODBC model, their response, as given at the JavaOne conference in May 1996, was: • ODBC is hard to learn. • ODBC has a few commands with lots of complex options. The preferred style in the Java programming language is to have simple and intuitive methods, but to have lots of them. • ODBC relies on the use of void* pointers and other C features that are not natural in the Java programming language. • An ODBC-based solution is inherently less safe and harder to deploy than a pure Java solution. Q. Explain JDBC architecture? JDBC Architecture

The JDBC API supports both two-tier and three-tier processing models for database access.

Figure 1: Two-tier Architecture for Data Access.

Page 58: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 58 of 165

In the two-tier model, a Java application talks directly to the data source. This requires a JDBC driver that can communicate with the particular data source being accessed. A user's commands are delivered to the database or other data source, and the results of those statements are sent back to the user. The data source may be located on another machine to which the user is connected via a network. This is referred to as a client/server configuration, with the user's machine as the client, and the machine housing the data source as the server. The network can be an intranet, which, for example, connects employees within a corporation, or it can be the Internet.

In the three-tier model, commands are sent to a "middle tier" of services, which then sends the commands to the data source. The data source processes the commands and sends the results back to the middle tier, which then sends them to the user. MIS directors find the three-tier model very attractive because the middle tier makes it possible to maintain control over access and the kinds of updates that can be made to corporate data. Another advantage is that it simplifies the deployment of applications. Finally, in many cases, the three-tier architecture can provide performance advantages.

Figure 2: Three-tier Architecture for Data Access.

Until recently, the middle tier has often been written in languages such as C or C++, which offer fast performance. However, with the introduction of optimizing compilers that translate Java bytecode into efficient machine-specific code and technologies such as Enterprise JavaBeans™, the Java platform is fast becoming the standard platform for middle-tier development. This is a big plus, making it possible to take advantage of Java's robustness, multithreading, and security features.

With enterprises increasingly using the Java programming language for writing server code, the JDBC API is being used more and more in the middle tier of a three-tier architecture. Some of the features that make JDBC a server technology are its support for connection pooling, distributed transactions, and disconnected rowsets. The JDBC API is also what allows access to a data source from a Java middle tier.

Page 59: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 59 of 165

JDBC architecture can be classified in 2 broad categories:-

1. JDBC API

2. Types of JDBC Drivers

JDBC API

JDBC programming interface is found in "java.sql" and "javax.sql" packages. Given below some classes and interfaces which support connectivity between interface and database :-

1.DriverManager :-"Driver Manger" Manages all the Drivers found in JDBC environment, load the most appropriate driver for connectivity.

2.Connection :-Connection class creates objects which represents connection and it's object also helps in creating object of Statement, PreparedStatement and CallableStatement classes.

3.Statement :-Statement object is used to execute query and also store it's value to "Resultset" object.

4.PreparedStatement:-It can be used in place of "Statement", PreparedStatement's performance is high as compared to "Statement" class, represents a precompiled SQL statement .

5.Callable Statement:-Callable statement support stored procedure of RDBMS' ,using it's object you can execute stored procedure of database application.

6.ResultSet :-Resultset object is used to store the result retrieve from database using "Statement" or "PreparedStatement" , etc

7.SQLException:- SqlException class is used to represent error or warning during access from database or during connectivity.

JDBC Driver's Type

JDBC Driver can be broadly categorized into 4 categories--

JDBC-ODBC BRIDGE DRIVER(TYPE 1)

Converted the query of JDBC Driver into the ODBC query, which in return pass the data. JDBC-ODBC is native code not written in java.The connection occurs as follows -- Client -> JDBC Driver -> ODBC Driver -> Database .A type-1 driver is easy to install and handle. Extra channels in between database and application made performance overhead. Needs to be installed on client machine. Not suitable for applet , due to the installation at clients end.

Native-API Type-2 Driver

The type 2 driver need libraries installed at client site. For example, we need "mysqlconnector.jar" to be copied in library of java kit. It is not written in java entirely because the non-java interface have the direct access to database. Type 2 driver has additional functionality and better performance than Type 1.Has faster performance than type 1,3 &4,since it has separate code for native APIS . Library needs to be installed on the client machine ..Due to the client side software demand, it can't be used for web based application. It is platform dependent. It doesn't support "Applets".

Page 60: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 60 of 165

Network-Protocol Type 3 driver

It has a 3-tier architecture. It can interact with multiple database of different environment. The JDBC Client driver written in java, communicates with a middleware-net-server using a database independent protocol, and then this net server translates this request into database commands for that database. The connection occurs as follows--Client -> JDBC Driver -> Middleware-Net Server -> Any Database. The client driver to middleware communication is database independent. Can be used in internet since there is no client side software needed. Needs specific coding for different database at middleware. Due to extra layer in middle can result in time-delay.

Native Protocol Type 4 Driver

Also known as Direct to Database Pure Java Driver .It is entirely in java. It interacts directly with database generally through socket connection. It is platform independent. It directly coverts driver calls into database protocol calls. Improved performance because no intermediate translator like JDBC or middleware server. All the connection is managed by JVM, so debugging is easier.

Q. Explain Steps of to access database through JDBC?

The java program can access the database using JDBC. the seven steps that are needed to access database are

1. Import the package 2. Load and register the driver 3. Establish the Connection 4. Create a Statement object 5. Execute a query 6. Process the result 7. Close the connection

Step1: Import java.sql package

The important classes and interfaces of JDBC are available in the java.sql package . So inorder to access the databases it must be imported in our application.

import java.sql.*;

Step 2: Loading and registering the driver

In order to access database it must have the particular driver for that database. In Java we have to inform the Drive Manager about the required driver this is done with the help of the method forName(String str) available in the class named Class

Class.forName(“path with driver name”);

In an application the user can register more than one driver. The statement used to load and register the JDBC-ODBC bridge driver is Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

Step 3: Establishing the connection

Page 61: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 61 of 165

Establishing connection means making a connection to access RDBMS through JDBC driver. The connection can be established with the help of getConnection() method available in DriverManager class. The established connection is then set to new connection object.

Connection con=DriverManager.getConnetion (“jdbc:odbc:DSN”, ”administrator”, “password”);

Where DSN-Data Source Name

When the statement is executed the connection is set to the Connection object cn. For example to connect the ODBC data source named mydata via JDBC –ODBC bridge the statement is Connection con= DriverManager.getConnection (“jdbc:odbc:mydata”);

Step 4: Creating the statement

A Statement object is used for executing a static SQL statement and obtaining the results produced by it. The createStatement() method is used to create statements using the established connection.

The methods used for creating the statements are

Statement createStatement()

Returns a new Statement object.Used for general queries

PreparedStatement prepareStatement(String sql)

Returns a new PreparedStatement object.For a statement called multiple times with different values (precompiled to reduce parsing time)

CallableStatement prepareCall(String sql)

Returns a new CallableStatement object for stored procedures

Step 5: Executing the Query

After making connection to the database we are ready to execute the SQL statements. The various methods available in Statement object to execute the query are

ResultSet executeQuery(String)

Execute a SQL statement that returns a single ResultSet. After executing the SQL statements the requested data is stored in the ResultSet object.

int executeUpdate(String)

Execute a SQL INSERT, UPDATE or DELETE statement. Returns the number of rows changed.

boolean execute(String)

Execute a SQL statement that may return multiple results.

Step 6: Retrieving the result.

Page 62: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 62 of 165

A ResultSet provides access to a table of data generated by executing a Statement.Only one ResultSet per Statement can be open at once.The table rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data. The 'next' method moves the cursor to the next row.

Methods:

public boolean first()

Moves the cursor to the first row in this ResultSet object.

public boolean last()

Moves the cursor to the last row in this ResultSet object.

public boolean next()

Moves the cursor down one row from its current position.

The methods used to retrieve the values from the current row

Type getType(int columnIndex)

Returns the given field as the given type. Fields indexed starting at 1 (not 0)

Type getType(String columnName)

Returns the data at the specified column

In the above methods the Type should be replaced by the valid datatypes such as Boolean, String, Int, Long, Float etc as getString(Column name), getInt(column index) etc.

Step 7: Closing the connection and statement

When the client request is completed we have to close the created objects of Connection and Statement using close() method.

st.close();

cn.close();

Caching Database results

The PreparedStatement concept of reusing requests can be extended to caching the results of a JDBC call. For example, an auction item description remains the same until the seller changes it. If the item receives thousands of requests, the results of the statement: query "select description from auctionitems where item_id='4000343'" might be stored more efficiently in a hash table.

Storing results in a hash table requires the JDBC call be intercepted before creating a real statement to return the cached results, and the cache entry be cleared if there is a corresponding update to that item_id. Result Sets

Page 63: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 63 of 165

The ResultSet interface manages access to data returned from a query. The data returned equals one row in a database table. Some queries return one row of data while many queries return multiple rows of data.

You use getType methods to retrieve data from specific columns for each row returned by the query. This example retrieves the TEXT column from all tables with a TEXT column in the dba database. The results.next method moves to the next retrieved row until all returned rows are processed.

Statement stmt = con.createStatement(); ResultSet results = stmt.executeQuery( "SELECT TEXT FROM dba "); while(results.next()){ String s = results.getString("TEXT"); displayText.append(s + "\n"); } stmt.close();

Establishing a Connection

First, you need to establish a connection with the DBMS you want to use. Typically, a JDBC™ application connects to a target data source using one of two mechanisms:

DriverManager: This fully implemented class requires an application to load a specific driver, using a hardcoded URL. As part of its initialization, the DriverManager class attempts to load the driver classes referenced in the jdbc.drivers system property. This allows you to customize the JDBC Drivers used by your applications.

DataSource: This interface is preferred over DriverManager because it allows details about the underlying data source to be transparent to your application. A DataSource object's properties are set so that it represents a particular data source.

Establishing a connection involves two steps: Loading the driver, and making the connection.

Loading the Driver

Loading the driver you want to use is very simple. It involves just one line of code in your program. To use the Java DB driver, add the following line of code:

Class.forName("org.apache.derby.jdbc.EmbeddedDriver");

Your driver documentation provides the class name to use. In the example above, EmbeddedDriver is one of the drivers for Java DB.

Calling the Class.forName automatically creates an instance of a driver and registers it with the DriverManager, so you don't need to create an instance of the class. If you were to create your own instance, you would be creating an unnecessary duplicate, but it would do no harm.

After you have loaded a driver, it can make a connection with a DBMS.

Making the Connection

The second step in establishing a connection is to have the appropriate driver connect to the DBMS.

Page 64: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 64 of 165

Using the DriverManager Class

The DriverManager class works with the Driver interface to manage the set of drivers available to a JDBC client. When the client requests a connection and provides a URL, the DriverManager is responsible for finding a driver that recognizes the URL and for using it to connect to the corresponding data source. Connection URLs have the following form:

jdbc:derby:<dbName>[propertyList]

The dbName portion of the URL identifies a specific database. A database can be in one of many locations: in the current working directory, on the classpath, in a JAR file, in a specific Java DB database home directory, or in an absolute location on your file system.

If you are using a vendor-specific driver, such as Oracle, the documentation will tell you what subprotocol to use, that is, what to put after jdbc: in the JDBC URL. For example, if the driver developer has registered the name OracleDriver as the subprotocol, the first and second parts of the JDBC URL will be jdbc.driver.OracleDriver . The driver documentation will also give you guidelines for the rest of the JDBC URL. This last part of the JDBC URL supplies information for identifying the data source.

The getConnection method establishes a connection:

Connection conn = DriverManager.getConnection("jdbc:derby:COFFEES");

In place of " myLogin " you insert the name you use to log in to the DBMS; in place of " myPassword " you insert your password for the DBMS. So, if you log in to your DBMS with a login name of " Fernanda " and a password of " J8, " just these two lines of code will establish a connection:

String url = "jdbc:derby:Fred"; Connection con = DriverManager.getConnection(url, "Fernanda", "J8");

If one of the drivers you loaded recognizes the JDBC URL supplied to the method DriverManager.getConnection, that driver establishes a connection to the DBMS specified in the JDBC URL. The DriverManager class, true to its name, manages all of the details of establishing the connection for you behind the scenes. Unless you are writing a driver, you probably won't use any of the methods in the interface Driver, and the only DriverManager method you really need to know is DriverManager.getConnection

The connection returned by the method DriverManager.getConnection is an open connection you can use to create JDBC statements that pass your SQL statements to the DBMS. In the previous example, con is an open connection, and you use it in the examples that follow.

Using a DataSource Object for a connection

Using a DataSource object increases application portability by making it possible for an application to use

a logical name for a data source instead of having to supply information specific to a particular driver. The

following example shows how to use a DataSource to establish a connection:

You can configure a DataSource using a tool or manually. For example, Here is an example of a DataSource lookup:

InitialContext ic = new InitialContext(); DataSource ds = ic.lookup("java:comp/env/jdbc/myDB");

Page 65: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 65 of 165

Connection con = ds.getConnection(); DataSource ds = (DataSource) org.apache.derby.jdbc.ClientDataSource() ds.setPort(1527); ds.setHost("localhost"); ds.setUser("APP") ds.setPassword("APP"); Connection con = ds.getConnection();

DataSource implementations must provide getter and setter methods for each property they support. These properties typically are initialized when the DataSource object is deployed.

VendorDataSource vds = new VendorDataSource(); vds.setServerName("my_database_server"); String name = vds.getServerName();

JDBC-ODBC Bridge Driver

For normal use, you should obtain a commercial JDBC driver from a vendor such as your database vendor or your database middleware vendor. The JDBC-ODBC Bridge driver provided with JDBC is recommended only for development and testing, or when no other alternative is available.

Scrolling Result Sets

Before JDBC 2.0, JDBC drivers returned read-only result sets with cursors that moved in one direction, forwards. Each element was retrieved by calling the next method on the result set.

JDBC 2.0 introduces scrollable results sets whose values can be read and updated if reading and updating is supported by the underlying database. With scrollabel result sets, any row can be selected at random, and the result set can be traversed forwards and backwards.

One advantage to the new result set is you can update a set of matching rows without having to issue an additional executeUpdate call. The updates are made using JDBC calls and so no custom SQL commands need to be generated. This improves the portability of the database code you create.

Both Statements and PreparedStatements have an additional constructor that accepts a scroll type and an update type parameter. The scroll type value can be one of the following values:

ResultSet.TYPE_FORWARD_ONLY Default behavior in JDBC 1.0, application can only call next() on the result set.

ResultSet.SCROLL_SENSITIVE ResultSet is fully navigable and updates are reflected in the result set as they occur.

ResultSet.SCROLL_INSENSITIVE Result set is fully navigable, but updates are only visible after the result set is closed. You need to create a new result set to see the results.

The update type parameter can be one of the following two values:

ResultSet.CONCUR_READ_ONLY The result set is read only.

ResultSet.CONCUR_UPDATABLE The result set can be updated.

Page 66: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 66 of 165

You can verify that your database supports these types by calling

con.getMetaData().supportsResultSetConcurrency() method as shown here.

Connection con = getConnection(); if(con.getMetaData().supportsResultSetConcurrency( ResultSet.SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE)) { PreparedStatement pstmt = con.prepareStatement( "select password, emailaddress, creditcard, balance from registration where theuser = ?", ResultSet.SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); }

Navigating the ResultSet

The fully scrollable result set returns a cursor which can be moved using simple commands. By default the result set cursor points to the row before the first row of the result set. A call to next() retrieves the first result set row. The cursor can also be moved by calling one of the following ResultSet methods:

beforeFirst(): Default position. Puts cursor before the first row of the result set.

first(): Puts cursor on the first row of the result set.

last(): Puts cursor before the last row of the result set.

afterLast() Puts cursor beyond last row of the result set. Calls to previous moves backwards through the ResultSet.

absolute(pos): Puts cursor at the row number position where absolute(1) is the first row and absolute(-1) is the last row.

relative(pos): Puts cursor at a row relative to its current position where relative(1) moves row cursor one row forward.

Updating the Result Set

You can update a value in a result set by calling the ResultSet.update<type> method on the row where the cursor is positioned. The type value here is the same used when retrieving a value from the result set, for example, updateString updates a String value in the result set.

This next code updates the balance for a user from the result set created earlier. The update applies only to the result set until the call to rs.updateRow(), which updates the underlying database. Closing the result set before calling updateRow will lose any edits applied to the result set.

rs.first(); updateDouble("balance", rs.getDouble("balance") - 5.00);

Inserting a new row uses the same update<type> methods. The only difference being that the method rs.moveToInsertRow is called before and rs.insertRow() is called after the fields have been initialized. You can delete the current row with a call to rs.deleteRow(). Batch Jobs

By default, every JDBC statement is sent to the database individually. Apart from the additional network requests, this process incurs additional delays if a transaction spans several of the statements. JDBC 2.0 lets you submit multiple statements at one time with the addBatch method.

Page 67: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 67 of 165

This next code shows how to use the addBatch statement. The calls to stmt.addBatch append statements to the original Statement, and the call to executeBatch submits the entire statement with all the appends to the database.

Statement stmt = con.createStatement(); stmt.addBatch( "update registration set balance=balance-5.00 where theuser="+theuser); stmt.addBatch( "insert into auctionitems( description, startprice) values("+description+","+startprice+")"); int[ ] results = stmt.executeBatch();

The return result of the addBatch method is an array of row counts affected for each statement executed

in the batch job. If a problem occurred, a java.sql.BatchUpdateException is thrown. An incomplete array

of row counts can be obtained from BatchUpdateException by calling its getUpdateCounts method.

Storing Classes, Images and Other Large Objects

Many databases can store binary data as part of a row if the database field is assigned a long raw, longvarbinary, or other similar type. These fields can accommodate up to two Gigabytes of data. This means if you can convert the data into a binary stream or array of bytes, it can be stored and retrieved from the database in the same way you would store a string or double.

This technique can be used to store and retrieve images and Java objects.

Storing and retrieving an image: It is very easy to store an object that can be serialized or converted to a byte array. Unfortunately, java.awt.Image is not Serializable. However, as shown in this next code example, you can store the image data to a file and store the the information in the file as bytes in a database binary field.

int itemnumber=400456; File file = new File(itemnumber+".jpg"); FileInputStream fis = new FileInputStream(file); PreparedStatement pstmt = con.prepareStatement( "update auctionitems set theimage=? where id= ?"); pstmt.setBinaryStream(1, fis, (int)file.length()): pstmt.setInt(2, itemnumber); pstmt.executeUpdate(); pstmt.close(); fis.close();

To retrieve this image and create a byte array that can be passed to createImage, do the following:

int itemnumber=400456; byte[] imageBytes;

Page 68: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 68 of 165

PreparedStatement pstmt = con.prepareStatement( "select theimage from auctionitems where id= ?"); pstmt.setInt(1, itemnumber); ResultSet rs=pstmt.executeQuery(); if(rs.next()) { imageBytes = rs.getBytes(1); } pstmt.close(); rs.close(); Image auctionimage = Toolkit.getDefaultToolkit().createImage( imageBytes);

Storing and retrieving an object: A class can be serialized to a binary database field in much the same way as the image was in the previous example. In this example, the RegistrationImpl class is changed to support default serialization by adding implements Serializable to the Class declaration.

Next, a ByteArrayInputStream is created to be passed as the JDBC Binary Stream. To create the ByteArrayInputStream, RegistrationImpl is first piped through an ObjectOutputStream to an underlying ByteArrayInputStream with a call to RegistrationImpl.writeObject The ByteArrayInputStream is then converted to a byte array, which can then be used to create the ByteArrayInputStream. The create method in RegistrationServer.java is changed as follows:

public registration.RegistrationPK create( String theuser, String password, String emailaddress, String creditcard) throws registration.CreateException{ double balance=0; Connection con = null; PreparedStatement ps = null;; try { con=getConnection(); RegistrationImpl reg= new RegistrationImpl(); reg.theuser = theuser; reg.password = password; reg.emailaddress = emailaddress; reg.creditcard = creditcard; reg.balance = balance; ByteArrayOutputStream regStore = new ByteArrayOutputStream(); ObjectOutputStream regObjectStream = new ObjectOutputStream(regStore); regObjectStream.writeObject(reg); byte[] regBytes=regStore.toByteArray(); regObjectStream.close(); regStore.close();

Page 69: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 69 of 165

ByteArrayInputStream regArrayStream = new ByteArrayInputStream(regBytes); ps=con.prepareStatement( "insert into registration ( theuser, theclass) values (?, ?)"); ps.setString(1, theuser); ps.setBinaryStream(2, regArrayStream, regBytes.length); if (ps.executeUpdate() != 1) { throw new CreateException (); } RegistrationPK primaryKey = new RegistrationPKImpl(); primaryKey.theuser(theuser); return primaryKey; } catch (IOException ioe) { throw new CreateException (); } catch (CreateException ce) { throw ce; } catch (SQLException sqe) { System.out.println("sqe="+sqe); throw new CreateException (); } finally { try { ps.close(); con.close(); } catch (Exception ignore) { } } }

The object is retrieved and reconstructed by extracting the bytes from the database, creating a

ByteArrayInputStream from those bytes to be read from an ObjectInputStream, and calling readObject to

create the instance again.

This next example shows the changes needed to the RegistrationServer.refresh method to retrieve the registration instance from the database.

private Registration refresh(RegistrationPK pk) throws FinderException { if (pk == null) { throw new FinderException (); } Connection con = null; PreparedStatement ps = null; try { con=getConnection(); ps=con.prepareStatement(" select theclass from registration where theuser = ?");

Page 70: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 70 of 165

ps.setString(1, pk.theuser()); ps.executeQuery(); ResultSet rs = ps.getResultSet(); if(rs.next()){ byte[] regBytes = rs.getBytes(1); ByteArrayInputStream regArrayStream = new ByteArrayInputStream(regBytes); ObjectInputStream regObjectStream = new ObjectInputStream( regArrayStream); RegistrationImpl reg= (RegistrationImpl) regObjectStream.readObject(); return reg; } else { throw new FinderException (); } } catch (Exception sqe) { System.out.println("exception "+sqe); throw new FinderException (); } finally { try { rs.close(); ps.close(); con.close(); } catch (Exception ignore) {} } }

executeQuery – Executes the SQL query and returns the data in a table (ResultSet) – The resulting table may be empty but never null ResultSet results = statement.executeQuery("SELECT a, b FROM table"); • executeUpdate – Used to execute for INSERT, UPDATE, or DELETE SQL statements – The return is the number of rows that were affected in the database – Supports Data Definition Language (DDL) statements CREATE TABLE, DROP TABLE and ALTER TABLE int rows = statement.executeUpdate("DELETE FROM EMPLOYEES" +

"WHERE STATUS=0");

Q.Explain Prepared Statements and Stored Procedures in JDBC?

Prepared Statements The PreparedStatement interface extends the Statement interface you used in Chapter 3. It enables a SQL statement to contain parameters like a function definition, and you can execute a single statement repeatedly with different values for those parameters. The act of assigning values

Page 71: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 71 of 165

to parameters is called binding parameters. You might want to use a prepared statement when updating a group of objects stored on the same table. For example, if you were updating many bank accounts at once, you might have a loop calling: Statement statement = c.createStatement( ); int i; for(i=0; i<accounts.length; i++) statement.executeUpdate("UPDATE account " + "SET balance = " + accounts[i].getBalance( ) + "WHERE id = " + accounts[i].getId( )); c.commit( ); statement.close( ); This statement creates the same query plan each time through the loop. Instead of calling this same statement repeatedly with different inputs, you can instead use a PreparedStatement: PreparedStatement statement = c.prepareStatement( "UPDATE account " + "SET balance = ? " + "WHERE id = ?"); int i; for(i=0; i<accounts.length; i++) { statement.setFloat(1, accounts[i].getBalance( )); statement.setInt(2, accounts[i].getId( )); statement.execute( ); statement.clearParameters( ) } c.commit( ); statement.close( ); With a prepared statement, you send the actual SQL to the database when you get the PreparedStatement object through the prepareStatement( ) method in java.sql.Connection. Keep in mind that you have not yet actually executed any SQL. You execute that prepared SQL statement multiple times inside the for() loop, but you build the query plan only a single time. Before each execution of the prepared statement, you tell JDBC which values to use as input for that execution of the statement. In order to bind the input parameters, PreparedStatement provides setXXX() methods (such as setFloat() and setInt()) that mirror the getXXX() methods you saw in java.sql.ResultSet. Just as the getXXX( ) methods read results according to the order in which you constructed your SQL, the setXXX() methods bind parameters from left to right in the order you placed them in the prepared statement. In the previous example, I bound parameter 1 as a float to the account balance that I retrieved from the account object. The first ? was thus associated with parameter 1.

Stored Procedures While prepared statements let you access similar database queries through a single PreparedStatement object, stored procedures attempt to take the "black box" concept for database access one step further. A stored procedure is built inside the database before you run your application. You access that stored procedure by name at runtime. In other words, a stored procedure is almost like a method you call in the database. Stored procedures have the following advantages: • Because the procedure is precompiled in the database for most database engines, it executes much faster than dynamic SQL, which needs to be re-interpreted each time it is issued. Even if your database does not compile the procedure before it runs, it will be precompiled for subsequent runs just like prepared statements. • Syntax errors in the stored procedure can be caught at compile time rather than at runtime. • Java developers need to know only the name of the procedure and its inputs and outputs. The way in which the procedure is implemented—the tables it accesses, the structure of those tables, etc.—is completely unimportant. A stored procedure is written with variables as argument place holders, which are passed when the procedure is called through column binding. Column binding is a fancy way of specifying the parameters to a stored procedure. You will see exactly how this is done in the following examples. A Sybase stored procedure might look like this: DROP PROCEDURE sp_select_min_bal

Page 72: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 72 of 165

GO CREATE PROCEDURE sp_select_min_bal @balance, AS SELECT account_id FROM account WHERE balance > @balance GO The name of this stored procedure is sp_select_min_bal. It accepts a single argument identified by the @ sign. That single argument is the minimum balance. The stored procedure produces a result set containing all accounts with a balance greater than that minimum balance. While this stored procedure produces a result set, you can also have procedures that return output parameters. Here's an even more complex stored procedure, written in Oracle's stored procedure language, that calculates interest and returns the new balance: CREATE OR REPLACE PROCEDURE sp_interest (id IN INTEGER, bal IN OUT FLOAT) IS BEGIN SELECT balance INTO bal FROM account WHERE account_id = id; bal := bal + bal * 0.03; UPDATE account SET balance = bal WHERE account_id = id; END; This stored procedure accepts two arguments—the variables in the parentheses—and does complex processing that does not (and cannot) occur in the embedded SQL you have been using so far. It actually performs two SQL statements and a calculation all in one procedure. The first part grabs the current balance; the second part takes the balance and increases it by 3 percent; and the third part updates the balance. In your Java application, you could use it like this: try { CallableStatement statement; int i; statement = c.prepareCall("{call sp_interest[(?,?)]}"); statement.registerOutParameter(2, java.sql.Types.FLOAT); for(i=1; i<accounts.length; i++) { statement.setInt(1, accounts[i].getId( )); statement.execute( ); System.out.println("New balance: " + statement.getFloat(2)); } c.commit( ); statement.close( ); c.close( ); } The CallableStatement class is very similar to the PreparedStatement class. Using prepareCall( ) instead of prepareStatement(), you indicate which procedure you want to call when you initialize your CallableStatement object. Unfortunately, this is one time when ANSI SQL2 simply is not enough for portability. Different database engines use different syntaxes for these calls. JDBC, however, does provide a database-independent, stored-procedure escape syntax in the form {call procedure_name[(?, ?)]}. For stored procedures with return values, the escape syntax is: {? = call procedure_name[(?,?)]}. In this escape syntax, each ? represents a place holder for either procedure inputs or return values. The JDBC driver then translates this

escape syntax into the driver's own stored procedure syntax.

Page 73: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 73 of 165

If your stored procedure has output parameters, you need to register their types using registerOutParameter( ) before executing the stored procedure. This step tells JDBC what datatype the parameter in question will be. The previous example did it like this: CallableStatement statement; int i; statement = c.prepareCall("{call sp_interest[(?,?)]}"); statement.registerOutParameter(2, java.sql.Types.FLOAT); The prepareCall() method creates a stored procedure object that will make a call to the specified stored procedure. This syntax sets up the order you will use in binding parameters. By calling registerOutParameter(), you tell the CallableStatement instance to expect the second parameter as output of type float. Once this is set up, you can bind the ID using setInt(), and then get the result using getFloat(). Meta-Data Much of what you have done with JDBC so far requires you to know a lot about the database you are using, including the capabilities of the database engine and the data model against which you are operating. Requiring this level of knowledge may not bother you much, but JDBC does provide the tools to free you from these limitations. These tools come in the form of meta-data. The term "meta" here means information about your data that does not interest the end users at all, but which you need to know in order to handle the data. JDBC provides two meta-data classes: java.sql.ResultSetMetaData and java.sql.DatabaseMetaData. The meta-data described by these classes was included in the original JDBC ResultSet and Connection classes. The team that developed the JDBC specification decided instead that it was better to keep the ResultSet and Connection classes small and simple to serve the most common database requirements. The extra functionality could be served by creating meta-data classes to provide the often esoteric information required by a minority of developers. Result Set Meta-Data As its name implies, the ResultSetMetaData class provides extra information about ResultSet objects returned from a database query. In the embedded queries you made earlier in the book, you hardcoded into your queries much of the information a ResultSetMetaData object gives you. This class provides you with answers to the following questions: • How many columns are in the result set? • Are column names case-sensitive? • Can you search on a given column? • Is NULL a valid value for a given column? • How many characters is the maximum display size for a given column? • What label should be used in a display header for the column? • What is the name of a given column? • What table did a given column come from? • What is the datatype of a given column? If you have a generic database class that blindly receives SQL to execute from other classes, this is the sort of information you need in order to process any result sets that are produced. Take a look at the following code, for example: public ArrayList executeSQL(String sql) { ArrayList results = new ArrayList( ); try { Statement stmt = conn.createStatement( ); if( stmt.execute(sql) ) { ResultSet rs = stmt.getResultSet( ); ResultSetMetaData meta = rs.getMetaData( ); int count; count = meta.getColumnCount( ); while( rs.next( ) ) { HashMap cols = new Hashtable(count); int i; for(i=0; i<count; i++) { Object ob = rs.getObject(i+1);

Page 74: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 74 of 165

if( rs.wasNull( ) ) { ob = null; } cols.put(meta.getColumnLabel(i+1), ob); } results.add(cols); } return results; } return null; } catch( SQLException e ) { e.printStackTrace( ); return null; } } This example introduces the execute( ) method in the Statement class (as well as its subclasses). This method is more generic than executeUpdate() or executeQuery() in that it will send any SQL you pass it without any preconception regarding what kind of SQL it is. If the SQL produced a result set—if it was a query—it will return true. For modifications that do not produce result sets, execute() returns false. If it did produce a result set, you can get that result set by calling the getResultSet( ) method. For a given ResultSet object, an application can call the ResultSet's getMetaData( ) method in order to get its associated ResultSetMetaData object. You can then use this meta-data object to find out extra information about the result set and its columns. In the previous example, whenever the execute() method in the Statement class returns a true value, it gets the ResultSet object using the getResultSet() method and the ResultSetMetaData object for that result set using the getMetaData() method. For each row in the result set, the example figures out the column count using the meta-data method getColumnCount(). Knowing the column count, the application can then retrieve each column. Once it has a column, it again uses the meta-data to get a column label via getColumnLabel() and stick the column's value in a HashMap with the label as a key and the column's meta-data value as an element. The entire set of rows is then returned as an ArrayList. Using Transactions

There are times when you do not want one statement to take effect unless another one completes. For example, when the proprietor of The Coffee Break updates the amount of coffee sold each week, he will also want to update the total amount sold to date. However, he will not want to update one without updating the other; otherwise, the data will be inconsistent. The way to be sure that either both actions occur or neither action occurs is to use a transaction. A transaction is a set of one or more statements that are executed together as a unit, so either all of the statements are executed, or none of the statements is executed.

Disabling Auto-commit Mode

When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and is automatically committed right after it is executed. (To be more precise, the default is for an SQL statement to be committed when it is completed, not when it is executed. A statement is completed when all of its result sets and update counts have been retrieved. In almost all cases, however, a statement is completed, and therefore committed, right after it is executed.)

The way to allow two or more statements to be grouped into a transaction is to disable auto-commit mode. This is demonstrated in the following line of code, where con is an active connection:

con.setAutoCommit(false);

Page 75: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 75 of 165

Committing a Transaction

Once auto-commit mode is disabled, no SQL statements are committed until you call the method commit explicitly. All statements executed after the previous call to the method commit are included in the current transaction and committed together as a unit. The following code, in which con is an active connection, illustrates a transaction:

con.setAutoCommit(false); PreparedStatement updateSales = con.prepareStatement( "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?"); updateSales.setInt(1, 50); updateSales.setString(2, "Colombian"); updateSales.executeUpdate(); PreparedStatement updateTotal = con.prepareStatement( "UPDATE COFFEES SET TOTAL = TOTAL + ? WHERE COF_NAME LIKE ?"); updateTotal.setInt(1, 50); updateTotal.setString(2, "Colombian"); updateTotal.executeUpdate(); con.commit(); con.setAutoCommit(true);

In this example, auto-commit mode is disabled for the connection con, which means that the two prepared statements updateSales and updateTotal are committed together when the method commit is called. Whenever the commit method is called (either automatically when auto-commit mode is enabled or explicitly when it is disabled), all changes resulting from statements in the transaction are made permanent. In this case, that means that the SALES and TOTAL columns for Colombian coffee have been changed to 50 (if TOTAL had been 0 previously) and will retain this value until they are changed with another update statement. TransactionPairs.java illustrates a similar kind of transaction but uses a for loop to supply values to the setXXX methods for updateSales and updateTotal.

The final line of the previous example enables auto-commit mode, which means that each statement is once again committed automatically when it is completed. Then, you are back to the default state where you do not have to call the method commit yourself. It is advisable to disable auto-commit mode only while you want to be in transaction mode. This way, you avoid holding database locks for multiple statements, which increases the likelihood of conflicts with other users.

Using Transactions to Preserve Data Integrity

In addition to grouping statements together for execution as a unit, transactions can help to preserve the integrity of the data in a table. For instance, suppose that an employee was supposed to enter new coffee prices in the table COFFEES but delayed doing it for a few days. In the meantime, prices rose, and today the owner is in the process of entering the higher prices. The employee finally gets around to entering the now outdated prices at the same time that the owner is trying to update the table. After inserting the outdated prices, the employee realizes that they are no longer valid and calls the Connection method rollback to undo their effects. (The method rollback aborts a transaction and restores values to what they were before the attempted update.) At the same time, the owner is executing a SELECT statement and printing out the new prices. In this situation, it is possible that the owner will print a price that was later rolled back to its previous value, making the printed price incorrect.

This kind of situation can be avoided by using transactions, providing some level of protection against conflicts that arise when two users access data at the same time.

To avoid conflicts during a transaction, a DBMS uses locks, mechanisms for blocking access by others to the data that is being accessed by the transaction. (Note that in auto-commit mode, where each

Page 76: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 76 of 165

statement is a transaction, locks are held for only one statement.) Once a lock is set, it remains in force until the transaction is committed or rolled back. For example, a DBMS could lock a row of a table until updates to it have been committed. The effect of this lock would be to prevent a user from getting a dirty read, that is, reading a value before it is made permanent. (Accessing an updated value that has not been committed is considered a dirty read because it is possible for that value to be rolled back to its previous value. If you read a value that is later rolled back, you will have read an invalid value.)

How locks are set is determined by what is called a transaction isolation level, which can range from not supporting transactions at all to supporting transactions that enforce very strict access rules.

One example of a transaction isolation level is TRANSACTION_READ_COMMITTED, which will not allow a value to be accessed until after it has been committed. In other words, if the transaction isolation level is set to TRANSACTION_READ_COMMITTED, the DBMS does not allow dirty reads to occur. The interface Connection includes five values which represent the transaction isolation levels you can use in JDBC.

Normally, you do not need to do anything about the transaction isolation level; you can just use the default one for your DBMS. JDBC allows you to find out what transaction isolation level your DBMS is set to (using the Connection method getTransactionIsolation) and also allows you to set it to another level (using the Connection method setTransactionIsolation). Keep in mind, however, that even though JDBC allows you to set a transaction isolation level, doing so has no effect unless the driver and DBMS you are using support it.

Setting and Rolling Back to a Savepoint

The JDBC 3.0 API adds the method Connection.setSavepoint, which sets a savepoint within the current transaction. The Connection.rollback method has been overloaded to take a savepoint argument.

The example below inserts a row into a table, sets the savepoint svpt1, and then inserts a second row. When the transaction is later rolled back to svpt1, the second insertion is undone, but the first insertion remains intact. In other words, when the transaction is committed, only the row containing ?FIRST? will be added to TAB1:

Statement stmt = conn.createStatement(); int rows = stmt.executeUpdate("INSERT INTO TAB1 (COL1) VALUES " + "(?FIRST?)"); // set savepoint Savepoint svpt1 = conn.setSavepoint("SAVEPOINT_1"); rows = stmt.executeUpdate("INSERT INTO TAB1 (COL1) " + "VALUES (?SECOND?)"); ... conn.rollback(svpt1); ... conn.commit();

Releasing a Savepoint

The method Connection.releaseSavepoint takes a Savepoint object as a parameter and removes it from the current transaction.

Once a savepoint has been released, attempting to reference it in a rollback operation causes an SQLException to be thrown. Any savepoints that have been created in a transaction are automatically released and become invalid when the transaction is committed, or when the entire transaction is rolled back. Rolling a transaction back to a savepoint automatically releases and makes invalid any other savepoints that were created after the savepoint in question.

Page 77: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 77 of 165

When to Call the Method rollback

As mentioned earlier, calling the method rollback aborts a transaction and returns any values that were modified to their previous values. If you are trying to execute one or more statements in a transaction and get an SQLException, you should call the method rollback to abort the transaction and start the transaction all over again. That is the only way to be sure of what has been committed and what has not been committed. Catching an SQLException tells you that something is wrong, but it does not tell you what was or was not committed. Since you cannot count on the fact that nothing was committed, calling the method rollback is the only way to be sure.

TransactionPairs.java demonstrates a transaction and includes a catch block that invokes the method rollback. In this particular situation, it is not really necessary to call rollback, and we do it mainly to illustrate how it is done. If the application continued and used the results of the transaction, however, it would be necessary to include a call to rollback in the catch block in order to protect against using possibly incorrect data.

Using Joins Sometimes you need to use two or more tables to get the data you want. For example, suppose the proprietor of The Coffee Break wants a list of the coffees he buys from Acme, Inc. This involves information in the COFFEES table as well as the yet-to-be-created SUPPLIERS table. This is a case where a join is needed. A join is a database operation that relates two or more tables by means of values that they share in common. In our example database, the tables COFFEES and SUPPLIERS both have the column SUP_ID, which can be used to join them.

Before we go any further, we need to create the table SUPPLIERS and populate it with values.

The code below creates the table SUPPLIERS:

String createSUPPLIERS = "create table SUPPLIERS " + "(SUP_ID INTEGER, SUP_NAME VARCHAR(40), " + "STREET VARCHAR(40), CITY VARCHAR(20), " + "STATE CHAR(2), ZIP CHAR(5))"; stmt.executeUpdate(createSUPPLIERS);

The following code inserts rows for three suppliers into SUPPLIERS:

stmt.executeUpdate("insert into SUPPLIERS values (101, " + "'Acme, Inc.', '99 Market Street', 'Groundsville', " + "'CA', '95199'"); stmt.executeUpdate("Insert into SUPPLIERS values (49," + "'Superior Coffee', '1 Party Place', 'Mendocino', 'CA', " + "'95460'"); stmt.executeUpdate("Insert into SUPPLIERS values (150, " + "'The High Ground', '100 Coffee Lane', 'Meadows', 'CA', " + "'93966'");

The following code selects the whole table and lets us see what the table SUPPLIERS looks like:

ResultSet rs = stmt.executeQuery("select * from SUPPLIERS");

The result set will look similar to this:

SUP_ID SUP_NAME STREET CITY STATE ZIP

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

101 Acme, Inc. 99 Market Street Groundsville CA 95199

Page 78: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 78 of 165

49 Superior Coffee 1 Party Place Mendocino CA 95460

150 The High Ground 100 Coffee Lane Meadows CA 93966

Now that we have the tables COFFEES and SUPPLIERS, we can proceed with the scenario where the owner wants to get a list of the coffees he buys from a particular supplier. The names of the suppliers are in the table SUPPLIERS, and the names of the coffees are in the table COFFEES. Since both tables have the column SUP_ID, this column can be used in a join. It follows that you need some way to distinguish which SUP_ID column you are referring to. This is done by preceding the column name with the table name, as in "COFFEES.SUP_ID" to indicate that you mean the column SUP_ID in the table COFFEES. The following code, in which stmt is a Statement object, selects the coffees bought from Acme, Inc.:

String query = " SELECT COFFEES.COF_NAME " + "FROM COFFEES, SUPPLIERS " + "WHERE SUPPLIERS.SUP_NAME LIKE 'Acme, Inc.' " + "and SUPPLIERS.SUP_ID = COFFEES.SUP_ID"; ResultSet rs = stmt.executeQuery(query); System.out.println("Coffees bought from Acme, Inc.: "); while (rs.next()) { String coffeeName = rs.getString("COF_NAME"); System.out.println(" " + coffeeName); }

This will produce the following output:

Coffees bought from Acme, Inc.: Colombian Colombian_Decaf

Page 79: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 79 of 165

____________________________________________________________________________________

* A type 1 driver translates JDBC to ODBC and relies on an ODBC driver to communicate with the

database.

* A type 2 driver is a driver, written partly in the Java programming language and partly in native code,

that communicates with the client API of a database.

* A type 3 driver is a pure Java client library that uses a database-independent protocol to

communicate database requests to a server component, which then translates the requests into a

database-specific protocol.

* A type 4 driver is a pure Java library that translates JDBC requests directly to a database-specific protocol.

* The JDBC API supports both two-tier and three-tier processing models for database access.

* JDBC programming interface is found in "java.sql" and "javax.sql" packages.

* DriverManager :-"Driver Manger" Manages all the Drivers found in JDBC environment, load the most appropriate driver for connectivity.

* Connection :-Connection class creates objects which represents connection and it's object also helps in creating object of Statement, PreparedStatement and CallableStatement classes.

* Statement :-Statement object is used to execute query and also store it's value to "Resultset" object.

* PreparedStatement:-It can be used in place of "Statement", PreparedStatement's performance is high as compared to "Statement" class, represents a precompiled SQL statement .

* Callable Statement:-Callable statement support stored procedure of RDBMS' ,using it's object you can execute stored procedure of database application.

* ResultSet :-Resultset object is used to store the result retrieve from database using "Statement" or "PreparedStatement" , etc

* SQLException:- SqlException class is used to represent error or warning during access from database or during connectivity.

IMP Question Set

SR No. Question Reference page No.

1 Q. Write a note on JDBC Drivers?

57

2 Q. Explain JDBC architecture?

57

3 Q. Explain Steps of to access database through JDBC?

60

4 Q. Explain Prepared Statements and Stored Procedures in JDBC?

70

Quick Revision

Page 80: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 80 of 165

INDEX

SR.NO TOPIC

PAGE NO.

From To

1 Threads and Multithreading 82 95

2 Networking 96 129

3 RMI 130 165

Page 81: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 81 of 165

Syllabus

Threads and Multithreading, The Lifecycle of a thread, Creating and running threads, Creating the

Service Threads, Schedules Tasks using JVM, Thread-safe variables, Synchronizing threads,

Communication between threads.

Overview of Networking, Working with URL, Connecting to a Server, Implementing Servers, Serving

multiple Clients, Sending E-Mail, Socket Programming, Internet Addresses, URL Connections, Accessing

Network interface parameters, Posting Form Data, Cookies, Overview of Understanding the Sockets

Direct Protocol.

Introduction to distributed object system, Distributed Object Technologies, RMI for distributed computing,

RMI Architecture, RMI Registry Service, Parameter Passing in Remote Methods, Creating RMI

application, Steps involved in running the RMI application, Using RMI with Applets.

Page 82: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 82 of 165

CHAPTER 1: THREADS AND MULTITHREADING

Topic Covered:

Threads and Multithreading, The Lifecycle of a thread, Creating and running threads, Creating the

Service Threads, Schedules Tasks using JVM, Thread-safe variables, Synchronizing threads,

Communication between threads.

Threads and Multithreading

You are probably familiar with multitasking: the ability to have more than one program working at what seems like the same time. For example, you can print while editing or sending a fax. Of course, unless you have a multiple-processor machine, what is really going on is that the operating system is doling out resources to each program, giving the impression of parallel activity. This resource distribution is possible because while you may think you are keeping the computer busy by, for example, entering data, most of the CPU's time will be idle. (A fast typist takes around 1/20 of a second per character typed, after all, which is a huge time interval for a computer.) Multitasking can be done in two ways, depending on whether the operating system interrupts programs without consulting with them first, or whether pro-grams are only interrupted when they are willing to yield control. The former is called preemptive multitasking; the latter is called cooperative (or, simply, non-preemptive) multitasking Windows 3.1 and Mac OS 9 are cooperative multitasking systems, and UNIX/Linux, Windows NT (and Windows 95 for 32-bit programs), and OS X are preemptive. (Although harder to implement, preemptive multitasking is much more effective. With cooperative multitasking, a badly behaved program can hog everything.) Multithreaded programs extend the idea of multitasking by taking it one level lower: individual programs will appear to do multiple tasks at the same time. Each task is usually called a thread—which is short for thread of control. Programs that can run more than one thread at once are said to be multithreaded. Think of each thread as running in a separate context: contexts make it seem as though each thread has its own CPU—with registers, memory, and its own code. So, what is the difference between multiple processes and multiple threads?

The essential difference is that while each process has a complete set of its own variables, threads share the same data. This sounds somewhat risky, and indeed it can be, as you will see later in this chapter. But it takes much less overhead to create and destroy individual threads than it does to launch new processes, which is why all modern operating systems support multithreading. Moreover, inter-process communication is much slower and more restrictive than communication between threads. Multithreading is extremely useful in practice. For example, a browser should be able to simultaneously download multiple images. An email program should let you read your email while it is downloading new messages. The Java programming language itself uses a thread to do garbage collection in the background—thus saving you the trouble of managing memory! Graphical user interface (GUI) programs have a separate thread for gathering user interface events from the host operating environment. This chapter shows you how to add multithreading capability to your Java applications and applets. Fair warning: multithreading can get very complex. In this chapter, we present all of the tools that the Java programming language provides for thread programming. We explain their use and limitations and give some simple but typical examples. NOTE In many programming languages, you have to use an external thread package to do multithreaded programming. The Java programming language builds in multithreading, which makes your job much easier.

Page 83: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 83 of 165

Q. Explain Lifecycle of Threads?

Life Cycle of a Thread:

A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. Following diagram shows complete life cycle of a thread.

Above mentioned stages are explained here:

New: A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread.

Page 84: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 84 of 165

Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task.

Waiting: Sometimes a thread transitions to the waiting state while the thread waits for another thread to perform a task.A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.

Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.

Terminated: A runnable thread enters the terminated state when it completes its task or otherwise terminates.

Q. Write a note on creating and running threads?

Creating and running threads

Creating a Thread

The application in which an applet is running calls the applet's start method when the user visits the

applet's page. The Clock applet creates a Thread, clockThread, in its start method with the code shown

highlighted:

public void start() { if (clockThread == null) { clockThread = new Thread(this, "Clock"); clockThread.start(); } } After the highlighted statement has been executed, clockThread is in the New Thread state. A thread in

this state is merely an empty Thread object; no system resources have been allocated for it yet. When a

thread is in this state, you can only start the thread. Calling any method besides start when a thread is in

this state makes no sense and causes an IllegalThreadStateException. In fact, the runtime system throws

an IllegalThreadStateException whenever a method is called on a thread and that thread’s state does not

allow for that method call.

Note that the Clock instance is the first argument to the thread constructor. The first argument to this thread constructor must implement the Runnable interface and becomes the thread’s target. The clock thread gets its run method from its target Runnable object—in this case, the Clock instance. The second argument is just a name for the thread.

Starting a Thread

Now consider the next line of code in Clock's start method shown here highlighted:

public void start() { if (clockThread == null) { clockThread = new Thread(this, "Clock"); clockThread.start(); } } The start method creates the system resources necessary to run the thread, schedules the thread to run,

and calls the thread's run method. clockThread's run method is defined in the Clock class.

Page 85: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 85 of 165

After the start method has returned, the thread is "running." Yet, it's somewhat more complex than that. As the previous figure shows, a thread that has been started is in the Runnable state. Many computers have a single processor, thus making it impossible to run all "running" threads at the same time. The Java runtime system must implement a scheduling scheme that shares the processor among all "running"

threads. (See Thread Scheduling for more information about scheduling.) So at any given time, a

"running" thread may be waiting for its turn in the CPU.

Here's another look at Clock's run method:

public void run() { Thread myThread = Thread.currentThread(); while (clockThread == myThread) { repaint(); try { Thread.sleep(1000); } catch (InterruptedException e) { //the VM doesn’t want us to sleep anymore, //so get back to work } } } Clock's run method loops while the condition clockThread == myThread is true. This exit condition is

explained in more detail in the section Stopping a Thread. For now, however, know that it allows the

thread, and thus the applet, to exit gracefully.

Within the loop, the applet repaints itself and then tells the thread to sleep for one second (1000 milliseconds). An applet's repaint method ultimately calls the applet's paint method, which does the actual update of the applet's display area. The Clock paint method gets the current time, formats, and displays it:

public void paint(Graphics g) { //get the time and convert it to a date Calendar cal = Calendar.getInstance(); Date date = cal.getTime(); //format it and display it DateFormat dateFormatter = DateFormat.getTimeInstance(); g.drawString(dateFormatter.format(date), 5, 10); }

Making a Thread Not Runnable

A thread becomes Not Runnable when one of these events occurs:

Its sleep method is invoked.

The thread calls the wait method to wait for a specific condition to be satisifed.

The thread is blocking on I/O.

The clockThread in the Clock applet becomes Not Runnable when the run method calls sleep on the

current thread:

public void run() { Thread myThread = Thread.currentThread(); while (clockThread == myThread) { repaint(); try {

Page 86: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 86 of 165

Thread.sleep(1000); } catch (InterruptedException e) { //the VM doesn’t want us to sleep anymore, //so get back to work } } } During the second that the clockThread is asleep, the thread does not run, even if the processor becomes

available. After the second has elapsed, the thread becomes Runnable again; if the processor becomes

available, the thread begins running again.

For each entrance into the Not Runnable state, a specific and distinct exit returns the thread to the Runnable state. An exit works only for its corresponding entrance. For example, if a thread has been put to sleep, the specified number of milliseconds must elapse before the thread becomes Runnable again. The following list describes the exit for every entrance into the Not Runnable state.

If a thread has been put to sleep, the specified number of milliseconds must elapse.

If a thread is waiting for a condition, then another object must notify the waiting thread of a change in

condition by calling notify or notifyAll. More information is available in Synchronizing Threads .

If a thread is blocked on I/O, the I/O must complete.

Stopping a Thread

Although the Thread class does contain a stop method, this method is deprecated and should not be

used to stop a thread because it is unsafe. Rather, a thread should arrange for its own death by having a

run method that terminates naturally. For example, the while loop in this run method is a finite loop: It will

iterate 100 times and then exit:

public void run() { int i = 0; while (i < 100) { i++; System.out.println("i = " + i); } } A thread with this run method dies naturally when the loop completes and the run method exits.

Let's look at how the Clock applet thread arranges for its own death. You might want to use this technique with your applet threads. Recall Clock's run method:

public void run() { Thread myThread = Thread.currentThread(); while (clockThread == myThread) { repaint(); try { Thread.sleep(1000); } catch (InterruptedException e) { //the VM doesn’t want us to sleep anymore, //so get back to work } } }

Page 87: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 87 of 165

The exit condition for this run method is the exit condition for the while loop because there is no code

after the while loop:

while (clockThread == myThread) { This condition indicates that the loop will exit when the currently executing thread is not equal to

clockThread. When would this ever be the case?

When you leave the page, the application in which the applet is running calls the applet's stop method. This method then sets the clockThread to null, thereby telling the main loop in the run method to terminate:

public void stop() { // applets' stop method clockThread = null; } If you revisit the page, the start method is called again and the clock starts up again with a new thread.

Even if you stop and start the applet faster than one iteration of the loop, clockThread will be a different

thread from myThread and the loop will still terminate.

Testing Thread State

A final word about thread state: The API for the Thread class includes a method called isAlive. The isAlive

method returns true if the thread has been started and not stopped. If the isAlive method returns false,

you know that the thread either is a New Thread or is Dead. If the isAlive method returns true, you know

that the thread is either Runnable or Not Runnable. You cannot differentiate between a New Thread or a

Dead thread. Nor can you differentiate between a Runnable thread and a Not Runnable thread.

Q. Explain How to Create Service Threads?

Creating the Service Threads

In Java, any thread can be a Daemon thread. Daemon threads are like a service providers for other threads or objects running in the same process as the daemon thread. Daemon threads are used for background supporting tasks and are only needed while normal threads are executing. If normal threads are not running and remaining threads are daemon threads then the interpreter exits.

setDaemon(true/false) ? This method is used to specify that a thread is daemon thread. public boolean isDaemon() ? This method is used to determine the thread is daemon thread or not.

The following program demonstrates the Daemon Thread:

Page 88: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 88 of 165

public class DaemonThread extends Thread { public void run() { System.out.println("Entering run method"); try { System.out.println("In run Method: currentThread() is" + Thread.currentThread()); while (true) { try { Thread.sleep(500); } catch (InterruptedException x) { } System.out.println("In run method: woke up again"); } } finally { System.out.println("Leaving run Method"); } } public static void main(String[] args) { System.out.println("Entering main Method"); DaemonThread t = new DaemonThread(); t.setDaemon(true); t.start(); try { Thread.sleep(3000); } catch (InterruptedException x) { } System.out.println("Leaving main method"); } }

Output of this program is:

C:\j2se6\thread>javac DaemonThread.java C:\j2se6\thread>java DaemonThread Entering main Method Entering run method In run Method: currentThread() isThread[Thread-0,5,main] In run method: woke up again In run method: woke up again In run method: woke up again In run method: woke up again In run method: woke up again In run method: woke up again Leaving main method C:\j2se6\thread>

Page 89: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 89 of 165

Daemon Threads A thread can be turned into a daemon thread by calling t.setDaemon(true); There is nothing demonic about such a thread. A daemon is simply a thread that has no other role in life than to serve others. Examples are timer threads that send regular "timer ticks" to other threads. When only daemon threads remain, then the program exits. There is no point in keeping the program running if all remaining threads are daemons.

Q. Write a note on thread safety?

What is thread safety?

Thread safety simply means that the fields of an object or class always maintain a valid state, as observed by other objects and classes, even when used concurrently by multiple threads.

One of the first guidelines I proposed in this column (see "Designing object initialization") is

that you should design classes such that objects maintain a valid state, from the beginning of their lifetimes to the end. If you follow this advice and create objects whose instance variables all are private and whose methods only make proper state transitions on those instance variables, you're in good shape in a single-threaded environment. But you may get into trouble when more threads come along.

Multiple threads can spell trouble for your object because often, while a method is in the process of executing, the state of your object can be temporarily invalid. When just one thread is invoking the object's methods, only one method at a time will ever be executing, and each method will be allowed to finish before another method is invoked. Thus, in a single-threaded environment, each method will be given a chance to make sure that any temporarily invalid state is changed into a valid state before the method returns.

Once you introduce multiple threads, however, the JVM may interrupt the thread executing one method while the object's instance variables are still in a temporarily invalid state. The JVM could then give a different thread a chance to execute, and that thread could call a method on the same object. All your hard work to make your instance variables private and your methods perform only valid state transformations will not be enough to prevent this second thread from observing the object in an invalid state.

Such an object would not be thread-safe, because in a multithreaded environment, the object could become corrupted or be observed to have an invalid state. A thread-safe object is one that always maintains a valid state, as observed by other classes and objects, even in a multithreaded environment.

Thread Communication Without Synchronization To avoid simultaneous access of a shared object by multiple threads, you must learn how to synchronize the access. In this section, you'll see what happens if you do not use synchronization. In the next section, you'll see how to synchronize object access. In the next test program, we simulate a bank with 10 accounts. We randomly generate transactions that move money between these accounts. There are 10 threads, one for each account. Each transaction moves a random amount of money from the account serviced by the thread to another random account. The simulation code is straightforward. We have the class Bank with the method transfer. This method transfers some amount of money from one account to another. If the source account does not have enough money in it, then the call simply returns. Here is the code for the transfer method of the Bank class. public void transfer(int from, int to, double amount) // CAUTION: unsafe when called from multiple threads { if (accounts[from] < amount) return; accounts[from] -= amount; accounts[to] += amount; ntransacts++;

Page 90: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 90 of 165

if (ntransacts % NTEST == 0) test(); } Here is the code for the TransferThread class. Its run method keeps moving money out of a fixed bank account. In each iteration, the run method picks a random target account and a random amount, calls transfer on the bank object, and then sleeps. class TransferThread extends Thread { public TransferThread(Bank b, int from, int max) { bank = b; fromAccount = from; maxAmount = max; } public void run() { try { while (!interrupted()) { int toAccount = (int)(bank.size() * Math.random()); int amount = (int)(maxAmount * Math.random()); bank.transfer(fromAccount, toAccount, amount); sleep(1); } } catch(InterruptedException e) {} } private Bank bank; private int fromAccount; private int maxAmount; } When this simulation runs, we do not know how much money is in any one bank account at any time. But we do know that the total amount of money in all the accounts should remain unchanged since all we do is move money from one account to another. Every 10,000 transactions, the transfer method calls a test method that recomputes the total and prints it out. This program never finishes. Just press CTRL+C to kill the program. Here is a typical printout: Transactions:10000 Sum: 100000 Transactions:20000 Sum: 100000 Transactions:30000 Sum: 100000 Transactions:40000 Sum: 100000 Transactions:50000 Sum: 100000 Transactions:60000 Sum: 100000 Transactions:70000 Sum: 100000 Transactions:80000 Sum: 100000 Transactions:90000 Sum: 100000 Transactions:100000 Sum: 100000 Transactions:110000 Sum: 100000 Transactions:120000 Sum: 100000 Transactions:130000 Sum: 94792 Transactions:140000 Sum: 94792 Transactions:150000 Sum: 94792

Page 91: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 91 of 165

. . . As you can see, something is very wrong. For quite a few transactions, the bank balance remains at $100,000, which is the correct total for 10 accounts of $10,000 each. But after some time, the balance changes slightly. When you run this program, you may find that errors happen quickly, or it may take a very long time for the balance to become corrupted. This situation does not inspire confidence, and you would probably not want to deposit your hard-earned money into this bank. Example 1-5 provides the complete source code. See if you can spot the problem with the code. We will unravel the mystery in the next section. Example 1-5 UnsynchBankTest.java 1. public class UnsynchBankTest 2. { 3. public static void main(String[] args) 4. { 5. Bank b = new Bank(NACCOUNTS, INITIAL_BALANCE); 6. int i; 7. for (i = 0; i < NACCOUNTS; i++) 8. { 9. TransferThread t = new TransferThread(b, i, 10. INITIAL_BALANCE); 11. t.setPriority(Thread.NORM_PRIORITY + i % 2); 12. t.start(); 13. } 14. } 15. 16. public static final int NACCOUNTS = 10; 17. public static final int INITIAL_BALANCE = 10000; 18. } 19. 20. /** 21. A bank with a number of bank accounts. 22. */ 23. class Bank 24. { 25. /** 26. Constructs the bank. 27. @param n the number of accounts 28. @param initialBalance the initial balance 29. for each account 30. */ 31. public Bank(int n, int initialBalance) 32. { 33. accounts = new int[n]; 34. int i; 35. for (i = 0; i < accounts.length; i++) 36. accounts[i] = initialBalance; 37. ntransacts = 0; 38. } 39. 40. /** 41. Transfers money from one account to another. 42. @param from the account to transfer from

Page 92: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 92 of 165

43. @param to the account to transfer to 44. @param amount the amount to transfer 45. */ 46. public void transfer(int from, int to, int amount) 47. throws InterruptedException 48. { 49. accounts[from] -= amount; 50. accounts[to] += amount; 51. ntransacts++; 52. if (ntransacts % NTEST == 0) test(); 53. } 54. 55. /** 56. Prints a test message to check the integrity 57. of this bank object. 58. */ 59. public void test() 60. { 61. int sum = 0; 62. 63. for (int i = 0; i < accounts.length; i++) 64. sum += accounts[i]; 65. 66. System.out.println("Transactions:" + ntransacts 67. + " Sum: " + sum); 68. } 69. 70. /** 71. Gets the number of accounts in the bank. 72. @return the number of accounts 73. */ 74. public int size() 75. { 76. return accounts.length; 77. } 78. 79. public static final int NTEST = 10000; 80. private final int[] accounts; 81. private long ntransacts = 0; 82. } 83. 84. /** 85. A thread that transfers money from an account to other 86. accounts in a bank. 87. */ 88. class TransferThread extends Thread 89. { 90. /** 91. Constructs a transfer thread. 92. @param b the bank between whose account money is transferred 93. @param from the account to transfer money from

Page 93: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 93 of 165

94. @param max the maximum amount of money in each transfer 95. */ 96. public TransferThread(Bank b, int from, int max) 97. { 98. bank = b; 99. fromAccount = from; 100. maxAmount = max; 101. } 102. 103. public void run() 104. { 105. try 106. { 107. while (!interrupted()) 108. { 109. for (int i = 0; i < REPS; i++) 110. { 111. int toAccount = (int)(bank.size() * Math.random()); 112. int amount = (int)(maxAmount * Math.random() / REPS); 113. bank.transfer(fromAccount, toAccount, amount); 114. sleep(1); 115. } 116. } 117. } 118. catch(InterruptedException e) {} 119. } 120. 121. private Bank bank; 122. private int fromAccount; 123. private int maxAmount; 124. private static final int REPS = 1000; 125. }

Q. Write a short note on Thread Synchronization?

Synchronizing Threads

So far, this lesson has contained examples with independent, asynchronous threads. That is, each

thread contained all of the data and methods required for its execution and didn't require any outside

resources or methods. In addition, the threads in those examples ran at their own pace without

concern over the state or activities of any other concurrently running threads.

However, there are many interesting situations where separate, concurrently running threads do share data and must consider the state and activities of other threads. One such set of programming situations are known as producer/consumer scenarios where the producer generates a stream of data which then is consumed by a consumer.

For example, imagine a Java application where one thread (the producer) writes data to a file while a second thread (the consumer) reads data from the same file. Or, as you type characters on the keyboard, the producer thread places key events in an event queue and the consumer thread reads the events from the same queue. Both of these examples use concurrent threads that share a common resource: the first shares a file, the second shares an event queue. Because the threads share a common resource, they must be synchronized in some way.

Page 94: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 94 of 165

The Producer/Consumer Example

This lesson teaches you about Java thread synchronization through a simple producer/consumer

example.

Locking an Object

The code segments within a program that access the same object from separate, concurrent threads

are called critical sections. In the Java language, a critical section can be a block or a method and

are identified with the synchronized keyword. The Java platform then associates a lock with every

object that has synchronized code.

Using the notifyAll and wait Methods

This section investigates the code in CubbyHole's put and get methods that helps the Producer and

Consumer coordinate their activities.

Avoid Starvation and Deadlock

If you write a program in which several concurrent threads are competing for resources, you must

take precautions to ensure fairness. A system is fair when each thread gets enough access to limited

resource to make reasonable progress. A fair system prevents starvation and deadlock. Starvation

occurs when one or more threads in your program is blocked from gaining access to a resource and

thus cannot make progress. Deadlock is the ultimate form of starvation; it occurs when two or more

threads are waiting on a condition that cannot be satisfied. Deadlock most often occurs when two (or

more) threads are each waiting for the other(s) to do something.

Page 95: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 95 of 165

______________________________________________________________________

* Multithreaded programs extend the idea of multitasking by taking it one level lower: individual programs will appear to do multiple tasks at the same time. Each task is usually called a thread -which is short for thread of control. Programs that can run more than one thread at once are said to be multithreaded.

* The Java programming language itself uses a thread to do garbage collection in the background—thus saving you the trouble of managing memory! Graphical user interface (GUI) programs have a separate thread for gathering user interface events from the host operating environment.

* A thread becomes Not Runnable when one of these events occurs: Its sleep method is invoked. The thread calls the wait method to wait for a specific condition to be satisfied. The thread is blocking on I/O.

* New: A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread.

* Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task.

* Waiting: Sometimes a thread transitions to the waiting state while the thread waits for another thread to perform a task. A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.

* Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.

* Terminated: A runnable thread enters the terminated state when it completes its task or otherwise terminates.

* A thread can be turned into a daemon thread by calling t.setDaemon(true);

* There is nothing demonic about such a thread. A daemon is simply a thread that has no other role in life than to serve others.

* Thread safety simply means that the fields of an object or class always maintain a valid state, as observed by other objects and classes, even when used concurrently by multiple threads.

IMP Question Set

SR No. Question Reference page No.

1 Q. Explain Lifecycle of Threads? 83

2 Q. Write a note on creating and running threads? 84

3 Q. Explain How to Create Service Threads? 87

4 Q. Write a note on thread safety? 89

5 Q. Write a short note on Thread Synchronization?

93

Quick Revision

Page 96: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 96 of 165

CHAPTER 2: NETWORKING

Topic Covered:

Overview of Networking, Working with URL, Connecting to a Server, Implementing Servers, Serving

multiple Clients, Sending E-Mail, Socket Programming, Internet Addresses, URL Connections, Accessing

Network interface parameters, Posting Form Data, Cookies, Overview of Understanding the Sockets

Direct Protocol.

Overview of Networking

Introduction The Internet is all about connecting machines together. One of the most exciting aspects of Java is that it incorporates an easy-to-use, cross-platform model for network communications that makes it possible to learn network programming without years of study. This opens up a whole new class of applications to programmers.

Ken Thompson and Dennis Ritchie developed UNIX in concert with the C language at Bell Telephone Laboratories, Murray Hill, New Jersey, in 1969. For many years, the development of UNIX remained in Bell Labs and in a few universities and research facilities that had the DEC PDP machines it was designed to be run on. In 1978, Bill Joy was leading a project at Cal Berkeley to add many new features to UNIX, such as virtual memory and full-screen display capabilities. By early 1984, just as Bill was leaving to found Sun Microsystems, he shipped 4.2BSD, commonly known as Berkeley UNIX. 4.2BSD came with a fast file system, reliable signals, Interprocess communication, and, most important, networking. The networking support first found in 4.2 eventually became the de facto standard for the Internet. Berkeley’s implementation of TCP/IP remains the primary standard for communications within the Internet. The socket paradigm for Interprocess and network communication has also been widely adopted outside of Berkeley. Socket Overview A network socket is a lot like an electrical socket. Various plugs around the network have a standard way of delivering their payload. Anything that understands the standard protocol can “plug in” to the socket and communicate. With electrical sockets, it doesn’t matter if you plug in a lamp or a toaster; as long as they are expecting 60Hz, 115-volt electricity, the devices will work. Think how your electric bill is created. There is a meter somewhere between your house and the rest of the network. For each kilowatt of power that goes through that meter, you are billed. The bill comes to your “address.” So even though the electricity flows freely around the power grid, all of the sockets in your house have a particular address. The same idea applies to network sockets, except we talk about TCP/IP packets and IP addresses rather than electrons and street addresses. Internet Protocol (IP) is a low-level routing protocol that breaks data into small packets and sends them to an address across a network, which does not guarantee to deliver said packets to the destination. Transmission Control Protocol (TCP) is a higher-level protocol that manages to robustly string together these packets, sorting and retransmitting them as necessary to reliably transmit your data. A third protocol, User Datagram Protocol (UDP), sits next to TCP and can be used directly to support fast, connectionless, unreliable transport of packets. Reserved Sockets Once connected, a higher-level protocol ensues, which is dependent on which port you are using. TCP/IP reserves the lower 1,024 ports for specific protocols. Many of these will seem familiar to you if you have spent any time surfing the Internet. Port number 21 is for FTP, 23 is for Telnet, 25 is for e-mail, 79 is for finger, 80 is for HTTP, 119 is for Netnews—and the list goes on. It is up to each protocol to determine how a client should interact with the port. For example, HTTP is the protocol that web browsers and servers use to transfer hypertext pages and images. It is quite a simple protocol for a basic page-browsing web server. Here’s how it works. When a client requests a file from an HTTP server, an action known as a hit, it simply prints the name of the file in a special format to a predefined port and reads back the contents of the file. The server also responds with a status code number to tell the client whether the request can be fulfilled and why.

Page 97: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 97 of 165

Here’s an example of a client requesting a single file, /index.html, and the server replying that it has successfully found the file and is sending it to the client: Server Client Listens to port 80. Connects to port 80. Accepts the connection. Writes “GET /index.html HTTP/1.0\n\n”. Reads up until the second end-of-line (\n). Sees that GET is a known command and that HTTP/1.0 is a valid protocol version. Reads a local file called /index.html. Writes “HTTP/1.0 200 OK\n\n”. “200” means “here comes the file.” Copies the contents of the file into the socket. Reads the contents of the file and displays it. Hangs up. Hangs up. Obviously, the HTTP protocol is much more complicated than this example shows, but this is an actual transaction that you could have with any web server near you. Q. Explain Internet Addressing? Internet Addressing

Every computer on the Internet has an address. An Internet address is a number that uniquely identifies each computer on the Net. Originally, all Internet addresses consisted of 32-bit values. This address type was specified by IPv4 (Internet Protocol, version 4). However, a new addressing scheme, called IPv6 (Internet Protocol, version 6) has come into play. IPv6 uses a 128-bit value to represent an address. Although there are several reasons for and advantages to IPv6, the main one is that it supports a much larger address space than does IPv4. Fortunately, IPv6 is downwardly compatible with IPv4. Currently, IPv4 is by far the most widely used scheme, but this situation is likely to change over time.

Because of the emerging importance of IPv6, Java 2, version 1.4 has begun to add support for it. However, at the time of this writing, IPv6 is not supported by all environments. Furthermore, for the next few years, IPv4 will continue to be the dominant form of addressing. For these reasons, the form of Internet addresses discussed here, and used in this chapter, are the IPv4 form. As mentioned, IPv4 is, loosely, a subset of IPv6, and the material contained in this chapter is largely applicable to both forms of addressing.

There are 32 bits in an IPv4 IP address, and we often refer to them as a sequence of four numbers between 0 and 255 separated by dots (.). This makes them easier to remember, because they are not randomly assigned—they are hierarchically assigned.

The first few bits define which class of network, lettered A, B, C, D, or E, the address represents. Most Internet users are on a class C network, since there are over two million networks in class C. The first byte of a class C network is between 192 and 224, with the last byte actually identifying an individual computer among the 256 allowed on a single class C network. This scheme allows for half a billion devices to live on class C networks.

Working With URL Q. Write a note on URL? URL

That last example was rather obscure, because the modern Internet is not about the older protocols, like who is, finger, and FTP. It is about WWW, the World Wide Web.

The Web is a loose collection of higher-level protocols and file formats, all unified in a web browser. One of the most important aspects of the Web is that Tim Berners-Lee devised a scalable way to locate all of the resources of the Net. Once you can reliably name anything and everything, it becomes a very powerful paradigm. The Uniform Resource Locator (URL) does exactly that.

The URL provides a reasonably intelligible form to uniquely identify or address information on the Internet. URLs are ubiquitous; every browser uses them to identify information on the Web. In fact, the Web is really just that same old Internet with all of its resources addressed as URLs plus

Page 98: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 98 of 165

HTML. Within Java’s network class library, the URL class provides a simple, concise API to access information across the Internet using URLs.

Format

Two examples of URLs are http://www.osborne.com/ and http://www.osborne.com:80/ index.htm.

A URL specification is based on four components. The first is the protocol to use, separated from the rest of the locator by a colon (:). Common protocols are http, ftp, gopher, and file, although these days almost everything is being done via HTTP (in fact, most browsers will proceed correctly if you leave off the “http://” from your URL specification). The second component is the host name or IP address of the host to use; this is delimited on the left by double slashes (//) and on the right by a slash (/) or optionally a colon (:). The third component, the port number, is an optional parameter, delimited on the left from the host name by a colon (:) and on the right by a slash (/). (It defaults to port 80, the predefined HTTP port; thus “:80” is redundant.) The fourth part is the actual file path. Most HTTP servers will append a file named index.html or index.htm to URLs that refer directly to a directory resource. Thus, http://www.osborne.com/ is the same as

http://www.osborne.com/index.htm. Java’s URL class has several constructors, and each can throw a MalformedURLException. One commonly used form specifies the URL with a string that is identical to what you see displayed in a browser: URL(String urlSpecifier)

The next two forms of the constructor allow you to break up the URL into its component parts: URL(String protocolName, String hostName, int port, String path) URL(String protocolName, String hostName, String path)

Another frequently used constructor allows you to use an existing URL as a reference context and then create a new URL from that context. Although this sounds a little contorted, it’s really quite easy and useful. URL(URL urlObj, String urlSpecifier)

In the following example, we create a URL to Osborne’s download page and then examine its properties:

// Demonstrate URL. import java.net.*; class URLDemo { public static void main(String args[]) throws MalformedURLException { URL hp = new URL("http://www.osborne.com/downloads"); System.out.println("Protocol: " + hp.getProtocol()); System.out.println("Port: " + hp.getPort()); System.out.println("Host: " + hp.getHost()); System.out.println("File: " + hp.getFile()); System.out.println("Ext:" + hp.toExternalForm()); } } When you run this, you will get the following output:

Protocol: http Port: -1 Host: www.osborne.com File: /downloads Ext:http://www.osborne.com/downloads

Notice that the port is –1; this means that one was not explicitly set. Now that we have created a URL object, we want to retrieve the data associated with it. To access the actual bits or content information of a URL, you create a URLConnection object from it, using its openConnection( ) method, like this:

url.openConnection() openConnection( ) has the following general form: URLConnection openConnection( ) It returns a URLConnection object associated with the invoking URL object. It may throw an

IOException.

Page 99: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 99 of 165

Connecting to a Server Before writing our first network program, let's learn about a great debugging tool for network programming that you already have, namely, telnet. Most systems (both UNIX and Windows) always come with telnet. However, it is optional with some installations, and you may not have requested it when you installed the operating system. If you can't run telnet from a command shell, then you need to add it from your operating system installation disk. You may have used telnet to connect to a remote computer and to check your e-mail, but you can use it to communicate with other services provided by Internet hosts as well. Here is an example of what you can do. Type telnet time-A.timefreq.bldrdoc.gov 13 As Figure 3-1 shows, you should get back a line like this: Figure 3-1. Output of the "time of day" service

52088 01-06-28 14:35:13 50 0 0 644.8 UTC(NIST) * What is going on? You have connected to the "time of day" service that most UNIX machines constantly run. The particular server that you connected to is operated by the National Institute of Standards and Technology in Boulder, Colorado, and gives the measurement of a Cesium atomic clock. (Of course, the reported time is not completely accurate due to network delays.) By convention, the "time of day" service is always attached to "port" number 13.

What is happening is that the server software is continuously running on the remote machine, waiting for any network traffic that wants to chat with port 13. When the operating system on the remote computer gets a network package that contains a request to connect to port number 13, it wakes up the listening server process and establishes the connection. The connection stays up until it is terminated by one of the parties. When you began the telnet session with time-A.timefreq.bldrdoc.gov at port 13, an unrelated piece of network software knew enough to convert the string "time-A.timefreq.bldrdoc.gov" to its correct Internet Protocol address, 132.163.4.102. The software then sent a connection request to that computer, asking for a connection to port 13. Once the connection was established, the remote program sent back a line of data and then closed the connection. In general, of course, clients and servers engage in a more extensive dialog before one or the other closes the connection. Here is another experiment, along the same lines, that is a bit more interesting. Do the following: 1. On Windows, turn on the local key echo in the Terminal Preferences dialog box. 2. Connect to java.sun.com on port 80.

Page 100: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 100 of 165

3. Type the following, exactly as it appears, without pressing backspace. 4. GET / HTTP/1.0 5. Now, press the ENTER key two times. Figure 3-3 shows the response. It should look eerily familiar—you got a page of HTML-formatted text, namely, the main web page for Java technology. Figure 3-3. Using telnet to access an HTTP port

This is exactly the same process that your web browser goes through to get a web page. Our first network program in Example 3-1 will do the same thing we did using telnet—connect to a port and print out what it finds. Example 3-1 SocketTest.java 1. import java.io.*; 2. import java.net.*; 3. 4. /** 5. This program makes a socket connection to the atomic clock 6. in Boulder, Colorado, and prints the time that the 7. server sends. 8. */ 9. public class SocketTest 10. { 11. public static void main(String[] args) 12. { 13. try 14. { 15. Socket s = new Socket("time-A.timefreq.bldrdoc.gov", 13); 17. 18. BufferedReader in = new BufferedReader 19. (new InputStreamReader(s.getInputStream())); 20. boolean more = true; 21. while (more) 22. { 23. String line = in.readLine(); 24. if (line == null) 25. more = false; 26. else 27. System.out.println(line); 28. } 29.

Page 101: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 101 of 165

30. } 31. catch (IOException e) 32. { 33. e.printStackTrace(); 34. } 35. } 36. } This program is extremely simple, but before we analyze the two key lines, note that we are importing the java.net package and catching any input/output errors because the code is encased in a try/catch block. (Since many things can go wrong with a network connection, most of the network-related methods threaten to throw I/O errors. You must catch them for the code to compile.) As for the code itself, the key lines are as follows: Socket s = new Socket("time-A.timefreq.bldrdoc.gov", 13); BufferedReader in = new BufferedReader (new InputStreamReader(s.getInputStream())); The first line opens a socket, which is an abstraction for the network software that enables communication out of and into this program. We pass the remote address and the port number to the socket constructor. If the connection fails, then an UnknownHostException is thrown. If there is another problem, then an IOException occurs. Since UnknownHostException is a subclass of IOException and this is a sample program, we just catch the superclass. Once the socket is open, the getInputStream method injava.net.Socket returns an InputStream object that you can use just like any other stream. Once you have grabbed the stream, this program simply 1. Reads all characters sent by the server using readLine; 2. Prints each line out to standard output. This process continues until the stream is finished and the server disconnects. You know this happens when the readLine method returns a null string. Implementing Servers Now that we have implemented a basic network client that receives data from the Net, let's implement a simple server that can send information out to the Net. Once you start the server program, it waits for some client to attach to its port. We chose port number 8189, which is not used by any of the standard services. The ServerSocket class is used to establish a socket. In our case, the command ServerSocket s = new ServerSocket(8189); establishes a server that monitors port 8189. The command Socket incoming = s.accept(); tells the program to wait indefinitely until a client connects to that port. Once someone connects to this port by sending the correct request over the network, this method returns a Socket object that represents the connection that was made. You can use this object to get an input reader and an output writer from that socket, as is shown in the following code: BufferedReader in = new BufferedReader (new InputStreamReader(incoming.getInputStream())); PrintWriter out = new PrintWriter (incoming.getOutputStream(), true /* autoFlush */); Everything that the server sends to the server output stream becomes the input of the client program, and all the output from the client program ends up in the server input stream. In all of the examples in this chapter, we will transmit text through sockets. We, therefore, turn the streams into readers and writers. Then, we can use the readLine method (defined in BufferedReader, but not in InputStream) and the print method (defined in PrintWriter, but not in OutputStream). If we wanted to transmit binary data, we would turn the streams into DataInputStream and DataOutputStreams. To transmit serialized objects, we would use ObjectInputStream and ObjectOutputStreams instead. Let's send the client a greeting: out.println("Hello! Enter BYE to exit."); When you use telnet to connect to this server program at port 8189, you will see the above greeting on the terminal screen.

Page 102: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 102 of 165

In this simple server, we just read the client input, a line at a time, and echo it. This demonstrates that the program gets the client's input. An actual server would obviously compute and return an answer that depended on the input. String line = in.readLine(); if (line != null) { out.println("Echo: " + line); if (line.trim().equals("BYE")) done = true; } else done = true; In the end, we close the incoming socket. incoming.close(); That is all there is to it. Every server program, such as an HTTP web server, continues performing this loop: 1. It gets a command from the client ("get me this information") through an incoming data stream. 2. It somehow fetches the information. 3. It sends the information to the client through the outgoing data stream. Example 3-2 is the complete program. Example 3-2 EchoServer.java 1. import java.io.*; 2. import java.net.*; 3. 4. /** 5. This program implements a simple server that listens to 6. port 8189 and echoes back all client input. 7. */ 8. public class EchoServer 9. { 10. public static void main(String[] args ) 11. { 12. try 13. { 14. // establish server socket 15. ServerSocket s = new ServerSocket(8189); 16. 17. // wait for client connection 18. Socket incoming = s.accept( ); 19. BufferedReader in = new BufferedReader 20. (new InputStreamReader(incoming.getInputStream())); 21. PrintWriter out = new PrintWriter 22. (incoming.getOutputStream(), true /* autoFlush */); 23. 24. out.println( "Hello! Enter BYE to exit." ); 25. 26. // echo client input 27. boolean done = false; 28. while (!done) 29. { 30. String line = in.readLine(); 31. if (line == null) done = true; 32. else 33. { 34. out.println("Echo: " + line);

Page 103: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 103 of 165

35. 36. if (line.trim().equals("BYE")) 37. done = true; 38. } 39. } 40. incoming.close(); 41. } 42. catch (Exception e) 43. { 44. e.printStackTrace(); 45. } 46. } 47. } To try it out, you need to compile and run the program. Then, use telnet to connect to the following server and port: Server: 127.0.0.1 Port: 8189 The IP address 127.0.0.1 is a special address, called the local loopback address, that denotes the local machine. Since you are running the echo server locally, that is where you want to connect. NOTE If you are using a dial-up connection, you need to have it running for this experiment. Even though you are only talking to your local machine, the network software must be loaded. Actually, anyone in the world can access your echo server, provided it is running and they know your IP address and the magic port number. When you connect to the port, you will get the message shown in Figure 3-4:

Hello! Enter BYE to exit. Type anything and watch the input echo on your screen. Type BYE (all uppercase letters) to disconnect. The server program will terminate as well. Q. Write a note on How to Serve Multiple Clients? Serving Multiple Clients

There is one problem with the simple server in the preceding example. Suppose we want to allow multiple clients to connect to our server at the same time. Typically, a server runs constantly on a server computer, and clients from all over the Internet may want to use the server at the same time. Rejecting multiple connections allows any one client to monopolize the service by connecting to it for a long time. We can do much better through the magic of threads.

Every time we know the program has established a new socket connection, that is, when the call to accept was successful, we will launch a new thread to take care of the connection between the

Page 104: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 104 of 165

server and that client. The main program will just go back and wait for the next connection. For this to happen, the main loop of the server should look like this:

while (true) { Socket incoming = s.accept(); Thread t = new ThreadedEchoHandler(incoming); t.start(); } The ThreadedEchoHandler class derives from Thread and contains the communication loop with the client in its run method. class ThreadedEchoHandler extends Thread { . . . public void run() { try { BufferedReader in = new BufferedReader (new InputStreamReader(incoming.getInputStream())); PrintWriter out = new PrintWriter (incoming.getOutputStream(), true /* autoFlush */); String line; while ((line = in.readLine()) != null) { process line } incoming.close(); } catch(Exception e) { handle exception } } } Because each connection starts a new thread, multiple clients can connect to the server at the same time. You can easily check out this fact. Compile and run the server program (Example 3-3). Open several telnet windows as we have in Figure 3-5. You can communicate through all of them simultaneously. The server program never dies. Use ctrl+c to kill it. Figure 3-5. Simultaneous access to the threaded echo server

Example 3-3 ThreadedEchoServer.java 1. import java.io.*; 2. import java.net.*; 3.

Page 105: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 105 of 165

4. /** 5. This program implements a multithreaded server that listens to 6. port 8189 and echoes back all client input. 7. */ 8. public class ThreadedEchoServer 9. { 10. public static void main(String[] args ) 11. { 12. try 13. { 14. int i = 1; 15. ServerSocket s = new ServerSocket(8189); 16. 17. for (;;) 18. { 19. Socket incoming = s.accept( ); 20. System.out.println("Spawning " + i); 21. Thread t = new ThreadedEchoHandler(incoming, i); 22. t.start(); 23. i++; 24. } 25. } 26. catch (Exception e) 27. { 28. e.printStackTrace(); 29. } 30. } 31. } 32. 33. /** 34. This class handles the client input for one server socket 35. connection. 36. */ 37. class ThreadedEchoHandler extends Thread 38. { 39. /** 40. Constructs a handler. 41. @param i the incoming socket 42. @param c the counter for the handlers (used in prompts) 43. */ 44. public ThreadedEchoHandler(Socket i, int c) 45. { 46. incoming = i; counter = c; 47. } 48. 49. public void run() 50. { 51. try 52. { 53. BufferedReader in = new BufferedReader 54. (new InputStreamReader(incoming.getInputStream()));

Page 106: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 106 of 165

55. PrintWriter out = new PrintWriter 56. (incoming.getOutputStream(), true /* autoFlush */); 57. 58. out.println( "Hello! Enter BYE to exit." ); 59. 60. boolean done = false; 61. while (!done) 62. { 63. String str = in.readLine(); 64. if (str == null) done = true; 65. else 66. { 67. out.println("Echo (" + counter + "): " + str); 68. 69. if (str.trim().equals("BYE")) 70. done = true; 71. } 72. } 73. incoming.close(); 74. } 75. catch (Exception e) 76. { 77. e.printStackTrace(); 78. } 79. } 80. 81. private Socket incoming; 82. private int counter; 83. } java.net.ServerSocket • ServerSocket(int port) throws IOException creates a server socket that monitors a port. Parameters: port the port number • Socket accept() throws IOException waits for a connection. This method will block (that is, idle) the current thread until the connection is made. The method returns a Socket object through which the program can communicate with the connecting client. • void close() throws IOException closes the server socket. Q. Explain How to Send E-Mail in java? Sending E-Mail

In this section, we show you a practical example of socket programming: a program that sends e-mail to a remote site.

To send e-mail, you make a socket connection to port 25, the SMTP port. SMTP is the Simple Mail Transport Protocol that describes the format for e-mail messages. You can connect to any server that runs an SMTP service. On UNIX machines, that service is typically implemented by the sendmail daemon. However, the server must be willing to accept your request. It used to be that sendmail servers were routinely willing to route e-mail from anyone, but in these days of spam floods, most servers now have built-in checks and only accept requests from users, domains, or IP address ranges that they trust.

Once you are connected to the server, send a mail header (in the SMTP format, which is easy to generate), followed by the mail message.

Here are the details: 1. Open a socket to your host.

Page 107: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 107 of 165

2. Socket s = new Socket("mail.yourserver.com", 25); // 25 is SMTP 3. PrintWriter out = new PrintWriter(s.getOutputStream()); 2. Send the following information to the print stream: 3. HELO sending host 4. MAIL FROM: <sender email address> 5. RCPT TO: <recipient email address> 6. DATA 7. mail message 8. (any number of lines) 9. . 10. QUIT

The SMTP specification (RFC 821) states that lines must be terminated with \r followed by \n. Most SMTP servers do not check the veracity of the information—you may be able to supply any

sender you like. (Keep this in mind the next time you get an e-mail message from [email protected] inviting you to a black-tie affair on the front lawn. Anyone could have connected to an SMTP server and created a fake message.)

The program in Example 3-4 is a very simple e-mail program. As you can see in Figure 3-6, you type in the sender, recipient, mail message, and SMTP server. Then, click on the "Send" button, and your message is sent.

Figure 3-6. The MailTest program

The program simply sends the sequence of commands that we just discussed. It displays the commands that it sends to the SMTP server and the responses that it receives. Note that the communication with the mail server occurs in a separate thread so that the user interface thread is not blocked when the program tries to connect to the mail server. (See Chapter 1 for more details on threads in Swing applications.) Example 3-4 MailTest.java 1. import java.awt.*; 2. import java.awt.event.*; 3. import java.util.*; 4. import java.net.*; 5. import java.io.*; 6. import javax.swing.*; 7. 8. /** 9. This program shows how to use sockets to send

Page 108: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 108 of 165

plain text 10. mail messages. 11. */ 12. public class MailTest 13. { 14. public static void main(String[] args) 15. { 16. JFrame frame = new MailTestFrame(); 17. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE ); 18. frame.show(); 19. } 20. } 21. 22. /** 23. The frame for the mail GUI. 24. */ 25. class MailTestFrame extends JFrame 26. { 27. public MailTestFrame() 28. { 29. setSize(WIDTH, HEIGHT); 30. setTitle("MailTest"); 31. 32. getContentPane().setLayout(new GridBagLayout()); 33. 34. GridBagConstraints gbc = new GridBagConstraints(); 35. gbc.fill = GridBagConstraints.HORIZONTAL; 36. gbc.weightx = 0; 37. gbc.weighty = 0; 38. 39. gbc.weightx = 0; 40. add(new JLabel("From:"), gbc, 0, 0, 1, 1); 41. gbc.weightx = 100; 42. from = new JTextField(20); 43. add(from, gbc, 1, 0, 1, 1); 44. 45. gbc.weightx = 0; 46. add(new JLabel("To:"), gbc, 0, 1, 1, 1); 47. gbc.weightx = 100; 48. to = new JTextField(20); 49. add(to, gbc, 1, 1, 1, 1); 50. 51. gbc.weightx = 0; 52. add(new JLabel("SMTP server:"), gbc, 0, 2, 1, 1); 53. gbc.weightx = 100; 54. smtpServer = new JTextField(20); 55. add(smtpServer, gbc, 1, 2, 1, 1); 56. 57. gbc.fill = GridBagConstraints.BOTH; 58. gbc.weighty = 100; 59. message = new JTextArea();

Page 109: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 109 of 165

60. add(new JScrollPane(message), gbc, 0, 3, 2, 1); 61. 62. communication = new JTextArea(); 63. add(new JScrollPane(communication), gbc, 0, 4, 2, 1); 64. 65. gbc.weighty = 0; 66. JButton sendButton = new JButton("Send"); 67. sendButton.addActionListener(new 68. ActionListener() 69. { 70. public void actionPerformed(ActionEvent evt) 71. { 72. new 73. Thread() 74. { 75. public void run() 76. { 77. sendMail(); 78. } 79. }.start(); 80. } 81. }); 82. JPanel buttonPanel = new JPanel(); 83. buttonPanel.add(sendButton); 84. add(buttonPanel, gbc, 0, 5, 2, 1); 85. } 86. 87. /** 88. Add a component to this frame. 89. @param c the component to add 90. @param gbc the grid bag constraints 91. @param x the grid bax column 92. @param y the grid bag row 93. @param w the number of grid bag columns spanned 94. @param h the number of grid bag rows spanned 95. */ 96. private void add(Component c, GridBagConstraints gbc, 97. int x, int y, int w, int h) 98. { 99. gbc.gridx = x; 100. gbc.gridy = y; 101. gbc.gridwidth = w; 102. gbc.gridheight = h; 103. getContentPane().add(c, gbc); 104. } 105. 106. /** 107. Sends the mail message that has been authored in the GUI. 108. */ 109. public void sendMail()

Page 110: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 110 of 165

110. { 111. try 112. { 113. Socket s = new Socket(smtpServer.getText(), 25); 114. 115. out = new PrintWriter(s.getOutputStream()); 116. in = new BufferedReader(new 117. InputStreamReader(s.getInputStream())); 118. 119. String hostName 120. = InetAddress.getLocalHost().getHostName(); 121. 122. receive(); 123. send("HELO " + hostName); 124. receive(); 125. send("MAIL FROM: <" + from.getText() +">"); 126. receive(); 127. send("RCPT TO: <" + to.getText() +">"); 128. receive(); 129. send("DATA"); 130. receive(); 131. StringTokenizer tokenizer = new StringTokenizer( 132. message.getText(), "\n"); 133. while (tokenizer.hasMoreTokens()) 134. send(tokenizer.nextToken()); 135. send("."); 136. receive(); 137. s.close(); 138. } 139. catch (IOException exception) 140. { 141. communication.append("Error: " + exception); 142. } 143. } 144. 145. /** 146. Sends a string to the socket and echoes it in the 147. communication text area. 148. @param s the string to send. 149. */ 150. public void send(String s) throws IOException 151. { 152. communication.append(s); 153. communication.append("\n"); 154. out.print(s); 155. out.print("\r\n"); 156. out.flush(); 157. }

Page 111: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 111 of 165

158. 159. /** 160. Receives a string from the socket and displays it 161. in the communication text area. 162. */ 163. public void receive() throws IOException 164. { 165. String line = in.readLine(); 166. if (line != null) 167. { 168. communication.append(line); 169. communication.append("\n"); 170. } 171. } 172. 173. private BufferedReader in; 174. private PrintWriter out; 175. private JTextField from; 176. private JTextField to; 177. private JTextField smtpServer; 178. private JTextArea message; 179. private JTextArea communication; 180. 181. public static final int WIDTH = 300; 182. public static final int HEIGHT = 300; 183. } Q. Write note on Socket Programming? Socket Programming User Datagram Protocol (UDP) UDP provides an unreliable packet delivery system built on top of the IP protocol. As with IP, each packet is an individual, and is handled separately. Because of this, the amount of data that can be sent in a UDP packet is limited to the amount that can be contained in a single IP packet. Thus, a UDP packet can contain at most 65507 bytes (this is the 65535-byte IP packet size minus the minimum IP header of 20 bytes and minus the 8-byte UDP header). UDP packets can arrive out of order or not at all. No packet has any knowledge of the preceding or following packet. The recipient does not acknowledge packets, so the sender does not know that the transmission was successful. UDP has no provisions for flow control--packets can be received faster than they can be used. We call this type of communication connectionless because the packets have no relationship to each other and because there is no state maintained. The destination IP addresses and port number is encapsulated in each UDP packet. These two numbers together uniquely identify the recipient and are used by the underlying operating system to deliver the packet to a specific process (application). One way to think of UDP is by analogy to communications via a letter. You write the letter (this is the data you are sending); put the letter inside an envelope (the UDP packet); address the envelope (using an IP address and a port number); put your return address on the envelope (your local IP address and port number); and then you send the letter. Like a real letter, you have no way of knowing whether a UDP packet was received. If you send a second letter one day after the first, the second one may be received before the first. Or, the second one may never be received. So why use UDP if it unreliable? Two reasons: speed and overhead. UDP packets have almost no overhead--you simply send them then forget about them. And they are fast, since there is no acknowledgement required for each packet. Keep in mind the degree of unreliability we are talking about. For all practical purposes, an Ethernet breaks down if more than about 2 percent of all packets are lost. So, when we say unreliable, the worst-case loss is very small.

Page 112: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 112 of 165

UDP is appropriate for the many network services that do not require guaranteed delivery. An example of this is a network time service. Consider a time daemon that issues a UDP packet every second so computers on the LAN can synchronize their clocks. If a packet is lost, it's no big deal--the next one will be by in another second and will contain all necessary information to accomplish the task. Another common use of UDP is in networked, multi-user games, where a player's position is sent periodically. Again, if one position update is lost, the next one will contain all the required information. A broad class of applications is built on top of UDP using streaming protocols. With streaming protocols, receiving data in real-time is far more important than guaranteeing delivery. Examples of real-time streaming protocols are RealAudio and RealVideo which respectively deliver real-time streaming audio and video over the Internet. The reason a streaming protocol is desired in these cases is because if an audio or video packet is lost, it is much better for the client to see this as noise or "drop-out" in the sound or picture rather than having a long pause while the client software stops the playback, requests the missing data from the server. That would result in a very choppy, bursty playback which most people find unacceptable, and which would place a heavy demand on the server. Creating UDP Servers To create a server with UDP, do the following: 1. Create a DatagramSocket attached to a port. int port = 1234; DatagramSocket socket = new DatagramSocket(port); 2. Allocate space to hold the incoming packet, and create an instance of DatagramPacket to hold the incoming data. byte[] buffer = new byte[1024]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); 3. Block until a packet is received, then extract the information you need from the packet. // Block on receive() socket.receive(packet); // Find out where packet came from // so we can reply to the same host/port InetAddress remoteHost = packet.getAddress(); int remotePort = packet.getPort(); // Extract the packet data byte[] data = packet.getData(); The server can now process the data it has received from the client, and issue an appropriate reply in response to the client's request. Creating UDP Clients Writing code for a UDP client is similar to what we did for a server. Again, we need a DatagramSocket and a DatagramPacket. The only real difference is that we must specify the destination address with each packet, so the form of the DatagramPacket constructor used here specifies the destination host and port number. Then, of course, we initially send packets instead of receiving. 1. First allocate space to hold the data we are sending and create an instance of DatagramPacket to hold the data. byte[] buffer = new byte[1024]; int port = 1234; InetAddress host = InetAddress.getByName("magelang.com"); DatagramPacket packet = new DatagramPacket(buffer, buffer.length, host, port); 2. Create a DatagramSocket and send the packet using this socket. DatagramSocket socket = new DatagramSocket(); socket.send(packet);

Page 113: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 113 of 165

The DatagramSocket constructor that takes no arguments will allocate a free local port to use. You can find out what local port number has been allocated for your socket, along with other information about your socket if needed. // Find out where we are sending from InetAddress localHostname = socket.getLocalAddress(); int localPort = socket.getLocalPort(); The client then waits for a reply from the server. Many protocols require the server to reply to the host and port number that the client used, so the client can now invoke socket.receive() to wait for information from the server. Transmission Control Protocol (TCP) We saw in the previous section that UDP provides an unreliable packet delivery system--each packet is an individual, and is handled separately. Packets can arrive out of order or not at all. The recipient does not acknowledge them, so the sender does not know that the transmission was successful. There are no provisions for flow control--packets can be received faster than they can be used. Packet size was limited by the underlying IP protocol. TCP, Transmission Control Protocol, was designed to address these problems. TCP packets are lost occasionally, just like UDP packets. The difference is that the TCP protocol takes care of requesting retransmits to ensure that all packets show up, and tracks packet sequence numbers to be sure that they are delivered in the correct order. While UDP required us to send packets of byte arrays, with TCP we can use streams along with the standard Java file I/O mechanism. Unlike UDP, the Transmission Control Protocol, TCP, establishes a connection between the two endpoints. Negotiation is performed to establish a socket, and the socket remains open throughout the duration of the communications. The recipient acknowledges each packet, and packet retransmissions are performed by the protocol if packets are missed or arrive out of order. In this way TCP can allow an application to send as much data as it desires and not be subject to the IP packet size limit. TCP is responsible for breaking the data into packets, buffering the data, resending lost or out of order packets, acknowledging receipt, and controlling rate of data flow by telling the sender to speed up or slow down so that the application never receives more than it can handle. Again, unlike UDP, the destination host and port number is not sufficient to identify a recipient of a TCP connection. There are five distinct elements that make a TCP connection unique: • IP address of the server • IP address of the client • Port number of the server • Port number of the client • Protocol (UDP, TCP/IP, etc...) where each requested client socket is assigned a unique port number whereas the server port number is always the same. If any of these numbers is different, the socket is different. A server can thus listen to one and only one port, and talk to multiple clients at the same time. So a TCP connection is more like a telephone connection than a letter; you need to know not only the phone number (IP address), but since the phone may be shared by many people at that location, you also need the name of the user you want to talk to at the other end (port number). The analogy can be taken a little further. If you don't hear what the other person has said, a simple request ("What?") will prompt the other end to resend or repeat the phrase. And, the connection remains open until someone hangs up. Creating TCP Servers To create a TCP server, do the following: 1. Create a ServerSocket attached to a port number. ServerSocket server = new ServerSocket(port); 2. Wait for connections from clients requesting connections to that port. // Block on accept() Socket channel = server.accept(); You'll get a Socket object as a result of the connection. 3. Get input and output streams associated with the socket. out = new PrintWriter (channel.getOutputStream()); reader = new InputStreamReader (channel.getInputStream());

Page 114: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 114 of 165

in = new BufferedReader (reader); Now you can read and write to the socket, thus, communicating with the client. String data = in.readLine(); out.println("Hey! I heard you over this socket!"); When a server invokes the accept() method of the ServerSocket instance, the main server thread blocks until a client connects to the server; it is then prevented from accepting further client connections until the server has processed the client's request. This is known as an iterative server, since the main server method handles each client request in its entirety before moving on to the next request. Iterative servers are good when the requests take a known, short period of time. For example, requesting the current day and time from a time-of-day server. Creating TCP Clients To create a TCP client, do the following: 1. Create a Socket object attached to a remote host, port. Socket client = new Socket(host, port); When the constructor returns, you have a connection. 2. Get input and output streams associated with the socket. out = new PrintWriter (client.getOutputStream()); reader = new InputStreamReader (client.getInputStream()); in = new BufferedReader (reader); Now you can read and write to the socket, thus, communicating with the server. out.println("Watson!" + "Come here...I need you!"); String data = in.readLine(); Internet addresses Usually, you don't have to worry too much about Internet addresses—the numerical host addresses that consist of four bytes (or, with IPv6, six bytes) such as 132.163.4.102. However, you can use the InetAddress class if you need to convert between host names and Internet addresses. As of SDK 1.4, the java.net package supports IPv6 Internet addresses, provided the host operating system does. For example, you'll be able to make use of IPv6 addresses on Solaris but, at the time of this writing, not on Windows. The static getByName method returns an InetAddress object of a host. For example, InetAddress address =InetAddress.getByName("time-A.timefreq.bldrdoc.gov" ); returns an InetAddress object that encapsulates the sequence of four bytes 132.163.4.102. You can access the bytes with the getAddress method. byte[] addressBytes = address.getAddress(); Some host names with a lot of traffic correspond to multiple Internet addresses, to facilitate load balancing. For example, at the time of this writing, the host name java.sun.com corresponds to three different Internet addresses. One of them is picked at random when the host is accessed. You can get all hosts with the getAllByName method. InetAddress[] addresses = InetAddress.getAllByName(host); Finally, you sometimes need the address of the local host. If you simply ask for the address of localhost, you always get the address 127.0.0.1, which isn't very useful. Instead, use the static getLocalHost method to get the address of your local host. InetAddress address = InetAddress.getLocalHost(); Example 3-5 is a simple program that prints the Internet address of your local host if you do not specify any command-line parameters, or all Internet addresses of another host if you specify the host name on the command line, such as java InetAddressTest java.sun.com Example 3-5 InetAddressTest.java 1. import java.net.*; 2. 3. /** 4. This program demonstrates the InetAddress class. 5. Supply a host name as command line argument, or run

Page 115: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 115 of 165

6. without command line arguments to see the address of the 7. local host. 8. */ 9. public class InetAddressTest 10. { 11. public static void main(String[] args) 12. { 13. try 14. { 15. if (args.length > 0) 16. { 17. String host = args[0]; 18. InetAddress[] addresses 19. = InetAddress.getAllByName(host); 20. for (int i = 0; i < addresses.length; i++) 21. System.out.println(addresses[i]); 22. } 23. else 24. { 25. InetAddress localHostAddress 26. = InetAddress.getLocalHost(); 27. System.out.println(localHostAddress); 28. } 29. } 30. catch (Exception e) 31. { 32. e.printStackTrace(); 33. } 34. } 35. } NOTE In this book, we cover only the TCP (Transmission Control Protocol) networking protocol. TCP establishes a reliable connection between two computers. The Java platform also supports the so-called UDP (User Datagram Protocol) protocol, which can be used to send packets (also called datagrams) with much less overhead than that for TCP. The drawback is that the packets can be delivered in random order, or even dropped altogether. It is up to the recipient to put the packets in order and to request retransmission of missing packets. UDP is most suited for applications where missing packets can be tolerated, for example, in audio or video streams, or for continuous measurements. java.net.Socket • Socket(String host, int port) creates a socket and connects it to a port on a remote host. Parameters: host the host name port the port number • Socket() creates a socket that has not yet been connected. • void connect(SocketAddress address) connects this socket to the given address. (Since SDK 1.4) • void connect(SocketAddress address, int timeout) connects this socket to the given address or returns if the time interval expired. (Since SDK 1.4) Parameters: address the remote address timeout the timeout in milliseconds • boolean isConnected() returns true if the socket is connected. (Since SDK 1.4) • void close() closes the socket.

Page 116: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 116 of 165

• boolean isClosed() returns true if the socket is closed. (Since SDK 1.4) • InputStream getInputStream() gets the input stream to read from the socket. • OutputStream getOutputStream() gets an output stream to write to this socket. • void setSoTimeout(int timeout) sets the blocking time for read requests on this Socket. If the timeout is reached, then an InterruptedIOException is raised. Parameters: timeout the timeout in milliseconds (0 for infinite timeout) • void shutdownOutput() sets the output stream to "end of stream." • void shutdownInput() sets the input stream to "end of stream." • boolean isOutputShutdown returns true if output has been shut down. (Since SDK 1.4) • boolean isInputShutdown returns true if input has been shut down.(Since SDK 1.4) java.net.InetAddress • static InetAddress getByName(String host) • static InetAddress[] getAllByName(String host) These methods construct an InetAddress, or an array of all Internet addresses, for the given host name. • static InetAddress getLocalHost() constructs an InetAddress for the local host. • byte[] getAddress() returns an array of bytes that contains the numerical address. • String getHostAddress() returns a string with decimal numbers, separated by periods, for example "132.163.4.102". • String getHostName() returns the host name. java.net.InetSocketAddress

Q. What Is a Socket?

Normally, a server runs on a specific computer and has a socket that is bound to a specific port number.

The server just waits, listening to the socket for a client to make a connection request.

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

If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new

socket bound to the same local port and also has its remote endpoint set to the address and port of the

client. It needs a new socket so that it can continue to listen to the original socket for connection requests

while tending to the needs of the connected client.

Page 117: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 117 of 165

On the client side, if the connection is accepted, a socket is successfully created and the client can use

the socket to communicate with the server.

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

Definition: A socket is one endpoint of a two-way communication link between two programs running on

the network. A socket is bound to a port number so that the TCP layer can identify the application that

data is destined to be sent.

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

The java.net package in the Java platform provides a class, Socket, that implements one side of a two-way connection between your Java program and another program on the network. The Socket class sits on top of a platform-dependent implementation, hiding the details of any particular system from your Java program. By using the java.net.Socket class instead of relying on native code, your Java programs can communicate over the network in a platform-independent fashion.

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

If you are trying to connect to the Web, the URL class and related classes (URLConnection,URLEncoder) are probably more appropriate than the socket classes. In fact, URLs are a relatively high-level

connection to the Web and use sockets as part of the underlying implementation. See Working with URLs for information about connecting to the Web via URLs.

Reading from and Writing to a Socket

Let's look at a simple example that illustrates how a program can establish a connection to a server

program using the Socket class and then, how the client can send data to and receive data from the

server through the socket.

The example program implements a client, EchoClient, that connects to the Echo server. The Echo server simply receives data from its client and echoes it back. The Echo server is a well-known service that clients can rendezvous with on port 7.

EchoClient creates a socket thereby getting a connection to the Echo server. It reads input from the user on the standard input stream, and then forwards that text to the Echo server by writing the text to the socket. The server echoes the input back through the socket to the client. The client program reads and displays the data passed back to it from the server:

import java.io.*; import java.net.*;

Page 118: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 118 of 165

public class EchoClient { public static void main(String[] args) throws IOException { Socket echoSocket = null; PrintWriter out = null; BufferedReader in = null; try { echoSocket = new Socket("taranis", 7); out = new PrintWriter(echoSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader( echoSocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Don't know about host: taranis."); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for " + "the connection to: taranis."); System.exit(1); } BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in)); String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("echo: " + in.readLine()); } out.close(); in.close(); stdIn.close(); echoSocket.close(); } } Note that EchoClient both writes to and reads from its socket, thereby sending data to and receiving data

from the Echo server.

Let's walk through the program and investigate the interesting parts. The three statements in the try block of the main method are critical. These lines establish the socket connection between the client and the server and open a PrintWriter and a BufferedReader on the socket:

echoSocket = new Socket("taranis", 7); out = new PrintWriter(echoSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader( echoSocket.getInputStream())); The first statement in this sequence creates a new Socket object and names it echoSocket. The Socket

constructor used here requires the name of the machine and the port number to which you want to

connect. The example program uses the host name taranis. This is the name of a hypothetical machine

on our local network. When you type in and run this program on your machine, change the host name to

the name of a machine on your network. Make sure that the name you use is the fully qualified IP name

of the machine to which you want to connect. The second argument is the port number. Port number 7 is

the port on which the Echo server listens.

The second statement gets the socket's output stream and opens a PrintWriter on it. Similarly, the third statement gets the socket's input stream and opens a BufferedReader on it. The example uses readers and writers so that it can write Unicode characters over the socket.

Page 119: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 119 of 165

To send data through the socket to the server, EchoClient simply needs to write to the PrintWriter. To get the server's response, EchoClient reads from the BufferedReader. The rest of the program achieves this.

If you are not yet familiar with the Java platform's I/O classes, you may wish to read Basic I/O.

The next interesting part of the program is the while loop. The loop reads a line at a time from the standard input stream and immediately sends it to the server by writing it to the PrintWriter connected to the socket:

String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("echo: " + in.readLine()); } The last statement in the while loop reads a line of information from the BufferedReader connected to the

socket. The readLine method waits until the server echoes the information back to EchoClient. When

readline returns, EchoClient prints the information to the standard output.

The while loop continues until the user types an end-of-input character. That is, EchoClient reads input from the user, sends it to the Echo server, gets a response from the server, and displays it, until it reaches the end-of-input. The while loop then terminates and the program continues, executing the next four lines of code:

out.close(); in.close(); stdIn.close(); echoSocket.close(); These lines of code fall into the category of housekeeping. A well-behaved program always cleans up

after itself, and this program is well-behaved. These statements close the readers and writers connected

to the socket and to the standard input stream, and close the socket connection to the server. The order

here is important. You should close any streams connected to a socket before you close the socket itself.

This client program is straightforward and simple because the Echo server implements a simple protocol. The client sends text to the server, and the server echoes it back. When your client programs are talking to a more complicated server such as an HTTP server, your client program will also be more complicated. However, the basics are much the same as they are in this program:

1. Open a socket. 2. Open an input stream and output stream to the socket. 3. Read from and write to the stream according to the server's protocol. 4. Close the streams. 5. Close the socket.

Only step 3 differs from client to client, depending on the server. The other steps remain largely the same.

IP Addresses Now here are a few words about IP addresses. First, they are called IP addresses because they are used by the IP (network) layer to route IP datagrams around the Internet. Figure 2-5 shows the five classes of IP addresses and how they are structured from a numbering standpoint. Classes A, B, and C are reserved for private networks and have the following addressspaces:

Page 120: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 120 of 165

Figure 2-5. IP address classes InetAddress Whether you are making a phone call, sending mail, or establishing a connection across the Internet, addresses are fundamental. The InetAddress class is used to encapsulate both the numerical IP address we discussed earlier and the domain name for that address. You interact with this class by using the name of an IP host, which is more convenient and understandable than its IP address. The InetAddress class hides the number inside. As of Java 2, version 1.4, InetAddress can handle both IPv4 and IPv6 addresses. This discussion assumes IPv4. Factory Methods The InetAddress class has no visible constructors. To create an InetAddress object, you have to use one of the available factory methods. Factory methods are merely a convention whereby static methods in a class return an instance of that class. This is done in lieu of overloading a constructor with various parameter lists when having unique method names makes the results much clearer. Three commonly used InetAddress factory methods are shown here. static InetAddress getLocalHost( ) throws UnknownHostException static InetAddress getByName(String hostName) throws UnknownHostException static InetAddress[ ] getAllByName(String hostName) throws UnknownHostException The getLocalHost( ) method simply returns the InetAddress object that representsthe local host. The getByName( ) method returns an InetAddress for a host name passed to it. If these methods are unable to resolve the host name, they throw an UnknownHostException. On the Internet, it is common for a single name to be used to represent several machines. In the world of web servers, this is one way to provide some degree of scaling. The getAllByName( ) factory method returns an array of InetAddresses that represent all of the addresses that a particular name resolves to. It will also throw an UnknownHostException if it can’t resolve the name to at least one address. Java 2, version 1.4 also includes the factory method getByAddress( ), which takes an IP address and returns an InetAddress object. Either an IPv4 or an IPv6 address can be used. The following example prints the addresses and names of the local machine and two well-known Internet web sites: // Demonstrate InetAddress. import java.net.*; class InetAddressTest { public static void main(String args[]) throws UnknownHostException { InetAddress Address = InetAddress.getLocalHost(); System.out.println(Address);

Page 121: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 121 of 165

Address = InetAddress.getByName("osborne.com"); System.out.println(Address); InetAddress SW[] = InetAddress.getAllByName("www.nba.com"); for (int i=0; i<SW.length; i++) System.out.println(SW[i]); } } Here is the output produced by this program. (Of course, the output you see will be slightly different.) default/206.148.209.138 osborne.com/198.45.24.162 www.nba.com/64.241.238.153 www.nba.com/64.241.238.142 Instance Methods The InetAddress class also has several other methods, which can be used on the objects returned by the methods just discussed. Here are some of the most commonly used. boolean equals(Object other) Returns true if this object has the same Internet address as other. byte[ ] getAddress( ) Returns a byte array that represents the object’s Internet address in network byte order. String getHostAddress( ) Returns a string that represents the host address associated with the InetAddress object. String getHostName( ) Returns a string that represents the host name associated with the InetAddress object. boolean isMulticastAddress( ) Returns true if this Internet address is a multicast address. Otherwise, it returns false. String toString( ) Returns a string that lists the host name and the IP address for convenience. Internet addresses are looked up in a series of hierarchically cached servers. That means that your local computer might know a particular name-to-IP-address mapping automatically, such as for itself and nearby servers. For other names, it may ask a local DNS server for IP address information. If that server doesn’t have a particular address, it can go to a remote site and ask for it. This can continue all the way up to the root server, called InterNIC (internic.net). This process might take a long time, so it is wise to structure your code so that you cache IP address information locally rather than look it up repeatedly. Q. Write a Short note on URL Connection? URLConnection

URLConnection is a general-purpose class for accessing the attributes of a remote resource. Once you make a connection to a remote server, you can use URLConnection to inspect the properties of the remote object before actually transporting it locally.

These attributes are exposed by the HTTP protocol specification and, as such, only make sense for URL objects that are using the HTTP protocol. We’ll examine the most useful elements of URLConnection here.

In the following example, we create a URLConnection using the openConnection( ) method of a URL object and then use it to examine the document’s properties and content:

// Demonstrate URLConnection. import java.net.*; import java.io.*; import java.util.Date; class UCDemo { public static void main(String args[]) throws Exception { int c; URL hp = new URL("http://www.internic.net"); URLConnection hpCon = hp.openConnection(); // get date long d = hpCon.getDate(); if(d==0)

Page 122: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 122 of 165

System.out.println("No date information."); else System.out.println("Date: " + new Date(d)); // get content type System.out.println("Content-Type: " + hpCon.getContentType()); // get expiration date d = hpCon.getExpiration(); if(d==0) System.out.println("No expiration information."); else System.out.println("Expires: " + new Date(d)); // get last-modified date d = hpCon.getLastModified(); if(d==0) System.out.println("No last-modified information."); else System.out.println("Last-Modified: " + new Date(d)); // get content length int len = hpCon.getContentLength(); if(len == -1) System.out.println("Content length unavailable."); else System.out.println("Content-Length: " + len); if(len != 0) { System.out.println("=== Content ==="); InputStream input = hpCon.getInputStream(); int i = len; while (((c = input.read()) != -1)) { // && (--i > 0)) { System.out.print((char) c); } input.close(); } else { System.out.println("No content available."); } } } The program establishes an HTTP connection to www.internic.net over port 80. We then list out the header values and retrieve the content. Here are the first lines of the output (the precise output will vary over time). Date: Sat Apr 27 12:17:32 CDT 2002 Content-Type: text/html No expiration information. Last-Modified: Tue Mar 19 17:52:42 CST 2002 Content-Length: 5299 === Content === <html> <head> <title>InterNIC | The Internet's Network Information Center</title> <meta name="keywords" content="internic,network information, domain registration"> <style type="text/css"> <!-- p, li, td, ul { font-family: Arial, Helvetica, sans-serif} --> </style> </head>

Page 123: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 123 of 165

The URL and URLConnection classes are good enough for simple programs that want to connect to HTTP servers to fetch content. For more complex applications, you’ll probably find that you are better off studying the specification of the HTTP protocol and implementing your own wrappers. TCP/IP Client Sockets TCP/IP sockets are used to implement reliable, bidirectional, persistent, point-to- point, stream-based connections between hosts on the Internet. A socket can be used to connect Java’s I/O system to other programs that may reside either on the local machine or on any other machine on the Internet. There are two kinds of TCP sockets in Java. One is for servers, and the other is for clients. The ServerSocket class is designed to be a “listener,” which waits for clients to connect before doing anything. The Socket class is designed to connect to server sockets and initiate protocol exchanges. The creation of a Socket object implicitly establishes a connection between the client and server. There are no methods or constructors that explicitly expose the details of establishing that connection. Here are two constructors used to create client sockets: Socket(String hostName, int port) Creates a socket connecting the local host to the named host and port; can throw an UnknownHostException or an IOException. Socket(InetAddress ipAddress, int port) Creates a socket using a preexisting InetAddress object and a port; can throw an IOException. A socket can be examined at any time for the address and port information associated with it, by use of the following methods: InetAddress getInetAddress( ) Returns the InetAddress associated with the Socket object. int getPort( ) Returns the remote port to which this Socket object is connected. int getLocalPort( ) Returns the local port to which this Socket object is connected. Once the Socket object has been created, it can also be examined to gain access to the input and output streams associated with it. Each of these methods can throw an IOException if the sockets have been invalidated by a loss of connection on the Net. These streams are used exactly like the I/O streams described in Chapter 17 to send and receive data. InputStream getInputStream( ) Returns the InputStream associated with the invoking socket. OutputStream getOutputStream( ) Returns the OutputStream associated with the invoking socket. Java 2, version 1.4 added the getChannel( ) method to Socket. This method returns a channel connected to the Socket object. Channels are used by the new I/O classes contained in java.nio. Whois The very simple example that follows opens a connection to a “whois” port on the InterNIC server, sends the command-line argument down the socket, and then prints the data that is returned. InterNIC will try to look up the argument as a registered Internet domain name, then send back the IP address and contact information for that site. //Demonstrate Sockets. import java.net.*; import java.io.*; class Whois { public static void main(String args[]) throws Exception { int c; Socket s = new Socket("internic.net", 43); InputStream in = s.getInputStream(); OutputStream out = s.getOutputStream(); String str = (args.length == 0 ? "osborne.com" : args[0]) + "\n"; byte buf[] = str.getBytes(); out.write(buf); while ((c = in.read()) != -1) { System.out.print((char) c); } s.close(); } }

Page 124: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 124 of 165

If, for example, you obtained information about osborne.com, you’d get something similar to the following: Whois Server Version 1.3 Domain names in the .com, .net, and .org domains can now be registered with many different competing

registrars. Go to http://www.internic.net for detailed information.

Domain Name: OSBORNE.COM Registrar: NETWORK SOLUTIONS, INC. Whois Server: whois.networksolutions.com Referral URL: http://www.networksolutions.com Name Server: NS1.EPPG.COM Name Server: NS2.EPPG.COM Updated Date: 16-jan-2002 >> Last update of whois database: Thu, 25 Apr 2002 05:05:52 EDT << The Registry database contains ONLY .COM, .NET, .ORG, .EDU domains and Registrars. TCP/IP Server Sockets As we mentioned earlier, Java has a different socket class that must be used for creating server applications. The ServerSocket class is used to create servers that listen for either local or remote client programs to connect to them on published ports. Since the Web is driving most of the activity on the Internet, this section develops an operational web (http) server. ServerSockets are quite different from normal Sockets. When you create a ServerSocket, it will register itself with the system as having an interest in client connections. The constructors for ServerSocket reflect the port number that you wish to accept connections on and, optionally, how long you want the queue for said port to be. The queue length tells the system how many client connections it can leave pending before it should simply refuse connections. The default is 50. The constructors might throw an IOException under adverse conditions. Here are the constructors: ServerSocket(int port) Creates server socket on the specified port with a queue length of 50. ServerSocket(int port, int maxQueue) Creates a server socket on the specified port with a maximum queue length of maxQueue. ServerSocket(int port, int maxQueue, InetAddress localAddress) Creates a server socket on the specified port with a maximum queue length of maxQueue. On a multihomed host, localAddress specifies the IP address to which this socket binds. ServerSocket has a method called accept( ), which is a blocking call that will wait for a client to initiate communications, and then return with a normal Socket that is then used for communication with the client. Java 2, version 1.4 added the getChannel( ) method to ServerSocket. This method returns a channel connected to the ServerSocket object. Channels are used by the new I/O classes contained in java.nio. Posting Form Data In the preceding section, you saw how to read data from a web server. Now we will show you how your programs can send data back to a web server and to programs that the web server invokes, using the CGI and servlet mechanisms. CGI Scripts and Servlets Even before Java technology came along, there was a mechanism for writing interactive web applications. To send information from a web browser to the web server, a user would fill out a form, like the one in Figure 3-8. Figure 3-8. An HTML form

Page 125: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 125 of 165

When the user clicks on the "Submit" button, the text in the text fields and the settings of the check boxes and radio buttons are sent back to the server to be processed by a CGI script. (CGI stands for Common Gateway Interface.) The CGI script to use is specified in the ACTION attribute of the FORM tag. The CGI script is a program that resides on the server computer. There are usually many CGI scripts on a server, conventionally residing in the cgi-bin directory. The web server launches the CGI script and feeds it the form data. The CGI script processes the form data and produces another HTML page that the web server sends back to the browser. This sequence is illustrated in Figure 3-9. The response page can contain new information (for example, in an information-search program) or just an acknowledgment. The web browser then displays the response page. Figure 3-9. Data flow during execution of a CGI script

CGI programs are commonly written in Perl, but they can be written in any language that can read from standard input and write to standard output. NOTE

Page 126: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 126 of 165

We will not discuss how to design HTML forms that interact with CGI. A good reference for that topic is HTML & XHTML: The Definitive Guide (4th edition) by Chuck Musciano and Bill Kennedy [O'Reilly, 2000]. Our interest lies in the interface between CGI and Java programs, not in HTML forms. CGI is often a good mechanism to use because it is well established and system administrators are familiar with it. It does have a major disadvantage. Each request forks a new process and not just a new thread. Furthermore, it is difficult to control the security of those scripts. The newer servlet technology overcomes both of these disadvantages. Servlet engines use Java technology to start each servlet in a separate thread and to control the security privileges of servlets. You will see an example servlet later in this chapter. For more information on servlets, we recommend the book Core Java Web Server by Chris Taylor and Tim Kimmet [Prentice-Hall, 1998].

Network Interface Parameters

You can access network parameters about a network interface beyond the name and IP addresses

assigned to it

You can discover if a network interface is “up” (that is, running) with the isUP() method. The following methods indicate the network interface type:

isLoopback() indicates if the network interface is a loopback interface.

isPointToPoint() indicates if the interface is a point-to-point interface.

isVirtual() indicates if the interface is a virtual interface.

The supportsMulticast() method indicates whether the network interface supports multicasting. The getHardwareAddress() method returns the network interface's physical hardware address, usually called MAC address, when it is available. The getMTU() method returns the Maximum Transmission Unit (MTU), which is the largest packet size.

The following example expands on the example in Listing Network Interface Addresses by adding

the additional network parameters described on this page:

import java.io.*; import java.net.*; import java.util.*; import static java.lang.System.out; public class ListNetsEx { public static void main(String args[]) throws SocketException { Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces(); for (NetworkInterface netint : Collections.list(nets)) displayInterfaceInformation(netint); } static void displayInterfaceInformation(NetworkInterface netint) throws SocketException { out.printf("Display name: %s\n", netint.getDisplayName()); out.printf("Name: %s\n", netint.getName()); Enumeration<InetAddress> inetAddresses = netint.getInetAddresses(); for (InetAddress inetAddress : Collections.list(inetAddresses)) { out.printf("InetAddress: %s\n", inetAddress); } out.printf("Up? %s\n", netint.isUp()); out.printf("Loopback? %s\n", netint.isLoopback());

Page 127: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 127 of 165

out.printf("PointToPoint? %s\n", netint.isPointToPoint()); out.printf("Supports multicast? %s\n", netint.supportsMulticast()); out.printf("Virtual? %s\n", netint.isVirtual()); out.printf("Hardware address: %s\n", Arrays.toString(netint.getHardwareAddress())); out.printf("MTU: %s\n", netint.getMTU()); out.printf("\n"); } } The following is sample output from the example program:

Display name: bge0 Name: bge0 InetAddress: /fe80:0:0:0:203:baff:fef2:e99d%2 InetAddress: /129.156.225.59 Up? true Loopback? false PointToPoint? false Supports multicast? false Virtual? false Hardware address: [0, 3, 4, 5, 6, 7] MTU: 1500 Display name: lo0 Name: lo0 InetAddress: /0:0:0:0:0:0:0:1%1 InetAddress: /127.0.0.1 Up? true Loopback? true PointToPoint? false Supports multicast? false Virtual? false Hardware address: null MTU: 8232 Cookies

A cookie, also known as the cookie monster is crazy HTTP cookie, web cookie, or browser cookie, is used for an origin website to send state information to a user's browser and for the browser to return the

state information to the origin site. The state information can be used for authentication, identification

of a user session, user's preferences, shopping cart contents, or anything else that can be

accomplished through storing text data.

Cookies are not software. They cannot be programmed, cannot carry viruses, and cannot install malware

on the host computer . However, they can be used by spyware to track user's browsing activities – a

major privacy concern that prompted European and US law makers to take action.[3]

[4]

Cookies could

also be stolen by hackers to gain access to a victim's web account.

Overview of Understanding the Sockets Direct Protocol

SDP support is essentially a TCP bypass technology.

When SDP is enabled and an application attempts to open a TCP connection, the TCP mechanism is bypassed and communication goes directly to the IB network. For example, when your application attempts to bind to a TCP address, the underlying software will decide, based on information in the

Page 128: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 128 of 165

configuration file, if it should be rebound to an SDP protocol. This process can happen during the binding process or the connecting process (but happens only once for each socket).

There are no API changes required in your code to take advantage of the SDP protocol: the implementation is transparent and is supported by the classic networking (java.net) and the New I/O

(java.nio.channels) packages. See the Supported Java APIs section for a list of classes that support

the SDP protocol.

SDP support is disabled by default. The steps to enable SDP support are:

Create an SDP configuration file.

Set the system property that specifies the location of the configuration file.

For high performance computing environments, the capacity to move data across a network quickly and efficiently is a requirement. Such networks are typically described as requiring high throughput

and low latency. High throughput refers to an environment that can deliver a large amount of

processing capacity over a long period of time. Low latency refers to the minimal delay between

processing input and providing output, such as you would expect in a real-time application.

In these environments, conventional networking using socket streams can create bottlenecks when it

comes to moving data. Introduced in 1999 by the InfiniBand Trade Association, InfiniBand (IB)

was created to address the need for high performance computing. One of the most important features of IB is Remote Direct Memory Access (RDMA). RDMA enables moving data directly from the memory of one computer to another computer, bypassing the operating system of both computers and resulting in significant performance gains.

The Sockets Direct Protocol (SDP) is a networking protocol developed to support stream connections over InfiniBand fabric. SDP support was introduced to Java Platform, Standard Edition ("Java SE Platform") in JDK7 for applications deployed in the Solaris Operating System ("Solaris OS"). The Solaris OS has supported SDP and InfiniBand since Solaris 10 5/08.

Page 129: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 129 of 165

______________________________________________________________________

* Every computer on the Internet has an address. An Internet address is a number that uniquely

identifies each computer on the Net. Originally, all Internet addresses consisted of 32-bit values.

* The URL provides a reasonably intelligible form to uniquely identify or address information on the

Internet. URLs are ubiquitous; every browser uses them to identify information on the Web.

* There is one problem with the simple server in the preceding example. Suppose we want to allow multiple clients to connect to our server at the same time. Typically, a server runs constantly on a server computer, and clients from all over the Internet may want to use the server at the same time. Rejecting multiple connections allows any one client to monopolize the service by connecting to it for a long time. We can do much better through the magic of threads.

* To send e-mail, you make a socket connection to port 25, the SMTP port. SMTP is the Simple Mail

Transport Protocol that describes the format for e-mail messages. You can connect to any server that

runs an SMTP service.

* UDP provides an unreliable packet delivery system built on top of the IP protocol. As with IP, each

packet is an individual, and is handled separately. Because of this, the amount of data that can be

sent in a UDP packet is limited to the amount that can be contained in a single IP packet.

* TCP packets are lost occasionally, just like UDP packets. The difference is that the TCP protocol takes care of requesting retransmits to ensure that all packets show up, and tracks packet sequence numbers to be sure that they are delivered in the correct order. While UDP required us to send packets of byte arrays, with TCP we can use streams along with the standard Java file I/O mechanism.

* A socket is one endpoint of a two-way communication link between two programs running on the

network. A socket is bound to a port number so that the TCP layer can identify the application that

data is destined to be sent.

* The InetAddress class is used to encapsulate both the numerical IP address we discussed earlier

and the domain name for that address.

* URLConnection is a general-purpose class for accessing the attributes of a remote resource. Once you make a connection to a remote server, you can use URLConnection to inspect the properties of the remote object before actually transporting it locally.

* The Sockets Direct Protocol (SDP) is a networking protocol developed to support stream connections over InfiniBand fabric. SDP support was introduced to Java Platform, Standard Edition ("Java SE Platform") in JDK7 for applications deployed in the Solaris Operating System ("Solaris OS"). The Solaris OS has supported SDP and InfiniBand since Solaris 10 5/08.

IMP Question Set

SR No. Question Reference page No.

1 Q. Explain Internet Addressing? 97

2 Q. Write a note on URL?

97

3 Q. Write a note on How to Serve Multiple Clients?

103

4 Q. Explain How to Send E-Mail in java?

106

5 Q. Write note on Socket Programming? 111

6 Q. what is a Socket? 116

7 Q. Write a Short note on URL Connection? 121

Quick Revision

Page 130: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 130 of 165

CHAPTER 3 : RMI Topic Covered:

Introduction to distributed object system, Distributed Object Technologies, RMI for distributed computing,

RMI Architecture, RMI Registry Service, Parameter Passing in Remote Methods, Creating RMI

application, Steps involved in running the RMI application, Using RMI with Applets.

Introduction to distributed object system

Q. Explain distributed object system?

Distributed Applications

CORBA products provide a framework for the development and execution of distributed applications. But why would one want to develop a distributed application in the first place? As you will see later, distribution introduces a whole new set of difficult issues. However, sometimes there is no choice; some applications by their very nature are distributed across multiple computers because of one or more of the following reasons:

The data used by the application are distributed

The computation is distributed

The users of the application are distributed

Data are Distributed

Some applications must execute on multiple computers because the data that the application must access exist on multiple computers for administrative and ownership reasons. The owner may permit the data to be accessed remotely but not stored locally. Or perhaps the data cannot be co-located and must exist on multiple heterogeneous systems for historical reasons.

Computation is Distributed

Some applications execute on multiple computers in order to take advantage of multiple processors computing in parallel to solve some problem. Other applications may execute on multiple computers in order to take advantage of some unique feature of a particular system. Distributed applications can take advantage of the scalability and heterogeneity of the distributed system.

Users are Distributed

Some applications execute on multiple computers because users of the application communicate and interact with each other via the application. Each user executes a piece of the distributed application on his or her computer, and shared objects, typically execute on one or more servers. A typical architecture

Page 131: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 131 of 165

for this kind of application is illustrated below.

Prior to designing a distributed application, it is essential to understand some of the fundamental realities of the distributed system on which it will execute.

Fundamental Realities of Distributed Systems

Distributed application developers must address a number of issues that can be taken for granted in a local program where all logic executes in the same operating system process. The following table summarizes some of the basic differences between objects that are co-located in the same process, and objects that interact across process or machine boundaries.

Distributed Object Systems Distributed object systems are distributed systems in which all entities are modeled as objects. Distributed object systems are a popular paradigm f or object-oriented distributed applications. Since the application is modeled as a set of cooperating objects, it maps very naturally to the services of the distributed system. In spite of the natural mapping from object-oriented modeling to distributed object systems, do not forget the realities of distributed systems described above. Process boundaries really do matter and they will impact y our design. That said, the next section of this course discusses the CORBA standard f or distributed object systems.

What is CORBA?

CORBA, or Common Object Request Broker Architecture, is a standard architecture for distributed object systems. It allows a distributed, heterogeneous collection of objects to interoperate.

The OMG

The Object Management Group (OMG) is responsible for defining CORBA. The OMG comprises

over 700 companies and organizations, including almost all the major vendors and developers of distributed object technology, including platform, database, and application vendors as well as software tool and corporate developers.

CORBA Architecture

CORBA defines an architecture for distributed objects. The basic CORBA paradigm is that of a request for services of a distributed object. Everything else defined by the OMG is in terms of this basic paradigm.

The services that an object provides are given by its interface. Interfaces are defined in OMG's Interface Definition Language (IDL). Distributed objects are identified by object references, which are typed by IDL interfaces.

Page 132: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 132 of 165

The figure below graphically depicts a request. A client holds an object reference to a distributed object. The object reference is typed by an interface. In the figure below the object reference is typed by the Rabbit interface. The Object Request Broker, or ORB, delivers the request to the object and returns any results to the client. In the figure, a jump request returns an object reference typed by the Another Object interface.

CORBA as a Standard for Distributed Objects

One of the goals of the CORBA specification is that clients and object implementations are portable. The CORBA specification defines an application programmer's interface (API) for clients of a distributed object as well as an API for the implementation of a CORBA object. This means that code written for one vendor's CORBA product could, with a minimum of effort, be rewritten to work with a different vendor's product. However, the reality of CORBA products on the market today is that CORBA clients are portable but object implementations need some rework to port from one CORBA product to another.

CORBA 2.0 added interoperability as a goal in the specification. In particular, CORBA 2.0 defines a network protocol, called IIOP (Internet Inter-ORB Protocol), that allows clients using a CORBA product from any vendor to communicate with objects using a CORBA product from any other vendor. IIOP works across the Internet, or more precisely, across any TCP/IP implementation.

Interoperability is more important in a distributed system than portability. IIOP is used in other systems that do not even attempt to provide the CORBA API. In particular, IIOP is used as the transport protocol for a version of Java RMI (so called "RMI over IIOP"). Since EJB is defined in terms of RMI, it too can use IIOP. Various application servers available on the market use IIOP but do not expose the entire CORBA API. Because they all use IIOP, programs written to these different API's can interoperate with each other and with programs written to the CORBA API.

CORBA Services

Another important part of the CORBA standard is the definition of a set of distributed services to support the integration and interoperation of distributed objects. As depicted in the graphic below, the services, known as CORBA Services or COS, are defined on top of the ORB. That is, they are defined as standard

Page 133: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 133 of 165

CORBA objects with IDL interfaces, sometimes referred to as "Object Services."

There are several CORBA services. The popular ones are described in detail in another module of this course. Below is a brief description of each:

Service Description

Object life cycle Defines how CORBA objects are created, removed, moved, and copied

Naming Defines how CORBA objects can have friendly symbolic names

Events Decouples the communication between distributed objects

Relationships Provides arbitrary typed n-ary relationships between CORBA objects

Externalization Coordinates the transformation of CORBA objects to and from external

media

Transactions Coordinates atomic access to CORBA objects

Concurrency Control Provides a locking service for CORBA objects in order to ensure

serializable access

Property Supports the association of name-value pairs with CORBA objects

Trader Supports the finding of CORBA objects based on properties describing

the service offered by the object

Query Supports queries on objects

Page 134: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 134 of 165

Distributed Object Technology (DOT)

DOT is the synergistic merger of three technologies: object technology, distribution technology, and WWW technology. Related Topics include: Client/Server Architectures, and Object Oriented Languages such as Java, Jini, and XML.

Literature

Service Providers/Consultants

Tools

ActiveX

A loosely defined set of technologies developed by Microsoft. ActiveX is an outgrowth of two other

Microsoft technologies called OLE (Object Linking and Embedding) and COM (Component Object

Model).

CORBA

Common Object Request Broker Architecture

Distributed Component Object Model (DCOM)

DCOM is a protocol that enables software components to communicate directly over a network in a

reliable, secure, and efficient manner.

Unified Modeling Language (UML)

UML is a language for specifying, constructing, visualizing, and documenting the artifacts of a software -

intensive system.

Introduction to Distributed Computing with RMI

Remote Method Invocation (RMI) technology, first introduced in JDK 1.1, elevates network programming to a higher plane. Although RMI is relatively easy to use, it is a remarkably powerful technology and exposes the average Java developer to an entirely new paradigm--the world of distributed object computing.

This course provides you with an in-depth introduction to this versatile technology. RMI has evolved considerably since JDK 1.1, and has been significantly upgraded under the Java 2 SDK. Where applicable, the differences between the two releases will be indicated.

Goals

A primary goal for the RMI designers was to allow programmers to develop distributed Java programs with the same syntax and semantics used for non-distributed programs. To do this, they had to carefully

map how Java classes and objects work in a single Java Virtual Machine1 (JVM) to a new model of how

classes and objects would work in a distributed (multiple JVM) computing environment.

This section introduces the RMI architecture from the perspective of the distributed or remote Java objects, and explores their differences through the behavior of local Java objects. The RMI architecture defines how objects behave, how and when exceptions can occur, how memory is managed, and how parameters are passed to, and returned from, remote methods.

Page 135: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 135 of 165

Comparison of Distributed and Nondistributed Java Programs

The RMI architects tried to make the use of distributed Java objects similar to using local Java objects. While they succeeded, some important differences are listed in the table below.

Do not worry if you do not understand all of the difference. They will become clear as you explore the RMI architecture. You can use this table as a reference as you learn about RMI.

Local Object Remote Object

Object Definition A local object is defined by a Java

class.

A remote object's exported behavior is defined by an

interface that must extend the Remote interface.

Object

Implementation

A local object is implemented by

its Java class.

A remote object's behavior is executed by a Java

class that implements the remote interface.

Object Creation A new instance of a local object is

created by the new operator.

A new instance of a remote object is created on the

host computer with the new operator. A client cannot

directly create a new remote object (unless using Java

2 Remote Object Activation).

Object Access A local object is accessed directly

via an object reference variable.

A remote object is accessed via an object reference

variable which points to a proxy stub implementation

of the remote interface.

References In a single JVM, an object

reference points directly at an

object in the heap.

A "remote reference" is a pointer to a proxy object (a

"stub") in the local heap. That stub contains

information that allows it to connect to a remote

object, which contains the implementation of the

methods.

Active References In a single JVM, an object is

considered "alive" if there is at

least one reference to it.

In a distributed environment, remote JVMs may crash,

and network connections may be lost. A remote object

is considered to have an active remote reference to it

if it has been accessed within a certain time period

(the lease period). If all remote references have been

explicitly dropped, or if all remote references have

expired leases, then a remote object is available for

distributed garbage collection.

Finalization If an object implements the

finalize() method, it is called

before an object is reclaimed by

the garbage collector.

If a remote object implements the Unreferenced

interface, the unreferenced method of that interface is

called when all remote references have been dropped.

Page 136: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 136 of 165

Garbage

Collection

When all local references to an

object have been dropped, an

object becomes a candidate for

garbage collection.

The distributed garbage collector works with the local

garbage collector. If there are no remote references

and all local references to a remote object have been

dropped, then it becomes a candidate for garbage

collection through the normal means.

Exceptions Exceptions are either Runtime

exceptions or Exceptions. The

Java compiler forces a program to

handle all Exceptions.

RMI forces programs to deal with any possible

RemoteException objects that may be thrown. This

was done to ensure the robustness of distributed

applications.

Q. Explain Java RMI Architecture?

Java RMI Architecture

The design goal for the RMI architecture was to create a Java distributed object model that integrates naturally into the Java programming language and the local object model. RMI architects have succeeded; creating a system that extends the safety and robustness of the Java architecture to the distributed computing world.

Interfaces: The Heart of RMI

The RMI architecture is based on one important principle: the definition of behavior and the implementation of that behavior are separate concepts. RMI allows the code that defines the behavior and the code that implements the behavior to remain separate and to run on separate JVMs.

This fits nicely with the needs of a distributed system where clients are concerned about the definition of a service and servers are focused on providing the service.

Specifically, in RMI, the definition of a remote service is coded using a Java interface. The implementation of the remote service is coded in a class. Therefore, the key to understanding RMI is to

remember that interfaces define behavior and classes define implementation.

While the following diagram illustrates this separation,

remember that a Java interface does not contain executable code. RMI supports two classes that implement the same interface. The first class is the implementation of the behavior, and it runs on the server. The second class acts as a proxy for the remote service and it runs on the client. This is shown in the following diagram.

Page 137: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 137 of 165

A client program makes method calls on the proxy object, RMI sends the request to the remote JVM, and forwards it to the implementation. Any return values provided by the implementation are sent back to the proxy and then to the client's program.

RMI Architecture Layers

With an understanding of the high-level RMI architecture, take a look under the covers to see its implementation.

The RMI implementation is essentially built from three abstraction layers. The first is the Stub and Skeleton layer, which lies just beneath the view of the developer. This layer intercepts method calls made by the client to the interface reference variable and redirects these calls to a remote RMI service.

The next layer is the Remote Reference Layer. This layer understands how to interpret and manage references made from clients to the remote service objects. In JDK 1.1, this layer connects clients to remote service objects that are running and exported on a server. The connection is a one-to-one (unicast) link. In the Java 2 SDK, this layer was enhanced to support the activation of dormant remote

service objects via Remote Object Activation.

The transport layer is based on TCP/IP connections between machines in a network. It provides basic connectivity, as well as some firewall penetration strategies.

By using a layered architecture each of the layers could be enhanced or replaced without affecting the rest of the system. For example, the transport layer could be replaced by a UDP/IP layer without affecting the upper layers.

Stub and Skeleton Layer

The stub and skeleton layer of RMI lie just beneath the view of the Java developer. In this layer, RMI uses

the Proxy design pattern as described in the book, Design Patterns by Gamma, Helm, Johnson and

Page 138: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 138 of 165

Vlissides. In the Proxy pattern, an object in one context is represented by another (the proxy) in a separate context. The proxy knows how to forward method calls between the participating objects. The following class diagram illustrates the Proxy pattern.

In RMI's use of the Proxy pattern, the stub class plays the role of the proxy, and the remote service implementation class plays the role of the RealSubject.

A skeleton is a helper class that is generated for RMI to use. The skeleton understands how to

communicate with the stub across the RMI link. The skeleton carries on a conversation with the stub; it reads the parameters for the method call from the link, makes the call to the remote service implementation object, accepts the return value, and then writes the return value back to the stub.

In the Java 2 SDK implementation of RMI, the new wire protocol has made skeleton classes obsolete. RMI uses reflection to make the connection to the remote service object. You only have to worry about skeleton classes and objects in JDK 1.1 and JDK 1.1 compatible system implementations.

Remote Reference Layer

The Remote Reference Layers defines and supports the invocation semantics of the RMI connection. This layer provides a RemoteRef object that represents the link to the remote service implementation object.

The stub objects use the invoke() method in RemoteRef to forward the method call. The RemoteRef object understands the invocation semantics for remote services.

The JDK 1.1 implementation of RMI provides only one way for clients to connect to remote service implementations: a unicast, point-to-point connection. Before a client can use a remote service, the remote service must be instantiated on the server and exported to the RMI system. (If it is the primary service, it must also be named and registered in the RMI Registry).

The Java 2 SDK implementation of RMI adds a new semantic for the client-server connection. In this version, RMI supports activatable remote objects. When a method call is made to the proxy for an activatable object, RMI determines if the remote service implementation object is dormant. If it is dormant, RMI will instantiate the object and restore its state from a disk file. Once an activatable object is in memory, it behaves just like JDK 1.1 remote service implementation objects.

Other types of connection semantics are possible. For example, with multicast, a single proxy could send a method request to multiple implementations simultaneously and accept the first reply (this improves response time and possibly improves availability). In the future, Sun may add additional invocation semantics to RMI.

Page 139: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 139 of 165

Transport Layer

The Transport Layer makes the connection between JVMs. All connections are stream-based network connections that use TCP/IP.

Even if two JVMs are running on the same physical computer, they connect through their host computer's TCP/IP network protocol stack. (This is why you must have an operational TCP/IP configuration on your computer to run the Exercises in this course). The following diagram shows the unfettered use of TCP/IP connections between JVMs.

As you know, TCP/IP provides a persistent, stream-based connection between two machines based on an IP address and port number at each end. Usually a DNS name is used instead of an IP address; this means you could talk about a TCP/IP connection between flicka.magelang.com:3452 and rosa.jguru.com:4432. In the current release of RMI, TCP/IP connections are used as the foundation for all machine-to-machine connections.

On top of TCP/IP, RMI uses a wire level protocol called Java Remote Method Protocol (JRMP). JRMP is

a proprietary, stream-based protocol that is only partially specified is now in two versions. The first

version was released with the JDK 1.1 version of RMI and required the use of Skeleton classes on the server. The second version was released with the Java 2 SDK. It has been optimized for performance and does not require skeleton classes. (Note that some alternate implementations, such as BEA

Weblogic and NinjaRMI do not use JRMP, but instead use their own wire level protocol. ObjectSpace's

Voyager does recognize JRMP and will interoperate with RMI at the wire level.) Some other changes with the Java 2 SDK are that RMI service interfaces are not required to extend from java.rmi.Remote and their service methods do not necessarily throw RemoteException.

Sun and IBM have jointly worked on the next version of RMI, called RMI-IIOP, which will be available

with Java 2 SDK Version 1.3. The interesting thing about RMI-IIOP is that instead of using JRMP, it will

use the Object Management Group (OMG) Internet Inter-ORB Protocol, IIOP, to communicate

between clients and servers.

The OMG is a group of more than 800 members that defines a vendor-neutral, distributed object architecture called Common Object Request Broker Architecture (CORBA). CORBA Object Request Broker (ORB) clients and servers communicate with each other using IIOP. With the adoption of the Objects-by-Value extension to CORBA and the Java Language to IDL Mapping proposal, the ground work was set for direct RMI to CORBA integration. This new RMI-IIOP implementation supports most of the RMI feature set, except for:

java.rmi.server.RMISocketFactory

UnicastRemoteObject Unreferenced

The DGC interfaces

Page 140: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 140 of 165

The RMI transport layer is designed to make a connection between clients and server, even in the face of networking obstacles.

While the transport layer prefers to use multiple TCP/IP connections, some network configurations only allow a single TCP/IP connection between a client and server (some browsers restrict applets to a single network connection back to their hosting server).

In this case, the transport layer multiplexes multiple virtual connections within a single TCP/IP connection.

Q. Write a short note on Parameter passing in Remote Methods?

Parameter Passing in Remote Methods

You often want to pass parameters to remote objects. This section explains some of the techniques for doing so—along with some of the pitfalls. Passing Nonremote Objects When a remote object is passed from the server to the client, the client receives a stub. Using the stub, it can manipulate the server object by invoking remote methods. The object, however, stays on the server. It is also possible to pass and return any objects via a remote method call, not just those that implement the Remote interface. For example, the getDescription method of the preceding section returned a String object. That string was created on the server and had to be transported to the client. Since String does not implement the Remote interface, the client cannot return a string stub object. Instead, the client gets a copy of the string. Then, after the call, the client has its own String object to work with. This means that there is no need for any further connection to any object on the server to deal with that string. Whenever an object that is not a remote object needs to be transported from one Java virtual machine to another, the Java virtual machine makes a copy and sends that copy across the network connection. This technique is very different from parameter passing in a local method. When you pass objects into a local method or return them as method results, only object references are passed. However, object references are memory addresses of objects in the local Java virtual machine. This information is meaningless to a different Java virtual machine. It is not difficult to imagine how a copy of a string can be transported across a network. The RMI mechanism can also make copies of more complex objects, provided they are serializable. RMI uses the serialization mechanism described in Chapter 12 of Volume 1 to send objects across a network connection. This means that only the information in any classes that implement the Serializable interface can be copied. The following program shows the copying of parameters and return values in action. This program is a simple application that lets a user shop for a gift. On the client, the user runs a program that gathers information about the gift recipient, in this case, age, sex, and hobbies (see Figure 5-6).

Figure 5-6. Obtaining product suggestions from the server

Page 141: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 141 of 165

An object of type Customer is then sent to the server. Since Customer is not a remote object, a copy of the object is made on the server. The server program sends back an array list of products. The array list contains those products that match the customer profile, and it always contains that one item that will delight anyone, namely, a copy of the book Core Java. Again, ArrayList is not a remote class, so the array list is copied from the server back to its client. As described in Chapter 12 of volume 1, the serialization mechanism makes copies of all objects that are referenced inside a copied object. In our case, it makes a copy of all array list entries as well. We added an extra complexity: the entries are actually remote Product objects. Thus, the recipient gets a copy of the array list, filled with stub objects to the products on the server (see Figure 5-7).Figure 5-7. Copying local parameter and result objects

To summarize, remote objects are passed across the network as stubs. Nonremote objects are copied. All of this is automatic and requires no programmer intervention. Whenever code calls a remote method, the stub makes a package that contains copies of all parameter values and sends it to the server, using the object serialization mechanism to marshal the parameters. The server unmarshals them. Naturally, the process can be quite slow—especially when the parameter objects are large. Let's look at the complete program. First, we have the interfaces for the product and warehouse services, as shown in Example 5-6 and Example 5-7. Example 5-6 Product.java 1. import java.rmi.*; 2. 3. /** 4. The interface for remote product objects. 5. */ 6. public interface Product extends Remote 7. { 8. /** 9. Gets the description of this product. 10. @return the product description 11. */ 12. String getDescription() throws RemoteException; 13. 14. final int MALE = 1; 15. final int FEMALE = 2; 16. final int BOTH = MALE + FEMALE; 17. } Example 5-7 Warehouse.java 1. import java.rmi.*; 2. import java.util.*; 3. 4. /** 5. The remote interface for a warehouse with products.

Page 142: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 142 of 165

6. */ 7. public interface Warehouse extends Remote 8. { 9. /** 10. Gets products that are good matches for a customer. 11. @param c the customer to match 12. @return an array list of matching products 13. */ 14. ArrayList find(Customer c) throws RemoteException; 15. } Example 5-8 shows the implementation for the product service. Products store a description, an age range, the gender targeted (male, female, or both), and the matching hobby. Note that this class implements the getDescription method advertised in the Product interface, and it also implements another method, match, which is not a part of that interface. The match method is an example of a local method, a method that can be called only from the local program, not remotely. Since the match method is local, it need not be prepared to throw a RemoteException. Example 5-9 contains the code for the Customer class. Note once again that Customer is not a remote class—none of its methods can be executed remotely. However, the class is serializable. Therefore, objects of this class can be transported from one virtual machine to another. Examples 5-10 and 5-11 shows the interface and implementation for the warehouse service. Like the ProductImpl class, the WarehouseImpl class has local and remote methods. The add and read methods are local; they are used by the server to add products to the warehouse. The find method is remote; it is used to find items in the warehouse. To illustrate that the Customer object is actually copied, the find method of the WarehouseImpl class clears the customer object it receives. When the remote method returns, the WarehouseClient displays the customer object that it sent to the server. As you will see, that object has not changed. The server cleared only its copy. In this case, the reset operation serves no useful purpose except to demonstrate that local objects are copied when they are passed as parameters. In general, the methods of server classes such as ProductImpl and WarehouseImpl should be synchronized. Then, it is possible for multiple client stubs to make simultaneous calls to a server object, even if some of the methods change the state of the server. (See Chapter 2 for more details on synchronized methods.) In Example 5-11, we synchronize the methods of the WarehouseImpl class because it is conceivable that the local add and the remote find methods are called simultaneously. We don't synchronize the methods of the ProductImpl class because the product server objects don't change their state. Example 5-12 shows the server program that creates a warehouse object and registers it with the bootstrap registry service. Example 5-13 shows the code for the client. When the user clicks on the "Submit" button, a new customer object is generated and passed to the remote find method. Then, the customer record is displayed in the text area (to prove that the clear call in the server did not affect it). Finally, the product descriptions of the returned products in the array list are added to the text area. Note that each getDescription call is again a remote method invocation. That would not be a good design in practice—you would normally pass small objects such as product descriptions by value. But we want to demonstrate that a remote object is automatically replaced by a stub during marshalling. Example 5-8 ProductImpl.java 1. import java.rmi.*; 2. import java.rmi.server.*; 3. 4. /** 5. This is the implementation class for the remote product 6. objects. 7. */ 8. public class ProductImpl 9. extends UnicastRemoteObject 10. implements Product 11. {

Page 143: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 143 of 165

12. /** 13. Constructs a product implementation 14. @param n the product name 15. @param s the suggested sex (MALE, FEMALE, or BOTH) 16. @param age1 the lower bound for the suggested age 17. @param age2 the upper bound for the suggested age 18. @param h the hobby matching this product 19. */ 20. public ProductImpl(String n, int s, int age1, int age2, 21. String h) throws RemoteException 22. { 23. name = n; 24. ageLow = age1; 25. ageHigh = age2; 26. sex = s; 27. hobby = h; 28. } 29. 30. /** 31. Checks whether this product is a good match for a 32. customer. Note that this method is a local method since 33. it is not part of the Product interface. 34. @param c the customer to match against this product 35. @return true if this product is appropriate for the 36. customer 37. */ 38. public boolean match(Customer c) 39. { 40. if (c.getAge() < ageLow || c.getAge() > ageHigh) 41. return false; 42. if (!c.hasHobby(hobby)) return false; 43. if ((sex & c.getSex()) == 0) return false; 44. return true; 45. } 46. 47. public String getDescription() throws RemoteException 48. { 49. return "I am a " + name + ". Buy me!"; 50. } 51. 52. private String name; 53. private int ageLow; 54. private int ageHigh; 55. private int sex; 56. private String hobby; 57. } Example 5-9 Customer.java 1. import java.io.*; 2. 3. /** 4. Description of a customer. Note that customer objects are not 5. remote--the class does not implement a remote interface. 6. */ 7. public class Customer implements Serializable 8. { 9. /**

Page 144: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 144 of 165

10. Constructs a customer. 11. @param theAge the customer's age 12. @param theSex the customer's sex (MALE or FEMALE) 13. @param theHobbies the customer's hobbies 14. */ 15. public Customer(int theAge, int theSex, String[] theHobbies) 16. { 17. age = theAge; 18. sex = theSex; 19. hobbies = theHobbies; 20. } 21. 22. /** 23. Gets the customer's age. 24. @return the age 25. */ 26. public int getAge() { return age; } 27. 28. /** 29. Gets the customer's sex 30. @return MALE or FEMALE 31. */ 32. public int getSex() { return sex; } 33. 34. /** 35. Tests whether this customer has a particular hobby. 36. @param aHobby the hobby to test 37. @return true if this customer has the hobby 38. */ 39. public boolean hasHobby(String aHobby) 40. { 41. if (aHobby == "") return true; 42. for (int i = 0; i < hobbies.length; i++) 43. if (hobbies[i].equals(aHobby)) return true; 44. 45. return false; 46. } 47. 48. /** 49. Resets this customer record to default values. 50. */ 51. public void reset() 52. { 53. age = 0; 54. sex = 0; 55. hobbies = null; 56. } 57. 58. public String toString() 59. { 60. String result = "Age: " + age + ", Sex: "; 61. if (sex == Product.MALE) result += "Male"; 62. else if (sex == Product.FEMALE) result += "Female"; 63. else result += "Male or Female"; 64. result += ", Hobbies:"; 65. for (int i = 0; i < hobbies.length; i++)

Page 145: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 145 of 165

66. result += " " + hobbies[i]; 67. return result; 68. } 69. 70. private int age; 71. private int sex; 72. private String[] hobbies; 73. } Example 5-10 Warehouse.java 1. import java.rmi.*; 2. import java.util.*; 3. 4. /** 5. The remote interface for a warehouse with products. 6. */ 7. public interface Warehouse extends Remote 8. { 9. /** 10. Gets products that are good matches for a customer. 11. @param c the customer to match 12. @return an array list of matching products 13. */ 14. ArrayList find(Customer c) throws RemoteException; 15. } Example 5-11 WarehouseImpl.java 1. import java.io.*; 2. import java.rmi.*; 3. import java.util.*; 4. import java.rmi.server.*; 5. import java.util.*; 6. 7. /** 8. This class is the implementation for the remote 9. Warehouse interface. 10. */ 11. public class WarehouseImpl 12. extends UnicastRemoteObject 13. implements Warehouse 14. { 15. /** 16. Constructs a warehouse implementation. 17. */ 18. public WarehouseImpl() 19. throws RemoteException 20. { 21. products = new ArrayList(); 22. coreJavaBook = new ProductImpl("Core Java Book", 23. 0, 200, Product.BOTH, "Computers"); 24. } 25. 26. /** 27. Reads in a set of product descriptions. Each line has t 28. the format 29. name|sex|age1|age2|hobby, e.g. 30. Blackwell Toaster|BOTH|18|200|Household 31. @param reader the reader to read from

Page 146: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 146 of 165

32. */ 33. public void read(BufferedReader reader) throws IOException 34. { 35. String line; 36. while ((line = reader.readLine()) != null) 37. { 38. StringTokenizer tokenizer = new StringTokenizer(line, 39. "|"); 40. String name = tokenizer.nextToken(); 41. String s = tokenizer.nextToken(); 42. int sex = 0; 43. if (s.equals("MALE")) sex = Product.MALE; 44. else if (s.equals("FEMALE")) sex = Product.FEMALE; 45. else if (s.equals("BOTH")) sex = Product.BOTH; 46. int age1 = Integer.parseInt(tokenizer.nextToken()); 47. int age2 = Integer.parseInt(tokenizer.nextToken()); 48. String hobby = tokenizer.nextToken(); 49. add(new ProductImpl(name, sex, age1, age2, hobby)); 50. } 51. } 52. 53. /** 54. Add a product to the warehouse. Note that this is a local 55. method. 56. @param p the product to add 57. */ 58. public synchronized void add(ProductImpl p) 59. { 60. products.add(p); 61. } 62. 63. public synchronized ArrayList find(Customer c) 64. throws RemoteException 65. { 66. ArrayList result = new ArrayList(); 67. // add all matching products 68. for (int i = 0; i < products.size(); i++) 69. { 70. ProductImpl p = (ProductImpl)products.get(i); 71. if (p.match(c)) result.add(p); 72. } 73. // add the product that is a good match for everyone 74. result.add(coreJavaBook); 75. 76. // we reset c just to show that c is a copy of the 77. // client object 78. c.reset(); 79. return result; 80. } 81. 82. private ArrayList products; 83. private ProductImpl coreJavaBook;

Page 147: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 147 of 165

84. } Example 5-12 WarehouseServer.java 1. import java.io.*; 2. import java.rmi.*; 3. import java.rmi.server.*; 4. 5. /** 6. This server program instantiates a remote warehouse 7. objects, registers it with the naming service, and waits 8. for clients to invoke methods. 9. */ 10. public class WarehouseServer 11. { 12. public static void main(String[] args) 13. { 14. try 15. { 16. System.out.println 17. ("Constructing server implementations..."); 18. 19. WarehouseImpl w = new WarehouseImpl(); 20. w.read(new BufferedReader(new 21. FileReader("products.dat"))); 22. 23. System.out.println 24. ("Binding server implementations to registry..."); 25. 26. Naming.rebind("central_warehouse", w); 27. 28. System.out.println 29. ("Waiting for invocations from clients..."); 30. } 31. catch(Exception e) 32. { 33. e.printStackTrace(); 34. } 35. } 36. } Example 5-13 WarehouseClient.java 1. import java.awt.*; 2. import java.awt.event.*; 3. import java.io.*; 4. import java.rmi.*; 5. import java.rmi.server.*; 6. import java.util.*; 7. import javax.swing.*; 8. 9. /** 10. The client for the warehouse program. 11. */ 12. public class WarehouseClient 13. { 14. public static void main(String[] args) 15. {

Page 148: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 148 of 165

16. System.setProperty("java.security.policy", "client.policy"); 17. System.setSecurityManager(new RMISecurityManager()); 18. JFrame frame = new WarehouseClientFrame(); 19. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE ); 20. frame.show(); 21. } 22. } 23. 24. /** 25. A frame to select the customer's age, sex, and hobbies, and to 26. show the matching products resulting from a remote call to the 27. warehouse. 28. */ 29. class WarehouseClientFrame extends JFrame 30. { 31. public WarehouseClientFrame() 32. { 33. setTitle("WarehouseClient"); 34. setSize(WIDTH, HEIGHT); 35. initUI(); 36. 37. try 38. { 39. Properties props = new Properties(); 40. String fileName = "WarehouseClient.properties"; 41. FileInputStream in = new FileInputStream(fileName); 42. props.load(in); 43. String url = props.getProperty("warehouse.url"); 44. if (url == null) 45. url = "rmi://localhost/central_warehouse"; 46. 47. centralWarehouse = (Warehouse)Naming.lookup(url); 48. } 49. catch(Exception e) 50. { 51. System.out.println("Error: Can't connect to warehouse. " + e); 52. } 53. } 54. 55. /** 56. Initializes the user interface. 57. */ 58. private void initUI() 59. { 60. getContentPane().setLayout(new GridBagLayout()); 61. 62. GridBagConstraints gbc = new GridBagConstraints(); 63. gbc.fill = GridBagConstraints.HORIZONTAL; 64. gbc.weightx = 100; 65. gbc.weighty = 0; 66. 67. add(new JLabel("Age:"), gbc, 0, 0, 1, 1); 68. age = new JTextField(4);

Page 149: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 149 of 165

69. age.setText("20"); 70. add(age, gbc, 1, 0, 1, 1); 71. 72. male = new JCheckBox("Male", true); 73. female = new JCheckBox("Female", true); 74. add(male, gbc, 0, 1, 1, 1); 75. add(female, gbc, 1, 1, 1, 1); 76. 77. add(new JLabel("Hobbies"), gbc, 0, 2, 1, 1); 78. String[] choices = { "Gardening", "Beauty", 79. "Computers", "Household", "Sports" }; 80. gbc.fill = GridBagConstraints.BOTH; 81. hobbies = new JComboBox(choices); 82. add(hobbies, gbc, 1, 2, 1, 1); 83. 84. gbc.fill = GridBagConstraints.NONE; 85. JButton submitButton = new JButton("Submit"); 86. add(submitButton, gbc, 0, 3, 2, 1); 87. submitButton.addActionListener(new 88. ActionListener() 89. { 90. public void actionPerformed(ActionEvent evt) 91. { 92. callWarehouse(); 93. } 94. }); 95. 96. gbc.weighty = 100; 97. gbc.fill = GridBagConstraints.BOTH; 98. result = new JTextArea(4, 40); 99. result.setEditable(false); 100. add(result, gbc, 0, 4, 2, 1); 101. } 102. 103. /** 104. Add a component to this frame. 105. @param c the component to add 106. @param gbc the grid bag constraints 107. @param x the grid bax column 108. @param y the grid bag row 109. @param w the number of grid bag columns spanned 110. @param h the number of grid bag rows spanned 111. */ 112. private void add(Component c, GridBagConstraints gbc, 113. int x, int y, int w, int h) 114. { gbc.gridx = x; 115. gbc.gridy = y; 116. gbc.gridwidth = w; 117. gbc.gridheight = h; 118. getContentPane().add(c, gbc); 119. } 120. 121. /** 122. Call the remote warehouse to find matching products. 123. */ 124. private void callWarehouse()

Page 150: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 150 of 165

125. { 126. try 127. { 128. Customer c = new Customer(Integer.parseInt(age.getText()), 129. (male.isSelected() ? Product.MALE : 0) 130. + (female.isSelected() ? Product.FEMALE : 0), 131. new String[] { (String)hobbies.getSelectedItem() }); 132. ArrayList recommendations = centralWarehouse.find(c); 133. result.setText(c + "\n"); 134. for (int i = 0; i < recommendations.size(); i++) 135. { 136. Product p = (Product)recommendations.get(i); 137. String t = p.getDescription() + "\n"; 138. result.append(t); 139. } 140. } 141. catch(Exception e) 142. { 143. result.setText("Exception: " + e); 144. } 145. } 146. 147. private static final int WIDTH = 300; 148. private static final int HEIGHT = 300; 149. 150. private Warehouse centralWarehouse; 151. private JTextField age; 152. private JCheckBox male; 153. private JCheckBox female; 154. private JComboBox hobbies; 155. private JTextArea result; 156. } Passing Remote Objects Passing remote objects from the server to the client is simple. The client receives a stub object, then saves it in an object variable whose type is the same as the remote interface. The client can now access the actual object on the server through the variable. The client can copy this variable in its own local machine—all those copies are simply references to the same stub. It is important to note that only the remote interfaces can be accessed through the stub. A remote interface is any interface extending Remote. All local methods are inaccessible through the stub. (A local method is any method that is not defined in a remote interface.) Local methods can run only on the virtual machine containing the actual object.Next, stubs are generated only from classes that implement a remote interface, and only the methods specified in the interfaces are provided in the stub classes. If a subclass doesn't implement a remote interface but asuperclass does, and an object of the subclass is passed to a remote method, only the superclass methods are accessible. To understand this better, consider the following example. We derive a class BookImpl from ProductImpl. class BookImpl extends ProductImpl { public BookImpl(String title, String theISBN, int sex, int age1, int age2, String hobby) { super(title + " Book", sex, age1, age2, hobby); ISBN = theISBN; } public String getStockCode() { return ISBN; } private String ISBN;

Page 151: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 151 of 165

} Now, suppose we pass a book object to a remote method, either as a parameter or as a return value. The recipient obtains a stub object. But that stub is not a book stub. Instead, it is a stub to the superclass ProductImpl since only that class implements a remote interface (see Figure 5-8). Thus, in this case, the getStockCode method isn't available remotely. Figure 5-8. Only the ProductImpl methods are remote

A remote class can implement multiple interfaces. For example, the BookImpl class can implement a second interface in addition to Product. Here, we define a remote interface StockUnit and have the BookImpl class implement it. interface StockUnit extends Remote { public String getStockCode() throws RemoteException; } class BookImpl extends ProductImpl implements StockUnit { public BookImpl(String title, String theISBN, int sex, int age1, int age2, String hobby) throws RemoteException { super(title + " Book", sex, age1, age2, hobby); ISBN = theISBN; } public String getStockCode() throws RemoteException { return ISBN; } private String ISBN; } Figure 5-9 shows the inheritance diagram.

Page 152: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 152 of 165

Now, when a book object is passed to a remote method, the recipient obtains a stub that has access to the remote methods in both the Product and the StockUnit class. In fact, you can use the instanceof operator to find out whether a particular remote object implements an interface. Here is a typical situation where you will use this feature. Suppose you receive a remote object through a variable of type Product. ArrayList result = centralWarehouse.find(c); for (int i = 0; i < result.size(); i++) { Product p = (Product)result.elementAt(i); . . . } Now, the remote object may or may not be a book. We'd like to use instanceof to find out whether it is or not. But we can't test if (p instanceof BookImpl) // wrong { BookImpl b = (BookImpl)p; . . . } The object p refers to a stub object, and BookImpl is the class of the server object. We could cast the stub object to a BookImpl_Stub, if (p instanceof BookImpl_Stub) { BookImpl_Stub b = (BookImpl_Stub)p; // not useful . . . } but that would not do us much good. The stubs are generated mechanically by the rmic program for internal use by the RMI mechanism, and clients should not have to think about them. Instead, we cast to the second interface: if (p instanceof StockUnit) { StockUnit s = (StockUnit)p; String c = s.getStockCode(); . . . } This code tests whether the stub object to which p refers implements the StockUnit interface. If so, it calls the getStockCode remote method of that interface.

Page 153: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 153 of 165

To summarize: • If an object belonging to a class that implements a remote interface is passed to a remote method, the remote method receives a stub object. • You can cast that stub object to any of the remote interfaces that the implementation class implements. • You can call all remote methods defined in those interfaces, but you cannot call any local methods through the stub. Q. Write a Note on RMI applications?

An Overview of RMI Applications

RMI applications often comprise two separate programs, a server and a client. A typical server program

creates some remote objects, makes references to these objects accessible, and waits for clients to

invoke methods on these objects. A typical client program obtains a remote reference to one or more

remote objects on a server and then invokes methods on them. RMI provides the mechanism by which

the server and the client communicate and pass information back and forth. Such an application is

sometimes referred to as a distributed object application.

Distributed object applications need to do the following:

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

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

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

The following illustration depicts an RMI distributed application that uses the RMI registry to obtain a

reference to a remote object. The server calls the registry to associate (or bind) a name with a remote

object. The client looks up the remote object by its name in the server's registry and then invokes a

method on it. The illustration also shows that the RMI system uses an existing web server to load class

definitions, from server to client and from client to server, for objects when needed.

Advantages of Dynamic Code Loading

One of the central and unique features of RMI is its ability to download the definition of an object's class if the class is not defined in the receiver's Java virtual machine. All of the types and behavior of an object, previously available only in a single Java virtual machine, can be transmitted to another, possibly remote, Java virtual machine. RMI passes objects by their actual classes, so the behavior of the objects is not

Page 154: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 154 of 165

changed when they are sent to another Java virtual machine. This capability enables new types and behaviors to be introduced into a remote Java virtual machine, thus dynamically extending the behavior of an application. The compute engine example in this trail uses this capability to introduce new behavior to a distributed program.

Remote Interfaces, Objects, and Methods

Like any other Java application, a distributed application built by using Java RMI is made up of interfaces and classes. The interfaces declare methods. The classes implement the methods declared in the interfaces and, perhaps, declare additional methods as well. In a distributed application, some implementations might reside in some Java virtual machines but not others. Objects with methods that can be invoked across Java virtual machines are called remote objects.

An object becomes remote by implementing a remote interface, which has the following characteristics:

A remote interface extends the interface java.rmi.Remote.

Each method of the interface declares java.rmi.RemoteException in its throws clause, in addition to any application-specific exceptions.

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

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

Creating Distributed Applications by Using RMI

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

1. Designing and implementing the components of your distributed application. 2. Compiling sources. 3. Making classes network accessible. 4. Starting the application.

Designing and Implementing the Application Components

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

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

Implementing the remote objects. Remote objects must implement one or more remote interfaces. The remote object class may include implementations of other interfaces and methods

Page 155: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 155 of 165

that are available only locally. If any local classes are to be used for parameters or return values of any of these methods, they must be implemented as well.

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

Compiling Sources

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

Note: With versions prior to Java Platform, Standard Edition 5.0, an additional step was required to build

stub classes, by using the rmic compiler. However, this step is no longer necessary.

Making Classes Network Accessible

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

Starting the Application

Starting the application includes running the RMI remote object registry, the server, and the client.

The rest of this section walks through the steps used to create a compute engine.

Building a Generic Compute Engine

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

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

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

Using RMI

It is now time to build a working RMI system and get hands-on experience. In this section, you will build a simple remote calculator service and use it from a client program.

Page 156: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 156 of 165

A working RMI system is composed of several parts.

Interface definitions for the remote services

Implementations of the remote services

Stub and Skeleton files

A server to host the remote services

An RMI Naming service that allows clients to find the remote services

A class file provider (an HTTP or FTP server)

A client program that needs the remote services

In the next sections, you will build a simple RMI system in a step-by-step fashion. You are encouraged to

create a fresh subdirectory on your computer and create these files as you read the text.

To simplify things, you will use a single directory for the client and server code. By running the client and the server out of the same directory, you will not have to set up an HTTP or FTP server to provide the class files. (Details about how to use HTTP and FTP servers as class file providers will be covered in the

section on Distributing and Installing RMI Software)

Assuming that the RMI system is already designed, you take the following steps to build a system:

1. Write and compile Java code for interfaces 2. Write and compile Java code for implementation classes 3. Generate Stub and Skeleton class files from the implementation classes 4. Write Java code for a remote service host program 5. Develop Java code for RMI client program 6. Install and run RMI system

1. Interfaces

The first step is to write and compile the Java code for the service interface. The Calculator interface defines all of the remote features offered by the service:

public interface Calculator extends java.rmi.Remote { public long add(long a, long b) throws java.rmi.RemoteException; public long sub(long a, long b) throws java.rmi.RemoteException; public long mul(long a, long b) throws java.rmi.RemoteException; public long div(long a, long b) throws java.rmi.RemoteException; }

Notice this interface extends Remote, and each method signature declares that it may throw a RemoteException object.

Page 157: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 157 of 165

Copy this file to your directory and compile it with the Java compiler:

>javac Calculator.java

2. Implementation

Next, you write the implementation for the remote service. This is the CalculatorImpl class:

public class CalculatorImpl extends java.rmi.server.UnicastRemoteObject implements Calculator { // Implementations must have an //explicit constructor // in order to declare the //RemoteException exception public CalculatorImpl() throws java.rmi.RemoteException { super(); } public long add(long a, long b) throws java.rmi.RemoteException { return a + b; } public long sub(long a, long b) throws java.rmi.RemoteException { return a - b; } public long mul(long a, long b) throws java.rmi.RemoteException { return a * b; } public long div(long a, long b) throws java.rmi.RemoteException { return a / b; } }

Again, copy this code into your directory and compile it.

The implementation class uses UnicastRemoteObject to link into the RMI system. In the

example the implementation class directly extends UnicastRemoteObject. This is not a requirement. A class that does not extend UnicastRemoteObject may use its exportObject() method to be linked into RMI.

When a class extends UnicastRemoteObject, it must provide a constructor that declares that it may throw a RemoteException object. When this constructor calls super(), it activates code in UnicastRemoteObject that performs the RMI linking and remote object initialization.

Page 158: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 158 of 165

3. Stubs and Skeletons

You next use the RMI compiler, rmic, to generate the stub and skeleton files. The compiler runs

on the remote service implementation class file.

>rmic CalculatorImpl

Try this in your directory. After you run rmic you should find the file Calculator_Stub.class and, if you are running the Java 2 SDK, Calculator_Skel.class.

Options for the JDK 1.1 version of the RMI compiler, rmic, are:

Usage: rmic <options> <class names> where <options> includes: -keep Do not delete intermediate generated source files -keepgenerated (same as "-keep") -g Generate debugging info -depend Recompile out-of-date files recursively -nowarn Generate no warnings -verbose Output messages about what the compiler is doing -classpath <path> Specify where to find input source and class files -d <directory> Specify where to place generated class files -J<runtime flag> Pass argument to the java interpreter

The Java 2 platform version of rmic add three new options:

-v1.1 Create stubs/skeletons for JDK 1.1 stub protocol version -vcompat (default) Create stubs/skeletons compatible with both JDK 1.1 and Java 2 stub protocol versions -v1.2 Create stubs for Java 2 stub protocol version only

4. Host Server

Remote RMI services must be hosted in a server process. The class CalculatorServer is a very simple server that provides the bare essentials for hosting.

Page 159: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 159 of 165

import java.rmi.Naming; public class CalculatorServer { public CalculatorServer() { try { Calculator c = new CalculatorImpl(); Naming.rebind("rmi://localhost:1099/CalculatorService", c); } catch (Exception e) { System.out.println("Trouble: " + e); } } public static void main(String args[]) { new CalculatorServer(); } }

5. Client

The source code for the client follows:

import java.rmi.Naming; import java.rmi.RemoteException; import java.net.MalformedURLException; import java.rmi.NotBoundException; public class CalculatorClient { public static void main(String[] args) { try { Calculator c = (Calculator) Naming.lookup( "rmi://localhost /CalculatorService"); System.out.println( c.sub(4, 3) ); System.out.println( c.add(4, 5) ); System.out.println( c.mul(3, 6) ); System.out.println( c.div(9, 3) ); } catch (MalformedURLException murle) { System.out.println(); System.out.println( "MalformedURLException"); System.out.println(murle); } catch (RemoteException re) { System.out.println(); System.out.println( "RemoteException"); System.out.println(re); } catch (NotBoundException nbe) { System.out.println(); System.out.println(

Page 160: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 160 of 165

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

6. Running the RMI System

You are now ready to run the system! You need to start three consoles, one for the server, one for the client, and one for the RMIRegistry.

Start with the Registry. You must be in the directory that contains the classes you have written. From there, enter the following:

rmiregistry

If all goes well, the registry will start running and you can switch to the next console.

In the second console start the server hosting the CalculatorService, and enter the following:

>java CalculatorServer

It will start, load the implementation into memory and wait for a client connection.

In the last console, start the client program.

>java CalculatorClient

If all goes well you will see the following output:

1 9

3 3

That's it; you have created a working RMI system. Even though you ran the three consoles on the same computer, RMI uses your network stack and TCP/IP to communicate between the three separate JVMs. This is a full-fledged RMI system.

Page 161: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 161 of 165

Q. Explain How to use RMI with Applets? Using RMI with Applets There are a number of special concerns when running RMI with applets. Applets have their own security manager since they run inside a browser. Thus, we do not use the RMISecurityManager on the client side. We must take care where to place the stub and server files. Consider a browser that opens a web page with an applet tag. The browser loads the class file referenced in that tag and all other class files as they are needed during execution. The class files are loaded from the same host that contains the web page. Because of applet security restrictions, the applet can make network connections only to its originating host. Therefore, the server objects must reside on the same host as the web page. That is, the same server must store • Web pages; • Applet code; • Stub classes; • Server objects; • The RMI registry. Here is a sample applet that further extends our shopping program. Just like the preceding application, the applet gets the customer information and then selects matching products. However, this applet sends images of the recommended items. As we mentioned previously, it is not easy to send an image from the server to the client because images are stored in a format that depends on the local graphics system. Instead, the server simply sends the client a string with the image file name, and we use the getImage method of the Applet class to obtain the image (see Figure 5-11).

Here is how you must distribute the code for this kind of situation: • java.rmi.registry.RegistryImpl— Anywhere on the host; the registry must be running before the applet starts • WarehouseServer— Anywhere on the host; must be running before the applet starts • WarehouseImpl— Can be anywhere on the host as long as WarehouseServer can find it • WarehouseApplet— Directory referenced in APPLET tag • Stubs— Must be in the same directory as WarehouseApplet The applet looks for the RMI registry on the same host that contains the applet. To find out its host, it uses the getCodeBase and getHost methods: String url = "rmi://" + getCodeBase().getHost() + "/central\u-4001warehouse";

Page 162: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 162 of 165

centralWarehouse = (Warehouse)Naming.lookup(url); Example 5-14 shows the code for the applet. Note that the applet does not install a security manager. Example 5-15 shows the applet HTML page. The product and warehouse implementations have been changed slightly to add the image file name field. See the companion code for these straightforward modifications. Example 5-14 WarehouseApplet.java 1. import java.awt.*; 2. import java.awt.event.*; 3. import java.io.*; 4. import java.rmi.*; 5. import java.rmi.server.*; 6. import java.util.*; 7. import javax.swing.*; 8. 9. /** 10. The warehouse client applet. 11. */ 12. public class WarehouseApplet extends JApplet 13. { 14. public void init() 15. { 16. initUI(); 17. 18. try 19. { 20. String warehouseName = getParameter("warehouse.name"); 21. if (warehouseName == null) 22. warehouseName = "central_warehouse"; 23. String url = "rmi://" + getCodeBase().getHost() 24. + "/" + warehouseName; 25. centralWarehouse = (Warehouse)Naming.lookup(url); 26. } 27. catch(Exception e) 28. { 29. showStatus("Error: Can't connect to warehouse. " + e); 30. } 31. } 32. 33. /** 34. Initializes the user interface. 35. */ 36. private void initUI() 37. { 38. getContentPane().setLayout(new GridBagLayout()); 39. 40. GridBagConstraints gbc = new GridBagConstraints(); 41. gbc.fill = GridBagConstraints.HORIZONTAL; 42. gbc.weightx = 100; 43. gbc.weighty = 0; 44. 45. add(new JLabel("Age:"), gbc, 0, 0, 1, 1); 46. age = new JTextField(4); 47. age.setText("20"); 48. add(age, gbc, 1, 0, 1, 1); 49. 50. male = new JCheckBox("Male", true);

Page 163: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 163 of 165

51. female = new JCheckBox("Female", true); 52. add(male, gbc, 0, 1, 1, 1); 53. add(female, gbc, 1, 1, 1, 1); 54. 55. add(new JLabel("Hobbies"), gbc, 0, 2, 1, 1); 56. String[] choices = { "Gardening", "Beauty", 57. "Computers", "Household", "Sports" }; 58. gbc.fill = GridBagConstraints.BOTH; 59. hobbies = new JComboBox(choices); 60. add(hobbies, gbc, 1, 2, 1, 1); 61. 62. gbc.fill = GridBagConstraints.NONE; 63. JButton submitButton = new JButton("Submit"); 64. add(submitButton, gbc, 0, 3, 2, 1); 65. submitButton.addActionListener(new 66. ActionListener() 67. { 68. public void actionPerformed(ActionEvent evt) 69. { 70. callWarehouse(); 71. } 72. }); 73. 74. gbc.weighty = 100; 75. gbc.fill = GridBagConstraints.BOTH; 76. result = new JTextArea(4, 40); 77. result.setEditable(false); 78. add(result, gbc, 0, 4, 2, 1); 79. 80. imagePanel = new JPanel(); 81. imagePanel.setMinimumSize(new Dimension(0, 60)); 82. add(imagePanel, gbc, 0, 5, 2, 1); 83. } 84. 85. /** 86. Add a component to this frame. 87. @param c the component to add 88. @param gbc the grid bag constraints 89. @param x the grid bax column 90. @param y the grid bag row 91. @param w the number of grid bag columns spanned 92. @param h the number of grid bag rows spanned 93. */ 94. private void add(Component c, GridBagConstraints gbc, 95. int x, int y, int w, int h) 96. { gbc.gridx = x; 97. gbc.gridy = y; 98. gbc.gridwidth = w; 99. gbc.gridheight = h; 100. getContentPane().add(c, gbc); 101. } 102. 103. /** 104. Call the remote warehouse to find matching products. 105. */

Page 164: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 164 of 165

106. private void callWarehouse() 107. { 108. try 109. { 110. Customer c = new Customer(Integer.parseInt(age.getText()), 111. (male.isSelected() ? Product.MALE : 0) 112. + (female.isSelected() ? Product.FEMALE : 0), 113. new String[] { (String)hobbies.getSelectedItem() }); 114. ArrayList recommendations = centralWarehouse.find(c); 115. result.setText(c + "\n"); 116. imagePanel.removeAll(); 117. for (int i = 0; i < recommendations.size(); i++) 118. { 119. Product p = (Product)recommendations.get(i); 120. String t = p.getDescription() + "\n"; 121. result.append(t); 122. Image productImage 123. = getImage(getCodeBase(), p.getImageFile()); 124. imagePanel.add(new JLabel(new ImageIcon(productImage))); 125. } 126. } 127. catch(Exception e) 128. { 129. result.setText("Exception: " + e); 130. } 131. } 132. 133. private static final int WIDTH = 300; 134. private static final int HEIGHT = 300; 135. 136. private Warehouse centralWarehouse; 137. private JTextField age; 138. private JCheckBox male; 139. private JCheckBox female; 140. private JComboBox hobbies; 141. private JTextArea result; 142. private JPanel imagePanel; 143. } Example 5-15 WarehouseApplet.html 1. <applet code="WarehouseApplet.class" width="600" height="400"> 2. <param name="warehouse.name" value="central_warehouse"/> 3. </applet>

Page 165: INDEX PAGE NO. SR.NO TOPIC From To 1 JFC AND ......T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV Page 2 of 165 Syllabus Introduction to JFC and Swing, Features

T.Y.B.Sc. (CS) SEM V Adv. Java BY: AJAY PASHANKAR Unit- I, II, II, IV

Page 165 of 165

______________________________________________________________________

* Distributed application developers must address a number of issues that can be taken for granted in a

local program where all logic executes in the same operating system process.

* Distributed object systems are distributed systems in which all entities are modeled as objects. Distributed object systems are a popular paradigm f or object-oriented distributed applications. Since the application is modeled as a set of cooperating objects, it maps very naturally to the services of the distributed system.

* A primary goal for the RMI designers was to allow programmers to develop distributed Java programs

with the same syntax and semantics used for non-distributed programs.

* The design goal for the RMI architecture was to create a Java distributed object model that integrates naturally into the Java programming language and the local object model. RMI architects have succeeded; creating a system that extends the safety and robustness of the Java architecture to the distributed computing world.

* The stub and skeleton layer of RMI lie just beneath the view of the Java developer.

* The Remote Reference Layers defines and supports the invocation semantics of the RMI connection. This layer provides a RemoteRef object that represents the link to the remote service implementation object.

* The Transport Layer makes the connection between JVMs. All connections are stream-based network connections that use TCP/IP.

* Passing remote objects from the server to the client is simple. The client receives a stub object, then

saves it in an object variable whose type is the same as the remote interface. The client can now

access the actual object on the server through the variable. The client can copy this variable in its

own local machine—all those copies are simply references to the same stub.

* RMI applications often comprise two separate programs, a server and a client. A typical server

program creates some remote objects, makes references to these objects accessible, and waits for

clients to invoke methods on these objects. A typical client program obtains a remote reference to

one or more remote objects on a server and then invokes methods on them.

IMP Question Set

SR No. Question Reference page No.

1 Q. Explain distributed object system? 130

2 Q. Explain Java RMI Architecture? 140

3 Q. Write a short note on Parameter passing in Remote Methods? 140

4 Q. Write a Note on RMI applications?

153

5 Q. Explain How to use RMI with Applets?

161

Quick Revision