w3c.model.tools.basicweb.Reply

w3c.model.tools.basicweb.Reply

/* basicweb.Reply.java
 * $Id, $Date eric Exp $
 * (c) COPYRIGHT MIT and INRIA, 1997.
 * Please first read the full copyright statement in file COPYRIGHT.html
 *
 * Use only under adult supervision.
 */

package w3c.model.tools.basicweb;

import java.io.*;
import java.net.*;
import java.util.*;
import w3c.model.www.pep.PEPAgent;
import w3c.model.www.pep.altlib.HttpErrors;
import w3c.model.www.pep.altlib.ErrorContext;

class Reply extends Message implements HttpErrors 
    /* D A T A */
    /*  the status line is made up of three elements:  *
     *  HTTP/1.1     200         OK                    *
     *  httpVersion, statusCode, reasonPhrase          */
    String httpVersion;
    int statusCode;
    String reasonPhrase;
    /* the original request is used to get status version */
    Request request;

/*

Constructors

*/
    Reply (Socket socket, InputStream in, OutputStream out, Request request) {
	super(socket, in, out, request.URI, request);
	this.request = request;
    }

    void copyStatusLine (Reply copy) {
	makeStatusLine(copy.httpVersion, copy.statusCode, copy.reasonPhrase);
    }

    /* S I M P L E   A C C E S S */
    int getStatusCode () {return statusCode;}

    /* I N H E R I T E D   A B S T R A C T S */
    boolean parseStartLine () {
	int iStatusCode, iReasonPhrase;
	if ((iStatusCode = startLine.indexOf(' ')) < 0 || (iReasonPhrase = startLine.indexOf(' ', iStatusCode + 1)) < 0))
	    return false;
	httpVersion = startLine.substring(0, iStatusCode);
	String tmp = startLine.substring(iStatusCode+1, iReasonPhrase);
	statusCode = Integer.parseInt(tmp);
	reasonPhrase = startLine.substring(iReasonPhrase+1);

	if (!httpVersion.startsWith("HTTP/")))
	    return false;
	httpVersion = httpVersion.substring(5);
	return true;
    }

    /* S T A T U S   L I N E */
    void makeStatusLine (String httpVersion, int statusCode, String reasonPhrase) {
	this.httpVersion = httpVersion;
	this.statusCode = statusCode;
	this.reasonPhrase = reasonPhrase;
	startLine = "HTTP/" + httpVersion + " " + statusCode + " " + reasonPhrase;
    }
    void makeStatusLine (int index) {
	makeStatusLine(request.getVersion(), statusCodes[index], reasonPhrases[index]);
    }

    /* P R E F A B R I C A T E D   R E P L I E S */
    /* some convenient prefab replies */
    final static String BUMMER = "<HTML><HEAD><TITLE>Bummer</TITLE></HEAD>n<BODY><H1>Bummer</H1>so sorry</BODY></HTML>n";
    final static String PUT_REPLY = "<HTML><HEAD><TITLE>PUT reply</TITLE></HEAD>n<BODY><H1>You did a put</H1>I sure hope you're not up to anything naughty.</BODY></HTML>n";

    void prefab (int code, String data) throws IOException{
	makeStatusLine(code);
	setMediaType(TEXT_HTML);
	setHeaderValue(CONTENT_LENGTH, "" + data.length());
	write(data);
    }