Search in sources :

Example 21 with Cookie

use of io.netty.handler.codec.http.cookie.Cookie in project netty by netty.

the class HttpUploadServerHandler method channelRead0.

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;
        URI uri = new URI(request.uri());
        if (!uri.getPath().startsWith("/form")) {
            // Write Menu
            writeMenu(ctx);
            return;
        }
        responseContent.setLength(0);
        responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
        responseContent.append("===================================\r\n");
        responseContent.append("VERSION: " + request.protocolVersion().text() + "\r\n");
        responseContent.append("REQUEST_URI: " + request.uri() + "\r\n\r\n");
        responseContent.append("\r\n\r\n");
        // new getMethod
        for (Entry<String, String> entry : request.headers()) {
            responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r\n");
        }
        responseContent.append("\r\n\r\n");
        // new getMethod
        Set<Cookie> cookies;
        String value = request.headers().get(HttpHeaderNames.COOKIE);
        if (value == null) {
            cookies = Collections.emptySet();
        } else {
            cookies = ServerCookieDecoder.STRICT.decode(value);
        }
        for (Cookie cookie : cookies) {
            responseContent.append("COOKIE: " + cookie + "\r\n");
        }
        responseContent.append("\r\n\r\n");
        QueryStringDecoder decoderQuery = new QueryStringDecoder(request.uri());
        Map<String, List<String>> uriAttributes = decoderQuery.parameters();
        for (Entry<String, List<String>> attr : uriAttributes.entrySet()) {
            for (String attrVal : attr.getValue()) {
                responseContent.append("URI: " + attr.getKey() + '=' + attrVal + "\r\n");
            }
        }
        responseContent.append("\r\n\r\n");
        // if GET Method: should not try to create a HttpPostRequestDecoder
        if (request.method().equals(HttpMethod.GET)) {
            // GET Method: should not try to create a HttpPostRequestDecoder
            // So stop here
            responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n");
            // Not now: LastHttpContent will be sent writeResponse(ctx.channel());
            return;
        }
        try {
            decoder = new HttpPostRequestDecoder(factory, request);
        } catch (ErrorDataDecoderException e1) {
            e1.printStackTrace();
            responseContent.append(e1.getMessage());
            writeResponse(ctx.channel());
            ctx.channel().close();
            return;
        }
        readingChunks = HttpUtil.isTransferEncodingChunked(request);
        responseContent.append("Is Chunked: " + readingChunks + "\r\n");
        responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n");
        if (readingChunks) {
            // Chunk version
            responseContent.append("Chunks: ");
            readingChunks = true;
        }
    }
    // if not it handles the form get
    if (decoder != null) {
        if (msg instanceof HttpContent) {
            // New chunk is received
            HttpContent chunk = (HttpContent) msg;
            try {
                decoder.offer(chunk);
            } catch (ErrorDataDecoderException e1) {
                e1.printStackTrace();
                responseContent.append(e1.getMessage());
                writeResponse(ctx.channel());
                ctx.channel().close();
                return;
            }
            responseContent.append('o');
            // example of reading chunk by chunk (minimize memory usage due to
            // Factory)
            readHttpDataChunkByChunk();
            // example of reading only if at the end
            if (chunk instanceof LastHttpContent) {
                writeResponse(ctx.channel());
                readingChunks = false;
                reset();
            }
        }
    } else {
        writeResponse(ctx.channel());
    }
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) Cookie(io.netty.handler.codec.http.cookie.Cookie) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) URI(java.net.URI) HttpPostRequestDecoder(io.netty.handler.codec.http.multipart.HttpPostRequestDecoder) QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) List(java.util.List) ErrorDataDecoderException(io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.ErrorDataDecoderException) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpContent(io.netty.handler.codec.http.HttpContent)

Example 22 with Cookie

use of io.netty.handler.codec.http.cookie.Cookie in project netty by netty.

the class HttpUploadServerHandler method writeResponse.

private void writeResponse(Channel channel) {
    // Convert the response content to a ChannelBuffer.
    ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8);
    responseContent.setLength(0);
    // 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);
    }
}
Also used : Cookie(io.netty.handler.codec.http.cookie.Cookie) ChannelFuture(io.netty.channel.ChannelFuture) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) ByteBuf(io.netty.buffer.ByteBuf)

Example 23 with Cookie

use of io.netty.handler.codec.http.cookie.Cookie in project netty by netty.

the class HttpSnoopServerHandler method writeResponse.

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);
    }
    // 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;
}
Also used : Cookie(io.netty.handler.codec.http.cookie.Cookie) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse)

Example 24 with Cookie

use of io.netty.handler.codec.http.cookie.Cookie in project ratpack by ratpack.

the class DefaultResponse method cookie.

public Cookie cookie(String name, String value) {
    Cookie cookie = new DefaultCookie(name, value);
    getCookies().add(cookie);
    return cookie;
}
Also used : Cookie(io.netty.handler.codec.http.cookie.Cookie) DefaultCookie(io.netty.handler.codec.http.cookie.DefaultCookie) DefaultCookie(io.netty.handler.codec.http.cookie.DefaultCookie)

Example 25 with Cookie

use of io.netty.handler.codec.http.cookie.Cookie in project ratpack by ratpack.

the class DefaultResponse method expireCookie.

public Cookie expireCookie(String name) {
    Cookie cookie = cookie(name, "");
    cookie.setMaxAge(0);
    return cookie;
}
Also used : Cookie(io.netty.handler.codec.http.cookie.Cookie) DefaultCookie(io.netty.handler.codec.http.cookie.DefaultCookie)

Aggregations

Cookie (io.netty.handler.codec.http.cookie.Cookie)45 DefaultCookie (io.netty.handler.codec.http.cookie.DefaultCookie)21 Test (org.junit.Test)19 DefaultHttpHeaders (io.netty.handler.codec.http.DefaultHttpHeaders)15 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)12 Charset (java.nio.charset.Charset)9 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)6 Test (org.testng.annotations.Test)5 HttpRequest (io.netty.handler.codec.http.HttpRequest)4 ByteBuf (io.netty.buffer.ByteBuf)3 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)3 HttpResponseHeaders (org.asynchttpclient.HttpResponseHeaders)3 DataProvider (com.tngtech.java.junit.dataprovider.DataProvider)2 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)2 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)2 HttpContent (io.netty.handler.codec.http.HttpContent)2 QueryStringDecoder (io.netty.handler.codec.http.QueryStringDecoder)2 HashSet (java.util.HashSet)2 List (java.util.List)2 Uri (org.asynchttpclient.uri.Uri)2