Category Archives: Code . Programming Samples . প্রোগ্রাম উদাহরন

Code . Programming Samples . প্রোগ্রাম উদাহরন

Demonstrates the use of a JColorChooser which presents a dialog with three different tabbed panes to allow the user to select a color preference

Demonstrates the use of a JColorChooser which presents a dialog with three different tabbed panes to allow the user to select a color preference. The dialog returns a Color object based on the user's selection or null if the user entered Cancel.

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

/** Simple example illustrating the use of JColorChooser. 
 *
 *  .
 */

public class JColorChooserTest extends JFrame
                               implements ActionListener {
  public static void main(String[] args) {
    new JColorChooserTest();
  }

  public JColorChooserTest() {
    super("Using JColorChooser");
    WindowUtilities.setNativeLookAndFeel();
    addWindowListener(new ExitListener());
    Container content = getContentPane();
    content.setBackground(Color.white);
    content.setLayout(new FlowLayout());
    JButton colorButton
      = new JButton("Choose Background Color");
    colorButton.addActionListener(this);
    content.add(colorButton);
    setSize(300, 100);
    setVisible(true);
  }

  public void actionPerformed(ActionEvent e) {
    // Args are parent component, title, initial color.
    Color bgColor
      = JColorChooser.showDialog(this,
                                 "Choose Background Color",
                                 getBackground());
    if (bgColor != null)
      getContentPane().setBackground(bgColor);
  }
}

WebClient – Client application that can talk interactively to Web servers. Requires the components listed below

import java.awt.*; // For BorderLayout, GridLayout, Font, Color.
import java.awt.event.*;
import java.util.*;
import javax.swing.*;

/** A graphical client that lets you interactively connect to
 *  Web servers and send custom request lines and
 *  request headers.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class WebClient extends JPanel
    implements Runnable, Interruptible, ActionListener {
  public static void main(String[] args) {
    WindowUtilities.setNativeLookAndFeel();
    WindowUtilities.openInJFrame(new WebClient(), 600, 700,
                                 "Web Client",
                                 SystemColor.control);
  }

  private LabeledTextField hostField, portField,
          requestLineField;
  private JTextArea requestHeadersArea, resultArea;
  private String host, requestLine;
  private int port;
  private String[] requestHeaders = new String[30];
  private JButton submitButton, interruptButton;
  private boolean isInterrupted = false;

  public WebClient() {
    setLayout(new BorderLayout(5, 30));
    int fontSize = 14;
    Font labelFont =
      new Font("Serif", Font.BOLD, fontSize);
    Font headingFont =
      new Font("SansSerif", Font.BOLD, fontSize+4);
    Font textFont =
      new Font("Monospaced", Font.BOLD, fontSize-2);
    JPanel inputPanel = new JPanel();
    inputPanel.setLayout(new BorderLayout());
    JPanel labelPanel = new JPanel();
    labelPanel.setLayout(new GridLayout(4,1));
    hostField = new LabeledTextField("Host:", labelFont,
                                     30, textFont);
    portField = new LabeledTextField("Port:", labelFont,
                                     "80", 5, textFont);
    // Use HTTP 1.0 for compatibility with the most servers.
    // If you switch this to 1.1, you *must* supply a
    // Host: request header.
    requestLineField =
      new LabeledTextField("Request Line:", labelFont,
                           "GET / HTTP/1.0", 50, textFont);
    labelPanel.add(hostField);
    labelPanel.add(portField);
    labelPanel.add(requestLineField);
    JLabel requestHeadersLabel =
      new JLabel("Request Headers:");
    requestHeadersLabel.setFont(labelFont);
    labelPanel.add(requestHeadersLabel);
    inputPanel.add(labelPanel, BorderLayout.NORTH);
    requestHeadersArea = new JTextArea(5, 80);
    requestHeadersArea.setFont(textFont);
    JScrollPane headerScrollArea =
      new JScrollPane(requestHeadersArea);
    inputPanel.add(headerScrollArea, BorderLayout.CENTER);
    JPanel buttonPanel = new JPanel();
    submitButton = new JButton("Submit Request");
    submitButton.addActionListener(this);
    submitButton.setFont(labelFont);
    buttonPanel.add(submitButton);
    inputPanel.add(buttonPanel, BorderLayout.SOUTH);
    add(inputPanel, BorderLayout.NORTH);
    JPanel resultPanel = new JPanel();
    resultPanel.setLayout(new BorderLayout());
    JLabel resultLabel =
      new JLabel("Results", JLabel.CENTER);
    resultLabel.setFont(headingFont);
    resultPanel.add(resultLabel, BorderLayout.NORTH);
    resultArea = new JTextArea();
    resultArea.setFont(textFont);
    JScrollPane resultScrollArea =
      new JScrollPane(resultArea);
    resultPanel.add(resultScrollArea, BorderLayout.CENTER);
    JPanel interruptPanel = new JPanel();
    interruptButton = new JButton("Interrupt Download");
    interruptButton.addActionListener(this);
    interruptButton.setFont(labelFont);
    interruptPanel.add(interruptButton);
    resultPanel.add(interruptPanel, BorderLayout.SOUTH);
    add(resultPanel, BorderLayout.CENTER);
  }

  public void actionPerformed(ActionEvent event) {
    if (event.getSource() == submitButton) {
      Thread downloader = new Thread(this);
      downloader.start();
    } else if (event.getSource() == interruptButton) {
      isInterrupted = true;
    }
  }

  public void run() {
    isInterrupted = false;
    if (hasLegalArgs())
      new HttpClient(host, port, requestLine,
             requestHeaders, resultArea, this);
  }

  public boolean isInterrupted() {
    return(isInterrupted);
  }

  private boolean hasLegalArgs() {
    host = hostField.getTextField().getText();
    if (host.length() == 0) {
      report("Missing hostname");
      return(false);
    }
    String portString =
      portField.getTextField().getText();
    if (portString.length() == 0) {
      report("Missing port number");
      return(false);
    }
    try {
      port = Integer.parseInt(portString);
    } catch(NumberFormatException nfe) {
      report("Illegal port number: " + portString);
      return(false);
    }
    requestLine =
      requestLineField.getTextField().getText();
    if (requestLine.length() == 0) {
      report("Missing request line");
      return(false);
    }
    getRequestHeaders();
    return(true);
  }

  private void report(String s) {
    resultArea.setText(s);
  }

  private void getRequestHeaders() {
    for(int i=0; i
   *    LabeledTextField ltf = new LabeledTextField(...);
   *    ltf.getLabel().someLabelMethod(...);
   *

*/ public JLabel getLabel() { return(label); } /** The TextField at the right side of the * LabeledTextField. */ public JTextField getTextField() { return(textField); } } Interruptible.java Polls to see if the user choose to interrupt the current network download. /** An interface for classes that can be polled to see * if they've been interrupted. Used by HttpClient * and WebClient to allow the user to interrupt a network * download. * * Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * . * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ public interface Interruptible { public boolean isInterrupted(); } NetworkClient.java Starting point for a network client to communicate with a remote computer. import java.net.*; import java.io.*; /** A starting point for network clients. You'll need to * override handleConnection, but in many cases connect can * remain unchanged. It uses SocketUtil to simplify the * creation of the PrintWriter and BufferedReader. * * Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ public class NetworkClient { protected String host; protected int port; /** Register host and port. The connection won't * actually be established until you call * connect. */ public NetworkClient(String host, int port) { this.host = host; this.port = port; } /** Establishes the connection, then passes the socket * to handleConnection. */ public void connect() { try { Socket client = new Socket(host, port); handleConnection(client); } catch(UnknownHostException uhe) { System.out.println("Unknown host: " + host); uhe.printStackTrace(); } catch(IOException ioe) { System.out.println("IOException: " + ioe); ioe.printStackTrace(); } } /** This is the method you will override when * making a network client for your task. * The default version sends a single line * ("Generic Network Client") to the server, * reads one line of response, prints it, then exits. */ protected void handleConnection(Socket client) throws IOException { PrintWriter out = SocketUtil.getWriter(client); BufferedReader in = SocketUtil.getReader(client); out.println("Generic Network Client"); System.out.println ("Generic Network Client:\n" + "Made connection to " + host + " and got '" + in.readLine() + "' in response"); client.close(); } /** The hostname of the server we're contacting. */ public String getHost() { return(host); } /** The port connection will be made on. */ public int getPort() { return(port); } } SocketUtil.java: Provides utilities for wrapping a BufferedReader and PrintWriter around the Socket's input and output streams, respectively. import java.net.*; import java.io.*; /** A shorthand way to create BufferedReaders and * PrintWriters associated with a Socket. * * Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * . * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ public class SocketUtil { /** Make a BufferedReader to get incoming data. */ public static BufferedReader getReader(Socket s) throws IOException { return(new BufferedReader( new InputStreamReader(s.getInputStream()))); } /** Make a PrintWriter to send outgoing data. * This PrintWriter will automatically flush stream * when println is called. */ public static PrintWriter getWriter(Socket s) throws IOException { // Second argument of true means autoflush. return(new PrintWriter(s.getOutputStream(), true)); } } WindowUtilities.java Simplifies the setting of native look and feel. import javax.swing.*; import java.awt.*; // For Color and Container classes. /** A few utilities that simplify using windows in Swing. * * Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ public class WindowUtilities { /** Tell system to use native look and feel, as in previous * releases. Metal (Java) LAF is the default otherwise. */ public static void setNativeLookAndFeel() { try { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) { System.out.println("Error setting native LAF: " + e); } } public static void setJavaLookAndFeel() { try { UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName()); } catch(Exception e) { System.out.println("Error setting Java LAF: " + e); } } public static void setMotifLookAndFeel() { try { UIManager.setLookAndFeel( "com.sun.java.swing.plaf.motif.MotifLookAndFeel"); } catch(Exception e) { System.out.println("Error setting Motif LAF: " + e); } } /** A simplified way to see a JPanel or other Container. Pops * up a JFrame with specified Container as the content pane. */ public static JFrame openInJFrame(Container content, int width, int height, String title, Color bgColor) { JFrame frame = new JFrame(title); frame.setBackground(bgColor); content.setBackground(bgColor); frame.setSize(width, height); frame.setContentPane(content); frame.addWindowListener(new ExitListener()); frame.setVisible(true); return(frame); } /** Uses Color.white as the background color. */ public static JFrame openInJFrame(Container content, int width, int height, String title) { return(openInJFrame(content, width, height, title, Color.white)); } /** Uses Color.white as the background color, and the * name of the Container's class as the JFrame title. */ public static JFrame openInJFrame(Container content, int width, int height) { return(openInJFrame(content, width, height, content.getClass().getName(), Color.white)); } } ExitListener.java WindowListener for applications in this chapter. import java.awt.*; import java.awt.event.*; /** A listener that you attach to the top-level JFrame of * your application, so that quitting the frame exits the * application. * * Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ public class ExitListener extends WindowAdapter { public void windowClosing(WindowEvent event) { System.exit(0); } }

EchoServer.java A simple HTTP server that creates a Web page showing all data sent from the client (browser), including all HTTP request headers sent form the client. Uses the following classes

EchoServer.java  A simple HTTP server that creates a Web page showing all data sent from the client (browser), including all HTTP request headers sent form the client. Uses the following classes:

 

import java.net.*;
import java.io.*;
import java.util.StringTokenizer;

/** A simple HTTP server that generates a Web page showing all
 *  of the data that it received from the Web client (usually
 *  a browser). To use this server, start it on the system of
 *  your choice, supplying a port number if you want something
 *  other than port 8088. Call this system server.com. Next,
 *  start a Web browser on the same or a different system, and
 *  connect to http://server.com:8088/whatever. The resultant
 *  Web page will show the data that your browser sent. For
 *  debugging in servlet or CGI programming, specify
 *  http://server.com:8088/whatever as the ACTION of your HTML
 *  form. You can send GET or POST data; either way, the
 *  resultant page will show what your browser sent.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class EchoServer extends NetworkServer {
  protected int maxRequestLines = 50;
  protected String serverName = "EchoServer";

  /** Supply a port number as a command-line
   *  argument. Otherwise, use port 8088.
   */

  public static void main(String[] args) {
    int port = 8088;
    if (args.length > 0) {
      try {
        port = Integer.parseInt(args[0]);
      } catch(NumberFormatException nfe) {}
    }
    new EchoServer(port, 0);
  }

  public EchoServer(int port, int maxConnections) {
    super(port, maxConnections);
    listen();
  }

  /** Overrides the NetworkServer handleConnection method to
   *  read each line of data received, save it into an array
   *  of strings, then send it back embedded inside a PRE
   *  element in an HTML page.
   */

  public void handleConnection(Socket server)
      throws IOException{
    System.out.println
        (serverName + ": got connection from " +
         server.getInetAddress().getHostName());
    BufferedReader in = SocketUtil.getReader(server);
    PrintWriter out = SocketUtil.getWriter(server);
    String[] inputLines = new String[maxRequestLines];
    int i;
    for (i=0; i\n" +
       "\n" +
       "\n" +
       "  \n" +
       "\n" +
       "\n" +
       "\n" +
       "
" + serverName +
         " Results
\n" +
       "Here is the request line and request headers\n" +
       "sent by your browser:\n" +
       "

");
  }

  // Print bottom of a standard Web page.

  private void printTrailer(PrintWriter out) {
    out.println
      ("

\n" +
       "\n" +
       "\n");
  }

  // Normal Web page requests use GET, so this server can simply
  // read a line at a time. However, HTML forms can also use
  // POST, in which case we have to determine the number of POST
  // bytes that are sent so we know how much extra data to read
  // after the standard HTTP headers.

  private boolean usingPost(String[] inputs) {
    return(inputs[0].toUpperCase().startsWith("POST"));
  }

  private void readPostData(String[] inputs, int i,
                            BufferedReader in)
      throws IOException {
    int contentLength = contentLength(inputs);
    char[] postData = new char[contentLength];
    in.read(postData, 0, contentLength);
    inputs[++i] = new String(postData, 0, contentLength);
  }

  // Given a line that starts with Content-Length,
  // this returns the integer value specified.

  private int contentLength(String[] inputs) {
    String input;
    for (int i=0; iOverride this method in servers
   *  you write.
   *  


   *  This generic version simply reports the host that made
   *  the connection, shows the first line the client sent,
   *  and sends a single line in response.
   */

  protected void handleConnection(Socket server)
      throws IOException{
    BufferedReader in = SocketUtil.getReader(server);
    PrintWriter out = SocketUtil.getWriter(server);
    System.out.println
      ("Generic Network Server: got connection from " +
       server.getInetAddress().getHostName() + "\n" +
       "with first line '" + in.readLine() + "'");
    out.println("Generic Network Server");
    server.close();
  }

  /** Gets the max connections server will handle before
   *  exiting. A value of 0 indicates that server should run
   *  until explicitly killed.
   */

  public int getMaxConnections() {
    return(maxConnections);
  }

  /** Sets max connections. A value of 0 indicates that server
   *  should run indefinitely (until explicitly killed).
   */

  public void setMaxConnections(int maxConnections) {
    this.maxConnections = maxConnections;
  }

  /** Gets port on which server is listening. */

  public int getPort() {
    return(port);
  }

  /** Sets port. You can only do before "connect" is
   *  called. That usually happens in the constructor.
   */

  protected void setPort(int port) {
    this.port = port;
  }
}


SocketUtil.java  Simplifies the creation of a PrintWriter and BufferedReader.

import java.net.*;
import java.io.*;

/** A shorthand way to create BufferedReaders and
 *  PrintWriters associated with a Socket.
 *
 *  Taken from Core Web Programming from 
 *  Prentice Hall and Sun Microsystems Press,
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted. 
 */

public class SocketUtil {
  /** Make a BufferedReader to get incoming data. */

  public static BufferedReader getReader(Socket s)
      throws IOException {
    return(new BufferedReader(
       new InputStreamReader(s.getInputStream())));
  }

  /** Make a PrintWriter to send outgoing data.
   *  This PrintWriter will automatically flush stream
   *  when println is called.
   */

  public static PrintWriter getWriter(Socket s)
      throws IOException {
    // Second argument of true means autoflush.
    return(new PrintWriter(s.getOutputStream(), true));
  }
}

StoppableThread.java A template to place a thread in a RUN, WAIT, or STOP state.

/** A template to control the state of a thread through setting
 *  an internal flag.

public class StoppableThread extends Thread {

   public static final int STOP    = 0;
   public static final int RUN     = 1;
   public static final int WAIT    = 2;
   private int state = RUN;

  /** Public method to permit setting a flag to stop or
   *  suspend the thread.  The state is monitored through the
   *  corresponding checkState method.
   */

   public synchronized void setState(int state) {
      this.state = state;
      if (state==RUN) {
         notify();
      }
   }

  /** Returns the desired state of the thread (RUN, STOP, WAIT).
   *  Normally, you may want to change the state or perform some
   *  other task if an InterruptedException occurs.
   */

   private synchronized int checkState() {
      while (state==WAIT) {
        try {
          wait();
        } catch (InterruptedException e) { }
      }
      return state;
   }

  /** An example of thread that will continue to run until
   *  the creating object tells the thread to STOP.
   */

   public void run() {
      while (checkState()!=STOP) {
         ...
      }
   }
}

mall example showing the basic use of a JToolBar

mall example showing the basic use of a JToolBar

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

/** Small example showing basic use of JToolBar. 
 *
 * 
 */

public class JToolBarExample extends JFrame
                             implements ItemListener {
  private BrowserToolBar toolbar;
  private JCheckBox labelBox;

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

  public JToolBarExample() {
    super("JToolBar Example");
    WindowUtilities.setNativeLookAndFeel();
    addWindowListener(new ExitListener());
    Container content = getContentPane();
    content.setBackground(Color.white);
    
    JPanel panel = new JPanel(new BorderLayout());
    labelBox = new JCheckBox("Show Text Labels?");
    labelBox.setHorizontalAlignment(SwingConstants.CENTER);
    labelBox.addItemListener(this);
    panel.add(new JTextArea(10,30), BorderLayout.CENTER);
    panel.add(labelBox, BorderLayout.SOUTH);

    toolbar = new BrowserToolBar();
    content.add(toolbar, BorderLayout.NORTH);
    content.add(panel, BorderLayout.CENTER);

    pack();
    setVisible(true);
  }

  public void itemStateChanged(ItemEvent event) {
    toolbar.setTextLabels(labelBox.isSelected());
    pack();
  }
}

UrlRetriever2.java Illustrates how the URL class can simplify communication to an HTTP server.

UrlRetriever2.java  Illustrates how the URL class can simplify communication to an HTTP server.

import java.net.*;
import java.io.*;

/** Read a remote file using the standard URL class
 *  instead of connecting explicitly to the HTTP server.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class UrlRetriever2 {
  public static void main(String[] args) {
    checkUsage(args);
    try {
      URL url = new URL(args[0]);
      BufferedReader in = new BufferedReader(
        new InputStreamReader(url.openStream()));
      String line;
      while ((line = in.readLine()) != null) {
        System.out.println("> " + line);
     }
      in.close();
    } catch(MalformedURLException mue) { // URL constructor
        System.out.println(args[0] + "is an invalid URL: " + mue);
    } catch(IOException ioe) { // Stream constructors
      System.out.println("IOException: " + ioe);
    }
  }

  private static void checkUsage(String[] args) {
    if (args.length != 1) {
      System.out.println("Usage: UrlRetriever2 ");
      System.exit(-1);
    }
  }
}

RMI Example – Message, illustrates retrieving a message from an object located on a remote server. Requires the following classes

Rem.java  Establishes which methods the client can access in the remote object. 





import java.rmi.*;

/** The RMI client will use this interface directly. The RMI
 *  server will make a real remote object that implements this,
 *  then register an instance of it with some URL.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public interface Rem extends Remote {
  public String getMessage() throws RemoteException;
}


RemClient.java  The client application which communicates to the remote object and retrieves the message. 

import java.rmi.*; // For Naming, RemoteException, etc.
import java.net.*; // For MalformedURLException
import java.io.*;  // For Serializable interface

/** Get a Rem object from the specified remote host.
 *  Use its methods as though it were a local object.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class RemClient {
  public static void main(String[] args) {
    try {
      String host =
        (args.length > 0) ? args[0] : "localhost";
      // Get the remote object and store it in remObject:
      Rem remObject =
        (Rem)Naming.lookup("rmi://" + host + "/Rem");
      // Call methods in remObject:
      System.out.println(remObject.getMessage());
    } catch(RemoteException re) {
      System.out.println("RemoteException: " + re);
    } catch(NotBoundException nbe) {
      System.out.println("NotBoundException: " + nbe);
    } catch(MalformedURLException mfe) {
      System.out.println("MalformedURLException: " + mfe);
    }
  }
}


RemImpl.java  The concrete, remote object that implements the methods in Rem.java. 

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

/** This is the actual implementation of Rem that the RMI
 *  server uses. The server builds an instance of this, then
 *  registers it with a URL. The client accesses the URL and
 *  binds the result to a Rem (not a RemImpl; it doesn't
 *  have this).
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class RemImpl extends UnicastRemoteObject
                     implements Rem {
  public RemImpl() throws RemoteException {}

  public String getMessage() throws RemoteException {
    return("Here is a remote message.");
  }
}


RemServer.java  Creates an instance of RemImpl on the remote server and binds the object in the registry for lookup by the client. 

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

/** The server creates a RemImpl (which implements the Rem
 *  interface), then registers it with the URL Rem, where
 *  clients can access it.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class RemServer {
  public static void main(String[] args) {
    try {
      RemImpl localObject = new RemImpl();
      Naming.rebind("rmi:///Rem", localObject);
    } catch(RemoteException re) {
      System.out.println("RemoteException: " + re);
    } catch(MalformedURLException mfe) {
      System.out.println("MalformedURLException: " + mfe);
    }
  }
}

Creates three common types of sliders

Creates three common types of sliders: one without tick marks, one with tick marks, and one with both tick marks and labels. 

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

/** Simple example illustrating the use of JSliders, especially
 *  the ability to specify tick marks and labels.
 *
 *   
 */

public class JSliders extends JFrame {
  public static void main(String[] args) {
    new JSliders();
  }

  public JSliders() {
    super("Using JSlider");
    WindowUtilities.setNativeLookAndFeel();
    addWindowListener(new ExitListener());
    Container content = getContentPane();
    content.setBackground(Color.white);
    
    JSlider slider1 = new JSlider();
    slider1.setBorder(BorderFactory.createTitledBorder
                        ("JSlider without Tick Marks"));
    content.add(slider1, BorderLayout.NORTH);
    
    JSlider slider2 = new JSlider();
    slider2.setBorder(BorderFactory.createTitledBorder
                        ("JSlider with Tick Marks"));
    slider2.setMajorTickSpacing(20);
    slider2.setMinorTickSpacing(5);
    slider2.setPaintTicks(true);
    content.add(slider2, BorderLayout.CENTER);

    JSlider slider3 = new JSlider();
    slider3.setBorder(BorderFactory.createTitledBorder
                        ("JSlider with Tick Marks & Labels"));
    slider3.setMajorTickSpacing(20);
    slider3.setMinorTickSpacing(5);
    slider3.setPaintTicks(true);
    slider3.setPaintLabels(true);
    content.add(slider3, BorderLayout.SOUTH);
    
    pack();
    setVisible(true);
  }
}

Basic Swing Details

  • WindowUtilities.java Utility class that simplifies creating a window and setting the look and feel.
  • ExitListener.java A WindowListener with support to close the window.
  • JAppletExample.java A simple applet (JApplet) created in Swing. Illustrates setting the look and feel, adding components to the content pane, and changing the layout to FlowLayout (default is BorderLayout). See JAppletExample.html (requires the Java Plug-In or a Java 2 compliant browser, for example, Netscape 6.x).
  • JFrameExample.java Demonstrates creating a simple Swing application using a JFrame. As with a JApplet, components must be added to the content pane, instead of the window directly.
  • JLabels.java Illustrates creating labels in Swing. A nice feature of JLabels is that the label text can contain HTML markup. Uses image JHUAPL.gif
  • JButtons.java Creates various buttons. In Swing, buttons can contain text only, an image only, or a combination of both an image and a label. Uses image cup.gif.
  • JPanels.java A simple example that illustrates creating panels. In Swing, a JPanel can contain custom borders. Typically, utility methods in the BorderFactory class are used to create a border for the panel. Uses the following class:
    o SixChoicePanel.java A JPanel that displays six radio buttons with labels.
  • JSliders.java Creates three common types of sliders: one without tick marks, one with tick marks, and one with both tick marks and labels.
  • JColorChooserTest.java Demonstrates the use of a JColorChooser which presents a dialog with three different tabbed panes to allow the user to select a color preference. The dialog returns a Color object based on the user's selection or null if the user entered Cancel.
  • JInternalFrames.java Illustrates the ability to create a Multiple Document Interface (MDI) application by placing internal frames (JInternalFrame) in a desktop pane (JDesktopPane).
  • JToolBarExample.java Small example showing the basic use of a JToolBar. Uses the following classes and images:
    o ToolBarButton.java A simple button that contains an image and a label for use in a toolbar.
    o BrowserToolBar.java A basic tool bar for holding multiple buttons.
    o Images used in the toolbar buttons: Help.gif, Home.gif, Left.gif, Print.gif, Right.gif, RotCCUp.gif, TrafficRed.gif.
  • Browser.java Implementation of a simple browser in Swing. The user can specify a URL to load into the browser (JEditorPane). By attaching an HyperlinkListener, the editor pane is responsive to hyperlinks selected by the user. Uses the following class and image:
    o JIconButton.java A simple button that the user can select to load the entered URL.
    o home.gif Image used in the button.
  • JCheckBoxTest.java Simple example illustrating the use of check boxes.
  • JRadioButtonTest.java Creates three radio buttons and illustrates handling ItemEvents in response to selecting a radio button.
  • JOptionPaneExamples.java Creates various modal dialogs to show messages. Uses the follwoing classes:
    o JLabeledTextField.java A simple JPanel that combines a JLabel and a JTextField.
    o RadioButtonPanel.java Groups several radio buttons in a single row, with a label on the left.
    o DisableListener.java A listener that toggles the enabled status of some other component.

UrlRetriever.java Accepts an URL from the command line, parses the host, port, and URI components from the URL and then retrieves the document. Requires the following classes

UrlRetriever.java  Accepts an URL from the command line, parses the host, port, and URI components from the URL and then retrieves the document. Requires the following classes: 


import java.util.*;

/** This parses the input to get a host, port, and file, then
 *  passes these three values to the UriRetriever class to
 *  grab the URL from the Web.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class UrlRetriever {
  public static void main(String[] args) {
    checkUsage(args);
    StringTokenizer tok = new StringTokenizer(args[0]);
    String protocol = tok.nextToken(":");
    checkProtocol(protocol);
    String host = tok.nextToken(":/");
    String uri;
    int port = 80;
    try {
      uri = tok.nextToken("");
      if (uri.charAt(0) == ':') {
        tok = new StringTokenizer(uri);
        port = Integer.parseInt(tok.nextToken(":/"));
        uri = tok.nextToken("");
      }
    } catch(NoSuchElementException nsee) {
      uri = "/";
    }
    UriRetriever uriClient = new UriRetriever(host, port, uri);
    uriClient.connect();
  }

  /** Warn user if the URL was forgotten. */

  private static void checkUsage(String[] args) {
    if (args.length != 1) {
      System.out.println("Usage: UrlRetriever ");
      System.exit(-1);
    }
  }

  /** Tell user that this can only handle HTTP. */

  private static void checkProtocol(String protocol) {
    if (!protocol.equals("http")) {
      System.out.println("Don't understand protocol " + protocol);
      System.exit(-1);
    }
  }
}




UriRetriever.java  Given a host, port, and URI, retrieves the document from the HTTP server. 

import java.net.*;
import java.io.*;

/** Retrieve a URL given the host, port, and file as three 
 *  separate command-line arguments. A later class 
 *  (UrlRetriever) supports a single URL instead.
 *
 *  Taken from Core Web Programming from 
 *  Prentice Hall and Sun Microsystems Press,
 
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted. 
 */

public class UriRetriever extends NetworkClient {
  private String uri;

  public static void main(String[] args) {
    UriRetriever uriClient
      = new UriRetriever(args[0], Integer.parseInt(args[1]),
                         args[2]);
    uriClient.connect();
  }

  public UriRetriever(String host, int port, String uri) {
    super(host, port); 
    this.uri = uri;
  }

  /** Send one GET line, then read the results one line at a
   *  time, printing each to standard output.
   */

  // It is safe to use blocking IO (readLine), since
  // HTTP servers close connection when done, resulting
  // in a null value for readLine.
  
  protected void handleConnection(Socket uriSocket)
      throws IOException {
    PrintWriter out = SocketUtil.getWriter(uriSocket);
    BufferedReader in = SocketUtil.getReader(uriSocket);
    out.println("GET " + uri + " HTTP/1.0\r\n");
    String line;
    while ((line = in.readLine()) != null) {
      System.out.println("> " + line);
    }
  }
}





NetworkClient.java

import java.net.*;
import java.io.*;

/** A starting point for network clients. You'll need to
 *  override handleConnection, but in many cases connect can
 *  remain unchanged. It uses SocketUtil to simplify the
 *  creation of the PrintWriter and BufferedReader.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class NetworkClient {
  protected String host;
  protected int port;

  /** Register host and port. The connection won't
   *  actually be established until you call
   *  connect.
   */

  public NetworkClient(String host, int port) {
    this.host = host;
    this.port = port;
  }

  /** Establishes the connection, then passes the socket
   *  to handleConnection.
   */

  public void connect() {
    try {
      Socket client = new Socket(host, port);
      handleConnection(client);
    } catch(UnknownHostException uhe) {
      System.out.println("Unknown host: " + host);
      uhe.printStackTrace();
    } catch(IOException ioe) {
      System.out.println("IOException: " + ioe);
      ioe.printStackTrace();
    }
  }

  /** This is the method you will override when
   *  making a network client for your task.
   *  The default version sends a single line
   *  ("Generic Network Client") to the server,
   *  reads one line of response, prints it, then exits.
   */

  protected void handleConnection(Socket client)
    throws IOException {
    PrintWriter out = SocketUtil.getWriter(client);
    BufferedReader in = SocketUtil.getReader(client);
    out.println("Generic Network Client");
    System.out.println
      ("Generic Network Client:\n" +
       "Made connection to " + host +
       " and got '" + in.readLine() + "' in response");
    client.close();
  }

  /** The hostname of the server we're contacting. */

  public String getHost() {
    return(host);
  }

  /** The port connection will be made on. */

  public int getPort() {
    return(port);
  }
}

SocketUtil.java  Provides utilities for wrapping a BufferedReader  and PrintWriter around the Socket's input and output streams, respectively. 

import java.net.*;
import java.io.*;

/** A shorthand way to create BufferedReaders and
 *  PrintWriters associated with a Socket.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class SocketUtil {
  /** Make a BufferedReader to get incoming data. */

  public static BufferedReader getReader(Socket s)
      throws IOException {
    return(new BufferedReader(
       new InputStreamReader(s.getInputStream())));
  }

  /** Make a PrintWriter to send outgoing data.
   *  This PrintWriter will automatically flush stream
   *  when println is called.
   */

  public static PrintWriter getWriter(Socket s)
      throws IOException {
    // Second argument of true means autoflush.
    return(new PrintWriter(s.getOutputStream(), true));
  }
}

AddressVerifier.java Connects to an SMTP server and issues a expn request to display details about a mailbox on the server. Uses the following classes

import java.net.*;
import java.io.*;

/** Given an e-mail address of the form user@host,
 *  connect to port 25 of the host and issue an
 *  'expn' request for the user. Print the results.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class AddressVerifier extends NetworkClient {
  private String username;

  public static void main(String[] args) {
    if (args.length != 1) {
      usage();
   }
    MailAddress address = new MailAddress(args[0]);
    AddressVerifier verifier
      = new AddressVerifier(address.getUsername(),
                            address.getHostname(), 25);
    verifier.connect();
  }

  public AddressVerifier(String username, String hostname,
                         int port) {
    super(hostname, port);
    this.username = username;
  }

  /** NetworkClient, the parent class, automatically establishes
   *  the connection and then passes the Socket to
   *  handleConnection. This method does all the real work
   *  of talking to the mail server.
   */

  // You can't use readLine, because it blocks. Blocking I/O
  // by readLine is only appropriate when you know how many
  // lines to read. Note that mail servers send a varying
  // number of lines when you first connect or send no line
  // closing the connection (as HTTP servers do), yielding
  // null for readLine. Also, we'll assume that 1000 bytes
  // is more than enough to handle any server welcome
  // message and the actual EXPN response.

  protected void handleConnection(Socket client) {
    try {
      PrintWriter out = SocketUtil.getWriter(client);
      InputStream in = client.getInputStream();
      byte[] response = new byte[1000];
      // Clear out mail server's welcome message.
      in.read(response);
      out.println("EXPN " + username);
      // Read the response to the EXPN command.
      int numBytes = in.read(response);
      // The 0 means to use normal ASCII encoding.
      System.out.write(response, 0, numBytes);
      out.println("QUIT");
      client.close();
    } catch(IOException ioe) {
      System.out.println("Couldn't make connection: " + ioe);
    }
  }

  /** If the wrong arguments, thn warn user. */

  public static void usage() {
    System.out.println ("You must supply an email address " +
       "of the form 'username@hostname'.");
    System.exit(-1);
  }
}


MailAddress.java  Separates the user and host components of an email address. 

import java.util.*;

/** Takes a string of the form "user@host" and
 *  separates it into the "user" and "host" parts.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class MailAddress {
  private String username, hostname;

  public MailAddress(String emailAddress) {
    StringTokenizer tokenizer
      = new StringTokenizer(emailAddress, "@");
    this.username = getArg(tokenizer);
    this.hostname = getArg(tokenizer);
  }

  private static String getArg(StringTokenizer tok) {
    try { return(tok.nextToken()); }
    catch (NoSuchElementException nsee) {
      System.out.println("Illegal email address");
      System.exit(-1);
      return(null);
    }
  }

  public String getUsername() {
    return(username);
  }

  public String getHostname() {
    return(hostname);
  }
}


NetworkClient.java  Starting point for a network client to communicate with a remote computer.

import java.net.*;
import java.io.*;

/** A starting point for network clients. You'll need to
 *  override handleConnection, but in many cases connect can
 *  remain unchanged. It uses SocketUtil to simplify the
 *  creation of the PrintWriter and BufferedReader.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class NetworkClient {
  protected String host;
  protected int port;

  /** Register host and port. The connection won't
   *  actually be established until you call
   *  connect.
   */

  public NetworkClient(String host, int port) {
    this.host = host;
    this.port = port;
  }

  /** Establishes the connection, then passes the socket
   *  to handleConnection.
   */

  public void connect() {
    try {
      Socket client = new Socket(host, port);
      handleConnection(client);
    } catch(UnknownHostException uhe) {
      System.out.println("Unknown host: " + host);
      uhe.printStackTrace();
    } catch(IOException ioe) {
      System.out.println("IOException: " + ioe);
      ioe.printStackTrace();
    }
  }

  /** This is the method you will override when
   *  making a network client for your task.
   *  The default version sends a single line
   *  ("Generic Network Client") to the server,
   *  reads one line of response, prints it, then exits.
   */

  protected void handleConnection(Socket client)
    throws IOException {
    PrintWriter out = SocketUtil.getWriter(client);
    BufferedReader in = SocketUtil.getReader(client);
    out.println("Generic Network Client");
    System.out.println
      ("Generic Network Client:\n" +
       "Made connection to " + host +
       " and got '" + in.readLine() + "' in response");
    client.close();
  }

  /** The hostname of the server we're contacting. */

  public String getHost() {
    return(host);
  }

  /** The port connection will be made on. */

  public int getPort() {
    return(port);
  }
}


SocketUtil.java  Provides utilities for wrapping a BufferedReader  and PrintWriter around the Socket's input and output streams, respectively. 

import java.net.*;
import java.io.*;

/** A shorthand way to create BufferedReaders and
 *  PrintWriters associated with a Socket.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class SocketUtil {
  /** Make a BufferedReader to get incoming data. */

  public static BufferedReader getReader(Socket s)
      throws IOException {
    return(new BufferedReader(
       new InputStreamReader(s.getInputStream())));
  }

  /** Make a PrintWriter to send outgoing data.
   *  This PrintWriter will automatically flush stream
   *  when println is called.
   */

  public static PrintWriter getWriter(Socket s)
      throws IOException {
    // Second argument of true means autoflush.
    return(new PrintWriter(s.getOutputStream(), true));
  }
}

Buggy Counter Applet.java Demonstrates that data shared by multiple threads is candidate for a potential race condition

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

/** Emulates the Counter and Counter2 classes, but this time
 *  from an applet that invokes multiple versions of its own run
 *  method. This version is likely to work correctly
 *  except when  an important customer is visiting.

public class BuggyCounterApplet extends Applet
                                implements Runnable{
  private int totalNum = 0;
  private int loopLimit = 5;

  // Start method of applet, not the start method of the thread. 
  // The applet start method is called by the browser after init is
  // called. 
  public void start() {
    Thread t;
    for(int i=0; i<3; i++) {
      t = new Thread(this);
      t.start();
    }
  }

  private void pause(double seconds) {
    try { Thread.sleep(Math.round(1000.0*seconds)); }
    catch(InterruptedException ie) {}
  }

  public void run() {
    int currentNum = totalNum;
    System.out.println("Setting currentNum to " + currentNum);
    totalNum = totalNum + 1;
    for(int i=0; i

SplitTest.java Illustrates parsing a string with a String.split

SplitTest.java  Illustrates parsing a string with a String.split


/** Prints the tokens resulting from treating the first
 *  command-line argument as the string to be tokenized
 *  and the second as the delimiter set. Uses
 *  String.split instead of StringTokenizer.
 */

public class SplitTest {
  public static void main(String[] args) {
    if (args.length == 2) {
      String input = args[0], delimiters = args[1];
      String[] tokens = args[0].split(delimiters);
      for(int i=0; i<tokens.length; i++)="" {="" string="" token="tokens[i];" if="" (token.length()="" !="0)" 
      system.out.println(token);="" }="" else="" system.out.println="" ("usage:="" java="" splittest="" 
      delimeters");="" <="" pre="">

TokTest.java Illustrates parsing a string with a StringTokenizer.

TokTest.java  Illustrates parsing a string with a StringTokenizer. 

import java.util.StringTokenizer;

/** Prints the tokens resulting from treating the first
 *  command-line argument as the string to be tokenized
 *  and the second as the delimiter set.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class TokTest {
  public static void main(String[] args) {
    if (args.length == 2) {
      String input = args[0], delimiters = args[1];
      StringTokenizer tok =
        new StringTokenizer(input, delimiters);
      while (tok.hasMoreTokens()) {
        System.out.println(tok.nextToken());
      }
    } else {
      System.out.println
        ("Usage: java TokTest string delimeters");
    }
  }
}

NetworkClientTest.java Makes a simple connection to the host and port specified on the command line. Uses the following classes

NetworkClientTest.java  Makes a simple connection to the host and port specified on the command line. Uses the following classes:

/** Make simple connection to host and port specified.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class NetworkClientTest {
  public static void main(String[] args) {
    String host = "localhost";
    int port = 8088;
    if (args.length > 0) {
      host = args[0];
    }
    if (args.length > 1) {
      port = Integer.parseInt(args[1]);
    }
    NetworkClient nwClient = new NetworkClient(host, port);
    nwClient.connect();
  }
}



NetworkClient.java  Starting point for a network client to communicate with a remote computer.

import java.net.*;
import java.io.*;

/** A starting point for network clients. You'll need to
 *  override handleConnection, but in many cases connect can
 *  remain unchanged. It uses SocketUtil to simplify the
 *  creation of the PrintWriter and BufferedReader.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class NetworkClient {
  protected String host;
  protected int port;

  /** Register host and port. The connection won't
   *  actually be established until you call
   *  connect.
   */

  public NetworkClient(String host, int port) {
    this.host = host;
    this.port = port;
  }

  /** Establishes the connection, then passes the socket
   *  to handleConnection.
   */

  public void connect() {
    try {
      Socket client = new Socket(host, port);
      handleConnection(client);
    } catch(UnknownHostException uhe) {
      System.out.println("Unknown host: " + host);
      uhe.printStackTrace();
    } catch(IOException ioe) {
      System.out.println("IOException: " + ioe);
      ioe.printStackTrace();
    }
  }

  /** This is the method you will override when
   *  making a network client for your task.
   *  The default version sends a single line
   *  ("Generic Network Client") to the server,
   *  reads one line of response, prints it, then exits.
   */

  protected void handleConnection(Socket client)
    throws IOException {
    PrintWriter out = SocketUtil.getWriter(client);
    BufferedReader in = SocketUtil.getReader(client);
    out.println("Generic Network Client");
    System.out.println
      ("Generic Network Client:\n" +
       "Made connection to " + host +
       " and got '" + in.readLine() + "' in response");
    client.close();
  }

  /** The hostname of the server we're contacting. */

  public String getHost() {
    return(host);
  }

  /** The port connection will be made on. */

  public int getPort() {
    return(port);
  }
}


SocketUtil.java  Provides utilities for wrapping a BufferedReader around the Socket's input stream and a PrintWriter  around the Socket's output stream

import java.net.*;
import java.io.*;

/** A shorthand way to create BufferedReaders and
 *  PrintWriters associated with a Socket.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class SocketUtil {
  /** Make a BufferedReader to get incoming data. */

  public static BufferedReader getReader(Socket s)
      throws IOException {
    return(new BufferedReader(
       new InputStreamReader(s.getInputStream())));
  }

  /** Make a PrintWriter to send outgoing data.
   *  This PrintWriter will automatically flush stream
   *  when println is called.
   */

  public static PrintWriter getWriter(Socket s)
      throws IOException {
    // Second argument of true means autoflush.
    return(new PrintWriter(s.getOutputStream(), true));
  }
}

ShowSession.java Servlet that uses session tracking to determine if the client is a repeat visitor. Uses the ServletUtilities class to simplify the DOCTYPE and HEAD output.

ShowSession.java  Servlet that uses session tracking to determine if the client is a repeat visitor. Uses the ServletUtilities  class to simplify the DOCTYPE and HEAD output.


package cwp;

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

/** Simple example of session tracking.
 *

* Taken from Core Web Programming Java 2 Edition * from Prentice Hall and Sun Microsystems Press, * . * May be freely used or adapted. */ public class ShowSession extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Session Tracking Example"; HttpSession session = request.getSession(true); String heading; Integer accessCount = (Integer)session.getAttribute("accessCount"); if (accessCount == null) { accessCount = new Integer(0); heading = "Welcome, Newcomer"; } else { heading = "Welcome Back"; accessCount = new Integer(accessCount.intValue() + 1); } // Use setAttribute instead of putValue in version 2.2. session.setAttribute("accessCount", accessCount); out.println(ServletUtilities.headWithTitle(title) + "\n" + "

" + heading + "

\n" +
                "

Information on Your Session:

\n" +
                "\n" +
                "\n" +
                "  \n" +
                "  \n" +
                "  \n" +
                "  \n" +
                "
Info Type Value\n" + "
ID\n" + " " + session.getId() + "\n" + "
Creation Time\n" + " " + new Date(session.getCreationTime()) + "\n" + "
Time of Last Access\n" + " " + new Date(session.getLastAccessedTime()) + "\n" + "
Number of Previous Accesses\n" + " " + accessCount + "\n" + "
\n" +
                "");

  }

  /** Handle GET and POST requests identically. */

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

LongLivedCookie.java Subclass of Cookie that automatically sets the max age to one year.

LongLivedCookie.java  Subclass of Cookie that automatically sets the max age to one year. 

package cwp;

import javax.servlet.http.*;

/** Cookie that persists 1 year. Default Cookie doesn't
 *  persist past current session.
 *  


 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class LongLivedCookie extends Cookie {
  public static final int SECONDS_PER_YEAR = 60*60*24*365;

  public LongLivedCookie(String name, String value) {
    super(name, value);
    setMaxAge(SECONDS_PER_YEAR);
  }
}


ShowCookies.java Servlet that displays all cookies that arrived in current request. Uses the ServletUtilities class.

ShowCookies.java  Servlet that displays all cookies that arrived in current request. Uses the ServletUtilities  class. 

package cwp;

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

/** Sets six cookies: three that apply only to the current
 *  session (regardless of how long that session lasts)
 *  and three that persist for an hour (regardless of
 *  whether the browser is restarted).
 *

* Taken from Core Web Programming Java 2 Edition * from Prentice Hall and Sun Microsystems Press, * . * May be freely used or adapted. */ public class SetCookies extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { for(int i=0; i<3; i++) { // Default maxAge is -1, indicating cookie // applies only to current browsing session. Cookie cookie = new Cookie("Session-Cookie-" + i, "Cookie-Value-S" + i); response.addCookie(cookie); cookie = new Cookie("Persistent-Cookie-" + i, "Cookie-Value-P" + i); // Cookie is valid for an hour, regardless of whether // user quits browser, reboots computer, or whatever. cookie.setMaxAge(3600); response.addCookie(cookie); } response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Setting Cookies"; out.println (ServletUtilities.headWithTitle(title) + "\n" + "

" + title + "

\n" +
       "There are six cookies associated with this page.\n" +
       "To see them, visit the\n" +
       "\n" +
       "ShowCookies servlet.\n" +
       "

\n" + "Three of the cookies are associated only with the\n" + "current session, while three are persistent.\n" + "Quit the browser, restart, and return to the\n" + "ShowCookies servlet to verify that\n" + "the three long-lived ones persist across sessions.\n" + ""); } } ServletUtilities.java package cwp; import javax.servlet.*; import javax.servlet.http.*; /** Some simple time savers. Note that most are static methods. *

* Taken from Core Web Programming Java 2 Edition * from Prentice Hall and Sun Microsystems Press, * . * May be freely used or adapted. */ public class ServletUtilities { public static final String DOCTYPE = ""; public static String headWithTitle(String title) { return(DOCTYPE + "\n" + "\n" + "\n"); } /** Read a parameter with the specified name, convert it * to an int, and return it. Return the designated default * value if the parameter doesn't exist or if it is an * illegal integer format. */ public static int getIntParameter(HttpServletRequest request, String paramName, int defaultValue) { String paramString = request.getParameter(paramName); int paramValue; try { paramValue = Integer.parseInt(paramString); } catch(NumberFormatException nfe) { // null or bad format paramValue = defaultValue; } return(paramValue); } /** Given an array of Cookies, a name, and a default value, * this method tries to find the value of the cookie with * the given name. If there is no cookie matching the name * in the array, then the default value is returned instead. */ public static String getCookieValue(Cookie[] cookies, String cookieName, String defaultValue) { if (cookies != null) { for(int i=0; i<cookies.length; i++)="" {="" cookie="" if="" (cookiename.equals(cookie.getname()))="" return(cookie.getvalue());="" }="" return(defaultvalue);="" **="" given="" an="" array="" of="" cookies="" and="" a="" name,="" this="" method="" tries="" *="" to="" find="" return="" the="" from="" that="" has="" name.="" there="" is="" no="" matching="" name="" in="" array,="" null="" returned.="" public="" static="" getcookie(cookie[]="" cookies,="" string="" cookiename)="" (cookies="" !="null)" for(int="" i="0;" i<cookies.length;="" return(cookie);="" return(null);="" string,="" replaces="" all="" occurrences="" '<'="" with="" '<',="" '="">' with * '>', and (to handle cases that occur inside attribute * values), all occurrences of double quotes with * '"' and all occurrences of '&' with '&'. * Without such filtering, an arbitrary string * could not safely be inserted in a Web page. */ public static String filter(String input) { StringBuffer filtered = new StringBuffer(input.length()); char c; for(int i=0; i<input.length(); i++)="" {="" c="input.charAt(i);" if="" (c="=" '<')="" filtered.append("<");="" }="" else="" '="">') { filtered.append(">"); } else if (c == '"') { filtered.append("""); } else if (c == '&') { filtered.append("&"); } else { filtered.append(c); } } return(filtered.toString()); } }

SearchEngines.java Servlet that redirects requests to various search engines. Uses the SearchSpec helper class. Accessed by means of SearchEngines.html.

SearchEngines.java  Servlet that redirects requests to various search engines. Uses the SearchSpec  helper class. Accessed by means of SearchEngines.html. 

package cwp;

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

/** Servlet that takes a search string, number of results per
 *  page, and a search engine name, sending the query to
 *  that search engine. Illustrates manipulating
 *  the response status line. It sends a 302 response
 *  (via sendRedirect) if it gets a known search engine,
 *  and sends a 404 response (via sendError) otherwise.
 *  


 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class SearchEngines extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    String searchString = request.getParameter("searchString");
    if ((searchString == null) ||
        (searchString.length() == 0)) {
      reportProblem(response, "Missing search string.");
      return;
    }
    // The URLEncoder changes spaces to "+" signs and other
    // non-alphanumeric characters to "%XY", where XY is the
    // hex value of the ASCII (or ISO Latin-1) character.
    // Browsers always URL-encode form values, so the
    // getParameter method decodes automatically. But since
    // we're just passing this on to another server, we need to
    // re-encode it.
    searchString = URLEncoder.encode(searchString);
    String numResults = request.getParameter("numResults");
    if ((numResults == null) ||
        (numResults.equals("0")) ||
        (numResults.length() == 0)) {
      numResults = "10";
    }
    String searchEngine =
      request.getParameter("searchEngine");
    if (searchEngine == null) {
      reportProblem(response, "Missing search engine name.");
      return;
    }
    SearchSpec[] commonSpecs = SearchSpec.getCommonSpecs();
    for(int i=0; i" + message + "");
  }

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



SearchSpec.java

package cwp;

/** Small class that encapsulates how to construct a
 *  search string for a particular search engine.
 *  


 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  May be freely used or adapted.
 */

public class SearchSpec {
  private String name, baseURL, numResultsSuffix;

  private static SearchSpec[] commonSpecs =
    { new SearchSpec("google",
                     "http://www.google.com/search?q=",
                     "&num="),
      new SearchSpec("infoseek",
                     "http://infoseek.go.com/Titles?qt=",
                     "&nh="),
      new SearchSpec("lycos",
                     "http://lycospro.lycos.com/cgi-bin/" +
                        "pursuit?query=",
                     "&maxhits="),
      new SearchSpec("hotbot",
                     "http://www.hotbot.com/?MT=",
                     "&DC=")
    };

  public SearchSpec(String name,
                    String baseURL,
                    String numResultsSuffix) {
    this.name = name;
    this.baseURL = baseURL;
    this.numResultsSuffix = numResultsSuffix;
  }

  public String makeURL(String searchString,
                        String numResults) {
    return(baseURL + searchString +
           numResultsSuffix + numResults);
  }

  public String getName() {
    return(name);
  }

  public static SearchSpec[] getCommonSpecs() {
    return(commonSpecs);
  }
}

SetCookies.java Servlet that sets a few persistent and session cookies. Uses the ServletUtilities class to simplify the DOCTYPE and HEAD output.

SetCookies.java  Servlet that sets a few persistent and session cookies. Uses the ServletUtilities  class to simplify the DOCTYPE and HEAD output.

 

package cwp;

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

/** Sets six cookies: three that apply only to the current
 *  session (regardless of how long that session lasts)
 *  and three that persist for an hour (regardless of
 *  whether the browser is restarted).
 *  


 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class SetCookies extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    for(int i=0; i<3; i++) {
      // Default maxAge is -1, indicating cookie
      // applies only to current browsing session.
      Cookie cookie = new Cookie("Session-Cookie-" + i,
                                 "Cookie-Value-S" + i);
      response.addCookie(cookie);
      cookie = new Cookie("Persistent-Cookie-" + i,
                          "Cookie-Value-P" + i);
      // Cookie is valid for an hour, regardless of whether
      // user quits browser, reboots computer, or whatever.
      cookie.setMaxAge(3600);
      response.addCookie(cookie);
    }
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Setting Cookies";
    out.println
      (ServletUtilities.headWithTitle(title) +
       "\n" +
       "
" + title + "
\n" +
       "There are six cookies associated with this page.\n" +
       "To see them, visit the\n" +
       "\n" +
       "ShowCookies servlet.\n" +
       "

\n" +
       "Three of the cookies are associated only with the\n" +
       "current session, while three are persistent.\n" +
       "Quit the browser, restart, and return to the\n" +
       "ShowCookies servlet to verify that\n" +
       "the three long-lived ones persist across sessions.\n" +
       "");
  }
}



ServletUtilities.java

package cwp;

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

/** Some simple time savers. Note that most are static methods.
 *  


 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class ServletUtilities {
  public static final String DOCTYPE =
    "";

  public static String headWithTitle(String title) {
    return(DOCTYPE + "\n" +
           "\n" +
           "\n");
  }

  /** Read a parameter with the specified name, convert it
   *  to an int, and return it. Return the designated default
   *  value if the parameter doesn't exist or if it is an
   *  illegal integer format.
  */

  public static int getIntParameter(HttpServletRequest request,
                                    String paramName,
                                    int defaultValue) {
    String paramString = request.getParameter(paramName);
    int paramValue;
    try {
      paramValue = Integer.parseInt(paramString);
    } catch(NumberFormatException nfe) { // null or bad format
      paramValue = defaultValue;
    }
    return(paramValue);
  }

  /** Given an array of Cookies, a name, and a default value,
   *  this method tries to find the value of the cookie with
   *  the given name. If there is no cookie matching the name
   *  in the array, then the default value is returned instead.
   */

  public static String getCookieValue(Cookie[] cookies,
                                      String cookieName,
                                      String defaultValue) {
    if (cookies != null) {
      for(int i=0; i' with
   *  '>', and (to handle cases that occur inside attribute
   *  values), all occurrences of double quotes with
   *  '"' and all occurrences of '&' with '&'.
   *  Without such filtering, an arbitrary string
   *  could not safely be inserted in a Web page.
   */

  public static String filter(String input) {
    StringBuffer filtered = new StringBuffer(input.length());
    char c;
    for(int i=0; i') {
        filtered.append(">");
      } else if (c == '"') {
        filtered.append(""");
      } else if (c == '&') {
        filtered.append("&");
      } else {
        filtered.append(c);
      }
    }
    return(filtered.toString());
  }
}

EncodedPage.java Servlet that shows the bandwidth benefits of gzipping pages to browsers that can handle gzip. Uses the ServletUtilities class to simplify the DOCTYPE and HEAD output.

EncodedPage.java  Servlet that shows the bandwidth benefits of gzipping pages to browsers that can handle gzip. Uses the ServletUtilities  class to simplify the DOCTYPE and HEAD output. 

package cwp;

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

/** Example showing benefits of gzipping pages to browsers
 *  that can handle gzip.
 *  


 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class EncodedPage extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    String encodings = request.getHeader("Accept-Encoding");
    String encodeFlag = request.getParameter("encoding");
    PrintWriter out;
    String title;
    if ((encodings != null) &&
        (encodings.indexOf("gzip") != -1) &&
        !"none".equals(encodeFlag)) {
      title = "Page Encoded with GZip";
      OutputStream out1 = response.getOutputStream();
      out = new PrintWriter(new GZIPOutputStream(out1), false);
      response.setHeader("Content-Encoding", "gzip");
    } else {
      title = "Unencoded Page";
      out = response.getWriter();
    }
    out.println(ServletUtilities.headWithTitle(title) +
                "\n" +
                "
" + title + "
\n");
    String line = "Blah, blah, blah, blah, blah. " +
                  "Yadda, yadda, yadda, yadda.";
    for(int i=0; i<10000; i++) {
      out.println(line);
    }
    out.println("");
    out.close();
  }
}

PrimeNumbers.java Servlet that processes a request to generate n prime numbers, each with at least m digits. If these results are not complete, it sends a Refresh header instructing the browser to ask for new results a little while later. Uses the Primes

PrimeNumbers.java  Servlet that processes a request to generate n prime numbers, each with at least m digits. If these results are not complete, it sends a Refresh header instructing the browser to ask for new results a little while later. Uses the Primes, PrimeList, and ServletUtilities  classes.

 

package cwp;

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

/** Servlet that processes a request to generate n
 *  prime numbers, each with at least m digits.
 *  It performs the calculations in a low-priority background
 *  thread, returning only the results it has found so far.
 *  If these results are not complete, it sends a Refresh
 *  header instructing the browser to ask for new results a
 *  little while later. It also maintains a list of a
 *  small number of previously calculated prime lists
 *  to return immediately to anyone who supplies the
 *  same n and m as a recent completed computation.
 *  


 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class PrimeNumbers extends HttpServlet {
  private Vector primeListVector = new Vector();
  private int maxPrimeLists = 30;

  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    int numPrimes =
      ServletUtilities.getIntParameter(request,
                                       "numPrimes", 50);
    int numDigits =
      ServletUtilities.getIntParameter(request,
                                       "numDigits", 120);
    PrimeList primeList =
      findPrimeList(primeListVector, numPrimes, numDigits);
    if (primeList == null) {
      primeList = new PrimeList(numPrimes, numDigits, true);
      // Multiple servlet request threads share the instance
      // variables (fields) of PrimeNumbers. So
      // synchronize all access to servlet fields.
      synchronized(primeListVector) {
        if (primeListVector.size() >= maxPrimeLists)
          primeListVector.removeElementAt(0);
        primeListVector.addElement(primeList);
      }
    }
    Vector currentPrimes = primeList.getPrimes();
    int numCurrentPrimes = currentPrimes.size();
    int numPrimesRemaining = (numPrimes - numCurrentPrimes);
    boolean isLastResult = (numPrimesRemaining == 0);
    if (!isLastResult) {
      response.setHeader("Refresh", "5");
    }
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Some " + numDigits + "-Digit Prime Numbers";
    out.println(ServletUtilities.headWithTitle(title) +
                "\n" +
                "
" + title + "
\n" +
                "
Primes found with " + numDigits +
                " or more digits: " + numCurrentPrimes +
                ".
");
    if (isLastResult)
      out.println("Done searching.");
    else
      out.println("Still looking for " + numPrimesRemaining +
                  " more...");
    out.println("

    ");
        for(int i=0; i" + currentPrimes.elementAt(i));
        }
        out.println("

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

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

  // See if there is an existing ongoing or completed
  // calculation with the same number of primes and number
  // of digits per prime. If so, return those results instead
  // of starting a new background thread. Keep this list
  // small so that the Web server doesn't use too much memory.
  // Synchronize access to the list since there may be
  // multiple simultaneous requests.

  private PrimeList findPrimeList(Vector primeListVector,
                                  int numPrimes,
                                  int numDigits) {
    synchronized(primeListVector) {
      for(int i=0; i
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class Primes {
  // Note that BigInteger.ZERO was new in JDK 1.2, and 1.1
  // code is being used to support the most servlet engines.
  private static final BigInteger ZERO = new BigInteger("0");
  private static final BigInteger ONE = new BigInteger("1");
  private static final BigInteger TWO = new BigInteger("2");

  // Likelihood of false prime is less than 1/2^ERR_VAL
  // Assumedly BigInteger uses the Miller-Rabin test or
  // equivalent, and thus is NOT fooled by Carmichael numbers.
  // See section 33.8 of Cormen et al's Introduction to
  // Algorithms for details.
  private static final int ERR_VAL = 100;

  public static BigInteger nextPrime(BigInteger start) {
    if (isEven(start))
      start = start.add(ONE);
    else
      start = start.add(TWO);
    if (start.isProbablePrime(ERR_VAL))
      return(start);
    else
      return(nextPrime(start));
  }

  private static boolean isEven(BigInteger n) {
    return(n.mod(TWO).equals(ZERO));
  }

  private static StringBuffer[] digits =
    { new StringBuffer("0"), new StringBuffer("1"),
      new StringBuffer("2"), new StringBuffer("3"),
      new StringBuffer("4"), new StringBuffer("5"),
      new StringBuffer("6"), new StringBuffer("7"),
      new StringBuffer("8"), new StringBuffer("9") };

  private static StringBuffer randomDigit() {
    int index = (int)Math.floor(Math.random() * 10);
    return(digits[index]);
  }

  public static BigInteger random(int numDigits) {
    StringBuffer s = new StringBuffer("");
    for(int i=0; i 0)
      numDigits = Integer.parseInt(args[0]);
    else
      numDigits = 150;
    BigInteger start = random(numDigits);
    for(int i=0; i<50; i++) {
      start = nextPrime(start);
      System.out.println("Prime " + i + " = " + start);
    }
  }
}



PrimeList.java
package cwp;

import java.util.*;
import java.math.BigInteger;

/** Creates a Vector of large prime numbers, usually in
 *  a low-priority background thread. Provides a few small
 *  thread-safe access methods.
 *  


 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class PrimeList implements Runnable {
  private Vector primesFound;
  private int numPrimes, numDigits;

  /** Finds numPrimes prime numbers, each of which are
   *  numDigits long or longer. You can set it to only
   *  return when done, or have it return immediately,
   *  and you can later poll it to see how far it
   *  has gotten.
   */

  public PrimeList(int numPrimes, int numDigits,
                   boolean runInBackground) {
    // Using Vector instead of ArrayList
    // to support JDK 1.1 servlet engines
    primesFound = new Vector(numPrimes);
    this.numPrimes = numPrimes;
    this.numDigits = numDigits;
    if (runInBackground) {
      Thread t = new Thread(this);
      // Use low priority so you don't slow down server.
      t.setPriority(Thread.MIN_PRIORITY);
      t.start();
    } else {
      run();
    }
  }

  public void run() {
    BigInteger start = Primes.random(numDigits);
    for(int i=0; i
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class ServletUtilities {
  public static final String DOCTYPE =
    "";

  public static String headWithTitle(String title) {
    return(DOCTYPE + "\n" +
           "\n" +
           "\n");
  }

  /** Read a parameter with the specified name, convert it
   *  to an int, and return it. Return the designated default
   *  value if the parameter doesn't exist or if it is an
   *  illegal integer format.
  */

  public static int getIntParameter(HttpServletRequest request,
                                    String paramName,
                                    int defaultValue) {
    String paramString = request.getParameter(paramName);
    int paramValue;
    try {
      paramValue = Integer.parseInt(paramString);
    } catch(NumberFormatException nfe) { // null or bad format
      paramValue = defaultValue;
    }
    return(paramValue);
  }

  /** Given an array of Cookies, a name, and a default value,
   *  this method tries to find the value of the cookie with
   *  the given name. If there is no cookie matching the name
   *  in the array, then the default value is returned instead.
   */

  public static String getCookieValue(Cookie[] cookies,
                                      String cookieName,
                                      String defaultValue) {
    if (cookies != null) {
      for(int i=0; i' with
   *  '>', and (to handle cases that occur inside attribute
   *  values), all occurrences of double quotes with
   *  '"' and all occurrences of '&' with '&'.
   *  Without such filtering, an arbitrary string
   *  could not safely be inserted in a Web page.
   */

  public static String filter(String input) {
    StringBuffer filtered = new StringBuffer(input.length());
    char c;
    for(int i=0; i') {
        filtered.append(">");
      } else if (c == '"') {
        filtered.append(""");
      } else if (c == '&') {
        filtered.append("&");
      } else {
        filtered.append(c);
      }
    }
    return(filtered.toString());
  }
}

ShowRequestHeaders.java Servlet that shows all request headers sent by browser in current request.

ShowRequestHeaders.java  Servlet that shows all request headers sent by browser in current request. 

package cwp;

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

/** Shows all the request headers sent on this request.
 *
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class ShowRequestHeaders extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Servlet Example: Showing Request Headers";
    out.println(ServletUtilities.headWithTitle(title) +
                "\n" +
                "
" + title + "
\n" +
                "Request Method: " +
                request.getMethod() + "
\n" +
                "Request URI: " +
                request.getRequestURI() + "
\n" +
                "Request Protocol: " +
                request.getProtocol() + "

\n" +
                "\n" +
                "\n" +
                "
Header Name
Header Value");
    Enumeration headerNames = request.getHeaderNames();
    while(headerNames.hasMoreElements()) {
      String headerName = (String)headerNames.nextElement();
      out.println("
" + headerName);
      out.println("
" + request.getHeader(headerName));
    }
    out.println("
\n");
  }

  /** Let the same servlet handle both GET and POST. */

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

ServletUtilities.java Utility class that, among other things, contains the static filter method that replaces special HTML characters with their HTML character entities.

ServletUtilities.java  Utility class that, among other things, contains the static filter  method that replaces special HTML characters with their HTML character entities. 

package cwp;

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

/** Some simple time savers. Note that most are static methods.
 *  


 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class ServletUtilities {
  public static final String DOCTYPE =
    "";

  public static String headWithTitle(String title) {
    return(DOCTYPE + "\n" +
           "\n" +
           "\n");
  }

  /** Read a parameter with the specified name, convert it
   *  to an int, and return it. Return the designated default
   *  value if the parameter doesn't exist or if it is an
   *  illegal integer format.
  */

  public static int getIntParameter(HttpServletRequest request,
                                    String paramName,
                                    int defaultValue) {
    String paramString = request.getParameter(paramName);
    int paramValue;
    try {
      paramValue = Integer.parseInt(paramString);
    } catch(NumberFormatException nfe) { // null or bad format
      paramValue = defaultValue;
    }
    return(paramValue);
  }

  /** Given an array of Cookies, a name, and a default value,
   *  this method tries to find the value of the cookie with
   *  the given name. If there is no cookie matching the name
   *  in the array, then the default value is returned instead.
   */

  public static String getCookieValue(Cookie[] cookies,
                                      String cookieName,
                                      String defaultValue) {
    if (cookies != null) {
      for(int i=0; i' with
   *  '>', and (to handle cases that occur inside attribute
   *  values), all occurrences of double quotes with
   *  '"' and all occurrences of '&' with '&'.
   *  Without such filtering, an arbitrary string
   *  could not safely be inserted in a Web page.
   */

  public static String filter(String input) {
    StringBuffer filtered = new StringBuffer(input.length());
    char c;
    for(int i=0; i') {
        filtered.append(">");
      } else if (c == '"') {
        filtered.append(""");
      } else if (c == '&') {
        filtered.append("&");
      } else {
        filtered.append(c);
      }
    }
    return(filtered.toString());
  }
}

ThreeParams.java Servlet that reads and displays three request (form) parameters. Uses the ServletUtilities class.

ThreeParams.java  Servlet that reads and displays three request (form) parameters. Uses the ServletUtilities  class. 

package cwp;

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

/** Simple servlet that reads three parameters from the
 *  form data.
 *  


 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class ThreeParams extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Reading Three Request Parameters";
    out.println(ServletUtilities.headWithTitle(title) +
                "\n" +
                "
" + title + "
\n" +
                "

    \n" +
                    "  
    param1: "
                    + request.getParameter("param1") + "\n" +
                    "  
    param2: "
                    + request.getParameter("param2") + "\n" +
                    "  
    param3: "
                    + request.getParameter("param3") + "\n" +
                    "

\n" +
                "");
  }
}

ShowMessage.java Servlet that demonstrates the use of initialization parameters.

ShowMessage.java  Servlet that demonstrates the use of initialization parameters. Remember that, to use this servlet, you have to do three things:

    * Put the modified web.xml file in the WEB-INF directory.
    * Restart the server.
    * Use the registered servlet name (i.e., the URL http://host/servlet/ShowMsg), not the raw servlet name (i.e., the URL http://host/servlet/cwp.ShowMessage). 


package cwp;

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

/** Example using servlet initialization. Here, the message
 *  to print and the number of times the message should be
 *  repeated is taken from the init parameters.
 *  


 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class ShowMessage extends HttpServlet {
  private String message;
  private String defaultMessage = "No message.";
  private int repeats = 1;

  public void init() throws ServletException {
    ServletConfig config = getServletConfig();
    message = config.getInitParameter("message");
    if (message == null) {
      message = defaultMessage;
    }
    try {
      String repeatString = config.getInitParameter("repeats");
      repeats = Integer.parseInt(repeatString);
    } catch(NumberFormatException nfe) {
      // NumberFormatException handles case where repeatString
      // is null *and* case where it is in an illegal format.
    }
  }

  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "The ShowMessage Servlet";
    out.println(ServletUtilities.headWithTitle(title) +
                "\n" +
                "
" + title + "
");
    for(int i=0; i" + message + "
");
    }
    out.println("");
  }
}


web.xml



?

ShowMsg
cwp.ShowMessage
?

message
Shibboleth

?

repeats
5


ServletUtilities.java Utility class that simplifies the output of the DOCTYPE and HEAD in servlets, among other things. Used by most remaining servlets in the chapter.

ServletUtilities.java  Utility class that simplifies the output of the DOCTYPE and HEAD  in servlets, among other things. Used by most remaining servlets in the chapter. 

package cwp;

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

/** Some simple time savers. Note that most are static methods.
 *  


 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class ServletUtilities {
  public static final String DOCTYPE =
    "";

  public static String headWithTitle(String title) {
    return(DOCTYPE + "\n" +
           "\n" +
           "\n");
  }

  /** Read a parameter with the specified name, convert it
   *  to an int, and return it. Return the designated default
   *  value if the parameter doesn't exist or if it is an
   *  illegal integer format.
  */

  public static int getIntParameter(HttpServletRequest request,
                                    String paramName,
                                    int defaultValue) {
    String paramString = request.getParameter(paramName);
    int paramValue;
    try {
      paramValue = Integer.parseInt(paramString);
    } catch(NumberFormatException nfe) { // null or bad format
      paramValue = defaultValue;
    }
    return(paramValue);
  }

  /** Given an array of Cookies, a name, and a default value,
   *  this method tries to find the value of the cookie with
   *  the given name. If there is no cookie matching the name
   *  in the array, then the default value is returned instead.
   */

  public static String getCookieValue(Cookie[] cookies,
                                      String cookieName,
                                      String defaultValue) {
    if (cookies != null) {
      for(int i=0; i' with
   *  '>', and (to handle cases that occur inside attribute
   *  values), all occurrences of double quotes with
   *  '"' and all occurrences of '&' with '&'.
   *  Without such filtering, an arbitrary string
   *  could not safely be inserted in a Web page.
   */

  public static String filter(String input) {
    StringBuffer filtered = new StringBuffer(input.length());
    char c;
    for(int i=0; i') {
        filtered.append(">");
      } else if (c == '"') {
        filtered.append(""");
      } else if (c == '&') {
        filtered.append("&");
      } else {
        filtered.append(c);
      }
    }
    return(filtered.toString());
  }
}


SimplerHelloWWW.java Servlet that uses ServletUtilities to simplify the generation of the DOCTYPE and HEAD part of the servlet.

SimplerHelloWWW.java  Servlet that uses ServletUtilities  to simplify the generation of the DOCTYPE and HEAD part of the servlet.

package cwp;

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

/** Simple servlet that generates HTML. This variation of
 *  HelloWWW uses the ServletUtilities utility class
 *  to generate the DOCTYPE, HEAD, and TITLE.
 *  


 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class SimplerHelloWWW extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println(ServletUtilities.headWithTitle("Hello WWW") +
                "\n" +
                "
Hello WWW
\n" +
                "");
  }
}


Servlet Utilities

package cwp;

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

/** Some simple time savers. Note that most are static methods.
 *  


 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  May be freely used or adapted.
 */

public class ServletUtilities {
  public static final String DOCTYPE =
    "";

  public static String headWithTitle(String title) {
    return(DOCTYPE + "\n" +
           "\n" +
           "\n");
  }

  /** Read a parameter with the specified name, convert it
   *  to an int, and return it. Return the designated default
   *  value if the parameter doesn't exist or if it is an
   *  illegal integer format.
  */
  
  public static int getIntParameter(HttpServletRequest request,
                                    String paramName,
                                    int defaultValue) {
    String paramString = request.getParameter(paramName);
    int paramValue;
    try {
      paramValue = Integer.parseInt(paramString);
    } catch(NumberFormatException nfe) { // null or bad format
      paramValue = defaultValue;
    }
    return(paramValue);
  }

  /** Given an array of Cookies, a name, and a default value,
   *  this method tries to find the value of the cookie with
   *  the given name. If there is no cookie matching the name
   *  in the array, then the default value is returned instead.
   */
  
  public static String getCookieValue(Cookie[] cookies,
                                      String cookieName,
                                      String defaultValue) {
    if (cookies != null) {
      for(int i=0; i' with
   *  '>', and (to handle cases that occur inside attribute
   *  values), all occurrences of double quotes with
   *  '"' and all occurrences of '&' with '&'.
   *  Without such filtering, an arbitrary string
   *  could not safely be inserted in a Web page.
   */

  public static String filter(String input) {
    StringBuffer filtered = new StringBuffer(input.length());
    char c;
    for(int i=0; i') {
        filtered.append(">");
      } else if (c == '"') {
        filtered.append(""");
      } else if (c == '&') {
        filtered.append("&");
      } else {
        filtered.append(c);
      }
    }
    return(filtered.toString());
  }
}

HelloWWW.java Servlet that generates HTML. This and all remaining servlets are in the cwp package and therefore should be installed in the cwp subdirectory.

HelloWWW.java  Servlet that generates HTML. This and all remaining servlets are in the cwp package and therefore should be installed in the cwp subdirectory.

package cwp;

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

/** Simple servlet that generates HTML.
 *  
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class HelloWWW extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String docType =
      "\n";
    out.println(docType +
                "\n" +
                "\n" +
                "\n" +
                "

HelloWorld.java Simple servlet that generates plain text.

HelloWorld.java  Simple servlet that generates plain text. 

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

/** Very simplistic servlet that generates plain text.
 *  


 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class HelloWorld extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    out.println("Hello World");
  }
}



ServletTemplate.java Starting point for servlets.

ServletTemplate.java Starting point for servlets. 


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

/** Servlet template.
 *  


 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

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

    // Use "request" to read incoming HTTP headers
    // (e.g., cookies) and query data from HTML forms.

    // Use "response" to specify the HTTP response status
    // code and headers (e.g. the content type, cookies).

    PrintWriter out = response.getWriter();
    // Use "out" to send content to browser
  }
}



StringBean.java Bean used to demonstrate jsp:useBean, etc. Remember to install it in the WEB-INF/classes/cwp directory.

StringBean.java  Bean used to demonstrate jsp:useBean, etc. Remember to install it in the WEB-INF/classes/cwp directory. 

package cwp;

/** A simple bean that has a single String property
 *  called message.
 *  <P>
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class StringBean {
  private String message = "No message specified";

  public String getMessage() {
    return(message);
  }

  public void setMessage(String message) {
    this.message = message;
  }
}

PluginApplet.jsp Page that demonstrates the use of jsp:plugin.

PluginApplet.jsp  Page that demonstrates the use of jsp:plugin. Requires you to compile and install PluginApplet.java, TextPanel.java, DrawingPanel.java, and WindowUtilities.java  Since these are classes sent to the client to used by applets, the .class files should be in the same directory as the JSP page, not in the WEB-INF/classes directory where classes the server uses go. Uses the JSP-Styles  style sheet. Warning: Allaire JRun 3.0 SP2 does not properly support jsp:plugin.


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- 
Example of using jsp:plugin for an applet that uses Java 2. 

Taken from Core Web Programming Java 2 Edition
from Prentice Hall and Sun Microsystems Press,
.
May be freely used or adapted.
-->
<HTML>
<HEAD>
<TITLE>Using jsp:plugin</TITLE>
<LINK REL=STYLESHEET
      HREF="JSP-Styles.css"
      TYPE="text/css">
</HEAD>

<BODY>

<TABLE BORDER=5 ALIGN="CENTER">
  <TR><TH CLASS="TITLE">
      Using jsp:plugin</TABLE>
<P>
<CENTER>
<jsp:plugin type="applet" 
            code="PluginApplet.class"
            width="370" height="420">
</jsp:plugin>
</CENTER>

</BODY>
</HTML>

PluginApplet.java

import javax.swing.*;

/** An applet that uses Swing and Java 2D and thus requires
 *  the Java Plug-In.
 *  <P>
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class PluginApplet extends JApplet {
  public void init() {
    WindowUtilities.setNativeLookAndFeel();
    setContentPane(new TextPanel());
  }
}


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

/** JPanel that places a panel with text drawn at various angles
 *  in the top part of the window and a JComboBox containing
 *  font choices in the bottom part.
 *  <P>
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class TextPanel extends JPanel
                       implements ActionListener {
  private JComboBox fontBox;
  private DrawingPanel drawingPanel;

  public TextPanel() {
    GraphicsEnvironment env =
      GraphicsEnvironment.getLocalGraphicsEnvironment();
    String[] fontNames = env.getAvailableFontFamilyNames();
    fontBox = new JComboBox(fontNames);
    setLayout(new BorderLayout());
    JPanel fontPanel = new JPanel();
    fontPanel.add(new JLabel("Font:"));
    fontPanel.add(fontBox);
    JButton drawButton = new JButton("Draw");
    drawButton.addActionListener(this);
    fontPanel.add(drawButton);
    add(fontPanel, BorderLayout.SOUTH);
    drawingPanel = new DrawingPanel();
    fontBox.setSelectedItem("Serif");
    drawingPanel.setFontName("Serif");
    add(drawingPanel, BorderLayout.CENTER);
  }

  public void actionPerformed(ActionEvent e) {
    drawingPanel.setFontName((String)fontBox.getSelectedItem());
    drawingPanel.repaint();
  }
}


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

/** A window with text drawn at an angle. The font is
 *  set by means of the setFontName method.
 *  <P>
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

class DrawingPanel extends JPanel {
  private Ellipse2D.Double circle =
    new Ellipse2D.Double(10, 10, 350, 350);
  private GradientPaint gradient =
    new GradientPaint(0, 0, Color.red, 180, 180, Color.yellow,
                      true); // true means to repeat pattern
  private Color[] colors = { Color.white, Color.black };

  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D)g;
    g2d.setPaint(gradient);
    g2d.fill(circle);
    g2d.translate(185, 185);
    for (int i=0; i<16; i++) {
      g2d.rotate(Math.PI/8.0);
      g2d.setPaint(colors[i%2]);
      g2d.drawString("jsp:plugin", 0, 0);
    }
  }

  public void setFontName(String fontName) {
    setFont(new Font(fontName, Font.BOLD, 35));
  }
}


WindowUtilities.java

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

/** A few utilities that simplify using windows in Swing.
 *  <P>
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class WindowUtilities {

  /** Tell system to use native look and feel, as in previous
   *  releases. Metal (Java) LAF is the default otherwise.
   */

  public static void setNativeLookAndFeel() {
    try {
      UIManager.setLookAndFeel
        (UIManager.getSystemLookAndFeelClassName());
    } catch(Exception e) {
      System.out.println("Error setting native LAF: " + e);
    }
  }

  public static void setJavaLookAndFeel() {
    try {
      UIManager.setLookAndFeel
        (UIManager.getCrossPlatformLookAndFeelClassName());
    } catch(Exception e) {
      System.out.println("Error setting Java LAF: " + e);
    }
  }

  public static void setMotifLookAndFeel() {
    try {
      UIManager.setLookAndFeel
        ("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
    } catch(Exception e) {
      System.out.println("Error setting Motif LAF: " + e);
    }
  }

  /** A simplified way to see a JPanel or other Container.
   *  Pops up a JFrame with specified Container
   *  as the content pane.
   */

  public static JFrame openInJFrame(Container content,
                                    int width,
                                    int height,
                                    String title,
                                    Color bgColor) {
    JFrame frame = new JFrame(title);
    frame.setBackground(bgColor);
    content.setBackground(bgColor);
    frame.setSize(width, height);
    frame.setContentPane(content);
    frame.addWindowListener(new ExitListener());
    frame.setVisible(true);
    return(frame);
  }

  /** Uses Color.white as the background color. */

  public static JFrame openInJFrame(Container content,
                                    int width,
                                    int height,
                                    String title) {
    return(openInJFrame(content, width, height, title, Color.white));
  }

  /** Uses Color.white as the background color, and the
   *  name of the Container's class as the JFrame title.
   */

  public static JFrame openInJFrame(Container content,
                                    int width,
                                    int height) {
    return(openInJFrame(content, width, height,
                        content.getClass().getName(),
                        Color.white));
  }
}

BGColor.jsp Page that demonstrates JSP scriptlets. Uses the JSP-Styles style sheet.

BGColor.jsp  Page that demonstrates JSP scriptlets. Uses the JSP-Styles  style sheet.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!--    
Taken from Core Web Programming Java 2 Edition
from Prentice Hall and Sun Microsystems Press,
.
May be freely used or adapted.
-->
<HTML>
<HEAD>
  <TITLE>Color Testing</TITLE>
</HEAD>
<% 
String bgColor = request.getParameter("bgColor");
boolean hasExplicitColor = true;
if (bgColor == null) {
  hasExplicitColor = false;
  bgColor = "WHITE";
} 
%>
<BODY BGCOLOR="<%= bgColor %>">
<H2 ALIGN="CENTER">Color Testing</H2>
<%
if (hasExplicitColor) {
  out.println("You supplied an explicit background color of " +
              bgColor + ".");
} else {
  out.println("Using default background color of WHITE. " +
              "Supply the bgColor request attribute to try " +
              "a standard color or RRGGBB value, or to see " +
              "if your browser supports X11 color names.");
}
%>
</BODY>
</HTML>

Excel.jsp Page that demonstrates the use of JSP to build Excel spreadsheets

Excel.jsp  Page that demonstrates the use of JSP to build Excel spreadsheets

First    Last    Email Address
Marty    Hall    hall@corewebprogramming.com
Larry    Brown    brown@corewebprogramming.com
Bill    Gates    gates@sun.com
Larry    Ellison    ellison@microsoft.com
<%@ page contentType="application/vnd.ms-excel" %>
<%-- There are tabs, not spaces, between columns. --%>

Expressions.jsp Page that demonstrates JSP expressions. Uses the JSP-Styles style sheet.

Expressions.jsp  Page that demonstrates JSP expressions. Uses the JSP-Styles  style sheet. 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- 
Example of JSP Expressions. 
   
Taken from Core Web Programming Java 2 Edition
from Prentice Hall and Sun Microsystems Press,
.
May be freely used or adapted.
-->
<HTML>
<HEAD>
<TITLE>JSP Expressions</TITLE>
<META NAME="keywords"
      CONTENT="JSP,expressions,JavaServer,Pages,servlets">
<META NAME="description"
      CONTENT="A quick example of JSP expressions.">
<LINK REL=STYLESHEET
      HREF="JSP-Styles.css"
      TYPE="text/css">
</HEAD>

<BODY>
<H2>JSP Expressions</H2>
<UL>
  <LI>Current time: <%= new java.util.Date() %>
  <LI>Your hostname: <%= request.getRemoteHost() %>
  <LI>Your session ID: <%= session.getId() %>
  <LI>The <CODE>testParam</CODE> form parameter:
      <%= request.getParameter("testParam") %>
</UL>
</BODY>
</HTML>

ImportAttribute.jsp Page that demonstrates the import attribute of the page directive. Uses the ServletUtilities class

ImportAttribute.jsp  Page that demonstrates the import attribute of the page directive. Uses the ServletUtilities class (Check Servlet Section)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!--
Example of the import attribute of the page directive.

Taken from Core Web Programming Java 2 Edition
from Prentice Hall and Sun Microsystems Press,
.
May be freely used or adapted.
-->
<HTML>
<HEAD>
<TITLE>The import Attribute</TITLE>
<LINK REL=STYLESHEET
HREF="JSP-Styles.css"
TYPE="text/css">
</HEAD>

<BODY>
<H2>The import Attribute</H2>
<%-- JSP page directive --%>
<%@ page import="java.util.*,cwp.*" %>

<%-- JSP Declaration --%>
<%!
private String randomID() {
int num = (int)(Math.random()*10000000.0);
return("id" + num);
}

private final String NO_VALUE = "<I>No Value</I>";
%>

<%-- JSP Scriptlet --%>
<%
Cookie[] cookies = request.getCookies();
String oldID =
ServletUtilities.getCookieValue(cookies, "userID", NO_VALUE);
if (oldID.equals(NO_VALUE)) {
String newID = randomID();
Cookie cookie = new Cookie("userID", newID);
response.addCookie(cookie);
}
%>

<%-- JSP Expressions --%>
This page was accessed on <%= new Date() %> with a userID
cookie of <%= oldID %>.

</BODY>
</HTML>

QueryViewer.java: An interactive database query viewer

# QueryViewer.java  An interactive database query viewer. Connects to the specified Oracle or Sybase database, executes a query, and presents the results in a JTable. Uses the following file:

    * DBResultsTableModel.java Simple class that tells a JTable how to extract relevant data from a DBResults object (which is used to store the results from a database query). 
############################################################################

  package cwp;

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

/** An interactive database query viewer. Connects to
 *  the specified Oracle or Sybase database, executes a query,
 *  and presents the results in a JTable.
 *  


 */

public class QueryViewer extends JFrame
                         implements ActionListener{
  public static void main(String[] args) {
    new QueryViewer();
  }

  private JTextField hostField, dbNameField,
                     queryField, usernameField;
  private JRadioButton oracleButton, sybaseButton;
  private JPasswordField passwordField;
  private JButton showResultsButton;
  Container contentPane;
  private JPanel tablePanel;
  
  public QueryViewer () {
    super("Database Query Viewer");
    WindowUtilities.setNativeLookAndFeel();
    addWindowListener(new ExitListener());
    contentPane = getContentPane();
    contentPane.add(makeControlPanel(), BorderLayout.NORTH);
    pack();
    setVisible(true);
  }

  /** When the "Show Results" button is pressed or
   *  RETURN is hit while the query textfield has the
   *  keyboard focus, a database lookup is performed,
   *  the results are placed in a JTable, and the window
   *  is resized to accommodate the table.
   */
  
  public void actionPerformed(ActionEvent event) {
    String host = hostField.getText();
    String dbName = dbNameField.getText();
    String username = usernameField.getText();
    String password =
      String.valueOf(passwordField.getPassword());
    String query = queryField.getText();
    int vendor;
    if (oracleButton.isSelected()) {
      vendor = DriverUtilities.ORACLE;
    } else {
      vendor = DriverUtilities.SYBASE;
    }
    if (tablePanel != null) {
      contentPane.remove(tablePanel);
    }
    tablePanel = makeTablePanel(host, dbName, vendor,
                                username, password,
                                query);
    contentPane.add(tablePanel, BorderLayout.CENTER);
    pack();
  }

  // Executes a query and places the result in a
  // JTable that is, in turn, inside a JPanel.
  
  private JPanel makeTablePanel(String host,
                                String dbName,
                                int vendor,
                                String username,
                                String password,
                                String query) {
    String driver = DriverUtilities.getDriver(vendor);
    String url = DriverUtilities.makeURL(host, dbName, vendor);
    DBResults results =
      DatabaseUtilities.getQueryResults(driver, url,
                                        username, password,
                                        query, true);
    JPanel panel = new JPanel(new BorderLayout());
    if (results == null) {
      panel.add(makeErrorLabel());
      return(panel);
    }
    DBResultsTableModel model =
      new DBResultsTableModel(results);
    JTable table = new JTable(model);
    table.setFont(new Font("Serif", Font.PLAIN, 17));
    table.setRowHeight(28);
    JTableHeader header = table.getTableHeader();
    header.setFont(new Font("SansSerif", Font.BOLD, 13));
    panel.add(table, BorderLayout.CENTER);
    panel.add(header, BorderLayout.NORTH);
    panel.setBorder
      (BorderFactory.createTitledBorder("Query Results"));
    return(panel);
  }

  // The panel that contains the textfields, checkboxes,
  // and button.
  
  private JPanel makeControlPanel() {
    JPanel panel = new JPanel(new GridLayout(0, 1));
    panel.add(makeHostPanel());
    panel.add(makeUsernamePanel());
    panel.add(makeQueryPanel());
    panel.add(makeButtonPanel());
    panel.setBorder
      (BorderFactory.createTitledBorder("Query Data"));
    return(panel);
  }

  // The panel that has the host and db name textfield and
  // the driver radio buttons. Placed in control panel.
  
  private JPanel makeHostPanel() {
    JPanel panel = new JPanel();
    panel.add(new JLabel("Host:"));
    hostField = new JTextField(15);
    panel.add(hostField);
    panel.add(new JLabel("    DB Name:"));
    dbNameField = new JTextField(15);
    panel.add(dbNameField);
    panel.add(new JLabel("    Driver:"));
    ButtonGroup vendorGroup = new ButtonGroup();
    oracleButton = new JRadioButton("Oracle", true);
    vendorGroup.add(oracleButton);
    panel.add(oracleButton);
    sybaseButton = new JRadioButton("Sybase");
    vendorGroup.add(sybaseButton);
    panel.add(sybaseButton);
    return(panel);
  }

  // The panel that has the username and password textfields.
  // Placed in control panel.
  
  private JPanel makeUsernamePanel() {
    JPanel panel = new JPanel();
    usernameField = new JTextField(10);
    passwordField = new JPasswordField(10);
    panel.add(new JLabel("Username: "));
    panel.add(usernameField);
    panel.add(new JLabel("    Password:"));
    panel.add(passwordField);
    return(panel);
  }

  // The panel that has textfield for entering queries.
  // Placed in control panel.
  
  private JPanel makeQueryPanel() {
    JPanel panel = new JPanel();
    queryField = new JTextField(40);
    queryField.addActionListener(this);
    panel.add(new JLabel("Query:"));
    panel.add(queryField);
    return(panel);
  }

  // The panel that has the "Show Results" button.
  // Placed in control panel.
  
  private JPanel makeButtonPanel() {
    JPanel panel = new JPanel();
    showResultsButton = new JButton("Show Results");
    showResultsButton.addActionListener(this);
    panel.add(showResultsButton);
    return(panel);
  }

  // Shows warning when bad query sent.
  
  private JLabel makeErrorLabel() {
    JLabel label = new JLabel("No Results", JLabel.CENTER);
    label.setFont(new Font("Serif", Font.BOLD, 36));
    return(label);
  }
}

AccessCounts.jsp Page that demonstrates JSP declarations.

AccessCounts.jsp  Page that demonstrates JSP declarations.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!--   
Taken from Core Web Programming Java 2 Edition
from Prentice Hall and Sun Microsystems Press,
.
May be freely used or adapted.
-->
<HTML>
<HEAD>
<TITLE>JSP Declarations</TITLE>
<META NAME="keywords"
      CONTENT="JSP,declarations,JavaServer,Pages,servlets">
<META NAME="description"
      CONTENT="A quick example of JSP declarations.">
<LINK REL=STYLESHEET
      HREF="JSP-Styles.css"
      TYPE="text/css">
</HEAD>

<BODY>
<H1>JSP Declarations</H1>

<%! private int accessCount = 0; %>
<H2>Accesses to page since server reboot: 
<%= ++accessCount %></H2>

</BODY>
</HTML>

PreparedStatements.java An example to test the timing differences resulting from repeated raw queries vs. repeated calls

package cwp;

import java.sql.*;

/** An example to test the timing differences resulting
 *  from repeated raw queries vs. repeated calls to
 *  prepared statements. These results will vary dramatically
 *  among database servers and drivers. With my setup
 *  and drivers, Oracle prepared statements took only half
 *  the time that raw queries required when using a modem
 *  connection, and took only 70% of the time that
 *  raw queries required when using a fast LAN connection.
 *  Sybase times were identical in both cases.
 *  


 */

public class PreparedStatements {
  public static void main(String[] args) {
    if (args.length < 5) {
      printUsage();
      return;
    }
    String vendorName = args[4];
    int vendor = DriverUtilities.getVendor(vendorName);
    if (vendor == DriverUtilities.UNKNOWN) {
      printUsage();
      return;
    }
    String driver = DriverUtilities.getDriver(vendor);
    String host = args[0];
    String dbName = args[1];
    String url =
      DriverUtilities.makeURL(host, dbName, vendor);
    String username = args[2];
    String password = args[3];
    // Use "print" only to confirm it works properly,
    // not when getting timing results.
    boolean print = false;
    if ((args.length > 5) && (args[5].equals("print"))) {
      print = true;
    }
    Connection connection =
      getConnection(driver, url, username, password);
    if (connection != null) {
      doPreparedStatements(connection, print);
      doRawQueries(connection, print);
    }
  }

  private static void doPreparedStatements(Connection conn,
                                           boolean print) {
    try {
      String queryFormat =
        "SELECT lastname FROM employees WHERE salary > ?";
      PreparedStatement statement =
        conn.prepareStatement(queryFormat);
      long startTime = System.currentTimeMillis();
      for(int i=0; i<40; i++) {
        statement.setFloat(1, i*5000);
        ResultSet results = statement.executeQuery();
        if (print) {
          showResults(results);
        }
      }
      long stopTime = System.currentTimeMillis();
      double elapsedTime = (stopTime - startTime)/1000.0;
      System.out.println("Executing prepared statement " +
                         "40 times took " +
                         elapsedTime + " seconds.");
    } catch(SQLException sqle) {
      System.out.println("Error executing statement: " + sqle);
    }
  }

  public static void doRawQueries(Connection conn,
                                  boolean print) {
    try {
      String queryFormat =
        "SELECT lastname FROM employees WHERE salary > ";
      Statement statement = conn.createStatement();
      long startTime = System.currentTimeMillis();
      for(int i=0; i<40; i++) {
        ResultSet results =
          statement.executeQuery(queryFormat + (i*5000));
        if (print) {
          showResults(results);
        }
      }
      long stopTime = System.currentTimeMillis();
      double elapsedTime = (stopTime - startTime)/1000.0;
      System.out.println("Executing raw query " +
                         "40 times took " +
                         elapsedTime + " seconds.");
    } catch(SQLException sqle) {
      System.out.println("Error executing query: " + sqle);
    }
  } 

  private static void showResults(ResultSet results)
      throws SQLException {
    while(results.next()) {
      System.out.print(results.getString(1) + " ");
    }
    System.out.println();
  }
    
  private static Connection getConnection(String driver,
                                          String url,
                                          String username,
                                          String password) {
    try {
      Class.forName(driver);
      Connection connection =
        DriverManager.getConnection(url, username, password);
      return(connection);
    } catch(ClassNotFoundException cnfe) {
      System.err.println("Error loading driver: " + cnfe);
      return(null);
    } catch(SQLException sqle) {
      System.err.println("Error connecting: " + sqle);
      return(null);
    }
  }

  private static void printUsage() {
    System.out.println("Usage: PreparedStatements host " +
                       "dbName username password " +
                       "oracle|sybase [print].");
  }
}

EmployeeCreation.java: Make a simple “employees” table using the database utilities

package cwp;

import java.sql.*;

/** Make a simple "employees" table using DatabaseUtilities.
 */

public class EmployeeCreation {
  public static Connection createEmployees(String driver,
                                           String url,
                                           String username,
                                           String password,
                                           boolean close) {
    String format =
      "(id int, firstname varchar(32), lastname varchar(32), " +
      "language varchar(16), salary float)";
    String[] employees =
      {"(1, 'Wye', 'Tukay', 'COBOL', 42500)",
       "(2, 'Britt', 'Tell',   'C++',   62000)",
       "(3, 'Max',  'Manager', 'none',  15500)",
       "(4, 'Polly', 'Morphic', 'Smalltalk', 51500)",
       "(5, 'Frank', 'Function', 'Common Lisp', 51500)",
       "(6, 'Justin', 'Timecompiler', 'Java', 98000)",
       "(7, 'Sir', 'Vlet', 'Java', 114750)",
       "(8, 'Jay', 'Espy', 'Java', 128500)" };
    return(DatabaseUtilities.createTable(driver, url,
                                         username, password,
                                         "employees",
                                         format, employees,
                                         close));    
  }

  public static void main(String[] args) {
    if (args.length < 5) {
      printUsage();
      return;
    }
    String vendorName = args[4];
    int vendor = DriverUtilities.getVendor(vendorName);
    if (vendor == DriverUtilities.UNKNOWN) {
      printUsage();
      return;
    }
    String driver = DriverUtilities.getDriver(vendor);
    String host = args[0];
    String dbName = args[1];
    String url =
      DriverUtilities.makeURL(host, dbName, vendor);
    String username = args[2];
    String password = args[3];
    createEmployees(driver, url, username, password, true);
  }

  private static void printUsage() {
    System.out.println("Usage: EmployeeCreation host dbName " +
                       "username password oracle|sybase.");
  }
}

extract relevant data from a DBResults

# QueryViewer.java  An interactive database query viewer. Connects to the specified Oracle or Sybase database, executes a query, and presents the results in a JTable. Uses the following file:

    * DBResultsTableModel.java Simple class that tells a JTable how to extract relevant data from a DBResults object (which is used to store the results from a database query). 
############################################################################

  package cwp;

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

/** An interactive database query viewer. Connects to
 *  the specified Oracle or Sybase database, executes a query,
 *  and presents the results in a JTable.
 *  


 */

public class QueryViewer extends JFrame
                         implements ActionListener{
  public static void main(String[] args) {
    new QueryViewer();
  }

  private JTextField hostField, dbNameField,
                     queryField, usernameField;
  private JRadioButton oracleButton, sybaseButton;
  private JPasswordField passwordField;
  private JButton showResultsButton;
  Container contentPane;
  private JPanel tablePanel;
  
  public QueryViewer () {
    super("Database Query Viewer");
    WindowUtilities.setNativeLookAndFeel();
    addWindowListener(new ExitListener());
    contentPane = getContentPane();
    contentPane.add(makeControlPanel(), BorderLayout.NORTH);
    pack();
    setVisible(true);
  }

  /** When the "Show Results" button is pressed or
   *  RETURN is hit while the query textfield has the
   *  keyboard focus, a database lookup is performed,
   *  the results are placed in a JTable, and the window
   *  is resized to accommodate the table.
   */
  
  public void actionPerformed(ActionEvent event) {
    String host = hostField.getText();
    String dbName = dbNameField.getText();
    String username = usernameField.getText();
    String password =
      String.valueOf(passwordField.getPassword());
    String query = queryField.getText();
    int vendor;
    if (oracleButton.isSelected()) {
      vendor = DriverUtilities.ORACLE;
    } else {
      vendor = DriverUtilities.SYBASE;
    }
    if (tablePanel != null) {
      contentPane.remove(tablePanel);
    }
    tablePanel = makeTablePanel(host, dbName, vendor,
                                username, password,
                                query);
    contentPane.add(tablePanel, BorderLayout.CENTER);
    pack();
  }

  // Executes a query and places the result in a
  // JTable that is, in turn, inside a JPanel.
  
  private JPanel makeTablePanel(String host,
                                String dbName,
                                int vendor,
                                String username,
                                String password,
                                String query) {
    String driver = DriverUtilities.getDriver(vendor);
    String url = DriverUtilities.makeURL(host, dbName, vendor);
    DBResults results =
      DatabaseUtilities.getQueryResults(driver, url,
                                        username, password,
                                        query, true);
    JPanel panel = new JPanel(new BorderLayout());
    if (results == null) {
      panel.add(makeErrorLabel());
      return(panel);
    }
    DBResultsTableModel model =
      new DBResultsTableModel(results);
    JTable table = new JTable(model);
    table.setFont(new Font("Serif", Font.PLAIN, 17));
    table.setRowHeight(28);
    JTableHeader header = table.getTableHeader();
    header.setFont(new Font("SansSerif", Font.BOLD, 13));
    panel.add(table, BorderLayout.CENTER);
    panel.add(header, BorderLayout.NORTH);
    panel.setBorder
      (BorderFactory.createTitledBorder("Query Results"));
    return(panel);
  }

  // The panel that contains the textfields, checkboxes,
  // and button.
  
  private JPanel makeControlPanel() {
    JPanel panel = new JPanel(new GridLayout(0, 1));
    panel.add(makeHostPanel());
    panel.add(makeUsernamePanel());
    panel.add(makeQueryPanel());
    panel.add(makeButtonPanel());
    panel.setBorder
      (BorderFactory.createTitledBorder("Query Data"));
    return(panel);
  }

  // The panel that has the host and db name textfield and
  // the driver radio buttons. Placed in control panel.
  
  private JPanel makeHostPanel() {
    JPanel panel = new JPanel();
    panel.add(new JLabel("Host:"));
    hostField = new JTextField(15);
    panel.add(hostField);
    panel.add(new JLabel("    DB Name:"));
    dbNameField = new JTextField(15);
    panel.add(dbNameField);
    panel.add(new JLabel("    Driver:"));
    ButtonGroup vendorGroup = new ButtonGroup();
    oracleButton = new JRadioButton("Oracle", true);
    vendorGroup.add(oracleButton);
    panel.add(oracleButton);
    sybaseButton = new JRadioButton("Sybase");
    vendorGroup.add(sybaseButton);
    panel.add(sybaseButton);
    return(panel);
  }

  // The panel that has the username and password textfields.
  // Placed in control panel.
  
  private JPanel makeUsernamePanel() {
    JPanel panel = new JPanel();
    usernameField = new JTextField(10);
    passwordField = new JPasswordField(10);
    panel.add(new JLabel("Username: "));
    panel.add(usernameField);
    panel.add(new JLabel("    Password:"));
    panel.add(passwordField);
    return(panel);
  }

  // The panel that has textfield for entering queries.
  // Placed in control panel.
  
  private JPanel makeQueryPanel() {
    JPanel panel = new JPanel();
    queryField = new JTextField(40);
    queryField.addActionListener(this);
    panel.add(new JLabel("Query:"));
    panel.add(queryField);
    return(panel);
  }

  // The panel that has the "Show Results" button.
  // Placed in control panel.
  
  private JPanel makeButtonPanel() {
    JPanel panel = new JPanel();
    showResultsButton = new JButton("Show Results");
    showResultsButton.addActionListener(this);
    panel.add(showResultsButton);
    return(panel);
  }

  // Shows warning when bad query sent.
  
  private JLabel makeErrorLabel() {
    JLabel label = new JLabel("No Results", JLabel.CENTER);
    label.setFont(new Font("Serif", Font.BOLD, 36));
    return(label);
  }
}

EmployeeTest2.java: A test case for the database utilities. Prints results formatted as an HTML table.

package cwp;

import java.sql.*;

/** Connect to Oracle or Sybase and print "employees" table
 *  as an HTML table.
 *  
 */

public class EmployeeTest2 {
  public static void main(String[] args) {
    if (args.length < 5) {
      printUsage();
      return;
    }
    String vendorName = args[4];
    int vendor = DriverUtilities.getVendor(vendorName);
    if (vendor == DriverUtilities.UNKNOWN) {
      printUsage();
      return;
    }
    String driver = DriverUtilities.getDriver(vendor);
    String host = args[0];
    String dbName = args[1];
    String url =
      DriverUtilities.makeURL(host, dbName, vendor);
    String username = args[2];
    String password = args[3];
    String query = "SELECT * FROM employees";
    DBResults results =
      DatabaseUtilities.getQueryResults(driver, url,
                                        username, password,
                                        query, true);
    System.out.println(results.toHTMLTable("CYAN"));
  }

  private static void printUsage() {
    System.out.println("Usage: EmployeeTest2 host dbName " +
                       "username password oracle|sybase.");
  }
}

DBResults.java: Class to store completed results of a JDBC Query. Differs from a ResultSet in several ways

# DBResults.java  Class to store completed results of a JDBC Query. Differs from a ResultSet in several ways:

    * ResultSet doesn?t necessarily have all the data; reconnection to database occurs as you ask for later rows.
    * This class stores results as strings, in arrays.
    * This class includes DatabaseMetaData (database product name and version) and ResultSetMetaData (the column names).
    * This class has a toHTMLTable method that turns the results into a long string corresponding to an HTML table.

package cwp;

import java.sql.*;
import java.util.*;

/** Class to store completed results of a JDBC Query.
 *  Differs from a ResultSet in several ways:
 *  
     *    
    ResultSet doesn't necessarily have all the data;
     *        reconnection to database occurs as you ask for
     *        later rows.
     *    
    This class stores results as strings, in arrays.
     *    
    This class includes DatabaseMetaData (database product
     *        name and version) and ResultSetMetaData
     *        (the column names).
     *    
    This class has a toHTMLTable method that turns
     *        the results into a long string corresponding to
     *        an HTML table.
     *  
 *  
 */

public class DBResults {
  private Connection connection;
  private String productName;
  private String productVersion;
  private int columnCount;
  private String[] columnNames;
  private Vector queryResults;
  String[] rowData;

  public DBResults(Connection connection,
                   String productName,
                   String productVersion,
                   int columnCount,
                   String[] columnNames) {
    this.connection = connection;
    this.productName = productName;
    this.productVersion = productVersion;
    this.columnCount = columnCount;
    this.columnNames = columnNames;
    rowData = new String[columnCount];
    queryResults = new Vector();
  }

  public Connection getConnection() {
    return(connection);
  }
  
  public String getProductName() {
    return(productName);
  }

  public String getProductVersion() {
    return(productVersion);
  }

  public int getColumnCount() {
    return(columnCount);
  }

  public String[] getColumnNames() {
    return(columnNames);
  }

  public int getRowCount() {
    return(queryResults.size());
  }

  public String[] getRow(int index) {
    return((String[])queryResults.elementAt(index));
  }

  public void addRow(String[] row) {
    queryResults.addElement(row);
  }

  /** Output the results as an HTML table, with
   *  the column names as headings and the rest of
   *  the results filling regular data cells.
   */
  
  public String toHTMLTable(String headingColor) {
    StringBuffer buffer =
      new StringBuffer("\n");
    if (headingColor != null) {
      buffer.append("  \n    ");
    } else {
      buffer.append("  \n    ");
    }
    for(int col=0; col" + columnNames[col]);
    }
    for(int row=0; row\n    ");
      String[] rowData = getRow(row);
      for(int col=0; col" + rowData[col]);
      }
    }
    buffer.append("\n");
    return(buffer.toString());
  } 
}

DatabaseUtilities.java: Several general-purpose utilities discussed and used in the chapter.

package cwp;

import java.sql.*;

/** Three database utilities:

 *   1) getQueryResults. Connects to a database, executes
 *      a query, retrieves all the rows as arrays
 *      of strings, and puts them inside a DBResults
 *      object. Also places the database product name,
 *      database version, and the names of all the columns
 *      into the DBResults object. This has two versions:
 *      one that makes a new connection and another that
 *      uses an existing connection. 


 *   2) createTable. Given a table name, a string denoting
 *      the column formats, and an array of strings denoting
 *      the row values, this method connects to a database,
 *      removes any existing versions of the designated
 *      table, issues a CREATE TABLE command with the
 *      designated format, then sends a series of INSERT INTO
 *      commands for each of the rows. Again, there are
 *      two versions: one that makes a new connection and
 *      another that uses an existing connection. 


 *   3) printTable. Given a table name, this connects to
 *      the specified database, retrieves all the rows,
 *      and prints them on the standard output.
 */

public class DatabaseUtilities {
  
  /** Connect to database, execute specified query,
   *  and accumulate results into DBRresults object.
   *  If the database connection is left open (use the
   *  close argument to specify), you can retrieve the
   *  connection via DBResults.getConnection.
   */
  
  public static DBResults getQueryResults(String driver,
                                          String url,
                                          String username,
                                          String password,
                                          String query,
                                          boolean close) {
    try {
      Class.forName(driver);
      Connection connection =
        DriverManager.getConnection(url, username, password);
      return(getQueryResults(connection, query, close));
    } catch(ClassNotFoundException cnfe) {
      System.err.println("Error loading driver: " + cnfe);
      return(null);
    } catch(SQLException sqle) {
      System.err.println("Error connecting: " + sqle);
      return(null);
    }
  }

  /** Retrieves results as in previous method, but uses
   *  an existing connection instead of opening a new one.
   */
  
  public static DBResults getQueryResults(Connection connection,
                                          String query,
                                          boolean close) {
    try {
      DatabaseMetaData dbMetaData = connection.getMetaData();
      String productName =
        dbMetaData.getDatabaseProductName();
      String productVersion =
        dbMetaData.getDatabaseProductVersion();
      Statement statement = connection.createStatement();
      ResultSet resultSet = statement.executeQuery(query);
      ResultSetMetaData resultsMetaData =
        resultSet.getMetaData();
      int columnCount = resultsMetaData.getColumnCount();
      String[] columnNames = new String[columnCount];
      // Column index starts at 1 (ala SQL) not 0 (ala Java).
      for(int i=1; i                                

EmployeeTest.java: A test case for the database utilities. Prints results in plain text.

package cwp;

import java.sql.*;

/** Connect to Oracle or Sybase and print "employees" table.
 *  


 */

public class EmployeeTest {
  public static void main(String[] args) {
    if (args.length < 5) {
      printUsage();
      return;
    }
    String vendorName = args[4];
    int vendor = DriverUtilities.getVendor(vendorName);
    if (vendor == DriverUtilities.UNKNOWN) {
      printUsage();
      return;
    }
    String driver = DriverUtilities.getDriver(vendor);
    String host = args[0];
    String dbName = args[1];
    String url =
      DriverUtilities.makeURL(host, dbName, vendor);
    String username = args[2];
    String password = args[3];
    DatabaseUtilities.printTable(driver, url,
                                 username, password,
                                 "employees", 12, true);
  }

  private static void printUsage() {
    System.out.println("Usage: EmployeeTest host dbName " +
                       "username password oracle|sybase.");
  }
}

Example Java Programs

HelloWorld.java


public class HelloWorld {

    // method main(): ALWAYS the APPLICATION entry point
    public static void main (String[] args) {
    System.out.println ("Hello World!");
    }
}


// Print Today's Date
import java.util.*;

public class HelloDate {
    public static void main (String[] args) {
    System.out.println ("Hello, it's: ");
    System.out.println(new Date());
    }
}


//example: function call in Java
public class FunctionCall {

    public static void funct1 () {
    System.out.println ("Inside funct1");
    }

    public static void main (String[] args) {
    int val;

    System.out.println ("Inside main");

    funct1();

    System.out.println ("About to call funct2");

    val = funct2(8);

    System.out.println ("funct2 returned a value of " + val);

    System.out.println ("About to call funct2 again");

    val = funct2(-3);

    System.out.println ("funct2 returned a value of " + val);
    }

    public static int funct2 (int param) {
    System.out.println ("Inside funct2 with param " + param);
    return param * 2;
    }
}


//Array in Java
public class ArrayDemo {
    public static void main(String[] args) {
    int[] anArray;            // DECLARE an array of integers

    anArray = new int[10];    // CREATE an array of integers

    // assign a value to each array element 
    for (int i = 0; i < anArray.length; i++) {
        anArray[i] = i;
        }

    // print a value from each array element
    for (int i = 0; i < anArray.length; i++) {
        System.out.print(anArray[i] + " ");
    }
    System.out.println();
    }
}


//class usage in Java
class Point2d {
    /* The X and Y coordinates of the point--instance variables */
    private double x;
    private double y;
    private boolean debug;    // A trick to help with debugging

    public Point2d (double px, double py) { // Constructor
    x = px;
    y = py;

    debug = false;        // turn off debugging
    }

    public Point2d () {        // Default constructor
    this (0.0, 0.0);        // Invokes 2 parameter Point2D constructor
    }
    // Note that a this() invocation must be the BEGINNING of
    // statement body of constructor

    public Point2d (Point2d pt) {    // Another consructor
    x = pt.getX();
    y = pt.getY();

    // a better method would be to replace the above code with
    //    this (pt.getX(), pt.getY());
    // especially since the above code does not initialize the
    // variable debug.  This way we are reusing code that is already
    // working.
    }

    public void dprint (String s) {
    // print the debugging string only if the "debug"
    // data member is true
    if (debug)
        System.out.println("Debug: " + s);
    }

    public void setDebug (boolean b) {
    debug = b;
    }

    public void setX(double px) {
    dprint ("setX(): Changing value of X from " + x + " to " + px );
    x = px;
    }

    public double getX() {
    return x;
    }

    public void setY(double py)  {
    dprint ("setY(): Changing value of Y from " + y + " to " + py );
    y = py;
    }

    public double getY() {
    return y;
    }

    public void setXY(double px, double py) {
    setX(px);
    setY(py);
    }

    public double distanceFrom (Point2d pt) {
    double dx = Math.abs(x - pt.getX());
    double dy = Math.abs(y - pt.getY());

    // check out the use of dprint()
    dprint ("distanceFrom(): deltaX = " + dx);
    dprint ("distanceFrom(): deltaY = " + dy);

    return Math.sqrt((dx * dx) + (dy * dy));
    }

    public double distanceFromOrigin () {
    return distanceFrom (new Point2d ( ));
    }

    public String toStringForXY() {
    String str = "(" + x + ", " + y;
    return str;
    }

    public String toString() {
    String str = toStringForXY() + ")";
    return str;
    }
}



//read integer from Keyboard
import java.io.*;
import java.util.*;

public class KeyboardIntegerReader {

 public static void main (String[] args) throws java.io.IOException {
  String s1;
  String s2;
  int num = 0;

  // set up the buffered reader to read from the keyboard
  BufferedReader br = new BufferedReader (new InputStreamReader (
            System.in));

  boolean cont = true;

  while (cont)
     {
      System.out.print ("Enter an integer:");
      s1 = br.readLine();
      StringTokenizer st = new StringTokenizer (s1);
      s2 = "";

      while (cont && st.hasMoreTokens())
     {
          try 
          {
           s2 = st.nextToken();
           num = Integer.parseInt(s2);
           cont = false;
          }
          catch (NumberFormatException n)
          {
           System.out.println("The value in \"" + s2 + "\" is not an 

integer");
          }
    }
     }

  System.out.println ("You entered the integer: " + num);
 }
}


//read data from keyboard
import java.io.*;
import java.util.*;

public class KeyboardReader
{

 public static void main (String[] args) throws java.io.IOException
 {

  String s1;
  String s2;

  double num1, num2, product;

  // set up the buffered reader to read from the keyboard
  BufferedReader br = new BufferedReader (new InputStreamReader (
            System.in));

  System.out.println ("Enter a line of input");

  s1 = br.readLine();

  System.out.println ("The line has " + s1.length() + " characters");

  System.out.println ();
  System.out.println ("Breaking the line into tokens we get:");

  int numTokens = 0;
  StringTokenizer st = new StringTokenizer (s1);

  while (st.hasMoreTokens())
     {
      s2 = st.nextToken();
      numTokens++;
      System.out.println ("    Token " + numTokens + " is: " + s2);
     }
 }
}


//read from file
import java.io.*;
import java.util.*;

public class MyFileReader
{

 public static void main (String[] args) throws java.io.IOException
 {

  String s1;
  String s2;

  // set up the buffered reader to read from the keyboard
  BufferedReader br = new BufferedReader (new FileReader 

("MyFileReader.txt"));

  s1 = br.readLine();

  System.out.println ("The line is " + s1);
  System.out.println ("The line has " + s1.length() + " characters");

  System.out.println ();
  System.out.println ("Breaking the line into tokens we get:");

  int numTokens = 0;
  StringTokenizer st = new StringTokenizer (s1);

  while (st.hasMoreTokens())
     {
      s2 = st.nextToken();
      numTokens++;
      System.out.println ("    Token " + numTokens + " is: " + s2);
     }
 }
}


//exception handling in Java

public class HelloWorldException {
    public static void main (String[] args) throws Exception {
        System.out.println("Bienvenitos!");
        throw new Exception("Generic Exception");
    }
}



//exception handling


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

/** Causes a compilation error due to an unhandled Exception
 */
public class KeyboardReaderError {

  public static void main (String[] args) { // throws java.io.IOException

    String s1;
    String s2;

    double num1, num2, product;

    // set up the buffered reader to read from the keyboard
    BufferedReader br = new BufferedReader (new InputStreamReader 

(System.in));

    System.out.println ("Enter a line of input");
    
    /* Following line triggers the error.  Error will show the type of
       unhandled exception and where the call occurs */
    s1 = br.readLine();

    System.out.println ("The line has " + s1.length() + " characters");

    System.out.println ();
    System.out.println ("Breaking the line into tokens we get:");

    int numTokens = 0;
    StringTokenizer st = new StringTokenizer (s1);

    while (st.hasMoreTokens()) {
    s2 = st.nextToken();
    numTokens++;
    System.out.println ("    Token " + numTokens + " is: " + s2);
    }
  }
}

//encounters an error

import java.io.*;

// This program shows a stack track that occurs when java
// encounters a terminal error when running a program.

public class DivBy0
{

 public static void funct1 ()
 {
  System.out.println ("Inside funct1()");

  funct2();
 }

 public static void main (String[] args)
 {
  int val;

  System.out.println ("Inside main()");

  funct1();

 }

 public static void funct2 ()
 {
  System.out.println ("Inside funct2()");
  int i, j, k;

  i = 10;
  j = 0;

  k = i/j;
 }

}


FruitCreation.java: Creates a simple table named fruits in either an Oracle or a Sybase database.

FruitCreation.java Creates a simple table named fruits in either an Oracle or a Sybase database.

package cwp;

import java.sql.*;

/** Creates a simple table named "fruits" in either
 *  an Oracle or a Sybase database.
 *  

 */

public class FruitCreation {
  public static void main(String[] args) {
    if (args.length < 5) {
      printUsage();
      return;
    }
    String vendorName = args[4];
    int vendor = DriverUtilities.getVendor(vendorName);
    if (vendor == DriverUtilities.UNKNOWN) {
      printUsage();
      return;
    }
    String driver = DriverUtilities.getDriver(vendor);
    String host = args[0];
    String dbName = args[1];
    String url =
      DriverUtilities.makeURL(host, dbName, vendor);
    String username = args[2];
    String password = args[3];
    String format =
      "(quarter int, " +
      "apples int, applesales float, " +
      "oranges int, orangesales float, " +
      "topseller varchar(16))";
    String[] rows =
    { "(1, 32248, 3547.28, 18459, 3138.03, 'Maria')",
      "(2, 35009, 3850.99, 18722, 3182.74, 'Bob')",
      "(3, 39393, 4333.23, 18999, 3229.83, 'Joe')",
      "(4, 42001, 4620.11, 19333, 3286.61, 'Maria')" };
    Connection connection = 
      DatabaseUtilities.createTable(driver, url,
                                    username, password,
                                    "fruits", format, rows,
                                    false);
    // Test to verify table was created properly. Reuse
    // old connection for efficiency.
    DatabaseUtilities.printTable(connection, "fruits",
                                 11, true);
  }

  private static void printUsage() {
     System.out.println("Usage: FruitCreation host dbName " +
                        "username password oracle|sybase.");
  }
}



	

Example illustrating inheritance and abstract classes

illustrating inheritance এবং abstract classes এর উদাহরণ

  • Shape.java সব, বদ্ধ খোলা, বাঁকা, এবং সোজা পার্শ্বে ধারবিশিষ্ট আকার এর জন্য প্যারেন্ট ক্লাস (সারাংশ)।
  • Curve.java একটি (সারাংশ) বাঁকা আকার (খোলা বা বন্ধ)
  • StraightEdgedShape.java সরাসরি ধার সম্বলিত একটি আকৃতি (খোলা বা বন্ধ)।
  • Measurable.java পরিমাপযোগ্য এলাকায় ইন্টারফেস ডিফাইনিং ক্লাস
  • Circle.java একটি বৃত্ত যা আকার প্রসারিত করে এবং পরিমাপ প্রয়োগ করে।
  • MeasureUtil.java পরিমাপযোগ্য স্থানের উপর কাজ করে।
  • Polygon.java সরাসরি ধার সম্বলিত একটি বদ্ধ আকৃতি; StraightEdgedShape প্রসারিত করে এবং পরিমাপ প্রয়োগ করে।
  • Rectangle.java একটি আয়তক্ষেত্র যা পরিমাপযোগ্য ইন্টারফেস ধারণ করে; বহুভুজে প্রসারিত করে।
  • MeasureTest.java উদাহরণ এর জন্য ড্রাইভার

Shape.java


/** The parent class for all closed, open, curved, and 
 *  straight-edged shapes.
 *

public abstract class Shape {
  protected int x, y;

  public int getX() {
    return(x);
  }

  public void setX(int x) {
    this.x = x;
  }

  public int getY() {
    return(y);
  }

  public void setY(int y) {
    this.y = y;
  }
}


 

Curve.java

একটি (সারাংশ) বাঁকা আকার (খোলা বা বন্ধ) Curve.java An (abstract) curved Shape (open or closed)


/** A curved shape (open or closed). Subclasses will include
 *  arcs and circles.
 *
public abstract class Curve extends Shape {}

 

StraightEdgedShape.java

সরাসরি ধার সম্বলিত একটি আকৃতি (খোলা বা বন্ধ) । A Shape with straight edges (open or closed).


/** A Shape with straight edges (open or closed). Subclasses
 *  will include Line, LineSegment, LinkedLineSegments,
 *  and Polygon.
 *

public abstract class StraightEdgedShape extends Shape {}

 

Measurable.java

পরিমাপযোগ্য এলাকায় ইন্টারফেস ডিফাইনিং ক্লাস Interface defining classes with measurable areas


/** Used in classes with measurable areas. 
 *
 **************

public interface Measurable {
  double getArea();
}

 

 

Circle.java

একটি বৃত্ত যা আকার প্রসারিত করে এবং পরিমাপ প্রয়োগ করে  ।  A circle that extends Shape and implements Measurable.


/** A circle. Since you can calculate the area of
 *  circles, class implements the Measurable interface.
 *

public class Circle extends Curve implements Measurable {
  private double radius;

  public Circle(int x, int y, double radius) {
    setX(x);
    setY(y);
    setRadius(radius);
  }

  public double getRadius() {
    return(radius);
  }

  public void setRadius(double radius) {
    this.radius = radius;
  }

  /** Required for Measurable interface. */

  public double getArea() {
    return(Math.PI * radius * radius);
  }
}

 

MeasureUtil.java

পরিমাপযোগ্য স্থানের উপর কাজ করে  ।  Operates on Measurable instances


/** Some operations on Measurable instances. 
 *

public class MeasureUtil {
  public static double maxArea(Measurable m1,
                               Measurable m2) {
    return(Math.max(m1.getArea(), m2.getArea()));
  }

  public static double totalArea(Measurable[] mArray) {
    double total = 0;
    for(int i=0; i

 

Some simple utilities for building Oracle and Sybase JDBC connections

এই সাধারণ উদ্দেশ্যে তৈরিকৃত কোড নয় - এটা আমাদের লোকাল সেটআপ এর ক্ষেত্রে প্রযোজ্য।


 

 

package cwp;

/** Some simple utilities for building Oracle and Sybase
 *  JDBC connections. This is not general-purpose
 *  code -- it is specific to my local setup.
 */

public class DriverUtilities {
  public static final int ORACLE = 1;
  public static final int SYBASE = 2;
  public static final int UNKNOWN = -1;

  /** Build a URL in the format needed by the
   *  Oracle and Sybase drivers I am using.
   */
  
  public static String makeURL(String host, String dbName,
                               int vendor) {
    if (vendor == ORACLE) {
      return("jdbc:oracle:thin:@" + host + ":1521:" + dbName);
    } else if (vendor == SYBASE) {
      return("jdbc:sybase:Tds:" + host  + ":1521" +
             "?SERVICENAME=" + dbName);
    } else {
      return(null);
    }
  }

  /** Get the fully qualified name of a driver. */
  
  public static String getDriver(int vendor) {
    if (vendor == ORACLE) {
      return("oracle.jdbc.driver.OracleDriver");
    } else if (vendor == SYBASE) {
      return("com.sybase.jdbc.SybDriver");
    } else {
      return(null);
    }
  }

  /** Map name to int value. */

  public static int getVendor(String vendorName) {
    if (vendorName.equalsIgnoreCase("oracle")) {
      return(ORACLE);
    } else if (vendorName.equalsIgnoreCase("sybase")) {
      return(SYBASE);
    } else {
      return(UNKNOWN);
    }
  }
}

FruitTest.java: A class that connects to either an Oracle or a Sybase database and prints out the values of predetermined columns in the “fruits” table.

# FruitTest.java  A class that connects to either an Oracle or a Sybase database and prints 
  out the values of predetermined columns in the "fruits" table. 

package cwp;

import java.sql.*;

/** A JDBC example that connects to either an Oracle or
 *  a Sybase database and prints out the values of
 *  predetermined columns in the "fruits" table.
 *  


 */

public class FruitTest {

  /** Reads the hostname, database name, username, password,
   *  and vendor identifier from the command line. It
   *  uses the vendor identifier to determine which
   *  driver to load and how to format the URL. The
   *  driver, URL, username, host, and password are then
   *  passed to the showFruitTable method.
   */
  
  public static void main(String[] args) {
    if (args.length < 5) {
      printUsage();
      return;
    }
    String vendorName = args[4];
    int vendor = DriverUtilities.getVendor(vendorName);
    if (vendor == DriverUtilities.UNKNOWN) {
      printUsage();
      return;
    }
    String driver = DriverUtilities.getDriver(vendor);
    String host = args[0];
    String dbName = args[1];
    String url = DriverUtilities.makeURL(host, dbName, vendor);
    String username = args[2];
    String password = args[3];
    showFruitTable(driver, url, username, password);
  }

  /** Get the table and print all the values. */
  
  public static void showFruitTable(String driver,
                                    String url,
                                    String username,
                                    String password) {
    try {
      // Load database driver if not already loaded
      Class.forName(driver);
      // Establish network connection to database
      Connection connection =
        DriverManager.getConnection(url, username, password);
      // Look up info about the database as a whole.
      DatabaseMetaData dbMetaData = connection.getMetaData();
      String productName =
        dbMetaData.getDatabaseProductName();
      System.out.println("Database: " + productName);
      String productVersion =
        dbMetaData.getDatabaseProductVersion();
      System.out.println("Version: " + productVersion + "\n");
      System.out.println("Comparing Apples and Oranges\n" +
                         "============================");
      Statement statement = connection.createStatement();
      String query = "SELECT * FROM fruits";
      // Send query to database and store results
      ResultSet resultSet = statement.executeQuery(query);
      // Look up information about a particular table
      ResultSetMetaData resultsMetaData =
        resultSet.getMetaData();
      int columnCount = resultsMetaData.getColumnCount();
      // Column index starts at 1 (ala SQL) not 0 (ala Java).
      for(int i=1; i

ContactSection.jsp A snippet of a JSP page. It defines a field (accessCount), so pages that include it and want to directly utilize that field must use the include directive, not jsp:include.

ContactSection.jsp হচ্ছে JSP পৃষ্ঠার একটি অংশ।এটি একটি ফিল্ডকে সঙ্গায়িত করে (accessCount), সুতরাং যে পৃষ্ঠায় এটি অন্তর্ভুক্ত থাকে এবং সরাসরি উক্ত ফিল্ড ব্যবহার করাতে চায় তাকে আবশ্যই include directive ব্যবহার করতে হবে, jsp:include নয়।.

<%@ page import="java.util.Date" %>

<%-- The following become fields in each servlet that
     results from a JSP page that includes this file. --%>
<%! 
private int accessCount = 0;
private Date accessDate = new Date();
private String accessHost = "<I>No previous access</I>";
%>

<P>
<HR>
This page © 2000 
<A HREF="http//www.my-company.com/">my-company.com</A>.
This page has been accessed <%= ++accessCount %>
times since server reboot. It was last accessed from 
<%= accessHost %> at <%= accessDate %>.

<% accessHost = request.getRemoteHost(); %>
<% accessDate = new Date(); %>

J2SE : LinkedList and Iterators in Java

/*
 * LinkedList.java
 *
 * Created on January 10, 2008, 8:51 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package linkedlist;

import java.util.List;
import java.util.LinkedList;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Collections;
import java.util.Random;

/**
 *
 * @author Sayed
 */
public class LinkedListTest {
    
    /** Creates a new instance of LinkedList */
    public LinkedListTest() {
    }
    
    /**
     *Example operations using linked lists
     */
    
    public void linkedListOperation(){
        
        final int MAX = 10;
        int counter = 0;

        //create two linked lists
        List listA = new LinkedList();
        List listB = new LinkedList();

        //store data in the linked list A
        for (int i = 0; i < MAX; i++) {
            System.out.println("  - Storing Integer(" + i + ")");
            listA.add(new Integer(i));
        }
       
        //print data from the linked list using iterator 
        Iterator it = listA.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }

        //print data from the linked list using listIterator. 
        counter = 0;
        ListIterator liIt = listA.listIterator();
        while (liIt.hasNext()) {
            System.out.println("Element [" + counter + "] = " + liIt.next());
            System.out.println("  - hasPrevious    = " + liIt.hasPrevious());
            System.out.println("  - hasNext        = " + liIt.hasNext());
            System.out.println("  - previousIndex  = " + liIt.previousIndex());
            System.out.println("  - nextIndex      = " + liIt.nextIndex());
            System.out.println();
            counter++;
        }


        //retrieve data from the linked list using index
        for (int j=0; j < listA.size(); j++) {
            System.out.println("[" + j + "] - " + listA.get(j));
        }

        //find the location of an element
        int locationIndex = listA.indexOf("5");
        System.out.println("Index location of the String \"5\" is: " + locationIndex);  

        //find the first and the last location of an element
        System.out.println("First occurance search for String \"5\".  Index =  " + 
        listA.indexOf("5"));
        System.out.println("Last Index search for String \"5\".       Index =  " + 
        listA.lastIndexOf("5"));

        //create a sublist from the list 
        List listSub = listA.subList(10, listA.size());
        System.out.println("New Sub-List from index 10 to " + listA.size() + ": " + 
        listSub);

        //sort the sub-list
        System.out.println("Original List   : " + listSub);
        Collections.sort(listSub);
        System.out.println("New Sorted List : " + listSub);
        System.out.println();

        //reverse the new sub-list
        System.out.println("Original List     : " + listSub);
        Collections.reverse(listSub);
        System.out.println("New Reversed List : " + listSub);
        System.out.println();

        //check to see if the lists are empty
        System.out.println("Is List A empty?   " + listA.isEmpty());
        System.out.println("Is List B empty?   " + listB.isEmpty());
        System.out.println("Is Sub-List empty? " + listSub.isEmpty());
        
        //compare two lists
        System.out.println("A=B? " + listA.equals(listB));        
        System.out.println();

        //Shuffle the elements around in some Random order for List A
        Collections.shuffle(listA, new Random());

        //convert a list into an array
        Object[] objArray = listA.toArray();
        for (int j=0; j < objArray.length; j++) {
            System.out.println("Array Element [" + j + "] = " + objArray[j]);
        }

        //clear listA
        System.out.println("List A   (before) : " + listA);        
        System.out.println();
        listA.clear();
        System.out.println("List A   (after)  : " + listA);        
        System.out.println();
        
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        LinkedListTest listExample = new LinkedListTest();
        listExample.linkedListOperation();
    }
    
}

Use sorting criterion in sort function

/* The following code example is taken from the book
 * "The C++ Standard Library - A Tutorial and Reference"
 * by Nicolai M. Josuttis, Addison-Wesley, 1999
 *
 * (C) Copyright Nicolai M. Josuttis 1999.
 * Permission to copy, use, modify, sell and distribute this software
 * is granted provided this copyright notice appears in all copies.
 * This software is provided "as is" without express or implied
 * warranty, and with no claim as to its suitability for any purpose.
 */

#include <iostream>
#include <vector>
#include <deque>
#include <list>
#include <set>
#include <map>
#include <string>
#include <algorithm>
#include <iterator>
#include <functional>
#include <numeric>

/* PRINT_ELEMENTS()
 * - prints optional C-string optcstr followed by
 * - all elements of the collection coll
 * - separated by spaces
 */
template <class T>
inline void PRINT_ELEMENTS (const T& coll, const char* optcstr="")
{
    typename T::const_iterator pos;

    std::cout << optcstr;
    for (pos=coll.begin(); pos!=coll.end(); ++pos) {
        std::cout << *pos << ' ';
    }
    std::cout << std::endl;
}

/* INSERT_ELEMENTS (collection, first, last)
 * - fill values from first to last into the collection
 * - NOTE: NO half-open range
 */
template <class T>
inline void INSERT_ELEMENTS (T& coll, int first, int last)
{
    for (int i=first; i<=last; ++i) {
        coll.insert(coll.end(),i);
    }
}

using namespace std;

void printCollection (const list<int>& l)
{
    PRINT_ELEMENTS(l);
}

bool lessForCollection (const list<int>& l1, const list<int>& l2)
{
    return lexicographical_compare
                (l1.begin(), l1.end(),   // first range
                 l2.begin(), l2.end());  // second range
}

int main()
{
    list<int> c1, c2, c3, c4;

    // fill all collections with the same starting values
    INSERT_ELEMENTS(c1,1,5);
    c4 = c3 = c2 = c1;

    // and now some differences
    c1.push_back(7);
    c3.push_back(2);
    c3.push_back(0);
    c4.push_back(2);

    // create collection of collections
    vector<list<int> > cc;

    cc.push_back(c1);
    cc.push_back(c2);
    cc.push_back(c3);
    cc.push_back(c4);
    cc.push_back(c3);
    cc.push_back(c1);
    cc.push_back(c4);
    cc.push_back(c2);

    // print all collections
    for_each (cc.begin(), cc.end(),
              printCollection);
    cout << endl;

    // sort collection lexicographically
    sort (cc.begin(), cc.end(),    // range
          lessForCollection);      // sorting criterion

    // print all collections again
    for_each (cc.begin(), cc.end(),
              printCollection);
}
/*
1 2 3 4 5 7
1 2 3 4 5
1 2 3 4 5 2 0
1 2 3 4 5 2
1 2 3 4 5 2 0
1 2 3 4 5 7
1 2 3 4 5 2
1 2 3 4 5

1 2 3 4 5
1 2 3 4 5
1 2 3 4 5 2
1 2 3 4 5 2
1 2 3 4 5 2 0
1 2 3 4 5 2 0
1 2 3 4 5 7
1 2 3 4 5 7

 */

Sort objects stored in deque

/* The following code example is taken from the book
 * "The C++ Standard Library - A Tutorial and Reference"
 * by Nicolai M. Josuttis, Addison-Wesley, 1999
 *
 * (C) Copyright Nicolai M. Josuttis 1999.
 * Permission to copy, use, modify, sell and distribute this software
 * is granted provided this copyright notice appears in all copies.
 * This software is provided "as is" without express or implied
 * warranty, and with no claim as to its suitability for any purpose.
 */
#include <iostream>
#include <string>
#include <deque>
#include <set>
#include <algorithm>
using namespace std;


/* class Person
 */
class Person {
  private:
    string fn;    // first name
    string ln;    // last name
  public:
    Person() {
    }
    Person(const string& f, const string& n)
     : fn(f), ln(n) {
    }
    string firstname() const;
    string lastname() const;
    // ...
};

inline string Person::firstname() const {
    return fn;
}

inline string Person::lastname() const {
    return ln;
}

ostream& operator<< (ostream& s, const Person& p)
{
    s << "[" << p.firstname() << " " << p.lastname() << "]";
    return s;
}


/* binary function predicate:
 * - returns whether a person is less than another person
 */
bool personSortCriterion (const Person& p1, const Person& p2)
{
    /* a person is less than another person
     * - if the last name is less
     * - if the last name is equal and the first name is less
     */
    return p1.lastname()<p2.lastname() ||
           (p1.lastname()==p2.lastname() &&
            p1.firstname()<p2.firstname());
}

int main()
{
    // create some persons
    Person p1("nicolai","josuttis");
    Person p2("ulli","josuttis");
    Person p3("anica","josuttis");
    Person p4("lucas","josuttis");
    Person p5("lucas","otto");
    Person p6("lucas","arm");
    Person p7("anica","holle");

    // insert person into collection coll
    deque<Person> coll;
    coll.push_back(p1);
    coll.push_back(p2);
    coll.push_back(p3);
    coll.push_back(p4);
    coll.push_back(p5);
    coll.push_back(p6);
    coll.push_back(p7);

    // print elements
    cout << "deque before sort():" << endl;
    deque<Person>::iterator pos;
    for (pos = coll.begin(); pos != coll.end(); ++pos) {
        cout << *pos << endl;
    }

    // sort elements
    sort(coll.begin(),coll.end(),    // range
         personSortCriterion);       // sort criterion

    // print elements
    cout << "deque after sort():" << endl;
    for (pos = coll.begin(); pos != coll.end(); ++pos) {
        cout << *pos << endl;
    }
}

/*
deque before sort():
[nicolai josuttis]
[ulli josuttis]
[anica josuttis]
[lucas josuttis]
[lucas otto]
[lucas arm]
[anica holle]
deque after sort():
[lucas arm]
[anica holle]
[anica josuttis]
[lucas josuttis]
[nicolai josuttis]
[ulli josuttis]
[lucas otto]

 */

Expressions.jsp Page that demonstrates JSP expressions. Uses the JSP-Styles style sheet.

Expressions.jsp  Page that demonstrates JSP expressions. Uses the JSP-Styles  style sheet. 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- 
Example of JSP Expressions. 
   
Taken from Core Web Programming Java 2 Edition
from Prentice Hall and Sun Microsystems Press,
.
May be freely used or adapted.
-->
<HTML>
<HEAD>
<TITLE>JSP Expressions</TITLE>
<META NAME="keywords"
      CONTENT="JSP,expressions,JavaServer,Pages,servlets">
<META NAME="description"
      CONTENT="A quick example of JSP expressions.">
<LINK REL=STYLESHEET
      HREF="JSP-Styles.css"
      TYPE="text/css">
</HEAD>

<BODY>
<H2>JSP Expressions</H2>
<UL>
  <LI>Current time: <%= new java.util.Date() %>
  <LI>Your hostname: <%= request.getRemoteHost() %>
  <LI>Your session ID: <%= session.getId() %>
  <LI>The <CODE>testParam</CODE> form parameter:
      <%= request.getParameter("testParam") %>
</UL>
</BODY>
</HTML>

A simple C++ Program code

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
  ifstream in("test", ios::in | ios::binary);

  if(!in) {
    cout << "Cannot open input file.\n";
    return 1;
  }

  double num;
  char str[80];

  in.read((char *) &num, sizeof(double));
  in.read(str, 14);
  str[14] = '\0'; // null terminate str

  cout << num << ' ' << str;

  in.close();

  return 0;
}

valarray with double value inside

/* The following code example is taken from the book
 * "The C++ Standard Library - A Tutorial and Reference"
 * by Nicolai M. Josuttis, Addison-Wesley, 1999
 *
 * (C) Copyright Nicolai M. Josuttis 1999.
 * Permission to copy, use, modify, sell and distribute this software
 * is granted provided this copyright notice appears in all copies.
 * This software is provided "as is" without express or implied
 * warranty, and with no claim as to its suitability for any purpose.
 */
#include <iostream>
#include <valarray>
using namespace std;

// print valarray line-by-line
template<class T>
void printValarray (const valarray<T>& va, int num)
{
    for (int i=0; i<va.size()/num; ++i) {
        for (int j=0; j<num; ++j) {
            cout << va[i*num+j] << ' ';
        }
        cout << endl;
    }
    cout << endl;
}

int main()
{
    /* valarray with 12 elements
     * - four rows
     * - three columns
     */
    valarray<double> va(12);

    // fill valarray with values
    for (int i=0; i<12; i++) {
        va[i] = i;
    }

    printValarray (va, 3);

    // assign 77 to all values that are less than 5
    va[va<5.0] = 77.0;

    // add 100 to all values that are greater than 5 and less than 9
    va[va>5.0 && va<9.0] = valarray<double>(va[va>5.0 && va<9.0]) + 100.0;

    printValarray (va, 3);
}

/*
0 1 2
3 4 5
6 7 8
9 10 11

77 77 77
77 77 5
106 107 108
9 10 11


 */

Print minimum, maximum, and sum of the valarray

/* The following code example is taken from the book
 * "The C++ Standard Library - A Tutorial and Reference"
 * by Nicolai M. Josuttis, Addison-Wesley, 1999
 *
 * (C) Copyright Nicolai M. Josuttis 1999.
 * Permission to copy, use, modify, sell and distribute this software
 * is granted provided this copyright notice appears in all copies.
 * This software is provided "as is" without express or implied
 * warranty, and with no claim as to its suitability for any purpose.
 */
#include <iostream>
#include <valarray>
using namespace std;
 
// print valarray
template <class T>
void printValarray (const valarray<T>& va)
{
    for (int i=0; i<va.size(); i++) {
        cout << va[i] << ' ';
    }
    cout << endl;
}
 
int main()
{
    // define two valarrays with ten elements
    valarray<double> va1(10), va2(10);
 
    // assign values 0.0, 1.1, up to 9.9 to the first valarray
    for (int i=0; i<10; i++) {
        va1[i] = i * 1.1;
    }
 
    // assign -1 to all elements of the second valarray
    va2 = -1;
 
    // print both valarrays
    printValarray(va1);
    printValarray(va2);
 
    // print minimum, maximum, and sum of the first valarray
    cout << "min(): " << va1.min() << endl;
    cout << "max(): " << va1.max() << endl;
    cout << "sum(): " << va1.sum() << endl;
 
    // assign values of the first to the second valarray
    va2 = va1;
 
    // remove all elements of the first valarray
    va1.resize(0);
 
    // print both valarrays again
    printValarray(va1);
    printValarray(va2);
}
 
/*
0 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1
min(): 0
max(): 9.9
sum(): 49.5
 
0 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9
 
 */

valarray slice

/* The following code example is taken from the book * "The C++ Standard Library - A Tutorial and Reference" * by Nicolai M. Josuttis, Addison-Wesley, 1999 * * (C) Copyright Nicolai M. Josuttis 1999. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. */

#include <iostream>
#include <valarray>
using namespace std; 

// print valarray line-by-line
template<class T>
void printValarray (const valarray<T>& va, int num)
{
   for (int i=0; i<va.size()/num; ++i) {
       for (int j=0; j<num; ++j) {
           cout << va[i*num+j] << ' ';
       }
     cout << endl;
   }
   cout << endl;
} 

int main()
{
   /* valarray with 12 elements
     * - four rows
     * - three columns
     */
   valarray<double> va(12); 

   // fill valarray with values
   for (int i=0; i<12; i++) {
       va[i] = i;
   } 

   printValarray (va, 3);
   // first column = second column raised to the third column
   va[slice(0,4,3)] = pow (valarray<double>(va[slice(1,4,3)]),
                           valarray<double>(va[slice(2,4,3)])); 

   printValarray (va, 3); 
   // create valarray with three times the third element of va
   valarray<double> vb(va[slice(2,4,0)]);
 
   // multiply the third column by the elements of vb
   va[slice(2,4,3)] *= vb;
   printValarray (va, 3); 
   // print the square root of the elements in the second row
   //printValarray (sqrt(valarray<double>(va[slice(3,3,1)])));
   // double the elements in the third row
   va[slice(2,4,3)] = valarray<double>(va[slice(2,4,3)]) * 2.0;
   printValarray (va, 3);
}
/*
0 1 2
3 4 5
6 7 8
9 10 11
1 1 2
1024 4 5
5.7648e+006 7 8
1e+011 10 11
1 1 4
1024 4 10
5.7648e+006 7 16
1e+011 10 22
1 1 8
1024 4 20
5.7648e+006 7 32
1e+011 10 44
*/

 

Call member function for each element in vector

/* The following code example is taken from the book
* "The C++ Standard Library - A Tutorial and Reference"
* by Nicolai M. Josuttis, Addison-Wesley, 1999
*
* (C) Copyright Nicolai M. Josuttis 1999.
* Permission to copy, use, modify, sell and distribute this software
* is granted provided this copyright notice appears in all copies.
* This software is provided "as is" without express or implied
* warranty, and with no claim as to its suitability for any purpose.
*/
//#define mem_fun1 mem_fun
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
class Person {
private:
   std::string name;
public:
   //...
   void print () const {
       std::cout << name << std::endl;
   }
   void printWithPrefix (std::string prefix) const {
       std::cout << prefix << name << std::endl;
   }
};
void foo (const std::vector<Person>& coll)
{
   using std::for_each;
   using std::bind2nd;
   using std::mem_fun_ref;
   // call member function print() for each element
   for_each (coll.begin(), coll.end(), mem_fun_ref(&Person::print));
   // call member function printWithPrefix() for each element
   // - "person: " is passed as an argument to the member function
   for_each (coll.begin(), coll.end(),bind2nd(mem_fun_ref(&Person::printWithPrefix),"person: "));
}

void ptrfoo (const std::vector<Person*>& coll)
                                   // ^^^ pointer !
{
   using std::for_each;
   using std::bind2nd;
   using std::mem_fun;
   // call member function print() for each referred object
   for_each (coll.begin(), coll.end(),
             mem_fun(&Person::print));
   // call member function printWithPrefix() for each referred object
   // - "person: " is passed as an argument to the member function
   for_each (coll.begin(), coll.end(),bind2nd(mem_fun(&Person::printWithPrefix),"person: "));
} 
 
int main()
{
   std::vector<Person> coll(5);
   foo(coll); 
   std::vector<Person*> coll2;
   coll2.push_back(new Person);
   ptrfoo(coll2);
} 
/*
person:
person:
person:
person:
person:
person: 

*/


	

Use bitset with enum together

/* The following code example is taken from the book
  * "The C++ Standard Library - A Tutorial and Reference"
  * by Nicolai M. Josuttis, Addison-Wesley, 1999
  *
  * (C) Copyright Nicolai M. Josuttis 1999.
  * Permission to copy, use, modify, sell and distribute this software
  * is granted provided this copyright notice appears in all copies.
  * This software is provided "as is" without express or implied
  * warranty, and with no claim as to its suitability for any purpose.
  */
 #include <bitset>
 #include <iostream>
 using namespace std;
 
 int main()
 {
     /* enumeration type for the bits
      * - each bit represents a color
      */
     enum Color { red, yellow, green, blue, white, black, //...,
                  numColors };
 
     // create bitset for all bits/colors
     bitset<numColors> usedColors;
 
     // set bits for two colors
     usedColors.set(red);
     usedColors.set(blue);
 
     // print some bitset data
     cout << "bitfield of used colors:   " << usedColors
          << endl;
     cout << "number   of used colors:   " << usedColors.count()
          << endl;
     cout << "bitfield of unused colors: " << ~usedColors
          << endl;
 
     // if any color is used
     if (usedColors.any()) {
         // loop over all colors
         for (int c = 0; c < numColors; ++c) {
             // if the actual color is used
             if (usedColors[(Color)c]) {
                 //...
             }
         }
     }
 }
 
 /* 
 bitfield of used colors:   001001
 number   of used colors:   2
 bitfield of unused colors: 110110
 
  */

Transform binary representation into integral number using bitset

 /* The following code example is taken from the book
  * "The C++ Standard Library - A Tutorial and Reference"
  * by Nicolai M. Josuttis, Addison-Wesley, 1999
  *
  * (C) Copyright Nicolai M. Josuttis 1999.
  * Permission to copy, use, modify, sell and distribute this software
  * is granted provided this copyright notice appears in all copies.
  * This software is provided "as is" without express or implied
  * warranty, and with no claim as to its suitability for any purpose.
  */
 #include <bitset>
 #include <iostream>
 #include <string>
 #include <limits>
 using namespace std;
 
 int main()
 {
     /* print some numbers in binary representation
      */
     cout << "267 as binary short:     "
          << bitset<numeric_limits<unsigned short>::digits>(267)
          << endl;
 
     cout << "267 as binary long:      "
          << bitset<numeric_limits<unsigned long>::digits>(267)
          << endl;
 
     cout << "10,000,000 with 24 bits: "
          << bitset<24>(1e7) << endl;
 
     /* transform binary representation into integral number
      */
     cout << "\"1000101011\" as number:  "
          << bitset<100>(string("1000101011")).to_ulong() << endl;
 }
 
  /* 
 267 as binary short:     0000000100001011
 267 as binary long:      00000000000000000000000100001011
 10,000,000 with 24 bits: 100110001001011010000000
 1000101011" as number:  555
 
  */       
    // create a bitset that is 8 bits long bitset<8> bs; // display that bitset for( int i = (int) bs.size()-1; i >= 0; i-- ) { cout << bs[i] << " "; } cout << endl; // create a bitset out of a number bitset<8> bs2( (long) 131 ); // display that bitset, too for( int i = (int) bs2.size()-1; i >= 0; i-- ) { cout << bs2[i] << " "; } cout << endl;

A simple applet that uses the ClickListener class

ClickReporter.java A simple applet that uses the ClickListener class to handle mouse events.
***************
import java.applet.Applet;
import java.awt.*;

/** Prints a message saying where the user clicks.
 *  Uses an external listener.
 *  


 ******
public class ClickReporter extends Applet {
  public void init() {
    setBackground(Color.yellow);
    addMouseListener(new ClickListener());
  }
}