package examples.htmlkona;

import java.io.*;
import java.util.*;
import weblogic.html.*;
import weblogic.common.*;
import weblogic.db.jdbc.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 * This servlet retrieves an image by a key provided in the URL
 * and displays it.
 * 
 * @author Copyright (c) 1996-98 by WebLogic, Inc. All Rights Reserved.
 * @author Copyright (c) 1999-2000 by BEA Systems, Inc. All Rights Reserved.
 */
public class ImageByKeyDisplay extends HttpServlet {

  public synchronized void service(HttpServletRequest req, HttpServletResponse res)
    throws IOException
  {
    Connection conn = null;

    try {
      res.setStatus(HttpServletResponse.SC_OK);
      String iname  = req.getParameter("imagename");
      conn = defaults.login();
  
      if (iname != null) {
	
	// Select the image from the image table
        TableDataSet td = new TableDataSet(conn, "imagetable");    
        td.selectStmt().setQbe("name", iname);
        td.fetchRecords(); 

        Record rec = td.getRecord(0);
	res.setContentType("image/" + rec.getValue("type").asString());

        // Retrieve the images from the database
        ImagePage hp = new ImagePage(rec.getValue("data").asBytes());
        hp.output(res.getOutputStream());  
      }
      else {
	res.setContentType("text/html");

        TableElement tab = new TableElement();
	tab.addElement(new TableRowElement()
		       .addElement(new BoldElement("Gif #1"))
		       .addElement(new ImageElement(defaults.prefix() +
						    "ImageByKeyDisplay?imagename=vars")))
	  .addElement(new TableRowElement()
		      .addElement(new BoldElement("Gif #2"))
		      .addElement(new ImageElement(defaults.prefix() +
						   "ImageByKeyDisplay?imagename=excepts")));
	
        ServletPage hp = new ServletPage("Example 15");
	hp.getBodyElement()
	  .setAttribute(BodyElement.bgColor, HtmlColor.white);
        hp.getBody()
          .addElement(new HeadingElement("These gifs were retrieved from the " + 
					 "database based on a key passed as a URL argument", 2))
	  .addElement(MarkupElement.HorizontalRule)
          .addElement(tab.asCenteredElement());
	
        hp.output(res.getOutputStream());
	
      }
    }
    catch (Exception e) {
      defaults.showException(e, res.getOutputStream());
    }
    finally {
      try {conn.close();} catch (Exception e2) {;}
    }
  }
}

