Advanced Java Book

Embed Size (px)

Citation preview

  • 7/25/2019 Advanced Java Book

    1/299

    Advanced Java Programming

  • 7/25/2019 Advanced Java Book

    2/299

    Version 1999First Impression August 1999

    Second Impression July 2000

    The Team

    Production / Series SupervisionJambu Krishnamurthy

    Vice President Product Development

    The HeadSridhar SubramaniamHead Training Solutions

    Technical WritersThirumurugan .R

    Bakkia Lakshmi .H

    Uma .S

    Review

    Sridhar Subramaniam

    Production/DesignVijay. V

    EditorNurjehan Dhanani

    Copyright1999, Comp-U-Learn Inc.

    All Rights Reserved

    No Part of this Book may be reproduced in any form by any means, stored in a retrieval system, or transmitted by any mode,

    electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. Exceptions aremade to the program listings, which can be typed, stored in a Computer System and executed. No patent liability is assumed

    with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this

    book, the publisher assumes no responsibility for errors or omissions. Neither is any liability assumed for damages resulting

    from the use of the information contained herein.

    All Trade Marks Acknowledged

  • 7/25/2019 Advanced Java Book

    3/299

    The Book at a Glance

  • 7/25/2019 Advanced Java Book

    4/299

    Table of Contents

  • 7/25/2019 Advanced Java Book

    5/299

  • 7/25/2019 Advanced Java Book

    6/299

  • 7/25/2019 Advanced Java Book

    7/299

  • 7/25/2019 Advanced Java Book

    8/299

  • 7/25/2019 Advanced Java Book

    9/299

  • 7/25/2019 Advanced Java Book

    10/299

    III. Index ....................................................................................................... 291

  • 7/25/2019 Advanced Java Book

    11/299

    i

    Before We Begin

    This beginning, a solid, stable one, will take the reader to greater heightsin Programming for the Web and the Internet. Mainly Java. Lets begin.....

    The phenomenon is waiting.

  • 7/25/2019 Advanced Java Book

    12/299

    ii

    How to use this Book

  • 7/25/2019 Advanced Java Book

    13/299

    iii

    Objectives of this Book

    Conventions Used in this Book

    Each session is divided into 12 topics. It is called the Twelve Point

    Program (12pp). In every session, these points are distinctly shown in

    an underlined bigger font.

    Subheadings appear in bold without underlining.

    Note is shown inside a box. It is information which is necessary to

    understand the subject discussed but does not come as a part of the text

    flow.

    Summary is at the end of each session, shown in a special table,

    italicized.

    Each session ends with a Going Over It Again. This helps the student

    in recapitulating the session contents. Figure numbers and descriptions are given below each picture, diagram

    or screen for proper navigation.

  • 7/25/2019 Advanced Java Book

    14/299

    Session 1

    Swing in Java

    On Completion of this Session you will be able to understand...

    Introduction to JFC

    Swing and their behavior

    Merits and Demerits of Swing

    Programming in Swing

    Using Tables and Image ListsUsing Geometric Figures in Swing

  • 7/25/2019 Advanced Java Book

    15/299

    In This Session...

    Introduction to Java Foundation Classes

    Introduction to Swing

    The Swing Component Hierarchy

    An Overview of Swing Packages

    Moving along with Swing

    Swing Button

    Slider Control and Progress Bar

    Image List

    Tables

    Drawing Objects

    JscrollBar

    JRadioButton

  • 7/25/2019 Advanced Java Book

    16/299

    Swing in Java

    Comp-U-Learn 3

    Introduction to Java Foundation Classes

    The Abstract Windowing ToolKit

    Swing

    Java 2D

    Drag and Drop Accessibility

    Introduction to Swing

  • 7/25/2019 Advanced Java Book

    17/299

    Advanced Java Programming

    Comp-U-Learn4

    Swing components are independent of the native windowing system.

    They can run on any windowing system that supports the AWT.

    Swing provides a pure Java implementation of many of the traditional AWTcomponents.

    Swing is compatible with the AWT and Swing components can be usedinterchangeably with AWT components.

    The number and quality of the GUI controls provided by Swing is unrivaled byany other GUI toolkit.

    Swing has a very rich collection and user friendly set of interface elements.

    Swing gives a consistent user experience across platforms.

    Swing has the capability of making Sun Microsystemss dream of Write once,run anywhere come to reality.

    Swing-based user interface elements are somewhat slower to appear on the usersscreen than the peer based components used by the AWT.

    Since the user interface elements look almost alike on all platforms, they will

    look different from the native controls on at least some platforms, and thus userswill be less familiar with them.

    Swing components can be used only with the JDK 1.1 event model. They dontsupport JDK 1.0 event model.

    The Swing Component Hierarchy

  • 7/25/2019 Advanced Java Book

    18/299

    Swing in Java

    Comp-U-Learn 5

  • 7/25/2019 Advanced Java Book

    19/299

    Advanced Java Programming

    Comp-U-Learn6

    An Overview of Swing Packages

    Thecom.sun.java.swing.plafprovides support for Swings pluggable look and feel features.

  • 7/25/2019 Advanced Java Book

    20/299

    Swing in Java

    Comp-U-Learn 7

    JCheck BoxMenuIte mJMenuJRadioButton MenuItem

    JButtonJMenuIte m

    JChech BoxJRadioButton

    JToggleButton

    AbstractButton

    DefaultTableCellRendere r(java.awt.swing.table)

    JLabel

    JI nte rnalFram eJC om boB ox

    JDesk topPane

    JLayeredPane

    JL istJM enuBarJO ption Pane

    ColorChooserPane

    JP anel

    JP op upMenuJP rogressBarJR ootPaneJS crollB arJS crollPaneJS eparatorJS liderJS plitPaneJTabbedPaneJTableJTableHeader(java .awt.sw ingn.table )

    JTe xtPane

    JEd itorPane

    JPasswordFie ld

    JTe xtFie ld

    JTe xtarea

    JTextCom pon ent(java .a wt.sw ing.text)

    JToolB arJToolTipJTreeJV ie wPor t

    JCom ponent

  • 7/25/2019 Advanced Java Book

    21/299

    Advanced Java Programming

    Comp-U-Learn8

    Moving along with Swing

    Example 1.1:

    import javax.swing.*;

    class frame extends JFrame

    {

    public frame()

    {

    setTitle(Our First Frame);

    setSize(300,200);

    }

    }

    public class framedemo

    {

    public static void main(String args[]){

    JFrame fr=new frame();

    fr.show();

    }

    }

    Fig. 1.1

  • 7/25/2019 Advanced Java Book

    22/299

    Swing in Java

    Comp-U-Learn 9

    Example 1.2:

    import javax.swing.*;import java.awt.event.*;class frame extends JFrame{

    public frame(){setTitle(Sample Frame);setSize(300,200); addWindowListener(new WindowAdapter() {

    public void windowClosing(WindowEvent e) { System.exit(0); } });}}

    public class framedemo{

    public static void main(String args[]){JFrame fr=new frame();fr.show();}}

    Fig 1.2

  • 7/25/2019 Advanced Java Book

    23/299

    Advanced Java Programming

    Comp-U-Learn10

    Example 1.3:

    import javax.swing.*;

    import java.awt.*;

    import java.awt.event.*;

    class ourpanel extends JPanel{

    public void paintComponent(Graphics g)

    {

    super.paintComponent(g);

    g.drawString(Welcome to Swing,100,80);

    }

    }

    class ourframe extends JFrame

    {

    public ourframe()

    {

    setTitle(Sample Frame Window);setSize(300,500);

    addWindowListener(new WindowAdapter()

    {

    public void windowClosing(WindowEvent e)

    {

    System.exit(0);

  • 7/25/2019 Advanced Java Book

    24/299

    Swing in Java

    Comp-U-Learn 11

    }

    });

    Container con=getContentPane();

    con.add(new ourpanel());

    }

    }

    public class welcome

    {

    public static void main(String args[])

    {

    JFrame fr=new ourframe();

    fr.show();

    }

    }

    Fig. 1.3

    Swing Button

    Example 1.4:

    import java.awt.*;

    import java.awt.event.*;

    import javax.swing.*;

    import javax.swing.event.*;

    import javax.swing.border.*;

  • 7/25/2019 Advanced Java Book

    25/299

    Advanced Java Programming

    Comp-U-Learn12

    class swing extends Frame

    {

    JTabbedPane tabbedPane = new JTabbedPane();

    JPanel buttonPanel = new JPanel();

    JPanel[] panels = {buttonPanel};

    Icon worldIcon = new ImageIcon(Dbmusic.gif);

    Icon printerIcon = new ImageIcon(Eatdrink.gif);

    JButton printerButton = new JButton(Print,printerIcon);

    JToggleButton worldButton = new

    JToggleButton(Connect,worldIcon,true);

    public swing()

    {

    super(Swing Button window);

    addWindowListener(new WindowHandler());

    String[] tabs = {Buttons};

    String[] tabTips = {A Button and a Toggle Button};

    for(int i=0;i

  • 7/25/2019 Advanced Java Book

    26/299

    Swing in Java

    Comp-U-Learn 13

    Fig 1.4

    Slider Control and Progress Bar

  • 7/25/2019 Advanced Java Book

    27/299

  • 7/25/2019 Advanced Java Book

    28/299

  • 7/25/2019 Advanced Java Book

    29/299

    Advanced Java Programming

    Comp-U-Learn16

    Example 1.6:

    import java.awt.*;

    import java.awt.event.*;

    import javax.swing.*;

    import javax.swing.event.*;

    import javax.swing.border.*;

    public class list extends Frame {

    JTabbedPane tb = new JTabbedPane();

    JPanel lpanel = new JPanel();

    JPanel[] panels = {lpanel};

    Icon i1 = new ImageIcon(videos.gif);

    Icon i2 = new ImageIcon(school.gif);

    Icon i3 = new ImageIcon(invntory.gif);

    Icon i4 = new ImageIcon(members.gif);

    Icon[] leaves = {i1, i2, i3, i4};

    JList mylist = new JList(leaves);

    public list() {

    super(List Box Display);

    addWindowListener(new WindowHandler());

    String[] tabs = {Icon List};

    String[] tabTips = {An Image List Control};

    mylist.setFixedCellHeight(100);

    lpanel.add(mylist);

    for(int i=0;i

  • 7/25/2019 Advanced Java Book

    30/299

    Swing in Java

    Comp-U-Learn 17

    public static void main(String args[]) {

    list l = new list();

    }

    public class WindowHandler extends WindowAdapter { public void windowClosing(WindowEvent e) {

    System.exit(0);

    }

    }

    }

    Fig. 1.6

    Tables

  • 7/25/2019 Advanced Java Book

    31/299

  • 7/25/2019 Advanced Java Book

    32/299

    Swing in Java

    Comp-U-Learn 19

    Fig. 1.7

    Drawing Objects

    Example 1.8:

    import java.awt.*;

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

    class shapes extends JPanel {

    public void paintComponent(Graphics g) {

    super.paintComponent(g);

  • 7/25/2019 Advanced Java Book

    33/299

    Advanced Java Programming

    Comp-U-Learn20

    g.setColor(Color.blue);

    g.drawRect(20,30,100,70);

    g.drawLine(180,220,300,270);

    g.drawRoundRect(140,40,80,50,15,15);

    g.drawOval(30,120,100,40);

    Polygon p = new Polygon();p.addPoint(320,320);

    p.addPoint(320,390);

    p.addPoint(400,400);

    g.drawPolygon(p);

    g.setColor(Color.orange);

    g.fillRect(320,30,100,70);

    g.fillRoundRect(70,220,80,50,15,15);

    g.fill3DRect(120,300,100,30,true);

    for(int i=1;i

  • 7/25/2019 Advanced Java Book

    34/299

  • 7/25/2019 Advanced Java Book

    35/299

    Advanced Java Programming

    Comp-U-Learn22

    Example 1.9:

    import java.awt.*;

    import java.awt.event.*;

    import javax.swing.*;

    public class ColorSelect extends JFrame implements AdjustmentListener

    private JLabel redLabel;

    private JLabel greenLabel;

    private JLabel blueLabel;

    private JScrollBar red;

    private JScrollBar green;

    private JScrollBar blue;

    private JPanel colorPanel;

    { public ColorSelect()

    { setTitle(ColorSelect);

    setSize(300, 200);

    addWindowListener(new WindowAdapter()

    { public void windowClosing(WindowEvent e)

    { System.exit(0);

    }

    } );

    Container contentPane = getContentPane();

    JPanel p = new JPanel();

    p.setLayout(new GridLayout(3, 2));

    p.add(redLabel = new JLabel(Red 0));

    p.add(red = new JScrollBar(Adjustable.HORIZONTAL,

    0, 0, 0, 255));

    red.setBlockIncrement(16);

    red.addAdjustmentListener(this);

    p.add(greenLabel = new JLabel(Green 0));

    p.add(green = new JScrollBar(Adjustable.HORIZONTAL,

    0, 0, 0, 255));

    green.setBlockIncrement(16);

    green.addAdjustmentListener(this);

    p.add(blueLabel = new JLabel(Blue 0));

    p.add(blue = new JScrollBar(Adjustable.HORIZONTAL,

    0, 0, 0, 255));

    blue.setBlockIncrement(16); blue.addAdjustmentListener(this);

    contentPane.add(p, South);

    colorPanel = new JPanel();

    colorPanel.setBackground(new Color(0, 0, 0));

    contentPane.add(colorPanel, Center);

    }

  • 7/25/2019 Advanced Java Book

    36/299

    Swing in Java

    Comp-U-Learn 23

    public void adjustmentValueChanged(AdjustmentEvent evt)

    { redLabel.setText(Red + red.getValue());

    greenLabel.setText(Green + green.getValue());

    blueLabel.setText(Blue + blue.getValue());

    colorPanel.setBackground(new Color(red.getValue(),

    green.getValue(), blue.getValue()));

    colorPanel.repaint();

    }

    public static void main(String[] args)

    { Frame f = new ColorSelect();

    f.show();

    }

    }

    Fig. 1.9

    JRadioButton

  • 7/25/2019 Advanced Java Book

    37/299

    Advanced Java Programming

    Comp-U-Learn24

    Example 1.10:

    import javax.swing.*;

    import javax.swing.event.*;

    import java.awt.*;

    import java.awt.event.*;

    class radiopanel extends JPanel

    {

    public radiopanel()

    {

    setLayout(new GridLayout(4,1));

    JRadioButton rb;

    ButtonGroup bg=new ButtonGroup();

    JLabel l=new JLabel(Ice creams);

    l.setFont(new Font(Times New Roman,Font.BOLD,12));

    add(l);

    rb=new JRadioButton(Vanilla);

    add(rb);

    bg.add(rb);

    rb.setSelected(true);

    rb=new JRadioButton(Cassatta);

    add(rb);

    bg.add(rb);

    rb=new JRadioButton(Strawberry);

    add(rb);

    bg.add(rb);}}

    class ourframe extends JFrame

    {

    public ourframe()

    {

    setTitle(Sample Frame Window);

    setSize(300,500);

    addWindowListener(new WindowAdapter()

    {

    public void windowClosing(WindowEvent e)

    {System.exit(0);

    }

    });

    Container con=getContentPane();

    con.add(new radiopanel());

  • 7/25/2019 Advanced Java Book

    38/299

    Swing in Java

    Comp-U-Learn 25

    }}

    public class Radio

    {

    public static void main(String args[])

    {JFrame fr=new ourframe();

    fr.show();

    }}

    Fig 1.10

    Summary

    In this session, we learnt about the basic concepts of Java Foundation Classes, Swing

    components, Swing Component hierarchy and some methods in those classes. We

    tried some Swing components like Button, Toggle Button, Slider, Progress Bar, Table

    and Image List. Then we also wrote a program, which enabled us to draw some

    geometric figures. The difference between AWT and Swing is only a hairline. The

    event handling in Swing is the same as in AWT. However, swing provides a rich

    source of components and other added features. The major difference lies in theusage of canvas in AWT. Only we can draw on the canvas area. The method paint() is

    substituted by paintComponent() in Swings. Here, we can draw on any Swing

    Component not essentially on a canvas. We will learn about more Swing components

    in the next session.

  • 7/25/2019 Advanced Java Book

    39/299

    Advanced Java Programming

    Comp-U-Learn26

    Going Over It Again

    I. Fill in the Blanks

    II. State True or False

    III. One line Answers

  • 7/25/2019 Advanced Java Book

    40/299

  • 7/25/2019 Advanced Java Book

    41/299

  • 7/25/2019 Advanced Java Book

    42/299

  • 7/25/2019 Advanced Java Book

    43/299

  • 7/25/2019 Advanced Java Book

    44/299

    Swing Components

    Comp-U-Learn 33

    ShowMessageDialog Show a message and wait for the user to click OK.

    ShowConfirmDialog Show a message and get a confirmation like OK or

    Cancel

    ShowOptionDialog Show a message and get a user option from a set of

    optionsShowInputDialog Show a message and get one line of user input

    ERROR_MESSAGE

    INFORMATION_MESSAGE

    WARNING_MESSAGE

    QUESTION_MESSAGE

    PLAIN_MESSAGE

    String draw the string

    Icon show the icon

    Component show the component

    Object[] Show all objects in the array.

    ShowMessageDialog None

    ShowConfirmDialog An integer representing the chosen option

    ShowOptionDialog An integer representing the chosen option

    ShowInputDialog The stringthat the user supplied or selected

  • 7/25/2019 Advanced Java Book

    45/299

    Advanced Java Programming

    Comp-U-Learn34

    OK_OPTION

    CANCEL_OPTION

    YES_OPTION

    NO_OPTION

    CLOSED_OPTION

    Property Setter Method Getter Method

    ICON_PROPERTY setIcon getIcon

    INITIAL_SELECTION_VALUE_PR

    OPERTY

    setInitialSelectionValue getInitialSelectionValue

    INITIAL_VALUE_PROPERTY setInitialValue getInitialValue

    INPUT_VALUE_PROPERTY setInputValue getInputValue

    MESSAGE_PROPERTY setMessage getMessage

    MESSAGE_TYPE_PROPERTY setMessageType getMessageType

    OPTION_TYPE_PROPERTY setOptionType getOptionTyp

    OPTIONS_PROPERTY setOptions getOptionsSELECTION_VALUES_PROPERTY setSelectionValues Get SelectionValue

    VALUE_PROPERTY setValue GetValue

    WANTS_INPUT_PROPERTY setWantsInput GetWantsInput

    Fig. 2.1

  • 7/25/2019 Advanced Java Book

    46/299

    Swing Components

    Comp-U-Learn 35

    Fig. 2.2

    Example 2.1:

    import javax.swing.*;public class options extends Object

    {public static void main(String args[]){JOptionPane.showMessageDialog(null,Simple Dialog Box);JOptionPane.showMessageDialog(null,Error Dialog Box withtitle,Title,JOptionPane.ERROR_MESSAGE);System.exit(0);}}

    Example 2.2:

    import javax.swing.*;

    public class option extends Object

    {

    public static void main(String args[])

    {

    int result=JOptionPane.showConfirmDialog(null,Continue?,Give

    your option,JOptionPane.YES_NO_OPTION);

    switch(result)

    {

  • 7/25/2019 Advanced Java Book

    47/299

    Advanced Java Programming

    Comp-U-Learn36

    case JOptionPane.YES_OPTION:

    System.out.println(Yes Button);

    break;

    case JOptionPane.NO_OPTION:

    System.out.println(No Button);

    break;

    case JOptionPane.CLOSED_OPTION:

    System.out.println(Closed Button);

    break;

    }

    System.exit(0);

    }

    }

    Fig. 2.3

    C:\jdk1.2\bin>java option

    C:\jdk1.2\bin>java option

    C:\jdk1.2\bin>java option

  • 7/25/2019 Advanced Java Book

    48/299

    Swing Components

    Comp-U-Learn 37

    Input Dialog Box

    Example 2.3:

    import javax.swing.*;public class input extends Object{public static void main(String args[]){

  • 7/25/2019 Advanced Java Book

    49/299

    Advanced Java Programming

    Comp-U-Learn38

    String[]flow={Rose,Lilly,Jasmine,Marigold,Tulip,Poppy,Zinna,Dairy};

    String ans=JOptionPane.showInputDialog(null,Enter yourName,Test Input,JOptionPane.QUESTION_MESSAGE);

    System.out.println(Your name is +ans);

    Object sel=JOptionPane.showInputDialog(null,Select from theflowers given,FlowerList,JOptionPane.PLAIN_MESSAGE,null,flow,flow[0]);System.out.println(Your Favourite Flower from selection is+sel);

    System.exit(0);

    }}

    Fig. 2.4

    Fig 2.5

    C:\jdk1.2\bin>java input

  • 7/25/2019 Advanced Java Book

    50/299

  • 7/25/2019 Advanced Java Book

    51/299

    Advanced Java Programming

    Comp-U-Learn40

    Fig 2.6

    C:\jdk1.2\bin>javac custom.javaC:\jdk1.2\bin>java custom

    C:\jdk1.2\bin>java custom

    C:\jdk1.2\bin>java custom

  • 7/25/2019 Advanced Java Book

    52/299

  • 7/25/2019 Advanced Java Book

    53/299

    Advanced Java Programming

    Comp-U-Learn42

    addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } );

    JPanel gridPanel = new JPanel(); gridPanel.setLayout(new GridLayout(2, 3));

    typePanel = new ButtonPanel(Type, new String[] { Message, Confirm, Option, Input });

    messageTypePanel = new ButtonPanel(Message Type, new String[] { ERROR_MESSAGE,

    INFORMATION_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE, PLAIN_MESSAGE });

    messagePanel = new ButtonPanel(Message, new String[] { String, Icon, Component, Other, Object[] });

    optionTypePanel = new ButtonPanel(Confirm, new String[] { DEFAULT_OPTION, YES_NO_OPTION, YES_NO_CANCEL_OPTION, OK_CANCEL_OPTION });

    optionsPanel = new ButtonPanel(Option, new String[] { String[], Icon[], Object[]

    });

    inputPanel = new ButtonPanel(Input, new String[] { Text field, Combo box });

  • 7/25/2019 Advanced Java Book

    54/299

    Swing Components

    Comp-U-Learn 43

    JPanel showPanel = new JPanel(); JButton showButton = new JButton(Show); showButton.addActionListener(this); showPanel.add(showButton);

    gridPanel.add(typePanel); gridPanel.add(messageTypePanel); gridPanel.add(messagePanel); gridPanel.add(optionTypePanel); gridPanel.add(optionsPanel); gridPanel.add(showPanel); gridPanel.add(inputPanel);

    Container contentPane = getContentPane(); contentPane.add(gridPanel, Center); contentPane.add(showPanel, South); }

    public Object getMessage()

    { String s = messagePanel.getSelection(); if (s.equals(String)) return messageString; else if (s.equals(Icon)) return messageIcon; else if (s.equals(Component)) return messageComponent; else if (s.equals(Object[])) return new Object[] { messageString, messageIcon, messageComponent, messageFont };

    else if (s.equals(Other)) return messageFont; else return null; }

    public Object[] getOptions() { String s = optionsPanel.getSelection(); if (s.equals(String[])) return new String[] { Yellow, Blue, Red }; else if (s.equals(Icon[])) return new Icon[] { new ImageIcon(icecream.gif), new ImageIcon(peach.gif), new ImageIcon(peas.gif)

    }; else if (s.equals(Object[])) return new Object[] { messageString, messageIcon, messageComponent, messageFont

  • 7/25/2019 Advanced Java Book

    55/299

  • 7/25/2019 Advanced Java Book

    56/299

  • 7/25/2019 Advanced Java Book

    57/299

    Advanced Java Programming

    Comp-U-Learn46

    Fig 2.8

    JLabel

    Add an Icon

    Set the vertical and horizontal position of text relative to Icon

    Set the relative position of contents within component

    Example 2.6:

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

    class label extends JPanel{public label(){JLabel l1=new JLabel(Our First label);add(l1);JLabel l2=new JLabel(Our Second Label);Font f=new Font(Times New Roman,Font.BOLD+ Font.ITALIC,20);l2.setFont(f);Icon i=newImageIcon(c:/jdk1.2/demo/jfc/Java2D/images/boat.gif);l2.setIcon(i);

    l2.setHorizontalAlignment(JLabel.RIGHT);add(l2);}}

    class ourframe extends JFrame{

  • 7/25/2019 Advanced Java Book

    58/299

    Swing Components

    Comp-U-Learn 47

    public ourframe(){setTitle(Sample Frame Window);setSize(300,500); addWindowListener(new WindowAdapter() {

    public void windowClosing(WindowEvent e){

    System.exit(0);} }); Container con=getContentPane(); con.add(new label());}}

    public class lab{

    public static void main(String args[]){JFrame fr=new ourframe();fr.show();}}

    Fig. 2.9

  • 7/25/2019 Advanced Java Book

    59/299

  • 7/25/2019 Advanced Java Book

    60/299

    Swing Components

    Comp-U-Learn 49

    null, Exit }, this));

    readonlyItem = new JCheckBoxMenuItem(Read-only);

    ButtonGroup group = new ButtonGroup(); JRadioButtonMenuItem insertItem = new JRadioButtonMenuItem(Insert); insertItem.setSelected(true); JRadioButtonMenuItem overtypeItem = new JRadioButtonMenuItem(Overtype); group.add(insertItem); group.add(overtypeItem);

    mbar.add(makeMenu(Edit, new Object[] { new JMenuItem(Cut, new ImageIcon(cut.gif)), new JMenuItem(Copy,

    new ImageIcon(copy.gif)), new JMenuItem(Paste, new ImageIcon(paste.gif)), null, makeMenu(Options, new Object[] { readonlyItem, null, insertItem, overtypeItem }, this) }, this));

    JMenu helpMenu = new JMenu(Help); helpMenu.setMnemonic(H);

    mbar.add(makeMenu(helpMenu, new Object[] { new JMenuItem(Index, I), new JMenuItem(About, A) }, this));

    popup = makePopupMenu( new Object[]

    { Cut, Copy, Paste }, this);

    getContentPane().addMouseListener(new MouseAdapter()

  • 7/25/2019 Advanced Java Book

    61/299

  • 7/25/2019 Advanced Java Book

    62/299

    Swing Components

    Comp-U-Learn 51

    if (target instanceof ActionListener) r.addActionListener((ActionListener)target); return r; }

    public static JPopupMenu makePopupMenu

    (Object[] items, Object target) { JPopupMenu m = new JPopupMenu();

    for (int i = 0; i < items.length; i++) { if (items[i] == null) m.addSeparator(); else m.add(makeMenuItem(items[i], target)); } return m; }

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

    f.show(); } private JMenuItem saveItem; private JMenuItem saveAsItem; private JCheckBoxMenuItem readonlyItem; private JPopupMenu popup;}

    Fig. 2.10

  • 7/25/2019 Advanced Java Book

    63/299

    Advanced Java Programming

    Comp-U-Learn52

    Fig. 2.11

    C:\jdk1.2\bin>java MenuTestOvertypeRead-onlyCopyNewOpenCutPaste

    IndexAboutInsertExit

  • 7/25/2019 Advanced Java Book

    64/299

  • 7/25/2019 Advanced Java Book

    65/299

  • 7/25/2019 Advanced Java Book

    66/299

  • 7/25/2019 Advanced Java Book

    67/299

    Advanced Java Programming

    Comp-U-Learn56

    }

    void setupEventHandlers() {

    addWindowListener(new WindowHandler());

    fileExit.addActionListener(new MenuItemHandler());}

    public static void main(String[] args) {

    SwingTree app = new SwingTree();

    }

    public class WindowHandler extends WindowAdapter {

    public void windowClosing(WindowEvent e) {

    System.exit(0);

    }

    }

    public class MenuItemHandler implements ActionListener {

    public void actionPerformed(ActionEvent e) {

    String cmd = e.getActionCommand();

    if(cmd.equals(Exit)) System.exit(0);

    }

    }

    class Renderer extends JLabel implements TreeCellRenderer {

    public Component getTreeCellRendererComponent(JTree tree,

    Object value, boolean selected, boolean expanded,

    boolean leaf, int row, boolean hasFocus) {

    setText(value.toString()+ ); return this;

    }

    }

    }

  • 7/25/2019 Advanced Java Book

    68/299

    Swing Components

    Comp-U-Learn 57

    Fig. 2.12

    Look and Feel

  • 7/25/2019 Advanced Java Book

    69/299

    Advanced Java Programming

    Comp-U-Learn58

    Example 2.9:import java.awt.*;import java.awt.event.*;import javax.swing.*;

    class PlafPanel extends JPanel implements ActionListener{ public PlafPanel() { metalButton = new JButton(Metal); motifButton = new JButton(Motif); windowsButton = new JButton(Windows);

    add(metalButton);

    add(motifButton); add(windowsButton);

    metalButton.addActionListener(this); motifButton.addActionListener(this); windowsButton.addActionListener(this); }

    public void actionPerformed(ActionEvent evt) { Object source = evt.getSource(); String plaf = ; if (source == metalButton) plaf = javax.swing.plaf.metal.MetalLookAndFeel; else if (source == motifButton)

    plaf = com.sun.java.swing.plaf.motif.MotifLookAndFeel; else if (source == windowsButton) plaf =com.sun.java.swing.plaf.windows.WindowsLookAndFeel; try { UIManager.setLookAndFeel(plaf); SwingUtilities.updateComponentTreeUI(this);

  • 7/25/2019 Advanced Java Book

    70/299

    Swing Components

    Comp-U-Learn 59

    } catch(Exception e) {} }

    private JButton metalButton; private JButton motifButton;

    private JButton windowsButton;}class PlafFrame extends JFrame{ public PlafFrame() { setTitle(PlafTest); setSize(300, 200); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } );

    Container contentPane = getContentPane(); contentPane.add(new PlafPanel());

    }}

    public class PlafTest{ public static void main(String[] args) { JFrame frame = new PlafFrame(); frame.show(); }}

    Fig. 2.13

  • 7/25/2019 Advanced Java Book

    71/299

  • 7/25/2019 Advanced Java Book

    72/299

    Swing Components

    Comp-U-Learn 61

    addWindowListener(new WindowAdapter()

    {

    public void windowClosing(WindowEvent e)

    {

    System.exit(0);

    } });

    Container con=getContentPane();

    con.add(new tPanel());

    setVisible(true);

    }

    }

    class tPanel extends JPanel{

    Timer timerActivity,timerCountdown;

    int TIMEOUT=40;

    int countdownTicks=TIMEOUT;

    JLabel countdownDisplay;

    public tPanel()

    {

    setLayout(new BorderLayout());

    requestFocus();

    String s=Application will terminate +TIMEOUT+ seconds of

    inactivity ;

    add(new JLabel(s),North);

    add(countdownDisplay=new

    JLabel(Integer.toString(TIMEOUT)),South);

    addKeyListener(new KeyAdapter(){

    public void keyPressed(KeyEvent e)

    {

    timerActivity.restart();

    countdownTicks=TIMEOUT;

    updateDisplay();

    }

    });

    addMouseListener(new MouseAdapter(){

    public void mouseClicked(MouseEvent e)

    {

    timerActivity.restart();

    countdownTicks=TIMEOUT;

    updateDisplay();}

    });

    addMouseMotionListener(new MouseMotionAdapter(){

    public void mouseMoved(MouseEvent e){

    timerActivity.restart();

  • 7/25/2019 Advanced Java Book

    73/299

  • 7/25/2019 Advanced Java Book

    74/299

  • 7/25/2019 Advanced Java Book

    75/299

  • 7/25/2019 Advanced Java Book

    76/299

  • 7/25/2019 Advanced Java Book

    77/299

    Advanced Java Programming

    Comp-U-Learn66

    Going Over It Again

    I. Fill in the Blanks

    II. State True or False

    III. One line Answers

  • 7/25/2019 Advanced Java Book

    78/299

    Session 3

    Beans Fundamentals

    On Completion of this Session you will be able to understand...

    Java Beans Basics

    Beans Architecture

    Bean Box

    Creating a Bean

    Bundled Beans

  • 7/25/2019 Advanced Java Book

    79/299

  • 7/25/2019 Advanced Java Book

    80/299

  • 7/25/2019 Advanced Java Book

    81/299

    Advanced Java Programming

    Comp-U-Learn70

    Builder

    Bridges

    Bean Concepts

    By adhering to specific naming conventions, known as design patterns, whennaming Bean features. Bean introspection relies on the API to discover Bean

    features via design patterns.

    By explicity providing property, method, and event information with a relatedBean Information class. A Bean information class implements the BeanInfo

    interface.

  • 7/25/2019 Advanced Java Book

    82/299

  • 7/25/2019 Advanced Java Book

    83/299

    Advanced Java Programming

    Comp-U-Learn72

    Bean Box

    Property Sheet

    Fig. 3.3

  • 7/25/2019 Advanced Java Book

    84/299

    Beans Fundamentals

    Comp-U-Learn 73

    Fig. 3.4

    Using Bean Box

    Fig. 3.5

  • 7/25/2019 Advanced Java Book

    85/299

    Advanced Java Programming

    Comp-U-Learn74

    Fig. 3.6

    Fig. 3.7

  • 7/25/2019 Advanced Java Book

    86/299

  • 7/25/2019 Advanced Java Book

    87/299

    Advanced Java Programming

    Comp-U-Learn76

    Using Bound Properties

    Fig. 3.9

    Fig. 3.10

  • 7/25/2019 Advanced Java Book

    88/299

    Beans Fundamentals

    Comp-U-Learn 77

    Fig. 3.11

    Creating a Bean

    Create a bean source code as a java file in our JDKs bin directory and compile itusing javac.

    Create a manifest file which will identify the .class file as a bean.

    Create a jar file which will contain the .class file and a .mf file.

    Copy the jar file into BDKs jars directory.

    In command line run the beanbox usually we can get our bean in the Toolbox.

    Example 3.1:

    import java.awt.*;

    import java.io.Serializable;import java.beans.*;public class mybean extends Canvasimplements Serializable{

    public mybean()

  • 7/25/2019 Advanced Java Book

    89/299

  • 7/25/2019 Advanced Java Book

    90/299

  • 7/25/2019 Advanced Java Book

    91/299

    Advanced Java Programming

    Comp-U-Learn80

    Fig. 3.13

    Fig. 3.14

    Other Bundled Beans

  • 7/25/2019 Advanced Java Book

    92/299

  • 7/25/2019 Advanced Java Book

    93/299

    Advanced Java Programming

    Comp-U-Learn82

    JDBC SELECT

    Fig. 3.16

    The QuoteMonitor

  • 7/25/2019 Advanced Java Book

    94/299

    Beans Fundamentals

    Comp-U-Learn 83

    Fig.. 3.17

    Other beans

    SummaryIn this session we have seen the basic things related to the Java Beans. Here

    we have dealt about the BDK and its requirements. We have used some of the

    bundled beans to get the practical idea about the beans. Also we have seen the

    creation of our own beans and its display in the toolbox. Now we can create

    our own bean and add it to the tool box.

    Going Over It Again

    I. Fill in the Blanks

  • 7/25/2019 Advanced Java Book

    95/299

    Advanced Java Programming

    Comp-U-Learn84

    II. State True or False

    III. One line Answers

  • 7/25/2019 Advanced Java Book

    96/299

    Session 4

    Inside Beans

    On Completion of this Session you will be able to understand...

    Introspection

    Persistence in Beans

    Java.Beans Package

    BeanInfo Interface

  • 7/25/2019 Advanced Java Book

    97/299

  • 7/25/2019 Advanced Java Book

    98/299

  • 7/25/2019 Advanced Java Book

    99/299

  • 7/25/2019 Advanced Java Book

    100/299

    Inside Beans

    Comp-U-Learn 89

    Fig. 4.2

    Fig. 4.3

  • 7/25/2019 Advanced Java Book

    101/299

  • 7/25/2019 Advanced Java Book

    102/299

    Inside Beans

    Comp-U-Learn 91

    This is an example of the use of the generatedMyApplet applet. Notice the Applet tag requires severalarchives, one per JAR used in building the Applet

    Trouble instantiating applet MyApplet!!

    Persistence

  • 7/25/2019 Advanced Java Book

    103/299

    Advanced Java Programming

    Comp-U-Learn92

    Making Beans Serializable

    Fig. 4.6

  • 7/25/2019 Advanced Java Book

    104/299

    Inside Beans

    Comp-U-Learn 93

    private transient Date mytime;

    Java.Beans Package

    Methods Usage

    instantiate() Creates an instance of a bean from the serialized

    object.

    isInstanceOf() Determines if a bean is of a specified class or

    interface.

    getInstanceOf() Returns an object that represents a particular view ofa

    bean.

    isDesignTime() Determines whether beans are running in an

    application builder environment.

    setDesignTime() Identifies the fact that beans are running in an

    application builder environment.

    isGuiAvailable() Determines whether a GUI is available for beans.

    setGuiAvailable() Identifies the fact that a GUI is available for beans.

  • 7/25/2019 Advanced Java Book

    105/299

  • 7/25/2019 Advanced Java Book

    106/299

  • 7/25/2019 Advanced Java Book

    107/299

    Advanced Java Programming

    Comp-U-Learn96

    package sunw.demo.juggler;import java.beans.*;

    import java.awt.Image.*;

    public class JugglerBeanInfo extends SimpleBeanInfo

    {

    public Image getIcon(int iconKind)

    {

    if (iconKind == BeanInfo.ICON_COLOR_16x16)

    {

    Image img;

    img = loadImage(JugglerIcon.gif);

    return img;

    }return null;

    }

    }

    Manifest-Version: 1.0

    Name: JugglerBean.class

    Java-Bean: True

    Name: JugglerBeanInfo.class

    Java-Bean: False

    Name: JugglerIcon.gifJava-Bean: False

  • 7/25/2019 Advanced Java Book

    108/299

  • 7/25/2019 Advanced Java Book

    109/299

    Advanced Java Programming

    Comp-U-Learn98

    Event Handling Classes

    Other Interfaces

    Aggregation

    Summary

    In this session we have seen the introspection concept related to the Java Beans. Alsowe have dealt with serialization in JavaBeans. We have used some of the classes in

    the java.beans packages. In the middle of the session we have seen the BeanInfo

    interface and its classes along with an example. At the end of the session we learnt

    about various descriptors and its concepts.

  • 7/25/2019 Advanced Java Book

    110/299

    Inside Beans

    Comp-U-Learn 99

    Going Over It Again

    I. Fill in the Blanks

    II. State True or False

    III. One line Answers

  • 7/25/2019 Advanced Java Book

    111/299

    Session 5

    Servlet Programming

    On Completion of this Session you will be able to understand...

    Java Servlets Basics

    Servlets Classes

    Developing & Running Servlets

    HTML Form Handling

    Life Cycle of Servlets

  • 7/25/2019 Advanced Java Book

    112/299

    In This Session...

    Introduction to Server-Side Java

    Servlets

    The Other World

    Why Servlets?

    Supports for Servlets

    Servlet Architecture

    Developing a Servlet

    Running a Servlet

    Handling HTML Form

    Servlet Life Cycle

    Init and Destroy Methods

    Service Method

  • 7/25/2019 Advanced Java Book

    113/299

    Servlet Programming

    Comp-U-Learn 103

    Introduction to Server-Side Java

    Servlets

  • 7/25/2019 Advanced Java Book

    114/299

    Advanced Java Programming

    Comp-U-Learn104

    The Other World

  • 7/25/2019 Advanced Java Book

    115/299

    Servlet Programming

    Comp-U-Learn 105

    Common Gateway Interface (CGI)

    For CGI implementation, the most common platform independent language is

    perl.

    But it requires the server to start a new interpreter for every request.

    CGI runs in a completely separate process from the web server. If a client submits

    a request to a CGI program that terminates before responding to the web server,

    the browser has no way of knowing what happened. It just sits there waiting for

    a response until it times out. A web server creates a new process every time it receives a CGI request. This

    result in the loss of response time, because the server must create and initialize a

    new address space for every process.

    Active Server Pages (ASP)

    Server-side JavaScript

    Server Extension APIs

  • 7/25/2019 Advanced Java Book

    116/299

    Advanced Java Programming

    Comp-U-Learn106

    Why Servlets?

    Efficient

    Persistent

    Portable

    Robust

  • 7/25/2019 Advanced Java Book

    117/299

    Servlet Programming

    Comp-U-Learn 107

    Extensible

    Flexible

    Secure

    Widespread Acceptance

    Supports for Servlets

    Servlet Engines

  • 7/25/2019 Advanced Java Book

    118/299

    Advanced Java Programming

    Comp-U-Learn108

    Servers with built in Servlet Support

    Product Vendor

    Acme.Serve AcmeJavaSoftware

    ApacheWebServer Apache

    DominoGoWebServer Lotus

    DynamoApplicationServer ATG

    EnterpriseServer NetscapeEnterpriseServer KonaSoft

    InternetConnectionServer IBM

    ITP WebServer Tandem

    JavaWebServer SunMicrosystems

    Jetty MorBay

    JigsawServer WorldWideWebConsortium

    NetForge Novocode

    ServletFactory EarlyMorningSoftware

    SunWebServer SunMicrosystems

    TengahApplicationServer WebLogic

    VisualAgeWebRunnerToolkit IBM

    WEASAL WebEasy

    WebCore Paralogic

    Website Professional OReilly

    ZeusWebServer Zeus Technology

    Third-Party Add-Ons with Servlet Support

    Product VendorWAICoolRunner Gefion Software

    Jrun Live Software

    ServletExec NewAtlanta

    Servlet CGI Development Kit Unicom

    Web Sphere Application Server IBM

  • 7/25/2019 Advanced Java Book

    119/299

    Servlet Programming

    Comp-U-Learn 109

    Servlet Architecture

    GenericServlet and HttpServlet

    public abstract void service(ServletRequest req,

    ServletResponse res) throws ServletException, IOException;

    Server Service()

    Request

    Response

    (Generic Servlet )

    Fig. 5.1

  • 7/25/2019 Advanced Java Book

    120/299

    Advanced Java Programming

    Comp-U-Learn110

    protected void service(HttpServletRequest req,

    HttpServletResponse resp)throws ServletException, IOException;

    Server

    Service()

    d o G e t ( )

    Service()

    d o P o s t ( )

    GET

    Request

    Response

    POST

    Request

    Response

    HTTP Servlet

    Fig. 5.2

    Developing a Servlet

  • 7/25/2019 Advanced Java Book

    121/299

    Servlet Programming

    Comp-U-Learn 111

    Example 5.1:

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

    public class hello extends HttpServlet{public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException

    {res.setContentType(text/html);PrintWriter out= res.getWriter();out.println();out.println( Hello Servlets!! );out.println();out.println( Hello Guys! Servlet Welcomes You!! );out.println();}}

    Running a Servlet

    Java Servlet Development Kit (JSDK). It contains the servlet API class fileswhich will support our servlet packages.

    Any one of the Servlet engines which are listed in the previous sections.

  • 7/25/2019 Advanced Java Book

    122/299

    Advanced Java Programming

    Comp-U-Learn112

    Write the servlet program and save it with .java extension.

    Compile the code using javac like a Java program. (remember that the directorywhich contain our .java file should have the JSDK)

    Then copy the .class file in to the servletsdirectory of our Apache server.

    Now open the browser. Enter the URL of our servlets file. The syntax is htttp:///servlets/.

    Fig. 5.3

    Handling HTML Form

  • 7/25/2019 Advanced Java Book

    123/299

    Servlet Programming

    Comp-U-Learn 113

    Example 5.2:

    // first.html

    HTML & Servlets

  • 7/25/2019 Advanced Java Book

    124/299

    Advanced Java Programming

    Comp-U-Learn114

    out.println(

    );out.println(My Country is: +name2);out.println();}

    }

    Fig. 5.4

    Fig. 5.5

  • 7/25/2019 Advanced Java Book

    125/299

    Servlet Programming

    Comp-U-Learn 115

    Servlet Life Cycle

    Init and Destroy Methods

    init()

    When the server starts

    When the servlet is first requested, just before the service() method is invoked.

    At the request of the server administrator.

    public void init(ServletConfig config) throws ServletException;

  • 7/25/2019 Advanced Java Book

    126/299

    Advanced Java Programming

    Comp-U-Learn116

    destroy()

    public void destroy();

    Service Method

    public void service(ServletRequest req, ServletResponse res)throws ServletException, IOException;

    Example 5.3:

    import javax.servlet.*;import javax.servlet.http.*;

    import java.io.*;import java.util.*;

    public class ex2 extends HttpServlet{ public void init(ServletConfig config) throws ServletException {

  • 7/25/2019 Advanced Java Book

    127/299

    Servlet Programming

    Comp-U-Learn 117

    // Always pass the ServletConfig object to the super class super.init(config);}

    //Process the HTTP Get request public void doGet(HttpServletRequest request,

    HttpServletResponse response) throws ServletException, IOException{ response.setContentType(text/html);

    PrintWriter out = response.getWriter(); out.println(); out.println(BasicServlet); out.println();

    // Prints the REQUEST_METHOD sent by the client out.println(Your request method was + request.getMethod() + \n); out.println(); out.close(); }//Process the HTTP Post request public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(text/html); PrintWriter out = response.getWriter(); out.println(); out.println(BasicServlet); out.println();// Prints the REQUEST_METHOD sent by the client

    out.println(Your request method was + request.getMethod() + \n); out.println(); out.close(); }

    //Get Servlet information

    public String getServletInfo() { return BasicServlet Information; }}

  • 7/25/2019 Advanced Java Book

    128/299

    Advanced Java Programming

    Comp-U-Learn118

    Fig. 5.6

    Life Cycle of Servlet



    Press Submit Button to invoke your method



  • 7/25/2019 Advanced Java Book

    129/299

    Servlet Programming

    Comp-U-Learn 119

    Fig. 5.7

    SummaryIn this session we learnt about Java Servlets basics, usage of servlets, servlets

    alternatives and the basic architecture of Java Servlets. Then experienced withwriting a simple servlet and running the servlet. We also learnt how the servlets are

    performed behind the HTML code. At the end of the session we learnt about the life

    cycle of the Java Servlets and its methods.

    Going Over it Again

    I. Fill in the Blanks

  • 7/25/2019 Advanced Java Book

    130/299

    Advanced Java Programming

    Comp-U-Learn120

    I. State True or False

    III. One line Answers

  • 7/25/2019 Advanced Java Book

    131/299

    Session 6

    More on Servlets

    On Completion of this Session you will be able to understand...

    Server & Client

    Servlet Chaining

    HTML Generation

    Servlet in a Middle Tier

  • 7/25/2019 Advanced Java Book

    132/299

    In This Session...

    The Server

    The Client

    The Request

    Servlet Chaining

    HTML Generation

    Building HTML Packages

    HTML Object

    HTML Document

    HTML Elements

    HTML Form

    Using HTML Package

    Servlet- A Middle Tier

  • 7/25/2019 Advanced Java Book

    133/299

    More on Servlet

    Comp-U-Learn 123

    The Server

    public string ServletRequest.getServerName()public int ServletRequest.getServerPort()

    public string ServletContext.getServerInfo()public object ServletContext.getAttribute()

    String str = getServletContext().getServerInfo()

    Example 6.1:

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

    public class ex1 extends GenericServlet{

  • 7/25/2019 Advanced Java Book

    134/299

    Advanced Java Programming

    Comp-U-Learn124

    public void service(ServletRequest req, ServletResponse res)throws ServletException,IOException{res.setContentType(text/plain);PrintWriter out= res.getWriter();

    out.println(Server Host Name: +req.getServerName());out.println(ServerPort: +req.getServerPort());out.println(Servlet Context: +getServletContext().getServerInfo());

    }

    }

    Fig. 6.1

    The Client

  • 7/25/2019 Advanced Java Book

    135/299

    More on Servlet

    Comp-U-Learn 125

    public String ServletRequest.getRemoteAddr()public String ServletRequest.getRemostHost()

    InetAddress add = InetAddress.getByName(req.getRemoteAddr())

    public String HttpServletRequest.getRemoteUser()

    The Request

    public String ServletRequest.getParameter(String name)public String[] ServletRequest.getParameterVales(String name)

  • 7/25/2019 Advanced Java Book

    136/299

    Advanced Java Programming

    Comp-U-Learn126

    Example 6.2:

    import java.io.*;import java.util.*;import javax.servlet.*;import javax.servlet.http.*;public class ex2 extends HttpServlet{

    public void doGet(HttpServletRequest req, HttpServletResponseres)throws ServletException,IOException{res.setContentType(text/plain);PrintWriter out= res.getWriter();

    out.println(Query String...);out.println(req.getQueryString());out.println(The file \ + req.getPathInfo()+\);out.println(Is stored at \ + req.getPathTranslated()+\);}}

    Fig. 6.2

  • 7/25/2019 Advanced Java Book

    137/299

    More on Servlet

    Comp-U-Learn 127

    http://205.166.22.74/servlets/ex2?parameter1

    Fig. 6.3

    Note

    When giving any URL there should not be a space. Also the ? symbolseparates the file name from the parameters. If we want to give more than one

    parameter, we can pass a number of parameters concatenating with + symbol.

    For example,

    Servlet Chaining

  • 7/25/2019 Advanced Java Book

    138/299

    Advanced Java Programming

    Comp-U-Learn128

    Server

    Servlet1

    Servlet2

    Servlet3

    Request

    Response

    Fig. 6.4

    By using the servlets we can quickly change the appearance of a page or a groupof pages, or type of content.

    We can take a kernal of content and display it in special formats.

    It also support esoteric data types

    They handle the content of the future, so we dont have to run our script every

    time new content is added.

    Example 6.3:

    import java.io.*;

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

    public class ex3 extends HttpServlet{

  • 7/25/2019 Advanced Java Book

    139/299

    More on Servlet

    Comp-U-Learn 129

    public void doGet(HttpServletRequest req, HttpServletResponseres)throws ServletException,IOException

    {String contentType=req.getContentType();

    if(contentType==null)return;res.setContentType(contentType);PrintWriter out= res.getWriter();BufferedReader in= req.getReader();String line=null;

    while((line= in.readLine())!=null){line=replace(line,, );line=replace(line,, );out.println(line);}

    }

    public void doPost(HttpServletRequest req, HttpServletResponseres)throws ServletException,IOException{doGet(req,res);}

    private String replace(String ln, String old, String news){int id=0;while((id=ln.indexOf(old, id))>=0)

    {ln=ln.substring(0,id)+ news + ln.substring(id+old.length());id+=news.length();}return ln;}}

    HTML Generation

  • 7/25/2019 Advanced Java Book

    140/299

    Advanced Java Programming

    Comp-U-Learn130

    Building HTML Packages

    HTMLObject

    Example 6.4:

    package HTML;import java.util.Vector;public abstract class HTMLObject{protected Vector htmlObjects = null; // Static Alignment values public static final int LEFT = 0; public static final int CENTER = 1; public static final int RIGHT = 2; // Set the objects initial alignment to LEFT private int alignment = LEFT; // This abstract method forces all derived classes to

  • 7/25/2019 Advanced Java Book

    141/299

    More on Servlet

    Comp-U-Learn 131

    // implement the toHTML() method. The toHTML() method // should return the HTML String necessary to // display this object in its current state. public abstract String toHTML(); // Constructor public HTMLObject() {

    // Default size of HTMLObject vector htmlObjects = new Vector(5); } // Add a HTMLObject public void addObject( HTMLObject value) { if ( value != null ) { htmlObjects.addElement(value); } } // Remove a HTMLObject, if the element is removed // successfully, returns true public boolean removeObject( HTMLObject value) { if ( value != null ) {

    return htmlObjects.removeElement(value); } return false; } // Set the objects Alignment public void setAlignment(int value) { if ( value >= LEFT && value

  • 7/25/2019 Advanced Java Book

    142/299

    Advanced Java Programming

    Comp-U-Learn132

    private String backgroundColor = new String(); private String textColor = new String(); private String linkColor = new String(); private String vlink = new String(); private String alink = new String(); // Default Constructor

    public HTMLDocument() { } // Constructor with title public HTMLDocument(String value) { title = value; } // Set the document Title public void setTitle(String value) { if ( value != null ) { title = value; } } // Get the document Title

    public String getTitle() { return title; } // Set the document Background Image public void setBackgroundImage(String value) { if ( value != null ) { backgroundImage = value; } } // Get the document Background Image public String getBackgroundImage() { return backgroundImage; }

    // Set the document Background Color public void setBackgroundColor( String value) { if ( value != null ) { backgroundColor = value; } } // Get the document Background Color public String getBackgroundColor() { return backgroundColor; } // Set the document Text Color public void setTextColor(String value) {

    if ( value != null ) { textColor = value; } } // Get the document Text Color public String getTextColor() { return textColor;

  • 7/25/2019 Advanced Java Book

    143/299

    More on Servlet

    Comp-U-Learn 133

    } // Set the document Link Color public void setLinkColor(String value) { if ( value != null ) { linkColor = value; }

    } // Get the document Link Color public String getLinkColor() { return linkColor; } } // Return String containing the HTML formatted document public String toHTML() { String document = new String(\n); document = document.concat( + title + \n\n 0 ) { document = document.concat(BACKGROUND=\ +

    backgroundImage + \ ); } String color = getBackgroundColor(); if ( color.length() > 0 ) { document = document.concat(BGCOLOR=\ + color + \ ); } String textColor = getTextColor(); if ( textColor.length() > 0 ) { document = document.concat(TEXT=\ + textColor + \ ); } if ( linkColor.length() > 0 ) {

    document = document.concat(LINK=\ + linkColor + \ ); } if ( vlink.length() > 0 ) { document = document.concat(VLINK=\ + vlink + \ ); } if ( alink.length() > 0 ) { document = document.concat(ALINK=\ + alink + \ ); } document = document.concat(>\n); // Iterate through all objects in the htmlObjects Vector for ( int x = 0; x < htmlObjects.size(); x ++ ) { try {

    document = document.concat( ((HTMLObject)htmlObjects.elementAt(x)).toHTML() + \n); } catch (ArrayIndexOutOfBoundsException ex) { // This will only log the error to stderr

  • 7/25/2019 Advanced Java Book

    144/299

    Advanced Java Programming

    Comp-U-Learn134

    System.err.println(ex.getMessage()); } catch (Exception ex) { // This will only log the error to stderr System.err.println(ex.getMessage()); }

    } // Then close the document document = document.concat(\n\n\n); return document; }}

    HTML Elements

    HTMLText

    Example 6.6:

    package HTML;public class HTMLText extends HTMLObject { private String text = new String(); private boolean bold = false;

    private boolean italic = false; private boolean underline = false; private boolean center = false; // Default Contructor public HTMLText() { } // Constructor initialized with Text value public HTMLText(String value) { if ( value != null ) { text = value; } } // Set the text value

    public void setText(String value) { if ( value != null ) { text = value; } } // Get the current text value public String getText() {

  • 7/25/2019 Advanced Java Book

    145/299

    More on Servlet

    Comp-U-Learn 135

    return text; } // Set Text Bold to true/false public void setBold(boolean value) { bold = value; }

    // Returns True if Bold is on public boolean isBold() { return bold; } // Set Text Italic to true/false public void setItalic( boolean value) { italic = value; } // Returns True if Italic is on public boolean isItalic() { return italic; } // Set Text Underline to true/false

    public void setUnderline( boolean value) { underline = value; } // Returns True if Underline is on public boolean isUnderline() { return underline; } // Set Text Center to true/false public void setCenter( boolean value) { center = value; } // Returns True if Center is on public boolean isCenter() {

    return center; } // Set Text Preformatted to true/false // Return String containing the HTML formatted Text public String toHTML() { String html = new String (text); if ( isBold() ) { html = ( + html + ); } if ( isItalic() ) { html = ( + html + ); } if ( isUnderline() ) {

    html = ( + html + ); } if ( isCenter() ) { html = ( + html + ); } if ( isPreformatted() ) { html = ( + html + );

  • 7/25/2019 Advanced Java Book

    146/299

    Advanced Java Programming

    Comp-U-Learn136

    } return html; }}

    HTMLHeading

    Example 6.7:

    package HTML;public class HTMLHeading extends HTMLObject { private String text = new String(); private int heading; public static final int H1 = 1;

    public static final int H2 = 2; public static final int H3 = 3; public static final int H4 = 4; public static final int H5 = 5; public static final int H6 = 6; // Constructor that initializes Heading Level to H1 public HTMLHeading() { heading = H1; } // Constructor that sets the initial Heading Text and Level public HTMLHeading(String txt, int head) { if ( txt != null ) { text = txt; } if ( head >= H1 && head = H1 && value

  • 7/25/2019 Advanced Java Book

    147/299

    More on Servlet

    Comp-U-Learn 137

    // Get Heading Level public int getHeadingLevel() { return heading; } // Return String containing the HTML formatted Heading public String toHTML() {

    String html = new String( + text + );

    return html; }}

    HTMLLineBreak

    Example 6.8:

    package HTML;public class HTMLLineBreak extends HTMLObject{ // Default Constructor public HTMLLineBreak() { } // Return String containing the HTML formatted Line Break public String toHTML() { return new String(
    ); }}

    HTMLInput

  • 7/25/2019 Advanced Java Book

    148/299

    Advanced Java Programming

    Comp-U-Learn138

    Example 6.9:

    package HTML;

    public class HTMLInput extends HTMLObject { protected String type = new String(); protected String name = new String(); protected String input_value = new String(); protected String attributes = new String(); // Default Constructor public HTMLInput() { } // Set the Input Type protected void setType(String value) { if ( value != null ) { type = value; }

    } // Get the Input Type public String getType() { return type; } // Set the Input Name public void setName(String value) { if ( value != null ) { name = value; } } // Get the Input Name public String getName() {

    return name; } // Set the value of the Input Object public void setValue(String value) { if ( value != null ) { input_value = value; } } // Get the value of the Input Object public String getValue() { return input_value; } // Set the additional attributes string // This will be used to specialize an input type protected void setAttributes(String value) { if ( value != null ) { attributes = value; } } // Get the additional attributes string

  • 7/25/2019 Advanced Java Book

    149/299

    More on Servlet

    Comp-U-Learn 139

    public String getAttributes() { return attributes; } // Return String containing the HTML formatted Input public String toHTML() { String html = new String( 0 ) { html = html.concat( VALUE=\ + input_value + \); } // If there is any additional attributes if ( attributes != null ) { html = html.concat(attributes); } // Ending Character html = html.concat(>); return html; }

    }

    HTMLInput Object

    Example 6.10:

    package HTML;

    public class HTMLTextInput extends HTMLInput { private int size = -1; private int maxlength = -1; // Default Constructor public HTMLTextInput() { // Set the Input Type setType(TEXT); } // Set the Input Size public void setSize(int value) { if ( value > -1 ) { size = value; }

    } // Get the Input Size public int getSize() { return size; } // Set the Maximum Length public void setMaxLength(int value) {

  • 7/25/2019 Advanced Java Book

    150/299

    Advanced Java Programming

    Comp-U-Learn140

    if ( value > -1 ) { maxlength = value; } } // Get the Maximum Length public int getMaxLength() {

    return maxlength; } // Return String containing the HTML formatted Text Input public String toHTML() { String html = new String(); if ( size > -1 ) { html = html.concat( SIZE= + size); } if ( maxlength > -1 ) { html = html.concat( MAXLENGTH= + maxlength); } setAttributes(html); return super.toHTML();

    }}

    HTMLForm

    Example 6.11:

    package HTML;import java.util.*;public class HTMLForm extends HTMLObject { private String action = new String(); private boolean post_method = false; private String enctype = new String (text/html); // Default Constructor public HTMLForm() { } // Set the action public void setAction( String value) { if ( value != null ) { action = value;

    } } // Get the action public String getAction() { return action; } // Set the POST method to true/false

  • 7/25/2019 Advanced Java Book

    151/299

    More on Servlet

    Comp-U-Learn 141

    public void setPostMethod( boolean value) {

    post_method = value;

    }

    // return true if POST, otherwise false

    public boolean isPostMethod() {

    return post_method; }

    // Set the ENCTYPE, ie. text/html

    public void setEnctype( String value) {

    if ( value != null ) {

    enctype = value;

    }

    }

    // Get the ENCTYPE

    public String getEnctype() {

    return enctype;

    }

    // Return String containing the HTML formatted Form public String toHTML() {

    String html = new String(\n); // adding HTMLInputs

    for ( int x = 0; x < htmlObjects.size(); x++ ) {

    try {

    html = html.concat(

    ((HTMLObject)htmlObjects.elementAt(x)).toHTML() +

    \n);

    }

    catch (Exception ex) {

    // Print exception to stderr

    System.err.println(ex.getMessage());

    }

    } html = html.concat(\n);

    return html;

    }

    }

  • 7/25/2019 Advanced Java Book

    152/299

    Advanced Java Programming

    Comp-U-Learn142

    Using HTML Package

    Example 6.12:

    import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;import HTML.*;public class expack extends HttpServlet {

    public void init(ServletConfig config) throws ServletException{ super.init(config); } //Process the HTTP Get request public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(text/html); PrintWriter out = response.getWriter(); HTMLDocument document = new HTMLDocument(New Customer Account); // Create the New Customer Account Form HTMLForm form = new HTMLForm(); form.setAction(/servlet/NewCustomerServlet); form.setPostMethod(true); // Add the Heading HTMLHeading heading = new HTMLHeading(Customer Account, HTMLHeading.H2); heading.setAlignment(HTMLObject.CENTER); form.addObject(heading); // Add the Name form.addObject(new HTMLText(Name : )); HTMLTextInput textinput = new HTMLTextInput(); textinput.setName(name); textinput.setSize(30); form.addObject(textinput);

    form.addObject(new HTMLLineBreak());

    // Add the Email form.addObject(new HTMLText(Email Address : ));

    textinput = new HTMLTextInput();

    textinput.setName(email);

    textinput.setSize(30);

  • 7/25/2019 Advanced Java Book

    153/299

    More on Servlet

    Comp-U-Learn 143

    form.addObject(textinput);

    form.addObject(new HTMLLineBreak());

    // Add the Billing Address

    form.addObject(new HTMLHeading(Billing Address,

    HTMLHeading.H4));

    form.addObject(new HTMLText(Street : )); textinput = new HTMLTextInput();

    textinput.setName(street);

    textinput.setSize(30);

    form.addObject(textinput);

    form.addObject(new HTMLLineBreak());

    // Add the City, State, Zip

    // City

    form.addObject(new HTMLText(City ));

    textinput = new HTMLTextInput();

    textinput.setName(city);

    textinput.setSize(30); form.addObject(textinput);

    // State

    form.addObject(new HTMLText(State ));

    textinput = new HTMLTextInput();

    textinput.setName(state);

    textinput.setSize(2);

    textinput.setMaxLength(2);

    form.addObject(textinput);

    // Zip

    form.addObject(new HTMLText(Zip )); textinput = new HTMLTextInput();

    textinput.setName(zip);

    textinput.setSize(5);

    textinput.setMaxLength(5);

    form.addObject(textinput);

    form.addObject(new HTMLLineBreak());

    document.addObject(form);

    // document string sent back in response

    out.println(document.toHTML());

    out.close();

    }

    //Get Servlet information

    public String getServletInfo() {

    return NewCustomerServlet Information;

    }

    }

  • 7/25/2019 Advanced Java Book

    154/299

    Advanced Java Programming

    Comp-U-Learn144

    Fig. 6.5

    Servlet A Middle Tier

  • 7/25/2019 Advanced Java Book

    155/299

    More on Servlet

    Comp-U-Learn 145

    Example 6.13:

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

    public class db extends HttpServlet{

    public void doPost(HttpServletRequest req, HttpServletResponseres)throws ServletException, IOException{res.setContentType(text/html);PrintWriter out=res.getWriter();

    Connection con=null;

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

    con=DriverManager.getConnection(jdbc:odbc:srt,scott,tiger);

    con.setAutoCommit(false);

    Statement s=con.createStatement();s.executeUpdate(update emp set eno=40 where ename=John);

    con.commit();out.println(Update Successful!);}catch(Exception e){

    try{

    con.rollback();}

    catch(SQLException ie){}out.println(Could not Upadate!);}

    finally{

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

    }}

  • 7/25/2019 Advanced Java Book

    156/299

    Advanced Java Programming

    Comp-U-Learn146

    SummaryIn this session we covered a lot of information related to servlets. We looked at

    how the server and the client works in relation to the servlets. Also we looked at

    servlet chaining. We created an HTML package that encapsulates basic HTML.

    By now we should have an in-depth understanding of how to use the HTMLpackage we created. At the end of this session we learnt about the usage of the

    servlet in database programming.

    Going Over it Again

    I. Fill in the Blanks

    II. State True or False

    III. One line Answers

    5. What is the use of the getAttribute() method?

  • 7/25/2019 Advanced Java Book

    157/299

    Session 7

    Java Stored Procedures

    On Completion of this Session you will be able to understand...

    Overview of Java Stored Procedures

    Usage of JDBC and SQLJ

    Build an ApplicationSub Programs in SQLJ

    Relationship of SQLJ to Embedded SQL

  • 7/25/2019 Advanced Java Book

    158/299

    In This Session...

    Java Stored Procedures - An Overview

    Goal for Designing SQLJ

    SQLJ Variables

    JDBC OCI Driver

    When to Use JDBC and When to Use SQLJ?

    SQL appears in Java Statements

    Building an Application

    Sub Programs in SQLJ

    Calling Stored Procedures

    Calling Stored Functions

    Relationship of SQLJ to Embedded SQL

    Advantages of SQLJ over JDBC

  • 7/25/2019 Advanced Java Book

    159/299

    Java Stored Procedures

    Comp-U-Learn 149

    Java Stored Procedures An Overview

    Connection conn = new OracleDriver().defaultConnection();

    C:\sqlj\demo>Loadjava

  • 7/25/2019 Advanced Java Book

    160/299

    Advanced Java Programming

    Comp-U-Learn150

    Two Components of SQLJ

    Translator

    Runtime

    Translator

    Runtime

  • 7/25/2019 Advanced Java Book

    161/299

    Java Stored Procedures

    Comp-U-Learn 151

    Java Source Code with Embedded

    Java Source Cod e with calls to JD BC

    Java Byte Cod e with calls to JDBC

    JDBC Dr iver

    Databases

    SQLJ Translator

    Java Compiler

    SQLJ Source

    Java Source

    Java Executable

    Java Executable

    Fig. 7.1

    Requirements for SQLJ

    JDBC driver implementing the standard java.sql JDBC interfaces from SunMicrosystems

    Oracle SQLJ works with any standards-compliant JDBC driver.

    Database system that is accessible using your JDBC driver

    Class files for the SQLJ translator, SQLJ profile customizer, and SQLJ runtime

  • 7/25/2019 Advanced Java Book

    162/299

    Advanced Java Programming

    Comp-U-Learn152

    JDK1.1.7 Version of Java to Execute the SQLJ Converted Java Programs, OracleJDBC drivers for version 8.1.5 do not support the JDK 1.2.

    Fig. 7.2

    Goal for Desiging SQLJ

  • 7/25/2019 Advanced Java Book

    163/299

    Java Stored Procedures

    Comp-U-Learn 153

    Standard Embedded SQL

    Brevity

    Type Checking

    Schema Checking

    Autonomous Development

    Location Transparency

  • 7/25/2019 Advanced Java Book

    164/299

    Advanced Java Programming

    Comp-U-Learn154

    Portability

    Generality

    Optimization of SQL

    Database Stored Programs

    Component Software

    Consistency with Java

  • 7/25/2019 Advanced Java Book

    165/299

    Java Stored Procedures

    Comp-U-Learn 155

    Java has automatic storage management (garbage collection) that simplifies themanagement of storage for data retrieved from databases.

    All Java types representing composite data, and data of varying sizes, have adistinguished value null, which can be used to represent the SQL NULL state,

    giving Java programs an alternative to NULL indicators, which are a fixture ofother host languages.

    Java is designed to support programs that are automatically heterogeneouslyportable (also called super-portable or simply downloadable). That, along

    with Javas type system of classes and interfaces, enables component software.

    In particular, a SQLJ translator, written in Java, can call components that are

    specialized by database vendors, in order to leverage the existing schema-

    checking and type-checking capabilities of databases, and to generate code

    optimized for particular databases.

    Java is designed for binary portability in heterogeneous networks, which

    promises to enable binary portability for database applications that use staticSQL.

    Availability of Development Tools

    Tracing

    Debugging

    Specification of breakpoints

    Automatic code formatting

    Code analysis and highlighting

    Automatic regeneration of byte codes

    Usage Scenarios

    Low Level: This is Embedded SQL as 3GL developers know it today. This levelhas a loose integration with the type system of the host language. Programming

    tools, such as visual or syntax-directed tools, are likely to generate Java code

    containing static SQL at this level, because the generated code is correct by

    construction as generated from a tools model of the relationships among the

    data.

  • 7/25/2019 Advanced Java Book

    166/299

    Advanced Java Programming

    Comp-U-Learn156

    Middle Level: Human programmers use this level when they write SQLJ codedirectly. Tight, concise integration of the SQL and Java constructs and type

    systems help programmers avoid and detect errors in their programs.

    High Level: At this level, programmers use graphical tools to constrain and

    compose their programs. Those tools will generate Java programs containingstatic SQL. Those generated programs may contain low-level Embedded SQL

    because they are correct by construction.

    SQLJ Variables

    SQLJ Data Type Java Data Type

    Char String

    Varchar String

    LongVarchar String

    Numeric java.math.BigDecimal

    Decimal java.math.BigDecimal

    Bit boolean

    TinyInt byte

    SmallInt Short

    Integer int

    BigInt longReal float

    Float double

    Double double

    Binary byte[ ]

    VarBinary byte[ ]

    LongVarBinary byte[ ]

    Date java.sql.Date

    Time java.sql.Time

    Timestamp java.sql.Timestamp

  • 7/25/2019 Advanced Java Book

    167/299

    Java Stored Procedures

    Comp-U-Learn 157

    class First{ public static void main(String args[]) { int Value; Var=100;

    System.out.println(Content of Variable Value is +Value); }}

    The keyword class is used to define the class with the name First, within the classwe can declare the methods(Procedures & Functions).

    main() program is declared as public to make it visible to the entire class.

    static declaration is used because it cannot be instantiated

    void indicates that main does not return the value.

    Variable args is declared so that the main function can take command linearguments. This array holds string values.

    NoteAll the variables and syntaxes are case sensitive, which means class is not equivalent

    to Class and VALUE is not equivalent to Value.

    JDBC OCI Driver

  • 7/25/2019 Advanced Java Book

    168/299

    Advanced Java Programming

    Comp-U-Learn158

    import java.sql.SQLException;import java.sql.DriverManager;import java.sql.Driver;import java.sql.Connection;import sqlj.runtime.ref.DefaultContext ;

    public class ConnectionManager {

    static public String DRIVER = null ;static public String DBURL = null ;static public String UID = null ;static public String PWD = null ;static {

    DRIVER = oracle.jdbc.driver.OracleDriver ; DBURL = jdbc:oracle:oci8:@Database_Name ; UID = ritchie ; PWD = ritchie ; }

    static public Connection newConnection() { Connection conn = null;

    if (UID== null || PWD==null || DBURL==null || DRIVER==null) {

    System.err.println ( Please edit the ConnectionManager.java file to assign + non-null values to the static string variables + DBURL, DRIVER, UID, and PWD. Then recompile and tryagain. ) ; System.exit(1) ; }

    try { Driver d = (Driver)(Class.forName( DRIVER ).newInstance()); DriverManager.registerDriver(d); } catch (Exception e) {

    System.err.println( Could not load driver: + DRIVER ) ; System.err.println(e) ; System.exit(1) ; } try {

    conn = DriverManager.getConnection (DBURL, UID, PWD);

    } catch (SQLException exception) {

  • 7/25/2019 Advanced Java Book

    169/299

    Java Stored Procedures

    Comp-U-Learn 159

    System.out.println(Error: could not get a connection);

    System.err.println(exception) ;

    System.exit(1);

    }

    return conn;

    }

    static public DefaultContext initContext()

    {

    DefaultContext ctx = DefaultContext.getDefaultContext();

    if (ctx == null) {

    try {

    ctx = new DefaultContext(newConnection());

    } catch (SQLException e) {

    System.out.println(Error: could not get a default context);

    System.err.println(e) ;

    System.exit(1);

    }

    DefaultContext.setDefaultContext(ctx);

    }

    return ctx;

    }

    }

    C:\>javac ConnectionManager.java

  • 7/25/2019 Advanced Java Book

    170/299

    Advanced Java Programming

    Comp-U-Learn160

    When to Use JDBC and When to Use SQLJ ?

    To check program for errors at translation-time rather than at run-time.

    To write an application that can deploy to another database. SQLJ can customizethe static SQL

    For database at deployment-time.

    While Working with a database that contains compiled SQL.

    To use dynamic SQL.

    To have a SQLJ layer during deployment or development.

    Three Kinds of SQLJ clauses

    #sql iterator iterator_classname (type declarations);

    #sql public iterator EmpIterator (String job, double Comm);

  • 7/25/2019 Advanced Java Book

    171/299

    Java Stored Procedures

    Comp-U-Learn 161

    Example for positional Iterator

    #sql public iterator EmpIterator (String, double);

    #sql context context_classname;

    Example

    #sql context TestContext;

    Executable clauses

    Statementclause == #sql [connection] [statement]

    #sql {Select EmpNo, Ename, Sal into :Eno, :En, :Salary From Emp};

    #sql [connection] var ={SQL statement or Function };

    Iterator java_var#sql x={ Select Ename, job, sal from Emp where Sal > 1000};

  • 7/25/2019 Advanced Java Book

    172/299

    Advanced Java Programming

    Comp-U-Learn162

    FETCH iterator_name into :variable1, :variable2,:variable3..........(: should used before the variable)Where variable1, variable2, variable3..........

    SQL appears in Java statements

    SQL procedure statement

    SQL dynamic statement

  • 7/25/2019 Advanced Java Book

    173/299

    Java Stored Procedures

    Comp-U-Learn 163

    SQL connection statement

    Host variable definition

  • 7/25/2019 Advanced Java Book

    174/299

    Advanced Java Programming

    Comp-U-Learn164

    SQL92 character sets

    Embedded exception declaration

    EXEC SQL WHENEVER exception-conditionGOTOprogram-label;EXEC SQL WHENEVER exception-conditionCONTINUE;

  • 7/25/2019 Advanced Java Book

    175/299

    Java Stored Procedures

    Comp-U-Learn 165

    try block-that-may-throw-exception-e catch (Exception e) block-that-handles-exception-e

    SQL diagnostics statement

    Declare cursor

    Input parameters to SQL statements

    Extracting column-values from result-sets

    EXEC SQL FETCH cursor1 INTO :var1,:var2,:var3;

  • 7/25/2019 Advanced Java Book

    176/299

    Advanced Java Programming

    Comp-U-Learn166

    OPEN cursor

    EXEC SQL OPEN cursor1;

    Build an Application

  • 7/25/2019 Advanced Java Book

    177/299

    Java Stored Procedures

    Comp-U-Learn 167

    import java.lang.*;import java.sql.SQLException;public class Server{public static void main(String args[]){try{String msg=Java Class Available in User_Objects Schema Table;#sql { Call Dbms_Output.put_line(:msg) };}catch(SQLException e) { System.out.println(e.getMessage()); }

    }

    Fig. 7.3

  • 7/25/2019 Advanced Java Book

    178/299

    Advanced Java Programming

    Comp-U-Learn168

    Fig. 7.4

    import java.sql.*;import java.sql.SQLException;

    public class Objects{public static void main(String args[]){String msg=null;try{#sql { Create table Dept(DeptNo Number(2) Constraint Dept_prim Primary key,Dname varchar2(20) Unique,

    Loc Varchar2(20)) };msg=Dept table is Created;#sql { Call DBMS_OUTPUT.PUT_LINE ( :msg ) };#sql { Create table Emp (EmpNo Number(4) Constraint Emp_prim Primary key,Ename varchar2(20) Unique,Sal Number(10,2),Comm Number(10,2),Mgr Number(4),Job Varchar2(20),HireDate date,

    DeptNo number(2) Not null Constraint dept_Emp referencesDept(DeptNo)) };msg=Emp table is Created;#sql { Call Dbms_Output.put_line (:msg) };

  • 7/25/2019 Advanced Java Book

    179/299

    Java Stored Procedures

    Comp-U-Learn 169

    #sql { Create table SalGrade ( Grade Number(2), LoSal Number(10,2), HiSal Number(10,2) ) };

    msg=SalGrade table is Created;#sql { Call Dbms_Output.put_line (:msg) };

    #sql { Create table Bonus ( Ename Varchar2(20) Unique references Emp(Ename), Job Varchar2(20), Sal Number(10,2), Comm Number(10,2)

    ) };msg=Bonus table is Created;#sql { Call Dbms_Output.put_line (:msg) };}catch(SQLException e) { System.out.println(Error due to + e);

    }}}

    Fig. 7.5

  • 7/25/2019 Advanced Java Book

    180/299

    Advanced Java Programming

    Comp-U-Learn170

    Fig. 7.5

    Create Table Command

    import java.sql.*;public class SQLTable

    { public static void main(String args[]) { try { ConnectionManager.initContext(); SQLTable C=new SQLTable(); C.Create(); } catch(SQLException e) { System.out.println (Error in your program); System.err.println(Error Description is + e); } }void Create() throws SQLException{ #sql { CREATE TABLE DEPT

  • 7/25/2019 Advanced Java Book

    181/299

    Java Stored Procedures

    Comp-U-Learn 171

    ( DeptNo Number(3) Constraint Dept_prim Primary Key, Dname Varchar2(20) Not Null, Loc Varchar2(20) ) };

    System.out.println(Table Created);}}

    Open DOS prompt from start->Run->Command and goto the specified directoryC:\Sqlj\Demo.

    Compile the sqlj program using sqljc SQLTable.sqlj

    Once the program is compiled successfully, file with the same name but with.java (SQLTable.java) extension will be created.

    Compile the .java file using java compiler javac SQLTable.java Once the program is compiled a file with the same name .class(SQLTable.class)

    extension will be created and this is the executable file for SQLJ programs.

    Execute the file using java SQLTable command.

    Fig. 7.5

  • 7/25/2019 Advanced Java Book

    182/299

    Advanced Java Programming

    Comp-U-Learn172

    Alter Table Command

    import java.sql.*;public class SQLAlterTable{ public static void main(String args[]) { try { ConnectionManager.initContext(); SQLAlterTable C=new SQLAlterTable();

    C.Alter(); } catch(SQLException e) { System.out.println (Error in your program); System.err.println(Error Description is + e); } }void Alter() throws SQLException{ #sql { ALTER TABLE DEPT

    Modify Loc Varchar2(30) }; System.out.println(Table Dept Altered);}}

  • 7/25/2019 Advanced Java Book

    183/299

    Java Stored Procedures

    Comp-U-Learn 173

    C:\sqlj\demo>sqljc SQLAlterTable.sqlj

    C:\sqlj\demo>javac SQLAlterTable.java

    C:\sqlj\demo>java SQLAlterTableTable Dept altered

    C:\sqlj\demo>

    Rename Command

    import java.sql.*;public class SQLRenameTable{ public static void main(String args[]) { try { ConnectionManager.initContext(); SQLRenameTable C=new SQLRenameTable(); C.Rename(); } catch(SQLException e) { System.out.println (Error in your program); System.err.println(Error Description is + e); } }void Rename() throws SQLException{

    #sql { Rename Dept To Department };System.out.println(Table Dept is Renamed to Department);}}

  • 7/25/2019 Advanced Java Book

    184/299

    Advanced Java Programming

    Comp-U-Learn174

    C:\sqlj\demo>sqljc SQLRenameTable.sqlj

    C:\sqlj\demo>javac SQLRenameTable.java

    C:\sqlj\demo>java SQLRenameTableTable Dept is Renamed to Department

    C:\sqlj\demo>

    Drop Table Command

    import java.sql.*;

    public class SQLDropTable{ public static void main(String args[]) { try { ConnectionManager.initContext();

  • 7/25/2019 Advanced Java Book

    185/299

    Java Stored Procedures

    Comp-U-Learn 175

    SQLDropTable C=new SQLDropTable(); C.Drop(); } catch(SQLException e) { System.out.println (Error in your program);

    System.err.println(Error Description is + e); } }void Drop() throws SQLException{ #sql { DROP TABLE DEPT };System.out.println(Table Dept Dropped);}}

    C:\sqlj\demo>sqljc SQLDropTable.sqlj

    C:\sqlj\demo>javac SQLDropTable.java

    C:\sqlj\demo>java SQLDropTable

    Table Dept Dropped

    C:\sqlj\demo>The table is now dropped.

  • 7/25/2019 Advanced Java Book

    186/299

    Advanced Java Programming

    Comp-U-Learn176

    Sub Programs in SQLJ

    connect internal;

    create or replace package sqljutl as function has_default(oid number,

    proc char, seq number, ovr number) return number;end sqljutl;/create or replace package body sqljutl is function has_default(oid number, proc char, seq number, ovr number) return number is def number; begin if proc IS NULL

    then select DEFAULT# INTO def FROM ARGUMENT$ WHERE PROCEDURE$ IS NULL AND OBJ# = oid AND SEQUENCE# = seq AND OVERLOAD# = ovr; else select DEFAULT# INTO def FROM ARGUMENT$ WHERE PROCEDURE$ = proc AND OBJ# = oid AND SEQUENCE# = seq AND OVERLOAD# = ovr; end if;

    if def IS NULL then return 0; else return 1; end if; end has_default;end sqljutl;/

    grant execute on sqljutl to public ;

  • 7/25/2019 Advanced Java Book

    187/299

    Java Stored Procedures

    Comp-U-Learn 177

    Calling Stored Procedures

    #sql { CALL Procedure_Name() };

    Create or Replace procedure SalaryIncrement(Emp_No

    Emp.Empno%type Default 7788,Salary Emp.Sal%type) as

    Emp_sal Emp.Sal%type;

    NoSalary Exception;

    Tot_Sal Emp.Sal%type;

    Begin

    Select Sal into Emp_sal from emp where Empno=Emp_no;

    if Emp_sal is Null then

    Raise NoSalary;

    else

    Update Emp set sal =Sal+Salary where Empno=Emp_no;

    Tot_sal:=Emp_sal + Salary;

    Dbms_output.put_line(Salary updated from || Emp_sal || to

    || Tot_sal || for employee number || Emp_No);

    end if;

    Exception

    when NoSalary then

    Dbms_output.put_line(Salary does not exists for employee ||

    Emp_No);

    When No_Data_found then

    Dbms_output.put_line(No Employee exists with the Number ||

    Emp_No);

    End;

    Procedure created.

  • 7/25/2019 Advanced Java Book

    188/299

    Advanced Java Programming

    Comp-U-Learn178

    import java.sql.*;public class ProcedureCall{

    public static void main(String args[]) { try { ConnectionManager.initContext(); ProcedureCall P=new ProcedureCall(); P.Proc(); } catch(SQLException e) { System.out.println(Error in program!); System.out.println(Due to + e); } }

    void Proc() throws SQLException { #sql { CALL SalaryIncrement(7788,2000) }; System.out.println(Salary is Increment for Employee 7788 by 2000"); }}

    C:\sqlj\demo>sqljc ProcedureCall.sqlj

    C:\sqlj\demo>javac ProcedureCall.java

  • 7/25/2019 Advanced Java Book

    189/299

    Java Stored Procedures

    Comp-U-Learn 179

    C:\sqlj\demo>java ProcedureCall

    C:\sqlj\demo>

    Calling Stored Functions

    #sql res = { VALUES(Function_Name()) };

    Create