Example usage for org.springframework.http HttpHeaders get

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

Introduction

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

Prototype

@Override
    @Nullable
    public List<String> get(Object key) 

Source Link

Usage

From source file:bjerne.gallery.controller.GalleryController.java

/**
 * Method used to return the binary of a gallery file (
 * {@link GalleryFile#getActualFile()} ). This method handles 304 redirects
 * (if file has not changed) and range headers if requested by browser. The
 * range parts is particularly important for videos. The correct response
 * status is set depending on the circumstances.
 * <p>/*from   ww w  .j av a 2 s  .  c  o m*/
 * NOTE: the range logic should NOT be considered a complete implementation
 * - it's a bare minimum for making requests for byte ranges work.
 * 
 * @param request
 *            Request
 * @param galleryFile
 *            Gallery file
 * @return The binary of the gallery file, or a 304 redirect, or a part of
 *         the file.
 * @throws IOException
 *             If there is an issue accessing the binary file.
 */
private ResponseEntity<InputStreamResource> returnResource(WebRequest request, GalleryFile galleryFile)
        throws IOException {
    LOG.debug("Entering returnResource()");
    if (request.checkNotModified(galleryFile.getActualFile().lastModified())) {
        return null;
    }
    File file = galleryFile.getActualFile();
    String contentType = galleryFile.getContentType();
    String rangeHeader = request.getHeader(HttpHeaders.RANGE);
    long[] ranges = getRangesFromHeader(rangeHeader);
    long startPosition = ranges[0];
    long fileTotalSize = file.length();
    long endPosition = ranges[1] != 0 ? ranges[1] : fileTotalSize - 1;
    long contentLength = endPosition - startPosition + 1;
    LOG.debug("contentLength: {}, file length: {}", contentLength, fileTotalSize);

    LOG.debug("Returning resource {} as inputstream. Start position: {}", file.getCanonicalPath(),
            startPosition);
    InputStream boundedInputStream = new BoundedInputStream(new FileInputStream(file), endPosition + 1);

    InputStream is = new BufferedInputStream(boundedInputStream, 65536);
    InputStreamResource inputStreamResource = new InputStreamResource(is);
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentLength(contentLength);
    responseHeaders.setContentType(MediaType.valueOf(contentType));
    responseHeaders.add(HttpHeaders.ACCEPT_RANGES, "bytes");
    if (StringUtils.isNotBlank(rangeHeader)) {
        is.skip(startPosition);
        String contentRangeResponseHeader = "bytes " + startPosition + "-" + endPosition + "/" + fileTotalSize;
        responseHeaders.add(HttpHeaders.CONTENT_RANGE, contentRangeResponseHeader);
        LOG.debug("{} was not null but {}. Adding header {} to response: {}", HttpHeaders.RANGE, rangeHeader,
                HttpHeaders.CONTENT_RANGE, contentRangeResponseHeader);
    }
    HttpStatus status = (startPosition == 0 && contentLength == fileTotalSize) ? HttpStatus.OK
            : HttpStatus.PARTIAL_CONTENT;
    LOG.debug("Returning {}. Status: {}, content-type: {}, {}: {}, contentLength: {}", file, status,
            contentType, HttpHeaders.CONTENT_RANGE, responseHeaders.get(HttpHeaders.CONTENT_RANGE),
            contentLength);
    return new ResponseEntity<InputStreamResource>(inputStreamResource, responseHeaders, status);
}

From source file:com.muk.services.security.DefaultUaaLoginService.java

@Override
public String approveClient(String approvalQuery, String cookie) {
    final UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(cfgService.getOauthServer());
    final HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8));

    final StringTokenizer cookieTokenizer = new StringTokenizer(cookie, "; ");
    while (cookieTokenizer.hasMoreTokens()) {
        headers.add(HttpHeaders.COOKIE, cookieTokenizer.nextToken());
    }/*from   w  w  w.  ja v  a  2  s.c om*/

    final MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    for (final String pair : approvalQuery.split("&")) {
        final String[] nv = pair.split("=");
        formData.add(nv[0], nv[1]);
    }
    formData.add("X-Uaa-Csrf", getCsrf(headers.get(HttpHeaders.COOKIE)));

    final UriComponents loginUri = uriBuilder.cloneBuilder().pathSegment("oauth").pathSegment("authorize")
            .build();

    final ResponseEntity<String> response = exchangeForType(loginUri.toUriString(), HttpMethod.POST, formData,
            headers, String.class);

    if (approvalQuery.contains("false")) {
        return null; // approval declined.
    }

    // accepted, but location contains error
    if (response.getHeaders().getLocation().getQuery().startsWith("error")) {
        throw new HttpClientErrorException(HttpStatus.UNAUTHORIZED,
                response.getHeaders().getLocation().getQuery());
    }

    // accepted with related auth code
    return response.getHeaders().getLocation().getQuery().split("=")[1];
}

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/*from   w w w .j a  v a  2  s.com*/
                    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.apache.geode.management.internal.web.http.support.HttpRequesterTest.java

private void verifyHeaderIsUpdated() {
    ArgumentCaptor<HttpHeaders> headerCaptor = ArgumentCaptor.forClass(HttpHeaders.class);
    verify(requester).addHeaderValues(headerCaptor.capture());

    HttpHeaders headers = headerCaptor.getValue();
    assertThat(headers.get("user").get(0)).isEqualTo("me");
    assertThat(headers.get("password").get(0)).isEqualTo("secret");
}

From source file:org.cloudfoundry.identity.uaa.integration.util.IntegrationTestUtils.java

public static void clearAllButJsessionID(HttpHeaders headers) {
    String jsessionid = null;//from w  ww .j ava 2  s .c  o m
    List<String> cookies = headers.get("Cookie");
    if (cookies != null) {
        for (String cookie : cookies) {
            if (cookie.contains("JSESSIONID")) {
                jsessionid = cookie;
            }
        }
    }
    if (jsessionid != null) {
        headers.set("Cookie", jsessionid);
    } else {
        headers.remove("Cookie");
    }
}

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  www .  j a v  a 2  s  .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.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   w w w.  j ava  2 s. c o m
    super.handleResponse(url, method, response);
}

From source file:org.springframework.cloud.gateway.filter.WebsocketRoutingFilter.java

@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    changeSchemeIfIsWebSocketUpgrade(exchange);

    URI requestUrl = exchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
    String scheme = requestUrl.getScheme();

    if (isAlreadyRouted(exchange) || (!"ws".equals(scheme) && !"wss".equals(scheme))) {
        return chain.filter(exchange);
    }/*from w ww  .j a  v a 2 s.c o m*/
    setAlreadyRouted(exchange);

    HttpHeaders headers = exchange.getRequest().getHeaders();
    HttpHeaders filtered = filterRequest(getHeadersFilters(), exchange);

    List<String> protocols = headers.get(SEC_WEBSOCKET_PROTOCOL);
    if (protocols != null) {
        protocols = headers.get(SEC_WEBSOCKET_PROTOCOL).stream()
                .flatMap(header -> Arrays.stream(commaDelimitedListToStringArray(header))).map(String::trim)
                .collect(Collectors.toList());
    }

    return this.webSocketService.handleRequest(exchange,
            new ProxyWebSocketHandler(requestUrl, this.webSocketClient, filtered, protocols));
}

From source file:org.springframework.cloud.gateway.test.GatewayIntegrationTests.java

@Test
public void defaultFiltersWorks() {
    assertThat(this.properties.getDefaultFilters()).isNotEmpty();

    Mono<ClientResponse> result = webClient.get().uri("/headers").header("Host", "www.addresponseheader.org")
            .exchange();/*from  w ww . j a v  a 2  s. c  o  m*/

    StepVerifier.create(result).consumeNextWith(response -> {
        HttpHeaders httpHeaders = response.headers().asHttpHeaders();
        assertThat(httpHeaders.getFirst("X-Response-Default-Foo")).isEqualTo("Default-Bar");
        assertThat(httpHeaders.get("X-Response-Default-Foo")).hasSize(1);
    }).expectComplete().verify(DURATION);
}

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

private Object getHttpHeader(HttpHeaders source, String name) {
    if (ACCEPT.equalsIgnoreCase(name)) {
        return source.getAccept();
    } else if (ACCEPT_CHARSET.equalsIgnoreCase(name)) {
        return source.getAcceptCharset();
    } else if (ALLOW.equalsIgnoreCase(name)) {
        return source.getAllow();
    } else if (CACHE_CONTROL.equalsIgnoreCase(name)) {
        String cacheControl = source.getCacheControl();
        return (StringUtils.hasText(cacheControl)) ? cacheControl : null;
    } else if (CONTENT_LENGTH.equalsIgnoreCase(name)) {
        long contentLength = source.getContentLength();
        return (contentLength > -1) ? contentLength : null;
    } else if (CONTENT_TYPE.equalsIgnoreCase(name)) {
        return source.getContentType();
    } else if (DATE.equalsIgnoreCase(name)) {
        long date = source.getDate();
        return (date > -1) ? date : null;
    } else if (ETAG.equalsIgnoreCase(name)) {
        String eTag = source.getETag();
        return (StringUtils.hasText(eTag)) ? eTag : null;
    } else if (EXPIRES.equalsIgnoreCase(name)) {
        try {//from  w ww  .  j a v a  2s .  c  o m
            long expires = source.getExpires();
            return (expires > -1) ? expires : null;
        } catch (Exception e) {
            if (logger.isDebugEnabled()) {
                logger.debug(e.getMessage());
            }
            // According to RFC 2616
            return null;
        }
    } else if (IF_NONE_MATCH.equalsIgnoreCase(name)) {
        return source.getIfNoneMatch();
    } else if (IF_MODIFIED_SINCE.equalsIgnoreCase(name)) {
        long modifiedSince = source.getIfModifiedSince();
        return (modifiedSince > -1) ? modifiedSince : null;
    } else if (IF_UNMODIFIED_SINCE.equalsIgnoreCase(name)) {
        String unmodifiedSince = source.getFirst(IF_UNMODIFIED_SINCE);
        return unmodifiedSince != null ? this.getFirstDate(unmodifiedSince, IF_UNMODIFIED_SINCE) : null;
    } else if (LAST_MODIFIED.equalsIgnoreCase(name)) {
        long lastModified = source.getLastModified();
        return (lastModified > -1) ? lastModified : null;
    } else if (LOCATION.equalsIgnoreCase(name)) {
        return source.getLocation();
    } else if (PRAGMA.equalsIgnoreCase(name)) {
        String pragma = source.getPragma();
        return (StringUtils.hasText(pragma)) ? pragma : null;
    }
    return source.get(name);
}