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:com.wavemaker.commons.json.deserializer.HttpHeadersDeSerializer.java

@Override
public HttpHeaders deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    ObjectCodec codec = jp.getCodec();/*from w w  w .j ava2  s  .c o  m*/
    ObjectNode root = codec.readTree(jp);
    Map<String, Object> map = ((ObjectMapper) codec).readValue(root.toString(),
            new TypeReference<LinkedHashMap<String, Object>>() {
            });
    HttpHeaders httpHeaders = new HttpHeaders();
    for (Map.Entry<String, Object> entry : map.entrySet()) {
        Object value = entry.getValue();
        if (value instanceof String) {
            httpHeaders.add(entry.getKey(), (String) entry.getValue());
        } else if (value instanceof List) {
            httpHeaders.put(entry.getKey(), (List<String>) value);
        }
    }
    return httpHeaders;
}

From source file:net.acesinc.convergentui.content.ContentFetchCommand.java

@Override
protected ContentResponse run() throws Exception {
    log.debug("Getting live content from [ " + location + " ]");
    try {/*  ww w . ja  va2  s.  c o  m*/
        HttpServletRequest request = requestContext.getRequest();
        MultiValueMap<String, String> headers = this.helper.buildZuulRequestHeaders(request);

        if (request.getQueryString() != null && !request.getQueryString().isEmpty()) {
            MultiValueMap<String, String> params = this.helper.buildZuulRequestQueryParams(request);
        }

        HttpHeaders requestHeaders = new HttpHeaders();
        for (String key : headers.keySet()) {
            for (String s : headers.get(key)) {
                requestHeaders.add(key, s);
            }
        }
        HttpEntity requestEntity = new HttpEntity(null, requestHeaders);

        ResponseEntity<Object> exchange = this.restTemplate.exchange(location, HttpMethod.GET, requestEntity,
                Object.class);

        ContentResponse response = new ContentResponse();
        response.setContent(exchange.getBody());
        response.setContentType(exchange.getHeaders().getContentType());
        response.setError(false);

        return response;
    } catch (Exception e) {
        log.debug("Error fetching live content from [ " + location + " ]", e);
        throw e;
    }
}

From source file:com.appglu.impl.UserSessionRequestInterceptor.java

public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
        throws IOException {
    HttpRequestWrapper wrapper = new HttpRequestWrapper(request) {

        @Override//from  w  w  w  . j ava2 s.  co m
        public HttpHeaders getHeaders() {
            HttpHeaders headers = super.getHeaders();

            if (userSessionPersistence.isUserAuthenticated()) {
                String sessionId = userSessionPersistence.getSessionId();
                headers.add(UserSessionPersistence.X_APPGLU_SESSION_HEADER, sessionId);
            }

            return headers;
        }

    };

    return execution.execute(wrapper, body);
}

From source file:ch.heigvd.gamification.api.PointScalesEndpoint.java

@RequestMapping(method = RequestMethod.POST)
@Override//from   w ww.j a v a2 s. co m

public ResponseEntity<Void> pointScalesPost(
        @ApiParam(value = "token that identifies the app sending the request", required = true) @RequestHeader(value = "X-Gamification-Token", required = true) String xGamificationToken,
        @ApiParam(value = "PointScale to add", required = true) @RequestBody PointScaleDTO body) {

    AuthenKey apiKey = authenRepository.findByAppKey(xGamificationToken);
    if (apiKey == null) {
        return new ResponseEntity("apikey not exist", HttpStatus.UNAUTHORIZED);
    }

    PointScale pointScale = new PointScale();
    Application app = apiKey.getApp();

    if (pointscaleRepository.findByNameAndApp(body.getName(), apiKey.getApp()) != null) {

        return new ResponseEntity("poinscat exist already", HttpStatus.UNPROCESSABLE_ENTITY);
    }

    if (body != null) {

        pointScale.setDescription(body.getDescription());
        pointScale.setName(body.getName());
        pointScale.setMinpoint(body.getNbrDePoints());
        pointScale.setApplication(app);
        pointScale.setApplication(app);
        pointscaleRepository.save(pointScale);

        StringBuffer location = request.getRequestURL();
        if (!location.toString().endsWith("/")) {
            location.append("/");
        }
        location.append(pointScale.getId().toString());
        HttpHeaders headers = new HttpHeaders();
        headers.add("Location", location.toString());
        return new ResponseEntity<>(headers, HttpStatus.CREATED);

    } else {
        return new ResponseEntity(HttpStatus.BAD_REQUEST);
    }
}

From source file:org.slc.sli.dashboard.client.RESTClient.java

/**
 * Make a request to a REST service and convert the result to JSON
 * /* ww w  .j a  v a2  s .  c  om*/
 * @param path
 *            the unique portion of the requested REST service URL
 * @param token
 *            not used yet
 *
 * @param fullEntities 
 *             flag for returning expanded entities from the API
 *            
 * @return a {@link JsonElement} if the request is successful and returns valid JSON, otherwise
 *         null.
 * @throws NoSessionException
 */
public String makeJsonRequestWHeaders(String path, String token) {

    if (token != null) {

        URLBuilder url = null;
        if (!path.startsWith("http")) {
            url = new URLBuilder(getSecurityUrl());
            url.addPath(path);
        } else {
            url = new URLBuilder(path);
        }

        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Bearer " + token);
        HttpEntity entity = new HttpEntity(headers);
        logger.debug("Accessing API at: {}", url);
        HttpEntity<String> response = null;
        try {
            response = exchange(template, url.toString(), HttpMethod.GET, entity, String.class);
        } catch (HttpClientErrorException e) {
            logger.debug("Catch HttpClientException: {}", e.getStatusCode());
        }
        if (response == null) {
            return null;
        }
        return response.getBody();
    }
    logger.debug("Token is null in call to RESTClient for path {}", path);

    return null;
}

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

@Test
public void testGetRequestHeaders() {
    HttpHeaders expected = new HttpHeaders();
    expected.add("MyHeaderA", "value1a");
    expected.add("MyHeaderA", "value1b");
    expected.add("MyHeaderB", "value2");
    expected.add("MyHeaderC", "value3");

    mockHeaders(expected);/*from   w ww. ja  v a 2s  .  com*/
    HttpHeaders actual = this.testee.getRequestHeaders();

    assertThat(actual).isEqualTo(expected);
}

From source file:se.vgregion.alfrescoclient.service.AlfrescoService.java

/**
 * Sets up the Http request entity./*from   w w w .  j a v a 2s.co m*/
 *
 * @param ssoUser user id for the user that the API calls should performed as.
 * @return Http entity
 */
private HttpEntity<String> setUpHttpEntity(String ssoUser) {
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.add(ssoUserHeaderField, ssoUser);
    HttpEntity<String> httpEntity = new HttpEntity<String>(httpHeaders);

    return httpEntity;

}

From source file:com.orange.cepheus.cep.EventSinkListener.java

/**
 * Set custom headers for Brokers either from the Broker section or from the actual tenant configuration
 *///www .  ja v  a 2 s. c  o m
private HttpHeaders getHeadersForBroker(Broker broker) {
    HttpHeaders httpHeaders = ngsiClient.getRequestHeaders(broker.getUrl());
    if (broker.getServiceName() != null) {
        httpHeaders.add("Fiware-Service", broker.getServiceName());
    } else if (configuration.getService() != null) {
        httpHeaders.add("Fiware-Service", configuration.getService());
    }
    if (broker.getServicePath() != null) {
        httpHeaders.add("Fiware-ServicePath", broker.getServicePath());
    } else if (configuration.getServicePath() != null) {
        httpHeaders.add("Fiware-ServicePath", configuration.getServicePath());
    }
    if (broker.getAuthToken() != null) {
        httpHeaders.add("X-Auth-Token", broker.getAuthToken());
    }
    return httpHeaders;
}

From source file:uk.ac.ebi.emma.controller.BiblioManagementListController.java

/**
 * Deletes the biblio identified by <b>id</b>. This method is configured as
 * a GET because it is intended to be called as an ajax call. Using GET
 * avoids re-posting problems with the back button. NOTE: It is the caller's
 * responsibility to insure there are no foreign key constraints.
 * //from  w ww .  j a  v  a2 s.  c om
 * @param biblio_key primary key of the biblio to be deleted
 * @return a JSON string containing 'status' [ok or fail], and a message [
 * empty string if status is ok; error message otherwise]
 */
@RequestMapping(value = "/deleteBiblio", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<String> deleteBiblio(@RequestParam int biblio_key) {
    String status, message;

    try {
        bibliosManager.delete(biblio_key);
        status = "ok";
        message = "";
    } catch (Exception e) {
        status = "fail";
        message = e.getLocalizedMessage();
    }

    JSONObject returnStatus = new JSONObject();
    returnStatus.put("status", status);
    returnStatus.put("message", message);
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/json; charset=utf-8");

    return new ResponseEntity(returnStatus.toJSONString(), headers, HttpStatus.OK);
}

From source file:com.embedler.moon.graphql.boot.sample.test.GenericTodoSchemaParserTest.java

@Test
public void restSchemaDoesNotExistsTest() throws IOException {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
    headers.add("graphql-schema", "no-such-schema");

    GraphQLServerRequest qlQuery = new GraphQLServerRequest("{viewer{ id }}");

    HttpEntity<GraphQLServerRequest> httpEntity = new HttpEntity<>(qlQuery, headers);
    ResponseEntity<GraphQLServerResult> responseEntity = restTemplate.exchange(
            "http://localhost:" + port + "/graphql", HttpMethod.POST, httpEntity, GraphQLServerResult.class);

    GraphQLServerResult result = responseEntity.getBody();
    Assert.assertFalse(CollectionUtils.isEmpty(result.getErrors()));
    LOGGER.info(objectMapper.writeValueAsString(result));
}