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");
    }
  }
}

কীবোর্ড থেকে একটি কী হারিয়ে গেলে বা নষ্ট হয়ে গেলে কি করবেন?

আপনার ল্যাপটপের একটি বা একাধিক কী হারিয়ে গেছে বা নষ্ট হয়ে গেছে এবং আপনি জানেন না এখন কি করবেন? ভয় পাবার কিছু নেই, সম্ভবত আপনি কীবোর্ডটি ঠিক করতে পারবেন এবং নতুন একটি কীবোর্ড ক্রয় করার কোন প্রয়োজন হবে না। সকল কীবোর্ড এর জন্য অনন্য সমাধান নেই, কারণ সকল কীবোর্ড এক নয়। এখানে সাধারণ ক্ষেত্রে কি করতে হবে তা দেওয়া হলো।

অবস্থা ০১ 

কী কেপ (key cap) এবং কী ধারক (key retainer) খুলে গেছে এবং আপনি জানেন না কীভাবে আপনি এদেরকে সঠিক অবস্থানে ফেরত দেবেন।

Key cap & Key retainer

সতর্কতার সাথে অন্য আরেককি কী এর কেপ খুলে ফেলুন যাতে retainer কীবোর্ড থেকে খুলে না যায়।

কী retainer টি ভাল করে দেখুন, এটি কীবোর্ড এর সাথে চারটি ভিন্ন বিন্দু দ্বারা যুক্ত আছে।

সংযোগ খুলে যাওয়া retainer টি একইভাবে সেট করে কীবোর্ড এ স্থাপন করুন।

কী কেপটি retainer এর উপর বসান এবং হালকা চাপ দিয়ে বসিয়ে দিন।

অবস্থা ০২ 

কীবোর্ড থেকে কী খুলে গেলে এবং আপনি তা হারিয়ে ফেলেছেন। এক্ষেত্রে আপনি একটি একক কী ইন্টারনেট থেকে ক্রয় করতে পারেন। নতুন একটি পাবার পরে, উপরোক্ত পদ্ধতিতে এটিকে সস্থানে স্থাপন করুন।

স্পেসবার কী স্থাপন করা

স্পেসবার কী এর সাথে একটি ধাতুর তৈরি ধারক সংযুক্ত থাকে (কিছু কীবোর্ড মডেল এর ক্ষেত্রে)। ধারকটিকে ফ্লাট (সমতল) মাথা বিশিষ্ট স্ক্রুড্রাইভার দিয়ে কীবোর্ড থেকে খুলে ফেলুন।

ছবিতে দেখানো পদ্ধতিতে ধারকটিকে স্থাপন করুন। আপনার ছোট আংটার সাহায্যে ধারকটিকে কীবোর্ড এর সাথে স্থাপন করতে হতে পারে।

স্পেসবার কীটিকে সস্থানে নিয়ে যান এবং যতক্ষন পর্যন্ত না ঠিকভাবে লেগে যায় ততক্ষন আঙ্গুল দিয়ে হালকাভাবে চাপ দিন।

ভেঙ্গে যাওয়া কীবোর্ড কী এর জন্য এখনে আরেকটি কৌশল দেখানো হলো

নিচের চিত্রটিতে আপনি দেখতে পারছেন যে আপনার U কী টি নেই। কী কেপ, ধারক এমনটি সিলিকন ঝিল্লিও নেই। এখানে দেখানো হলো কীভাবে নতুন কী ক্রয় না করেও কিভাবে এটিকে সাময়িকভাবে ঠিক করবেন।

আমি নিজে U কী ছাড়া কীবোর্ড ব্যবহার করতে পারবো না, কিন্তু ডান অল্ট কী বা রাইট ক্লিক কী ছাড়াও চলতে পারবো। নিচের গাইড এ আমি দেখাবো কিভাবে আমি ব্যবহার করি না এমন একটি কী খুলে ফেলে U কী এর স্থলে স্থাপন করবো।

সতর্কতার সাথে আঙ্গুলের সাহায্যে কী কেপ টি খুলে ফেলুন।

ধারকটি খুলে ফেলুন। ধারকটি দুটি অংশ দ্বারা একে অপরের সাথে যুক্ত থাকে। যদি একটি অংশ অপর অংশে থেকে খুলে যায় তাহলে এদেরকে পুনরায় সংযুক্ত করুন।

সিলিকন ঝিল্লিটি আঠা দিয়ে কীবোর্ড এর সাথে লাগানো থাকে। খুবই সতর্কতার সাথে একটি ধারালো ছুরি দিয়ে ধীরে ধীরে ঝিল্লিটিকে কীবোর্ড থেকে আলগা করুন।

সিলিকন ঝিল্লিটি আলগা হয়ে যাবে।

এখন ঝিল্লিটির নিচের প্রান্তে যতটুকু প্রয়োজন ঠিক ততটুকু সুপারগ্লু লাগান।

সতর্কতার সাথে ঝিল্লিটিকে U এর কেন্দ্রে স্থাপন করুন। গ্লু শুকানো পর্যন্ত অপেক্ষা করুন।

ধারকটিকে স্থাপন করুন।

কী কেপটিকে ধারকের উপরে স্থাপন করুন। হালকাভাবে চাপ দিয়ে ধারকের সাথে স্থাপন করুন।

এখন আপনি U কী আবার ব্যবহার করতে পারবেন।

কেন কী সংযুক্ত করা যায় না।

কী টিকে উল্টো করুন এবং ক্লিপটিকে ভালভাবে দেখুন। সম্ভাবনা আছে, এটির একটি ক্লিপ নষ্ট হয়ে যাবার কারণে ধারকের সাথে এটি আটকাচ্ছে না। যদি এটি কারণ হয়ে থাকে তাহলে আপনাকে নতুন একটি কী ক্রয় করতে হবে।

পরবর্তী ছবিতে আপনি দেখেতে পাচ্ছেন যে, একটি ক্লিপ নেই, এটি ভেঙ্গে গেছে। এই কী টি ধারক এর সাথে সংযুক্ত করা যাবে না। যদি এটি কারণ হয়ে থাকে তাহলে আপনাকে নতুন একটি কী ক্রয় করতে হবে।

সম্ভবত, আপনার কী টি ভাল আছে, কিন্তু ধারকটি ভেঙ্গে গেছে। পরবর্তী ছবিতে আপনি দেখতে পাচ্ছেন যে, ধারক এর সাথে টিপটি নেই। বাম টিপ টি আছে কিন্তু ডান টিপ টি নেই। যদি এটি কারণ হয়ে থাকে তাহলে আপনাকে নতুন একটি কী ক্রয় করতে হবে।

এখানে আরো একটি ছবি আছে। এই ছবিতে ধারকটির দুটি অংশ একে অপরের সাথে সংযুক্ত করা যাচ্ছে না। এটির কারণ হচ্ছে এদের একটি ভেঙ্গে গেছে।বাম টিপ টি আছে কিন্তু ডান টিপ টি নেই। যদি এটি কারণ হয়ে থাকে তাহলে আপনাকে নতুন একটি কী ক্রয় করতে হবে।

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);
  }
}