Example usage for org.springframework.http HttpHeaders add

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

Introduction

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

Prototype

@Override
public void add(String headerName, @Nullable String headerValue) 

Source Link

Document

Add the given, single header value under the given name.

Usage

From source file:org.apache.servicecomb.demo.springmvc.server.CodeFirstSpringmvc.java

@ResponseHeaders({ @ResponseHeader(name = "h1", response = String.class),
        @ResponseHeader(name = "h2", response = String.class) })
@RequestMapping(path = "/responseEntity", method = RequestMethod.POST)
public ResponseEntity<Date> responseEntity(InvocationContext c1, @RequestAttribute("date") Date date) {
    HttpHeaders headers = new HttpHeaders();
    headers.add("h1", "h1v " + c1.getContext().get(Const.SRC_MICROSERVICE));

    InvocationContext c2 = ContextUtils.getInvocationContext();
    headers.add("h2", "h2v " + c2.getContext().get(Const.SRC_MICROSERVICE));

    return new ResponseEntity<>(date, headers, HttpStatus.ACCEPTED);
}

From source file:org.apache.servicecomb.demo.springmvc.tests.endpoints.CodeFirstSpringmvcBase.java

public ResponseEntity<Date> responseEntity(InvocationContext c1, Date date) {
    HttpHeaders headers = new HttpHeaders();
    headers.add("h1", "h1v " + c1.getContext().toString());

    InvocationContext c2 = ContextUtils.getInvocationContext();
    headers.add("h2", "h2v " + c2.getContext().toString());

    return new ResponseEntity<Date>(date, headers, HttpStatus.ACCEPTED);
}

From source file:org.apache.servicecomb.demo.springmvc.tests.SpringMvcIntegrationTestBase.java

@Test
public void ableToPostDate() throws Exception {
    ZonedDateTime date = ZonedDateTime.now().truncatedTo(SECONDS);
    MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
    body.add("date",
            RestObjectMapperFactory.getRestObjectMapper().convertToString(Date.from(date.toInstant())));

    HttpHeaders headers = new HttpHeaders();
    headers.add(CONTENT_TYPE, APPLICATION_FORM_URLENCODED_VALUE);

    int seconds = 1;
    Date result = restTemplate.postForObject(codeFirstUrl + "addDate?seconds={seconds}",
            new HttpEntity<>(body, headers), Date.class, seconds);

    assertThat(result, is(Date.from(date.plusSeconds(seconds).toInstant())));

    ListenableFuture<ResponseEntity<Date>> listenableFuture = asyncRestTemplate.postForEntity(
            codeFirstUrl + "addDate?seconds={seconds}", new HttpEntity<>(body, headers), Date.class, seconds);
    ResponseEntity<Date> dateResponseEntity = listenableFuture.get();
    assertThat(dateResponseEntity.getBody(), is(Date.from(date.plusSeconds(seconds).toInstant())));
}

From source file:org.apache.servicecomb.demo.springmvc.tests.SpringMvcIntegrationTestBase.java

@Test
public void ableToPostWithHeader() throws Exception {
    Person person = new Person();
    person.setName("person name");

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(APPLICATION_JSON);
    headers.add("prefix", "prefix  prefix");

    HttpEntity<Person> requestEntity = new HttpEntity<>(person, headers);
    ResponseEntity<String> responseEntity = restTemplate.postForEntity(codeFirstUrl + "saysomething",
            requestEntity, String.class);

    assertThat(jsonOf(responseEntity.getBody(), String.class), is("prefix  prefix person name"));

    ListenableFuture<ResponseEntity<String>> listenableFuture = asyncRestTemplate
            .postForEntity(codeFirstUrl + "saysomething", requestEntity, String.class);
    responseEntity = listenableFuture.get();
    assertThat(jsonOf(responseEntity.getBody(), String.class), is("prefix  prefix person name"));
}

From source file:org.apache.servicecomb.demo.springmvc.tests.SpringMvcIntegrationTestBase.java

@Test
public void ableToPostForm() throws Exception {
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("a", "5");
    params.add("b", "3");

    HttpHeaders headers = new HttpHeaders();
    headers.add(CONTENT_TYPE, APPLICATION_FORM_URLENCODED_VALUE);
    int result = restTemplate.postForObject(codeFirstUrl + "add", new HttpEntity<>(params, headers),
            Integer.class);

    assertThat(result, is(8));/*  w  w  w  . ja  v a  2 s  . co  m*/

    ListenableFuture<ResponseEntity<Integer>> listenableFuture = asyncRestTemplate
            .postForEntity(codeFirstUrl + "add", new HttpEntity<>(params, headers), Integer.class);
    ResponseEntity<Integer> futureResponse = listenableFuture.get();
    assertThat(futureResponse.getBody(), is(8));
}

From source file:org.apache.servicecomb.demo.springmvc.tests.SpringMvcIntegrationTestBase.java

@Test
public void ableToExchangeCookie() throws Exception {
    Map<String, String> params = new HashMap<>();
    params.put("a", "5");

    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.COOKIE, "b=3");

    HttpEntity<?> requestEntity = new HttpEntity<>(headers);
    ResponseEntity<Integer> result = restTemplate.exchange(codeFirstUrl + "reduce?a={a}", GET, requestEntity,
            Integer.class, params);

    assertThat(result.getBody(), is(2));

    ListenableFuture<ResponseEntity<Integer>> listenableFuture = asyncRestTemplate
            .exchange(codeFirstUrl + "reduce?a={a}", GET, requestEntity, Integer.class, params);
    result = listenableFuture.get();//  w w  w. j a  va  2 s .c  om
    assertThat(result.getBody(), is(2));
}

From source file:org.apache.zeppelin.livy.BaseLivyInterprereter.java

private String callRestAPI(String targetURL, String method, String jsonData) throws LivyException {
    targetURL = livyURL + targetURL;//from  w ww .j  av  a2  s.  c o m
    LOGGER.debug("Call rest api in {}, method: {}, jsonData: {}", targetURL, method, jsonData);
    RestTemplate restTemplate = getRestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/json");
    headers.add("X-Requested-By", "zeppelin");
    ResponseEntity<String> response = null;
    try {
        if (method.equals("POST")) {
            HttpEntity<String> entity = new HttpEntity<>(jsonData, headers);
            response = restTemplate.exchange(targetURL, HttpMethod.POST, entity, String.class);
        } else if (method.equals("GET")) {
            HttpEntity<String> entity = new HttpEntity<>(headers);
            response = restTemplate.exchange(targetURL, HttpMethod.GET, entity, String.class);
        } else if (method.equals("DELETE")) {
            HttpEntity<String> entity = new HttpEntity<>(headers);
            response = restTemplate.exchange(targetURL, HttpMethod.DELETE, entity, String.class);
        }
    } catch (HttpClientErrorException e) {
        response = new ResponseEntity(e.getResponseBodyAsString(), e.getStatusCode());
        LOGGER.error(String.format("Error with %s StatusCode: %s", response.getStatusCode().value(),
                e.getResponseBodyAsString()));
    }
    if (response == null) {
        throw new LivyException("No http response returned");
    }
    LOGGER.debug("Get response, StatusCode: {}, responseBody: {}", response.getStatusCode(),
            response.getBody());
    if (response.getStatusCode().value() == 200 || response.getStatusCode().value() == 201) {
        return response.getBody();
    } else if (response.getStatusCode().value() == 404) {
        if (response.getBody().matches("\"Session '\\d+' not found.\"")) {
            throw new SessionNotFoundException(response.getBody());
        } else {
            throw new APINotFoundException(
                    "No rest api found for " + targetURL + ", " + response.getStatusCode());
        }
    } else {
        String responseString = response.getBody();
        if (responseString.contains("CreateInteractiveRequest[\\\"master\\\"]")) {
            return responseString;
        }
        throw new LivyException(String.format("Error with %s StatusCode: %s", response.getStatusCode().value(),
                responseString));
    }
}

From source file:org.apache.zeppelin.livy.BaseLivyInterpreter.java

private String callRestAPI(String targetURL, String method, String jsonData) throws LivyException {
    targetURL = livyURL + targetURL;/*w ww .  j a  v  a  2 s  .  co  m*/
    LOGGER.debug("Call rest api in {}, method: {}, jsonData: {}", targetURL, method, jsonData);
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);
    headers.add("X-Requested-By", "zeppelin");
    for (Map.Entry<String, String> entry : customHeaders.entrySet()) {
        headers.add(entry.getKey(), entry.getValue());
    }
    ResponseEntity<String> response = null;
    try {
        if (method.equals("POST")) {
            HttpEntity<String> entity = new HttpEntity<>(jsonData, headers);
            response = restTemplate.exchange(targetURL, HttpMethod.POST, entity, String.class);
        } else if (method.equals("GET")) {
            HttpEntity<String> entity = new HttpEntity<>(headers);
            response = restTemplate.exchange(targetURL, HttpMethod.GET, entity, String.class);
        } else if (method.equals("DELETE")) {
            HttpEntity<String> entity = new HttpEntity<>(headers);
            response = restTemplate.exchange(targetURL, HttpMethod.DELETE, entity, String.class);
        }
    } catch (HttpClientErrorException e) {
        response = new ResponseEntity(e.getResponseBodyAsString(), e.getStatusCode());
        LOGGER.error(String.format("Error with %s StatusCode: %s", response.getStatusCode().value(),
                e.getResponseBodyAsString()));
    } catch (RestClientException e) {
        // Exception happens when kerberos is enabled.
        if (e.getCause() instanceof HttpClientErrorException) {
            HttpClientErrorException cause = (HttpClientErrorException) e.getCause();
            if (cause.getResponseBodyAsString().matches(SESSION_NOT_FOUND_PATTERN)) {
                throw new SessionNotFoundException(cause.getResponseBodyAsString());
            }
            throw new LivyException(cause.getResponseBodyAsString() + "\n"
                    + ExceptionUtils.getFullStackTrace(ExceptionUtils.getRootCause(e)));
        }
        if (e instanceof HttpServerErrorException) {
            HttpServerErrorException errorException = (HttpServerErrorException) e;
            String errorResponse = errorException.getResponseBodyAsString();
            if (errorResponse.contains("Session is in state dead")) {
                throw new SessionDeadException();
            }
            throw new LivyException(errorResponse, e);
        }
        throw new LivyException(e);
    }
    if (response == null) {
        throw new LivyException("No http response returned");
    }
    LOGGER.debug("Get response, StatusCode: {}, responseBody: {}", response.getStatusCode(),
            response.getBody());
    if (response.getStatusCode().value() == 200 || response.getStatusCode().value() == 201) {
        return response.getBody();
    } else if (response.getStatusCode().value() == 404) {
        if (response.getBody().matches(SESSION_NOT_FOUND_PATTERN)) {
            throw new SessionNotFoundException(response.getBody());
        } else {
            throw new APINotFoundException(
                    "No rest api found for " + targetURL + ", " + response.getStatusCode());
        }
    } else {
        String responseString = response.getBody();
        if (responseString.contains("CreateInteractiveRequest[\\\"master\\\"]")) {
            return responseString;
        }
        throw new LivyException(String.format("Error with %s StatusCode: %s", response.getStatusCode().value(),
                responseString));
    }
}

From source file:org.apache.zeppelin.livy.LivyHelper.java

protected String executeHTTP(String targetURL, String method, String jsonData, String paragraphId)
        throws Exception {
    LOGGER.debug("Call rest api in {}, method: {}, jsonData: {}", targetURL, method, jsonData);
    RestTemplate restTemplate = getRestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/json");
    headers.add("X-Requested-By", "zeppelin");
    ResponseEntity<String> response = null;
    try {/*from   w ww.jav  a2 s  .  c  om*/
        if (method.equals("POST")) {
            HttpEntity<String> entity = new HttpEntity<>(jsonData, headers);

            response = restTemplate.exchange(targetURL, HttpMethod.POST, entity, String.class);
            paragraphHttpMap.put(paragraphId, response);
        } else if (method.equals("GET")) {
            HttpEntity<String> entity = new HttpEntity<>(headers);
            response = restTemplate.exchange(targetURL, HttpMethod.GET, entity, String.class);
            paragraphHttpMap.put(paragraphId, response);
        } else if (method.equals("DELETE")) {
            HttpEntity<String> entity = new HttpEntity<>(headers);
            response = restTemplate.exchange(targetURL, HttpMethod.DELETE, entity, String.class);
        }
    } catch (HttpClientErrorException e) {
        response = new ResponseEntity(e.getResponseBodyAsString(), e.getStatusCode());
        LOGGER.error(String.format("Error with %s StatusCode: %s", response.getStatusCode().value(),
                e.getResponseBodyAsString()));
    }
    if (response == null) {
        return null;
    }

    if (response.getStatusCode().value() == 200 || response.getStatusCode().value() == 201
            || response.getStatusCode().value() == 404) {
        return response.getBody();
    } else {
        String responseString = response.getBody();
        if (responseString.contains("CreateInteractiveRequest[\\\"master\\\"]")) {
            return responseString;
        }
        LOGGER.error(String.format("Error with %s StatusCode: %s", response.getStatusCode().value(),
                responseString));
        throw new Exception(String.format("Error with %s StatusCode: %s", response.getStatusCode().value(),
                responseString));
    }
}

From source file:org.apereo.portal.events.tincan.providers.DefaultTinCanAPIProvider.java

/**
 * Send a request to the LRS./*from w  ww .ja va2  s.c  om*/
 *
 * @param pathFragment the URL.  Should be relative to the xAPI API root
 * @param method the HTTP method
 * @param getParams the set of GET params
 * @param postData the post data.
 * @param returnType the type of object to expect in the response
 * @param <T> The type of object to expect in the response
 * @return The response object.
 */
protected <T> ResponseEntity<T> sendRequest(String pathFragment, HttpMethod method,
        List<? extends NameValuePair> getParams, Object postData, Class<T> returnType) {
    HttpHeaders headers = new HttpHeaders();
    headers.add(XAPI_VERSION_HEADER, XAPI_VERSION_VALUE);

    // make multipart data is handled correctly.
    if (postData instanceof MultiValueMap) {
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    }

    URI fullURI = buildRequestURI(pathFragment, getParams);

    HttpEntity<?> entity = new HttpEntity<>(postData, headers);
    ResponseEntity<T> response = restTemplate.exchange(fullURI, method, entity, returnType);

    return response;
}