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

项目:netty-socketio-demo    文件:CookieUserAuthorizationListener.java   
/**
 * 从Http Cookie中获取用户Id
 * 
 * @param data
 * @return
 */
public static final PushUser getUser(HandshakeData data) {
    String _cookie = data.getSingleHeader(HttpHeaders.Names.COOKIE);
    if (_cookie != null) {
        Set<Cookie> cookies = ServerCookieDecoder.LAX.decode(_cookie);
        for (Cookie cookie : cookies) {
            if (TokenManager.LOGIN_COOKIE_NAME.equals(cookie.name())) {
                String value = cookie.value();
                if (value != null) {
                    return getUserIdFromCookie(value);
                }
            }
        }
    }
    return null;
}
项目:qonduit    文件:HttpRequestDecoder.java   
public static String getSessionId(FullHttpRequest msg, boolean anonymousAccessAllowed) {
    final StringBuilder buf = new StringBuilder();
    msg.headers().getAll(Names.COOKIE).forEach(h -> {
        ServerCookieDecoder.STRICT.decode(h).forEach(c -> {
            if (c.name().equals(Constants.COOKIE_NAME)) {
                if (buf.length() == 0) {
                    buf.append(c.value());
                }
            }
        });
    });
    String sessionId = buf.toString();
    if (sessionId.length() == 0 && anonymousAccessAllowed) {
        sessionId = NO_AUTHORIZATIONS;
    } else if (sessionId.length() == 0) {
        sessionId = null;
    }
    return sessionId;
}
项目:timely    文件:HttpRequestDecoder.java   
public static String getSessionId(FullHttpRequest msg, boolean anonymousAccessAllowed) {
    final StringBuilder buf = new StringBuilder();
    msg.headers().getAll(Names.COOKIE).forEach(h -> {
        ServerCookieDecoder.STRICT.decode(h).forEach(c -> {
            if (c.name().equals(Constants.COOKIE_NAME)) {
                if (buf.length() == 0) {
                    buf.append(c.value());
                }
            }
        });
    });
    String sessionId = buf.toString();
    if (sessionId.length() == 0 && anonymousAccessAllowed) {
        sessionId = NO_AUTHORIZATIONS;
    } else if (sessionId.length() == 0) {
        sessionId = null;
    }
    return sessionId;
}
项目:lannister    文件:HttpResponse.java   
public static HttpResponse createServerDefault(String requestCookie) {
    HttpResponse ret = new HttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.buffer());

    ret.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8");

    if (requestCookie == null) { return ret; }

    Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(requestCookie);
    if (cookies.isEmpty()) { return ret; }

    // Reset the cookies if necessary.
    for (Cookie cookie : cookies) {
        ret.headers().add(HttpHeaderNames.SET_COOKIE, ClientCookieEncoder.STRICT.encode(cookie));
    }

    return ret;
}
项目:Dream-Catcher    文件:HarCaptureFilter.java   
protected void captureRequestCookies(HttpRequest httpRequest) {
    Log.e("InnerHandle", "captureRequestCookies " + harEntry.getId());
    String cookieHeader = httpRequest.headers().get(HttpHeaders.Names.COOKIE);
    if (cookieHeader == null) {
        return;
    }

    Set<Cookie> cookies = ServerCookieDecoder.LAX.decode(cookieHeader);

    for (Cookie cookie : cookies) {
        HarCookie harCookie = new HarCookie();

        harCookie.setName(cookie.name());
        harCookie.setValue(cookie.value());

        harRequest.getRequest().getCookies().add(harCookie);
        harRequest.addHeader(cookie.name(), cookie.value());
    }
}
项目:blynk-server    文件:SessionDao.java   
public User getUserFromCookie(FullHttpRequest request) {
    String cookieString = request.headers().get(HttpHeaderNames.COOKIE);

    if (cookieString != null) {
        Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(cookieString);
        if (!cookies.isEmpty()) {
            for (Cookie cookie : cookies) {
                if (isValid(cookie)) {
                    String token = cookie.value();
                    return httpSession.get(token);
                }
            }
        }
    }

    return null;
}
项目:redant    文件:CookieHelper.java   
/**
 * 获取HttpRequest中的Cookies
 * @param request
 * @return
 */
public static Set<Cookie> getCookies(HttpRequest request){
    Set<Cookie> cookies;
    String value = request.headers().get(HttpHeaderNames.COOKIE);
    if (value == null) {
        cookies = Collections.emptySet();
    } else {
        cookies = ServerCookieDecoder.STRICT.decode(value);
    }
    return cookies;
}
项目: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    文件:Utils.java   
public static final Collection<Cookie> getCookies(String name, HttpRequest request) {
    String cookieString = request.headers().get(COOKIE);
    if (cookieString != null) {
        List<Cookie> foundCookie = new ArrayList<Cookie>();
        // 不验证name 和 value
        Set<Cookie> cookies = ServerCookieDecoder.LAX.decode(cookieString);
        for (Cookie cookie : cookies) {
            if (cookie.name().equals(name))
                foundCookie.add(cookie);
        }

        return foundCookie;
    }
    return null;
}
项目:tasfe-framework    文件:Utils.java   
public static final Collection<Cookie> getCookies(String name, HttpResponse response) {
    String cookieString = response.headers().get(COOKIE);
    if (cookieString != null) {
        List<Cookie> foundCookie = new ArrayList<Cookie>();
        // 不验证name 和 value
        Set<Cookie> cookies = ServerCookieDecoder.LAX.decode(cookieString);
        for (Cookie cookie : cookies) {
            if (cookie.name().equals(name))
                foundCookie.add(cookie);
        }

        return foundCookie;
    }
    return null;
}
项目:vaadin-vertx-samples    文件:WebsocketSessionHandler.java   
@Override
public void handle(ServerWebSocket serverWebSocket) {
    String basePath = Optional.ofNullable(mountPoint)
        .map(m -> m.substring(0, m.lastIndexOf('/')) )
        .orElse("");

    if (!serverWebSocket.path().startsWith(basePath + "/PUSH")) {
        serverWebSocket.reject();
    }
    String cookieHeader = serverWebSocket.headers().get(COOKIE);

    if (cookieHeader != null) {
        Optional<String> sessionId = ServerCookieDecoder.STRICT.decode(cookieHeader).stream()
            .filter(cookie -> cookieName.equals(cookie.name()))
            .findFirst().map(Cookie::value);
        if (sessionId.isPresent()) {
            sessionId.ifPresent(sid -> sessionStore.get(sid, event -> {
                    Session session = null;
                    if (event.succeeded()) {
                        session = event.result();
                    }
                    next.accept(serverWebSocket, session);
                }
            ));
            return;
        }
    }
    next.accept(serverWebSocket, null);
}
项目:riposte    文件:HttpUtils.java   
public static Set<Cookie> extractCookies(HttpRequest request) {
    Set<Cookie> cookies = new HashSet<>();

    HttpHeaders trailingHeaders = extractTrailingHeadersIfPossible(request);

    String cookieString = request.headers().get(COOKIE);
    if (cookieString == null && trailingHeaders != null)
        cookieString = trailingHeaders.get(COOKIE);

    if (cookieString != null)
        cookies.addAll(ServerCookieDecoder.LAX.decode(cookieString));

    return cookies;
}
项目: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;
}
项目:bridje-framework    文件:HttpServerChannelHandler.java   
public Set<Cookie> parseCookies(String cookiesHeader)
{
    Set<Cookie> cookies;
    if (cookiesHeader == null)
    {
        cookies = Collections.emptySet();
    }
    else
    {
        cookies = ServerCookieDecoder.STRICT.decode(cookiesHeader);
    }
    return cookies;
}
项目:lambdatra    文件:WrappedRequest.java   
public WrappedRequest(FullHttpRequest req, Map<String, String> params, SessionStore<S> sessions) {
    this.req = req;
    this.params = params;
    this.query = new QueryStringDecoder(req.getUri());
    this.cookies = new HashMap<>();
    this.sessions = sessions;

    {
        getHeader(Names.COOKIE).ifPresent(header -> {
            for (Cookie c : ServerCookieDecoder.LAX.decode(header)) {
                cookies.put(c.name(), c);
            }
        });
    }
}
项目:blade    文件:HttpRequest.java   
private void init(FullHttpRequest fullHttpRequest) {
    // headers
    HttpHeaders httpHeaders = fullHttpRequest.headers();
    if (httpHeaders.size() > 0) {
        this.headers = new HashMap<>(httpHeaders.size());
        httpHeaders.forEach((header) -> headers.put(header.getKey(), header.getValue()));
    } else {
        this.headers = new HashMap<>();
    }

    // body content
    this.body = fullHttpRequest.content().copy();

    // request query parameters
    Map<String, List<String>> parameters = new QueryStringDecoder(fullHttpRequest.uri(), CharsetUtil.UTF_8).parameters();
    if (null != parameters) {
        this.parameters = new HashMap<>();
        this.parameters.putAll(parameters);
    }

    if (!HttpConst.METHOD_GET.equals(fullHttpRequest.method().name())) {
        HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(HTTP_DATA_FACTORY, fullHttpRequest);
        decoder.getBodyHttpDatas().forEach(this::parseData);
    }

    // cookies
    String cookie = header(HttpConst.COOKIE_STRING);
    cookie = cookie.length() > 0 ? cookie : header(HttpConst.COOKIE_STRING.toLowerCase());
    if (StringKit.isNotBlank(cookie)) {
        ServerCookieDecoder.LAX.decode(cookie).forEach(this::parseCookie);
    }
}
项目:glowroot    文件:HttpSessionManager.java   
@Nullable
String getSessionId(CommonRequest request) throws Exception {
    String cookieHeader = request.getHeader(HttpHeaderNames.COOKIE);
    if (cookieHeader == null) {
        return null;
    }
    Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(cookieHeader);
    for (Cookie cookie : cookies) {
        if (cookie.name().equals(configRepository.getWebConfig().sessionCookieName())) {
            return cookie.value();
        }
    }
    return null;
}
项目: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    文件:RequestWrapper.java   
private void initCookies() {
  if (null == headers || headers.isEmpty()) {
    return;
  }
  String value = headers.get(HttpHeaderNames.COOKIE);
  if (Strings.isNullOrEmpty(value)) {
    return;
  }
  Set<Cookie> cookieSet = ServerCookieDecoder.STRICT.decode(value);
  this.cookies = cookieSet.stream().collect(Collectors.toMap(Cookie::name, Cookie::value));
}
项目:jooby    文件:NettyRequest.java   
@Override
public List<org.jooby.Cookie> cookies() {
  if (this.cookies == null) {
    String cookieString = req.headers().get(HttpHeaderNames.COOKIE);
    if (cookieString != null) {
      this.cookies = ServerCookieDecoder.STRICT.decode(cookieString).stream()
          .map(this::cookie)
          .collect(Collectors.toList());

    } else {
      this.cookies = Collections.emptyList();
    }
  }
  return this.cookies;
}
项目:divconq    文件:Request.java   
public void load(ChannelHandlerContext ctx, HttpRequest req) {
    this.method = req.getMethod();
    this.headers = req.headers();

       String value = req.headers().get(Names.COOKIE);

       if (StringUtil.isNotEmpty(value)) {
        Set<Cookie> cset = ServerCookieDecoder.STRICT.decode(value);

        for (Cookie cookie : cset) 
            this.cookies.put(cookie.name(), cookie);
       }

       QueryStringDecoder decoderQuery = new QueryStringDecoder(req.getUri());        
       this.parameters = decoderQuery.parameters();        // TODO decode
       this.path = new CommonPath(QueryStringDecoder.decodeComponent(decoderQuery.path()));
       this.orgpath = this.path;
       this.orgrequri = QueryStringDecoder.decodeComponent(decoderQuery.uri());

       this.contentType = new ContentTypeParser(this.headers.get(Names.CONTENT_TYPE));

    if (Logger.isDebug()) {
        Logger.debug("Request Method " + this.method);

        for (Entry<String, String> ent : this.headers.entries()) {
            Logger.debug("Request header: " + ent.getKey() + ": " + ent.getValue());
        }
    }
}
项目:mockserver    文件:MockServerRequestDecoder.java   
private void setCookies(HttpRequest httpRequest, FullHttpRequest fullHttpResponse) {
    Cookies cookies = new Cookies();
    for (String cookieHeader : fullHttpResponse.headers().getAll(COOKIE)) {
        Set<io.netty.handler.codec.http.cookie.Cookie> decodedCookies =
            ServerCookieDecoder.LAX.decode(cookieHeader);
        for (io.netty.handler.codec.http.cookie.Cookie decodedCookie : decodedCookies) {
            cookies.withEntry(new Cookie(
                decodedCookie.name(),
                decodedCookie.value()
            ));
        }
    }
    httpRequest.withCookies(cookies);
}
项目: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);
    }
}
项目:carbon-uuf    文件:MicroserviceHttpRequest.java   
public MicroserviceHttpRequest(Request request, MultivaluedMap<String, ?> formParams, Object postParams) {

        this.msf4jRequest = request;
        this.method = request.getHttpMethod();
        this.isGetRequest = REQUEST_GET.equals(method);

        // process URI
        String rawUri = request.getUri();
        int uriPathEndIndex = rawUri.indexOf('?');
        String rawUriPath, rawQueryString;
        if (uriPathEndIndex == -1) {
            rawUriPath = rawUri;
            rawQueryString = null;
        } else {
            rawUriPath = rawUri.substring(0, uriPathEndIndex);
            rawQueryString = rawUri.substring(uriPathEndIndex + 1, rawUri.length());
        }
        this.uri = QueryStringDecoder.decodeComponent(rawUriPath);
        this.contextPath = HttpRequest.getContextPath(this.uri);
        this.uriWithoutContextPath = HttpRequest.getUriWithoutContextPath(this.uri);
        this.queryString = rawQueryString; // Query string is not very useful, so we don't bother to decode it.
        if (rawQueryString != null) {
            HashMap<String, Object> map = new HashMap<>();
            new QueryStringDecoder(rawQueryString, false).parameters()
                    .forEach((key, value) -> map.put(key, (value.size() == 1) ? value.get(0) : value));
            this.queryParams = map;
        } else {
            this.queryParams = Collections.emptyMap();
        }

        // process headers and cookies
        this.headers = new HashMap<>();
        request.getHeaders().getAll().forEach(header -> this.headers.put(header.getName(), header.getValue()));
        String cookieHeader = this.headers.get(HttpHeaders.COOKIE);
        this.cookies = (cookieHeader == null) ? Collections.emptyMap() :
                ServerCookieDecoder.STRICT.decode(cookieHeader).stream().collect(Collectors.toMap(Cookie::name,
                                                                                                  c -> c));

        // process POST data
        if (formParams == null) {
            // This request is not a form POST submission.
            this.files = Collections.emptyMap();
            if (postParams == null) {
                this.formParams = Collections.emptyMap();
            } else {
                if (postParams instanceof List) {
                    List<?> postParamsList = (List<?>) postParams;
                    this.formParams = new HashMap<>(postParamsList.size());
                    for (int i = 0; i < postParamsList.size(); i++) {
                        this.formParams.put(Integer.toString(i), postParamsList.get(i));
                    }
                } else if (postParams instanceof Map) {
                    this.formParams = (Map<String, Object>) postParams;
                } else {
                    throw new NotSupportedException(
                            "Unsupported JSON data type. Expected Map or List. Instead found '" +
                                    postParams.getClass().getName() + "'.");
                }
            }
        } else {
            this.formParams = new HashMap<>();
            this.files = new HashMap<>();
            for (Map.Entry<String, ? extends List<?>> entry : formParams.entrySet()) {
                List<?> values = entry.getValue();
                if (values.isEmpty()) {
                    continue;
                }
                if (values.get(0) instanceof File) {
                    this.files.put(entry.getKey(), (values.size() == 1) ? values.get(0) : values);
                } else {
                    this.formParams.put(entry.getKey(), (values.size() == 1) ? values.get(0) : values);
                }
            }
        }
    }
项目:lannister    文件:HttpRequest.java   
public Set<Cookie> cookies() {
    if (cookies != null) { return cookies; }

    String cookie = headers().get(HttpHeaderNames.COOKIE);
    if (cookie == null || "".equals(cookie)) { return new HashSet<Cookie>(); }

    Set<Cookie> ret = ServerCookieDecoder.STRICT.decode(cookie);

    return ret == null || ret.isEmpty() ? new HashSet<Cookie>() : ret;
}