
import java.util.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;

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

public class DumpServlet extends HttpServlet
{
  static final String COUNT = "count";
  static final String CHUNK = "chunked";
  static final String SLEEP = "sleep";

  static final int DEFAULT_COUNT = 4096;
  static final long DEFAULT_SLEEP = 1000;

  protected void doGet(HttpServletRequest req,  HttpServletResponse resp)
    throws ServletException, IOException
  {
    doPost(req, resp);
  }

  protected void doPost(HttpServletRequest req,  HttpServletResponse resp)
    throws ServletException, IOException
  {
    String value = req.getParameter(COUNT);

    int count = value == null ? DEFAULT_COUNT : Integer.parseInt(value);
    boolean chunked = new Boolean(req.getParameter(CHUNK)).booleanValue();

    value = req.getParameter(SLEEP);

    long sleep = value == null ? DEFAULT_SLEEP : Long.parseLong(value);

    resp.setStatus(resp.SC_OK);
    resp.setContentType("application/octet-stream");

    String head = "Dumping " + count + 
      " bytes, sleeping " + sleep + " millis, chunked " + chunked + "\n";

    byte[] headBytes = head.getBytes();

    if ( !chunked )
    {
      resp.setContentLength(count + headBytes.length);
    }

    resp.getOutputStream().write(headBytes);

    byte[] b = new byte[128];
    for(int i = 0; i < b.length; i++)
    {
      b[i] = (byte)(i%20 + (int)'a');
      if ( b[i] == 'a' )
      {
        b[i] = '\n';
      }
    }

    while (count > 0)
    {
      int write = Math.min(b.length, count);
      count -= write;
      resp.getOutputStream().write(b, 0, write);
      resp.getOutputStream().flush();
    }

    try
    {
      Thread.sleep(sleep);
    }
    catch (Throwable t)
    {}
  }
}
