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:spring.travel.site.controllers.LoginControllerTest.java

@Test
public void shouldSetSessionCookieIfUserLogsInSuccessfully() throws Exception {
    stubPost("/login", new LoginData("brubble", "bambam"),
            new User("346436", "Barney", "Rubble", "brubble", Optional.<Address>empty()));

    when(signer.sign("id=346436")).thenReturn("SIGNATURE");

    MvcResult mvcResult = this.mockMvc
            .perform(post("/login").contentType(MediaType.APPLICATION_JSON)
                    .content("{ \"username\":\"brubble\", \"password\":\"bambam\" }")
                    .accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
            .andExpect(request().asyncStarted())
            .andExpect(request().asyncResult(instanceOf(ResponseEntity.class))).andReturn();

    this.mockMvc.perform(asyncDispatch(mvcResult)).andExpect(status().is(200));

    Object asyncResult = mvcResult.getAsyncResult(2000);

    assertTrue(asyncResult instanceof ResponseEntity);
    ResponseEntity<User> response = (ResponseEntity<User>) asyncResult;

    User user = response.getBody();//from w  w  w  .  ja  v  a2s .  co m
    assertEquals("Barney", user.getFirstName());

    HttpHeaders headers = response.getHeaders();
    List<String> session = headers.get("Set-Cookie");

    assertEquals(1, session.size());
    assertEquals("GETAWAY_SESSION=SIGNATURE-id=346436; path=/", session.get(0));
}

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  w w  . java  2  s .c om
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:net.paslavsky.springrest.HttpHeadersHelperTest.java

@Test(dataProvider = "data")
public void testGetHttpHeaders(String header, Object value, String converted) throws Exception {
    Map<String, Integer> map = new HashMap<String, Integer>();
    map.put(header, 0);/*from   w ww.j  a v a 2  s . c om*/
    HttpHeaders headers = helper.getHttpHeaders(map, new Object[] { value });
    Assert.assertNotNull(headers);
    Assert.assertEquals(headers.size(), 1);
    Assert.assertEquals(headers.get(header).get(0), converted);
}

From source file:jp.co.ctc_g.rack.websocket.sharedmessage.SharedMessageHandler.java

private String getGroupId(WebSocketSession session) {

    HttpHeaders headers = session.getHandshakeHeaders();
    if (headers == null) {
        throw new InternalException(SharedMessageHandler.class, "E-SHARED#0001");
    }/*from   w ww . ja  v  a  2  s.  co m*/
    List<String> groupIds = headers.get("x-GroupId");
    if (groupIds == null || groupIds.size() != 1) {
        throw new InternalException(SharedMessageHandler.class, "E-SHARED#0001");
    }
    return groupIds.get(0);
}

From source file:be.solidx.hot.rest.RestController.java

protected ResponseEntity<byte[]> buildResponse(Map content, Map headers, Integer httpStatus,
        Charset requestedEncoding) {
    try {/*from  w w  w .  j  a  va 2 s. co m*/
        HttpHeaders httpHeaders = buildHttpHeaders(headers);
        List<String> contentType = httpHeaders.get(com.google.common.net.HttpHeaders.CONTENT_TYPE);
        if (contentType != null && contentType.size() > 0
                && contentType.contains(MediaType.APPLICATION_JSON_VALUE)) {
            return new ResponseEntity<byte[]>(objectMapper.writeValueAsBytes(content), httpHeaders,
                    HttpStatus.valueOf(httpStatus));
        } else {
            return new ResponseEntity<byte[]>(content.toString().getBytes(requestedEncoding), httpHeaders,
                    HttpStatus.valueOf(httpStatus));
        }
    } catch (Exception e) {
        logger.error("", e);
        return new ResponseEntity<byte[]>(e.getMessage().toString().getBytes(requestedEncoding),
                HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:org.apigw.util.OAuthTestHelper.java

public ResponseEntity<TokenResponseDTO> requestToken(String clientId, String redirectUri, String code,
        String scope) {//from   w w w .  j av a 2  s  .  c  o  m
    MultiValueMap<String, String> formData = getTokenFormData(clientId, redirectUri, code, scope);

    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization",
            "Basic " + new String(Base64.encode(String.format("%s:secret", clientId).getBytes())));

    ResponseEntity<TokenResponseDTO> token = serverRunning.postForToken("/apigw-auth-server-intsvc/oauth/token",
            headers, formData);

    HttpHeaders responseHeaders = token.getHeaders();
    assertTrue("Missing no-store: " + responseHeaders,
            responseHeaders.get("Cache-Control").contains("no-store"));
    return token;
}

From source file:com.alexshabanov.springrestapi.restapitest.RestOperationsTestClient.java

private MockHttpServletRequest toMockHttpServletRequest(URI url, HttpMethod method,
        ClientHttpRequest clientHttpRequest) throws IOException {
    final MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(method.name(),
            url.getPath());//from w  w w. j a  v a2 s. co m

    // copy headers
    final HttpHeaders headers = clientHttpRequest.getHeaders();
    for (final String headerKey : headers.toSingleValueMap().keySet()) {
        final List<String> headerValues = headers.get(headerKey);
        for (final String headerValue : headerValues) {
            mockHttpServletRequest.addHeader(headerKey, headerValue);
        }
    }

    // copy query parameters
    final String query = clientHttpRequest.getURI().getQuery();
    if (query != null) {
        mockHttpServletRequest.setQueryString(query);
        final String[] queryParameters = query.split("&");
        for (String keyValueParam : queryParameters) {
            final String[] components = keyValueParam.split("=");
            if (components.length == 1) {
                continue; // optional parameter
            }

            Assert.isTrue(components.length == 2,
                    "Can't split query parameters " + keyValueParam + " by key-value pair");
            mockHttpServletRequest.setParameter(components[0], components[1]);
        }
    }

    // copy request body
    // TODO: another byte copying approach here
    // TODO: for now we rely to the fact that request body is always presented as byte array output stream
    final OutputStream requestBodyStream = clientHttpRequest.getBody();
    if (requestBodyStream instanceof ByteArrayOutputStream) {
        mockHttpServletRequest.setContent(((ByteArrayOutputStream) requestBodyStream).toByteArray());
    } else {
        throw new AssertionError("Ooops, client http request has non-ByteArrayOutputStream body");
    }

    return mockHttpServletRequest;
}

From source file:de.loercher.localpress.core.api.LocalPressController.java

@RequestMapping(value = "/articles", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> addArticleEntry(@RequestBody LocalPressArticleEntity entity,
        @RequestHeader HttpHeaders headers)
        throws UnauthorizedException, GeneralLocalPressException, JsonProcessingException {
    AddArticleEntityDTO geoDTO = new AddArticleEntityDTO(entity.getRelease());

    List<String> userHeader = headers.get("UserID");
    if (userHeader == null || userHeader.isEmpty()) {
        throw new UnauthorizedException("There needs to be set a UserID-Header!", "", "");
    }//from  ww w . j av  a2s .co m

    MultiValueMap<String, String> geoHeaders = new LinkedMultiValueMap<>();
    geoHeaders.add("UserID", userHeader.get(0));

    HttpEntity<AddArticleEntityDTO> request = new HttpEntity<>(geoDTO, geoHeaders);

    RestTemplate template = new RestTemplate();
    String ratingURL = RATING_URL + "feedback";
    ResponseEntity<Map> result;
    try {
        result = template.postForEntity(ratingURL, request, Map.class);
    } catch (RestClientException e) {
        GeneralLocalPressException ex = new GeneralLocalPressException(
                "There happened an error by trying to invoke the geo API!", e);
        log.error(ex.getLoggingString());
        throw ex;
    }

    if (!result.getStatusCode().equals(HttpStatus.CREATED)) {
        GeneralLocalPressException e = new GeneralLocalPressException(result.getStatusCode().getReasonPhrase());
        log.error(e.getLoggingString());
        throw e;
    }

    String articleID = (String) result.getBody().get("articleID");
    if (articleID == null) {
        GeneralLocalPressException e = new GeneralLocalPressException(
                "No articleID found in response from rating module by trying to add new article!");
        log.error(e.getLoggingString());
        throw e;
    }

    HttpEntity<LocalPressArticleEntity> second = new HttpEntity<>(entity, geoHeaders);

    template.put(GEO_URL + articleID, second);

    String url = (String) result.getBody().get("feedbackURL");

    Map<String, Object> returnMap = new LinkedHashMap<>();
    returnMap.put("articleID", articleID);
    returnMap.put("userID", userHeader.get(0));

    Timestamp now = new Timestamp(new Date().getTime());
    returnMap.put("timestamp", now);
    returnMap.put("status", 201);
    returnMap.put("message", "Created.");

    returnMap.put("feedbackURL", url);

    return new ResponseEntity<>(objectMapper.writeValueAsString(returnMap), HttpStatus.CREATED);
}

From source file:com.orange.ngsi2.client.Ngsi2Client.java

/**
 * @return return a clone HttpHeader from default HttpHeader
 *//*  ww w .  j a va 2s .  c o m*/
private HttpHeaders cloneHttpHeaders() {
    HttpHeaders httpHeaders = getHttpHeaders();
    HttpHeaders clone = new HttpHeaders();
    for (String entry : httpHeaders.keySet()) {
        clone.put(entry, httpHeaders.get(entry));
    }
    return clone;
}