Java Code Examples for io.netty.handler.codec.http.cookie.ServerCookieDecoder

The following examples show how to use io.netty.handler.codec.http.cookie.ServerCookieDecoder. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: arcusplatform   Author: arcus-smart-home   File: OAuthBindClientContextHandler.java    License: Apache License 2.0 6 votes vote down vote up
private String extractFromCookies(String cookieHeader) {
   // look for auth cookie
   if(cookieHeader == null) {
      return null;
   }

   String sessionId = null;
   logger.trace("Found cookies: value = {}", cookieHeader);
   Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(cookieHeader);
   for (Cookie cookie : cookies) {
      if (cookieConfig.getAuthCookieName().equals(cookie.name())) {
         logger.trace("Found {} cookie: value = {}", cookieConfig.getAuthCookieName(), cookie.value());
         sessionId = cookie.value();
         if (StringUtils.isNotEmpty(sessionId)) {
            logger.trace("Token {} found in {} cookie.", sessionId, cookieConfig.getAuthCookieName());
         } else {
            sessionId = null;
         }
      }
   }
   return sessionId;
}
 
Example #2
Source Project: arcusplatform   Author: arcus-smart-home   File: BindClientContextHandler.java    License: Apache License 2.0 6 votes vote down vote up
private String extractFromCookies(String cookieHeader) {
   // look for auth cookie
   if(cookieHeader == null) {
      return null;
   }
   
   String sessionId = null;
   logger.trace("Found cookies: value = {}", cookieHeader);
   Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(cookieHeader);
   for (Cookie cookie : cookies) {
      if (cookieConfig.getAuthCookieName().equals(cookie.name())) {
         logger.trace("Found {} cookie: value = {}", cookieConfig.getAuthCookieName(), cookie.value());
         sessionId = cookie.value();
         if (StringUtils.isNotEmpty(sessionId)) {
            logger.trace("Token {} found in {} cookie.", sessionId, cookieConfig.getAuthCookieName());
         } else {
            sessionId = null;
         }
      }
   }
   return sessionId;
}
 
Example #3
Source Project: CapturePacket   Author: huanglqweiwei   File: HarCaptureFilter.java    License: MIT License 6 votes vote down vote up
protected void captureRequestCookies(HttpRequest httpRequest) {
    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());

        harEntry.getRequest().getCookies().add(harCookie);
    }
}
 
Example #4
Source Project: leo-im-server   Author: lining90567   File: UserController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 从cookie中得到Session Id
 * @return
 */
private String getJSessionId(FullHttpRequest request) {
    try {
        String cookieStr = request.headers().get("Cookie");
        if(cookieStr == null || cookieStr.trim().isEmpty()) {
            return null;
        }
        Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(cookieStr);
        Iterator<Cookie> it = cookies.iterator();

        while (it.hasNext()) {
            Cookie cookie = it.next();
            if (cookie.name().equals(CacheKeys.JSESSIONID)) {
                if (CacheManagerFactory.getCacheManager().get(cookie.value()) != null) {
                    return cookie.value();
                }
            }
        }
    } catch (Exception e1) {
        return null;
    }
    return null;
}
 
Example #5
Source Project: leo-im-server   Author: lining90567   File: AuthController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 从cookie中得到Session Id
 * @param request
 * @return
 */
private String getJSessionId(FullHttpRequest request) {
    try {
        String cookieStr = request.headers().get("Cookie");
        if(cookieStr == null || cookieStr.trim().isEmpty()) {
            return null;
        }
        Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(cookieStr);
        Iterator<Cookie> it = cookies.iterator();

        while (it.hasNext()) {
            Cookie cookie = it.next();
            if (cookie.name().equals(CacheKeys.JSESSIONID)) {
                if (CacheManagerFactory.getCacheManager().get(cookie.value()) != null) {
                    return cookie.value();
                }
            }
        }
    } catch (Exception e1) {
        return null;
    }
    return null;
}
 
Example #6
Source Project: styx   Author: HotelsDotCom   File: HttpRequestOperationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldTransformStyxRequestToNettyRequestWithAllRelevantInformation() {
    LiveHttpRequest request = new LiveHttpRequest.Builder()
            .method(GET)
            .header("X-Forwarded-Proto", "https")
            .cookies(
                    requestCookie("HASESSION_V3", "asdasdasd"),
                    requestCookie("has", "123456789")
            )
            .uri("https://www.example.com/foo%2Cbar?foo,baf=2")
            .build();

    DefaultHttpRequest nettyRequest = HttpRequestOperation.toNettyRequest(request);
    assertThat(nettyRequest.method(), is(io.netty.handler.codec.http.HttpMethod.GET));
    assertThat(nettyRequest.uri(), is("https://www.example.com/foo%2Cbar?foo%2Cbaf=2"));
    assertThat(nettyRequest.headers().get("X-Forwarded-Proto"), is("https"));

    assertThat(ServerCookieDecoder.LAX.decode(nettyRequest.headers().get("Cookie")),
            containsInAnyOrder(
                    new DefaultCookie("HASESSION_V3", "asdasdasd"),
                    new DefaultCookie("has", "123456789")));

}
 
Example #7
Source Project: qonduit   Author: NationalSecurityAgency   File: HttpRequestDecoder.java    License: Apache License 2.0 6 votes vote down vote up
public static String getSessionId(FullHttpRequest msg, boolean anonymousAccessAllowed) {
    final StringBuilder buf = new StringBuilder();
    msg.headers().getAll(HttpHeaderNames.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;
}
 
Example #8
Source Project: timely   Author: NationalSecurityAgency   File: GrafanaRequestDecoder.java    License: Apache License 2.0 6 votes vote down vote up
public static String getSessionId(FullHttpRequest msg) {
    Multimap<String, String> headers = HttpHeaderUtils.toMultimap(msg.headers());
    Collection<String> cookies = headers.get(HttpHeaderNames.COOKIE.toString());
    final StringBuilder buf = new StringBuilder();
    cookies.forEach(h -> {
        ServerCookieDecoder.STRICT.decode(h).forEach(c -> {
            if (c.name().equals(Constants.COOKIE_NAME)) {
                if (buf.length() == 0) {
                    buf.append(c.value());
                }
            }
        });
    });
    if (buf.length() == 0) {
        return null;
    } else {
        return buf.toString();
    }
}
 
Example #9
Source Project: timely   Author: NationalSecurityAgency   File: HttpRequestDecoder.java    License: Apache License 2.0 6 votes vote down vote up
public static String getSessionId(FullHttpRequest msg) {
    Multimap<String, String> headers = HttpHeaderUtils.toMultimap(msg.headers());
    Collection<String> cookies = headers.get(HttpHeaderNames.COOKIE.toString());
    final StringBuilder buf = new StringBuilder();
    cookies.forEach(h -> {
        ServerCookieDecoder.STRICT.decode(h).forEach(c -> {
            if (c.name().equals(Constants.COOKIE_NAME)) {
                if (buf.length() == 0) {
                    buf.append(c.value());
                }
            }
        });
    });
    if (buf.length() == 0) {
        return null;
    } else {
        return buf.toString();
    }
}
 
Example #10
Source Project: riposte   Author: Nike-Inc   File: HttpUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static @NotNull Set<Cookie> extractCookies(@Nullable HttpRequest request) {
    if (request == null) {
        return Collections.emptySet();
    }

    HttpHeaders trailingHeaders = extractTrailingHeadersIfPossible(request);

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

    if (cookieString != null) {
        return new HashSet<>(ServerCookieDecoder.LAX.decode(cookieString));
    }

    return Collections.emptySet();
}
 
Example #11
Source Project: lannister   Author: anyflow   File: HttpResponse.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #12
Source Project: Dream-Catcher   Author: misakuo   File: HarCaptureFilter.java    License: MIT License 6 votes vote down vote up
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());
    }
}
 
Example #13
Source Project: reactor-netty   Author: reactor   File: HttpServerConfig.java    License: Apache License 2.0 6 votes vote down vote up
static void addStreamHandlers(Channel ch, ChannelOperations.OnSetup opsFactory,
		ConnectionObserver listener, boolean readForwardHeaders,
		ServerCookieEncoder encoder, ServerCookieDecoder decoder) {
	if (ACCESS_LOG) {
		ch.pipeline()
		  .addLast(NettyPipeline.AccessLogHandler, new AccessLogHandlerH2());
	}
	ch.pipeline()
	  .addLast(NettyPipeline.H2ToHttp11Codec, new Http2StreamFrameToHttpObjectCodec(true))
	  .addLast(NettyPipeline.HttpTrafficHandler,
	           new Http2StreamBridgeServerHandler(listener, readForwardHeaders, encoder, decoder));

	ChannelOperations.addReactiveBridge(ch, opsFactory, listener);

	if (log.isDebugEnabled()) {
		log.debug(format(ch, "Initialized HTTP/2 stream pipeline {}"), ch.pipeline());
	}
}
 
Example #14
Source Project: reactor-netty   Author: reactor   File: HttpServerConfig.java    License: Apache License 2.0 6 votes vote down vote up
static void configureH2Pipeline(ChannelPipeline p,
		ServerCookieDecoder cookieDecoder,
		ServerCookieEncoder cookieEncoder,
		boolean forwarded,
		Http2Settings http2Settings,
		ConnectionObserver listener,
		ChannelOperations.OnSetup opsFactory,
		boolean validate) {
	p.remove(NettyPipeline.ReactiveBridge);

	Http2FrameCodecBuilder http2FrameCodecBuilder =
			Http2FrameCodecBuilder.forServer()
			                      .validateHeaders(validate)
			                      .initialSettings(http2Settings);

	if (p.get(NettyPipeline.LoggingHandler) != null) {
		http2FrameCodecBuilder.frameLogger(new Http2FrameLogger(LogLevel.DEBUG,
				"reactor.netty.http.server.h2"));
	}

	p.addLast(NettyPipeline.HttpCodec, http2FrameCodecBuilder.build())
	 .addLast(NettyPipeline.H2MultiplexHandler,
	          new Http2MultiplexHandler(new H2Codec(opsFactory, listener, forwarded, cookieEncoder, cookieDecoder)));
}
 
Example #15
Source Project: reactor-netty   Author: reactor   File: HttpServerConfig.java    License: Apache License 2.0 6 votes vote down vote up
Http11OrH2CleartextCodec(
		ServerCookieDecoder cookieDecoder,
		ServerCookieEncoder cookieEncoder,
		boolean debug,
		boolean forwarded,
		Http2Settings http2Settings,
		ConnectionObserver listener,
		ChannelOperations.OnSetup opsFactory,
		boolean validate) {
	this.cookieDecoder = cookieDecoder;
	this.cookieEncoder = cookieEncoder;
	this.forwarded = forwarded;
	Http2FrameCodecBuilder http2FrameCodecBuilder =
			Http2FrameCodecBuilder.forServer()
			                      .validateHeaders(validate)
			                      .initialSettings(http2Settings);

	if (debug) {
		http2FrameCodecBuilder.frameLogger(new Http2FrameLogger(
				LogLevel.DEBUG,
				"reactor.netty.http.server.h2"));
	}
	this.http2FrameCodec = http2FrameCodecBuilder.build();
	this.listener = listener;
	this.opsFactory = opsFactory;
}
 
Example #16
Source Project: reactor-netty   Author: reactor   File: HttpServerConfig.java    License: Apache License 2.0 6 votes vote down vote up
H2OrHttp11Codec(
		@Nullable BiPredicate<HttpServerRequest, HttpServerResponse> compressPredicate,
		ServerCookieDecoder cookieDecoder,
		ServerCookieEncoder cookieEncoder,
		HttpRequestDecoderSpec decoder,
		boolean forwarded,
		Http2Settings http2Settings,
		ConnectionObserver listener,
		@Nullable Supplier<? extends ChannelMetricsRecorder> metricsRecorder,
		int minCompressionSize,
		ChannelOperations.OnSetup opsFactory,
		@Nullable Function<String, String> uriTagValue) {
	super(ApplicationProtocolNames.HTTP_1_1);
	this.compressPredicate = compressPredicate;
	this.cookieDecoder = cookieDecoder;
	this.cookieEncoder = cookieEncoder;
	this.decoder = decoder;
	this.forwarded = forwarded;
	this.http2Settings = http2Settings;
	this.listener = listener;
	this.metricsRecorder = metricsRecorder;
	this.minCompressionSize = minCompressionSize;
	this.opsFactory = opsFactory;
	this.uriTagValue = uriTagValue;
}
 
Example #17
Source Project: reactor-netty   Author: reactor   File: HttpServerOperations.java    License: Apache License 2.0 6 votes vote down vote up
HttpServerOperations(Connection c,
		ConnectionObserver listener,
		@Nullable BiPredicate<HttpServerRequest, HttpServerResponse> compressionPredicate,
		HttpRequest nettyRequest,
		@Nullable ConnectionInfo connectionInfo,
		ServerCookieEncoder encoder,
		ServerCookieDecoder decoder) {
	super(c, listener);
	this.nettyRequest = nettyRequest;
	this.path = resolvePath(nettyRequest.uri());
	this.nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
	this.responseHeaders = nettyResponse.headers();
	this.responseHeaders.set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
	this.compressionPredicate = compressionPredicate;
	this.cookieHolder = Cookies.newServerRequestHolder(requestHeaders(), decoder);
	this.connectionInfo = connectionInfo;
	this.cookieEncoder = encoder;
	this.cookieDecoder = decoder;
}
 
Example #18
Source Project: reactor-netty   Author: reactor   File: HttpServerTests.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("FutureReturnValueIgnored")
private void doTestStatus(HttpResponseStatus status) {
	EmbeddedChannel channel = new EmbeddedChannel();
	HttpServerOperations ops = new HttpServerOperations(
			Connection.from(channel),
			ConnectionObserver.emptyListener(),
			null,
			new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"),
			null,
			ServerCookieEncoder.STRICT,
			ServerCookieDecoder.STRICT);
	ops.status(status);
	HttpMessage response = ops.newFullBodyMessage(Unpooled.EMPTY_BUFFER);
	assertThat(((FullHttpResponse) response).status().reasonPhrase()).isEqualTo(status.reasonPhrase());
	// "FutureReturnValueIgnored" is suppressed deliberately
	channel.close();
}
 
Example #19
Source Project: AndroidHttpCapture   Author: JZ-Darkal   File: HarCaptureFilter.java    License: MIT License 6 votes vote down vote up
protected void captureRequestCookies(HttpRequest httpRequest) {
    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());

        harEntry.getRequest().getCookies().add(harCookie);
    }
}
 
Example #20
Source Project: blynk-server   Author: blynkkk   File: SessionDao.java    License: GNU General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #21
Source Project: cxf   Author: apache   File: Utils.java    License: Apache License 2.0 6 votes vote down vote up
public static Collection<Cookie> getCookies(String name,
                                            HttpRequest request) {
    String cookieString = request.headers().get(COOKIE);
    if (cookieString != null) {
        List<Cookie> foundCookie = new ArrayList<>();
        Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(cookieString);
        for (Cookie cookie : cookies) {
            if (cookie.name().equals(name)) {
                foundCookie.add(cookie);
            }
        }

        return foundCookie;
    }
    return null;
}
 
Example #22
Source Project: litchi   Author: phantacix   File: HttpController.java    License: Apache License 2.0 5 votes vote down vote up
public void init(Channel channel, FullHttpRequest request, RouteResult<RouteAction> routeResult, boolean enableCookies) {
    this.channel = channel;
    this.request = request;
    this.routeResult = routeResult;
    this.enableCookies = enableCookies;

    if (this.method() == HttpMethod.POST) {
        try { 
            HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(request);
            decoder.offer(request);
            List<InterfaceHttpData> paramsList = decoder.getBodyHttpDatas();
            for (InterfaceHttpData httpData : paramsList) {
            	if (httpData.getHttpDataType() == HttpDataType.Attribute) {
            		Attribute data = (Attribute) httpData;
            		postMaps.put(data.getName(), data.getValue());
            	} else if (httpData.getHttpDataType() == HttpDataType.FileUpload) {
            		MixedFileUpload fileUpload = (MixedFileUpload) httpData;
            		this.fileUpload = fileUpload;
            	} else {
            		LOGGER.error("not support http data type. type={}", httpData.getHttpDataType());
            	}
            }
        } catch (Exception ex) {
            LOGGER.error("{}", ex);
        }
    }

    if (enableCookies) {
        List<String> cookiesList = request.headers().getAll(HttpHeaderNames.COOKIE);
        cookiesList.forEach(h -> ServerCookieDecoder.STRICT.decode(h).forEach(c -> cookieMaps.put(c.name(), c)));
    }
}
 
Example #23
Source Project: browserup-proxy   Author: browserup   File: HarCaptureFilter.java    License: Apache License 2.0 5 votes vote down vote up
protected void captureRequestCookies(HttpRequest httpRequest) {
    String cookieHeader = httpRequest.headers().get(HttpHeaderNames.COOKIE);
    if (cookieHeader == null) {
        return;
    }

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

    cookies.forEach(cookie -> {
        HarCookie harCookie = new HarCookie();
        harCookie.setName(cookie.name());
        harCookie.setValue(cookie.value());
        harEntry.getRequest().getCookies().add(harCookie);
    });
}
 
Example #24
Source Project: netty-4.1.22   Author: tianheframe   File: HttpSnoopServerHandler.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #25
Source Project: julongchain   Author: JulongChain   File: HttpSnoopServerHandler.java    License: Apache License 2.0 5 votes vote down vote up
private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) {
    // 用以判断是否要关闭链接.
    boolean keepAlive = HttpUtil.isKeepAlive(request);
    // 构建Respons对象.
    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) {
        // 只为keep-alive 链接增加 'Content-Length' 头.
        response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
        // 根据以下规范增加 keep alive header a头:
        // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
        response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }

    // 编码 cookie.
    String cookieString = request.headers().get(HttpHeaderNames.COOKIE);
    if (cookieString != null) {
        Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(cookieString);
        if (!cookies.isEmpty()) {
            // 重置cookie.
            for (Cookie cookie: cookies) {
                response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie));
            }
        }
    } else {
        // 为浏览器添加一些cookie.
        response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode("key1", "value1"));
        response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode("key2", "value2"));
    }

    // 发送响应内容.
    ctx.write(response);

    return keepAlive;
}
 
Example #26
Source Project: dorado   Author: javagossip   File: HttpRequestImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ai.houyi.dorado.rest.http.Cookie[] getCookies() {
	String cookieString = this.request.headers().get(HttpHeaderNames.COOKIE);
	if (cookieString != null) {
		Set<Cookie> cookies = ServerCookieDecoder.LAX.decode(cookieString);
		return cookies.stream().map(cookie -> new CookieImpl(cookie)).collect(Collectors.toList())
				.toArray(new CookieImpl[] {});
	}
	return null;
}
 
Example #27
Source Project: krpc   Author: bruceran   File: DefaultWebReq.java    License: Apache License 2.0 5 votes vote down vote up
HashMap<String, String> decodeCookie() {
    String cookie = getHeader("cookie");
    if (cookie != null && !cookie.isEmpty()) {
        Set<Cookie> decoded = ServerCookieDecoder.STRICT.decode(cookie);
        if (decoded != null && decoded.size() > 0) {
            HashMap<String, String> m = new HashMap<String, String>();
            for (Cookie c : decoded) {
                m.put(c.name(), c.value());
            }
            return m;
        }
    }
    return new HashMap<String, String>();
}
 
Example #28
Source Project: redant   Author: all4you   File: DefaultCookieManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Set<Cookie> getCookies() {
    HttpRequest request = RedantContext.currentContext().getRequest();
    Set<Cookie> cookies = new HashSet<>();
    if (request != null) {
        String value = request.headers().get(HttpHeaderNames.COOKIE);
        if (value != null) {
            cookies = ServerCookieDecoder.STRICT.decode(value);
        }
    }
    return cookies;
}
 
Example #29
Source Project: spring-boot-starter-netty   Author: Leibnizhu   File: NettyHttpServletRequest.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
     * 解析request中的Cookie到本类的cookies数组中
     *
     * @author Leibniz
     */
    private void parseCookie() {
        if (isCookieParsed) {
            return;
        }

        String cookieOriginStr = this.headers.get("Cookie");
        if (cookieOriginStr == null) {
            return;
        }
        Set<io.netty.handler.codec.http.cookie.Cookie> nettyCookies = ServerCookieDecoder.LAX.decode(cookieOriginStr);
        if (nettyCookies.size() == 0) {
            return;
        }
        this.cookies = new Cookie[nettyCookies.size()];
        Iterator<io.netty.handler.codec.http.cookie.Cookie> itr = nettyCookies.iterator();
        int i = 0;
        while (itr.hasNext()) {
            io.netty.handler.codec.http.cookie.Cookie nettyCookie = itr.next();
            Cookie servletCookie = new Cookie(nettyCookie.name(), nettyCookie.value());
//            servletCookie.setMaxAge(Ints.checkedCast(nettyCookie.maxAge()));
            if(nettyCookie.domain() != null) servletCookie.setDomain(nettyCookie.domain());
            if(nettyCookie.path() != null) servletCookie.setPath(nettyCookie.path());
            servletCookie.setHttpOnly(nettyCookie.isHttpOnly());
            this.cookies[i++] = servletCookie;
        }

        this.isCookieParsed = true;
    }
 
Example #30
Source Project: tools-journey   Author: shoukai   File: HttpSnoopServerHandler.java    License: Apache License 2.0 5 votes vote down vote up
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;
}