org.springframework.http.HttpCookie Java Examples

The following examples show how to use org.springframework.http.HttpCookie. 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: ServletServerHttpRequest.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected MultiValueMap<String, HttpCookie> initCookies() {
	MultiValueMap<String, HttpCookie> httpCookies = new LinkedMultiValueMap<>();
	Cookie[] cookies;
	synchronized (this.cookieLock) {
		cookies = this.request.getCookies();
	}
	if (cookies != null) {
		for (Cookie cookie : cookies) {
			String name = cookie.getName();
			HttpCookie httpCookie = new HttpCookie(name, cookie.getValue());
			httpCookies.add(name, httpCookie);
		}
	}
	return httpCookies;
}
 
Example #2
Source File: CookieCsrfFilterTest.java    From jhipster with Apache License 2.0 6 votes vote down vote up
@Test
public void cookieNotSetIfTokenInRequest() {
    WebFilterChain filterChain = (filterExchange) -> {
        try {
            assertThat(filterExchange.getResponse().getCookies().getFirst(CSRF_COOKIE_NAME)).isNull();
        } catch (AssertionError ex) {
            return Mono.error(ex);
        }
        return Mono.empty();
    };
    MockServerWebExchange exchange = MockServerWebExchange.from(
        MockServerHttpRequest
            .post(TEST_URL)
            .cookie(new HttpCookie(CSRF_COOKIE_NAME, "csrf_token"))
    );
    exchange.getAttributes().put(CsrfToken.class.getName(), Mono.just(new DefaultCsrfToken(CSRF_COOKIE_NAME, "_csrf", "some token")));
    this.filter.filter(exchange, filterChain).block();
}
 
Example #3
Source File: ArmeriaServerHttpRequestTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void getCookies() {
    final HttpRequest httpRequest = HttpRequest.of(RequestHeaders.builder(HttpMethod.POST, "/")
                                                                 .scheme("http")
                                                                 .authority("127.0.0.1")
                                                                 .add(HttpHeaderNames.COOKIE, "a=1;b=2")
                                                                 .build());
    final ServiceRequestContext ctx = newRequestContext(httpRequest);
    final ArmeriaServerHttpRequest req = request(ctx);

    // Check cached.
    final MultiValueMap<String, HttpCookie> cookie1 = req.getCookies();
    final MultiValueMap<String, HttpCookie> cookie2 = req.getCookies();
    assertThat(cookie1 == cookie2).isTrue();

    assertThat(cookie1.get("a")).containsExactly(new HttpCookie("a", "1"));
    assertThat(cookie1.get("b")).containsExactly(new HttpCookie("b", "2"));
}
 
Example #4
Source File: ServletServerHttpRequest.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
protected MultiValueMap<String, HttpCookie> initCookies() {
	MultiValueMap<String, HttpCookie> httpCookies = new LinkedMultiValueMap<>();
	Cookie[] cookies;
	synchronized (this.cookieLock) {
		cookies = this.request.getCookies();
	}
	if (cookies != null) {
		for (Cookie cookie : cookies) {
			String name = cookie.getName();
			HttpCookie httpCookie = new HttpCookie(name, cookie.getValue());
			httpCookies.add(name, httpCookie);
		}
	}
	return httpCookies;
}
 
Example #5
Source File: ClientHttpRequestCookieExtractor.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@Override
public String getCookie(final ClientHttpRequest request) {
    if (request != null && request.getCookies() != null) {
        final StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, List<HttpCookie>> entry : request.getCookies().entrySet()) {
            boolean repeated = false;
            for (HttpCookie httpCookie : entry.getValue()) {
                if (repeated) {
                    sb.append(',');
                }
                sb.append(httpCookie.getName());
                sb.append('=');
                sb.append(httpCookie.getValue());
                repeated = true;
            }
        }
        if (isDebug) {
            logger.debug("Cookie={}", sb.toString());
        }
        return sb.toString();
    }
    return null;
}
 
Example #6
Source File: GoldenCustomerRoutePredicateFactory.java    From tutorials with MIT License 6 votes vote down vote up
@Override
public Predicate<ServerWebExchange> apply(Config config) {
    
    return (ServerWebExchange t) -> {
        List<HttpCookie> cookies = t.getRequest()
          .getCookies()
          .get(config.getCustomerIdCookie());
          
        boolean isGolden; 
        if ( cookies == null || cookies.isEmpty()) {
            isGolden = false;
        }
        else {                
            String customerId = cookies.get(0).getValue();                
            isGolden = goldenCustomerService.isGoldenCustomer(customerId);
        }
          
        return config.isGolden()?isGolden:!isGolden;           
    };
}
 
Example #7
Source File: MockServerRequest.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private MockServerRequest(HttpMethod method, URI uri, String contextPath, MockHeaders headers,
		MultiValueMap<String, HttpCookie> cookies, @Nullable Object body,
		Map<String, Object> attributes, MultiValueMap<String, String> queryParams,
		Map<String, String> pathVariables, @Nullable WebSession session, @Nullable Principal principal,
		@Nullable InetSocketAddress remoteAddress, List<HttpMessageReader<?>> messageReaders,
		@Nullable ServerWebExchange exchange) {

	this.method = method;
	this.uri = uri;
	this.pathContainer = RequestPath.parse(uri, contextPath);
	this.headers = headers;
	this.cookies = cookies;
	this.body = body;
	this.attributes = attributes;
	this.queryParams = queryParams;
	this.pathVariables = pathVariables;
	this.session = session;
	this.principal = principal;
	this.remoteAddress = remoteAddress;
	this.messageReaders = messageReaders;
	this.exchange = exchange;
}
 
Example #8
Source File: CookieValueMethodArgumentResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected Object resolveNamedValue(String name, MethodParameter parameter, ServerWebExchange exchange) {
	HttpCookie cookie = exchange.getRequest().getCookies().getFirst(name);
	Class<?> paramType = parameter.getNestedParameterType();
	if (HttpCookie.class.isAssignableFrom(paramType)) {
		return cookie;
	}
	return (cookie != null ? cookie.getValue() : null);
}
 
Example #9
Source File: CookieValueMethodArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@SuppressWarnings("unused")
public void params(
		@CookieValue("name") HttpCookie cookie,
		@CookieValue(name = "name", defaultValue = "bar") String cookieString,
		String stringParam,
		@CookieValue Mono<String> monoCookie) {
}
 
Example #10
Source File: DefaultServerHttpRequestBuilder.java    From spring-analysis-note with MIT License 5 votes vote down vote up
public MutatedServerHttpRequest(URI uri, @Nullable String contextPath,
		HttpHeaders headers, String methodValue, MultiValueMap<String, HttpCookie> cookies,
		@Nullable SslInfo sslInfo, Flux<DataBuffer> body, ServerHttpRequest originalRequest) {

	super(uri, contextPath, headers);
	this.methodValue = methodValue;
	this.cookies = cookies;
	this.remoteAddress = originalRequest.getRemoteAddress();
	this.sslInfo = sslInfo != null ? sslInfo : originalRequest.getSslInfo();
	this.body = body;
	this.originalRequest = originalRequest;
}
 
Example #11
Source File: ReactorServerHttpRequest.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected MultiValueMap<String, HttpCookie> initCookies() {
	MultiValueMap<String, HttpCookie> cookies = new LinkedMultiValueMap<>();
	for (CharSequence name : this.request.cookies().keySet()) {
		for (Cookie cookie : this.request.cookies().get(name)) {
			HttpCookie httpCookie = new HttpCookie(name.toString(), cookie.value());
			cookies.add(name.toString(), httpCookie);
		}
	}
	return cookies;
}
 
Example #12
Source File: CookieConverter.java    From vertx-spring-boot with Apache License 2.0 5 votes vote down vote up
private static ResponseCookie toResponseCookie(java.net.HttpCookie cookie) {
    return ResponseCookie.from(cookie.getName(), cookie.getValue())
        .domain(cookie.getDomain())
        .httpOnly(cookie.isHttpOnly())
        .maxAge(cookie.getMaxAge())
        .path(cookie.getPath())
        .secure(cookie.getSecure())
        .build();
}
 
Example #13
Source File: AbstractClientHttpRequest.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public MultiValueMap<String, HttpCookie> getCookies() {
	if (State.COMMITTED.equals(this.state.get())) {
		return CollectionUtils.unmodifiableMultiValueMap(this.cookies);
	}
	return this.cookies;
}
 
Example #14
Source File: CookieValueMethodArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void resolveCookieStringArgument() {
	HttpCookie cookie = new HttpCookie("name", "foo");
	MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").cookie(cookie));

	Mono<Object> mono = this.resolver.resolveArgument(
			this.cookieStringParameter, this.bindingContext, exchange);

	assertEquals("Invalid result", cookie.getValue(), mono.block());
}
 
Example #15
Source File: UndertowServerHttpRequest.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected MultiValueMap<String, HttpCookie> initCookies() {
	MultiValueMap<String, HttpCookie> cookies = new LinkedMultiValueMap<>();
	for (String name : this.exchange.getRequestCookies().keySet()) {
		Cookie cookie = this.exchange.getRequestCookies().get(name);
		HttpCookie httpCookie = new HttpCookie(name, cookie.getValue());
		cookies.add(name, httpCookie);
	}
	return cookies;
}
 
Example #16
Source File: DefaultServerRequestBuilder.java    From spring-analysis-note with MIT License 5 votes vote down vote up
public BuiltServerHttpRequest(String id, String method, URI uri, HttpHeaders headers,
		MultiValueMap<String, HttpCookie> cookies, Flux<DataBuffer> body) {

	this.id = id;
	this.method = method;
	this.uri = uri;
	this.path = RequestPath.parse(uri, null);
	this.headers = HttpHeaders.readOnlyHttpHeaders(headers);
	this.cookies = unmodifiableCopy(cookies);
	this.queryParams = parseQueryParams(uri);
	this.body = body;
}
 
Example #17
Source File: AbstractServerHttpRequest.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public MultiValueMap<String, HttpCookie> getCookies() {
	if (this.cookies == null) {
		this.cookies = CollectionUtils.unmodifiableMultiValueMap(initCookies());
	}
	return this.cookies;
}
 
Example #18
Source File: DefaultClientRequestBuilder.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Mono<Void> writeTo(ClientHttpRequest request, ExchangeStrategies strategies) {
	HttpHeaders requestHeaders = request.getHeaders();
	if (!this.headers.isEmpty()) {
		this.headers.entrySet().stream()
				.filter(entry -> !requestHeaders.containsKey(entry.getKey()))
				.forEach(entry -> requestHeaders
						.put(entry.getKey(), entry.getValue()));
	}

	MultiValueMap<String, HttpCookie> requestCookies = request.getCookies();
	if (!this.cookies.isEmpty()) {
		this.cookies.forEach((name, values) -> values.forEach(value -> {
			HttpCookie cookie = new HttpCookie(name, value);
			requestCookies.add(name, cookie);
		}));
	}

	return this.body.insert(request, new BodyInserter.Context() {
		@Override
		public List<HttpMessageWriter<?>> messageWriters() {
			return strategies.messageWriters();
		}
		@Override
		public Optional<ServerHttpRequest> serverRequest() {
			return Optional.empty();
		}
		@Override
		public Map<String, Object> hints() {
			return Hints.from(Hints.LOG_PREFIX_HINT, logPrefix());
		}
	});
}
 
Example #19
Source File: UndertowServerHttpRequest.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected MultiValueMap<String, HttpCookie> initCookies() {
	MultiValueMap<String, HttpCookie> cookies = new LinkedMultiValueMap<>();
	for (String name : this.exchange.getRequestCookies().keySet()) {
		Cookie cookie = this.exchange.getRequestCookies().get(name);
		HttpCookie httpCookie = new HttpCookie(name, cookie.getValue());
		cookies.add(name, httpCookie);
	}
	return cookies;
}
 
Example #20
Source File: AbstractServerHttpRequest.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public MultiValueMap<String, HttpCookie> getCookies() {
	if (this.cookies == null) {
		this.cookies = CollectionUtils.unmodifiableMultiValueMap(initCookies());
	}
	return this.cookies;
}
 
Example #21
Source File: CookieWebSessionIdResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public List<String> resolveSessionIds(ServerWebExchange exchange) {
	MultiValueMap<String, HttpCookie> cookieMap = exchange.getRequest().getCookies();
	List<HttpCookie> cookies = cookieMap.get(getCookieName());
	if (cookies == null) {
		return Collections.emptyList();
	}
	return cookies.stream().map(HttpCookie::getValue).collect(Collectors.toList());
}
 
Example #22
Source File: MockServerHttpRequest.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private MockServerHttpRequest(HttpMethod httpMethod, URI uri, @Nullable String contextPath,
		HttpHeaders headers, MultiValueMap<String, HttpCookie> cookies,
		@Nullable InetSocketAddress remoteAddress, @Nullable SslInfo sslInfo,
		Publisher<? extends DataBuffer> body) {

	super(uri, contextPath, headers);
	this.httpMethod = httpMethod;
	this.cookies = cookies;
	this.remoteAddress = remoteAddress;
	this.sslInfo = sslInfo;
	this.body = Flux.from(body);
}
 
Example #23
Source File: MockServerHttpRequest.java    From java-technology-stack with MIT License 5 votes vote down vote up
private MockServerHttpRequest(HttpMethod httpMethod, URI uri, @Nullable String contextPath,
		HttpHeaders headers, MultiValueMap<String, HttpCookie> cookies,
		@Nullable InetSocketAddress remoteAddress, @Nullable SslInfo sslInfo,
		Publisher<? extends DataBuffer> body) {

	super(uri, contextPath, headers);
	this.httpMethod = httpMethod;
	this.cookies = cookies;
	this.remoteAddress = remoteAddress;
	this.sslInfo = sslInfo;
	this.body = Flux.from(body);
}
 
Example #24
Source File: CookieIntegrationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void basicTest() throws Exception {
	URI url = new URI("http://localhost:" + port);
	String header = "SID=31d4d96e407aad42; lang=en-US";
	ResponseEntity<Void> response = new RestTemplate().exchange(
			RequestEntity.get(url).header("Cookie", header).build(), Void.class);

	Map<String, List<HttpCookie>> requestCookies = this.cookieHandler.requestCookies;
	assertEquals(2, requestCookies.size());

	List<HttpCookie> list = requestCookies.get("SID");
	assertEquals(1, list.size());
	assertEquals("31d4d96e407aad42", list.iterator().next().getValue());

	list = requestCookies.get("lang");
	assertEquals(1, list.size());
	assertEquals("en-US", list.iterator().next().getValue());

	List<String> headerValues = response.getHeaders().get("Set-Cookie");
	assertEquals(2, headerValues.size());

	assertThat(splitCookie(headerValues.get(0)), containsInAnyOrder(equalTo("SID=31d4d96e407aad42"),
			equalToIgnoringCase("Path=/"), equalToIgnoringCase("Secure"), equalToIgnoringCase("HttpOnly")));

	assertThat(splitCookie(headerValues.get(1)), containsInAnyOrder(equalTo("lang=en-US"),
			equalToIgnoringCase("Path=/"), equalToIgnoringCase("Domain=example.com")));
}
 
Example #25
Source File: HttpHandlerConnector.java    From java-technology-stack with MIT License 5 votes vote down vote up
private ServerHttpRequest adaptRequest(MockClientHttpRequest request, Publisher<DataBuffer> body) {
	HttpMethod method = request.getMethod();
	URI uri = request.getURI();
	HttpHeaders headers = request.getHeaders();
	MultiValueMap<String, HttpCookie> cookies = request.getCookies();
	return MockServerHttpRequest.method(method, uri).headers(headers).cookies(cookies).body(body);
}
 
Example #26
Source File: MockServerHttpRequest.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private MockServerHttpRequest(HttpMethod httpMethod, URI uri, @Nullable String contextPath,
		HttpHeaders headers, MultiValueMap<String, HttpCookie> cookies,
		@Nullable InetSocketAddress remoteAddress, @Nullable SslInfo sslInfo,
		Publisher<? extends DataBuffer> body) {

	super(uri, contextPath, headers);
	this.httpMethod = httpMethod;
	this.cookies = cookies;
	this.remoteAddress = remoteAddress;
	this.sslInfo = sslInfo;
	this.body = Flux.from(body);
}
 
Example #27
Source File: VertxServerHttpRequest.java    From vertx-spring-boot with Apache License 2.0 5 votes vote down vote up
@Override
protected MultiValueMap<String, HttpCookie> initCookies() {
    MultiValueMap<String, HttpCookie> cookies = new LinkedMultiValueMap<>();

    context.cookieMap()
        .values()
        .stream()
        .map(CookieConverter::toHttpCookie)
        .forEach(cookie -> cookies.add(cookie.getName(), cookie));

    return cookies;
}
 
Example #28
Source File: CookieIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void basicTest() throws Exception {
	URI url = new URI("http://localhost:" + port);
	String header = "SID=31d4d96e407aad42; lang=en-US";
	ResponseEntity<Void> response = new RestTemplate().exchange(
			RequestEntity.get(url).header("Cookie", header).build(), Void.class);

	Map<String, List<HttpCookie>> requestCookies = this.cookieHandler.requestCookies;
	assertEquals(2, requestCookies.size());

	List<HttpCookie> list = requestCookies.get("SID");
	assertEquals(1, list.size());
	assertEquals("31d4d96e407aad42", list.iterator().next().getValue());

	list = requestCookies.get("lang");
	assertEquals(1, list.size());
	assertEquals("en-US", list.iterator().next().getValue());

	List<String> headerValues = response.getHeaders().get("Set-Cookie");
	assertEquals(2, headerValues.size());

	assertThat(splitCookie(headerValues.get(0)), containsInAnyOrder(equalTo("SID=31d4d96e407aad42"),
			equalToIgnoringCase("Path=/"), equalToIgnoringCase("Secure"), equalToIgnoringCase("HttpOnly")));

	assertThat(splitCookie(headerValues.get(1)), containsInAnyOrder(equalTo("lang=en-US"),
			equalToIgnoringCase("Path=/"), equalToIgnoringCase("Domain=example.com")));
}
 
Example #29
Source File: HttpHandlerConnector.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private ServerHttpRequest adaptRequest(MockClientHttpRequest request, Publisher<DataBuffer> body) {
	HttpMethod method = request.getMethod();
	URI uri = request.getURI();
	HttpHeaders headers = request.getHeaders();
	MultiValueMap<String, HttpCookie> cookies = request.getCookies();
	return MockServerHttpRequest.method(method, uri).headers(headers).cookies(cookies).body(body);
}
 
Example #30
Source File: CookieRoutePredicateFactoryTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void okOneCookieForYou() {
	MockServerHttpRequest request = MockServerHttpRequest.get("https://example.com")
			.cookie(new HttpCookie("yourcookie", "sugar"),
					new HttpCookie("mycookie", "chip"))
			.build();
	MockServerWebExchange exchange = MockServerWebExchange.from(request);

	Predicate<ServerWebExchange> predicate = new CookieRoutePredicateFactory()
			.apply(new Config().setName("mycookie").setRegexp("ch.p"));

	assertThat(predicate.test(exchange)).isTrue();
}