Java 类io.netty.handler.codec.http.Cookie 实例源码

项目:ponycar    文件:Response.java   
/**
 * 转换为Netty所用Response
 * 
 * @return FullHttpResponse
 */
public FullHttpResponse toFullHttpResponse() {
    final FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(httpVersion, status, content);

    // headers
    final HttpHeaders httpHeaders = fullHttpResponse.headers().add(headers);
    httpHeaders.set(Names.CONTENT_TYPE, contentType + "; charset=" + charset);
    httpHeaders.set(Names.CONTENT_ENCODING, charset);
    httpHeaders.set(Names.CONTENT_LENGTH, content.readableBytes());

    // Cookies
    for (Cookie cookie : cookies) {
        httpHeaders.add(Names.SET_COOKIE, ServerCookieEncoder.encode(cookie));
    }

    return fullHttpResponse;
}
项目:mqttserver    文件:HttpSessionStore.java   
public static String getClientSessionId(HttpRequest req) {
    Set<Cookie> cookies;
    String value = req.headers().get(HttpHeaders.Names.COOKIE);
    if (value == null) {
        return null;
    } else {
        cookies = CookieDecoder.decode(value);
    }

    for (Cookie cookie : cookies) {
        if (cookie.getName().contains("JSESSIONID")) {
            return cookie.getValue();
        }
    }

    return null;
}
项目:netty-cookbook    文件:FunctionsChannelHandler.java   
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);
        return;
    }

    String uri = request.getUri();
    QueryStringDecoder decoder = new QueryStringDecoder(uri);           
    SimpleHttpRequest req = new SimpleHttpRequest(decoder.path(), decoder.parameters());

    String cookieString = request.headers().get(HttpHeaders.Names.COOKIE);
    if (cookieString != null) {
        Set<Cookie> cookies = CookieDecoder.decode(cookieString);
        req.setCookies(cookies);
    } else {
        req.setCookies(Collections.emptySet());
    }
    req.setHeaders(request.headers());
    copyHttpBodyData(request, req);

    SimpleHttpResponse resp =  eventHandler.apply(req);
    ctx.write( HttpEventHandler.buildHttpResponse(resp.toString(), resp.getStatus(), resp.getContentType()) );
    ctx.flush().close();

}
项目:netty-cookbook    文件:ServletNettyChannelHandler.java   
void copyToServletCookie(FullHttpRequest fullHttpReq, MockHttpServletRequest servletRequest){
    String cookieString = fullHttpReq.headers().get(HttpHeaders.Names.COOKIE);
    if (cookieString != null) {
        Set<Cookie> cookies = CookieDecoder.decode(cookieString);
        if (!cookies.isEmpty()) {
         // Reset the cookies if necessary.
            javax.servlet.http.Cookie[] sCookies = new javax.servlet.http.Cookie[cookies.size()];
            int i = 0;
            for (Cookie cookie: cookies) {
                javax.servlet.http.Cookie sCookie = new javax.servlet.http.Cookie(cookie.getName(), cookie.getValue());
                sCookie.setPath(cookie.getPath());
                sCookie.setMaxAge((int) cookie.getMaxAge());
                sCookies[i++] = sCookie;
            }               
            servletRequest.setCookies(sCookies);
        }
       } else {
        servletRequest.setCookies( new javax.servlet.http.Cookie[0]);
       }
}
项目:web-utils    文件:CookieHelper.java   
public void setSigned(String name, String value, long timeout, String path, HttpServerRequest request) {
    Cookie cookie = new DefaultCookie(name, value);
    cookie.setMaxAge(timeout);
    cookie.setSecure("https".equals(Renders.getScheme(request)));
    cookie.setHttpOnly(true);
    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().add("Set-Cookie", ServerCookieEncoder.encode(cookie));
    }
}
项目:RxNetty    文件:CookiesHolder.java   
private synchronized Map<String, Set<Cookie>> _parseIfNeededAndGet() {
    if (cookiesParsed) { // This method is synchronized, so creates a memory barrier for this variable to be refreshed.
        return allCookies;
    }
    List<String> allCookieHeaders = nettyHeaders.getAll(cookiesHeaderName);
    Map<String, Set<Cookie>> cookies = new HashMap<String, Set<Cookie>>();
    for (String aCookieHeader : allCookieHeaders) {
        Set<Cookie> decode = CookieDecoder.decode(aCookieHeader);
        for (Cookie cookie : decode) {
            Set<Cookie> existingCookiesOfName = cookies.get(cookie.getName());
            if (null == existingCookiesOfName) {
                existingCookiesOfName = new HashSet<Cookie>();
                cookies.put(cookie.getName(), existingCookiesOfName);
            }
            existingCookiesOfName.add(cookie);
        }
    }
    allCookies = Collections.unmodifiableMap(cookies);
    cookiesParsed = true;
    return allCookies;
}
项目:RxNetty    文件:CookieTest.java   
@Test
public void testGetCookie() throws Exception {
    DefaultHttpResponse nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);
    String cookie1Name = "PREF";
    String cookie1Value = "ID=a95756377b78e75e:FF=0:TM=1392709628:LM=1392709628:S=a5mOVvTB7DBkexgi";
    String cookie1Domain = ".google.com";
    String cookie1Path = "/";
    String cookie1Header = cookie1Name + '=' + cookie1Value
                           + "; expires=Thu, 18-Feb-2016 07:47:08 GMT; path=" + cookie1Path + "; domain=" + cookie1Domain;
    nettyResponse.headers().add(HttpHeaders.Names.SET_COOKIE, cookie1Header);
    HttpClientResponse<ByteBuf> response = new HttpClientResponse<ByteBuf>(nettyResponse, PublishSubject.<ByteBuf>create());
    Map<String,Set<Cookie>> cookies = response.getCookies();
    Assert.assertNotNull("Cookies are null.", cookies);
    Assert.assertEquals("Cookies are empty.", 1, cookies.size());
    Set<Cookie> cookies1 = cookies.get(cookie1Name);
    Assert.assertNotNull("No cookies found with name: " + cookie1Name, cookies1);
    Assert.assertEquals("Unexpected number of cookies found.", 1, cookies1.size());
    Cookie cookieFound = cookies1.iterator().next();
    Assert.assertEquals("unexpected cookie name.", cookie1Name, cookieFound.getName());
    Assert.assertEquals("unexpected cookie value.", cookie1Value, cookieFound.getValue());
    Assert.assertEquals("unexpected cookie path.", cookie1Path, cookieFound.getPath());
    Assert.assertEquals("unexpected cookie domain.", cookie1Domain, cookieFound.getDomain());
}
项目:RxNetty    文件:CookieTest.java   
@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);
    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());
}
项目:RxNetty    文件:CookieTest.java   
@Test
public void testGetCookie() 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 = "/";
    String cookie1Header = cookie1Name + '=' + cookie1Value
                           + "; expires=Thu, 18-Feb-2016 07:47:08 GMT; path=" + cookie1Path + "; domain=" + cookie1Domain;
    nettyRequest.headers().add(HttpHeaders.Names.COOKIE, cookie1Header);
    HttpServerRequest<ByteBuf> request = new HttpServerRequest<ByteBuf>(nettyRequest, PublishSubject.<ByteBuf>create());
    Map<String,Set<Cookie>> cookies = request.getCookies();
    Assert.assertEquals("Unexpected number of cookies.", 1, cookies.size());
    Set<Cookie> cookies1 = cookies.get(cookie1Name);
    Assert.assertNotNull("No cookie found with name: " + cookie1Name, cookies1);
    Assert.assertEquals("Unexpected number of cookies with name: " + cookie1Name, 1, cookies1.size() );
    Cookie cookie = cookies1.iterator().next();
    Assert.assertEquals("Unexpected cookie name.", cookie1Name, cookie.getName());
    Assert.assertEquals("Unexpected cookie path.", cookie1Path, cookie.getPath());
}
项目:RxNetty    文件:CookieTest.java   
@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);
    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());

}
项目:Sparkngin    文件:TrackingPixelRouteHandler.java   
void setCookie(HttpRequest request, FullHttpResponse response) {
  // 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) {
        if("visit-count".equals(cookie.getName())) {
          int count = Integer.parseInt(cookie.getValue()) ;
          cookie.setValue(Integer.toString(count + 1));
          //System.out.println("Visit: " + count);
        }
        response.headers().add(SET_COOKIE, ServerCookieEncoder.encode(cookie));
      }
    }
  } else {
    // Browser sent no cookie.  Add some.
    response.headers().add(SET_COOKIE, ServerCookieEncoder.encode("id", UUID.randomUUID().toString()));
    response.headers().add(SET_COOKIE, ServerCookieEncoder.encode("visit-count", "1"));
    response.headers().add(SET_COOKIE, ServerCookieEncoder.encode("first-visit-time", new Date().toString()));
  }
}
项目:sardine    文件:CookieTest.java   
public static void main(String[] args) {
    Set<Cookie> cookies = new HashSet<>();
    cookies.add(new DefaultCookie("id", "123"));

    Optional<Cookie> cookie = cookies.stream().filter(c -> c.name().equalsIgnoreCase("id")).findFirst();

    if (cookie.isPresent())
        System.out.println(cookie.get());
    else
        System.out.println("none");
}
项目:netty-cookbook    文件:HttpRequestData.java   
public HttpRequestData(HttpRequestEvent event){
    HttpHeaders headers = event.getRequest().headers();
    String refererUrl = NettyHttpUtil.getRefererUrl(headers);               
    String userAgent = headers.get(USER_AGENT);

    String cookieString = headers.get(COOKIE);
    Map<String, String> cookiesMap = null;
    if (cookieString != null) {         
        try {               
            Set<Cookie> cookies = CookieDecoder.decode(cookieString);           
            int z = cookies.size();
            if (z > 0) {
                cookiesMap = new HashMap<>(z);
                for (Cookie cookie : cookies) {
                    cookiesMap.put(cookie.getName(), cookie.getValue());
                }                                       
            } else {
                cookiesMap = new HashMap<>(0);
            }
        } catch (Exception e) {         
            e.printStackTrace();
            System.err.println("--cookie: "+cookieString);
        }           
    }
    set(userAgent, refererUrl, event.getParams(), cookiesMap);      
    //System.out.println(cookieString + " request COOKIE " + cookies );
}
项目:netty-cookbook    文件:HttpRequestData.java   
public HttpRequestData(HttpRequestEvent event){
    HttpHeaders headers = event.getRequest().headers();
    String refererUrl = NettyHttpUtil.getRefererUrl(headers);               
    String userAgent = headers.get(USER_AGENT);

    String cookieString = headers.get(COOKIE);
    Map<String, String> cookiesMap = null;
    if (cookieString != null) {         
        try {               
            Set<Cookie> cookies = CookieDecoder.decode(cookieString);           
            int z = cookies.size();
            if (z > 0) {
                cookiesMap = new HashMap<>(z);
                for (Cookie cookie : cookies) {
                    cookiesMap.put(cookie.getName(), cookie.getValue());
                }                                       
            } else {
                cookiesMap = new HashMap<>(0);
            }
        } catch (Exception e) {         
            e.printStackTrace();
            System.err.println("--cookie: "+cookieString);
        }           
    }
    set(userAgent, refererUrl, event.getParams(), cookiesMap);      
    //System.out.println(cookieString + " request COOKIE " + cookies );
}
项目:netty-cookbook    文件:HttpRequestData.java   
public HttpRequestData(HttpRequestEvent event){
    HttpHeaders headers = event.getRequest().headers();
    String refererUrl = NettyHttpUtil.getRefererUrl(headers);               
    String userAgent = headers.get(USER_AGENT);

    String cookieString = headers.get(COOKIE);
    Map<String, String> cookiesMap = null;
    if (cookieString != null) {         
        try {               
            Set<Cookie> cookies = CookieDecoder.decode(cookieString);           
            int z = cookies.size();
            if (z > 0) {
                cookiesMap = new HashMap<>(z);
                for (Cookie cookie : cookies) {
                    cookiesMap.put(cookie.getName(), cookie.getValue());
                }                                       
            } else {
                cookiesMap = new HashMap<>(0);
            }
        } catch (Exception e) {         
            e.printStackTrace();
            System.err.println("--cookie: "+cookieString);
        }           
    }
    set(userAgent, refererUrl, event.getParams(), cookiesMap);      
    //System.out.println(cookieString + " request COOKIE " + cookies );
}
项目:netty-cookbook    文件:HttpRequestData.java   
public HttpRequestData(HttpRequestEvent event){
    HttpHeaders headers = event.getRequest().headers();
    String refererUrl = NettyHttpUtil.getRefererUrl(headers);               
    String userAgent = headers.get(USER_AGENT);

    String cookieString = headers.get(COOKIE);
    Map<String, String> cookiesMap = null;
    if (cookieString != null) {         
        try {               
            Set<Cookie> cookies = CookieDecoder.decode(cookieString);           
            int z = cookies.size();
            if (z > 0) {
                cookiesMap = new HashMap<>(z);
                for (Cookie cookie : cookies) {
                    cookiesMap.put(cookie.getName(), cookie.getValue());
                }                                       
            } else {
                cookiesMap = new HashMap<>(0);
            }
        } catch (Exception e) {         
            e.printStackTrace();
            System.err.println("--cookie: "+cookieString);
        }           
    }
    set(userAgent, refererUrl, event.getParams(), cookiesMap);      
    //System.out.println(cookieString + " request COOKIE " + cookies );
}
项目:netty-cookbook    文件:HttpRequestData.java   
public HttpRequestData(HttpRequestEvent event){
    HttpHeaders headers = event.getRequest().headers();
    String refererUrl = NettyHttpUtil.getRefererUrl(headers);               
    String userAgent = headers.get(USER_AGENT);

    String cookieString = headers.get(COOKIE);
    Map<String, String> cookiesMap = null;
    if (cookieString != null) {         
        try {               
            Set<Cookie> cookies = CookieDecoder.decode(cookieString);           
            int z = cookies.size();
            if (z > 0) {
                cookiesMap = new HashMap<>(z);
                for (Cookie cookie : cookies) {
                    cookiesMap.put(cookie.getName(), cookie.getValue());
                }                                       
            } else {
                cookiesMap = new HashMap<>(0);
            }
        } catch (Exception e) {         
            e.printStackTrace();
            System.err.println("--cookie: "+cookieString);
        }           
    }
    set(userAgent, refererUrl, event.getParams(), cookiesMap);      
    //System.out.println(cookieString + " request COOKIE " + cookies );
}
项目:netty-cookbook    文件:HttpRequestData.java   
public HttpRequestData(HttpRequestEvent event){
    HttpHeaders headers = event.getRequest().headers();
    String refererUrl = NettyHttpUtil.getRefererUrl(headers);               
    String userAgent = headers.get(USER_AGENT);

    String cookieString = headers.get(COOKIE);
    Map<String, String> cookiesMap = null;
    if (cookieString != null) {         
        try {               
            Set<Cookie> cookies = CookieDecoder.decode(cookieString);           
            int z = cookies.size();
            if (z > 0) {
                cookiesMap = new HashMap<>(z);
                for (Cookie cookie : cookies) {
                    cookiesMap.put(cookie.getName(), cookie.getValue());
                }                                       
            } else {
                cookiesMap = new HashMap<>(0);
            }
        } catch (Exception e) {         
            e.printStackTrace();
            System.err.println("--cookie: "+cookieString);
        }           
    }
    set(userAgent, refererUrl, event.getParams(), cookiesMap);      
    //System.out.println(cookieString + " request COOKIE " + cookies );
}
项目:netty-cookbook    文件:HttpRequestData.java   
public HttpRequestData(HttpRequestEvent event){
    HttpHeaders headers = event.getRequest().headers();
    String refererUrl = NettyHttpUtil.getRefererUrl(headers);               
    String userAgent = headers.get(USER_AGENT);

    String cookieString = headers.get(COOKIE);
    Map<String, String> cookiesMap = null;
    if (cookieString != null) {         
        try {               
            Set<Cookie> cookies = CookieDecoder.decode(cookieString);           
            int z = cookies.size();
            if (z > 0) {
                cookiesMap = new HashMap<>(z);
                for (Cookie cookie : cookies) {
                    cookiesMap.put(cookie.getName(), cookie.getValue());
                }                                       
            } else {
                cookiesMap = new HashMap<>(0);
            }
        } catch (Exception e) {         
            e.printStackTrace();
            System.err.println("--cookie: "+cookieString);
        }           
    }
    set(userAgent, refererUrl, event.getParams(), cookiesMap);      
    //System.out.println(cookieString + " request COOKIE " + cookies );
}
项目:netty4.0.27Learn    文件:HttpSnoopServerHandler.java   
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);
    }

    // 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;
}
项目:netty.book.kor    文件:HttpSnoopServerHandler.java   
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);
    }

    // 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;
}
项目:ponycar    文件:Request.java   
/**
 * 填充头部信息和Cookie信息
 * 
 * @param headers
 *            HttpHeaders
 */
private void buildHeadersAndCookies(HttpHeaders headers) {
    for (Entry<String, String> entry : headers) {
        this.headers.put(entry.getKey(), entry.getValue());
    }
    final String cookieString = this.headers.get(Names.COOKIE.toString());
    if (StringUtils.isNotBlank(cookieString)) {
        final Set<Cookie> cookies = CookieDecoder.decode(cookieString);
        for (Cookie cookie : cookies) {
            this.cookies.put(cookie.getName(), cookie);
        }
    }
}
项目:netty4study    文件:HttpSnoopServerHandler.java   
private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) {
    // Decide whether to close the connection or not.
    boolean keepAlive = 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);
    }

    // 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;
}
项目:detective    文件:HttpServerTask.java   
private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) {
  // Decide whether to close the connection or not.
  boolean keepAlive = 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);
  }

  // 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;
}
项目:xio    文件:SampleHandler.java   
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);
  }

  // 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;
}
项目:ob1k    文件:NettyRequest.java   
@Override
public String getCookie(final String cookieName) {
  if (cookies == null) {
    populateCookies();
  }

  final Cookie cookie = cookies.get(cookieName);
  return cookie != null ? cookie.getValue() : null;
}
项目:ob1k    文件:NettyRequest.java   
private void populateCookies() {
  cookies = Maps.newHashMap();

  final String cookieHeaderValue = inner.headers().get("Cookie");
  if (cookieHeaderValue == null) return;

  final Set<Cookie> cookiesSet = CookieDecoder.decode(cookieHeaderValue, false);

  for (final Cookie cookie : cookiesSet) {
    cookies.put(cookie.getName(), cookie);
  }
}
项目:pipes    文件:HttpRequestServletAdapter.java   
private Map<String, Cookie> buildCookies(HttpServletRequest httpRequest) {
    LinkedHashMap<String, Cookie> cookies = new LinkedHashMap<>();
    String cookieString = httpRequest.getHeader(HttpHeaders.COOKIE);
    if (StringUtils.isNotBlank(cookieString)) {
        for (Cookie cookie : ServerCookieDecoder.decode(cookieString)) {
            cookies.put(cookie.name(), cookie);
        }
    }
    return cookies;
}
项目:pipes    文件:HttpUtil.java   
public static Map<String, Cookie> parseCookieHeader(String cookieHeader) {
    LinkedHashMap<String, Cookie> cookies = new LinkedHashMap<>();
    if (StringUtils.isNotBlank(cookieHeader)) {
        for (Cookie cookie : ServerCookieDecoder.decode(cookieHeader)) {
            cookies.put(cookie.name(), cookie);
        }
    }
    return cookies;
}
项目:web-utils    文件:CookieHelper.java   
public static String get(String name, HttpServerRequest request) {
    if (request.headers().get("Cookie") != null) {
        Set<Cookie> cookies = CookieDecoder.decode(request.headers().get("Cookie"));
        for (Cookie c : cookies) {
            if (c.getName().equals(name)) {
                return c.getValue();
            }
        }
    }
    return null;
}
项目:web-utils    文件:CookieHelper.java   
public static void set(String name, String value, long timeout, String path, HttpServerRequest request) {
    Cookie cookie = new DefaultCookie(name, value);
    cookie.setMaxAge(timeout);
    cookie.setSecure("https".equals(Renders.getScheme(request)));
    if (path != null && !path.trim().isEmpty()) {
        cookie.setPath(path);
    }
    request.response().headers().add("Set-Cookie", ServerCookieEncoder.encode(cookie));
}
项目:web-utils    文件:CookieHelper.java   
private void signCookie(Cookie cookie)
        throws InvalidKeyException, NoSuchAlgorithmException,
        IllegalStateException, UnsupportedEncodingException {
    String signature = HmacSha1.sign(
            cookie.getDomain()+cookie.getName()+
            cookie.getPath()+cookie.getValue(), signKey);
    cookie.setValue(cookie.getValue() + ":" + signature);
}
项目:web-utils    文件:CookieHelper.java   
public String getSigned(String name, String path, HttpServerRequest request) {
    if (request.headers().get("Cookie") != null) {
        Set<Cookie> cookies = CookieDecoder.decode(request.headers().get("Cookie"));
        return getSignedCookie(name, path, cookies);
    }
    return null;
}
项目:web-utils    文件:CookieHelper.java   
public String getSigned(String name, String path, ServerWebSocket ws) {
    if (ws.headers().get("Cookie") != null) {
        Set<Cookie> cookies = CookieDecoder.decode(ws.headers().get("Cookie"));
        return getSignedCookie(name, path, cookies);
    }
    return null;
}
项目:web-utils    文件:CookieHelper.java   
private String getSignedCookie(String name, String path, Set<Cookie> cookies) {
    for (Cookie c : cookies) {
        if (c.getName().equals(name) && c.getValue().contains(":")) {
            int idx = c.getValue().lastIndexOf(":");
            if (idx > c.getValue().length() - 1) continue;
            String value = c.getValue().substring(0, idx);
            String signature = c.getValue().substring(idx+1);
            String calcSign = null;
            String cookiePath = path;
            if (cookiePath == null || cookiePath.trim().isEmpty()) {
                cookiePath = c.getPath();
            }
            try {
                calcSign = HmacSha1.sign(
                        c.getDomain() + c.getName() +
                                cookiePath + value, signKey);
            } catch (InvalidKeyException | NoSuchAlgorithmException
                    | IllegalStateException
                    | UnsupportedEncodingException e) {
            }
            if (calcSign != null && calcSign.equals(signature)) {
                return value;
            }
        }
    }
    return null;
}
项目:netty-netty-5.0.0.Alpha1    文件:HttpSnoopServerHandler.java   
private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) {
    // Decide whether to close the connection or not.
    boolean keepAlive = 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);
    }

    // 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;
}
项目:Instantlogic    文件:NettyTraveler.java   
private String readAuthentication(HttpRequest request) {
  String requestCookie = request.headers().get("Cookie");
  if (requestCookie == null) {
    return null;
  }
  Set<Cookie> cookies = CookieDecoder.decode(requestCookie);
  for (Cookie cookie : cookies) {
    if ("who-am-i".equals(cookie.getName())) {
      return cookie.getValue();
    }
  }
  return null;
}
项目:netty-cookbook    文件:SimpleHttpRequest.java   
public Set<Cookie> getCookies() {
    return cookies;
}
项目:netty-cookbook    文件:SimpleHttpRequest.java   
public void setCookies(Set<Cookie> cookies) {
    this.cookies = cookies;
}
项目:netty-http-server    文件:NettyHttpResponse.java   
public Collection<Cookie> getCookies() {
    return cookies;
}