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

项目:whirlpool    文件:WebSocketHelper.java   
public static void realWriteAndFlush(Channel channel, String text, String contentType, boolean keepalive, DefaultCookie nettyCookie) {
    FullHttpResponse response = new DefaultFullHttpResponse(
            HttpVersion.HTTP_1_1,
            HttpResponseStatus.OK,
            Unpooled.copiedBuffer(text + "\r\n", CharsetUtil.UTF_8));

    HttpUtil.setContentLength(response, text.length());
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, contentType);
    setDateAndCacheHeaders(response, null);
    if (keepalive) {
        response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }

    if (nettyCookie != null) {
        response.headers().set(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(nettyCookie));
    }
    // Write the initial line and the header.
    channel.write(response);
    channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
}
项目:glowroot    文件:HttpSessionManager.java   
private CommonResponse createSession(String username, Set<String> roles, boolean ldap)
        throws Exception {
    String sessionId = new BigInteger(130, secureRandom).toString(32);
    ImmutableSession session = ImmutableSession.builder()
            .caseAmbiguousUsername(username)
            .ldap(ldap)
            .roles(roles)
            .lastRequest(clock.currentTimeMillis())
            .build();
    sessionMap.put(sessionId, session);

    String layoutJson = layoutService
            .getLayoutJson(session.createAuthentication(central, configRepository));
    CommonResponse response = new CommonResponse(OK, MediaType.JSON_UTF_8, layoutJson);
    Cookie cookie =
            new DefaultCookie(configRepository.getWebConfig().sessionCookieName(), sessionId);
    cookie.setHttpOnly(true);
    cookie.setPath("/");
    response.setHeader(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie));
    purgeExpiredSessions();

    auditSuccessfulLogin(username);
    return response;
}
项目:elasticsearch_my    文件:Netty4HttpChannel.java   
private void addCookies(HttpResponse resp) {
    if (transport.resetCookies) {
        String cookieString = nettyRequest.headers().get(HttpHeaders.Names.COOKIE);
        if (cookieString != null) {
            Set<io.netty.handler.codec.http.cookie.Cookie> cookies = ServerCookieDecoder.STRICT.decode(cookieString);
            if (!cookies.isEmpty()) {
                // Reset the cookies if necessary.
                resp.headers().set(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookies));
            }
        }
    }
}
项目:tasfe-framework    文件:HttpSessionInterceptor.java   
@Override
public void onRequestSuccessed(ChannelHandlerContext ctx, HttpRequest request, HttpResponse response) {

    HttpSession s = HttpSessionThreadLocal.get();
    if (s != null && !this.sessionRequestedByCookie) {
        HttpHeaders.addHeader(response, SET_COOKIE,
                ServerCookieEncoder.LAX.encode(HttpSessionImpl.SESSION_ID_KEY, s.getId()));
    }

}
项目:nebo    文件:NettyHttpServletResponse.java   
/**
     * Get a Netty {@link io.netty.handler.codec.http.HttpResponse}, committing the {@link javax.servlet.http.HttpServletResponse}.
     */
    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;
    }
项目:riposte    文件:HttpServletResponseWrapperForResponseInfoTest.java   
@Test
public void addCookie_adds_to_cookie_header() {
    // given
    Cookie cookie = new Cookie(UUID.randomUUID().toString(), UUID.randomUUID().toString());

    // when
    wrapper.addCookie(cookie);

    // then
    assertThat(headers.get(HttpHeaders.Names.SET_COOKIE))
        .isEqualTo(ServerCookieEncoder.LAX.encode(cookie.getName(), cookie.getValue()));
}
项目:reactor-netty    文件:HttpServerOperations.java   
@Override
public HttpServerResponse addCookie(Cookie cookie) {
    if (!hasSentHeaders()) {
        this.responseHeaders.add(HttpHeaderNames.SET_COOKIE,
                ServerCookieEncoder.STRICT.encode(cookie));
    }
    else {
        throw new IllegalStateException("Status and headers already sent");
    }
    return this;
}
项目:zbus    文件:MonitorAdaptor.java   
public void handle(Message msg, Session sess) throws IOException {  
    if("GET".equals(msg.getMethod())){
        ReplyKit.replyTemplate(msg, sess, "login.htm"); 
        return;
    } 

    Map<String, String> data = StrKit.kvp(msg.getBodyString(), "&"); 
    String tokenstr = null;
    if(data.containsKey(Protocol.TOKEN)) {
        tokenstr = data.get(Protocol.TOKEN);
    }
    Token token = authProvider.getToken(tokenstr); 

    Message res = new Message(); 
    if(token == null){
        res.setHeader("location", "/?cmd=login"); 
        res.setStatus(302); 
        sess.write(res);
        return;
    } 

    if(token != null){
        Cookie cookie = new DefaultCookie(Protocol.TOKEN, tokenstr); 
        res.setHeader("Set-Cookie", ServerCookieEncoder.STRICT.encode(cookie));
    } 
    res.setHeader("location", "/"); 
    res.setStatus(302); //redirect to home page
    sess.write(res);
}
项目:zbus    文件:MonitorAdaptor.java   
public void handle(Message msg, Session sess) throws IOException {  
    Message res = new Message();  
    res.setId(msg.getId());
    res.setHeader("location", "/?cmd=login"); 

    Cookie cookie = new DefaultCookie(Protocol.TOKEN, "");
    cookie.setMaxAge(0);
    res.setHeader("Set-Cookie", ServerCookieEncoder.STRICT.encode(cookie)); 
    res.setStatus(302); 
    sess.write(res); 
}
项目:JavaAyo    文件:HttpSnoopServerHandler.java   
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;
}
项目:nomulus    文件:TestUtils.java   
public static FullHttpResponse makeEppHttpResponse(
    String content, HttpResponseStatus status, Cookie... cookies) {
  FullHttpResponse response = makeHttpResponse(content, status);
  response.headers().set(HttpHeaderNames.CONTENT_TYPE, EPP_CONTENT_TYPE);
  for (Cookie cookie : cookies) {
    response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie));
  }
  return response;
}
项目:bridje-framework    文件:HttpServerChannelHandler.java   
private void writeCookies(DefaultHttpResponse response)
{
    if (resp.getCookies() != null && !resp.getCookies().isEmpty())
    {
        // Reset the cookies if necessary.
        resp.getCookies().forEach((name, cookie) ->
        {
            response.headers()
                    .add(SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie.getInternalCookie()));
        });
    }
}
项目:blynk-server    文件:AdminAuthHandler.java   
@POST
@Consumes(value = MediaType.APPLICATION_FORM_URLENCODED)
@Path("/login")
public Response login(@FormParam("email") String email,
                      @FormParam("password") String password) {

    if (email == null || password == null) {
        return redirect(rootPath);
    }

    User user = userDao.getByName(email, AppNameUtil.BLYNK);

    if (user == null || !user.isSuperAdmin) {
        return redirect(rootPath);
    }

    if (!password.equals(user.pass)) {
        return redirect(rootPath);
    }

    Response response = redirect(rootPath);

    log.debug("Admin login is successful. Redirecting to {}", rootPath);

    Cookie cookie = makeDefaultSessionCookie(sessionDao.generateNewSession(user), COOKIE_EXPIRE_TIME);
    response.headers().add(SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie));

    return response;
}
项目:blynk-server    文件:AdminAuthHandler.java   
@POST
@Path("/logout")
public Response logout() {
    Response response = redirect(rootPath);
    Cookie cookie = makeDefaultSessionCookie("", 0);
    response.headers().add(SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie));
    return response;
}
项目:glowroot    文件:HttpSessionManager.java   
void deleteSessionCookie(CommonResponse response) throws Exception {
    Cookie cookie = new DefaultCookie(configRepository.getWebConfig().sessionCookieName(), "");
    cookie.setHttpOnly(true);
    cookie.setMaxAge(0);
    cookie.setPath("/");
    response.setHeader(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie));
}
项目:vertx-web    文件:BaseTransport.java   
static MultiMap removeCookieHeaders(MultiMap headers) {
  // We don't want to remove the JSESSION cookie.
  String cookieHeader = headers.get(COOKIE);
  if (cookieHeader != null) {
    headers.remove(COOKIE);
    Set<Cookie> nettyCookies = ServerCookieDecoder.STRICT.decode(cookieHeader);
    for (Cookie cookie: nettyCookies) {
      if (cookie.name().equals("JSESSIONID")) {
        headers.add(COOKIE, ServerCookieEncoder.STRICT.encode(cookie));
        break;
      }
    }
  }
  return headers;
}
项目:laputa    文件:AbstractResponseTranslator.java   
protected void setCookies(FullHttpResponse res, Set<ResponseCookie> cookies) {
  if (null == cookies || cookies.isEmpty()) {
    return;
  }
  for (ResponseCookie cookie : cookies) {
    try {
      res.headers().set(SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie));
    } catch (Exception e) {
      LOGGER.error(e.getMessage(), e);
    }
  }
}
项目:divconq    文件:Response.java   
public void writeStart(Channel ch, int contentLength) {
    // Build the response object.
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, this.status);

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

    if (this.keepAlive) {
        // Add 'Content-Length' header only for a keep-alive connection.
        if (contentLength > 0)
            response.headers().set(Names.CONTENT_LENGTH, contentLength);

        // 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(Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    if (contentLength == 0)
        response.headers().set(Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);

    // Encode the cookies
    for (Cookie c : this.cookies.values()) 
     response.headers().add(Names.SET_COOKIE, ServerCookieEncoder.STRICT.encode(c));

    for (Entry<CharSequence, String> h : this.headers.entrySet())
        response.headers().set(h.getKey(), h.getValue());

    Hub.instance.getSecurityPolicy().hardenHttpResponse(response);

    if (Logger.isDebug()) {
        Logger.debug("Web server responding to " + ch.remoteAddress());

        for (Entry<String, String> ent : response.headers().entries()) {
            Logger.debug("Response header: " + ent.getKey() + ": " + ent.getValue());
        }
    }

    // Write the response.
    ch.write(response);
}
项目:divconq    文件:Response.java   
public void writeChunked(Channel ch) {
      // Build the response object.
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, this.status);

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

      if (this.keepAlive) {
          // 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(Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
      }

      // TODO add a customer header telling how many messages are in the session adaptor's queue - if > 0

      // Encode the cookies
      for (Cookie c : this.cookies.values()) 
       response.headers().add(Names.SET_COOKIE, ServerCookieEncoder.STRICT.encode(c));

      for (Entry<CharSequence, String> h : this.headers.entrySet())
        response.headers().set(h.getKey(), h.getValue());

    response.headers().set(Names.TRANSFER_ENCODING, Values.CHUNKED);

      // Write the response.
      ChannelFuture future = ch.writeAndFlush(response);

      // Close the non-keep-alive connection after the write operation is done.
      if (!this.keepAlive) 
          future.addListener(ChannelFutureListener.CLOSE);

      /*  we do not need to sync - HTTP is one request, one response.  we would not pile messages on this channel
      try {
    future.sync();
} 
      catch (InterruptedException x) {
    // TODO should we close channel?
}
*/
  }
项目:mockserver    文件:MockServerResponseEncoder.java   
private void setCookies(HttpResponse response, DefaultFullHttpResponse fullHttpResponse) {
    if (response.getCookieList() != null) {
        List<Cookie> cookieValues = new ArrayList<Cookie>();
        for (org.mockserver.model.Cookie cookie : response.getCookieList()) {
            if (!cookieHeaderAlreadyExists(response, cookie)) {
                cookieValues.add(new DefaultCookie(cookie.getName().getValue(), cookie.getValue().getValue()));
            }
        }
        for (Cookie cookieValue : cookieValues) {
            fullHttpResponse.headers().add(SET_COOKIE, ServerCookieEncoder.LAX.encode(cookieValue));
        }
    }
}
项目:mockserver    文件:MockServerResponseToHttpServletResponseEncoder.java   
private void setCookies(HttpResponse httpResponse, HttpServletResponse httpServletResponse) {
    if (httpResponse.getCookieList() != null) {
        for (Cookie cookie : httpResponse.getCookieList()) {
            if (!cookieHeaderAlreadyExists(httpResponse, cookie)) {
                httpServletResponse.addHeader(SET_COOKIE.toString(), ServerCookieEncoder.LAX.encode(new DefaultCookie(cookie.getName().getValue(), cookie.getValue().getValue())));
            }
        }
    }
}
项目:riposte    文件:HttpServletResponseWrapperForResponseInfo.java   
@Override
public void addCookie(Cookie cookie) {
    responseInfo.getHeaders().add(SET_COOKIE, ServerCookieEncoder.LAX.encode(cookie.getName(), cookie.getValue()));
}
项目:JavaAyo    文件:HttpUploadServerHandler.java   
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);
    }
}
项目:lambdatra    文件:WrappedResponse.java   
/**
 * Applies <i>cached</i> header values
 */
protected void applyHeader() {
    setHeader(Names.SET_COOKIE, ServerCookieEncoder.LAX.encode(cookies));
}
项目:vertx-web    文件:CookieImpl.java   
@Override
public String encode() {
  return ServerCookieEncoder.STRICT.encode(nettyCookie);
}
项目:divconq    文件:Response.java   
public void write(Channel ch) {
      if ((this.status != HttpResponseStatus.OK) && (this.body.getLength() == 0))
        this.body.write(this.status.toString());

      // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, this.status);

      int clen = 0;
      this.body.setPosition(0);

try {
    clen = response.content().writeBytes(new InputWrapper(this.body), this.body.getLength());
} 
catch (IOException e) {
}

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

      if (this.keepAlive) {
          // Add 'Content-Length' header only for a keep-alive connection.
          response.headers().set(Names.CONTENT_LENGTH, clen);

          // 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(Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
      }

      // Encode the cookies
      for (Cookie c : this.cookies.values()) 
       response.headers().add(Names.SET_COOKIE, ServerCookieEncoder.STRICT.encode(c));

      for (Entry<CharSequence, String> h : this.headers.entrySet())
        response.headers().set(h.getKey(), h.getValue());

      Hub.instance.getSecurityPolicy().hardenHttpResponse(response);

    if (Logger.isDebug()) {
        Logger.debug("Web server responding to " + ch.remoteAddress());

        for (Entry<String, String> ent : response.headers().entries()) {
            Logger.debug("Response header: " + ent.getKey() + ": " + ent.getValue());
        }
    }

      // Write the response.
      ChannelFuture future = ch.writeAndFlush(response);

      // Close the non-keep-alive connection after the write operation is done.
      if (!this.keepAlive) 
          future.addListener(ChannelFutureListener.CLOSE);

      /*  we do not need to sync - HTTP is one request, one response.  we would not pile messages on this channel
       * 
       *  furthermore, when doing an upload stream we can actually get locked up here because the "write" from our stream
       *  is locked on the write process of the data bus and the response to the session is locked on the write of the response
       *  here - but all the HTTP threads are busy with their respective uploads.  If they all use the same data bus session 
       *  then all HTTP threads can get blocked trying to stream upload if even one of those has called an "OK" to upload and
       *  is stuck here.  so be sure not to use sync with HTTP responses.  this won't be a problem under normal use.
       *   
      try {
    future.sync();
} 
      catch (InterruptedException x) {
    // TODO should we close channel?
}
*/
  }
项目:divconq    文件:Response.java   
public void writeDownloadHeaders(Channel ch, String name, String mime) {
      // Build the response object.
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, this.status);

      response.headers().set(Names.CONTENT_TYPE, StringUtil.isNotEmpty(mime) ? mime : MimeUtil.getMimeTypeForFile(name));

      if (StringUtil.isEmpty(name))
        name = FileUtil.randomFilename("bin");

      response.headers().set("Content-Disposition", "attachment; filename=\"" + NetUtil.urlEncodeUTF8(name) + "\"");

Cookie dl = new DefaultCookie("fileDownload", "true");
dl.setPath("/");

      response.headers().add(Names.SET_COOKIE, ServerCookieEncoder.STRICT.encode(dl));

      // Encode the cookies
      for (Cookie c : this.cookies.values()) 
       response.headers().add(Names.SET_COOKIE, ServerCookieEncoder.STRICT.encode(c));

      for (Entry<CharSequence, String> h : this.headers.entrySet())
        response.headers().set(h.getKey(), h.getValue());

    response.headers().set(Names.TRANSFER_ENCODING, Values.CHUNKED);

      // Write the response.
      ch.writeAndFlush(response);
  }
项目:redant    文件:CookieHelper.java   
/**
 * 设置Cookie
 * @param response
 * @param cookie
 */
public static void setCookie(HttpResponse response,Cookie cookie){
    response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie));
}