Example usage for org.springframework.http HttpHeaders containsKey

List of usage examples for org.springframework.http HttpHeaders containsKey

Introduction

In this page you can find the example usage for org.springframework.http HttpHeaders containsKey.

Prototype

@Override
    public boolean containsKey(Object key) 

Source Link

Usage

From source file:cz.jirutka.spring.http.client.cache.DefaultResponseExpirationResolver.java

/**
 * Parses value of the <tt>Age</tt> header from the given headers. When
 * the header is not specified, returns 0. When the header is specified
 * multiple times, then returns greater value. If the value is less then
 * zero or malformed, then {@link #MAX_AGE} is returned.
 *
 * @param headers HTTP headers of the response.
 * @return An <tt>Age</tt> header value.
 *///from   w ww  .  j av  a  2 s .c  o m
long parseAgeHeader(HttpHeaders headers) {
    long result = 0;

    if (!headers.containsKey("Age")) {
        return result;
    }
    for (String value : headers.get("Age")) {
        long age = toLong(value, MAX_AGE);
        if (age < 0)
            age = MAX_AGE;

        result = max(result, age);
    }
    return result;
}

From source file:io.neba.core.mvc.MultipartSlingHttpServletRequestTest.java

@Test
public void testGetMultipartHeaders() {
    String fileName = "test1";
    String contentType = "image/png";

    mockFileFieldWithContentType(fileName, contentType);

    HttpHeaders headers = this.testee.getMultipartHeaders(fileName);
    assertThat(headers.size()).isEqualTo(1);
    assertThat(headers.containsKey(MultipartSlingHttpServletRequest.CONTENT_TYPE)).isTrue();
    assertThat(headers.getFirst(MultipartSlingHttpServletRequest.CONTENT_TYPE)).isEqualTo(contentType);
}

From source file:cz.jirutka.spring.http.client.cache.DefaultCachingPolicy.java

protected boolean isResponseCacheable(ClientHttpResponse response) {

    boolean cacheable = false;
    HttpHeaders headers = response.getHeaders();

    try {// www .  j a v a 2 s  .  c  o  m
        int status = response.getRawStatusCode();
        if (isImplicitlyCacheableStatus(status)) {
            cacheable = true; //MAY be cached

        } else if (isUncacheableStatus(status)) {
            log.trace("Response with status code {} is not cacheable", status);
            return false;
        }
    } catch (IOException ex) {
        throw new IllegalStateException(ex);
    }

    if (isExplicitlyNonCacheable(response)) {
        log.trace("Response with Cache-Control: '{}' is not cacheable", headers.getCacheControl());
        return false;
    }

    if (headers.getContentLength() > maxBodySizeBytes) {
        log.debug("Response with Content-Lenght {} > {} is not cacheable", headers.getContentLength(),
                maxBodySizeBytes);
        return false;
    }

    try {
        if (response.getHeaders().getDate() < 0) {
            log.debug("Response without a valid Date header is not cacheable");
            return false;
        }
    } catch (IllegalArgumentException ex) {
        return false;
    }

    // dunno how to properly handle Vary
    if (headers.containsKey("Vary")) {
        log.trace("Response with Vary header is not cacheable");
        return false;
    }

    return (cacheable || isExplicitlyCacheable(response));
}

From source file:com.tyro.oss.pact.spring4.pact.consumer.ReturnExpect.java

private void assertRequestHeaders(HttpHeaders actualHeaders, Object requestObject,
        Map<String, Matcher<? super List<String>>> additionalExpectedHeaders) {
    Map<String, Matcher<? super List<String>>> expectedHeaders = new HashMap<>();

    if (requestObject != null && requestObject instanceof HttpEntity) {
        HttpEntity httpEntity = (HttpEntity) requestObject;
        HttpHeaders headers = httpEntity.getHeaders();
        Map<String, Matcher<List<String>>> stringMatcherMap = Maps.transformValues(headers,
                new Function<List<String>, Matcher<List<String>>>() {
                    @Override/* w  w  w. ja va 2  s.  c o  m*/
                    public Matcher<List<String>> apply(List<String> input) {
                        return is(input);
                    }
                });
        expectedHeaders.putAll(stringMatcherMap);
    }

    expectedHeaders.putAll(additionalExpectedHeaders);

    Set<String> headerNames = expectedHeaders.keySet();
    for (String headerName : headerNames) {
        Matcher<? super List<String>> headerValuesMatcher = expectedHeaders.get(headerName);
        assertThat(format("Contains header %s", headerName), actualHeaders.containsKey(headerName), is(true));
        assertThat(format("'%s' header value fails assertion", headerName), actualHeaders.get(headerName),
                headerValuesMatcher);
    }
}

From source file:org.cloudfoundry.identity.uaa.login.RemoteUaaController.java

protected void saveCookie(HttpHeaders headers, Map<String, Object> model) {
    if (!headers.containsKey(SET_COOKIE)) {
        return;/*from ww  w .j  a va 2s  . c o m*/
    }
    StringBuilder cookie = new StringBuilder();
    // Save back end cookie for later
    for (String value : headers.get(SET_COOKIE)) {
        if (value.contains(";")) {
            value = value.substring(0, value.indexOf(";"));
        }
        if (cookie.length() > 0) {
            cookie.append(";");
        }
        cookie.append(value);
    }
    logger.debug("Saved back end cookies: " + cookie);
    model.put(COOKIE_MODEL, cookie.toString());
}

From source file:org.cloudfoundry.identity.uaa.login.RemoteUaaController.java

protected HttpHeaders getResponseHeaders(HttpHeaders headers) {
    // Some of the headers coming back are poisonous apparently
    // (content-length?)...
    HttpHeaders outgoingHeaders = new HttpHeaders();
    outgoingHeaders.putAll(headers);//from   w  w  w .  j a  va  2s .co m
    if (headers.getContentLength() >= 0) {
        outgoingHeaders.remove(CONTENT_LENGTH);
        outgoingHeaders.remove(CONTENT_LENGTH.toLowerCase());
    }
    if (headers.containsKey(TRANSFER_ENCODING)) {
        outgoingHeaders.remove(TRANSFER_ENCODING);
        outgoingHeaders.remove(TRANSFER_ENCODING.toLowerCase());
    }
    return outgoingHeaders;
}

From source file:org.jgrades.rest.client.StatefullRestTemplate.java

@Override
protected void handleResponse(URI url, HttpMethod method, ClientHttpResponse response) throws IOException {
    HttpHeaders headers = response.getHeaders();
    if (headers.containsKey("Set-Cookie")) {
        cookie = headers.get("Set-Cookie").get(0);
    }/*from   ww  w.j  a  va 2s  . c  o  m*/
    super.handleResponse(url, method, response);
}

From source file:org.springframework.cloud.stream.app.http.source.DefaultMixedCaseContentTypeHttpHeaderMapper.java

/**
 * Map from an HttpHeaders instance to integration MessageHeaders.
 * Depending on which type of adapter is using this mapper, the HttpHeaders might be
 * from an HTTP request (inbound adapter) or from an HTTP response (outbound adapter).
 *//*from w  w  w  .j  a v a 2  s  .c om*/
@Override
public Map<String, Object> toHeaders(HttpHeaders source) {
    if (logger.isDebugEnabled()) {
        logger.debug(MessageFormat.format("inboundHeaderNames={0}",
                CollectionUtils.arrayToList(this.inboundHeaderNames)));
    }
    Map<String, Object> target = new HashMap<String, Object>();
    Set<String> headerNames = source.keySet();
    for (String name : headerNames) {
        String lowerName = name.toLowerCase();
        if (this.shouldMapInboundHeader(lowerName)) {
            if (!HTTP_REQUEST_HEADER_NAMES_LOWER.contains(lowerName)
                    && !HTTP_RESPONSE_HEADER_NAMES_LOWER.contains(lowerName)) {
                String prefixedName = StringUtils.startsWithIgnoreCase(name, this.userDefinedHeaderPrefix)
                        ? name
                        : this.userDefinedHeaderPrefix + name;
                Object value = source.containsKey(prefixedName) ? this.getHttpHeader(source, prefixedName)
                        : this.getHttpHeader(source, name);
                if (value != null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug(MessageFormat.format("setting headerName=[{0}], value={1}", name, value));
                    }
                    this.setMessageHeader(target, name, value);
                }
            } else {
                Object value = this.getHttpHeader(source, name);
                if (value != null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug(MessageFormat.format("setting headerName=[{0}], value={1}", name, value));
                    }
                    if (CONTENT_TYPE.equalsIgnoreCase(name)) {
                        name = MessageHeaders.CONTENT_TYPE;
                    }
                    this.setMessageHeader(target, name, value);
                }
            }
        }
    }
    return target;
}

From source file:org.springframework.http.codec.EncoderHttpMessageWriter.java

@SuppressWarnings("unchecked")
@Override//w  w w . j ava  2  s.  com
public Mono<Void> write(Publisher<? extends T> inputStream, ResolvableType elementType,
        @Nullable MediaType mediaType, ReactiveHttpOutputMessage message, Map<String, Object> hints) {

    MediaType contentType = updateContentType(message, mediaType);

    Flux<DataBuffer> body = this.encoder.encode(inputStream, message.bufferFactory(), elementType, contentType,
            hints);

    if (inputStream instanceof Mono) {
        HttpHeaders headers = message.getHeaders();
        if (headers.getContentLength() < 0 && !headers.containsKey(HttpHeaders.TRANSFER_ENCODING)) {
            return Mono.from(body).flatMap(dataBuffer -> {
                headers.setContentLength(dataBuffer.readableByteCount());
                return message.writeWith(Mono.just(dataBuffer));
            });
        }
    }

    return (isStreamingMediaType(contentType) ? message.writeAndFlushWith(body.map(Flux::just))
            : message.writeWith(body));
}

From source file:org.springframework.http.converter.AbstractHttpMessageConverter.java

/**
 * Add default headers to the output message.
 * <p>This implementation delegates to {@link #getDefaultContentType(Object)} if a
 * content type was not provided, set if necessary the default character set, calls
 * {@link #getContentLength}, and sets the corresponding headers.
 * @since 4.2/*from w w w  .  j  a  v  a 2s  . c o  m*/
 */
protected void addDefaultHeaders(HttpHeaders headers, T t, @Nullable MediaType contentType) throws IOException {
    if (headers.getContentType() == null) {
        MediaType contentTypeToUse = contentType;
        if (contentType == null || contentType.isWildcardType() || contentType.isWildcardSubtype()) {
            contentTypeToUse = getDefaultContentType(t);
        } else if (MediaType.APPLICATION_OCTET_STREAM.equals(contentType)) {
            MediaType mediaType = getDefaultContentType(t);
            contentTypeToUse = (mediaType != null ? mediaType : contentTypeToUse);
        }
        if (contentTypeToUse != null) {
            if (contentTypeToUse.getCharset() == null) {
                Charset defaultCharset = getDefaultCharset();
                if (defaultCharset != null) {
                    contentTypeToUse = new MediaType(contentTypeToUse, defaultCharset);
                }
            }
            headers.setContentType(contentTypeToUse);
        }
    }
    if (headers.getContentLength() < 0 && !headers.containsKey(HttpHeaders.TRANSFER_ENCODING)) {
        Long contentLength = getContentLength(t, headers.getContentType());
        if (contentLength != null) {
            headers.setContentLength(contentLength);
        }
    }
}