Search in sources :

Example 1 with Response

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

the class WebSocketResponseHandlerTest method testMissingKeyReturnsErrorResponse.

@Test
public void testMissingKeyReturnsErrorResponse() {
    this.headers.remove("sec-websocket-key");
    Response handshakeResponse = this.nanoWebSocketServer.handle(this.session);
    assertNotNull(handshakeResponse);
    assertEquals(Status.BAD_REQUEST, handshakeResponse.getStatus());
}
Also used : Response(org.nanohttpd.protocols.http.response.Response) Test(org.junit.Test)

Example 2 with Response

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

the class NanoWSD method handleWebSocket.

public Response handleWebSocket(final IHTTPSession session) {
    Map<String, String> headers = session.getHeaders();
    if (isWebsocketRequested(session)) {
        if (!NanoWSD.HEADER_WEBSOCKET_VERSION_VALUE.equalsIgnoreCase(headers.get(NanoWSD.HEADER_WEBSOCKET_VERSION))) {
            return Response.newFixedLengthResponse(Status.BAD_REQUEST, NanoHTTPD.MIME_PLAINTEXT, "Invalid Websocket-Version " + headers.get(NanoWSD.HEADER_WEBSOCKET_VERSION));
        }
        if (!headers.containsKey(NanoWSD.HEADER_WEBSOCKET_KEY)) {
            return Response.newFixedLengthResponse(Status.BAD_REQUEST, NanoHTTPD.MIME_PLAINTEXT, "Missing Websocket-Key");
        }
        WebSocket webSocket = openWebSocket(session);
        Response handshakeResponse = webSocket.getHandshakeResponse();
        try {
            handshakeResponse.addHeader(NanoWSD.HEADER_WEBSOCKET_ACCEPT, makeAcceptKey(headers.get(NanoWSD.HEADER_WEBSOCKET_KEY)));
        } catch (NoSuchAlgorithmException e) {
            return Response.newFixedLengthResponse(Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, "The SHA-1 Algorithm required for websockets is not available on the server.");
        }
        if (headers.containsKey(NanoWSD.HEADER_WEBSOCKET_PROTOCOL)) {
            handshakeResponse.addHeader(NanoWSD.HEADER_WEBSOCKET_PROTOCOL, headers.get(NanoWSD.HEADER_WEBSOCKET_PROTOCOL).split(",")[0]);
        }
        return handshakeResponse;
    } else {
        return null;
    }
}
Also used : Response(org.nanohttpd.protocols.http.response.Response) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 3 with Response

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

the class SimpleWebServer method newFixedFileResponse.

private Response newFixedFileResponse(File file, String mime) throws FileNotFoundException {
    Response res;
    res = Response.newFixedLengthResponse(Status.OK, mime, new FileInputStream(file), (int) file.length());
    res.addHeader("Accept-Ranges", "bytes");
    return res;
}
Also used : Response(org.nanohttpd.protocols.http.response.Response) FileInputStream(java.io.FileInputStream)

Example 4 with Response

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

the class SimpleWebServer method serveFile.

/**
 * Serves file from homeDir and its' subdirectories (only). Uses only URI,
 * ignores all headers and HTTP parameters.
 */
Response serveFile(String uri, Map<String, String> header, File file, String mime) {
    Response res;
    try {
        // Calculate etag
        String etag = Integer.toHexString((file.getAbsolutePath() + file.lastModified() + "" + file.length()).hashCode());
        // Support (simple) skipping:
        long startFrom = 0;
        long endAt = -1;
        String range = header.get("range");
        if (range != null) {
            if (range.startsWith("bytes=")) {
                range = range.substring("bytes=".length());
                int minus = range.indexOf('-');
                try {
                    if (minus > 0) {
                        startFrom = Long.parseLong(range.substring(0, minus));
                        endAt = Long.parseLong(range.substring(minus + 1));
                    }
                } catch (NumberFormatException ignored) {
                }
            }
        }
        // get if-range header. If present, it must match etag or else we
        // should ignore the range request
        String ifRange = header.get("if-range");
        boolean headerIfRangeMissingOrMatching = (ifRange == null || etag.equals(ifRange));
        String ifNoneMatch = header.get("if-none-match");
        boolean headerIfNoneMatchPresentAndMatching = ifNoneMatch != null && ("*".equals(ifNoneMatch) || ifNoneMatch.equals(etag));
        // Change return code and add Content-Range header when skipping is
        // requested
        long fileLen = file.length();
        if (headerIfRangeMissingOrMatching && range != null && startFrom >= 0 && startFrom < fileLen) {
            // and the startFrom of the range is satisfiable
            if (headerIfNoneMatchPresentAndMatching) {
                // range request that matches current etag
                // and the startFrom of the range is satisfiable
                // would return range from file
                // respond with not-modified
                res = newFixedLengthResponse(Status.NOT_MODIFIED, mime, "");
                res.addHeader("ETag", etag);
            } else {
                if (endAt < 0) {
                    endAt = fileLen - 1;
                }
                long newLen = endAt - startFrom + 1;
                if (newLen < 0) {
                    newLen = 0;
                }
                FileInputStream fis = new FileInputStream(file);
                fis.skip(startFrom);
                res = Response.newFixedLengthResponse(Status.PARTIAL_CONTENT, mime, fis, newLen);
                res.addHeader("Accept-Ranges", "bytes");
                res.addHeader("Content-Length", "" + newLen);
                res.addHeader("Content-Range", "bytes " + startFrom + "-" + endAt + "/" + fileLen);
                res.addHeader("ETag", etag);
            }
        } else {
            if (headerIfRangeMissingOrMatching && range != null && startFrom >= fileLen) {
                // return the size of the file
                // 4xx responses are not trumped by if-none-match
                res = newFixedLengthResponse(Status.RANGE_NOT_SATISFIABLE, NanoHTTPD.MIME_PLAINTEXT, "");
                res.addHeader("Content-Range", "bytes */" + fileLen);
                res.addHeader("ETag", etag);
            } else if (range == null && headerIfNoneMatchPresentAndMatching) {
                // full-file-fetch request
                // would return entire file
                // respond with not-modified
                res = newFixedLengthResponse(Status.NOT_MODIFIED, mime, "");
                res.addHeader("ETag", etag);
            } else if (!headerIfRangeMissingOrMatching && headerIfNoneMatchPresentAndMatching) {
                // range request that doesn't match current etag
                // would return entire (different) file
                // respond with not-modified
                res = newFixedLengthResponse(Status.NOT_MODIFIED, mime, "");
                res.addHeader("ETag", etag);
            } else {
                // supply the file
                res = newFixedFileResponse(file, mime);
                res.addHeader("Content-Length", "" + fileLen);
                res.addHeader("ETag", etag);
            }
        }
    } catch (IOException ioe) {
        res = getForbiddenResponse("Reading file failed.");
    }
    return res;
}
Also used : Response(org.nanohttpd.protocols.http.response.Response) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream)

Example 5 with Response

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

the class SimpleWebServer method newFixedLengthResponse.

public static Response newFixedLengthResponse(IStatus status, String mimeType, String message) {
    Response response = Response.newFixedLengthResponse(status, mimeType, message);
    response.addHeader("Accept-Ranges", "bytes");
    return response;
}
Also used : Response(org.nanohttpd.protocols.http.response.Response)

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