Example usage for io.netty.handler.codec.http ServerCookieEncoder encode

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

Introduction

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

Prototype

@Deprecated
public static List<String> encode(Iterable<Cookie> cookies) 

Source Link

Document

Batch encodes cookies into Set-Cookie header values.

Usage

From source file: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);//  www .  j a va2s.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(HttpVersion.HTTP_1_1, HttpResponseStatus.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, String.valueOf(buf.readableBytes()));
    }

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

From source file:baseFrame.netty.atest.HttpHelloWorldServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest request = (HttpRequest) msg;
        if (HttpHeaders.is100ContinueExpected(request)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }// ww  w.  ja va2 s.c om
        boolean keepAlive = HttpHeaders.isKeepAlive(request);

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

        if (HttpHeaders.is100ContinueExpected(request)) {
            send100Continue(ctx);
        }

        responseContent.append("VERSION: ").append(request.getProtocolVersion()).append("\r\n");
        //responseContent.append("HOSTNAME: ").append(request.headers().).append("\r\n");
        responseContent.append("REQUEST_URI: ").append(request.getUri()).append("\r\n\r\n");

        HttpHeaders headers = request.headers();
        if (!headers.isEmpty()) {
            for (Entry<String, String> h : headers) {
                CharSequence key = h.getKey();
                CharSequence value = h.getValue();
                responseContent.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n");
            }
            responseContent.append("\r\n");
        }

        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri());
        Map<String, List<String>> params = queryStringDecoder.parameters();
        if (!params.isEmpty()) {
            for (Entry<String, List<String>> p : params.entrySet()) {
                String key = p.getKey();
                List<String> vals = p.getValue();
                for (String val : vals) {
                    responseContent.append("PARAM: ").append(key).append(" = ").append(val).append("\r\n");
                }
            }
            responseContent.append("\r\n");
        }

        response = setResponse(response, responseContent);

        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(Names.CONNECTION, Values.KEEP_ALIVE);
            ctx.write(response);
        }
    }

    if (msg instanceof HttpContent) {
        HttpContent content = (HttpContent) msg;

        if (msg instanceof LastHttpContent) {

        }
    }
}

From source file:cc.io.lessons.server.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 ww w.  ja  v  a  2s .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(HttpVersion.HTTP_1_1, HttpResponseStatus.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);
    }
    if (!cookies.isEmpty()) {
        // Reset the cookies if necessary.
        for (Cookie cookie : cookies) {
            response.headers().add(SET_COOKIE, ServerCookieEncoder.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:ch07.handlers.HttpSnoopServerHandler.java

License:Apache License

private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) {
    // Decide whether to close the connection or not.
    boolean keepAlive = HttpHeaders.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(CONTENT_TYPE, "text/plain; charset=UTF-8");

    if (keepAlive) {
        // Add 'Content-Length' header only for a keep-alive connection.
        response.headers().set(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(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }//from   www .j  a v a  2s. c o m

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

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

    return keepAlive;
}

From source file:com.bala.learning.learning.netty.HttpServerHandler.java

License:Apache License

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

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

    if (keepAlive) {
        // Add 'Content-Length' header only for a keep-alive connection.
        response.headers().set(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(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }/* w w  w.  j  a va  2 s  . c o m*/

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

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

    return keepAlive;
}

From source file:com.barchart.http.server.PooledServerResponse.java

License:BSD License

private ChannelFuture startResponse() {

    checkFinished();//from ww w.  j  a  v a 2 s  .co m

    if (started) {
        throw new IllegalStateException("Response already started");
    }

    // Set headers
    headers().set(HttpHeaders.Names.SET_COOKIE, ServerCookieEncoder.encode(cookies));

    if (!isChunkedEncoding()) {
        setContentLength(content().readableBytes());
    }

    if (HttpHeaders.isKeepAlive(request)) {
        headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    started = true;

    return context.writeAndFlush(this);

}

From source file:com.barchart.netty.server.http.pipeline.PooledHttpServerResponse.java

License:BSD License

private ChannelFuture startResponse() throws IOException {

    checkFinished();/* w w w . ja v  a 2 s. c  o m*/

    if (started)
        throw new IllegalStateException("Response already started");

    started = true;

    // Set headers
    headers().set(HttpHeaders.Names.SET_COOKIE, ServerCookieEncoder.encode(cookies));
    // Default content type
    if (!headers().contains(HttpHeaders.Names.CONTENT_TYPE)) {
        setContentType("text/html; charset=utf-8");
    }

    if (HttpHeaders.isKeepAlive(request)) {
        headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    if (chunkSize > 0) {
        // Chunked, send initial response that is not a FullHttpResponse
        final DefaultHttpResponse resp = new DefaultHttpResponse(getProtocolVersion(), getStatus());
        resp.headers().add(headers());
        HttpHeaders.setTransferEncodingChunked(resp);
        return context.writeAndFlush(resp);
    } else {
        setContentLength(content().readableBytes());
        return context.writeAndFlush(this);
    }

}

From source file:com.dwarf.netty.guide.http.snoop.HttpSnoopServerHandler.java

License:Apache License

private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) {
    // Decide whether to close the connection or not.
    boolean keepAlive = HttpHeaderUtil.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(CONTENT_TYPE, "text/plain; charset=UTF-8");

    if (keepAlive) {
        // Add 'Content-Length' header only for a keep-alive connection.
        response.headers().setInt(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(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }/*from  ww w.j  av a  2  s . c  o m*/

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

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

    return keepAlive;
}

From source file:com.ebay.jetstream.http.netty.server.DefaultHttpServletResponse.java

License:MIT License

@Override
public void addCookie(Cookie arg0) {
    String cookieString = m_nettyhttpresp.headers().get(HttpHeaders.Names.COOKIE);
    Set<io.netty.handler.codec.http.Cookie> cookies;
    if (cookieString != null) {
        cookies = CookieDecoder.decode(cookieString);
        cookies.add(new io.netty.handler.codec.http.DefaultCookie(arg0.getName(), arg0.getValue()));
    } else {/*from   ww  w .  j a  v a2 s .  c o  m*/
        cookies = new HashSet<io.netty.handler.codec.http.Cookie>();
        cookies.add(new io.netty.handler.codec.http.DefaultCookie(arg0.getName(), arg0.getValue()));
    }

    if (!cookies.isEmpty()) {
        // Reset the cookies if necessary.
        HttpHeaders.setHeader(m_nettyhttpresp, HttpHeaders.Names.SET_COOKIE,
                ServerCookieEncoder.encode(cookies));
    }
}

From source file:com.ejisto.modules.vertx.handler.SecurityEnforcer.java

License:Open Source License

@Override
public void handle(HttpServerRequest request) {

    final MultiMap headers = request.headers();
    Optional<String> xRequestedWith = Optional.ofNullable(headers.get(X_REQUESTED_WITH))
            .filter("XMLHttpRequest"::equals);

    if (xRequestedWith.isPresent()) {
        if (!isDevModeActive()) {
            request.response().write(SECURITY_TOKEN);
        }//from w w  w  .j  av a 2s. co  m
        Optional<String> header = Optional.ofNullable(headers.get(XSRF_TOKEN_HEADER)).filter(token::equals);
        if (!header.isPresent()) {
            Boilerplate.writeError(request, HttpResponseStatus.FORBIDDEN.code(),
                    HttpResponseStatus.FORBIDDEN.reasonPhrase());
            return;
        }
    }

    if ("/index.html".equals(request.path())) {
        Cookie cookie = new DefaultCookie(XSRF_TOKEN, token);
        cookie.setPath("/");
        request.response().headers().set(HttpHeaders.SET_COOKIE, ServerCookieEncoder.encode(cookie));
    }
    super.handle(request);
}