alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

What this is

This file is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Other links

The source code

/**
 * CSGuestbook.java
 * Pete Willemsen
 * CoolServlets.com
 * February 3, 2000
 * Version 1.01
 *
 * Any errors or feature requests can be reported on CoolServlets.com.
 * We hope you enjoy this program!
 *
 *    Copyright (C) 1999  Pete Willemsen
 *
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

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

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

import com.coolservlets.guestbook.*;
import com.coolservlets.util.*;

/**
 * The main Java servlet for the CSGuestbook system.
 *
 * Three modes of operation: DISPLAY_MODE, RECORD_MODE, ADMIN_MODE
 * 
 * "mode" - determines mode of operation
 *          VALUES: "display", "record", "admin" (default="display")
 *
 * MODE 1 PARAMETERS - DISPLAY_MODE - mode="display" || mode=null
 *
 * "key" - specifies the name of the guestbook to use
 *         VALUES: a string representing name of guestbook (default="default")
 *
 * "html" - determines whether guestbook should return full HTML, or
 *          just guestbook entries (I envision use of the SERVLET tag
 *          in the * latter case)
 *          VALUES: "on", "off" (default="on")
 * 
 * "sty" - specifies the style type for printing of guestbook entries
 *         VALUES: "s1", "s2", "s3", "s4", "s5" (default="s1")
 *
 * "fltr" - specifies whether to filter words in the comment section;
 *          currently uses built-in list of words
 *          VALUES: "on", "off" (default="off")
 *
 * "fltrlist" - specifies a comma-delimited list of strings to use as 
 *              the filter in the comment section.  This option is 
 *              only effective when fltr="on".  The comma-delimited list
 *              of words overrides the built-in list of words.  The 
 *              filter currently only works well with words, so things
 *              like "filter this" won't work well as a filter, but 
 *              unique separate words like "shit" will work.  Future 
 *              versions will be more robust about filtering.
 *              VALUES: comma-delimited list of strings to filter
 *
 * "cnt" - number of entries to return (returns most recent entries)
 *         VALUES: any positive number (default=all)
 *
 * "title" - specifies the title to be used on the guestbook page
 * "fontFace" - sets the style of the font face for the document
 *              VALUES: any font face (default=normal)
 * "fontSize" - sets the style for the font size for the document
 *              VALUES: any font size (default=normal)
 * "background" - uses the file given as parameter for a background
 *                image.  VALUES: an image file (default=none)
 * "bgcolor" - specifies the background color for the guestbook page.
 *             VALUES: any browser specified color (default=normal)
 * "text" - specifies the color for normal text
 *          VALUES: any browser defined color (default="#000000")
 * "link" - specifies the color for links
 *          VALUES: any browser defined color (default="#0000ff")
 * "vlink" - specifies the color for visited links
 *           VALUES: any browser defined color (default="#800080")
 * "alink" - specifies the color for active links
 *           VALUES: any browser defined color (default="#ff0000")
 *
 * MODE 2 PARAMETERS - RECORD_MODE - mode="record"
 *
 * "key" - specifies the name of the guestbook to use
 * "name" - form input parameter that holds their name
 * "email" - form input parameter that holds their email address
 * "url" - form input parameter that holds their url
 * "city" - form input parameter that holds their city
 * "state" - form input parameter that holds their state
 * "country" - form input parameter that holds their country
 * "comment" - form input parameter (textarea) that holds their comment
 *
 * "response" - specifies a thank you response used when an entry has
 *              been added to the database.
 * "linkBack" - Specifies the link to use as a return link.
 *              VALUES: any URL such as "http://www.cnn.com" (default=none)
 * "textBack" - The text that is associated with the linkBack parameter.
 *              VALUES: a string (default="Go Back")
 *
 * "title" - specifies the title to be used on the guestbook page
 * "fontFace" - sets the style of the font face for the document
 *              VALUES: any font face (default=normal)
 * "fontSize" - sets the style for the font size for the document
 *              VALUES: any font size (default=normal)
 * "background" - uses the file given as parameter for a background
 *                image.  VALUES: an image file (default=none)
 * "bgcolor" - specifies the background color for the guestbook page.
 *             VALUES: any browser specified color (default=normal)
 * "text" - specifies the color for normal text
 *          VALUES: any browser defined color (default="#000000")
 * "link" - specifies the color for links
 *          VALUES: any browser defined color (default="#0000ff")
 * "vlink" - specifies the color for visited links
 *           VALUES: any browser defined color (default="#800080")
 * "alink" - specifies the color for active links
 *           VALUES: any browser defined color (default="#ff0000")
 *
 *
 * MODE 3 PARAMETERS - ADMIN_MODE - mode="admin" - NOT IMPLEMENTED
 * 
 * */
public class CSGuestbook extends HttpServlet implements MaintainedServlet {

  /** ****************************************
    * Initialize global variables
    */
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
	
    // Read the guestbook database from file.
    database = readDatabaseFile();
	
    //Startup a maintenance thread that will write the guestbook database
    //to file every 10 minutes.
    maintenance = new ServletMaintenance(this, 10, ServletMaintenance.MINUTES);
  }

    /**
     * Process HTTP requests.
     */
    public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
      
      response.setContentType("text/html");
      
      // --------------------------------------------------------
      // acquire basic options used in all modes
      // --------------------------------------------------------
      thankyou_response   = request.getParameter( "response" );
      if (thankyou_response == null)
	  thankyou_response = "Thanks for signing our guestbook!";
      title      = request.getParameter( "title" );
      if (title == null || title.length() == 0)
	  title = "CSGuestbook";
      fontFace   = request.getParameter( "fontFace" );
      fontSize   = request.getParameter( "fontSize" );
      linkBack   = request.getParameter( "linkBack" );
      textBack   = request.getParameter( "textBack" );
      background = request.getParameter( "background" );
      bgcolor    = request.getParameter( "bgcolor" );
      text       = request.getParameter( "text" );
      link       = request.getParameter( "link" );
      vlink      = request.getParameter( "vlink" );
      alink      = request.getParameter( "alink" );

      // --------------------------------------------------------
      // Check mode type first: DISPLAY, RECORD, ADMIN
      // --------------------------------------------------------
      String mode = request.getParameter("mode");
      if (mode != null) {
	if (mode.equals( "record" )) {
	  
	  // enter RECORD_MODE and process request
	  enterRecordMode( request, response );
	  
	}
	// else if (mode.equals( "admin" )) {
	// do admin duties - not yet completed and will be release
	// in next version
	// }
	else {
	  // assume DISPLAY_MODE if no "known" mode is specified
	  enterDisplayMode( request, response );
	}
      } 
      else {
	// assume DISPLAY_MODE if no mode is specified
	enterDisplayMode( request, response );
      }

  }


  /** ****************************************
    *
    */
  public void doMaintenance() {
    writeDatabaseFile();
  }


  /** ****************************************
    * Called as the servlet is being destroyed. It saves the counter
    * database and stops the maintenance thread.
    */
  public void destroy() {
    writeDatabaseFile();
    maintenance.shutDown();
  } 


  /** ****************************************
    * Get Servlet information
    */
  public String getServletInfo() {
    return "CSGuestbook v1.0 - CoolServlets.com";
  }


  /** ****************************************
    *
    */
    private void printGuestbookHeader( PrintWriter out ) {

          out.println( "<html>" + title + "" );
          // use buffers for a little more string efficiency
          StringBuffer body = new StringBuffer();
	  body.append( "<body " );
	  if (background != null)
	      body.append( "background=\""+background+"\" " );
	  if ((bgcolor != null) && !(bgcolor.equals("")))
	      body.append( "bgcolor=\""+bgcolor+"\" " );
	  if (text != null)
	      body.append( "text=\""+text+"\" " );
	  if (link != null)
	      body.append( "link=\""+link+"\" " );
	  if (vlink != null)
	      body.append( "vlink=\""+vlink+"\" " );
	  if (alink != null)
	      body.append( "alink=\""+alink+"\"" );
	  body.append(">");
          out.println( body.toString() );

	  if (fontFace!=null || fontSize!=null) {
	      out.println( "<font" );
	      if (fontFace != null)
		  out.println("face=\"" + fontFace + "\"");
	      if (fontSize != null)
		  out.println("size=" + fontSize + ">" );
	  }
	
    }


  /** ****************************************
    *
    */
    private void printGuestbookFooter( PrintWriter out ) {
	out.println( "</body>" );
	out.println( "</html>" );
    }


  /** ****************************************
    *
    */
  private void printGuestbookEntry(PrintWriter out, GuestbookEntry entry) {
    entry.print( out, _style, _filter );
  }


  /** ****************************************
    *
    */
  private synchronized void writeDatabaseFile() {
    try {
      ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream( "coolservlets/data/GuestbookDatabase" ));
      out.writeObject(database);
      out.close();
    }
    catch (Exception e) { 
      System.out.println("ERROR writing database file");	
    }
  }


  /** ****************************************
    *
    */
  private synchronized GuestbookDatabase readDatabaseFile() {
    GuestbookDatabase tempdatabase = new GuestbookDatabase();
    try {
      ObjectInputStream in = new ObjectInputStream(new FileInputStream( "coolservlets/data/GuestbookDatabase" ));
      tempdatabase = (GuestbookDatabase)in.readObject();
      in.close();
    }
    catch (Exception e) { }
    
    return tempdatabase;
  }


  /** ****************************************
    * EnterDisplayMode
    */
  private void enterDisplayMode( HttpServletRequest request, HttpServletResponse response ) 
    throws IOException {
      
      PrintWriter out = response.getWriter();

      // --------------------------------------------------------
      // determine which guestbook to use - if no "key" PARAM is
      // specified, use the "DEFAULT" specified guestbook
      // --------------------------------------------------------
      String gbkey = request.getParameter("key");
      if (gbkey == null) {
	  gbkey = DEFAULT_DATABASE_KEY;
      }

      // --------------------------------------------------------
      // if number of entries to output is specified, record that here
      // --------------------------------------------------------
      String count = request.getParameter( "cnt" );
      if (count != null) {
	  try {
	      _entry_output_count = Integer.parseInt( count );
	      if (_entry_output_count < 0 || _entry_output_count > database.size( gbkey )) {
		  _entry_output_count = database.size( gbkey );  // default is to display all
	      }
	      else {
		  // use the default number of entries to print
		  _entry_output_count = database.size( gbkey );
	      }
	  }
	  catch (NumberFormatException nfe) {
	      // use the default number of entries to print
	      _entry_output_count = database.size( gbkey );	      
	  }
      }

      // --------------------------------------------------------
      // check for output format style and record
      // --------------------------------------------------------
      String style = request.getParameter( "sty" );    
      if (style != null) {
	if (style.equals( "s1" )) 
	  _style = new GuestbookStyle( GuestbookStyle.STYLE_1 );
	else if (style.equals( "s2" ))
	  _style = new GuestbookStyle( GuestbookStyle.STYLE_2 );
	else if (style.equals( "s3" )) 
	  _style = new GuestbookStyle( GuestbookStyle.STYLE_3 );
	else if (style.equals( "s4" )) 
	  _style = new GuestbookStyle( GuestbookStyle.STYLE_4 );
	else if (style.equals( "s5" )) 
	  _style = new GuestbookStyle( GuestbookStyle.STYLE_5 );
	else 
	  _style = new GuestbookStyle( GuestbookStyle.STYLE_1 );
      }
      else {
	// use the default style
	_style = new GuestbookStyle( GuestbookStyle.STYLE_1 );
      }

      // --------------------------------------------------------
      // check for whether filter is on or not
      // --------------------------------------------------------
      String filter = request.getParameter( "fltr" );
      String filter_list = request.getParameter( "fltrlist" );
      if ( filter != null ) {
	if (filter.equals( "on" )) {
	    _filter = new GuestbookFilter( true, filter_list );
	}
	else 
	    _filter = new GuestbookFilter( false );
      }
      else 
	  _filter = new GuestbookFilter( false );

      // --------------------------------------------------------
      // check for whether to output full html or not - by default,
      // full html will be printed - default parameter value is "on"
      // --------------------------------------------------------
      String html_param = request.getParameter( "html" );
      if ( html_param != null ) {
	if (html_param.equals( "off" )) {
           _full_html = false;
	}
      }

      // print html header if full html is requested
      if (_full_html) {
	  printGuestbookHeader( out );
      }
      
      out.println( "<h1>" + title + "" );
      out.println( "<hr>
" ); if (_entry_output_count == 0) { out.println( "<p>At the moment, there are no guestbook entries.

" ); } else { // now, print out the specified entries from the specified // guestbook after running the entry info through the filter int idx; for (idx=0; idx<_entry_output_count; idx++) { printGuestbookEntry(out, database.getEntry( gbkey, idx )); } } // print html footer if full html is requested if (_full_html) { printGuestbookFooter( out ); } // close the output stream out.close(); } /** **************************************** * EnterRecordMode */ private void enterRecordMode( HttpServletRequest request, HttpServletResponse response ) throws IOException { // -------------------------------------------------------- // determine which guestbook to use - if no "key" PARAM is // specified, use the "DEFAULT" specified guestbook // -------------------------------------------------------- String gbkey = request.getParameter("key"); if (gbkey == null) { gbkey = DEFAULT_DATABASE_KEY; } // attempt to add entry to specified database GuestbookEntry ge = addDatabaseEntry( request, response, gbkey ); PrintWriter out = response.getWriter(); printGuestbookHeader( out ); out.println( "<h1>" + title + "" ); out.println( "<hr>" ); out.println( thankyou_response ); out.println("<p>Here's the information you entered.

"); GuestbookStyle sty = new GuestbookStyle( GuestbookStyle.FULL ); GuestbookFilter fltr = new GuestbookFilter( false ); ge.print( out, sty, fltr ); if (linkBack != null) { out.println( "<a href=\""+ linkBack + "\">" ); if (textBack != null) out.println( textBack + "</a>" ); else out.println( "Click Here</a>" ); } out.println("<hr>"); printGuestbookFooter( out ); // close the output stream out.close(); } /** **************************************** * */ private synchronized GuestbookEntry addDatabaseEntry( HttpServletRequest request, HttpServletResponse response, String db ) throws IOException { String entry_name = request.getParameter("name"); if (entry_name == null) entry_name = ""; String entry_email = request.getParameter("email"); if (entry_email == null) entry_email = ""; String entry_url = request.getParameter("url"); if (urentry_urll == null) entry_url = ""; String entry_city = request.getParameter("city"); if (entry_city == null) entry_city = ""; String entry_state = request.getParameter("state"); if (entry_state == null) entry_state = ""; String entry_country = request.getParameter("country"); if (entry_country == null) entry_country = ""; String entry_comments = request.getParameter("comment"); if (entry_comments == null) entry_comments = ""; // create a guestbook entry and add it to the database // Security update -- pass all params through an HTML tag filter before // adding them -- added Feb 2000 GuestbookEntry ge = new GuestbookEntry(); ge.name = HTMLUtils.escapeHTMLTags(entry_name); ge.email = HTMLUtils.escapeHTMLTags(entry_email); ge.url = HTMLUtils.escapeHTMLTags(entry_url); ge.city = HTMLUtils.escapeHTMLTags(entry_city); ge.state = HTMLUtils.escapeHTMLTags(entry_state); ge.country = HTMLUtils.escapeHTMLTags(entry_country); ge.comments = HTMLUtils.escapeHTMLTags(entry_comments); database.addEntry( db, ge ); return ge; } private ServletMaintenance maintenance; private GuestbookDatabase database; private final String VERSION_INFO = "version 1.0"; private final String DEFAULT_DATABASE_KEY = "default"; private Date _older_date, _newer_date; private int _entry_output_count = -1; private boolean _full_html = true; private GuestbookStyle _style; private GuestbookFilter _filter; private String thankyou_response; private String title; private String fontFace; private String fontSize; private String linkBack; private String textBack; private String background; private String bgcolor; private String text; private String link; private String vlink; private String alink; }

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2024 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.