FileDocCategorySizeDatePackage
GraphicalCounter.javaAPI DocExample2874Tue Jan 25 10:45:14 GMT 2000None

GraphicalCounter

public class GraphicalCounter extends HttpServlet

Fields Summary
public static final String
DIR
public static final String
COUNT
Constructors Summary
Methods Summary
public voiddoGet(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse res)

  
       
                                  
    ServletOutputStream out = res.getOutputStream();
  
    Frame frame = null;
    Graphics g = null;

    try {
      // Get the count to display, must be sole value in the raw query string
      // Or use the default
      String count = (String)req.getQueryString();
      if (count == null) count = COUNT;
  
      int countlen = count.length();
      Image images[] = new Image[countlen];
  
      for (int i = 0; i < countlen; i++) {
        String imageSrc = 
          req.getRealPath(DIR + "/" + count.charAt(i) + ".GIF");
        images[i] = Toolkit.getDefaultToolkit().getImage(imageSrc);
      }
  
      // Create an unshown Frame
      frame = new Frame();
      frame.addNotify();
  
      // Load the images
      MediaTracker mt = new MediaTracker(frame);
      for (int i = 0; i < countlen; i++) {
        mt.addImage(images[i], i);
      }
      try {
        mt.waitForAll();
      }
      catch (InterruptedException e) { 
        getServletContext().log(e, "Interrupted while loading image");
        throw new ServletException(e.getMessage());
      }
  
      // Check for problems loading the images
      if (mt.isErrorAny()) {
        // We had a problem, find which image(s)
        StringBuffer problemChars = new StringBuffer();
        for (int i = 0; i < countlen; i++) {
          if (mt.isErrorID(i)) {
            problemChars.append(count.charAt(i));
          }
        }
        throw new ServletException(
          "Coult not load an image for these characters: " + 
          problemChars.toString());
      }
  
      // Get the cumulative size of the images
      int width = 0;
      int height = 0;
      for (int i = 0; i < countlen; i++) {
        width += images[i].getWidth(frame);
        height = Math.max(height, images[i].getHeight(frame));
      }
  
      // Get a graphics region to match, using the Frame
      Image image = frame.createImage(width, height);
      g = image.getGraphics();
  
      // Draw the images
      int xindex = 0;
      for (int i = 0; i < countlen; i++) {
        g.drawImage(images[i], xindex, 0, frame);
        xindex += images[i].getWidth(frame);
      }
  
      // Encode and return the composite
      res.setContentType("image/gif");
      GifEncoder encoder = new GifEncoder(image, out);
      encoder.encode();
    }
    finally {
      // Clean up resources
      if (g != null) g.dispose();
      if (frame != null) frame.removeNotify();
    }