import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.net.*;
import java.util.*;

public class CheckResponse extends Object {
  protected String url, nextUrl;
  protected HttpServletResponse res;

  public CheckResponse(HttpServletRequest req, HttpServletResponse r) throws InternalException {
    res = r;
    url = req.getParameter("url");
    nextUrl = req.getParameter("nextUrl");

    if(url == null)
      throw new InternalException("missing url in CheckResponse");
    else if(nextUrl == null)
      throw new InternalException("missing nextUrl in CheckResponse");
  }

  public void getResponse() throws IOException, URLFileException, APIException {
    URL p;
    URLConnection page;
    InputStream in;
    DataInputStream din;

    try {
      p = new URL(url);
      page = p.openConnection();
      in = page.getInputStream();
      din = new DataInputStream(in);

      String line, eline = null;
      int numlines = 0, ecode = -1;
      boolean ok = false, goodEcode = false;
      while((line = din.readLine()) != null) {
	if(numlines == 0)
	  ;  // <PRE> line
	else if(numlines == 1) {
	  try {
	    ecode = Integer.parseInt(line);
	    goodEcode = true;
	    if(ecode == 0)
	      ok = true;
	  }
	  catch (NumberFormatException nf) {
	    eline = new String(line);
	  }
	}
	numlines++;
      }

      if(ok)
	res.sendRedirect(nextUrl);
      else if(goodEcode)
	throw new APIException(ecode, "Check Response: error # " + ecode);
      else if(eline != null)
	throw new APIException("Check Response: " + eline);
      else
	throw new APIException("Check Response: unknown error");
    }
    catch (FileNotFoundException fnf) {
      throw new URLFileException(fnf.getMessage());
    }
  }
}
