Top Banner
[JAVA LAB DOCUMENT] 2k8 Information technology
139

Java Programming Lab Manual

Jan 26, 2016

Download

Documents

nalluri_08

Programming using Java Laboratory programs with solutions.
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Java Programming Lab Manual

[]

2k8

Information technology

Page 2: Java Programming Lab Manual

2k8 [ ]

2

Page 3: Java Programming Lab Manual

2k8 [ ]

INDEX

TITLE PAGE

1: BASIC PROGRAMS 1-5

2: APPLETS AND FRAMES 6-20

3: AWT AND SWING 21-39

4: PACKAGES 40-42

5: POLYMORPHISM 43-44

6: THREADS 45-49

7: INNER CLASSES 50-53

8: BEANS 54-70

9: REMOTE METHOD INVOCATION 71-74

10: SERVLETS 75-87

11: JDBC 88-104

12: NETWORKING 105-113

3

Page 4: Java Programming Lab Manual

2k8 [ ]

Note :

After installing the java software we must set path and classpath variables . Always ensure that the path variable points to bin directory of jdk1.6.0 and

classpath variable points to lib folder of jdk and current directory How to set PATH, CLASSPATH?

Click on MyComputer-properties- advanced tab and environment variables

In that press new button in the user-variables don’t edit system variables it may cause problems in your system response Add like thisVariable name:pathVariable value: %path%;C:\Program Files\Java\jdk1.6.0\bin;-here it is assumed that javadeveloper kit is installed in C drive

Now then make classpath as Variable name: classpathVariable value: .;C:\Program Files\Java\jre1.6.0\lib;-here (.) means current directory

4

Page 5: Java Programming Lab Manual

2k8 [ ]

Program-1 :( MyClass.java)

Write a program that reads data from key board and display it on a Console?

Source:

import java.io.*;public class MyClass{ public static void main(String pars[])

{ BufferedReader console = new BufferedReader(new

InputStreamReader(System.in));String input="" ;System.out.println("Enter Your Name::");try{input=console.readLine();}catch(Exception e){System.out.println("Exception caught::"+e.getMessage());}System.out.println("Hello "+input+" Welcome to Java!");

}}

OUTPUT:

//to compile: javac <filename>.java

// To Execute: java <file-name>

Applet:

5

Page 6: Java Programming Lab Manual

2k8 [ ]

A program that can be referenced by HTML source code of a Web page.

Can be run on Web browser after having been downloaded.

May be dangerous

Security Problem

Note:

We can view these applets by creating web document (.html) file or using the java tool appletviewer.

FRAME:

Frame is a window that is not contained inside another window. Frame is the basis to contain other user interface components in Java GUI applications.

The Frame class can be used to create windows.

PROGRAM-2: (AppletTest.java)

Write an Applet that handles mouse events and key events using adapter classes?

Source:

// <applet code="AppletTest.class" width=300 height=300> </applet>

import java.awt.*;import java.awt.event.*;

public class AppletTest extends java.applet.Applet{ int len;

public void init( ) {

this.addMouseListener( new MyMouseAdapter( ) ); this.addKeyListener( new MyKeyAdapter( ) );}

public void start( ) {

len = 0; }

public void paint( Graphics g ){

g.setColor( Color.red ); g.fillRect( 10, 10, len, 5 );

6

Page 7: Java Programming Lab Manual

2k8 [ ]

requestFocus( );}class MyMouseAdapter extends MouseAdapter{

public void mouseClicked( MouseEvent e ) {

len += 10; repaint( ); }}class MyKeyAdapter extends KeyAdapter{

public void keyTyped( KeyEvent e )

{ showStatus(""+e.getKeyCode()); if ( e.getKeyChar( ) == ' ' )

{ len -= 5;

repaint( ); }

}public void keyPressed( KeyEvent e )

{ showStatus(""+e.getKeyCode());

}}

}

OUTPUT:

By applet viewer-

Appletviewer takes a file name, that contains the following line

//<applet code="AppletTest.class" width=300 height=300> </applet>

as parameter

C:\ appletviewer AppletTest.java

7

Page 8: Java Programming Lab Manual

2k8 [ ]

Applet embedded inside html file

<html><applet code=”AppletTest.class” height=200 width=300></applet></html>

Save as .html file and open that html file

PROGRAM-3: (BoxDraw.java)

8

Page 9: Java Programming Lab Manual

2k8 [ ]

Write an applet that handles mouse events by implementing corresponding listener interfaces?

Source:

// <applet code="BoxDraw.class" width=600 height=600> </applet>import java.awt.*;import java.awt.event.*;import java.applet.*;public class BoxDraw extends Applet implements MouseListener, MouseMotionListener{/* declare graphics object and integers for size of rect*/ // private Graphics g; int firstX=0, firstY=0, lastX, lastY, width=0,height=0;

public void init( ){

System.out.println("init");}

public BoxDraw() { /* make the applet a listener to mouse events*/ addMouseListener(this); addMouseMotionListener(this);

System.out.println("boxdraw"); }

public void paint(Graphics g) { /* draw the rectangle with the graphics object*/

g.drawRect(firstX,firstY,width,height); }

public void mousePressed(MouseEvent evt) { firstX = evt.getX(); // initial width and height firstY = evt.getY(); } public void mouseDragged(MouseEvent evt) {

lastX=evt.getX(); width=lastX-firstX; // set the width

lastY=evt.getY(); height=lastY-firstY; // set the height repaint();

}

9

Page 10: Java Programming Lab Manual

2k8 [ ]

/* these empty methods are here because all the methods in the listener interfaces must be implemented*/ public void mouseMoved(MouseEvent evt) { } public void mouseEntered(MouseEvent evt) { } public void mouseExited(MouseEvent evt) { } public void mouseClicked(MouseEvent evt) { } public void mouseReleased(MouseEvent evt) { }}

OUTPUT:

PROGRAM-4 : (Card.java)

10

Page 11: Java Programming Lab Manual

2k8 [ ]

Write an applet that demonstrates cardlayout ?

Source:

// <applet code="Card.class" width=300 height=300> </applet>

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

public class Card extends Applet implements ActionListener{ CardLayout cl; Panel p; static String[] names =

{ "This", "is", "a", "layout", "tester" }; public void init( ) { p = new Panel( );

cl = new CardLayout( );p.setLayout( cl );for ( int i = 0; i < names.length; ++i ){ Button b = new Button( names[i] ); p.add( b, names[i] ); b.addActionListener( this );}add( p );

}

public void actionPerformed( ActionEvent evt ) { cl.next( p ); }}

OUTPUT: PROGRAM-5 : (ChoiceMu.java)-choice menu

11

Page 12: Java Programming Lab Manual

2k8 [ ]

Write an applet that demonstrates choice class and itemevent?

Source:

//<applet code="ChoiceMu.class" width=300 height=300> </applet>

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

public class ChoiceMu extends Applet implements ItemListener{ String shape = "Circle";

public void init ( ) { Choice c = new Choice( ); c.addItem( "Circle" ); c.addItem( "Square" ); c.addItem( "Oval" ); c.addItem( "Rectangle" ); add( c ); c.addItemListener( this ); }

public void itemStateChanged( ItemEvent evt ) { shape = (String) evt.getItem( ); repaint( ); }

public void paint( Graphics g ) { g.setColor( Color.blue ); if ( "Circle".equals( shape ) ) g.fillOval( 50,50,40,40 ); if ( "Oval".equals( shape ) ) g.fillOval( 50,50,40,60 ); if ( "Square".equals( shape ) ) g.fillRect( 50,50,40,40 ); if ( "Rectangle".equals( shape ) ) g.fillRect( 50,50,40,60 ); }}

OUTPUT:

PROGRAM-6 : (CkBoxTst.java)-enabling

12

Page 13: Java Programming Lab Manual

2k8 [ ]

Write an applet that demonstrates checkboxes and itemevent?

Source:

// <applet code="CkboxTst.class" width=300 height=300> </applet>

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

public class CkboxTst extends Applet implements ItemListener{ static String[] labels = { "Bread", "Milk", "Eggs", "Butter", "Flour", "Sugar" }; Checkbox[] ckbox; public void init( ) { ckbox = new Checkbox[labels.length];

for( int i = 0; i < labels.length; ++i ) { ckbox[i] = new Checkbox( labels[i] ); add( ckbox[i] ); ckbox[i].addItemListener( this ); } }

public void itemStateChanged( ItemEvent evt ) { repaint( ); } public void paint( Graphics g ) { String theList = "Buy"; for( int i = 0; i < ckbox.length; ++i ) { if ( ckbox[i].getState( ) ) theList += " " + ckbox[i].getLabel( ); } g.drawString( theList, 10,50 ); }}

OUTPUT:

PROGRAM-7 : (DialogTst.java)-enabling

13

Page 14: Java Programming Lab Manual

2k8 [ ]

Write an application program that demonstrates dialog box?

Source:

// <applet code="DialogTest.class" width=300 height=300> </applet>

import java.awt.*;import java.awt.event.*;

public class DialogTest extends Frame{ public DialogTest( ) { setTitle( "DialogTest" );

setLayout( new FlowLayout( FlowLayout.CENTER ) );add( new Label( "Would you like to see the dialog box?" ) );Button bYes = new Button( "Yes" );add( bYes );bYes.addActionListener( new YesAction( ) );Button bNo = new Button( "No" );add( bNo );bNo.addActionListener( new NoAction( ) );addWindowListener( new MyWindowAdapter( ) );

}public static void main( String args[] ){ Frame f = new DialogTest( );

f.setSize( 250, 100 );f.setLocation( 200,200 );f.setVisible( true );

}class YesAction implements ActionListener{ public void actionPerformed( ActionEvent evt )

{ AuthorDialog ad = new AuthorDialog( DialogTest.this );ad.setVisible( true );

}}class NoAction implements ActionListener{ public void actionPerformed( ActionEvent evt )

{ System.exit( 0 );}

}}

class AuthorDialog extends Dialog{ Frame myParent; public AuthorDialog( Frame parent ) { super( parent, "Brought to you by", true );

Panel p1 = new Panel( );p1.add( new Label( "Modal Dialog Box") );add( p1, "Center" );

14

Page 15: Java Programming Lab Manual

2k8 [ ]

Panel p2 = new Panel( );Button bye = new Button( "Bye" );p2.add( bye );bye.addActionListener( new ByeAction( ) );add( p2, "South" );setSize( 220, 150 );setLocation( 200, 300 );addWindowListener( new MyWindowAdapter( ) );myParent = parent;

} class ByeAction implements ActionListener

{ public void actionPerformed( ActionEvent evt ) { dispose( ); }}

}

class MyWindowAdapter extends WindowAdapter{ public void windowClosing( WindowEvent evt ) { System.exit(0); }}

OUTPUT:

PROGRAM-8 : (GridBag.java)-layout enabling

Write an applet that demonstrates Gridbag layout?

15

Page 16: Java Programming Lab Manual

2k8 [ ]

Source:

// <applet code="Gridbag.class" width=500 height=500> </applet>

import java.awt.*;

public class Gridbag extends java.applet.Applet{ void post ( String name, GridBagLayout gb, GridBagConstraints gbc ) { Button b = new Button( name ); gb.setConstraints( b, gbc ); add( b ); }

public void init( ) { GridBagLayout gb = new GridBagLayout( ); GridBagConstraints gbc = new GridBagConstraints( ); setLayout( gb ); gbc.anchor = GridBagConstraints.SOUTH; gbc.fill = GridBagConstraints.BOTH;

/* Row One - One button */ gbc.gridwidth = GridBagConstraints.REMAINDER; post( "One", gb, gbc );

/* Row Two - Two buttons */ gbc.gridwidth = GridBagConstraints.RELATIVE; post( "Two", gb, gbc );

gbc.gridwidth = GridBagConstraints.REMAINDER; post( "Three", gb, gbc );

/* Row Three - Three buttons */

gbc.weightx = 1.0; gbc.gridwidth = 1; post( "Four", gb, gbc ); gbc.gridwidth = GridBagConstraints.RELATIVE; post( "Five12345", gb, gbc ); gbc.gridwidth = GridBagConstraints.REMAINDER; post( "S", gb, gbc ); gbc.weightx = 0.0;

16

Page 17: Java Programming Lab Manual

2k8 [ ]

/* Row Four - One Three High, Three One High */ gbc.gridwidth = 1; gbc.gridheight = 3; post( "Seven", gb, gbc ); gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.gridheight = 1; post( "Eight", gb, gbc ); post( "Nine", gb, gbc ); post( "Ten", gb, gbc ); resize( getPreferredSize( ) ); }}

OUTPUT:

PROGRAM-9 : (ListTest.java)

Write an applet that demonstrates the list class and itemevents?

17

Page 18: Java Programming Lab Manual

2k8 [ ]

Source:

// <applet code="ListTest.class" width=600 height=600> </applet>

import java.awt.*;import java.awt.event.*;import java.applet.Applet;

public class ListTest extends Applet implements ItemListener{ List l; public void init( ) { l = new List( 6, false ); l.addItem ( "New York" ); l.addItem ( "London" ); l.addItem ( "Paris" ); l.addItem ( "Manila" ); l.addItem ( "Singapore" ); l.addItem ( "Montevideo" ); l.addItem ( "Sydney" ); l.addItem ( "Madras" ); l.addItem ( "Moscow" ); l.addItem ( "Vancouver" ); l.addItem ( "Lagos" ); add( l ); l.addItemListener( this ); }

public void itemStateChanged( ItemEvent evt ){ repaint( );

} public void paint( Graphics g ) { String where = l.getSelectedItem( ); if ( where == null ) where = "Nowhere"; g.drawString( where + " in the Spring", 15, 130 );}}

OUTPUT:

PROGRAM-10 : (MenuTest.java)

Write an application program that demonstrates MenuBar class?

18

Page 19: Java Programming Lab Manual

2k8 [ ]

Source:

import java.awt.*;import java.awt.event.*;

public class MenuTest extends Frame implements ActionListener{ MenuBar lunchMenuBar = new MenuBar( ); Label lunchSelection = new Label( "", Label.CENTER );

public MenuTest( ){ super("Alice's Restaurant");

Menu lunchMenu = new Menu("Lunch Menu");lunchMenu.addActionListener( this );lunchMenu.add("Hot Dog");lunchMenu.add("-");lunchMenu.add("Hamburger");lunchMenu.add("-");Menu saladMenu = new Menu("Salad");saladMenu.addActionListener( this );saladMenu.add("Caesar Salad");saladMenu.add("Greek Salad");saladMenu.add("Cobb Salad");lunchMenu.add(saladMenu);Menu sandwichMenu = new Menu("Sandwich");sandwichMenu.addActionListener( this );sandwichMenu.add("BLT");sandwichMenu.add("Turkey Club");sandwichMenu.add("Grilled Cheese");lunchMenu.add(sandwichMenu);lunchMenuBar.add(lunchMenu);setMenuBar(lunchMenuBar);add( lunchSelection );addWindowListener( new MyWindowAdapter( ) );

}

public void actionPerformed( ActionEvent evt ) { lunchSelection.setText( "Lunch is a " + evt.getActionCommand( ) );

}

public static void main(String args[]){ MenuTest Lunch = new MenuTest();

Lunch.setSize(600,600);Lunch.setVisible( true );

}

class MyWindowAdapter extends WindowAdapter { public void windowClosing( WindowEvent evt )

19

Page 20: Java Programming Lab Manual

2k8 [ ]

{ dispose( ); System.exit(0);}

}}

OUTPUT:

AWT (Abstract window tool kit)

The Abstract Window Toolkit (AWT) and Swing provide standard components to build a graphical user interface (GUI)

20

Page 21: Java Programming Lab Manual

2k8 [ ]

The GUI enables interaction between the user and the program by using the mouse, keyboard, or another input device

AWT also provides a mechanism to paint different shapes on the screen (e.g., lines, rectangles, text, etc.)

PROGRAM-11 : (HelloJava4.java)

Write an application program that demonstrate swing components?

Source:

import java.awt.*; import java.awt.event.*; import javax.swing.*;

public class HelloJava4 { public static void main( String[] args ) { JFrame frame = new JFrame( "HelloJava4" ); frame.add( new HelloComponent4("Hello, Java!") ); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); frame.setSize( 300, 300 ); frame.setVisible( true ); } } class HelloComponent4 extends JComponent implements MouseMotionListener, ActionListener, Runnable { String theMessage; int messageX = 125, messageY = 95; // Coordinates of the message

JButton theButton;

int colorIndex; // Current index into someColors. static Color[] someColors = { Color.black, Color.red, Color.green, Color.blue, Color.magenta }; boolean blinkState; public HelloComponent4( String message ) { theMessage = message; theButton = new JButton("Change Color"); setLayout( new FlowLayout( ) ); add( theButton ); theButton.addActionListener( this ); addMouseMotionListener( this ); Thread t = new Thread( this ); t.start( ); }

21

Page 22: Java Programming Lab Manual

2k8 [ ]

public void paintComponent( Graphics g ) { g.setColor(blinkState ? getBackground( ) : currentColor( )); g.drawString(theMessage, messageX, messageY); } public void mouseDragged(MouseEvent e) { messageX = e.getX( ); messageY = e.getY( ); repaint( ); } public void mouseMoved(MouseEvent e) { } public void actionPerformed( ActionEvent e ) { if ( e.getSource( ) == theButton ) changeColor( ); } synchronized private void changeColor( ) { if (++colorIndex == someColors.length) colorIndex = 0; setForeground( currentColor( ) ); repaint( ); } synchronized private Color currentColor( ) { return someColors[colorIndex]; } public void run( ) { try { while(true) { blinkState = !blinkState; // Toggle blinkState. repaint( ); // Show the change. Thread.sleep(300); } } catch (InterruptedException ie) { } } }

OUTPUT:

pROGRAM-12 : (TempConvertor.java)

Write an application program that converts the temperature to Fahrenheit-centigrade and vice versa using swing components?

22

Page 23: Java Programming Lab Manual

2k8 [ ]

Source:

import javax.swing.*;import java.awt.*;import java.awt.event.*;import javax.swing.border.*;

//panel p1 for main panel//panel p2 for temp values//panel p3 for conversion radio buttons//panel p4 for buttons

public class TempConverter extends JFrame {JPanel p1,p2,p3,p4;JLabel f,c;JTextField ct,ft;JRadioButton cb,rb;ButtonGroup bg;JButton convert,clear;boolean toc=true;public TempConverter(String title) {

super(title);p1=new JPanel();p1.setLayout(new BoxLayout(p1, BoxLayout.PAGE_AXIS));

p1.setBorder(BorderFactory.createTitledBorder("Temperature Converter"));p1.setOpaque(true);p2= new JPanel(); p3= new JPanel();p4= new JPanel();

add(p1);p1.add(Box.createRigidArea(new Dimension(0, 10)));p1.add(p2);

p1.add(Box.createRigidArea(new Dimension(0, 10)));p1.add(p3);p1.add(Box.createRigidArea(new Dimension(0, 10)));p1.add(p4);

p2.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED)); p3.setBorder(BorderFactory.createTitledBorder("Choose a Conversion"));

p4.setBorder(BorderFactory.createTitledBorder("Press a Button"));p2.setLayout(new BoxLayout(p2, BoxLayout.LINE_AXIS));p3.setLayout(new FlowLayout());p4.setLayout(new BoxLayout(p4, BoxLayout.LINE_AXIS));

f=new JLabel("Fahrenheit");c=new JLabel("Centrigade");

23

Page 24: Java Programming Lab Manual

2k8 [ ]

ft=new JTextField();ft.setColumns(10);ct= new JTextField();ct.setColumns(10);p2.add(f);p2.add(ft);p2.add(c);p2.add(ct);cb= new JRadioButton("Centigrade",true);rb= new JRadioButton("Reaumur");bg=new ButtonGroup();bg.add(cb);bg.add(rb);p3.add(cb);p3.add(rb);cb.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){toc=true;

}});rb.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){toc=false;

}});convert=new JButton("Convert");convert.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){double t;String input=ft.getText();double f=Double.parseDouble(input);if(toc)

t=5.0/9.0*(f-32);else

t=4.0/9.0*(f-32);

ct.setText(String.valueOf(t));}

});clear=new JButton("Clear");clear.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){ft.setText("");ct.setText("");

}});p4.add(Box.createRigidArea(new Dimension(20,50)));

24

Page 25: Java Programming Lab Manual

2k8 [ ]

p4.add(convert);p4.add(Box.createHorizontalStrut(200));p4.add(clear);p4.add(Box.createHorizontalGlue());setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true);setSize(getPreferredSize());

}public static void main(String []str) {

new TempConverter("Demo on JPanels");}

}

OUTPUT:

PROGRAM-13 : (Jtabp1.java)-jtabbedpane

Write an application program that demonstrates JTabbedpane?

25

Page 26: Java Programming Lab Manual

2k8 [ ]

Source:

import javax.swing.*;import java.awt.*;import java.awt.event.*;

class jtabp1 extends JFrame implements MouseListener{ //private JPopupMenu popupMenu = new LaFPopupMenu(this);

public jtabp1() { super("JTabbedPane 1"); JPanel p = new JPanel(); p.add("North", Box.createRigidArea(new Dimension(1, 5))); JLabel l = new JLabel("Appointment Schedule", JLabel.CENTER); l.setFont(new Font("Roman", Font.BOLD, 18)); p.add("Center", l); p.add("South", Box.createRigidArea(new Dimension(1, 5))); getContentPane().add("North", p); String[] tab = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; String[] tabLabel = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; Color[] color = {Color.lightGray, Color.pink, Color.white}; JTabbedPane tp = new JTabbedPane();

for (int i = 0; i < tab.length; ++i) { tp.addTab(tab[i], createPane(tabLabel[i])); tp.setBackgroundAt(i, color[i % 3]); } tp.setSelectedIndex(3); getContentPane().add("Center", tp); // popup menu for controlling L&F addMouseListener( this ); // listeners, etc. //addWindowListener(new DetectWindowClose()); setSize(300, 200); show(); } static public void main(String[] args)

26

Page 27: Java Programming Lab Manual

2k8 [ ]

{ new jtabp1(); } private JPanel createPane(String text) { JPanel p = new JPanel(); p.add("North", new JLabel("--- " + text + " ---")); return p; } // MouseListener methods public void mouseClicked(MouseEvent e){} public void mousePressed(MouseEvent e){} public void mouseEntered(MouseEvent e){} public void mouseExited(MouseEvent e){} // process LAF popup menu public void mouseReleased(MouseEvent e) { //if (e.isPopupTrigger()) { // popupMenu.show(e.getComponent(), e.getX(), e.getY()); //} }}

OUTPUT:

PROGRAM-14 : (Jtable1.java)-jtable

Write an application program that demonstrates JTable and JScrollpane?

Source:

27

Page 28: Java Programming Lab Manual

2k8 [ ]

import javax.swing.*;import java.awt.*;import java.awt.event.*;

class jtable1 extends JFrame implements MouseListener{// private JPopupMenu popupMenu = new LaFPopupMenu(this);

private String[] colHeading = { "Last Name", "First Name", "City", "State" };

private String[][] data = { {"Smith", "Mary", "Chicago", "IL"}, {"Harris", "Michael", "Los Angeles", "CA"}, {"Curran", "Peter", "Boise", "ID"}, {"Alexander", "John", "Seattle", "WA"}, {"Jones", "Annette", "Miami", "FL"}, {"Allen", "James", "New Orleans", "LA"}, {"Lincoln", "Anthony", "Detroit", "MI"}, {"Ames", "Kathy", "Boston", "MA"}, {"Arness", "Adam", "Richmond", "VA"}, {"Hall", "Andrea", "Atlanta", "GA"}, {"Higgins", "Andrew", "Saint Paul", "MN"}, {"Peters", "Lucy", "Las Vegas", "NV"}, {"Gardiner", "Allison", "Phoeniz", "AZ"} };

public jtable1() { super("JTable"); JPanel p = new JPanel(); p.add("North", Box.createRigidArea(new Dimension(1, 5))); JLabel l = new JLabel("Friends", JLabel.CENTER); l.setFont(new Font("Roman", Font.BOLD, 18)); p.add("Center", l); p.add("South", Box.createRigidArea(new Dimension(1, 5))); getContentPane().add("North", p); JTable table = new JTable(data, colHeading); JScrollPane pane = new JScrollPane( table ); getContentPane().add("Center", pane);

// popup menu for controlling L&F addMouseListener( this ); // listeners, etc. //addWindowListener(new DetectWindowClose()); setSize(400, 200);

28

Page 29: Java Programming Lab Manual

2k8 [ ]

show(); } static public void main(String[] args) { new jtable1(); } // MouseListener methods public void mouseClicked(MouseEvent e){} public void mousePressed(MouseEvent e){} public void mouseEntered(MouseEvent e){} public void mouseExited(MouseEvent e){} // process LAF popup menu public void mouseReleased(MouseEvent e) { //if (e.isPopupTrigger()) { // popupMenu.show(e.getComponent(), e.getX(), e.getY()); // } }}

OUTPUT:

PROGRAM-15 : (JLsitSimpleExample.java)-jlist

Write an application program that demonstrates simple JList?

Source:

29

Page 30: Java Programming Lab Manual

2k8 [ ]

import java.awt.*;import javax.swing.*;import javax.swing.event.*;import javax.swing.border.*; public class JListSimpleExample extends JFrame { public static void main(String[] args) { new JListSimpleExample(); } private JList sampleJList; private JTextField valueField; public JListSimpleExample() { super("Creating a Simple JList"); setDefaultCloseOperation(DISPOSE_ON_CLOSE ); Container content = getContentPane();

// Create the JList, set the number of visible rows, add a // listener, and put it in a JScrollPane. String[] entries = { "Entry 1", "Entry 2", "Entry 3", "Entry 4", "Entry 5", "Entry 6" }; sampleJList = new JList(entries); sampleJList.setVisibleRowCount(4); Font displayFont = new Font("Serif", Font.BOLD, 18); sampleJList.setFont(displayFont); sampleJList.addListSelectionListener(new ValueReporter()); JScrollPane listPane = new JScrollPane(sampleJList); JPanel listPanel = new JPanel(); listPanel.setBackground(Color.white); Border listPanelBorder = BorderFactory.createTitledBorder("Sample JList"); listPanel.setBorder(listPanelBorder); listPanel.add(listPane); content.add(listPanel, BorderLayout.CENTER); JLabel valueLabel = new JLabel("Last Selection:"); valueLabel.setFont(displayFont); valueField = new JTextField("None", 7); valueField.setFont(displayFont); JPanel valuePanel = new JPanel(); valuePanel.setBackground(Color.white); Border valuePanelBorder = BorderFactory.createTitledBorder("JList Selection"); valuePanel.setBorder(valuePanelBorder); valuePanel.add(valueLabel); valuePanel.add(valueField); content.add(valuePanel, BorderLayout.SOUTH);

30

Page 31: Java Programming Lab Manual

2k8 [ ]

pack(); setVisible(true); } private class ValueReporter implements ListSelectionListener { public void valueChanged(ListSelectionEvent event) { if (!event.getValueIsAdjusting()) valueField.setText(sampleJList.getSelectedValue().toString()); } }}

OUTPUT:

PROGRAM-16 : (Jtree1.java)-tree structure

Write an application program that demonstrates JTree?

Source:

import javax.swing.*;

31

Page 32: Java Programming Lab Manual

2k8 [ ]

import javax.swing.tree.*;import javax.swing.event.*;import java.awt.*;import java.awt.event.*;

class jtree1 extends JFrame implements TreeSelectionListener , TreeExpansionListener , MouseListener{ //private JPopupMenu popupMenu = new LaFPopupMenu(this); private JFrame frame = new JFrame("Listener Information"); private JTextArea ta = new JTextArea(6, 20);

public jtree1() { super("JTree 1");

DefaultMutableTreeNode root = new DefaultMutableTreeNode("Continents");

// ------------------------

DefaultMutableTreeNode africa = new DefaultMutableTreeNode("Africa"); root.add(africa); DefaultMutableTreeNode egypt = new DefaultMutableTreeNode("Egypt"); africa.add(egypt); DefaultMutableTreeNode nigeria = new DefaultMutableTreeNode("Nigeria"); africa.add(nigeria); DefaultMutableTreeNode southafrica = new DefaultMutableTreeNode("South Africa"); africa.add(southafrica);

// ------------------------

DefaultMutableTreeNode antarctica = new DefaultMutableTreeNode("Antarctica"); root.add(antarctica);

// ------------------------

DefaultMutableTreeNode asia = new DefaultMutableTreeNode("Asia"); root.add(asia); DefaultMutableTreeNode china

32

Page 33: Java Programming Lab Manual

2k8 [ ]

= new DefaultMutableTreeNode("China"); asia.add(china); DefaultMutableTreeNode japan = new DefaultMutableTreeNode("Japan"); asia.add(japan); DefaultMutableTreeNode southeastasia = new DefaultMutableTreeNode("South East Asia"); asia.add(southeastasia); DefaultMutableTreeNode malaysia = new DefaultMutableTreeNode("Malaysia"); southeastasia.add(malaysia); DefaultMutableTreeNode singapore = new DefaultMutableTreeNode("Singapore"); southeastasia.add(singapore);

// ------------------------

DefaultMutableTreeNode australasia = new DefaultMutableTreeNode("Australasia"); root.add(australasia); DefaultMutableTreeNode australia = new DefaultMutableTreeNode("Australia"); australasia.add(australia); DefaultMutableTreeNode newzealand = new DefaultMutableTreeNode("New Zealand"); australasia.add(newzealand);

// ------------------------

DefaultMutableTreeNode europe = new DefaultMutableTreeNode("Europe"); root.add(europe); DefaultMutableTreeNode austria = new DefaultMutableTreeNode("Austria"); europe.add(austria); DefaultMutableTreeNode balticstates = new DefaultMutableTreeNode("Baltic States"); europe.add(balticstates); DefaultMutableTreeNode estonia = new DefaultMutableTreeNode("Estonia"); balticstates.add(estonia); DefaultMutableTreeNode latvia = new DefaultMutableTreeNode("Latvia"); balticstates.add(latvia); DefaultMutableTreeNode lithuania = new DefaultMutableTreeNode("Lithuania"); balticstates.add(lithuania);

33

Page 34: Java Programming Lab Manual

2k8 [ ]

DefaultMutableTreeNode france = new DefaultMutableTreeNode("France"); europe.add(france); DefaultMutableTreeNode germany = new DefaultMutableTreeNode("Germany"); europe.add(germany); DefaultMutableTreeNode italy = new DefaultMutableTreeNode("Italy"); europe.add(italy); DefaultMutableTreeNode scandinavia = new DefaultMutableTreeNode("Scandinavia"); europe.add(scandinavia); DefaultMutableTreeNode denmark = new DefaultMutableTreeNode("Denmark"); scandinavia.add(denmark); DefaultMutableTreeNode finland = new DefaultMutableTreeNode("Finland"); scandinavia.add(finland); DefaultMutableTreeNode iceland = new DefaultMutableTreeNode("Iceland"); scandinavia.add(iceland); DefaultMutableTreeNode norway = new DefaultMutableTreeNode("Norway"); scandinavia.add(norway); DefaultMutableTreeNode sweden = new DefaultMutableTreeNode("Sweden"); scandinavia.add(sweden);

// ------------------------

DefaultMutableTreeNode northamerica = new DefaultMutableTreeNode("North America"); root.add(northamerica); DefaultMutableTreeNode canada = new DefaultMutableTreeNode("Canada"); northamerica.add(canada); DefaultMutableTreeNode caribbean = new DefaultMutableTreeNode("Caribbean"); northamerica.add(caribbean); DefaultMutableTreeNode bahamas = new DefaultMutableTreeNode("Bahamas"); caribbean.add(bahamas); DefaultMutableTreeNode puertorico = new DefaultMutableTreeNode("Puerto Rico"); caribbean.add(puertorico); DefaultMutableTreeNode jamaica = new DefaultMutableTreeNode("Jamaica");

34

Page 35: Java Programming Lab Manual

2k8 [ ]

caribbean.add(jamaica); DefaultMutableTreeNode centralamerica = new DefaultMutableTreeNode("Central America"); northamerica.add(centralamerica); DefaultMutableTreeNode costarica = new DefaultMutableTreeNode("Costa Rica"); centralamerica.add(costarica); DefaultMutableTreeNode elsalvador = new DefaultMutableTreeNode("El Salvador"); centralamerica.add(elsalvador); DefaultMutableTreeNode panama = new DefaultMutableTreeNode("Panama"); centralamerica.add(panama); DefaultMutableTreeNode mexico = new DefaultMutableTreeNode("Mexico"); northamerica.add(mexico); DefaultMutableTreeNode unitedstates = new DefaultMutableTreeNode("United States of America"); northamerica.add(unitedstates);

// ------------------------

DefaultMutableTreeNode southamerica = new DefaultMutableTreeNode("South America"); root.add(southamerica); DefaultMutableTreeNode argentina = new DefaultMutableTreeNode("Argentina"); southamerica.add(argentina); DefaultMutableTreeNode bolivia = new DefaultMutableTreeNode("Bolivia"); southamerica.add(bolivia); DefaultMutableTreeNode brazil = new DefaultMutableTreeNode("Brazil"); southamerica.add(brazil); DefaultMutableTreeNode chile = new DefaultMutableTreeNode("Chile"); southamerica.add(chile); DefaultMutableTreeNode ecuador = new DefaultMutableTreeNode("Ecuador"); southamerica.add(ecuador); DefaultMutableTreeNode venezuela = new DefaultMutableTreeNode("Venezuela"); southamerica.add(venezuela);

// ------------------------

JPanel p = new JPanel();

35

Page 36: Java Programming Lab Manual

2k8 [ ]

p.add("North", Box.createRigidArea(new Dimension(1, 5))); JLabel l = new JLabel("Countries by Continent", JLabel.CENTER); l.setFont(new Font("Roman", Font.BOLD, 18)); p.add("Center", l); p.add("South", Box.createRigidArea(new Dimension(1, 5))); getContentPane().add("North", p);

JTree tree = new JTree(root); JScrollPane pane1 = new JScrollPane(); pane1.getViewport().add(tree); getContentPane().add("Center", pane1);

JScrollPane pane2 = new JScrollPane(); pane2.getViewport().add(ta); frame.getContentPane().add("Center", pane2); ta.setEditable(false); frame.setSize(250, 250); frame.show();

// popup menu for controlling L&F addMouseListener( this );

// listeners, etc.

tree.addTreeSelectionListener(this); tree.addTreeExpansionListener(this); // addWindowListener(new DetectWindowClose()); setSize(275, 300); show(); }

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

// MouseListener methods public void mouseClicked(MouseEvent e){} public void mousePressed(MouseEvent e){} public void mouseEntered(MouseEvent e){} public void mouseExited(MouseEvent e){}

// process LAF popup menu public void mouseReleased(MouseEvent e) { //if (e.isPopupTrigger()) { // popupMenu.show(e.getComponent(), e.getX(), e.getY()); //}

36

Page 37: Java Programming Lab Manual

2k8 [ ]

}

// TreeSelectionListener

public void valueChanged(TreeSelectionEvent e) { ta.setText(""); //TreePath tp=tree.getSelectionPath(); TreePath[] treePaths = e.getPaths(); for (int j = 0; j < treePaths.length; ++j) { Object[] pathComponent = treePaths[j].getPath(); String pathName = "";

for (int i = 0; i < pathComponent.length; ++i) { pathName += "/" + pathComponent[i]+"\n"; }

if (e.isAddedPath(treePaths[j])) { // selected or deselected ta.append("S(" + treePaths[j].getPathCount() + ") " + pathName + "\n"); } else { ta.append("D(" + treePaths[j].getPathCount() + ") " + pathName + "\n"); } } }

// TreeExpansionListener

public void treeExpanded(TreeExpansionEvent e) { /* TreePath treePath = e.getPath(); Object[] pathComponent = treepath.getPath(); String pathName = ""; for (int i = 0; i < pathComponent.length; ++i) { pathName += "/" + pathComponent[i]; } ta.setText("Expanded: " + pathName);*/ }

public void treeCollapsed(TreeExpansionEvent e) { /* TreePath treePath = e.getPath(); Object[] pathComponent = treepath.getPath(); String pathName = ""; for (int i = 0; i < pathComponent.length; ++i) {

37

Page 38: Java Programming Lab Manual

2k8 [ ]

pathName += "/" + pathComponent[i]; } ta.setText("Collapsed: " + pathName);*/ }}

OUTPUT:

PROGRAM-17 : ( DynamicTree.java)

Write an application program that demonstrates dynamic tree ?

Source:

38

Page 39: Java Programming Lab Manual

2k8 [ ]

import java.awt.*;import javax.swing.*;

public class DynamicTree extends JFrame { public static void main(String[] args) { int n = 5; // Number of children to give each node if (args.length > 0) try { n = Integer.parseInt(args[0]); } catch(NumberFormatException nfe) { System.out.println("Can't parse number; using default of " + n); } new DynamicTree(n); } public DynamicTree(int n) { super("Creating a Dynamic JTree"); Container content = getContentPane(); JTree tree = new JTree(new OutlineNode(1, n)); content.add(new JScrollPane(tree), BorderLayout.CENTER); setSize(300, 475); setVisible(true); }}

OUTPUT:

Packages:A concept similar to “class libraries” in other languages .Another way of achieving

reusability in java, is to use packages.

Creating a package: Declare a package at the beginning of the file using the form

39

Page 40: Java Programming Lab Manual

2k8 [ ]

package <package-name>. Define the class that isto be put in the package and declare it public. Create a subdirectory under the directory where the main source files are stored. Store the listing as the <classname>.java file in the subdirectory created. Compile the file.This creates .class file in the directory

We can compile with creating subdirectories by javac -d <filename.java>

Java also supports package hierarchy. This is done by specifying them separated by dots(.)ex:- package firstpackage.secondpackage;

Accessing a package: import package1 [.package2] [.package3].classname; import packagename.*; ex: import firstpackage.secondpackage.MyClass;

PROGRAM-18 : (package02.java)-first create root package

Write an application program that demonstrates packages?

Source:

Package02: :--creating package00 at Combined.java.p2 directory

package Combined.Java.p2;

40

Page 41: Java Programming Lab Manual

2k8 [ ]

public class Package02{public Package02(){System.out.println("Constructing Package02 object in folder p2");}}

Compilation:

-- compile the program with javac –d package02.java

Package01:--creating package01 at Combined.java.p1 directory

package Combined.Java.p1;import Combined.Java.p2.*;public class Package01 {

Package02 p02; public Package01(){ p02=new Package02(); System.out.println("Constructing Package01 object in folder p1"); }

}//final class finalclass {}

Compilation:

-- compile the program with javac –d package01.java

Package00(main):-invoking packages

package Combined.Java;

import Combined.Java.p1.*;import Combined.Java.p2.*;

class Package00{ public static void main(String s[]){ System.out.println("Starting Package00"); System.out.println("Instantiate obj of public " + "classes in different packages"); new Package01(); new Package02(); System.out.println("Back in main of Package00"); }

41

Page 42: Java Programming Lab Manual

2k8 [ ]

}

OUTPUT:

C:\java Package00

C:\java Package00

Starting Package00Instantiate obj of public Classes in different packagesConstructing Package02 object in folder p2Constructing Package01 object in folder p1Back in main of Package00

PolyMorphism:• Polymorphism (many shapes): Behaviour can vary depending on the actual

type of an object

PROGRAM-19 : (Poly03.java)

Write an application program that demonstrates polymorphism using classes?

42

Page 43: Java Programming Lab Manual

2k8 [ ]

Source:

class A extends Object{ public void m(){ System.out.println("m in class A"); }}class B extends A{ public void m(){ System.out.println("m in class B"); }}public class Poly03{ public static void main(String[] args){ Object var = new B(); B bref=new B();//bref.m(); ((B)var).m(); ((A)var).m(); //var.m(); var = new A(); ((A)var).m(); }}

OUTPUT:

PROGRAM-20 : (Poly06.java)

Write an application program that demonstrates polymorphism using interfaces?

Source:

interface I1{ public void p();}//end interface I1//===================================//

43

Page 44: Java Programming Lab Manual

2k8 [ ]

interface I2 extends I1{ public void q();}//end interface I2//===================================//

class A extends Object{ public String toString(){ return "toString in A"; }//end toString() //---------------------------------// public String x(){ return "x in A"; }//end x() //---------------------------------//}//end class A

class B extends A implements I2{ public void p(){ System.out.println("p in B"); }//end p() //---------------------------------// public void q(){ System.out.println("q in B"); }//end q(); //---------------------------------//}//end class B

class C extends Object implements I2{ public void p(){ System.out.println("p in C"); }//end p() public void q(){ System.out.println("q in C"); }//end q(); //---------------------------------//}//end class B

public class Poly06{ public static void main( String[] args){ I1 var1 = new B(); var1.p();//OK //var1.q();//won't compile ((I2)var1).q();//OK System.out.println("");//blank line I2 var2 = new B();

44

Page 45: Java Programming Lab Manual

2k8 [ ]

var2.p();//OK var2.q();//OK //Following won't compile //String var3 = var2.x(); String var3 = ((A)var2).x();//OK System.out.println(var3); var3 = var2.toString();//OK System.out.println(var3); System.out.println("");//blank line Object var4 = new B(); //var4.p();//won't compile ((I1)var4).p();//OK System.out.println("");//blank line var2 = new C(); var2.p();//OK var2.q();//OK System.out.println("");//blank line }//end main}//end class Poly06OUTPUT:

Threads:

Sharing a single CPU between multiple tasks (or "threads") in a way designed to minimize the time required to switch tasks. This is accomplished by sharing as much as possible of the program execution environment between the different tasks so that very little state needs to be saved and restored when changing tasks.

45

Page 46: Java Programming Lab Manual

2k8 [ ]

PROGRAM-21 : (AddSync.java)

Write an application program that demonstrate Threads?

Source:

public class AddSync extends Thread { static int value = 0; public static void main(String arg[]) { for(int i=0; i<50; i++) {

46

Page 47: Java Programming Lab Manual

2k8 [ ]

AddSync as = new AddSync(); as.start(); } } public void run() { showValue(); } static synchronized void showValue() { value++; System.out.println("Value=" + value); value--; }}

OUTPUT:

PROGRAM-22 : (producer.java,consumer.java)

Write an application program that demonstrates producer-consumer problem using threads?

Source:

Producer:

47

Page 48: Java Programming Lab Manual

2k8 [ ]

import java.util.*;

public class Producer implements Runnable{ static final int MAXQUEUE = 5; private List messages = new ArrayList( );

public void run( ) { while ( true ) { putMessage( ); try { Thread.sleep( 1000 ); } catch ( InterruptedException e ) { } } }

private synchronized void putMessage( ) { while ( messages.size( ) >= MAXQUEUE ) try { wait( ); } catch( InterruptedException e ) { }

messages.add( new java.util.Date( ).toString( ) ); notify( ); }

// called by Consumer public synchronized String getMessage( ) { while ( messages.size( ) == 0 ) try { notify( ); wait( ); } catch( InterruptedException e ) { } String message = (String)messages.remove(0); notify( ); return message; } }

// compile this producer.java by javac Producer.javaConsumer:

public class Consumer implements Runnable { Producer producer;

String name;

48

Page 49: Java Programming Lab Manual

2k8 [ ]

Consumer( String NAME,Producer producer ) { this.producer = producer;

this.name = NAME; } public void run( ) { while ( true ) { String message = producer.getMessage( ); System.out.println(name + " got message: " + message);

try { Thread.sleep( 2000 ); } catch ( InterruptedException e ) { } } } public static void main(String args[]) { Producer producer = new Producer( ); new Thread( producer ).start( ); Consumer consumer = new Consumer( "Two", producer ); new Thread( consumer ).start( );

consumer = new Consumer( "One", producer ); new Thread( consumer ).start( ); } }

OUTPUT:

//Compile //and run this program

//Javac consumer.java//Java consumer

49

Page 50: Java Programming Lab Manual

2k8 [ ]

InnerClasses:

This feature lets you define a class as part of another class, just as fields and methods are defined within classes.

Java defines four types of inner classes.

50

Page 51: Java Programming Lab Manual

2k8 [ ]

A nested top-level class or interface is a static member of an enclosing top-level class or interface.

A member class is a nonstatic inner class. As a full-fledged member of its containing class, a member class can refer to the fields and methods of the containing class, even the private fields and methods. Just as you would expect for the other instance fields and methods of a class, all instances of a member class are associated with an instance of the enclosing class.

A local class is an inner class defined within a block of Java code, such as within a method or within the body of a loop. Local classes have local scope they can only be used within the block in which they are defined. Local classes can refer to the methods and variables of their enclosing classes. They are used mostly to implement adapters, which are used to handle events.

An anonymous class is a local class whose definition and use are combined into a single expression. Rather than defining the class in one statement and using it in another, both operations are combined into a single expression. Anonymous classes are intended for one-time use. Therefore, they do not contain constructors

When Java compiles a file containing a named inner class, it creates separate class files for them with names that include the nesting class as a qualifier. For example, if you define an inner class named Metric inside a top-level class named Converter, the compiler will create a class file named Converter$Metric.class for the inner class. If you wanted to access the inner class from some other class (besides Converter), you would use a qualified name: Converter. Metric.

An anonymous class bytecode files are given names like ConverterFrame$1.class.

Eg1: Inner Classes Example Program Eg2: Local Class Eg3: Anonymous Class

PROGRAM-23 : (ConverterUser.java)

Write an application program that converts meters to inches and kilograms to lbs and display to console?

Source:

class Converter { private static final double INCH_PER_METER = 39.37;

51

Page 52: Java Programming Lab Manual

2k8 [ ]

private final double LBS_PER_KG = 2.2; public static class Distance { // Nested Top-level class public double metersToInches(double meters) { return meters * INCH_PER_METER; } } // Distance class

public class Weight { // Member class public double kgsToPounds(double kg) { return kg * LBS_PER_KG; } } // Weight class} // Converter classpublic class ConverterUser { public static void main(String args[]) { Converter.Distance distance = new Converter.Distance(); Converter converter = new Converter(); Converter.Weight weight = converter.new Weight(); System.out.println( "5 m = " + distance.metersToInches(5) + " in"); System.out.println( "5 kg = " + weight.kgsToPounds(5) + " lbs"); } // main()} // ConverterUser class

OUTPUT:

PROGRAM-24 : (ConverterUser.java)

Write an application program that converts meters to inches and kilograms to lbs and display them using gui?

Source:

import javax.swing.*;

52

Page 53: Java Programming Lab Manual

2k8 [ ]

import java.awt.*;import java.awt.event.*;

public class ConverterFrame extends JFrame { private Converter converter = new Converter(); // Reference to app private JTextField inField = new JTextField(8); private JTextField outField = new JTextField(8); private JButton metersToInch; private JButton kgsToLbs;

public ConverterFrame() { metersToInch = createJButton("Meters To Inches"); kgsToLbs = createJButton("Kilos To Pounds"); getContentPane().setLayout( new FlowLayout() ); getContentPane().add(inField); getContentPane().add(outField); getContentPane().add(metersToInch); getContentPane().add(kgsToLbs); } // ConverterFram()

private JButton createJButton(String s) { // A method to create a JButton JButton jbutton = new JButton(s); class ButtonListener implements ActionListener { // Local class

public void actionPerformed(ActionEvent e) { double inValue = Double.valueOf(inField.getText()).doubleValue(); JButton button = (JButton) e.getSource(); if (button.getText().equals("Meters To Inches")) outField.setText(""+ new Converter.Distance().metersToInches(inValue)); else outField.setText(""+ converter.new Weight().kgsToPounds(inValue)); } // actionPerformed() } // ButtonListener class ActionListener listener = new ButtonListener(); // Create a listener jbutton.addActionListener(listener); // Register buttons with listener return jbutton; } // createJButton()

public static void main(String args[]) { ConverterFrame frame = new ConverterFrame(); frame.setSize(200,200); frame.setVisible(true); } // main()} // ConverterFrame class

OUTPUT:

53

Page 54: Java Programming Lab Manual

2k8 [ ]

BEANS:

What exactly is or are JavaBeans? JavaBeans (the architecture) defines a set of rules; Java beans are ordinary Java objects that play by these rules. That is, Java beans are Java objects that conform to the JavaBeans API and design patterns. By doing so, they can be recognized and manipulated within visual application builder environments, as well as by hand coding. Beans live and work in the Java runtime system, as do all Java objects. They communicate with their neighbors using events and other normal method invocations.

54

Page 55: Java Programming Lab Manual

2k8 [ ]

For examples of Java beans, we need look no further than the javax.swing packages. All the familiar components, such as JButton, JTextArea, JScrollpane, etc., are not only suitable items for beans, but are also, in fact, beans. Much of what you learned in Chapter about the Swing components has prepared you for understanding beans. Although most of the Swing components aren't very useful in isolation, in general, beans can also be large and complex application components, such as spreadsheets or document editors. Sun used to have a HotJavaBrowser bean, a complete web browser whose interface was presented as a Java bean. We'll talk more about exactly what makes a bean a bean in a moment. For now, we want to give you a better sense of how they are used.

The ultimate goal of JavaBeans was to allow components to be manipulated visually within a graphical application builder. Beans can be chosen from a palette of tools and manipulated graphically in an application builder's workspace. In this sense, beans resemble the widgets used in a traditional GUI builder: user interface components that can be assembled to make application "screens." In traditional GUI builders, the result is usually some automatically generated code that provides a skeleton on which you hang the meat of your application. GUI builders generally build GUIs, not entire applications.

In contrast, Java beans can be not only simple UI components, such as buttons and sliders, but also more complex and abstract components. It is easy to get the impression that beans are, themselves, always graphical objects (like the Swing components that we mentioned), but Java beans can implement any part of an application, including "invisible" parts that perform calculations, storage, and communications. Ideally, we would like to be able to snap together a substantial application using prefabricated beans, without ever writing a line of code. Three characteristics of the JavaBeans architecture aim to make it possible to work with application components at this level:

Design patterns

Reflection

Object serialization

-Here we are using the BEANBOX software which comes from sun.microsoft

How to open?

-Click on the run batch file which was placed in beansoftware/beanbox/

Appears like this……….

55

Page 56: Java Programming Lab Manual

2k8 [ ]

Consists of:1: tool box2: Beanbox3: properties4: Jmethod traces

-the tool box loads the jar files placed in the beansoftware/jars folder or load the jar file from file menu.

How to create A jar file? JAR (Java Archive) is a platform-independent file format that aggregates many files into one. The JAR format also supports compression, which reduces the file size, further improving the download time. In addition, the applet author can digitally sign individual entries in a JAR file to authenticate their origin. It is fully extensible.

Create jar file-C:\java>jar cf myFile.jar *.class

56

Page 57: Java Programming Lab Manual

2k8 [ ]

In this example, all the class files in the current directory are placed into the file named "myFile.jar". A manifest file entry named META-INF/MANIFEST.MF is automatically generated by the jar tool and is always the first entry in the jar file. The manifest file is the place where any meta-information about the archive is stored as NAME : VALUE pairs.

>If you have a pre-existing manifest file whose name: value pairs you want the jar

tool to include for the new jar archive, you can specify it using the -m option:

C:\Java> jar cmf myManifestFile myFile.jar *.class

Note:  A jar command that specifies cfm on the command line instead of cmf (the order of the -m and -f options are reversed), the jar command line must specify the name of the jar archive first, followed by the name of the manifest file:

C:\Java> jar cfm myFile.jar myManifestFile *.class

The manifest is in a text format inspired by RFC822 ASCII format, so it is easy to view and process manifest-file contents

Extraction of files from jar:

To extract the files from a jar file, use -x, as in:

C:\Java> jar xf myFile.jar

To extract only certain files from a jar file, supply their filenames:

C:\Java> jar xf myFile.jar foo bar

Manifest Specification:

manifest-file :          main-section newline *individual-section  main-section :            version-info newline *main-attribute  version-info :           Manifest-Version : version-number  version-number :           digit+{.digit+}*

57

Page 58: Java Programming Lab Manual

2k8 [ ]

  main-attribute :           (any legitimate main attribute) newline  individual-section :          Name : value newline *perentry-attribute  perentry-attribute :         (any legitimate perentry attribute) newline  newline :           CR LF | LF | CR (not followed by LF)   digit :            {0-9}

How to create a manifest file by user?

Manifest-Version: 1.0Created-By: 1.2.2 (Sun Microsystems Inc.)

Name: NumericField.classJava-Bean: True

Name: TextLabel.classJava-Bean: True

Name: Multiplier.classJava-Bean: True

And save it as <filename>.mf

---now place the jar files beansoftware/jars folder or load the jar file from file menu.

PROGRAM-25(A) : (NumericFiled.java,Textarea.java,Multiplier.java)

Write an application program that demonstrates user defined beans?

Source:

Numericfield.java

import javax.swing.JTextField;

58

Page 59: Java Programming Lab Manual

2k8 [ ]

import java.awt.event.*;

import java.beans.*;

public class NumericField extends JTextField implements ActionListener {

private double value;

public NumericField( ) {

super(6);

addActionListener( this );

}public void actionPerformed( ActionEvent e ) {

try {setValue( Double.parseDouble( getText( ) ) );

} catch ( NumberFormatException ex ) {

select(0, getText().length( ));}

}

public double getValue( ) {

return value;}public void setValue( double newValue ) {

double oldValue = value;

value = newValue;

setText( "" + newValue );

firePropertyChange( "value", oldValue, newValue );}

}

TextLabel.java

import javax.swing.JLabel;

public class TextLabel extends JLabel {

59

Page 60: Java Programming Lab Manual

2k8 [ ]

public void setText( String s ) {

super.setText(s);

if ( getParent( ) != null ) {

invalidate( );

getParent().validate( );}

}}

Multiplier.java

import java.beans.*;

public class Multiplier implements java.io.Serializable {

private double a, b, c;

synchronized public void setA( double val ) {

a = val;

multiply( );

}synchronized public double getA( ) {

return a;}synchronized public void setB( double val ) {

b = val;multiply( );}synchronized public double getB( ) {return b;}

synchronized public double getC( ) {return c;

}

private void multiply( ) {double oldC = c;

c = a * b;

60

Page 61: Java Programming Lab Manual

2k8 [ ]

propChanges.firePropertyChange("c", new Double(oldC), new Double(c));}private PropertyChangeSupport propChanges = new PropertyChangeSupport(this);public void addPropertyChangeListener(PropertyChangeListener listener) {

propChanges.addPropertyChangeListener(listener);}public void removePropertyChangeListener(PropertyChangeListener listener) {

propChanges.removePropertyChangeListener(listener);}

}

OUTPUT: Compile: c:\java> javac *.class

Create jar file for classes: C:\java>jar cf myFile.jar *.class

Orusing manifest file

myManifestFile.mf

Manifest-Version: 1.0Created-By: 1.2.2 (Sun Microsystems Inc.)

Name: NumericField.classJava-Bean: True

Name: TextLabel.classJava-Bean: True

Name: Multiplier.classJava-Bean: True

C:\java> jar cfm myFile.jar myManifestFile *.class

-now place the myFile.jar in the beansoftware/jars folder or load the jar file from file menu.

61

Page 62: Java Programming Lab Manual

2k8 [ ]

Working:

Here we are dra the numeric fields named by placing TextLabels As val1 and val2, resultAnd a multiplier is placed between these fields. We want that the values in numeric fields’ val1, val2 is multiplied and displayed in result numericfiled using multiplier.

In the edit menu we have to bind properties values to a,b and the value of c is binded to the result And the appropriate roperties displayed in the properties box………

PROGRAM-25(B) : (MyNumericFiled.java,MyTextarea.java,MyMultiplier.java),and their info’s

Write an application program that demonstrates user defined beans which extends simplebeaninfo?

Source:

62

Page 63: Java Programming Lab Manual

2k8 [ ]

MyField.java

import javax.swing.JTextField;

import java.awt.event.*;

import java.beans.*;

public class MyField extends JTextField implements ActionListener {

private double value;

public MyField( ) {

super(6);

addActionListener( this );

}

public void actionPerformed( ActionEvent e ) {

try {

setValue( Double.parseDouble( getText( ) ) );

} catch ( NumberFormatException ex ) {

select(0, getText().length( ));

}

}

public double getValue( ) {

return value;

}

public void setValue( double newValue ) {

double oldValue = value;

value = newValue;

setText( "" + newValue );

63

Page 64: Java Programming Lab Manual

2k8 [ ]

firePropertyChange( "value", oldValue, newValue );

}

}

MyFieldBeanInfo.java

import java.beans.*;

public class MyFieldBeanInfo extends SimpleBeanInfo {

public PropertyDescriptor[] getPropertyDescriptors( ) {

try {

PropertyDescriptor pd1 = new

PropertyDescriptor("value", MyField.class);

pd1.setBound(true);

return new PropertyDescriptor [] { pd1 };

}

catch (IntrospectionException e) {

return null;

}

}

}

MYLABEL.JAVA

import javax.swing.JLabel;

public class MyLabel extends JLabel {

public void setText( String s ) {

super.setText(s);

64

Page 65: Java Programming Lab Manual

2k8 [ ]

if ( getParent( ) != null ) {

invalidate( );

getParent().validate( );

}

}

}

MYLABELBEANINFO.JAVA

import java.beans.*;public class MyLabelBeanInfo extends SimpleBeanInfo {

public PropertyDescriptor[] getPropertyDescriptors( ) {try {

PropertyDescriptor pd1 = new PropertyDescriptor("text", MyLabel.class);

pd1.setBound(true);

return new PropertyDescriptor [] { pd1 };}catch (IntrospectionException e) {

return null;}

}}

MYMULTIPLIER.JAVA

import java.beans.*;

public class MyMultiplier implements java.io.Serializable {

private double a, b, c;

synchronized public void setA( double val ) {

a = val;

multiply( );

65

Page 66: Java Programming Lab Manual

2k8 [ ]

}

synchronized public double getA( ) {

return a;

}

synchronized public void setB( double val ) {

b = val;

multiply( );

}

synchronized public double getB( ) {

return b;

}

synchronized public double getC( ) {

return c;

}

private void multiply( ) {

double oldC = c;

c = a * b;

propChanges.firePropertyChange("c", new Double(oldC), new Double(c));

}

private PropertyChangeSupport propChanges = new PropertyChangeSupport(this);

public void addPropertyChangeListener(PropertyChangeListener listener) {

propChanges.addPropertyChangeListener(listener);

}

public void removePropertyChangeListener(PropertyChangeListener listener) {

66

Page 67: Java Programming Lab Manual

2k8 [ ]

propChanges.removePropertyChangeListener(listener);

}

}

MYMULTIPLIERBEANINFO.JAVA

import java.beans.*;

public class MyMultiplierBeanInfo extends SimpleBeanInfo {

public PropertyDescriptor[] getPropertyDescriptors( ) {

try {

PropertyDescriptor pd1 = new

PropertyDescriptor("a", MyMultiplier.class);

PropertyDescriptor pd2 = new

PropertyDescriptor("b", MyMultiplier.class);

PropertyDescriptor pd3 = new

PropertyDescriptor("c", MyMultiplier.class);

pd1.setBound(true);

pd2.setBound(true);

pd3.setBound(true);

return new PropertyDescriptor [] { pd1,pd2,pd3 };

}

catch (IntrospectionException e) {

return null;

}

}

67

Page 68: Java Programming Lab Manual

2k8 [ ]

}

OUTPUT: Compile: c:\java> javac *.class

Create jar file for classes: C:\java>jar cf myFile.jar *.class

Orusing manifest file

myManifestFile.mf

Manifest-Version: 1.0Created-By: 1.2.2 (Sun Microsystems Inc.)

C:\java> jar cfm myFile.jar myManifestFile *.class

Manifest-Version: 1.0Created-By: 1.2.2 (Sun Microsystems Inc.)

Name: MyField.classJava-Bean: True

Name: MyLabel.classJava-Bean: True

Name: MyMultiplier.classJava-Bean: True

-now place the myFile.jar in the beansoftware/jars folder or load the jar file from file menu.

68

Page 69: Java Programming Lab Manual

2k8 [ ]

Working:

In this bean program we are implementing the beans which extends with simplebeaninfo class.It results that in the previous illustrative example we can observe that we have the properties of beans that are unnecessary and note that here we are observing with our defined methods only…

And the remaining continue from previous program.

69

Page 70: Java Programming Lab Manual

2k8 [ ]

REMOTE METHOD INVOCATION (RMI) TOOLS

These tools help to create apps that interact over the Web or other network.

Tool Name Brief Description

rmic Generate stubs and skeletons for remote objects.

rmiregistry Remote object registry service.

rmid RMI activation system daemon.

serialver Return class serialVersionUID.

The most fundamental means of communication in Java is method invocation. Mechanisms such as the Java event model are built on simple method invocations between objects in the same virtual machine. Therefore, when we want to communicate between virtual machines on different hosts, it's natural to want a mechanism with similar capabilities and semantics. Java's RMI mechanism does just that. It lets us get a reference to an object on a remote host and use it almost as if it were in our own virtual machine. RMI lets us invoke methods on remote objects, passing real Java objects as arguments and getting real Java objects as returned values.

Steps: Compile the java files and also rmi-implementation file must. Next we can add the remote class by compiling the implementing class file

rmic <rmi-implementationfile>(class) - create a stub.class file. Then start the rmi-registry service by command start rmiregistry A new window opened indicates registry service started.

---Now run sever file first and don’t close.---And then run client file with sufficient port address along with arguments..

PROGRAM-26 : (rmi)

70

Page 71: Java Programming Lab Manual

2k8 [ ]

Write an application program that demonstrates Remote method invocation?

Source:

Addserver.java

import java.net.*;import java.rmi.*;

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

try {AddServerImpl addServerImpl = new AddServerImpl();Naming.rebind("AddServer", addServerImpl);

}catch(Exception e) {

System.out.println("Exception: " + e);}

}}

AddServerIntf.java

import java.rmi.*;public interface AddServerIntf extends Remote {

//public static final double pi=3.1456;double add(double d1, double d2) throws RemoteException;double mul(double d1, double d2) throws RemoteException;

public double div(double d1, double d2) throws RemoteException ;public double sub(double d1, double d2) throws RemoteException ;}

AddServerImpl.java

import java.rmi.*;import java.rmi.server.*;

public class AddServerImpl extends UnicastRemoteObjectimplements AddServerIntf {

public AddServerImpl() throws RemoteException {}public double add(double d1, double d2) throws RemoteException {

return d1 + d2;}public double mul(double d1, double d2) throws RemoteException {

return d1 * d2;}

71

Page 72: Java Programming Lab Manual

2k8 [ ]

public double div(double d1, double d2) throws RemoteException {return d1/d2;

}public double sub(double d1, double d2) throws RemoteException {

return d1-d2;}

}

AddClient.java

import java.rmi.*;

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

try {String addServerURL = "rmi://" + args[0] + "/AddServer";AddServerIntf addServerIntf =(AddServerIntf)Naming.lookup(addServerURL);System.out.println("The first number is: " + args[1]);double d1 = Double.valueOf(args[1]).doubleValue();System.out.println("The second number is: " + args[2]);double d2 = Double.valueOf(args[2]).doubleValue();System.out.println("The sum is: " + addServerIntf.add(d1, d2));

}catch(Exception e) {

System.out.println("Exception: " + e);}

}}

OUTPUT:

C:\java>javac AddServer.javaC:\java>javac AddServerIntf.javaC:\java>javac AddServerImpl.javaC:\java>javac AddClient.java

Now create a stub file using AddServerImpl.class

C:\java>rmic AddServerImpl

Now Start the registry service

C:\java>start rmiregistry

72

Page 73: Java Programming Lab Manual

2k8 [ ]

Now run server first and client next

C:\java>java AddServer

C:\java>java AddClient localhost 30 20

73

Page 74: Java Programming Lab Manual

2k8 [ ]

Servlets:What is a Servlet?

• Servlets are Java programs that can be run dynamically from a Web Server

• Servlets are a server-side technology

• A servlet is an intermediating layer between an HTTP request of a client and the Web server

What do Servlets do?

• Read data sent by the user (e.g., form data)

• Look up other information about request in the HTTP request (e.g., headers, cookies, etc.)

• Generate the results (may do this by talking to a database, file system, etc.)

• Format the results in a document (e.g., make it into HTML

• Set the appropriate HTTP response parameters (e.g., cookies, content-type, etc.)

• Send the document to the user

Why use a Servlet?

• Servlets are used to create dynamic pages. Why?

– Page is based on data submitted by the user. Example Scenario:

– Page is derived from data that changes often. Example Scenario:

– Page uses information from server-side sources. Example Scenario:

74

Page 75: Java Programming Lab Manual

2k8 [ ]

• Supporting ServletsThe Web server must support servlets (since it must run the servlets):

– Apache Tomcat

– Sun’s JavaServer Web Development Kit (JSWDK)

– Allaire Jrun – an engine that can be added to IIS, PWS, old Apache Web servers etc…

– Sun’s Java Web Server

Compiling

• In order to compile a servlet, you may need to add to your CLASSPATH definition the following:

setenv CLASSPATH ${CLASSPATH}:

/usr/local/java/apache/jakarta-tomcat/lib/ant.jar:

/usr/local/java/apache/jakarta-tomcat/lib/jasper.jar:

/usr/local/java/apache/jakarta-tomcat/lib/jaxp.jar:

/usr/local/java/apache/jakarta-tomcat/lib/parser.jar:

/usr/local/java/apache/jakarta-tomcat/lib/servlet.jar:

/usr/local/java/apache/jakarta-tomcat/ lib/webserver.jar

Servlet Package

• Need to import javax.servlet.*;

• The Servlet interface defines methods that manage servlets and their communication with clients

• When a connection is formed, the servlet receives two objects that implement:

– ServletRequest

– ServletResponse

Here we are using apache tomcat 6.0 All html file must be in C:\Program Files\Apache Software Foundation\Tomcat 6.0\

webapps\ROOT directory to request

75

Page 76: Java Programming Lab Manual

2k8 [ ]

Note: place servlet package jar file at C:\Program Files\Apache Software Foundation\Tomcat 6.0\lib

How to place a request to the server?

Steps: First create a directory at

C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\ROOT\WEB-INFName as classes.

Compile the source file you want and copy the class file and place it in C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\ROOT\WEB-

INF\classes

And then edit the web.xml file (don’t delete any matter in it just append your servlet tags as mentioned below and save it.

<servlet>

<servlet-name> firstservlet</servlet-name>

<servlet-class>HelloServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>firstservlet</servlet-name>

<url-pattern>/hello</url-pattern>

</servlet-mapping>

76

Page 77: Java Programming Lab Manual

2k8 [ ]

Now its time to place the request

Let us open Internet explorer and verify tomcat webserver is running or not..

If not start the tomcat webserver at the administrative options/servces and start it.

Now verify tomcat is running by placing request at the address bar as

http://localhost:8080 press enter

then tomcat default website is opened then your request is success..

from the above web.xml document by placing the request as hello which is for accessing HelloSevlet.class placed in webserver

(C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\ROOT\WEB-INF\classes)

request: http://localhost:8080/hello press enter

If we did not modify the web.xml document then it gives error service

There is another way to fulfill your request that is

Remove the comments for invoker servlet and servlet-mapping at

C:\Program Files\Apache Software Foundation\Tomcat 6.0\conf

Or

create the invoker servlet by editing

Then restart the tomcat-service.

77

Page 78: Java Programming Lab Manual

2k8 [ ]

PROGRAM-27 : (HelloServlet.java)

Write a servlet program that demonstrate simple servlet ?

Source:

import javax.servlet.*;import java.io.*;

public class HelloServlet implements Servlet{

private ServletConfig sConfig;

public void init(ServletConfig sc){sConfig=sc;

}

public void service(ServletRequest req, ServletResponse res)throws IOException{PrintWriter pw = res.getWriter();res.setContentType("text/html");pw.println("<html><body bgcolor=red>Hello,World</body></html>");

}public void destroy(){}public ServletConfig getServletConfig(){

return sConfig;}public String getServletInfo(){

return "A Simple Servlet";}

}

OUTPUT:

C:\java>javac HelloServlet.java

Palce the class file at C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\ROOT\WEB-INF\classes

And edit the xml document as

78

Page 79: Java Programming Lab Manual

2k8 [ ]

<servlet><servlet-name> firstservlet</servlet-name><servlet-class>HelloServlet</servlet-class>

</servlet>

<servlet-mapping><servlet-name>firstservlet</servlet-name><url-pattern>/Show</url-pattern>

</servlet-mapping>

Request: http://localhost:8080/show

79

Page 80: Java Programming Lab Manual

2k8 [ ]

PROGRAM-28 : (FormData.html)

Write a html program that demonstrates to accept or request the servlets?

Source:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML>

<HEAD><TITLE>A Sample Form Using GET</TITLE></HEAD><BODY BGCOLOR="#FDF5E6">

<H2 ALIGN="CENTER">A Sample Form Using GET</H2><FORM ACTION="/servlet/ShowParameters" method="post">

First Parameter: <INPUT TYPE="TEXT" NAME="param1"><BR>

Second Parameter: <INPUT TYPE="TEXT" NAME="param2"><BR>

Third Parameter: <INPUT TYPE="TEXT" NAME="param3"><BR>

<CENTER><INPUT TYPE="SUBMIT"></CENTER></FORM>

</BODY></HTML>

OUTPUT:

80

Page 81: Java Programming Lab Manual

2k8 [ ]

PROGRAM-29 : (ShowParameter.java)

Write a servlet program that demonstrates the html file to request to showparameters of the servlet?

Source:

import java.io.*;import javax.servlet.*;import javax.servlet.http.*;import java.util.*;

public class ShowParameters extends HttpServlet {public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {

response.setContentType("text/html");PrintWriter out = response.getWriter();String docType =

"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +

"Transitional//EN\">\n";String title = "Reading All Request Parameters";out.println(docType +

"<HTML>\n" +"<HEAD><TITLE>"+title +

"</TITLE></HEAD>\n"+"<BODY BGCOLOR=\"#FDF5E6\">\n"

+"<H1 ALIGN=CENTER>" + title +

"</H1>\n" +"<TABLE BORDER=1

ALIGN=CENTER>\n" +"<TR BGCOLOR=\"#FFAD00\">\n" +"<TH>Parameter Name<TH>Parameter

Value(s)");Enumeration paramNames = request.getParameterNames();while(paramNames.hasMoreElements()) {

String paramName = (String)paramNames.nextElement();out.print("<TR><TD>" + paramName + "\n<TD>");String[] paramValues =request.getParameterValues(paramName);if (paramValues.length == 1) {

String paramValue = paramValues[0];if (paramValue.length() == 0)

out.println("<I>No Value</I>");else

out.println(paramValue);

81

Page 82: Java Programming Lab Manual

2k8 [ ]

} else {out.println("<UL>");for(int i=0; i<paramValues.length; i++) {out.println("<LI>" + paramValues[i]);}out.println("</UL>");

}}out.println("</TABLE>\n</BODY></HTML>");

}public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {

doGet(request, response);}

}

OUTPUT:

82

Page 83: Java Programming Lab Manual

2k8 [ ]

PROGRAM-30 : (ShowRequestHeaders.java)

Write a servlet program that demonstrates the html file to show headers of servlet?

Source:

import java.io.*;import java.util.Enumeration;import javax.servlet.*;import javax.servlet.http.*;

public class ShowRequestHeaders extends HttpServlet {public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {

PrintWriter out=response.getWriter();String title="Request Headers";out.println

("<HTML>\n" +"<HEAD><TITLE>"+title+"</TITLE></HEAD>\n"+"<BODY BGCOLOR=\"#FDF5E6\">\n" +"<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" +"<B>Request Method: </B>" +request.getMethod() + "<BR>\n" +"<B>Request URI: </B>" +request.getRequestURI() + "<BR>\n" +"<B>Request Protocol: </B>" +request.getProtocol() + "<BR><BR>\n" +"<TABLE BORDER=1 ALIGN=\"CENTER\">\n" +"<TR BGCOLOR=\"#FFAD00\">\n" +"<TH>Header Name<TH>Header Value"

);Enumeration headerNames = request.getHeaderNames();while(headerNames.hasMoreElements()) {

String headerName = (String)headerNames.nextElement();out.println("<TR><TD>" + headerName);out.println(" <TD>"+request.getHeader(headerName));

}out.println("</TABLE>\n</BODY></HTML>");

}/** Since this servlet is for debugging, have it* handle GET and POST identically.*/public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {

doGet(request, response);}}

83

Page 84: Java Programming Lab Manual

2k8 [ ]

OUTPUT:

84

Page 85: Java Programming Lab Manual

2k8 [ ]

PROGRAM-31 : (RequestParameters.java)

Write a servlet program that demonstrates the html file to request the parameters of a servlet?

Source:

import java.io.*;import java.util.*;import javax.servlet.*;import javax.servlet.http.*;

public class RequestParamExample extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

String fn,ln; response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>Request Parameters Example</title>"); out.println("</head>"); out.println("<body>"); out.println("<h3>Request Parameters Example</h3>"); out.println("Parameters in this request:<br>");

fn=request.getParameter("firstname");ln=request.getParameter("lastname");if (fn != null || ln != null) {

out.println("First Name:"); out.println(" = " + fn + "<br>"); out.println("Last Name:"); out.println(" = " + ln); } else { out.println("No Parameters, Please enter some");

} Cookie cookie = null;

Cookie[] cookies=request.getCookies(); if(cookies != null){

for(int i=0; i<cookies.length; i++) { if (cookies[i].getName().equals("NoOfVisits")) cookie=cookies[i]; }

} if(cookie==null){

85

Page 86: Java Programming Lab Manual

2k8 [ ]

cookie=new Cookie("NoOfVisits",new Integer(1).toString());cookie.setMaxAge(3000);response.addCookie(cookie);

}else{int n=Integer.parseInt(cookie.getValue());out.println("<P>");out.println("You have visited this page " + n + " times");n++;cookie.setValue(new Integer(n).toString());response.addCookie(cookie);

} out.println("<P>"); out.print("<form action=\""); out.print("RequestParamExample\" "); out.println("method=GET>"); out.println("First Name:"); out.println("<input type=text size=20 name=firstname>"); out.println("<br>"); out.println("Last Name:"); out.println("<input type=text size=20 name=lastname>"); out.println("<br>"); out.println("<input type=submit>"); out.println("</form>"); out.println("</body>"); out.println("</html>"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doGet(request, response); }}

OUTPUT:

86

Page 87: Java Programming Lab Manual

2k8 [ ]

JDBC• JDBC is used for accessing databases from Java applications• Information is transferred from relations to objects and vice-versa

– databases optimized for searching/indexing– objects optimized for engineering/flexibility

Working With Oracle Add to your .cshrc the following:

if ($HOST == sol4) then setenv ORACLE_HOME /opt/oracle

else setenv ORACLE_HOME /usr/local/oracle9i

endif setenv PATH $ORACLE_HOME/bin:$PATHsetenv ORACLE_SID stud

Seven Steps

• Load the driver• Define the Connection URL• Establish the Connection• Create a Statement object• Execute a query• Process the result• Close the connection

87

Page 88: Java Programming Lab Manual

2k8 [ ]

Using Oracle

• If a student whose login is Snoopy wants to work directly with Oracle:sqlplus snoopy/[email protected]

• Note: we use the login for a password! (Don’t change your password)

Or create a DNS (domain name service) connection

How to create a DNS service? Open control panel/administrative tools/Data sources(ODBC) Create USER DSN-ADD user DSN with Sufficient account in oracle along with

password The default account for oracle is username:scott and password: tiger then test connection successful or not if successful then click ok return Compile and the programs of java to make necessary methods to access the database

and run it.

• In order to connect to the Oracle database from java, import the following packages:

– java.sql.*; (usually enough)– javax.sql.* ; (for advanced features, such as scrollable result

sets)

NOTE:

1. Verify whether the path existence to oracle first because it causes our java programs to unexpected results.

2. DriverManager.getConnection ("jdbc:odbc:harsha", "scott", "tiger");

// jdbc:odbc:<dns name>”,”<username-oracle>”,”<password>”

88

Page 89: Java Programming Lab Manual

2k8 [ ]

JDBC technology-based drivers generally fit into one of four categories:

1. JDBC-ODBC bridge plus ODBC driver2. Native-API partly-Java driver3. JDBC-Net pure Java driver4. Native-protocol pure Java driver

-we have to give classpath to existing oracle class driver which were installed in the pc.

Classpath:

C:\oracle\ora92\jdbc\lib;

- Here we notice that our class definitions are placed in the classes12.jar

89

Page 90: Java Programming Lab Manual

2k8 [ ]

PROGRAM-32 : (dboperations.java)

Write an application program that access the database using jtabbedpane ?

Source:

//oracle driver (type 2 hybrid java driver)import java.sql.*;import oracle.jdbc.driver.*;import javax.swing.*;import java.awt.*;import java.awt.event.*;

public class dbOperations extends JFrame{Connection conn;Statement stmt;ResultSet rset;

JTabbedPane dbJTP;JPanel browsePanel,insertPanel,deletePanel;dbOperations(String title){

super(title);dbInit();dbJTP=new JTabbedPane();add(dbJTP);browsePanel=new BrowsePanel();insertPanel=new InsertPanel();deletePanel=new DeletePanel();dbJTP.addTab("Browse",browsePanel);dbJTP.addTab("Insert",insertPanel);dbJTP.addTab("Delete",deletePanel);setVisible(true);setSize(200,200);setDefaultCloseOperation(EXIT_ON_CLOSE);

}public void dbInit() {

try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

}catch (ClassNotFoundException ex){System.out.println(ex.getMessage());

}try{

conn = DriverManager.getConnection ("jdbc:odbc:empdata", "scott", "tiger"); stmt = conn.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

90

Page 91: Java Programming Lab Manual

2k8 [ ]

rset = stmt.executeQuery("select * from Dept");}catch(SQLException e){

System.out.println(e);}

}

public static void main (String args []) throws SQLException{new dbOperations("Database Operations");

}

public class BrowsePanel extends JPanel{JTextField dname,dno,dloc;JButton next;BrowsePanel(){

dname=new JTextField();dno=new JTextField();dloc=new JTextField();next=new JButton("Next");setLayout(new GridLayout(4,2));add(new JLabel("Deptno"));add(dno);add(new JLabel("Dept Name"));add(dname);add(new JLabel("Location"));add(dloc);add(Box.createHorizontalGlue());add(next);try{

rset.next();dno.setText(rset.getString(1));dname.setText(rset.getString(2));dloc.setText(rset.getString(3));

}catch(SQLException e){}next.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent ae) {try{

if(rset.isLast()){rset.absolute(1);

}

elserset.next();

dno.setText(rset.getString(1));dname.setText(rset.getString(2));dloc.setText(rset.getString(3));

}catch(SQLException e){}

91

Page 92: Java Programming Lab Manual

2k8 [ ]

}});

}

}public class InsertPanel extends JPanel{

JTextField dname,dno,dloc;JButton insert;InsertPanel(){

dname=new JTextField();dno=new JTextField();dloc=new JTextField();insert=new JButton("Insert");setLayout(new GridLayout(4,2));add(new JLabel("Deptno"));add(dno);add(new JLabel("Dept Name"));add(dname);add(new JLabel("Location"));add(dloc);add(Box.createHorizontalGlue());add(insert);insert.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent ae) {try{

/*System.out.println("insert into dept values (" +dno.getText()+","+dname.getText()+","+dloc.getText()+")");

stmt.executeUpdate("insert into dept values (" +dno.getText()+","+dname.getText()+","+dloc.getText()+")");

*/stmt.executeUpdate("insert into dept values (50,'Marketing','Sydney')");

conn.commit();System.out.println(""+rset);

}catch(SQLException e){System.out.println(e.getMessage());}

}});

}

}public class DeletePanel extends JPanel{

JTextField dno;JButton delete;Box b;DeletePanel(){

b=Box.createVerticalBox();

92

Page 93: Java Programming Lab Manual

2k8 [ ]

add(b);dno=new JTextField();delete = new JButton("Delete");b.add(Box.createVerticalGlue());b.add(new JLabel("Enter Dept No"));b.add(dno);b.add(Box.createVerticalGlue());b.add(delete);

}}

}

OUTPUT:

PROGRAM-33 : (dbOracleType4.java)

93

Page 94: Java Programming Lab Manual

2k8 [ ]

Write an application program that access the database operations using type 4 driver?

Source:

//oracle driver (type 4 pure java driver)import java.sql.*;import oracle.jdbc.driver.*;

class dbOracleType4 { public static void main (String args []) throws SQLException { //DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver()); try{

Class.forName("oracle.jdbc.driver.OracleDriver"); }catch (ClassNotFoundException ex){

System.out.println(ex.getMessage()); }

Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:sivaram", "scott", "tiger"); // @machineName:port:SID, userid, password

Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery("select * from emp"); while (rset.next()) System.out.println (rset.getString(1)+ " "+ rset.getString(2)+ " "+rset.getString(3)); // Print col 1 stmt.close(); }}OUTPUT:

PROGRAM-34 : (dbOracleType2.java)

Write an application program that access the database operations with type 2 driver?

94

Page 95: Java Programming Lab Manual

2k8 [ ]

Source:

//oracle driver (type 2 hybrid java driver)import java.sql.*;import oracle.jdbc.driver.*;

class dbOracleType2 { public static void main (String args []) throws SQLException { //DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver()); try{

Class.forName("oracle.jdbc.driver.OracleDriver"); }catch (ClassNotFoundException ex){

System.out.println(ex.getMessage()); }

Connection conn = DriverManager.getConnection ("jdbc:oracle:oci:@sivaram", "scott", "tiger"); // @machineName:port:SID, userid, password

Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery("select * from emp"); while (rset.next()) System.out.println (rset.getString(1)+ " "+ rset.getString(2)+ " "+rset.getString(3)); // Print col 1 stmt.close();

conn.close(); }}OUTPUT:

PROGRAM-33 : (JdbcExample.java)

Write a program that demonstrate the database operations on java with type 1 driver?

95

Page 96: Java Programming Lab Manual

2k8 [ ]

Source:

import java.sql.*;import javax.swing.*;import java.awt.event.*;import java.io.*;import java.awt.*;

public class JdbcExample extends JFrame implements ActionListener {

JButton next, prev,first,last,insert,update,delete;JTextField dno,dname,loc;JPanel deptPanel,navPanel;Connection con=null;ResultSet rs=null;Statement stmt;PreparedStatement pstmt;

JdbcExample(){

super("JDBC Example");setGUI();getData();if(rs!=null)System.out.println("OK got Connection to database...");fillDetail(0);setDefaultCloseOperation(DISPOSE_ON_CLOSE);pack();show();

}

public void setGUI(){

navPanel=new JPanel();deptPanel=new JPanel();

deptPanel.setLayout(new GridLayout(0,2,15,15));

deptPanel.add(new JLabel("DNO:"));deptPanel.add(dno=new JTextField());

deptPanel.add(new JLabel("DName:"));deptPanel.add(dname=new JTextField());deptPanel.add(new JLabel("LOCATION:"));deptPanel.add(loc=new JTextField());

dno.setEditable(false);dname.setEditable(false);

96

Page 97: Java Programming Lab Manual

2k8 [ ]

loc.setEditable(false);

navPanel.add(first=new JButton("|<"));navPanel.add(prev=new JButton("<<"));navPanel.add(next=new JButton(">>"));navPanel.add(last=new JButton(">|"));navPanel.add(insert=new JButton("Insert"));navPanel.add(delete=new JButton("Delete"));

add(BorderLayout.CENTER,deptPanel);

add(BorderLayout.SOUTH,navPanel);

first.addActionListener(this);next.addActionListener(this);prev.addActionListener(this);last.addActionListener(this);insert.addActionListener(this);delete.addActionListener(this);

}

public void actionPerformed(ActionEvent ae){String qry,cmd=ae.getActionCommand();int j=0;if(cmd.equals(">>"))

fillDetail(0);

else if(cmd.equals("<<"))

fillDetail(1);

else if(cmd.equals(">|"))

fillDetail(3);

else if(cmd.equals("|<"))

fillDetail(2);else if(cmd.equals("Insert")){ qry="INSERT INTO DEPT VALUES(?,?,?)";

try{

pstmt=con.prepareStatement(qry,ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);

int departmentno=Integer.parseInt(JOptionPane.showInputDialog("Enter DNO"));

97

Page 98: Java Programming Lab Manual

2k8 [ ]

String departmentname=JOptionPane.showInputDialog("Enter DNAME");

String departmentloc=JOptionPane.showInputDialog("Enter DLOC");

pstmt.setInt(1,departmentno);pstmt.setString(2,departmentname);pstmt.setString(3,departmentloc);j=pstmt.executeUpdate();/* rs.close();rs=stmt.executeQuery("select * from dept");rs.last();dno.setText(rs.getString(1));dname.setText(rs.getString(2));loc.setText(rs.getString(3));*/

}

catch(Exception e){

System.out.println("Exception in insert::"+e.getMessage());}System.out.println(j);

}else if(cmd.equals("Delete")){

qry="DELETE FROM DEPT WHERE DEPTNO=?";try{

pstmt=con.prepareStatement(qry);int

departmentno=Integer.parseInt(JOptionPane.showInputDialog("Enter DNO"));pstmt.setInt(1,departmentno);j=pstmt.executeUpdate();

}catch(SQLException e){}System.out.println(j);

}

System.out.println("action event occured..."+ cmd);}

public void getData(){

//Connection con = null;//ResultSet rs=null;int rowNumber;

98

Page 99: Java Programming Lab Manual

2k8 [ ]

String query,empname,empno; try { Class.forName("jdbc.odbc.OracleDriver"); con = DriverManager.getConnection("jdbc:odbc:empdata", "scott", "tiger"); if (!con.isClosed()) System.out.println("Successfully connected to Oracle Server...");

stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);

//ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLEquery="select * from dept";rs=stmt.executeQuery(query);System.out.println("Returning result set..");

} catch(Exception e) { System.err.println("Exception: " + e.getMessage()); } }

public void fillDetail(int i){

try{if(rs==null) {

System.out.println("rs is null");System.exit(1);

}

switch(i) {

case 0:if(rs.isAfterLast()) rs.beforeFirst();if(rs.next()){

dno.setText(rs.getString(1));dname.setText(rs.getString(2));loc.setText(rs.getString(3));

}break;

case 1:if(rs.isBeforeFirst()) rs.afterLast();if(rs.previous()){

dno.setText(rs.getString(1));dname.setText(rs.getString(2));loc.setText(rs.getString(3));

}

99

Page 100: Java Programming Lab Manual

2k8 [ ]

break;case 2:

if(rs.first()){dno.setText(rs.getString(1));dname.setText(rs.getString(2));loc.setText(rs.getString(3));

}break;

case 3:if(rs.last()){

dno.setText(rs.getString(1));dname.setText(rs.getString(2));loc.setText(rs.getString(3));

}break;

default:System.out.println("Default Case");

}

}catch(Exception e){

System.out.println("Exception occured..."+e.getMessage());}

}

public static void main(String args[]){

new JdbcExample();}

}

OUTPUT:

100

Page 101: Java Programming Lab Manual

2k8 [ ]

PROGRAM-34 : (JdbcExample2.java)

101

Page 102: Java Programming Lab Manual

2k8 [ ]

Write an application program that demonstrates the database operations on java with type 1 driver?

Source:

import java.sql.*;

public class JdbcExample2 {

public static void main(String args[]) { Connection con = null;

ResultSet rs;CallableStatement stmt;String query,regno;int total;

try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:studentdata", "scott", "tiger"); if (!con.isClosed()) System.out.println("Successfully connected to Oracle Server...");

query="{ call HiSal(?) }";stmt = con.prepareCall(query);stmt.registerOutParameter(1, Types.INTEGER);

stmt.execute();/* rs = (ResultSet)stmt.getObject(1);System.out.println("REGNO"+" "+"TOTAL");while(rs.next()){

rowNumber=rs.getRow();regno=rs.getString(1);total=rs.getInt(2);

System.out.println(regno+" "+total);}*/

int i=stmt.getInt(1);System.out.println("The max salary is ::"+i);

} catch(Exception e) { System.err.println("Exception: " + e.getMessage()); } finally { try {

102

Page 103: Java Programming Lab Manual

2k8 [ ]

if (con != null) con.close(); } catch(SQLException e) {} } }}

OUTPUT:

103

Page 104: Java Programming Lab Manual

2k8 [ ]

NETWORK PROGRAMMING:

PROGRAM-35 : (Server.java,Client.java)

Write an applcation program that demonstrate the interconnection between server and client using datagrampacket ?

Source:

Server.java

import java.net.*;

import java.io.*;

public class Server

{

//Initialize Port number and Packet Size

static final int serverPort = 1036;

static final int packetSize = 1024;

104

Page 105: Java Programming Lab Manual

2k8 [ ]

public static void main(String args[])

throws SocketException{

DatagramPacket packet;

DatagramSocket socket;

byte[] data; // For data to be Sent in packets

int clientPort;

InetAddress address;

String str;

socket = new DatagramSocket(serverPort);

for(;;){

data = new byte[packetSize];

// Create packets to receive the message

packet = new DatagramPacket(data,packetSize);

System.out.println("Waiting to receive the packets");

try{

// wait infinetely for arrival of the packet

socket.receive(packet);

}catch(IOException ie){

System.out.println(" Could not Receive :"+ie.getMessage());

System.exit(0);

}

// get data about client in order to echo data back

address = packet.getAddress();

clientPort = packet.getPort();

// print string that was received on server's console

str = new String(data,0,packet.getLength());

System.out.println("Message :"+ str.trim());

105

Page 106: Java Programming Lab Manual

2k8 [ ]

System.out.println("From :"+address);

// echo data back to the client

// Create packets to send to the client

//String temp=new String("Server:messagefromserver");

//data=temp.getBytes();

packet = new DatagramPacket(data,packetSize,address,clientPort);

try{

// sends packet

socket.send(packet);

} catch(IOException ex) {

System.out.println("Could not Send "+ex.getMessage());

System.exit(0);

}

} // for loop

} // main

}

Client.java:

import java.net.*;

import java.io.*;

public class Client{

static final int serverPort = 1036;

static final int packetSize = 1024;

public static void main(String args[]) throws

UnknownHostException, SocketException{

DatagramSocket socket; //How we send packets

DatagramPacket packet; //what we send it in

106

Page 107: Java Programming Lab Manual

2k8 [ ]

InetAddress address; //Where to send

String messageSend; //Message to be send

String messageReturn; //What we get back from the Server

byte[] data;

//Checks for the arguments that sent to the java interpreter

if(args.length != 2){

System.out.println("Usage Error : Java Client < Server name> < Message>");

System.exit(0);

}

// Gets the IP address of the Server

address = InetAddress.getByName(args[0]);

socket = new DatagramSocket();

data = new byte[packetSize];

messageSend = new String(args[1]);

data =messageSend.getBytes();

packet = new DatagramPacket(data,data.length,address,serverPort);

System.out.println(" Trying to Send the packet ");

try{// sends the packet

socket.send(packet);

}catch(IOException ie){

System.out.println("Could not Send :"+ie.getMessage());

System.exit(0);

}

//packet is reinitialized to use it for recieving

packet = new DatagramPacket(data,data.length);

try{// Receives the packet from the server

socket.receive(packet);

107

Page 108: Java Programming Lab Manual

2k8 [ ]

}catch(IOException iee){

System.out.println("Could not receive : "+iee.getMessage() );

System.exit(0);

}

// display message received

messageReturn = new String (packet.getData());

System.out.println("Message Returned : "+

messageReturn.trim());

} // main

} // Class Client

OUTPUT:

108

Page 109: Java Programming Lab Manual

2k8 [ ]

PROGRAM-36 : (EchoServer.java,EchoClient.java)

Write a program that demonstrate the interconnection between server and client using sockets ?

Source:

EchoServer.java

import java.net.Socket;

import java.net.ServerSocket;

import java.io.*;

public class EchoServer {

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

// create socket

int port = 7;

ServerSocket serverSocket = new ServerSocket(port);

System.err.println("Started server on port " + port);

109

Page 110: Java Programming Lab Manual

2k8 [ ]

// repeatedly wait for connections, and process

while (true) {

// a "blocking" call which waits until a connection is requested

Socket clientSocket = serverSocket.accept();

System.err.println("Accepted connection from client");

// open up IO streams

InputStream in = clientSocket.getInputStream ();

OutputStream out = clientSocket.getOutputStream();

// waits for data and reads it in until connection dies

int s;

while ((s = in.read()) != -1)

out.write((char)s);

// close IO streams, then socket

System.err.println("Closing connection with client");

out.close();

in.close();

clientSocket.close();

}

}

}

EchoClient.java

import java.io.*;

import java.net.*;

public class EchoClient{

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

String hostname = "localhost";

110

Page 111: Java Programming Lab Manual

2k8 [ ]

Socket clientSocket = new Socket(hostname, 7);

BufferedReader sockIn = new BufferedReader(

new InputStreamReader(

clientSocket.getInputStream()));

BufferedReader userIn = new BufferedReader(

new InputStreamReader(System.in));

PrintWriter sockOut = new PrintWriter(clientSocket.getOutputStream());

System.out.println("Connected to echo server");

while (true) {

String theLine = userIn.readLine();

if (theLine.equals("."))

break;

sockOut.println(theLine);

sockOut.flush();

System.out.println(sockIn.readLine());

}

userIn.close();

sockIn.close();

sockOut.close();

}

}

OUTPUT:

111

Page 112: Java Programming Lab Manual

2k8 [ ]

112