Example usage for org.springframework.http HttpHeaders getFirst

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

Introduction

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

Prototype

@Override
@Nullable
public String getFirst(String headerName) 

Source Link

Document

Return the first header value for the given header name, if any.

Usage

From source file:com.orange.ngsi.client.UpdateContextRequestTest.java

@Test
public void performPostWith200_XML() throws Exception {

    protocolRegistry.registerHost(brokerUrl);

    HttpHeaders httpHeaders = ngsiClient.getRequestHeaders(brokerUrl);
    Assert.assertEquals("application/xml", httpHeaders.getFirst("Content-Type"));
    Assert.assertEquals("application/xml", httpHeaders.getFirst("Accept"));

    httpHeaders.add("Fiware-Service", serviceName);
    httpHeaders.add("Fiware-ServicePath", servicePath);

    String responseBody = xml(xmlConverter, createUpdateContextResponseTempSensor());

    this.mockServer.expect(requestTo(brokerUrl + "/ngsi10/updateContext")).andExpect(method(HttpMethod.POST))
            .andExpect(header("Content-Type", MediaType.APPLICATION_XML_VALUE))
            .andExpect(header("Accept", MediaType.APPLICATION_XML_VALUE))
            .andExpect(header("Fiware-Service", serviceName))
            .andExpect(header("Fiware-ServicePath", servicePath))
            .andExpect(xpath("updateContextRequest/updateAction").string(UpdateAction.UPDATE.getLabel()))
            .andExpect(xpath("updateContextRequest/contextElementList/contextElement/entityId/id").string("S1"))
            .andExpect(xpath(// w w  w. j a va  2s .  c o m
                    "updateContextRequest/contextElementList/contextElement/contextAttributeList/contextAttribute/name")
                            .string("temp"))
            .andExpect(xpath(
                    "updateContextRequest/contextElementList/contextElement/contextAttributeList/contextAttribute/type")
                            .string("float"))
            .andExpect(xpath(
                    "updateContextRequest/contextElementList/contextElement/contextAttributeList/contextAttribute/contextValue")
                            .string("15.5"))
            .andRespond(withSuccess(responseBody, MediaType.APPLICATION_XML));

    ngsiClient.updateContext(brokerUrl, httpHeaders, createUpdateContextTempSensor(0)).get();

    this.mockServer.verify();
}

From source file:io.kahu.hawaii.rest.DefaultResponseManagerTest.java

@Test
public void testHeadersContainsXHawaiiTxIdWhenEnabledAndTxIdInLoggingContent() throws ServerException {
    responseManager = new DefaultResponseManager(logManager, "tx.id"); // 2nd argument null to enable X-Hawaii-Tx-Id
    LoggingContext.get().put("tx.id", "12345"); // store tx.id in logging content
    ResponseEntity<?> response = responseManager.toResponse();
    HttpHeaders headers = response.getHeaders();
    assertThat(headers, hasKey(DefaultResponseManager.X_HAWAII_TRANSACTION_ID_HEADER));
    assertThat(headers.getFirst(DefaultResponseManager.X_HAWAII_TRANSACTION_ID_HEADER).toString(), is("12345"));
}

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:com.orange.cepheus.cep.EventSinkListenerTest.java

/**
 * Check that an updateContext is fired when a new event bean arrives
 *//*from  ww w  . ja  v a2 s  .  c om*/
@Test
public void postMessageOnEventUpdate() {

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(MediaType.APPLICATION_JSON);
    httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

    when(statement.getText()).thenReturn("statement");
    when(ngsiClient.getRequestHeaders(any())).thenReturn(httpHeaders);

    // Trigger event update
    List<ContextAttribute> attributes = new LinkedList<>();
    attributes.add(new ContextAttribute("id", "string", "OUT1234"));
    attributes.add(new ContextAttribute("avgTemp", "double", 10.25));
    attributes.add(new ContextAttribute("avgTemp_unit", "string", "celcius"));
    EventBean[] beans = { buildEventBean("TempSensorAvg", attributes) };
    eventSinkListener.update(beans, null, statement, provider);

    // Capture updateContext when postUpdateContextRequest is called on updateContextRequest,
    ArgumentCaptor<UpdateContext> updateContextArg = ArgumentCaptor.forClass(UpdateContext.class);
    ArgumentCaptor<HttpHeaders> headersArg = ArgumentCaptor.forClass(HttpHeaders.class);

    verify(ngsiClient).updateContext(eq(broker.getUrl()), headersArg.capture(), updateContextArg.capture());

    // Check updateContext is valid
    UpdateContext updateContext = updateContextArg.getValue();
    assertEquals(UpdateAction.APPEND, updateContext.getUpdateAction());
    assertEquals(1, updateContext.getContextElements().size());

    // Check headers are valid
    HttpHeaders headers = headersArg.getValue();
    assertEquals(MediaType.APPLICATION_JSON, headers.getContentType());
    assertTrue(headers.getAccept().contains(MediaType.APPLICATION_JSON));
    assertEquals("SN", headers.getFirst("Fiware-Service"));
    assertEquals("SP", headers.getFirst("Fiware-ServicePath"));
    assertEquals("AUTH_TOKEN", headers.getFirst("X-Auth-Token"));

    ContextElement contextElement = updateContext.getContextElements().get(0);
    assertEquals("OUT1234", contextElement.getEntityId().getId());
    assertEquals("TempSensorAvg", contextElement.getEntityId().getType());
    assertFalse(contextElement.getEntityId().getIsPattern());
    assertEquals(1, contextElement.getContextAttributeList().size());

    ContextAttribute attr = contextElement.getContextAttributeList().get(0);
    assertEquals("avgTemp", attr.getName());
    assertEquals("double", attr.getType());
    assertEquals(10.25, attr.getValue());
    assertEquals(1, attr.getMetadata().size());
    assertEquals("unit", attr.getMetadata().get(0).getName());
    assertEquals("string", attr.getMetadata().get(0).getType());
    assertEquals("celcius", attr.getMetadata().get(0).getValue());
}

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

public boolean isResponseCacheable(HttpRequest request, ClientHttpResponse response) {
    HttpHeaders reqHeaders = request.getHeaders();
    HttpHeaders respHeaders = response.getHeaders();

    if (!isCacheableMethod(request.getMethod())) {
        log.trace("Not cacheable: method {}", request.getMethod());
        return false;
    }//from w  w w . j a  va  2 s . com

    if (parseCacheControl(reqHeaders).isNoStore()) {
        log.trace("Not cacheable: request has Cache-Control: no-store");
        return false;
    }

    if (sharedCache) {
        if (reqHeaders.getFirst("Authorization") != null) {
            CacheControl cc = parseCacheControl(respHeaders);
            if (!cc.isPublic() && cc.getSMaxAge() <= 0) {
                log.trace("Not cacheable: this cache is shared and request contains "
                        + "Authorization header, but no Cache-Control: public");
                return false;
            }
        }
    }
    return isResponseCacheable(response);
}

From source file:org.cloudfoundry.client.lib.rest.CloudControllerClientImpl.java

@Override
public StartingInfo startApplication(String appName) {
    CloudApplication app = getApplication(appName);
    if (app.getState() != CloudApplication.AppState.STARTED) {
        HashMap<String, Object> appRequest = new HashMap<String, Object>();
        appRequest.put("state", CloudApplication.AppState.STARTED);

        HttpEntity<Object> requestEntity = new HttpEntity<Object>(appRequest);
        ResponseEntity<String> entity = getRestTemplate().exchange(getUrl("/v2/apps/{guid}?stage_async=true"),
                HttpMethod.PUT, requestEntity, String.class, app.getMeta().getGuid());

        HttpHeaders headers = entity.getHeaders();

        // Return a starting info, even with a null staging log value, as a non-null starting info
        // indicates that the response entity did have headers. The API contract is to return starting info
        // if there are headers in the response, null otherwise.
        if (headers != null && !headers.isEmpty()) {
            String stagingFile = headers.getFirst("x-app-staging-log");

            if (stagingFile != null) {
                try {
                    stagingFile = URLDecoder.decode(stagingFile, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    logger.error("unexpected inability to UTF-8 decode", e);
                }// w  w w . j  a  v a2 s .  c o  m
            }
            // Return the starting info even if decoding failed or staging file is null
            return new StartingInfo(stagingFile);
        }
    }
    return null;
}

From source file:com.lenovo.h2000.mvc.LicenseController.java

@RequestMapping(value = "/export", method = RequestMethod.GET)
@ResponseBody//from  w  w  w  .  j  av a 2s  . c om
public String export(@RequestHeader HttpHeaders headers) throws Exception {
    _logger.info("getting LicenseController.export headers.X-Lenovo-ClusterName "
            + headers.getFirst("X-Lenovo-ClusterName"));
    Map<String, String> header = new HashMap<String, String>();
    header.put("X-Lenovo-ClusterName", headers.getFirst("X-Lenovo-ClusterName"));
    return _licenseService.export(header);
}

From source file:com.lenovo.h2000.mvc.LicenseController.java

@RequestMapping(value = "/import", method = RequestMethod.POST)
@ResponseBody/*from  w w  w  .j a va2s.  c o m*/
public String upload(@RequestParam("licenseFile") CommonsMultipartFile file, @RequestHeader HttpHeaders headers)
        throws Exception {
    _logger.info("getting LicenseController.upload headers.X-Lenovo-ClusterName "
            + headers.getFirst("X-Lenovo-ClusterName"));
    Map<String, String> header = new HashMap<String, String>();
    header.put("X-Lenovo-ClusterName", headers.getFirst("X-Lenovo-ClusterName"));
    /*String path = System.getProperty("java.io.tmpdir")+ "/" + new Date().getTime()+file.getOriginalFilename();
    File newFile=new File(path);
      file.transferTo(newFile);
              
      return _licenseService.upload(path, header);*/
    return _licenseService.upload(file.getBytes(), header);
}

From source file:com.lenovo.h2000.mvc.LicenseController.java

@RequestMapping(value = "/validate", method = RequestMethod.GET)
@ResponseBody/* w  w  w. j a  v  a2 s  .  c o  m*/
public String validate(@RequestHeader HttpHeaders headers) throws Exception {
    _logger.info("getting LicenseController.upload headers.X-Lenovo-ClusterName "
            + headers.getFirst("X-Lenovo-ClusterName"));
    Map<String, String> header = new HashMap<String, String>();
    header.put("X-Lenovo-ClusterName", headers.getFirst("X-Lenovo-ClusterName"));

    return _licenseService.validate(header);
}

From source file:com.lenovo.h2000.mvc.LicenseController.java

@RequestMapping(value = "/show", method = RequestMethod.GET)
@ResponseBody// www  .ja  v a 2  s.  co m
public String show(@RequestHeader HttpHeaders headers) throws Exception {
    _logger.info("getting LicenseController.upload headers.X-Lenovo-ClusterName "
            + headers.getFirst("X-Lenovo-ClusterName"));
    Map<String, String> header = new HashMap<String, String>();
    header.put("X-Lenovo-ClusterName", headers.getFirst("X-Lenovo-ClusterName"));

    return _licenseService.show(header);
}