io.netty.handler.codec.http.cookie.DefaultCookie Java Examples

The following examples show how to use io.netty.handler.codec.http.cookie.DefaultCookie. 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 File: CookieHelper.java    From wisdom with Apache License 2.0 6 votes vote down vote up
/**
 * Converts the Wisdom's cookie to a Netty's cookie.
 *
 * @param cookie the Wisdom's cookie
 * @return the Netty's cookie with the same metadata and content than the input cookie.
 */
public static DefaultCookie convertWisdomCookieToNettyCookie(Cookie cookie) {
    DefaultCookie nettyCookie = new DefaultCookie(cookie.name(), cookie.value());
    nettyCookie.setMaxAge(cookie.maxAge());
    // Comments are not supported anymore by netty.
    if (cookie.domain() != null) {
        nettyCookie.setDomain(cookie.domain());
    }
    if (cookie.isSecure()) {
        nettyCookie.setSecure(true);
    }
    if (cookie.path() != null) {
        nettyCookie.setPath(cookie.path());
    }
    if (cookie.isHttpOnly()) {
        nettyCookie.setHttpOnly(true);
    }
    return nettyCookie;
}
 
Example #2
Source File: TestVerifyEmailRESTHandler.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
private void mockSetup(UUID personId, String token) {
	EasyMock.expect(client.getPrincipalId()).andReturn(personId).anyTimes();
   EasyMock.expect(request.content()).andReturn(Unpooled.copiedBuffer(generateClientMessage(personId, generateRequest(token)).getBytes()));
   EasyMock.expect(ctx.channel()).andReturn(channel).anyTimes();

   EasyMock.expect(clientFactory.get(channel)).andReturn(client).anyTimes();
   platformMsgCapture = EasyMock.newCapture(CaptureType.ALL);     
   EasyMock.expect(platformBus.send(EasyMock.capture(platformMsgCapture))).andAnswer(
      () -> {
         return Futures.immediateFuture(null);
      }
   ).anyTimes();
   
   
   //logout always needs to be called
   client.logout();
	EasyMock.expectLastCall();   	  	
	EasyMock.expect(authenticator.expireCookie()).andReturn(new DefaultCookie("test", "test"));
}
 
Example #3
Source File: WebRunHandler.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public FullHttpResponse respond(FullHttpRequest req, ChannelHandlerContext ctx) throws Exception {
	Client client = factory.get(ctx.channel());
	RequestInfo info = parseUrl(req, PATH);
	if(StringUtils.isEmpty(info.getToken())) {
		throw new HttpException(HttpResponseStatus.BAD_REQUEST, "Missing token");
	}
	try {
		AppHandoffToken authenticationToken = new AppHandoffToken(info.getToken());
		authenticationToken.setHost(((InetSocketAddress) ctx.channel().remoteAddress()).getHostString());
		authenticationToken.setRememberMe(true);
		client.login(authenticationToken);
		
		FullHttpResponse response = redirect(info.toQueryString(webUrl).toString());
		DefaultCookie cookie = authenticator.createCookie(client.getSessionId());
		response.headers().set(HttpHeaders.Names.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie));
		return response;
	}
	catch(AuthenticationException e) {
		logger.debug("Failed to authenticate token, redirecting to web anyway");
		return redirect(info.toQueryString(webUrl).toString());
	}
}
 
Example #4
Source File: ReactorServerHttpResponse.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
protected void applyCookies() {
	for (String name : getCookies().keySet()) {
		for (ResponseCookie httpCookie : getCookies().get(name)) {
			Cookie cookie = new DefaultCookie(name, httpCookie.getValue());
			if (!httpCookie.getMaxAge().isNegative()) {
				cookie.setMaxAge(httpCookie.getMaxAge().getSeconds());
			}
			if (httpCookie.getDomain() != null) {
				cookie.setDomain(httpCookie.getDomain());
			}
			if (httpCookie.getPath() != null) {
				cookie.setPath(httpCookie.getPath());
			}
			cookie.setSecure(httpCookie.isSecure());
			cookie.setHttpOnly(httpCookie.isHttpOnly());
			this.response.addCookie(cookie);
		}
	}
}
 
Example #5
Source File: HttpRequestOperationTest.java    From styx with 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 #6
Source File: WebSocketHelper.java    From whirlpool with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #7
Source File: ResponseSenderTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
private Set<Cookie> createCookies(int numberOfCookies) {
    if (numberOfCookies < 0) {
        return null;
    }

    Set<Cookie> cookies = new HashSet<>();

    for (int x = 0; x < numberOfCookies; x++) {
        Cookie cookie = new DefaultCookie(UUID.randomUUID().toString(), UUID.randomUUID().toString());
        cookie.setHttpOnly(new Random().ints(0, 1000).findAny().getAsInt() % 2 == 0);
        cookie.setMaxAge(new Random().longs(0, 1000).findAny().getAsLong());
        cookies.add(cookie);
    }

    return cookies;
}
 
Example #8
Source File: HttpServletRequestWrapperForRequestInfoTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void getCookies_returns_cookies_from_requestInfo() {
    // given
    Set<io.netty.handler.codec.http.cookie.Cookie> nettyCookies = new LinkedHashSet<>(Arrays.asList(
        new DefaultCookie(UUID.randomUUID().toString(), UUID.randomUUID().toString()),
        new DefaultCookie(UUID.randomUUID().toString(), UUID.randomUUID().toString())
    ));
    doReturn(nettyCookies).when(requestInfoMock).getCookies();

    List<Cookie> expectedCookieList = nettyCookies
        .stream().map(nc -> new Cookie(nc.name(), nc.value())).collect(Collectors.toList());

    // when
    Cookie[] result = wrapper.getCookies();

    // then
    for (int i = 0; i < result.length; i++) {
        Cookie expected = expectedCookieList.get(i);
        Cookie actual = result[i];
        assertThat(actual.getName()).isEqualTo(expected.getName());
        assertThat(actual.getValue()).isEqualTo(expected.getValue());
    }
}
 
Example #9
Source File: BaseResponseInfoTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void uber_constructor_for_full_response_sets_fields_as_expected() {
    // given
    int httpStatusCode = 200;
    HttpHeaders headers = new DefaultHttpHeaders();
    String mimeType = "text/text";
    Charset contentCharset = CharsetUtil.UTF_8;
    Set<Cookie> cookies = Sets.newHashSet(new DefaultCookie("key1", "val1"), new DefaultCookie("key2", "val2"));
    boolean preventCompressedResponse = true;

    // when
    BaseResponseInfo<?> responseInfo = createNewBaseResponseInfoForTesting(httpStatusCode, headers, mimeType, contentCharset, cookies, preventCompressedResponse);

    // then
    assertThat(responseInfo.getHttpStatusCode(), is(httpStatusCode));
    assertThat(responseInfo.getHeaders(), is(headers));
    assertThat(responseInfo.getDesiredContentWriterMimeType(), is(mimeType));
    assertThat(responseInfo.getDesiredContentWriterEncoding(), is(contentCharset));
    assertThat(responseInfo.getCookies(), is(cookies));
    assertThat(responseInfo.getUncompressedRawContentLength(), nullValue());
    assertThat(responseInfo.isPreventCompressedOutput(), is(preventCompressedResponse));
    assertThat(responseInfo.isResponseSendingStarted(), is(false));
    assertThat(responseInfo.isResponseSendingLastChunkSent(), is(false));
}
 
Example #10
Source File: HttpUtilsTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void extractCookies_works_if_cookies_defined_in_trailing_headers() {
    // given
    Cookie cookie1 = new DefaultCookie(UUID.randomUUID().toString(), UUID.randomUUID().toString());
    Cookie cookie2 = new DefaultCookie(UUID.randomUUID().toString(), UUID.randomUUID().toString());
    HttpHeaders trailingHeaders = new DefaultHttpHeaders().add(HttpHeaders.Names.COOKIE, ClientCookieEncoder.LAX.encode(cookie1, cookie2));

    FullHttpRequest nettyRequestMock = mock(FullHttpRequest.class);
    doReturn(new DefaultHttpHeaders()).when(nettyRequestMock).headers();
    doReturn(trailingHeaders).when(nettyRequestMock).trailingHeaders();

    // when
    Set<Cookie> extractedCookies = HttpUtils.extractCookies(nettyRequestMock);

    // then
    assertThat(extractedCookies.contains(cookie1), is(true));
    assertThat(extractedCookies.contains(cookie2), is(true));
}
 
Example #11
Source File: ReactorServerHttpResponse.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected void applyCookies() {
	for (String name : getCookies().keySet()) {
		for (ResponseCookie httpCookie : getCookies().get(name)) {
			Cookie cookie = new DefaultCookie(name, httpCookie.getValue());
			if (!httpCookie.getMaxAge().isNegative()) {
				cookie.setMaxAge(httpCookie.getMaxAge().getSeconds());
			}
			if (httpCookie.getDomain() != null) {
				cookie.setDomain(httpCookie.getDomain());
			}
			if (httpCookie.getPath() != null) {
				cookie.setPath(httpCookie.getPath());
			}
			cookie.setSecure(httpCookie.isSecure());
			cookie.setHttpOnly(httpCookie.isHttpOnly());
			this.response.addCookie(cookie);
		}
	}
}
 
Example #12
Source File: SessionAwareWebClientTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadManyCookies(TestContext context) {
  Async async = context.async();
  prepareServer(context, req -> {
    req.response().headers().add("set-cookie", ServerCookieEncoder.STRICT.encode(new DefaultCookie("test1", "toast1")));
    req.response().headers().add("set-cookie", ServerCookieEncoder.STRICT.encode(new DefaultCookie("test2", "toast2")));
    req.response().headers().add("set-cookie", ServerCookieEncoder.STRICT.encode(new DefaultCookie("test3", "toast3")));
  });

  client.get(PORT, "localhost", "/").send(ar -> {
    context.assertTrue(ar.succeeded());
    validate(context, client.cookieStore().get(false, "localhost", "/"),
        new String[] { "test1" ,"test2", "test3" }, new String[] { "toast1", "toast2", "toast3" });
    async.complete();
  });
}
 
Example #13
Source File: HttpSessionManager.java    From glowroot with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #14
Source File: Response.java    From netty-rest with Apache License 2.0 6 votes vote down vote up
public Response addCookie(String name, String value, String domain, Boolean isHttpOnly, Long maxAge, String path, Boolean isSecured) {
    if(cookies == null) {
        cookies = Lists.newArrayList();
    }
    final DefaultCookie defaultCookie = new DefaultCookie(name, value);
    if(domain != null) {
        defaultCookie.setDomain(domain);
    }
    if(isHttpOnly != null) {
        defaultCookie.setHttpOnly(isHttpOnly);
    }
    if(maxAge != null) {
        defaultCookie.setMaxAge(maxAge);
    }
    if(path != null) {
        defaultCookie.setPath(path);
    }
    if(isSecured != null) {
        defaultCookie.setSecure(isSecured);
    }
    cookies.add(defaultCookie);
    return this;
}
 
Example #15
Source File: EppServiceHandlerTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccess_setCookies() throws Exception {
  setHandshakeSuccess();
  // First inbound message is hello.
  channel.readInbound();
  String responseContent = "<epp>response</epp>";
  Cookie cookie1 = new DefaultCookie("name1", "value1");
  Cookie cookie2 = new DefaultCookie("name2", "value2");
  channel.writeOutbound(
      makeEppHttpResponse(responseContent, HttpResponseStatus.OK, cookie1, cookie2));
  ByteBuf response = channel.readOutbound();
  assertThat(response).isEqualTo(Unpooled.wrappedBuffer(responseContent.getBytes(UTF_8)));
  String requestContent = "<epp>request</epp>";
  channel.writeInbound(Unpooled.wrappedBuffer(requestContent.getBytes(UTF_8)));
  FullHttpRequest request = channel.readInbound();
  assertHttpRequestEquivalent(request, makeEppHttpRequest(requestContent, cookie1, cookie2));
  // Nothing further to pass to the next handler.
  assertThat((Object) channel.readInbound()).isNull();
  assertThat((Object) channel.readOutbound()).isNull();
  assertThat(channel.isActive()).isTrue();
}
 
Example #16
Source File: HttpClient.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
/**
 * Apply cookies configuration emitted by the returned Mono before requesting.
 *
 * @param cookieBuilder the cookies {@link Function} to invoke before sending
 *
 * @return a new {@link HttpClient}
 */
public final HttpClient cookiesWhen(String name, Function<? super Cookie, Mono<? extends Cookie>> cookieBuilder) {
	Objects.requireNonNull(name, "name");
	Objects.requireNonNull(cookieBuilder, "cookieBuilder");
	HttpClient dup = duplicate();
	dup.configuration().deferredConf(config ->
			cookieBuilder.apply(new DefaultCookie(name, ""))
			             .map(c -> {
			                 if (!c.value().isEmpty()) {
			                     HttpHeaders headers = configuration().headers.copy();
			                     headers.add(HttpHeaderNames.COOKIE, config.cookieEncoder.encode(c));
			                     config.headers = headers;
			                 }
			                 return config;
			             }));
	return dup;
}
 
Example #17
Source File: HttpUtilsTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void extractCookies_handles_cookie_values_leniently() {
    // given
    //these are cookie values seen in the wild...
    Cookie cookie1 = new DefaultCookie(UUID.randomUUID().toString(), "2094%3Az%7C2021%3Ab");
    Cookie cookie2 = new DefaultCookie(UUID.randomUUID().toString(), "geoloc=cc=US,rc=OR,tp=vhigh,tz=PST,la=45.4978,lo=-122.6937,bw=5000");
    Cookie cookie3 = new DefaultCookie(UUID.randomUUID().toString(), "\"dm=n.com&si=27431295-a282-4745-8cd5-542e7fce" +
            "429e&ss=1477551008358&sl=76&tt=437632&obo=12&sh=1477552753923%3D76%3A12%3A437632%2C1477552698670%3D75%3" +
            "A12%3A429879%2C1477552677137%3D74%3A12%3A426596%2C1477552672564%3D73%3A12%3A425585%2C1477552669893%3D72" +
            "%3A12%3A423456&bcn=%2F%2F3408178b.mpstat.us%2F&ld=1477552753923&r=http%3A%2F%2Fwww.nike.com%2Fbe%2Fde_de%" +
            "2F&ul=1477552756811\"");
    HttpHeaders headers = new DefaultHttpHeaders().add(HttpHeaders.Names.COOKIE, ClientCookieEncoder.LAX.encode(cookie1, cookie2, cookie3));

    HttpRequest nettyRequestMock = mock(HttpRequest.class);
    doReturn(headers).when(nettyRequestMock).headers();

    // when
    Set<Cookie> extractedCookies = HttpUtils.extractCookies(nettyRequestMock);

    // then
    assertThat(extractedCookies.contains(cookie1), is(true));
    assertThat(extractedCookies.contains(cookie2), is(true));
    assertThat(extractedCookies.contains(cookie3), is(true));
}
 
Example #18
Source File: HttpUtilsTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void extractCookies_works_if_cookies_defined_in_headers() {
    // given
    Cookie cookie1 = new DefaultCookie(UUID.randomUUID().toString(), UUID.randomUUID().toString());
    Cookie cookie2 = new DefaultCookie(UUID.randomUUID().toString(), UUID.randomUUID().toString());
    HttpHeaders headers = new DefaultHttpHeaders().add(HttpHeaders.Names.COOKIE, ClientCookieEncoder.LAX.encode(cookie1, cookie2));

    HttpRequest nettyRequestMock = mock(HttpRequest.class);
    doReturn(headers).when(nettyRequestMock).headers();

    // when
    Set<Cookie> extractedCookies = HttpUtils.extractCookies(nettyRequestMock);

    // then
    assertThat(extractedCookies.contains(cookie1), is(true));
    assertThat(extractedCookies.contains(cookie2), is(true));
}
 
Example #19
Source File: HttpResponse.java    From blade with Apache License 2.0 5 votes vote down vote up
@Override
public Response cookie(@NonNull String name, @NonNull String value, int maxAge, boolean secured) {
    Cookie nettyCookie = new io.netty.handler.codec.http.cookie.DefaultCookie(name, value);
    nettyCookie.setPath("/");
    nettyCookie.setMaxAge(maxAge);
    nettyCookie.setSecure(secured);
    this.cookies.add(nettyCookie);
    return this;
}
 
Example #20
Source File: FullResponseInfoTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Test
public void uber_constructor_for_full_response_sets_fields_as_expected() {
    // given
    String content = UUID.randomUUID().toString();
    int httpStatusCode = 200;
    HttpHeaders headers = new DefaultHttpHeaders();
    String mimeType = "text/text";
    Charset contentCharset = CharsetUtil.UTF_8;
    Set<Cookie> cookies = Sets.newHashSet(new DefaultCookie("key1", "val1"), new DefaultCookie("key2", "val2"));
    boolean preventCompressedResponse = true;

    // when
    FullResponseInfo<String> responseInfo = new FullResponseInfo<>(content, httpStatusCode, headers, mimeType, contentCharset, cookies, preventCompressedResponse);

    // then
    assertThat(responseInfo.getContentForFullResponse(), is(content));
    assertThat(responseInfo.getHttpStatusCode(), is(httpStatusCode));
    assertThat(responseInfo.getHeaders(), is(headers));
    assertThat(responseInfo.getDesiredContentWriterMimeType(), is(mimeType));
    assertThat(responseInfo.getDesiredContentWriterEncoding(), is(contentCharset));
    assertThat(responseInfo.getCookies(), is(cookies));
    assertThat(responseInfo.getUncompressedRawContentLength(), nullValue());
    assertThat(responseInfo.getFinalContentLength(), nullValue());
    assertThat(responseInfo.isPreventCompressedOutput(), is(preventCompressedResponse));
    assertThat(responseInfo.isChunkedResponse(), is(false));
    assertThat(responseInfo.isResponseSendingStarted(), is(false));
    assertThat(responseInfo.isResponseSendingLastChunkSent(), is(false));
}
 
Example #21
Source File: FullResponseInfoTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Test
public void builder_sets_values_as_expected() {
    // given
    String content = UUID.randomUUID().toString();
    int httpStatusCode = 200;
    HttpHeaders headers = new DefaultHttpHeaders();
    String mimeType = "text/text";
    Charset contentCharset = CharsetUtil.ISO_8859_1;
    Set<Cookie> cookies = Sets.newHashSet(new DefaultCookie("key1", "val1"), new DefaultCookie("key2", "val2"));
    boolean preventCompressedOutput = true;

    // when
    FullResponseInfo<String> responseInfo = ResponseInfo.<String>newBuilder()
                                                    .withContentForFullResponse(content)
                                                    .withHttpStatusCode(httpStatusCode)
                                                    .withHeaders(headers)
                                                    .withDesiredContentWriterMimeType(mimeType)
                                                    .withDesiredContentWriterEncoding(contentCharset).withCookies(cookies)
                                                    .withPreventCompressedOutput(preventCompressedOutput).build();

    // then
    assertThat(responseInfo.getContentForFullResponse(), is(content));
    assertThat(responseInfo.getHttpStatusCode(), is(httpStatusCode));
    assertThat(responseInfo.getHeaders(), is(headers));
    assertThat(responseInfo.getDesiredContentWriterMimeType(), is(mimeType));
    assertThat(responseInfo.getDesiredContentWriterEncoding(), is(contentCharset));
    assertThat(responseInfo.getCookies(), is(cookies));
    assertThat(responseInfo.getUncompressedRawContentLength(), nullValue());
    assertThat(responseInfo.getFinalContentLength(), nullValue());
    assertThat(responseInfo.isPreventCompressedOutput(), is(preventCompressedOutput));
    assertThat(responseInfo.isChunkedResponse(), is(false));
    assertThat(responseInfo.isResponseSendingStarted(), is(false));
    assertThat(responseInfo.isResponseSendingLastChunkSent(), is(false));
}
 
Example #22
Source File: ChunkedResponseInfoTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Test
public void uber_constructor_for_chunked_response_sets_fields_as_expected() {
    // given
    int httpStatusCode = 200;
    HttpHeaders headers = new DefaultHttpHeaders();
    String mimeType = "text/text";
    Charset contentCharset = CharsetUtil.UTF_8;
    Set<Cookie> cookies = Sets.newHashSet(new DefaultCookie("key1", "val1"), new DefaultCookie("key2", "val2"));
    boolean preventCompressedResponse = true;

    // when
    ChunkedResponseInfo responseInfo = new ChunkedResponseInfo(httpStatusCode, headers, mimeType, contentCharset, cookies, preventCompressedResponse);

    // then
    assertThat(responseInfo.getHttpStatusCode(), is(httpStatusCode));
    assertThat(responseInfo.getHeaders(), is(headers));
    assertThat(responseInfo.getDesiredContentWriterMimeType(), is(mimeType));
    assertThat(responseInfo.getDesiredContentWriterEncoding(), is(contentCharset));
    assertThat(responseInfo.getCookies(), is(cookies));
    assertThat(responseInfo.getUncompressedRawContentLength(), nullValue());
    assertThat(responseInfo.getFinalContentLength(), nullValue());
    assertThat(responseInfo.isPreventCompressedOutput(), is(preventCompressedResponse));
    assertThat(responseInfo.isChunkedResponse(), is(true));
    assertThat(responseInfo.isResponseSendingStarted(), is(false));
    assertThat(responseInfo.isResponseSendingLastChunkSent(), is(false));

}
 
Example #23
Source File: SessionLogoutResponder.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public void sendResponse(FullHttpRequest req, ChannelHandlerContext ctx) throws Exception {
   try {
      logger.debug("User requested logout");
      factory.get(ctx.channel()).logout();
   } catch (Throwable t) {
      logger.debug("Error attempting to logout current user", t);
   } finally {
      DefaultFullHttpResponse resp = new DefaultFullHttpResponse(HTTP_1_1, UNAUTHORIZED);
      DefaultCookie nettyCookie = authenticator.expireCookie();
      resp.headers().set(HttpHeaders.Names.SET_COOKIE, ServerCookieEncoder.STRICT.encode(nettyCookie)); 
      httpSender.sendHttpResponse(ctx, req, resp);
   }
}
 
Example #24
Source File: EppServiceHandlerTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testSuccess_updateCookies() throws Exception {
  setHandshakeSuccess();
  // First inbound message is hello.
  channel.readInbound();
  String responseContent1 = "<epp>response1</epp>";
  Cookie cookie1 = new DefaultCookie("name1", "value1");
  Cookie cookie2 = new DefaultCookie("name2", "value2");
  // First response written.
  channel.writeOutbound(
      makeEppHttpResponse(responseContent1, HttpResponseStatus.OK, cookie1, cookie2));
  channel.readOutbound();
  String requestContent1 = "<epp>request1</epp>";
  // First request written.
  channel.writeInbound(Unpooled.wrappedBuffer(requestContent1.getBytes(UTF_8)));
  FullHttpRequest request1 = channel.readInbound();
  assertHttpRequestEquivalent(request1, makeEppHttpRequest(requestContent1, cookie1, cookie2));
  String responseContent2 = "<epp>response2</epp>";
  Cookie cookie3 = new DefaultCookie("name3", "value3");
  Cookie newCookie2 = new DefaultCookie("name2", "newValue");
  // Second response written.
  channel.writeOutbound(
      makeEppHttpResponse(responseContent2, HttpResponseStatus.OK, cookie3, newCookie2));
  channel.readOutbound();
  String requestContent2 = "<epp>request2</epp>";
  // Second request written.
  channel.writeInbound(Unpooled.wrappedBuffer(requestContent2.getBytes(UTF_8)));
  FullHttpRequest request2 = channel.readInbound();
  // Cookies in second request should be updated.
  assertHttpRequestEquivalent(
      request2, makeEppHttpRequest(requestContent2, cookie1, newCookie2, cookie3));
  // Nothing further to pass to the next handler.
  assertThat((Object) channel.readInbound()).isNull();
  assertThat((Object) channel.readOutbound()).isNull();
  assertThat(channel.isActive()).isTrue();
}
 
Example #25
Source File: Response.java    From netty-rest with Apache License 2.0 5 votes vote down vote up
public Response addCookie(DefaultCookie cookie) {
    if(cookies == null) {
        cookies = Lists.newArrayList();
    }
    cookies.add(cookie);
    return this;
}
 
Example #26
Source File: Response.java    From netty-rest with Apache License 2.0 5 votes vote down vote up
public Response addCookie(String name, String value) {
    if(cookies == null) {
        cookies = Lists.newArrayList();
    }
    cookies.add(new DefaultCookie(name, value));
    return this;
}
 
Example #27
Source File: HttpResponse.java    From blade with Apache License 2.0 5 votes vote down vote up
@Override
public Response cookie(@NonNull String name, @NonNull String value, int maxAge) {
    Cookie nettyCookie = new io.netty.handler.codec.http.cookie.DefaultCookie(name, value);
    nettyCookie.setPath("/");
    nettyCookie.setMaxAge(maxAge);
    this.cookies.add(nettyCookie);
    return this;
}
 
Example #28
Source File: SessionAwareWebClientTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testCookieStoreIsFluent(TestContext context) {
  CookieStore store = CookieStore.build();
  Cookie cookie = new DefaultCookie("a", "a");
  context.assertTrue(store == store.put(cookie));
  context.assertTrue(store == store.remove(cookie));
}
 
Example #29
Source File: TestRequestEmailVerificationRESTHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private Capture<Person> mockSetup(Person curPerson, boolean personExist, boolean principalMatch, String source, int times) {
	EasyMock.expect(client.getPrincipalId()).andReturn(curPerson.getId()).times(times);
   EasyMock.expect(request.content()).andReturn(Unpooled.copiedBuffer(generateClientMessage(curPerson.getId(), generateRequest(source)).getBytes())).times(times);
   EasyMock.expect(ctx.channel()).andReturn(channel).times(times);

   EasyMock.expect(clientFactory.get(channel)).andReturn(client).times(times);
   platformMsgCapture = EasyMock.newCapture(CaptureType.ALL);     
   EasyMock.expect(platformBus.send(EasyMock.capture(platformMsgCapture))).andAnswer(
      () -> {
         return Futures.immediateFuture(null);
      }
   ).anyTimes();
   
   
   //logout always needs to be called
   client.logout();
	EasyMock.expectLastCall().times(times);   	  	
	EasyMock.expect(authenticator.expireCookie()).andReturn(new DefaultCookie("test", "test")).times(times);
	
	if(principalMatch) {
		EasyMock.expect(client.getPrincipalName()).andReturn(curPerson.getEmail()).times(times);   	
	}else{
		EasyMock.expect(client.getPrincipalName()).andReturn("[email protected]").times(times); 
	}
	if(personExist) {
		EasyMock.expect(personDao.findById(curPerson.getId())).andReturn(curPerson).times(times);
	}else{
		EasyMock.expect(personDao.findById(curPerson.getId())).andReturn(null).times(times);
	}
	Capture<Person> personUpdatedCapture = EasyMock.newCapture(CaptureType.ALL);
	EasyMock.expect(personDao.update(EasyMock.capture(personUpdatedCapture))).andReturn(curPerson).times(times);
	
	EasyMock.expect(mockPersonPlaceAssocDAO.findPlaceIdsByPerson(curPerson.getId())).andReturn(ImmutableSet.<UUID>of(curPerson.getCurrPlace())).anyTimes();
	
	return personUpdatedCapture;
}
 
Example #30
Source File: SessionAwareWebClientTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadCookie(TestContext context) {
  Async async = context.async();
  prepareServer(context, req -> {
    req.response().headers().add("set-cookie", ServerCookieEncoder.STRICT.encode(new DefaultCookie("test", "toast")));
  });

  client.get(PORT, "localhost", "/").send(ar -> {
    context.assertTrue(ar.succeeded());
    validate(context, client.cookieStore().get(false, "localhost", "/"),
        new String[] { "test" }, new String[] { "toast" });
    async.complete();
  });
}