Example usage for io.netty.handler.codec.http HttpResponseStatus REQUESTED_RANGE_NOT_SATISFIABLE

List of usage examples for io.netty.handler.codec.http HttpResponseStatus REQUESTED_RANGE_NOT_SATISFIABLE

Introduction

In this page you can find the example usage for io.netty.handler.codec.http HttpResponseStatus REQUESTED_RANGE_NOT_SATISFIABLE.

Prototype

HttpResponseStatus REQUESTED_RANGE_NOT_SATISFIABLE

To view the source code for io.netty.handler.codec.http HttpResponseStatus REQUESTED_RANGE_NOT_SATISFIABLE.

Click Source Link

Document

416 Requested Range Not Satisfiable

Usage

From source file:com.mastfrog.netty.http.client.ResponseHandler.java

License:Open Source License

protected void internalReceive(HttpResponseStatus status, HttpHeaders headers, ByteBuf content) {
    try {/*from   w w  w . jav  a2  s  .  com*/
        if (status.code() > 399) {
            byte[] b = new byte[content.readableBytes()];
            content.readBytes(b);
            onErrorResponse(status, headers, new String(b, CharsetUtil.UTF_8));
            return;
        }
        if (type == ByteBuf.class) {
            _doReceive(status, headers, type.cast(content));
        } else if (type == String.class || type == CharSequence.class) {
            byte[] b = new byte[content.readableBytes()];
            content.readBytes(b);
            _doReceive(status, headers, type.cast(new String(b, CharsetUtil.UTF_8)));
        } else if (type == byte[].class) {
            byte[] b = new byte[content.readableBytes()];
            content.readBytes(b);
            _doReceive(status, headers, type.cast(b));
        } else {
            byte[] b = new byte[content.readableBytes()];
            content.readBytes(b);
            try {
                Object o = mapper.readValue(b, type);
                _doReceive(status, headers, type.cast(o));
            } catch (JsonParseException ex) {
                content.resetReaderIndex();
                try {
                    String s = Streams.readString(new ByteBufInputStream(content), "UTF-8");
                    onErrorResponse(HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE, headers, s);
                } catch (IOException ex1) {
                    Exceptions.chuck(ex1);
                }
            } catch (Exception ex) {
                Exceptions.chuck(ex);
            }
        }
    } finally {
        latch.countDown();
    }
}

From source file:io.crate.protocols.http.HttpBlobHandler.java

License:Apache License

private void partialContentResponse(String range, HttpRequest request, String index, final String digest)
        throws IOException {
    assert range != null : "Getting partial response but no byte-range is not present.";
    Matcher matcher = CONTENT_RANGE_PATTERN.matcher(range);
    if (!matcher.matches()) {
        LOGGER.warn("Invalid byte-range: {}; returning full content", range);
        fullContentResponse(request, index, digest);
        return;/*from ww  w  . j a  va 2 s . c  o m*/
    }
    BlobShard blobShard = localBlobShard(index, digest);

    final RandomAccessFile raf = blobShard.blobContainer().getRandomAccessFile(digest);
    long start;
    long end;
    try {
        try {
            start = Long.parseLong(matcher.group(1));
            if (start > raf.length()) {
                LOGGER.warn("416 Requested Range not satisfiable");
                simpleResponse(HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE);
                raf.close();
                return;
            }
            end = raf.length() - 1;
            if (!matcher.group(2).equals("")) {
                end = Long.parseLong(matcher.group(2));
            }
        } catch (NumberFormatException ex) {
            LOGGER.error("Couldn't parse Range Header", ex);
            start = 0;
            end = raf.length();
        }

        DefaultHttpResponse response = new DefaultHttpResponse(HTTP_1_1, PARTIAL_CONTENT);
        maybeSetConnectionCloseHeader(response);
        HttpUtil.setContentLength(response, end - start + 1);
        response.headers().set(HttpHeaderNames.CONTENT_RANGE,
                "bytes " + start + "-" + end + "/" + raf.length());
        setDefaultGetHeaders(response);

        ctx.channel().write(response);
        ChannelFuture writeFuture = transferFile(digest, raf, start, end - start + 1);
        if (!HttpUtil.isKeepAlive(request)) {
            writeFuture.addListener(ChannelFutureListener.CLOSE);
        }
    } catch (Throwable t) {
        /*
         * Make sure RandomAccessFile is closed when exception is raised.
         * In case of success, the ChannelFutureListener in "transferFile" will take care
         * that the resources are released.
         */
        raf.close();
        throw t;
    }
}

From source file:org.restnext.server.ServerHandler.java

License:Apache License

private HttpResponseStatus fromStatus(Response.Status status) {
    switch (status) {
    case OK:/*from w  ww.j  av  a  2s . c  o m*/
        return HttpResponseStatus.OK;
    case CREATED:
        return HttpResponseStatus.CREATED;
    case ACCEPTED:
        return HttpResponseStatus.ACCEPTED;
    case NO_CONTENT:
        return HttpResponseStatus.NO_CONTENT;
    case RESET_CONTENT:
        return HttpResponseStatus.RESET_CONTENT;
    case PARTIAL_CONTENT:
        return HttpResponseStatus.PARTIAL_CONTENT;
    case MOVED_PERMANENTLY:
        return HttpResponseStatus.MOVED_PERMANENTLY;
    case FOUND:
        return HttpResponseStatus.FOUND;
    case SEE_OTHER:
        return HttpResponseStatus.SEE_OTHER;
    case NOT_MODIFIED:
        return HttpResponseStatus.NOT_MODIFIED;
    case USE_PROXY:
        return HttpResponseStatus.USE_PROXY;
    case TEMPORARY_REDIRECT:
        return HttpResponseStatus.TEMPORARY_REDIRECT;
    case BAD_REQUEST:
        return HttpResponseStatus.BAD_REQUEST;
    case UNAUTHORIZED:
        return HttpResponseStatus.UNAUTHORIZED;
    case PAYMENT_REQUIRED:
        return HttpResponseStatus.PAYMENT_REQUIRED;
    case FORBIDDEN:
        return HttpResponseStatus.FORBIDDEN;
    case NOT_FOUND:
        return HttpResponseStatus.NOT_FOUND;
    case METHOD_NOT_ALLOWED:
        return HttpResponseStatus.METHOD_NOT_ALLOWED;
    case NOT_ACCEPTABLE:
        return HttpResponseStatus.NOT_ACCEPTABLE;
    case PROXY_AUTHENTICATION_REQUIRED:
        return HttpResponseStatus.PROXY_AUTHENTICATION_REQUIRED;
    case REQUEST_TIMEOUT:
        return HttpResponseStatus.REQUEST_TIMEOUT;
    case CONFLICT:
        return HttpResponseStatus.CONFLICT;
    case GONE:
        return HttpResponseStatus.GONE;
    case LENGTH_REQUIRED:
        return HttpResponseStatus.LENGTH_REQUIRED;
    case PRECONDITION_FAILED:
        return HttpResponseStatus.PRECONDITION_FAILED;
    case REQUEST_ENTITY_TOO_LARGE:
        return HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE;
    case REQUEST_URI_TOO_LONG:
        return HttpResponseStatus.REQUEST_URI_TOO_LONG;
    case UNSUPPORTED_MEDIA_TYPE:
        return HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE;
    case REQUESTED_RANGE_NOT_SATISFIABLE:
        return HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE;
    case EXPECTATION_FAILED:
        return HttpResponseStatus.EXPECTATION_FAILED;
    case INTERNAL_SERVER_ERROR:
        return HttpResponseStatus.INTERNAL_SERVER_ERROR;
    case NOT_IMPLEMENTED:
        return HttpResponseStatus.NOT_IMPLEMENTED;
    case BAD_GATEWAY:
        return HttpResponseStatus.BAD_GATEWAY;
    case SERVICE_UNAVAILABLE:
        return HttpResponseStatus.SERVICE_UNAVAILABLE;
    case GATEWAY_TIMEOUT:
        return HttpResponseStatus.GATEWAY_TIMEOUT;
    case HTTP_VERSION_NOT_SUPPORTED:
        return HttpResponseStatus.HTTP_VERSION_NOT_SUPPORTED;
    case CONTINUE:
        return HttpResponseStatus.CONTINUE;
    default:
        throw new RuntimeException(String.format("Status: %s not supported", status));
    }
}

From source file:org.robotbrains.support.web.server.netty.NettyStaticContentHandler.java

License:Apache License

@Override
public void handleWebRequest(ChannelHandlerContext ctx, HttpRequest request, Set<HttpCookie> cookiesToAdd)
        throws IOException {
    String url = request.getUri();
    String originalUrl = url;//from   www .j  a  va 2 s . c o  m

    // Strip off query parameters, if any, as we don't care.
    int pos = url.indexOf('?');
    if (pos != -1) {
        url = url.substring(0, pos);
    }

    int luriPrefixLength = uriPrefix.length();
    String filepath = URLDecoder.decode(url.substring(url.indexOf(uriPrefix) + luriPrefixLength),
            StandardCharsets.UTF_8.name());

    File file = new File(baseDir, filepath);

    // Refuse to process if the path wanders outside of the base directory.
    if (!allowLinks && !fileSupport.isParent(baseDir, file)) {
        HttpResponseStatus status = HttpResponseStatus.FORBIDDEN;
        parentHandler.getWebServer().getLog().warn(String.format(
                "HTTP [%s] %s --> (Path attempts to leave base directory)", status.code(), originalUrl));
        parentHandler.sendError(ctx, status);
        return;
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException fnfe) {
        if (fallbackHandler != null) {
            fallbackHandler.handleWebRequest(ctx, request, cookiesToAdd);
        } else {
            HttpResponseStatus status = HttpResponseStatus.NOT_FOUND;
            parentHandler.getWebServer().getLog()
                    .warn(String.format("HTTP [%s] %s --> (File Not Found)", status.code(), originalUrl));
            parentHandler.sendError(ctx, status);
        }
        return;
    }
    long fileLength = raf.length();

    // Start with an initial OK response which will be modified as needed.
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK);

    setMimeType(filepath, response);

    parentHandler.addHttpResponseHeaders(response, extraHttpContentHeaders);
    parentHandler.addHeaderIfNotExists(response, HttpHeaders.Names.ACCEPT_RANGES, HttpHeaders.Values.BYTES);

    if (cookiesToAdd != null) {

        addHeader(response, HttpHeaders.Names.SET_COOKIE, ServerCookieEncoder.STRICT
                .encode(Collections2.transform(cookiesToAdd, new Function<HttpCookie, Cookie>() {
                    @Override
                    public Cookie apply(HttpCookie cookie) {
                        return NettyHttpResponse.createNettyCookie(cookie);
                    }
                })));
    }

    RangeRequest rangeRequest = null;
    try {
        rangeRequest = parseRangeRequest(request, fileLength);
    } catch (Exception e) {
        try {
            HttpResponseStatus status = HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE;
            parentHandler.getWebServer().getLog()
                    .error(String.format("[%s] HTTP %s --> %s", status.code(), originalUrl, e.getMessage()));
            response.setStatus(status);
            parentHandler.sendError(ctx, status);
        } finally {
            try {
                raf.close();
            } catch (Exception e1) {
                parentHandler.getWebServer().getLog().warn("Unable to close static content file", e1);
            }
        }
        return;
    }

    HttpResponseStatus status = HttpResponseStatus.OK;
    if (rangeRequest == null) {
        setContentLength(response, fileLength);
    } else {
        setContentLength(response, rangeRequest.getRangeLength());
        addHeader(response, HttpHeaders.Names.CONTENT_RANGE,
                CONTENT_RANGE_PREFIX + rangeRequest.begin + CONTENT_RANGE_RANGE_SEPARATOR + rangeRequest.end
                        + CONTENT_RANGE_RANGE_SIZE_SEPARATOR + fileLength);
        status = HttpResponseStatus.PARTIAL_CONTENT;
        response.setStatus(status);
    }

    Channel ch = ctx.channel();

    // Write the initial line and the header.
    ChannelFuture writeFuture = ch.write(response);

    // Write the content if there have been no errors and we are a GET request.
    if (HttpMethod.GET == request.getMethod()) {
        if (ch.pipeline().get(SslHandler.class) != null) {
            // Cannot use zero-copy with HTTPS.
            writeFuture = ch.write(new ChunkedFile(raf, 0, fileLength, COPY_CHUNK_SIZE));
        } else {
            // No encryption - use zero-copy.
            final FileRegion region = new DefaultFileRegion(raf.getChannel(),
                    rangeRequest != null ? rangeRequest.begin : 0,
                    rangeRequest != null ? rangeRequest.getRangeLength() : fileLength);
            writeFuture = ch.write(region);
            writeFuture.addListener(new ChannelProgressiveFutureListener() {
                @Override
                public void operationComplete(ChannelProgressiveFuture future) throws Exception {
                    region.release();
                }

                @Override
                public void operationProgressed(ChannelProgressiveFuture future, long progress, long total)
                        throws Exception {
                    // Do nothng
                }
            });
        }
    }

    // Decide whether to close the connection or not.
    if (!isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        writeFuture.addListener(ChannelFutureListener.CLOSE);
    }

    parentHandler.getWebServer().getLog()
            .trace(String.format("[%s] HTTP %s --> %s", status.code(), originalUrl, file.getPath()));
}