Search in sources :

Example 16 with Response

use of org.nanohttpd.protocols.http.response.Response in project nanohttpd by NanoHttpd.

the class WebSocketResponseHandlerTest method testWrongConnectionHeaderReturnsNullResponse.

@Test
public void testWrongConnectionHeaderReturnsNullResponse() {
    this.headers.put("connection", "Junk");
    Response handshakeResponse = this.nanoWebSocketServer.handle(this.session);
    assertNull(handshakeResponse.getHeader(NanoWSD.HEADER_UPGRADE));
}
Also used : Response(org.nanohttpd.protocols.http.response.Response) Test(org.junit.Test)

Example 17 with Response

use of org.nanohttpd.protocols.http.response.Response in project nanohttpd by NanoHttpd.

the class HTTPSession method execute.

@Override
public void execute() throws IOException {
    Response r = null;
    try {
        // Read the first 8192 bytes.
        // The full header should fit in here.
        // Apache's default header limit is 8KB.
        // Do NOT assume that a single read will get the entire header
        // at once!
        byte[] buf = new byte[HTTPSession.BUFSIZE];
        this.splitbyte = 0;
        this.rlen = 0;
        int read = -1;
        this.inputStream.mark(HTTPSession.BUFSIZE);
        try {
            read = this.inputStream.read(buf, 0, HTTPSession.BUFSIZE);
        } catch (SSLException e) {
            throw e;
        } catch (IOException e) {
            NanoHTTPD.safeClose(this.inputStream);
            NanoHTTPD.safeClose(this.outputStream);
            throw new SocketException("NanoHttpd Shutdown");
        }
        if (read == -1) {
            // socket was been closed
            NanoHTTPD.safeClose(this.inputStream);
            NanoHTTPD.safeClose(this.outputStream);
            throw new SocketException("NanoHttpd Shutdown");
        }
        while (read > 0) {
            this.rlen += read;
            this.splitbyte = findHeaderEnd(buf, this.rlen);
            if (this.splitbyte > 0) {
                break;
            }
            read = this.inputStream.read(buf, this.rlen, HTTPSession.BUFSIZE - this.rlen);
        }
        if (this.splitbyte < this.rlen) {
            this.inputStream.reset();
            this.inputStream.skip(this.splitbyte);
        }
        this.parms = new HashMap<String, List<String>>();
        if (null == this.headers) {
            this.headers = new HashMap<String, String>();
        } else {
            this.headers.clear();
        }
        // Create a BufferedReader for parsing the header.
        BufferedReader hin = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf, 0, this.rlen)));
        // Decode the header into parms and header java properties
        Map<String, String> pre = new HashMap<String, String>();
        decodeHeader(hin, pre, this.parms, this.headers);
        if (null != this.remoteIp) {
            this.headers.put("remote-addr", this.remoteIp);
            this.headers.put("http-client-ip", this.remoteIp);
        }
        this.method = Method.lookup(pre.get("method"));
        if (this.method == null) {
            throw new ResponseException(Status.BAD_REQUEST, "BAD REQUEST: Syntax error. HTTP verb " + pre.get("method") + " unhandled.");
        }
        this.uri = pre.get("uri");
        this.cookies = new CookieHandler(this.headers);
        String connection = this.headers.get("connection");
        boolean keepAlive = "HTTP/1.1".equals(protocolVersion) && (connection == null || !connection.matches("(?i).*close.*"));
        // Ok, now do the serve()
        // TODO: long body_size = getBodySize();
        // TODO: long pos_before_serve = this.inputStream.totalRead()
        // (requires implementation for totalRead())
        r = httpd.handle(this);
        if (r == null) {
            throw new ResponseException(Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: Serve() returned a null response.");
        } else {
            String acceptEncoding = this.headers.get("accept-encoding");
            this.cookies.unloadQueue(r);
            r.setRequestMethod(this.method);
            if (acceptEncoding == null || !acceptEncoding.contains("gzip")) {
                r.setUseGzip(false);
            }
            r.setKeepAlive(keepAlive);
            r.send(this.outputStream);
        }
        if (!keepAlive || r.isCloseConnection()) {
            throw new SocketException("NanoHttpd Shutdown");
        }
    } catch (SocketException e) {
        // throw it out to close socket object (finalAccept)
        throw e;
    } catch (SocketTimeoutException ste) {
        // exception up the call stack.
        throw ste;
    } catch (SSLException ssle) {
        Response resp = Response.newFixedLengthResponse(Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, "SSL PROTOCOL FAILURE: " + ssle.getMessage());
        resp.send(this.outputStream);
        NanoHTTPD.safeClose(this.outputStream);
    } catch (IOException ioe) {
        Response resp = Response.newFixedLengthResponse(Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
        resp.send(this.outputStream);
        NanoHTTPD.safeClose(this.outputStream);
    } catch (ResponseException re) {
        Response resp = Response.newFixedLengthResponse(re.getStatus(), NanoHTTPD.MIME_PLAINTEXT, re.getMessage());
        resp.send(this.outputStream);
        NanoHTTPD.safeClose(this.outputStream);
    } finally {
        NanoHTTPD.safeClose(r);
        this.tempFileManager.clear();
    }
}
Also used : SocketException(java.net.SocketException) InputStreamReader(java.io.InputStreamReader) HashMap(java.util.HashMap) ResponseException(org.nanohttpd.protocols.http.NanoHTTPD.ResponseException) IOException(java.io.IOException) SSLException(javax.net.ssl.SSLException) Response(org.nanohttpd.protocols.http.response.Response) SocketTimeoutException(java.net.SocketTimeoutException) ByteArrayInputStream(java.io.ByteArrayInputStream) BufferedReader(java.io.BufferedReader) ArrayList(java.util.ArrayList) List(java.util.List) CookieHandler(org.nanohttpd.protocols.http.content.CookieHandler)

Aggregations

Response (org.nanohttpd.protocols.http.response.Response)17 Test (org.junit.Test)9 ByteArrayInputStream (java.io.ByteArrayInputStream)4 IOException (java.io.IOException)4 FileInputStream (java.io.FileInputStream)3 CookieHandler (org.nanohttpd.protocols.http.content.CookieHandler)3 BufferedReader (java.io.BufferedReader)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 File (java.io.File)2 InputStreamReader (java.io.InputStreamReader)2 HashMap (java.util.HashMap)2 HTTPSession (org.nanohttpd.protocols.http.HTTPSession)2 FileNotFoundException (java.io.FileNotFoundException)1 InputStream (java.io.InputStream)1 SocketException (java.net.SocketException)1 SocketTimeoutException (java.net.SocketTimeoutException)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 SimpleDateFormat (java.text.SimpleDateFormat)1 ArrayList (java.util.ArrayList)1 Date (java.util.Date)1