Example usage for io.netty.handler.codec.http.cookie ServerCookieEncoder STRICT

List of usage examples for io.netty.handler.codec.http.cookie ServerCookieEncoder STRICT

Introduction

In this page you can find the example usage for io.netty.handler.codec.http.cookie ServerCookieEncoder STRICT.

Prototype

ServerCookieEncoder STRICT

To view the source code for io.netty.handler.codec.http.cookie ServerCookieEncoder STRICT.

Click Source Link

Document

Strict encoder that validates that name and value chars are in the valid scope defined in RFC6265, and (for methods that accept multiple cookies) that only one cookie is encoded with any given name.

Usage

From source file:com.bay1ts.bay.core.Response.java

License:Apache License

/**
 * Adds cookie to the response. Can be invoked multiple times to insert more than one cookie.
 *
 * @param path     path of the cookie//  w w w.  j ava  2s. c om
 * @param name     name of the cookie
 * @param value    value of the cookie
 * @param maxAge   max age of the cookie in seconds (negative for the not persistent cookie, zero - deletes the cookie)
 * @param secured  if true : cookie will be secured
 * @param httpOnly if true: cookie will be marked as http only
 */
public void cookie(String path, String name, String value, int maxAge, boolean secured, boolean httpOnly) {
    Cookie cookie = new DefaultCookie(name, value);
    cookie.setPath(path);
    cookie.setMaxAge(maxAge);
    cookie.setSecure(secured);
    cookie.setHttpOnly(httpOnly);
    response.headers().set(HttpHeaderNames.COOKIE, ServerCookieEncoder.STRICT.encode(cookie));
}

From source file:com.bunjlabs.fuga.network.netty.NettyHttpServerHandler.java

License:Apache License

private void writeResponse(ChannelHandlerContext ctx, Request request, Response response) {
    HttpResponse httpresponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            HttpResponseStatus.valueOf(response.status()));

    httpresponse.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
    httpresponse.headers().set(HttpHeaderNames.CONTENT_TYPE, response.contentType());

    // Disable cache by default
    httpresponse.headers().set(HttpHeaderNames.CACHE_CONTROL, "no-cache, no-store, must-revalidate, max-age=0");
    httpresponse.headers().set(HttpHeaderNames.PRAGMA, "no-cache");
    httpresponse.headers().set(HttpHeaderNames.EXPIRES, "0");

    response.headers().entrySet().stream().forEach((e) -> httpresponse.headers().set(e.getKey(), e.getValue()));

    httpresponse.headers().set(HttpHeaderNames.SERVER, "Fuga Netty Web Server/" + serverVersion);

    // Set cookies
    httpresponse.headers().set(HttpHeaderNames.SET_COOKIE,
            ServerCookieEncoder.STRICT.encode(NettyCookieConverter.convertListToNetty(response.cookies())));

    if (response.length() >= 0) {
        httpresponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.length());
    }/*from   w w  w.  ja v a  2  s.com*/

    if (HttpUtil.isKeepAlive(httprequest)) {
        httpresponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    } else {
        httpresponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
    }

    ctx.write(httpresponse);

    if (response.stream() != null) {
        ctx.write(new HttpChunkedInput(new ChunkedStream(response.stream())));
    }

    LastHttpContent fs = new DefaultLastHttpContent();
    ChannelFuture sendContentFuture = ctx.writeAndFlush(fs);
    if (!HttpUtil.isKeepAlive(httprequest)) {
        sendContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.cmz.http.snoop.HttpSnoopServerHandler.java

License:Apache License

private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) {
    // Decide whether to close the connection or not.
    boolean keepAlive = HttpUtil.isKeepAlive(request);
    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,
            currentObj.decoderResult().isSuccess() ? OK : BAD_REQUEST,
            Unpooled.copiedBuffer(buf.toString(), CharsetUtil.UTF_8));

    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");

    if (keepAlive) {
        // Add 'Content-Length' header only for a keep-alive connection.
        response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
        // Add keep alive header as per:
        // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
        response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }/*from   w  w  w. j a  v a  2 s  . c  om*/

    // Encode the cookie.
    String cookieString = request.headers().get(HttpHeaderNames.COOKIE);
    if (cookieString != null) {
        Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(cookieString);
        if (!cookies.isEmpty()) {
            // Reset the cookies if necessary.
            for (Cookie cookie : cookies) {
                response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie));
            }
        }
    } else {
        // Browser sent no cookie.  Add some.
        response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode("key1", "value1"));
        response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode("key2", "value2"));
    }

    // Write the response.
    ctx.write(response);

    return keepAlive;
}

From source file:com.cmz.http.upload.HttpUploadServerHandler.java

License:Apache License

private void writeResponse(Channel channel) {
    // Convert the response content to a ChannelBuffer.
    ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8);
    responseContent.setLength(0);/*from   w  w w  .  jav a  2 s  .co m*/

    // Decide whether to close the connection or not.
    boolean close = request.headers().contains(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE, true)
            || request.protocolVersion().equals(HttpVersion.HTTP_1_0) && !request.headers()
                    .contains(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE, true);

    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");

    if (!close) {
        // There's no need to add 'Content-Length' header
        // if this is the last response.
        response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes());
    }

    Set<Cookie> cookies;
    String value = request.headers().get(HttpHeaderNames.COOKIE);
    if (value == null) {
        cookies = Collections.emptySet();
    } else {
        cookies = ServerCookieDecoder.STRICT.decode(value);
    }
    if (!cookies.isEmpty()) {
        // Reset the cookies if necessary.
        for (Cookie cookie : cookies) {
            response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie));
        }
    }
    // Write the response.
    ChannelFuture future = channel.writeAndFlush(response);
    // Close the connection after the write operation is done if necessary.
    if (close) {
        future.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.nextcont.ecm.fileengine.http.nettyServer.HttpUploadServerHandler.java

License:Apache License

private void writeResponse(Channel channel) {
    logger.info("writeResponse ...");
    // Convert the response content to a ChannelBuffer.
    ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8);
    responseContent.setLength(0);//from w w  w.java2  s. co m

    // Decide whether to close the connection or not.
    boolean close = HttpHeaders.Values.CLOSE.equalsIgnoreCase(request.headers().get(CONNECTION))
            || request.getProtocolVersion().equals(HttpVersion.HTTP_1_0)
                    && !HttpHeaders.Values.KEEP_ALIVE.equalsIgnoreCase(request.headers().get(CONNECTION));

    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, buf);

    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");

    if (!close) {
        // There's no need to add 'Content-Length' header
        // if this is the last response.
        response.headers().set(CONTENT_LENGTH, buf.readableBytes());
    }

    Set<Cookie> cookies;
    String value = request.headers().get(COOKIE);
    if (value == null) {
        cookies = Collections.emptySet();
    } else {
        //            cookies = CookieDecoder.decode(value);
        cookies = ServerCookieDecoder.STRICT.decode(value);
    }
    if (!cookies.isEmpty()) {
        // Reset the cookies if necessary.
        for (Cookie cookie : cookies) {
            //                response.headers().add(SET_COOKIE, ServerCookieEncoder.encode(cookie));
            response.headers().add(HttpHeaders.Names.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie));
        }
    }
    // Write the response.
    ChannelFuture future = channel.writeAndFlush(response);
    // Close the connection after the write operation is done if necessary.
    if (close) {
        future.addListener(ChannelFutureListener.CLOSE);
    }
}

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());
    }//from  w w w  . ja va  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);
}

From source file:io.nebo.container.NettyHttpServletResponse.java

License:Apache License

/**
 * Get a Netty {@link io.netty.handler.codec.http.HttpResponse}, committing the {@link javax.servlet.http.HttpServletResponse}.
 *//*  w w  w  .j a va 2s.  c o m*/
public HttpResponse getNettyResponse() {
    if (committed) {
        return response;
    }
    committed = true;
    HttpHeaders headers = response.headers();
    if (null != contentType) {
        String value = null == characterEncoding ? contentType : contentType + "; charset=" + characterEncoding;
        headers.set(HttpHeaders.Names.CONTENT_TYPE, value);
    } else {
        headers.set(HttpHeaders.Names.CONTENT_TYPE, DEFAULT_CONTENT_TYPE);
    }

    headers.set(HttpHeaders.Names.DATE, new Date());
    headers.set(HttpHeaders.Names.SERVER, servletContext.getServerInfoAscii());

    for (Cookie ck : cookies) {
        io.netty.handler.codec.http.cookie.Cookie nettyCookie = new DefaultCookie(ck.getName(), ck.getValue());
        nettyCookie.setDomain(ck.getDomain());
        nettyCookie.setPath(ck.getPath());
        if (ck.getMaxAge() > 0) {
            nettyCookie.setMaxAge(ck.getMaxAge());
        }
        //            response.headers().add("Set-Cookie", nettyCookie);
        response.headers().add("Set-Cookie", ServerCookieEncoder.STRICT.encode(nettyCookie));
    }
    return response;
}

From source file:io.netty.example.http.upload.HttpUploadServerHandler.java

License:Apache License

private void writeResponse(Channel channel, boolean forceClose) {
    // Convert the response content to a ChannelBuffer.
    ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8);
    responseContent.setLength(0);//from  ww w  .  ja  va  2 s .c  o  m

    // Decide whether to close the connection or not.
    boolean keepAlive = HttpUtil.isKeepAlive(request) && !forceClose;

    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
    response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes());

    if (!keepAlive) {
        response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
    } else if (request.protocolVersion().equals(HttpVersion.HTTP_1_0)) {
        response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }

    Set<Cookie> cookies;
    String value = request.headers().get(HttpHeaderNames.COOKIE);
    if (value == null) {
        cookies = Collections.emptySet();
    } else {
        cookies = ServerCookieDecoder.STRICT.decode(value);
    }
    if (!cookies.isEmpty()) {
        // Reset the cookies if necessary.
        for (Cookie cookie : cookies) {
            response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie));
        }
    }
    // Write the response.
    ChannelFuture future = channel.writeAndFlush(response);
    // Close the connection after the write operation is done if necessary.
    if (!keepAlive) {
        future.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:io.vertx.ext.web.client.SessionAwareWebClientTest.java

License:Open Source License

@Test
public void testReadCookie(TestContext context) {
    Async async = context.async();/*from  www  .  j a  va 2 s  .  co m*/
    prepareServer(context, req -> {
        req.response().headers().add("set-cookie",
                ServerCookieEncoder.STRICT.encode(new DefaultCookie("test", "toast")));
    });

    client.get(PORT, "localhost", "/").send(ar -> {
        context.assertTrue(ar.succeeded());
        validate(context, client.cookieStore().get(false, "localhost", "/"), new String[] { "test" },
                new String[] { "toast" });
        async.complete();
    });
}

From source file:io.vertx.ext.web.client.SessionAwareWebClientTest.java

License:Open Source License

@Test
public void testReadManyCookies(TestContext context) {
    Async async = context.async();//from  ww w .j a va2  s  . c o m
    prepareServer(context, req -> {
        req.response().headers().add("set-cookie",
                ServerCookieEncoder.STRICT.encode(new DefaultCookie("test1", "toast1")));
        req.response().headers().add("set-cookie",
                ServerCookieEncoder.STRICT.encode(new DefaultCookie("test2", "toast2")));
        req.response().headers().add("set-cookie",
                ServerCookieEncoder.STRICT.encode(new DefaultCookie("test3", "toast3")));
    });

    client.get(PORT, "localhost", "/").send(ar -> {
        context.assertTrue(ar.succeeded());
        validate(context, client.cookieStore().get(false, "localhost", "/"),
                new String[] { "test1", "test2", "test3" }, new String[] { "toast1", "toast2", "toast3" });
        async.complete();
    });
}