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

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

Introduction

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

Prototype

HttpResponseStatus NOT_MODIFIED

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

Click Source Link

Document

304 Not Modified

Usage

From source file:com.barchart.netty.server.http.handlers.StaticResourceHandler.java

License:BSD License

private boolean handleCache(final HttpServerRequest request, final Resource resource) {

    // Cache-Control: no-cache
    if (request.headers().contains(HttpHeaders.Names.CACHE_CONTROL)
            && request.headers().get(HttpHeaders.Names.CACHE_CONTROL).equals(HttpHeaders.Values.NO_CACHE)) {
        return false;
    }//from ww  w . java 2  s . com

    // If-Modified-Since: <date>
    if (request.headers().contains(HttpHeaders.Names.IF_MODIFIED_SINCE)) {

        try {

            final Date cached = HttpHeaders.getDateHeader(request, HttpHeaders.Names.IF_MODIFIED_SINCE);

            if (cached.getTime() >= resource.modified()) {
                // Cache is good, return 304
                request.response().setStatus(HttpResponseStatus.NOT_MODIFIED);
                request.response().setContentLength(0);
                return true;
            }

        } catch (final ParseException e) {
            // Bad date header
        }

    }

    // Send resource
    return false;

}

From source file:com.bloom.zerofs.rest.NettyResponseChannel.java

License:Open Source License

/**
 * Converts a {@link ResponseStatus} into a {@link HttpResponseStatus}.
 * @param responseStatus {@link ResponseStatus} that needs to be mapped to a {@link HttpResponseStatus}.
 * @return the {@link HttpResponseStatus} that maps to the {@link ResponseStatus}.
 *//*from   w  w w .ja v a2s . co  m*/
private HttpResponseStatus getHttpResponseStatus(ResponseStatus responseStatus) {
    HttpResponseStatus status;
    switch (responseStatus) {
    case Ok:
        status = HttpResponseStatus.OK;
        break;
    case Created:
        status = HttpResponseStatus.CREATED;
        break;
    case Accepted:
        status = HttpResponseStatus.ACCEPTED;
        break;
    case NotModified:
        status = HttpResponseStatus.NOT_MODIFIED;
        break;
    case BadRequest:
        nettyMetrics.badRequestCount.inc();
        status = HttpResponseStatus.BAD_REQUEST;
        break;
    case Unauthorized:
        nettyMetrics.unauthorizedCount.inc();
        status = HttpResponseStatus.UNAUTHORIZED;
        break;
    case NotFound:
        nettyMetrics.notFoundCount.inc();
        status = HttpResponseStatus.NOT_FOUND;
        break;
    case Gone:
        nettyMetrics.goneCount.inc();
        status = HttpResponseStatus.GONE;
        break;
    case Forbidden:
        nettyMetrics.forbiddenCount.inc();
        status = HttpResponseStatus.FORBIDDEN;
        break;
    case ProxyAuthenticationRequired:
        nettyMetrics.proxyAuthRequiredCount.inc();
        status = HttpResponseStatus.PROXY_AUTHENTICATION_REQUIRED;
        break;
    case InternalServerError:
        nettyMetrics.internalServerErrorCount.inc();
        status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
        break;
    default:
        nettyMetrics.unknownResponseStatusCount.inc();
        status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
        break;
    }
    return status;
}

From source file:com.corundumstudio.socketio.handler.ResourceHandler.java

License:Apache License

private void sendNotModified(ChannelHandlerContext ctx) {
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.NOT_MODIFIED);
    setDateHeader(response);/*  w w w  .ja v a 2s .  c o  m*/

    // Close the connection as soon as the error message is sent.
    ctx.channel().write(response).addListener(ChannelFutureListener.CLOSE);
}

From source file:com.github.ambry.frontend.FrontendIntegrationTest.java

License:Open Source License

/**
 * Gets the blob with blob ID {@code blobId} and verifies that the blob is not returned as blob is not modified
 * @param blobId the blob ID of the blob to GET.
 * @throws Exception/*from   w  ww. j  a va2 s  .c o m*/
 */
private void getNotModifiedBlobAndVerify(String blobId) throws Exception {
    HttpHeaders headers = new DefaultHttpHeaders();
    headers.add(RestUtils.Headers.IF_MODIFIED_SINCE, new Date());
    FullHttpRequest httpRequest = buildRequest(HttpMethod.GET, blobId, headers, null);
    Queue<HttpObject> responseParts = nettyClient.sendRequest(httpRequest, null, null).get();
    HttpResponse response = (HttpResponse) responseParts.poll();
    assertEquals("Unexpected response status", HttpResponseStatus.NOT_MODIFIED, response.getStatus());
    assertTrue("No Date header", response.headers().get(RestUtils.Headers.DATE) != null);
    assertNull("No Last-Modified header expected", response.headers().get("Last-Modified"));
    assertNull(RestUtils.Headers.BLOB_SIZE + " should have been null ",
            response.headers().get(RestUtils.Headers.BLOB_SIZE));
    assertNull("Content-Type should have been null", response.headers().get(RestUtils.Headers.CONTENT_TYPE));
    assertNoContent(responseParts);
}

From source file:com.linecorp.armeria.server.http.file.HttpFileServiceInvocationHandler.java

License:Apache License

@Override
public void invoke(ServiceInvocationContext ctx, Executor blockingTaskExecutor, Promise<Object> promise)
        throws Exception {

    final HttpRequest req = ctx.originalRequest();
    if (req.method() != HttpMethod.GET) {
        respond(ctx, promise, HttpResponseStatus.METHOD_NOT_ALLOWED, 0, ERROR_MIME_TYPE,
                Unpooled.wrappedBuffer(CONTENT_METHOD_NOT_ALLOWED));
        return;/* w  w w .j a  v a2  s.  com*/
    }

    final String path = normalizePath(ctx.mappedPath());
    if (path == null) {
        respond(ctx, promise, HttpResponseStatus.NOT_FOUND, 0, ERROR_MIME_TYPE,
                Unpooled.wrappedBuffer(CONTENT_NOT_FOUND));
        return;
    }

    Entry entry = getEntry(path);
    long lastModifiedMillis;
    if ((lastModifiedMillis = entry.lastModifiedMillis()) == 0) {
        boolean found = false;
        if (path.charAt(path.length() - 1) == '/') {
            // Try index.html if it was a directory access.
            entry = getEntry(path + "index.html");
            if ((lastModifiedMillis = entry.lastModifiedMillis()) != 0) {
                found = true;
            }
        }

        if (!found) {
            respond(ctx, promise, HttpResponseStatus.NOT_FOUND, 0, ERROR_MIME_TYPE,
                    Unpooled.wrappedBuffer(CONTENT_NOT_FOUND));
            return;
        }
    }

    long ifModifiedSinceMillis = Long.MIN_VALUE;
    try {
        ifModifiedSinceMillis = req.headers().getTimeMillis(HttpHeaderNames.IF_MODIFIED_SINCE, Long.MIN_VALUE);
    } catch (Exception e) {
        // Ignore the ParseException, which is raised on malformed date.
        //noinspection ConstantConditions
        if (!(e instanceof ParseException)) {
            throw e;
        }
    }

    // HTTP-date does not have subsecond-precision; add 999ms to it.
    if (ifModifiedSinceMillis > Long.MAX_VALUE - 999) {
        ifModifiedSinceMillis = Long.MAX_VALUE;
    } else {
        ifModifiedSinceMillis += 999;
    }

    if (lastModifiedMillis < ifModifiedSinceMillis) {
        respond(ctx, promise, HttpResponseStatus.NOT_MODIFIED, lastModifiedMillis, entry.mimeType(),
                Unpooled.EMPTY_BUFFER);
        return;
    }

    respond(ctx, promise, HttpResponseStatus.OK, lastModifiedMillis, entry.mimeType(),
            entry.readContent(ctx.alloc()));
}

From source file:com.mastfrog.acteur.CheckIfNoneMatchHeader.java

@Inject
CheckIfNoneMatchHeader(HttpEvent event, Page page) throws Exception {
    Checks.notNull("event", event);
    Checks.notNull("page", page);
    String etag = event.getHeader(Headers.IF_NONE_MATCH);
    String pageEtag = page.getResponseHeaders().getETag();
    if (etag != null && pageEtag != null) {
        if (etag.equals(pageEtag)) {
            setState(new RespondWith(HttpResponseStatus.NOT_MODIFIED));
            // XXX workaround for peculiar problem with FileResource =
            // not modified responses are leaving a hanging connection
            setResponseBodyWriter(ChannelFutureListener.CLOSE);
            return;
        }//from w w w.  ja v  a 2s  .  com
    }
    setState(new ConsumedState());
}

From source file:com.sangupta.swift.netty.NettyUtils.java

License:Apache License

/**
 * When file timestamp is the same as what the browser is sending up, send a
 * "304 Not Modified"//from  w w w .j  av a  2  s . c  o  m
 *
 * @param ctx
 *            Context
 */
public static void sendNotModified(ChannelHandlerContext ctx) {
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
            HttpResponseStatus.NOT_MODIFIED);
    setDateHeader(response);

    // Close the connection as soon as the error message is sent.
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}

From source file:com.thesoftwarefactory.vertx.web.mvc.ActionResult.java

License:Apache License

public static HttpStatusCodeResult notModified() {
    return new HttpStatusCodeResultImpl(HttpResponseStatus.NOT_MODIFIED);
}

From source file:gribbit.http.response.exception.NotModifiedException.java

License:Open Source License

public NotModifiedException() {
    super(HttpResponseStatus.NOT_MODIFIED);
}

From source file:gribbit.http.response.Response.java

License:Open Source License

protected void sendHeaders(ChannelHandlerContext ctx) {

    // Set general headers ---------------------------------------------------------------------------------------

    DefaultHttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status);
    HttpHeaders headers = httpResponse.headers();
    headers.add(SERVER, SERVER_IDENTIFIER);

    // Date header uses server time, and should use the same clock as Expires and Last-Modified
    headers.add(DATE, dateTimeFormatter.format(timeNow));

    // Add an Accept-Encoding: gzip header to the response to let the client know that in future
    // it can send compressed requests. (This header is probably ignored by most clients, because
    // on initial request they don't know yet if the server can accept compressed content, but
    // there must be clients out there that look for this header and compress content on the
    // second and subsequent requests? See http://stackoverflow.com/a/1450163/3950982 )
    headers.add(ACCEPT_ENCODING, "gzip");

    // Set HTTP2 stream ID in response if present in request
    if (request.getStreamId() != null) {
        headers.add(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), request.getStreamId());
    }//  w w w.  j  a  v  a 2  s. c  o  m

    if (keepAlive) {
        headers.add(CONNECTION, KEEP_ALIVE);
    }

    if (customHeaders != null) {
        for (CustomHeader c : customHeaders) {
            httpResponse.headers().add(c.key, c.value);
        }
    }

    // Set cookies in the response
    if (cookies != null) {
        for (String cookieStr : ServerCookieEncoder.STRICT.encode(cookies.values())) {
            headers.add(SET_COOKIE, cookieStr);
        }
    }

    // Set cache headers ---------------------------------------------------------------------------------------

    boolean cached = false;
    if (status == HttpResponseStatus.OK) {
        // Set caching headers -- see:
        // http://www.mobify.com/blog/beginners-guide-to-http-cache-headers/
        // https://www.mnot.net/cache_docs/

        // Last-Modified is used to determine whether a Not Modified response should be returned on next request.
        // RouteHandlers that want to make use of this value should check the return value of
        // request.cachedVersionIsOlderThan(serverTimestamp), where serverTimestamp was the timestamp at which
        // the value previously changed, and if the return value is false, throw NotModifiedException.
        if (lastModifiedEpochSeconds > 0L) {
            headers.add(LAST_MODIFIED, dateTimeFormatter
                    .format(ZonedDateTime.ofInstant(Instant.ofEpochSecond(lastModifiedEpochSeconds), UTC)));
        }

        //            if (request.isHashURL() && maxAgeSeconds != 0L) {
        //                // TODO: Move cache busting code out of http package
        //
        //                // Treat negative maxAgeSeconds as "cache forever" (according to spec, max is 1 year). 
        //                long maxAge = maxAgeSeconds < 0 ? ONE_YEAR_IN_SECONDS : maxAgeSeconds;
        //
        //                // Only URLs that include a hash key (and whose response has a non-zero maxAgeSeconds) can be cached.
        //                // N.B. can set "Cache-Control: public", since the resource is hashed, so it can be served to other
        //                // clients that request it (they would have to know the hash URL to request it in the first place).
        //                headers.add(CACHE_CONTROL, "public, max-age=" + maxAge);
        //                headers.add(EXPIRES, dateTimeFormatter.format(timeNow.plusSeconds(maxAge)));
        //                headers.add(ETAG, request.getURLHashKey());
        //                cached = true;
        //            }

    } else if (this.getStatus() == HttpResponseStatus.NOT_MODIFIED) {
        // For NOT_MODIFIED, need to return the same last modified time as was passed in the request
        if (request != null && request.getIfModifiedSince() != null) {
            headers.add(LAST_MODIFIED, request.getIfModifiedSince());
        }
        cached = true;

    } else if (this.getStatus() == HttpResponseStatus.NOT_FOUND) {
        // Cache 404 messages for 5 minutes to reduce server load
        int cacheTime = 60 * 5;
        headers.add(CACHE_CONTROL, "max-age=" + cacheTime);
        headers.add(EXPIRES, dateTimeFormatter.format(timeNow.plusSeconds(cacheTime)));
        cached = true;
    }

    if (!cached) {
        // Disable caching for all URLs that do not contain a hash key. In particular, caching is
        // disabled for error messages, resources that don't have a last modified time, and responses
        // from RouteHandlers that do not set a maxAge (and are therefore not hashed).

        // This is the minimum necessary set of headers for disabling caching, see http://goo.gl/yXGd2x
        headers.add(CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // HTTP 1.1
        headers.add(PRAGMA, "no-cache"); // HTTP 1.0
        headers.add(EXPIRES, "0"); // Proxies
    }

    // Set content headers -------------------------------------------------------------------------------------

    headers.add(CONTENT_TYPE, contentType != null ? contentType : "application/octet-stream");
    if (isChunked) {
        // "Transfer-Encoding: chunked" is used in place of "Content-Length" header
        headers.add(TRANSFER_ENCODING, CHUNKED);
    } else {
        if (contentLength >= 0) {
            headers.add(CONTENT_LENGTH, Long.toString(contentLength));
        }
    }

    // This header is only typically for .svgz files, which are supposed to be served with a content type of
    // "image/svg+xml" but with a "Content-Encoding: gzip" header. For auto-compressed content, this header
    // will be added automatically by HttpContentCompressor (below).
    if (contentEncodingGzip) {
        headers.add(CONTENT_ENCODING, GZIP);
    }

    // Dynamically add compression for the response content if necessary ---------------------------------------

    // TODO: compression is disabled for now, see: http://andreas.haufler.info/2014/01/making-http-content-compression-work-in.html
    //        if (request.acceptEncodingGzip() && (isChunked || contentLength > 0)
    //                && ContentTypeUtils.isCompressibleContentType(contentType)) {
    //            ctx.pipeline().addBefore(HttpRequestDecoder.NAME_IN_PIPELINE, "HttpContentCompressor",
    //                    new HttpContentCompressor(1));
    //        }

    // Send headers --------------------------------------------------------------------------------------------

    ctx.write(httpResponse);
}