Example usage for io.netty.handler.codec.http DefaultCookie DefaultCookie

List of usage examples for io.netty.handler.codec.http DefaultCookie DefaultCookie

Introduction

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

Prototype

public DefaultCookie(String name, String value) 

Source Link

Document

Creates a new cookie with the specified name and value.

Usage

From source file:fr.wseduc.webutils.request.CookieHelper.java

License:Apache License

public void setSigned(String name, String value, long timeout, String path, HttpServerRequest request) {
    Cookie cookie = new DefaultCookie(name, value);
    cookie.setMaxAge(timeout);//from   w  w  w.  j a v  a2  s . com
    cookie.setSecure("https".equals(Renders.getScheme(request)));
    if (path != null && !path.trim().isEmpty()) {
        cookie.setPath(path);
    }
    if (signKey != null) {
        try {
            signCookie(cookie);
        } catch (InvalidKeyException | NoSuchAlgorithmException | IllegalStateException
                | UnsupportedEncodingException e) {
            log.error(e);
            return;
        }
        request.response().headers().set("Set-Cookie", ServerCookieEncoder.encode(cookie));
    }
}

From source file:holon.internal.http.netty.NettyRequestContext.java

License:Open Source License

private void renderCookies(FullHttpResponse response) {
    for (Map.Entry<String, Cookie> cookieToAdd : this.responseCookies.entrySet()) {
        Cookie holonCookie = cookieToAdd.getValue();
        DefaultCookie cookie = new DefaultCookie(cookieToAdd.getKey(), cookieToAdd.getValue().value());

        cookie.setPath(holonCookie.path() == null ? "/" : holonCookie.path());
        cookie.setSecure(holonCookie.secure());
        cookie.setDomain(holonCookie.domain() == null ? "" : holonCookie.domain());
        cookie.setHttpOnly(holonCookie.httpOnly());

        response.headers().add("Set-Cookie", ServerCookieEncoder.encode(cookie));
    }/*  w w w  .j  a v  a  2s .  c om*/
    for (String name : this.discardCookies) {
        DefaultCookie cookie = new DefaultCookie(name, "");
        cookie.setDiscard(true);
        response.headers().add("Set-Cookie", ServerCookieEncoder.encode(cookie));
    }
}

From source file:inn.eatery.clientTest.ClientHandler.java

License:Apache License

private void getEvents(Channel ch) {
    StringWriter estr = new StringWriter();
    getEvents.write(estr);/*from   w  ww.java  2 s . com*/
    String contentStr = estr.toString();

    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/events/find",
            ch.alloc().buffer().writeBytes(contentStr.getBytes()));

    request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
    request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
    request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json");

    request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes());
    // Set some example cookies.
    request.headers().set(HttpHeaders.Names.COOKIE, ClientCookieEncoder
            .encode(new DefaultCookie("userId", "ahanda"), new DefaultCookie("sessStart", "kal")));

    l.info("getevents bytes {}", request.content().readableBytes());

    // Send the HTTP request.
    ch.writeAndFlush(request);
}

From source file:inn.eatery.clientTest.ClientHandler.java

License:Apache License

public static void pubEvent(Channel ch, JSONObject e) {
    // Prepare the HTTP request.
    JSONArray es = new JSONArray();
    es.put(e);/* w  ww .j a va 2 s.c  o  m*/

    StringWriter estr = new StringWriter();
    es.write(estr);
    String contentStr = estr.toString();
    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/events",
            ch.alloc().buffer().writeBytes(contentStr.getBytes()));

    request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
    request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json");

    request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes());
    // Set some example cookies.
    request.headers().set(HttpHeaders.Names.COOKIE, ClientCookieEncoder
            .encode(new DefaultCookie("userId", "ahanda"), new DefaultCookie("sessStart", "kal")));

    l.info("readable bytes {}", request.content().readableBytes());

    // Send the HTTP request.
    ch.writeAndFlush(request);
}

From source file:io.aos.netty5.http.snoop.HttpSnoopClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    URI uri = new URI(URL);
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    int port = uri.getPort();
    if (port == -1) {
        if ("http".equalsIgnoreCase(scheme)) {
            port = 80;//w  w w  .  jav a2  s  .c  o  m
        } else if ("https".equalsIgnoreCase(scheme)) {
            port = 443;
        }
    }

    if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
        System.err.println("Only HTTP(S) is supported.");
        return;
    }

    // Configure SSL context if necessary.
    final boolean ssl = "https".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new HttpSnoopClientInitializer(sslCtx));

        // Make the connection attempt.
        Channel ch = b.connect(host, port).sync().channel();

        // Prepare the HTTP request.
        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
                uri.getRawPath());
        request.headers().set(HttpHeaders.Names.HOST, host);
        request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
        request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);

        // Set some example cookies.
        request.headers().set(HttpHeaders.Names.COOKIE, ClientCookieEncoder
                .encode(new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar")));

        // Send the HTTP request.
        ch.writeAndFlush(request);

        // Wait for the server to close the connection.
        ch.closeFuture().sync();
    } finally {
        // Shut down executor threads to exit.
        group.shutdownGracefully();
    }
}

From source file:io.aos.netty5.http.upload.HttpUploadClient.java

License:Apache License

/**
 * Standard usage of HTTP API in Netty without file Upload (get is not able to achieve File upload
 * due to limitation on request size)./*from w w  w.  ja  v a 2s.co m*/
 *
 * @return the list of headers that will be used in every example after
 **/
private static List<Entry<String, String>> formget(Bootstrap bootstrap, String host, int port, String get,
        URI uriSimple) throws Exception {
    // XXX /formget
    // No use of HttpPostRequestEncoder since not a POST
    Channel channel = bootstrap.connect(host, port).sync().channel();

    // Prepare the HTTP request.
    QueryStringEncoder encoder = new QueryStringEncoder(get);
    // add Form attribute
    encoder.addParam("getform", "GET");
    encoder.addParam("info", "first value");
    encoder.addParam("secondinfo", "secondvalue &");
    // not the big one since it is not compatible with GET size
    // encoder.addParam("thirdinfo", textArea);
    encoder.addParam("thirdinfo", "third value\r\ntest second line\r\n\r\nnew line\r\n");
    encoder.addParam("Send", "Send");

    URI uriGet = new URI(encoder.toString());
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uriGet.toASCIIString());
    HttpHeaders headers = request.headers();
    headers.set(HttpHeaders.Names.HOST, host);
    headers.set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
    headers.set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP + "," + HttpHeaders.Values.DEFLATE);

    headers.set(HttpHeaders.Names.ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
    headers.set(HttpHeaders.Names.ACCEPT_LANGUAGE, "fr");
    headers.set(HttpHeaders.Names.REFERER, uriSimple.toString());
    headers.set(HttpHeaders.Names.USER_AGENT, "Netty Simple Http Client side");
    headers.set(HttpHeaders.Names.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

    //connection will not close but needed
    // headers.set("Connection","keep-alive");

    headers.set(HttpHeaders.Names.COOKIE, ClientCookieEncoder.encode(new DefaultCookie("my-cookie", "foo"),
            new DefaultCookie("another-cookie", "bar")));

    // send request
    List<Entry<String, String>> entries = headers.entries();
    channel.writeAndFlush(request);

    // Wait for the server to close the connection.
    channel.closeFuture().sync();

    return entries;
}

From source file:io.example.UploadClient.HttpUploadClient.java

License:Apache License

/**
 * Standard usage of HTTP API in Netty without file Upload (get is not able to achieve File upload
 * due to limitation on request size).//w  w w  .j av a  2 s.  com
 *
 * @return the list of headers that will be used in every example after
 **/
private static List<Entry<String, String>> formget(Bootstrap bootstrap, String host, int port, String get,
        URI uriSimple) throws Exception {
    // XXX /formget
    // No use of HttpPostRequestEncoder since not a POST
    Channel channel = bootstrap.connect(host, port).sync().channel();

    // Prepare the HTTP request.
    QueryStringEncoder encoder = new QueryStringEncoder(get);
    // add Form attribute
    encoder.addParam("getform", "GET");
    encoder.addParam("info", "first value");
    encoder.addParam("secondinfo", "secondvalue &");
    // not the big one since it is not compatible with GET size
    // encoder.addParam("thirdinfo", textArea);
    encoder.addParam("thirdinfo", "third value\r\ntest second line\r\n\r\nnew line\r\n");
    encoder.addParam("Send", "Send");

    URI uriGet = new URI(encoder.toString());
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uriGet.toASCIIString());
    HttpHeaders headers = request.headers();
    headers.set(HttpHeaders.Names.HOST, host);
    headers.set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
    headers.set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP + "," + HttpHeaders.Values.DEFLATE);

    headers.set(HttpHeaders.Names.ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
    headers.set(HttpHeaders.Names.ACCEPT_LANGUAGE, "fr");
    headers.set(HttpHeaders.Names.REFERER, uriSimple.toString());
    headers.set(HttpHeaders.Names.USER_AGENT, "Netty Simple Http Client side");
    headers.set(HttpHeaders.Names.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

    //connection will not close but needed
    // headers.set("Connection","keep-alive");

    headers.set(HttpHeaders.Names.COOKIE, ClientCookieEncoder.encode(new DefaultCookie("my-cookie", "foo"),
            new DefaultCookie("another-cookie", "bar")));

    // send request
    List<Entry<String, String>> entries = headers.entries();
    channel.writeAndFlush(request);
    System.out.println("Sent formget");

    // Wait for the server to close the connection.
    channel.closeFuture().sync();

    return entries;
}

From source file:io.reactivex.netty.protocol.http.client.CookieTest.java

License:Apache License

@Test
public void testSetCookie() throws Exception {
    DefaultHttpRequest nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "");
    String cookie1Name = "PREF";
    String cookie1Value = "ID=a95756377b78e75e:FF=0:TM=1392709628:LM=1392709628:S=a5mOVvTB7DBkexgi";
    String cookie1Domain = ".google.com";
    String cookie1Path = "/";
    Cookie cookie = new DefaultCookie(cookie1Name, cookie1Value);
    cookie.setPath(cookie1Path);/*from   www .j  a v a2 s.c  om*/
    cookie.setDomain(cookie1Domain);
    new HttpClientRequest<ByteBuf>(nettyRequest).withCookie(cookie);
    String cookieHeader = nettyRequest.headers().get(HttpHeaders.Names.COOKIE);
    Assert.assertNotNull("No cookie header found.", cookieHeader);
    Set<Cookie> decodeCookies = CookieDecoder.decode(cookieHeader);
    Assert.assertNotNull("No cookie found with name.", decodeCookies);
    Assert.assertEquals("Unexpected number of cookies.", 1, decodeCookies.size());
    Cookie decodedCookie = decodeCookies.iterator().next();
    Assert.assertEquals("Unexpected cookie name.", cookie1Name, decodedCookie.getName());
    Assert.assertEquals("Unexpected cookie path.", cookie1Path, decodedCookie.getPath());
    Assert.assertEquals("Unexpected cookie domain.", cookie1Domain, decodedCookie.getDomain());
}

From source file:io.reactivex.netty.protocol.http.server.CookieTest.java

License:Apache License

@Test
public void testSetCookie() throws Exception {
    DefaultHttpResponse nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            HttpResponseStatus.NOT_FOUND);
    HttpServerResponse<ByteBuf> response = new HttpServerResponse<ByteBuf>(new NoOpChannelHandlerContext(),
            nettyResponse, new MetricEventsSubject<HttpServerMetricsEvent<?>>());
    String cookieName = "name";
    String cookieValue = "value";
    response.addCookie(new DefaultCookie(cookieName, cookieValue));
    String cookieHeader = nettyResponse.headers().get(HttpHeaders.Names.SET_COOKIE);
    Assert.assertNotNull("Cookie header not found.", cookieHeader);
    Set<Cookie> decode = CookieDecoder.decode(cookieHeader);
    Assert.assertNotNull("Decoded cookie not found.", decode);
    Assert.assertEquals("Unexpected number of decoded cookie not found.", 1, decode.size());
    Cookie cookie = decode.iterator().next();
    Assert.assertEquals("Unexpected cookie name.", cookieName, cookie.getName());
    Assert.assertEquals("Unexpected cookie value.", cookieValue, cookie.getValue());

}

From source file:io.vertx.ext.apex.impl.CookieImpl.java

License:Open Source License

public CookieImpl(String name, String value) {
    this.nettyCookie = new DefaultCookie(name, value);
    this.changed = true;
}