httpserver.java

来自「cqME :java framework for TCK test.」· Java 代码 · 共 790 行 · 第 1/2 页

JAVA
790
字号
                return;            }            verboseln(getName() + " next_app: " + next_app);            File jar_path = new File(jarSourceDir, next_app);            verboseln(getName() + " jar_path: " + jar_path);            long length = jar_path.length();            // reset bos's count, discard accumulated output            bos.reset();            PrintWriter pw = new PrintWriter(new OutputStreamWriter(bos, "ISO8859_1"));            pw.println("JAR-File-URL: http://"                 + request.getHost()                 + ":" + port + "/" + next_app);            pw.println("JAR-File-Size: " + length);            pw.println("Main-Class: " + mainClass);            pw.println("Application-Name: Test Suite");  // needed by JAM            pw.println("Use-Once: yes");            pw.close();            setResponseProperty("Content-Type", "application/x-jam");            setResponseProperty("Content-Length", "" + bos.size());            sendDiagnostics(HTTP_OK, out);            flushRawBuffer(bos.toByteArray());        // cmd "get next test"        } else if (path.startsWith(testRoot + "getNextTest")) {            verboseln(getName() + " getNextTest");            if (done) {                setResponseProperty("Content-Length", "" + 0 );                sendDiagnostics(HTTP_OK, out);                return;            }            if (path.length() > testRoot.length() + "getNextTest".length()) {               bundleId = path.substring(testRoot.length() +                                         "getNextTest".length() + 1);            }            byte[] args = testProvider.getNextTest(bundleId);            setResponseProperty("Content-Length",                 "" + (args == null ? 0 : args.length));            sendDiagnostics(HTTP_OK, out);            if (args != null) {                flushRawBuffer(args);            }        // assume cmd is a request for file download        } else {            if (done) {                sendDiagnostics(HTTP_NOT_FOUND, out);                return;            }            File file = new File(jarSourceDir, path);            verboseln(getName() + " file download: " + file);            if (file.isFile() && file.canRead()) {                try {                    FileInputStream fis = new FileInputStream(file);		    DataInputStream fin = new DataInputStream(fis);                    buffer.reset();                    buffer.write(fin, (int)file.length()); 		    fin.close();		    setResponseProperty("Content-Length", 					"" + file.length());		    sendDiagnostics(HTTP_OK, out);		    flushRawBuffer();                    return;                } catch (java.io.InterruptedIOException iioe) {                    sendDiagnostics(HTTP_NOT_FOUND, out);                } catch (IOException ioe) {                    System.out.println("error: " + ioe.getMessage());                    sendDiagnostics(HTTP_SERVER_ERROR, out);                }            }            sendDiagnostics(HTTP_NOT_FOUND, out);        }    }    private void handlePost(URL request, DataInputStream in, PrintWriter out) throws IOException {        String path = request.getFile();        String bundleId = "";        // cmd "send test results"        if (done) {            sendDiagnostics(HTTP_OK, out);            return;        }        if (path.startsWith(testRoot + "sendTestResult")) {            verboseln(getName() + " sendTestResult");            if (path.length() > testRoot.length() + "sendTestResult".length()) {                bundleId = path.substring(testRoot.length() +                                           "sendTestResult".length() + 1);            }            byte[] buf;            int count = -1;            String encoding = getHeaderField("Transfer-Encoding");            if (encoding != null && encoding.equals("chunked")) {                buf = readChunkedData(in);            } else {               try {                   count = Integer.parseInt(getHeaderField("Content-Length"));                   if (count <= 0) {                       System.err.println("Non-positive Content-Length: " + count);                       sendDiagnostics(HTTP_BAD_REQUEST, out);                       return;                   }                   buf = new byte[count];                   in.readFully(buf);               } catch (NumberFormatException nfe) {                   System.err.println("Invalid Content-Length: " + getHeaderField("Content-Length"));                   sendDiagnostics(HTTP_BAD_REQUEST, out);                   return;               }            }                        testProvider.sendTestResult(buf, bundleId);            sendDiagnostics(HTTP_OK, out);        } else {            sendDiagnostics(HTTP_NOT_FOUND, out);        }    }    private byte[] readChunkedData(DataInputStream in) throws IOException {        chunksize = readChunkSize(in);        buffer.reset();        while (chunksize > 0) {            buffer.write(in, chunksize);            readCRLF(in);            chunksize = readChunkSize(in);        }        return buffer.dataCopy();    }     private int readChunkSize(DataInputStream inputStream) throws IOException {        int size = -1;        try {            String chunk = null;            try {                chunk = inputStream.readLine();            } catch (IOException ioe) {                /* throw new IOException(ioe.getMessage()); */            }            if (chunk == null) {                throw new IOException("No Chunk Size");            }            int i;            for (i = 0; i < chunk.length(); i++) {                char ch = chunk.charAt(i);                if (Character.digit(ch, 16) == -1)                    break;            }            size = Integer.parseInt(chunk.substring(0, i), 16);        } catch (NumberFormatException e) {            throw new IOException("invalid chunk size number format");        }                return size;    }    private void readCRLF(DataInputStream in) throws IOException {         int ch;        ch = in.read();        if (ch != '\r') {            throw new IOException("missing CRLF");         }        ch = in.read();        if (ch != '\n') {            throw new IOException("missing CRLF");        }    }     /**     * 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();    }    /**     * Writes content of internal byte array buffer to the raw output stream      *     * @exception java.io.IOException - if an I/O error occurs.     */    public void flushRawBuffer() throws IOException {        raw.write(buffer.data(), 0, buffer.dataLength());        raw.flush();    }     /**     * Returns the print writer for response properties     */    public PrintWriter getTranslatingWriter() {        return out;    }    /**     * Sets a new property for the response     * @param key the header name     * @param value the value of the header     */    public void setResponseProperty(String key, String value) {        responseHeaders.addElement(key + ": " + 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;    }    /**     * Sends response      * @param errCode the response code     * @param out the print writer for response properties     * @exception java.io.IOException - if an I/O error occurs.      */    public void sendDiagnostics(int errCode, PrintWriter out) throws IOException {        out.println("HTTP/1.1 " + errCode + " " + phrase(errCode));        if (getResponseProperty("Content-Length") == null) {            setResponseProperty("Content-Length", "0");        }        if (errCode == HTTP_UNAVAILABLE && getResponseProperty("Retry-After") == null) {            setResponseProperty("Retry-After", "" + retry);        }        for (int i=0; i<responseHeaders.size(); i++) {            String header = (String)responseHeaders.elementAt(i);            out.println(header);        }        out.println();        out.flush();        responseHeaders.removeAllElements();    }    protected void verboseln(String s) {        if (verbose) {            synchronized (testProvider) {                System.out.println(verboseId + s);            }        }    }    public void run() {            Socket conn;            DataInputStream in;            String line = null, method = null;            String url = null, version = null;            StringTokenizer cutter;            URL request;            verboseln(getName() + " HttpServer started @ port " + port);            while (!finish) {                try {                    synchronized(socket) {                        if (finish) {break;}                        try {                            if (done) socket.setSoTimeout(100);                            conn = socket.accept();                        } catch (InterruptedIOException iie) {                            continue;                        }                        if (finish) {                            conn.close();                            try {                                conn.close(); // the second close is intentional                            } catch (IOException ignore) {                            }                            break;                        }                    }                                    } catch (Throwable x) {                    if (!finish)                                        x.printStackTrace();                    continue;                }                try {                    raw = conn.getOutputStream();                    in = new DataInputStream(conn.getInputStream());                } catch (Throwable x) {                    if (!finish)                                        x.printStackTrace();                    try {                        conn.close();                        conn.close(); // the second close is intentional                    } catch (IOException ioe) {}                    continue;                }                try {                    out = new PrintWriter(new OutputStreamWriter(raw, "ISO8859_1"));                } catch (Throwable x) {                    if (!finish)                                        x.printStackTrace();                    try {                        in.close();                        conn.close();                        conn.close(); // the second close is intentional                    } catch (IOException ioe) {}                    continue;                }                try {                    line = in.readLine();                    if (line == null) {                        out.close();                        in.close();                        conn.close();                        try {                            conn.close(); // the second close is intentional                        } catch (IOException ignore) {                        }                        verboseln(getName() + " Connection failure. Retrying.");                        continue;                    }                    IPAddr = conn.getInetAddress().toString();                    verboseln(getName() + " got new request from " +                               IPAddr + ": " + line);                    cutter = new StringTokenizer(line);                    try {                        method = cutter.nextToken();                        url = cutter.nextToken();                        version = cutter.nextToken();                    } catch (NoSuchElementException nsee) {                        System.out.println("Incorrect request received.");                        sendDiagnostics(HTTP_BAD_REQUEST, out);                    }                    readHeaders(in);                       if (method != null && url != null && version != null) {                        try {                            try {                                request = new URL(url);                            } catch (MalformedURLException e) {                                request = new URL("http", host, port, url);                            }                                                if (method.equals(GET)) {                                handleGet(request, out, raw, in);                            } else if (method.equals(POST)) {                                handlePost(request, in, out);                            } else {                                verboseln(getName() + " unknown request method: " + method);                                sendDiagnostics(HTTP_BAD_METHOD, out);                            }                        } catch (MalformedURLException mue) {                            System.out.println("Http server error: " + mue);                            sendDiagnostics(HTTP_BAD_REQUEST, out);                        }                    }                } catch (java.io.InterruptedIOException ignore) {                } catch (Throwable x) {                    if (!finish)                                        x.printStackTrace();                }                try {                    out.close();                    in.close();                    conn.close();                    conn.close(); // the second close is intentional                } catch (IOException ioe) {                }                         }            verboseln(getName() + " HttpServer shut down.");    }} // end class RequestHandler} // end class HttpServer

⌨️ 快捷键说明

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