midhttpsupportserver.java.svn-base

来自「cqME :java framework for TCK test.」· SVN-BASE 代码 · 共 350 行

SVN-BASE
350
字号
/* * $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.tck.midp.lib;import java.io.DataInputStream;import java.io.IOException;import java.net.InetAddress;import java.net.MalformedURLException;import java.net.URL;import java.net.UnknownHostException;import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Hashtable;import java.util.Locale;import java.util.ResourceBundle;import java.util.StringTokenizer;import java.util.TimeZone;import com.sun.cldc.communication.midp.BaseHttpServer;import com.sun.cldc.communication.midp.BaseServer;public class MIDHttpSupportServer extends BaseServer {    private static final Hashtable shareData = new Hashtable();    private String testPath = null;    public MIDHttpSupportServer() {        done = true;        try {            host = InetAddress.getLocalHost().getHostName();        } catch (UnknownHostException uhe) {            host = "localhost";        }    }    /**     * Initialize the server with necessary parameters.     * "test.root=bar"     * "http.port=42"     */    public void init(String[] arg) {        for (int i = 0; arg != null && i < arg.length; i++) {            // Parsed argument below is required for tests on HttpConnection            // test.url=http://<host>:<port>/...            if (arg[i].startsWith(TEST_URL) && arg[i].length() > TEST_URL.length()) {                try {                    URL url = new URL(arg[i].substring(TEST_URL.length()));                    testPath = url.getFile();                    host = url.getHost();                    port = url.getPort();                } catch (MalformedURLException e) {                    throw new IllegalArgumentException(i18n.getString("error.url")                                       + arg[i].substring(TEST_URL.length()));                }                continue;            }            super.processArg(arg[i]);        }        if (runners == null) {            runners = new RequestHandler[handlerCount];            for (int i = 0; i < handlerCount; i++) {                runners[i] = new RequestHandler();                runners[i].setName("HttpSupportRequestHandler_" + i);                ((BaseHttpServer) runners[i]).setParams(verbose, host, port, retry);            }        }    }    public class RequestHandler extends BaseHttpServer {        private long date;        private long length = 0;        private byte[] data = null;        private String type;        private String enc;        private String respMessage = "OK";        private DateFormat formatter;        public RequestHandler() {            readMore = false;        }            protected void handleGet(URL request, DataInputStream in)                throws IOException {            handleCommon(request, GET);        }        protected void handleHead(URL request)                throws IOException {            handleCommon(request, HEAD);        }        protected void handlePost(URL request, DataInputStream in)  throws IOException {            byte[] buf = null;            int cl_size;            String te = getRequestProperty("transfer-encoding");            String cl = getRequestProperty("content-length");                            if (te != null && te.equals("chunked")) {                buf = readChunkedData(in);                ignoreEntityHeader(in);            } else if (cl != null &&                 (cl_size = Integer.parseInt(getRequestProperty("content-length"))) != 0) {                buf = new byte[cl_size];                in.readFully(buf);            }            if (buf != null) {                synchronized (shareData) {                    String newCookie = String.valueOf(System.currentTimeMillis());                    setResponseProperty("Test-Cookie", newCookie);                    shareData.put(newCookie, buf);                }            }            handleCommon(request, POST);        }        protected boolean isDone() {            return done;        }        private boolean isValidHttpMethod(String httpMethod) {            return ((httpMethod != null)                    && (httpMethod.equals(GET)                            || httpMethod.equals(POST)                            || httpMethod.equals(HEAD)));        }        /**         * @param httpMethod Should be HttpServer.GET,         * HttpServer.POST or HttpServer.HEAD.         */        private void handleCommon(URL request, String httpMethod)                throws IOException {            String path = request.getFile();            int idx = path.indexOf('?');            if (idx != -1) {                String testQuery = path.substring(path.indexOf('?') + 1);                parseQuery(testQuery);                path = path.substring(0, idx);            }            // Checking for supported encodings            String acceptedEncoding = getRequestProperty("accept-encoding");            // Setting "Cache-Control" header to "no-transform" to ensure            // fewer header and content modifications are done by a proxy            setResponseProperty("Cache-Control", "no-transform");            if (path.equals(testPath)) {                String cookie = getRequestProperty("test-cookie");                try {                    if (formatter != null) {                        String d = formatter.format(new Date(date));                        setResponseProperty("Date", d);                        setResponseProperty("Last-Modified", d);                        setResponseProperty("Expires", d);                    }                    if (type != null) {                        setResponseProperty("Content-Type", type);                    } else {                        setResponseProperty(                                "Content-Type", "application/octet-stream");                    }                    if (enc != null) {                        sendEncodedData(acceptedEncoding, httpMethod);                        return;                    }                    if (length < 0) {                        // do not send Content-Length header                        // and set readMore to false.                        readMore = false;                        sendDiagnostics(HTTP_OK, respMessage);                    } else if (length > 0) {                        // if length is not 0                        // this means the content length is                        // set via test. Thus length takes                        // precedence over data.                        // if length is 0, set content length                        // based on the data.                        setResponseProperty("Content-Length",                                Long.toString(length));                        sendDiagnostics(HTTP_OK, respMessage);                        if (!HEAD.equals(httpMethod)) {                            byte[] dummyData = new byte[(int) length];                            for (int i = 0; i < dummyData.length; i++) {                                dummyData[i] = (byte) 63;                            }                            flushRawBuffer(dummyData);                        }                    } else if (data != null) {                        setResponseProperty("Content-Length",                                 Long.toString(data.length));                        sendDiagnostics(HTTP_OK, respMessage);                        if (!HEAD.equals(httpMethod)) {                            flushRawBuffer(data);                        }                    } else if (shareData.size() != 0                            && !POST.equals(httpMethod) && cookie != null) {                        byte[] content = null;                        synchronized (shareData) {                            content = (byte[]) shareData.get(cookie);                            shareData.remove(cookie);                        }                        if (content != null) {                            setResponseProperty("Content-Length",                                   Long.toString(content.length));                            sendDiagnostics(HTTP_OK, respMessage);                            if (!HEAD.equals(httpMethod)) {                                flushRawBuffer(content);                            }                        } else {                            setResponseProperty("Content-Length", "0");                            sendDiagnostics(HTTP_OK, respMessage);                        }                    } else {                        setResponseProperty("Content-Length", "0");                        sendDiagnostics(HTTP_OK, respMessage);                    }                } finally {                    clearResponseProperties();                    formatter = null;                    type = null;                    enc = null;                    data = null;                    length = 0;                }            // assume cmd is a request for file download            } else {                sendDiagnostics(HTTP_NOT_FOUND);            }        }        // Parses parameter's query in form "param=value+[;]param=value..."        private void parseQuery(String query) {            String param;            String value;            String charenc = null;            String tmpdata = null;            StringTokenizer st = new StringTokenizer(query, "=+;");            while (st.hasMoreTokens()) {                param = st.nextToken();                value = st.nextToken();                if (param.equals("Date")) {                    formatter = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss 'GMT'",                                 Locale.US);                    formatter.setTimeZone(TimeZone.getTimeZone("GMT"));                    try {                        date = Long.parseLong(value);                    } catch (NumberFormatException e) {                        verboseln("HttpSupportServer: "                                + i18n.getString("error.date") + " = " + value);                        throw new IllegalArgumentException(i18n.getString("error.date"));                    }                                  } else if (param.equals("Content-Length")) {                    try {                        length = Long.parseLong(value);                    } catch (NumberFormatException e) {                        verboseln("HttpSupportServer: "                                + i18n.getString("error.length") + " = " + value);                        throw new IllegalArgumentException(i18n.getString("error.length"));                    }                } else if (param.equals("Response-Message")) {                    respMessage = value;                } else if (param.equals("Content-Encoding")) {                    enc = value;                } else if (param.equals("Content-Type")) {                    type = value;                } else if (param.equals("Data")) {                    tmpdata = value;                } else if (param.equals("charset")) {                    charenc = value;                }            }            try {                if (tmpdata != null) {                    data = tmpdata.getBytes(charenc);                }            } catch (Exception e) {                verbosetrace(e);            }        }        private void sendEncodedData(String acceptedEncoding,                String httpMethod) throws IOException {            byte[] encodedData;                                    // Encoded data represents a string "Hello"            if (acceptedEncoding != null                     && acceptedEncoding.indexOf("gzip") == -1) {                // WAP Terminal is most likely to support "deflate"                // content-encoding                setResponseProperty("Content-Encoding", "deflate");                encodedData = new byte[] {120, -100, -13, 72, -51, -55, -55,                        7, 0, 5, -116, 1, -11};            } else {                // Using "gzip" data and content-encoding                setResponseProperty("Content-Encoding", "gzip");                encodedData = new byte[] {31, -117, 8, 0, 0, 0, 0, 0, 0, 0,                        -13, 72, -51, -55, -55, 7, 0, -126, -119, -47, -9, 5,                        0, 0, 0};            }            setResponseProperty("Content-Length",                    Long.toString(encodedData.length));            sendDiagnostics(HTTP_OK, respMessage);            if (!HEAD.equals(httpMethod)) {                flushRawBuffer(encodedData);            }        }    }    private static ResourceBundle i18n =         ResourceBundle.getBundle("com.sun.tck.midp.lib.i18n");    // DEBUG/*    public static void main(String[] arg) {        MIDHttpSupportServer server = new MIDHttpSupportServer();        server.init(new String[] {"test.url=http://localhost:8022/index.html"});        server.start();        System.out.println("server.start()");        for (;;) {}    }*/}

⌨️ 快捷键说明

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