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.encuestame.oauth1.support.OAuth1Support.java

/**
 *
 * @param tokenUrl/*w w  w.j ava  2  s.com*/
 * @param tokenRequestParameters
 * @param additionalParameters
 * @param tokenSecret
 * @return
 * @throws EnMeOAuthSecurityException
 */
protected OAuth1Token getTokenFromProvider(String tokenUrl, Map<String, String> tokenRequestParameters,
        Map<String, String> additionalParameters, String tokenSecret) throws EnMeOAuthSecurityException {
    log.debug("getTokenFromProvider TOKEN " + tokenUrl);
    log.debug("getTokenFromProvider TOKEN " + tokenRequestParameters);
    log.debug("getTokenFromProvider TOKEN " + additionalParameters);
    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization",
            getAuthorizationHeaderValue(tokenUrl, tokenRequestParameters, additionalParameters, tokenSecret));
    MultiValueMap<String, String> bodyParameters = new LinkedMultiValueMap<String, String>();
    bodyParameters.setAll(additionalParameters);
    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(
            bodyParameters, headers);
    Map<String, String> responseMap = null;
    /*
     * org.springframework.web.client.HttpServerErrorException: 503 Service Unavailable
     * Sometimes, api service are unavailable, like the famous twitter over capacity
     */
    try {
        ResponseEntity<String> response = getRestTemplate().exchange(tokenUrl, HttpMethod.POST, request,
                String.class);
        responseMap = parseResponse(response.getBody());
    } catch (HttpServerErrorException e) {
        e.printStackTrace();
        throw new EnMeOAuthSecurityException(e);
    } catch (HttpClientErrorException e) {
        // normally if the social credentials are wrong
        e.printStackTrace();
        throw new EnMeBadCredentialsException(e.getMessage());
    } catch (Exception e) {
        // another kind of error, possible wrong configuration
        //TODO : only happends with twitter
        e.printStackTrace();
        throw new EnMeBadCredentialsException(e.getMessage());
    }

    return new OAuth1Token(responseMap.get("oauth_token"), responseMap.get("oauth_token_secret"));
}

From source file:org.fenixedu.bennu.social.domain.api.BitbucketAPI.java

public HttpEntity<MultiValueMap<String, String>> getAccessTokenRequest(String code) {
    MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
    map.add("grant_type", "authorization_code");
    map.add("code", code);

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    String plainCreds = getClientId() + ":" + getClientSecret();
    byte[] plainCredsBytes = plainCreds.getBytes();
    byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
    String base64Creds = new String(base64CredsBytes);
    headers.add("Authorization", "Basic " + base64Creds);

    return new HttpEntity<MultiValueMap<String, String>>(map, headers);
}

From source file:org.jgrades.rest.client.StatefullRestTemplate.java

private Object insertCookieToHeaderIfApplicable(Object requestBody) {
    HttpEntity<?> httpEntity;/*from   w  w w .j  a  v a 2s  . c  om*/

    if (requestBody instanceof HttpEntity) {
        httpEntity = (HttpEntity<?>) requestBody;
    } else if (requestBody != null) {
        httpEntity = new HttpEntity<Object>(requestBody);
    } else {
        httpEntity = HttpEntity.EMPTY;
    }

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.putAll(httpEntity.getHeaders());

    httpHeaders.set("Accept", MediaType.APPLICATION_JSON_VALUE);
    if (httpHeaders.getContentType() == null) {
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
    }

    if (StringUtils.isNotEmpty(cookie)) {
        httpHeaders.add("Cookie", cookie);
    }

    return new HttpEntity<>(httpEntity.getBody(), httpHeaders);
}

From source file:org.openlegacy.terminal.mvc.web.DefaultGenericController.java

/**
 * handle ajax request for load more/*from   w  w  w. ja v  a  2s.  co  m*/
 * 
 * @return
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
@RequestMapping(value = "/{screen}/more", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<String> more(@PathVariable("screen") String entityName) {
    // sync the current entity
    ScreenEntity screenBefore = (ScreenEntity) terminalSession.getEntity(entityName);
    ScreenEntity nextScreen = terminalSession.doAction(TerminalActions.PAGEDOWN());

    TableScrollStopConditions tableScrollStopConditions = SpringUtil.getDefaultBean(applicationContext,
            TableScrollStopConditions.class);

    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/text; charset=utf-8");

    Map<String, ScreenTableDefinition> tableDefinitions = tablesDefinitionProvider
            .getTableDefinitions(nextScreen.getClass());
    if (tableDefinitions.size() == 0) {
        logger.error("Next screen after PAGEDOWN does not contain a table");
        return new ResponseEntity<String>("", headers, HttpStatus.OK);
    }

    if (tableScrollStopConditions.shouldStop(screenBefore, nextScreen)) {
        return new ResponseEntity<String>("", headers, HttpStatus.OK);
    }

    List<?> records = ScrollableTableUtil.getSingleScrollableTable(tablesDefinitionProvider, nextScreen);
    String result = new JSONSerializer().serialize(records);
    return new ResponseEntity<String>(result, headers, HttpStatus.OK);
}

From source file:org.openlegacy.terminal.mvc.web.DefaultGenericController.java

/**
 * handle Ajax request for auto compete fields
 * /*w  w w.j  ava2s. co  m*/
 * @param screenEntityName
 * @param fieldName
 * @return JSON content
 */
@RequestMapping(value = "/{screen}/{field}Values", method = RequestMethod.GET, headers = "X-Requested-With=XMLHttpRequest")
@ResponseBody
public ResponseEntity<String> autoCompleteJson(@PathVariable("screen") String screenEntityName,
        @PathVariable("field") String fieldName) {
    ScreenEntity screenEntity = (ScreenEntity) terminalSession.getEntity(screenEntityName);

    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/text; charset=utf-8");
    @SuppressWarnings("unchecked")
    Map<Object, Object> fieldValues = (Map<Object, Object>) ReflectionUtil.invoke(screenEntity,
            MessageFormat.format("get{0}Values", StringUtils.capitalize(fieldName)));

    String result = JsonSerializationUtil.toDojoFormat(fieldValues);
    return new ResponseEntity<String>(result, headers, HttpStatus.OK);
}

From source file:org.openlegacy.terminal.mvc.web.DefaultGenericScreensController.java

/**
 * handle ajax request for load more/* w  ww  . j a  v  a 2 s .c o m*/
 * 
 * @return
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
@RequestMapping(value = "/{screen}/more", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<String> more(@PathVariable("screen") String entityName) {
    // sync the current entity
    ScreenEntity screenBefore = (ScreenEntity) getSession().getEntity(entityName);
    ScreenEntity nextScreen = getSession().doAction(TerminalActions.PAGE_DOWN());

    TableScrollStopConditions tableScrollStopConditions = SpringUtil.getDefaultBean(applicationContext,
            TableScrollStopConditions.class);

    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/text; charset=utf-8");

    Map<String, ScreenTableDefinition> tableDefinitions = tablesDefinitionProvider
            .getTableDefinitions(nextScreen.getClass());
    if (tableDefinitions.size() == 0) {
        logger.error("Next screen after PAGEDOWN does not contain a table");
        return new ResponseEntity<String>("", headers, HttpStatus.OK);
    }

    if (tableScrollStopConditions.shouldStop(screenBefore, nextScreen)) {
        return new ResponseEntity<String>("", headers, HttpStatus.OK);
    }

    List<?> records = ScrollableTableUtil.getSingleScrollableTable(tablesDefinitionProvider, nextScreen);
    String result = new JSONSerializer().serialize(records);
    return new ResponseEntity<String>(result, headers, HttpStatus.OK);
}

From source file:org.openlegacy.terminal.mvc.web.DefaultGenericScreensController.java

/**
 * handle Ajax request for auto compete fields
 * //  w  ww. j a  va 2s.  c  o  m
 * @param screenEntityName
 * @param fieldName
 * @return JSON content
 */
@RequestMapping(value = "/{screen}/{field}Values", method = RequestMethod.GET, headers = "X-Requested-With=XMLHttpRequest")
@ResponseBody
public ResponseEntity<String> autoCompleteJson(@PathVariable("screen") String screenEntityName,
        @PathVariable("field") String fieldName, @RequestParam(value = "name", required = false) String text) {

    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/text; charset=utf-8");

    if (text != null) {
        text = text.replace("*", "");
    }

    Map<Object, Object> fieldValues = tableBindUtil.getRecords(getSession(), text, screenEntityName, fieldName);

    String result = JsonSerializationUtil.toDojoFormat(fieldValues, text);
    return new ResponseEntity<String>(result, headers, HttpStatus.OK);
}

From source file:org.openlmis.auth.service.BaseCommunicationService.java

protected String obtainAccessToken() {
    String plainCreds = clientId + ":" + clientSecret;
    byte[] plainCredsBytes = plainCreds.getBytes();
    byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
    String base64Creds = new String(base64CredsBytes);

    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Basic " + base64Creds);

    HttpEntity<String> request = new HttpEntity<>(headers);

    Map<String, Object> params = new HashMap<>();
    params.put("grant_type", "client_credentials");

    ResponseEntity<?> response = restTemplate.exchange(buildUri(authorizationUrl, params), HttpMethod.POST,
            request, Object.class);

    return ((Map<String, String>) response.getBody()).get(ACCESS_TOKEN);
}

From source file:org.openlmis.upload.AuthService.java

/**
 * Retrieves access token from the auth service.
 *
 * @return token/*from ww w.  java2  s  .  co m*/
 */
public String obtainAccessToken() {
    String plainCreds = configuration.getClientId() + ":" + configuration.getClientSecret();
    byte[] plainCredsBytes = plainCreds.getBytes();
    byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
    String base64Creds = new String(base64CredsBytes);

    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Basic " + base64Creds);
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
    form.add("username", configuration.getLogin());
    form.add("password", configuration.getPassword());

    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(form, headers);
    RequestParameters params = RequestParameters.init().set("grant_type", "password");

    try {
        ResponseEntity<?> response = restTemplate.exchange(
                createUri(configuration.getHost() + "/api/oauth/token", params), HttpMethod.POST, request,
                Object.class);
        return ((Map<String, String>) response.getBody()).get(ACCESS_TOKEN);
    } catch (RestClientException ex) {
        throw new AuthorizationException("Cannot obtain access token using the provided credentials. "
                + "Please verify they are correct.", ex);
    }
}

From source file:org.opentestsystem.authoring.testauth.rest.FileGroupController.java

private static HttpHeaders buildResponseHeaders(final int contentLength, final String filename,
        final String contentType) {
    final HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.clear();/*  w w w.ja  v a  2s  .  c  om*/
    responseHeaders.add(org.apache.http.HttpHeaders.CONTENT_TYPE, contentType);
    responseHeaders.setPragma("public");
    responseHeaders.setCacheControl("no-store, must-revalidate");
    responseHeaders.setExpires(Long.valueOf("-1"));
    responseHeaders.setContentDispositionFormData("attachment", filename);
    responseHeaders.setContentLength(contentLength);
    responseHeaders.add(org.apache.http.HttpHeaders.ACCEPT_RANGES, "bytes");
    return responseHeaders;
}