basehttpserver.java.svn-base

来自「cqME :java framework for TCK test.」· SVN-BASE 代码 · 共 554 行 · 第 1/2 页

SVN-BASE
554
字号
/* * $Id$ * * Copyright 1996-2007 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 only, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License version 2 for more details (a copy is * included at /legal/license.txt). * * You should have received a copy of the GNU General Public License * version 2 along with this work; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa * Clara, CA 95054 or visit www.sun.com if you need additional * information or have any questions. * */package com.sun.cldc.communication.midp;import java.io.DataInputStream;import java.io.IOException;import java.io.InterruptedIOException;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.io.PrintWriter;import java.net.MalformedURLException;import java.net.ServerSocket;import java.net.Socket;import java.net.URL;import java.util.Hashtable;import java.util.NoSuchElementException;import java.util.StringTokenizer;import java.util.Vector;public abstract class BaseHttpServer extends Thread implements HttpServer {    protected boolean verbose;    protected ServerSocket socket;    protected OutputStream raw;    protected boolean readMore = false;    protected PrintWriter out;    private Vector responseHeaders = new Vector();    protected Hashtable requestHeaders;    private String host;    private int port;    private int retry;    public String getHost() {       return host;    }    public int getPort() {        return port;    }    public int getRetry() {        return retry;    }    public void setParams(boolean verbose, String host,                                      int port, int retry) {        this.verbose = verbose;        this.host = host;        this.port = port;        this.retry = retry;    }    public void setSocket(ServerSocket socket) {        this.socket = socket;    }    public void verboseln(String s) {        if (verbose) {            System.out.println(s);        }    }        public void verbosetrace(Throwable t) {        if (verbose) {            t.printStackTrace();        }    }    protected void printHeader(String header) {        out.print(header);        out.print("\r\n");    }        /**     * Sends response      * @param errCode the response code     * @exception java.io.IOException - if an I/O error occurs.      */    public void sendDiagnostics(int errCode, String message)                                                            throws IOException {        printHeader("HTTP/1.1 " + errCode + " " + ((message == null)                                                ? phrase(errCode) : message));        if (getResponseProperty("Content-Length") == null && message == null) {            setResponseProperty("Content-Length", "0");        }        if (errCode == HTTP_UNAVAILABLE && getResponseProperty("Retry-After") == null) {            setResponseProperty("Retry-After", "" + retry);        }              setResponseProperty("Connection", "close");        for (int i = 0; i < responseHeaders.size(); i++) {            String header = (String)responseHeaders.elementAt(i);            printHeader(header);        }        out.print("\r\n");        out.flush();        clearResponseProperties();    }    public void sendDiagnostics(int errCode) throws IOException {        sendDiagnostics(errCode, null);    }    protected String phrase(int code) {        switch (code) {            case HTTP_OK: return "Ok";            case HTTP_BAD_REQUEST: return "Bad Request";            case HTTP_NOT_FOUND: return "Not Found";            case HTTP_BAD_METHOD: return "Bad Method";            case HTTP_SERVER_ERROR: return "Server Error";            case HTTP_UNAVAILABLE: return "Server Unavailable";            default: return null;        }    }    /**     * Returns a value for the request property     * @param name the header name      */    public String getRequestProperty(String name) {        if (requestHeaders == null) return null;               return (String)requestHeaders.get(name.toLowerCase());    }    public void setRequestProperty(String name, String value) {        requestHeaders.put(name.toLowerCase(), value);    }    public void clearResponseProperties() {        responseHeaders.removeAllElements();    }    public Vector getResponseProperties() {        return responseHeaders;    }    /**     * Sets a new property for the response     * @param name the header name     * @param value the value of the header     */    public void setResponseProperty(String name, String value) {        responseHeaders.addElement(name + ": " + value);    }    /**     * Returns a value for the response property     * @param name the header name      */    public String getResponseProperty(String name) {        for (int i = 0; responseHeaders != null && i < responseHeaders.size(); i++) {            String field = (String)responseHeaders.elementAt(i);            int index = field.indexOf(':');            if (index <= 0) throw new IllegalArgumentException(                                "illegal header field: " + field);            String key = field.substring(0, index);            if (name.equalsIgnoreCase(key)) {                return field.substring(key.length() + 2);            }        }        return null;    }            protected void readHeaders(DataInputStream in) throws IOException {        int index;        String line;        requestHeaders = new Hashtable();        for (;;) {            line = in.readLine();            // funny enough, but this deprecated method does exactly what we need!            // zero-extension from byte to character corresponds to ISO8859_1!            if (line == null || line.length() == 0) break;            index = line.indexOf(':');            if (index <= 0 || index + 1 == line.length()) continue;                        setRequestProperty(line.substring(0, index), line.substring(index + 1).trim());        }    }    /**     * Writes a byte array to the raw output stream      *     * @param data the byte array of data to be written into     *             the output stream.     * @exception java.io.IOException - if an I/O error occurs.     */    public void flushRawBuffer(byte[] data) throws IOException {        raw.write(data);        raw.flush();     }     /**     * Returns the print writer for response properties     */    public PrintWriter getTranslatingWriter() {        return out;    }    /**     * Processes the GET request     * @param request the URL request     * @param in the input stream to read any payload in this request     */    protected abstract void handleGet(URL request, DataInputStream in) throws IOException;    /**     * Processes the POST request     * @param request the URL request     * @param in the input stream to read any payload in this request     */    protected abstract void handlePost(URL request, DataInputStream in) throws IOException;    /**     * Processes the HEAD request.     * <p>     * This method should be overridden by those Servers that actually support     * <code>HEAD</code> method.     *     * @param request     *                the URL request to process.     */    protected void handleHead(URL request) throws IOException {        verboseln("unknown request method: " + HEAD);        sendDiagnostics(HTTP_BAD_METHOD);    }    protected abstract boolean isDone();    /**     * Reads chunked data from the inout stream.     * @param inputStream the input stream to read data from     * @return the byte array of data     */    protected byte[] readChunkedData(DataInputStream inputStream) throws IOException {        byte[] data = {};        int length = 0;        int chunksize = readChunkSize(inputStream);        while (chunksize > 0) {            byte[] readBuf = new byte[chunksize];            inputStream.readFully(readBuf, 0, chunksize);            readCRLF(inputStream);            length += chunksize;

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?