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.ge.predix.test.utils.ZoneHelper.java

public ResponseEntity<String> registerServicetoZac(final String zoneId,
        final Map<String, Object> trustedIssuers) throws JsonProcessingException {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.add(this.acsZoneHeaderName, zoneId);

    HttpEntity<String> requestEntity = new HttpEntity<>(new ObjectMapper().writeValueAsString(trustedIssuers),
            headers);//from  w  w  w.j ava2s.co  m

    ResponseEntity<String> response = this.zacRestTemplate.exchange(
            this.zacUrl + "/v1/registration/" + this.serviceId + "/" + zoneId, HttpMethod.PUT, requestEntity,
            String.class);
    return response;
}

From source file:cn.org.once.cstack.maven.plugin.utils.RestUtils.java

public Map<String, Object> sendPostForUpload(String url, String path, Log log) throws IOException {
    File file = new File(path);
    FileInputStream fileInputStream = new FileInputStream(file);
    fileInputStream.available();//from   w  ww  .  ja  v a  2  s .  c  o  m
    fileInputStream.close();
    FileSystemResource resource = new FileSystemResource(file);
    Map<String, Object> params = new HashMap<>();
    params.put("file", resource);
    RestTemplate restTemplate = new RestTemplate();
    MultiValueMap<String, Object> postParams = new LinkedMultiValueMap<String, Object>();
    postParams.setAll(params);
    Map<String, Object> response = new HashMap<String, Object>();
    HttpHeaders headers = new HttpHeaders();
    headers.set("Content-Type", "multipart/form-data");
    headers.set("Accept", "application/json");
    headers.add("Cookie", "JSESSIONID=" + localContext.getCookieStore().getCookies().get(0).getValue());
    org.springframework.http.HttpEntity<Object> request = new org.springframework.http.HttpEntity<Object>(
            postParams, headers);
    ResponseEntity<?> result = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
    String body = result.getBody().toString();
    MediaType contentType = result.getHeaders().getContentType();
    HttpStatus statusCode = result.getStatusCode();
    response.put("content-type", contentType);
    response.put("statusCode", statusCode);
    response.put("body", body);

    return response;
}

From source file:org.nuvola.tvshowtime.ApplicationLauncher.java

private void markEpisodeAsWatched(String episode) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    headers.add("User-Agent", TVST_USER_AGENT);
    HttpEntity<String> entity = new HttpEntity<>("filename=" + episode, headers);

    String checkinUrl = new StringBuilder(TVST_CHECKIN_URI).append("?access_token=")
            .append(accessToken.getAccess_token()).toString();

    ResponseEntity<Message> content = tvShowTimeTemplate.exchange(checkinUrl, POST, entity, Message.class);
    Message message = content.getBody();

    if (message.getResult().equals("OK")) {
        LOG.info("Mark " + episode + " as watched in TVShowTime");
    } else {/*  w  w w.j ava 2 s  .  c  o m*/
        LOG.error("Error while marking [" + episode + "] as watched in TVShowTime ");
    }

    // Check if we are below the Rate-Limit of the API
    int remainingApiCalls = Integer.parseInt(content.getHeaders().get(TVST_RATE_REMAINING_HEADER).get(0));
    if (remainingApiCalls == 0) {
        try {
            LOG.info("Consumed all available TVShowTime API calls slots, waiting for new slots ...");
            Thread.sleep(MINUTE_IN_MILIS);
        } catch (Exception e) {
            LOG.error(e.getMessage());

            System.exit(1);
        }
    }
}

From source file:eu.freme.common.rest.OwnedResourceManagingController.java

@RequestMapping(value = "/{identifier}", method = RequestMethod.GET)
@Secured({ "ROLE_USER", "ROLE_ADMIN" })
public ResponseEntity<String> getEntityById(@PathVariable("identifier") String identifier) {
    try {/*from   w ww.j a va  2 s.  co  m*/
        Entity entity = entityDAO.findOneByIdentifier(identifier);
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", SerializationFormatMapper.JSON);
        return new ResponseEntity<>(entity.toJson(), responseHeaders, HttpStatus.OK);
    } catch (AccessDeniedException ex) {
        logger.error(ex.getMessage(), ex);
        throw new eu.freme.common.exception.AccessDeniedException(ex.getMessage());
    } catch (BadRequestException ex) {
        logger.error(ex.getMessage(), ex);
        throw ex;
    } catch (FREMEHttpException ex) {
        logger.error(ex.getMessage());
        throw ex;
    } catch (Exception ex) {
        logger.error(ex.getMessage());
        throw new FREMEHttpException(ex.getMessage());
    }
}

From source file:cz.muni.fi.mushroomhunter.restclient.LocationUpdateSwingWorker.java

@Override
protected Integer doInBackground() throws Exception {
    DefaultTableModel model = (DefaultTableModel) restClient.getTblLocation().getModel();
    int selectedRow = restClient.getTblLocation().getSelectedRow();

    String plainCreds = RestClient.USER_NAME + ":" + RestClient.PASSWORD;
    byte[] plainCredsBytes = plainCreds.getBytes();
    byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
    String base64Creds = new String(base64CredsBytes);

    RestTemplate restTemplate = new RestTemplate();

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    List<MediaType> mediaTypeList = new ArrayList<>();
    mediaTypeList.add(MediaType.ALL);//from  w w w.  j  a v a  2  s.co m
    headers.setAccept(mediaTypeList);

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

    HttpEntity request = new HttpEntity<>(headers);

    ResponseEntity<LocationDto> responseEntity = restTemplate.exchange(
            RestClient.SERVER_URL + "pa165/rest/location/" + RestClient.getLocationIDs().get(selectedRow),
            HttpMethod.GET, request, LocationDto.class);

    LocationDto locationDto = responseEntity.getBody();

    locationDto.setName(restClient.getTfLocationName().getText());
    locationDto.setDescription(restClient.getTfLocationDescription().getText());
    locationDto.setNearCity(restClient.getTfLocationNearCity().getText());

    ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
    String json = ow.writeValueAsString(locationDto);
    request = new HttpEntity(json, headers);

    restTemplate.exchange(RestClient.SERVER_URL + "pa165/rest/location", HttpMethod.PUT, request,
            LocationDto.class);
    return selectedRow;
}

From source file:net.orpiske.tcs.client.services.TagCloudServiceClient.java

private HttpHeaders getHeaders() {
    String user = System.getenv("TCS_USER");
    String password = System.getenv("TCS_PASSWORD");

    if (user == null || user.isEmpty()) {
        logger.fatal("The backend system username is not provided (please set "
                + "the TCS_USER environment variable)");

        throw new InvalidCredentialsException("The backend system username is not provided");
    }/*from  w w  w  . j  a v a  2  s  .  c  om*/

    if (password == null || password.isEmpty()) {
        logger.fatal("The backend system password is not provided (please set "
                + "the TCS_PASSWORD environment variable)");

        throw new InvalidCredentialsException("The backend system password is not provided");
    }

    String auth = user + ":" + password;

    HttpHeaders headers = new HttpHeaders();

    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    byte[] encodedAuth = Base64.encodeBase64(auth.getBytes());
    headers.add("Authorization", "Basic " + new String(encodedAuth));

    return headers;
}

From source file:com.bailen.radioOnline.recursos.REJA.java

public Incidencia ratings(String apiKey, String rating, String idCancion, String fav) {
    MultiValueMap<String, String> params1 = new LinkedMultiValueMap<>();
    params1.add("rating", (rating));
    params1.add("idCancion", (idCancion));
    params1.add("fav", (fav));

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    headers.add("Authorization", apiKey);

    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params1, headers);

    String result = new RestTemplate().postForObject("http://ceatic.ujaen.es:8075/radioapi/v2/ratings", request,
            String.class);

    try {//from   www.j  av a  2  s  .co  m

        ObjectMapper a = new ObjectMapper();
        Incidencia listilla = a.readValue(result, Incidencia.class);
        return listilla;

    } catch (Exception e) {
        return null;

    }

}

From source file:com.salmon.security.xacml.demo.springmvc.rest.HTTPPopulatorsTest.java

private HttpHeaders getHeaders(String auth) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    byte[] encodedAuthorisation = Base64.encode(auth.getBytes());
    headers.add("Authorization", "Basic " + new String(encodedAuthorisation));

    return headers;
}

From source file:cz.muni.fi.mushroomhunter.restclient.MushroomUpdateSwingWorker.java

@Override
protected Integer doInBackground() throws Exception {
    DefaultTableModel model = (DefaultTableModel) restClient.getTblMushroom().getModel();
    int selectedRow = restClient.getTblMushroom().getSelectedRow();

    RestTemplate restTemplate = new RestTemplate();

    String plainCreds = RestClient.USER_NAME + ":" + RestClient.PASSWORD;
    byte[] plainCredsBytes = plainCreds.getBytes();
    byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
    String base64Creds = new String(base64CredsBytes);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    List<MediaType> mediaTypeList = new ArrayList<>();
    mediaTypeList.add(MediaType.ALL);/*from w w  w  .j a  v  a2  s. co  m*/
    headers.setAccept(mediaTypeList);

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

    HttpEntity request = new HttpEntity<>(headers);

    ResponseEntity<MushroomDto> responseEntity = restTemplate.exchange(
            RestClient.SERVER_URL + "pa165/rest/mushroom/" + RestClient.getMushroomIDs().get(selectedRow),
            HttpMethod.GET, request, MushroomDto.class);

    MushroomDto mushroomDto = responseEntity.getBody();

    mushroomDto.setName(restClient.getTfMushroomName().getText());

    SimpleDateFormat formatter = new SimpleDateFormat("dd-MMMM-yyyy", new Locale("en_US"));

    //to create date object only month is used, day and year are fixed values
    String dateInString = "01-" + restClient.getComboBoxMushroomStartOfOccurence().getSelectedItem().toString()
            + "-2000";
    mushroomDto.setStartOfOccurence(formatter.parse(dateInString));

    //to create date object only month is used, day and year are fixed values
    dateInString = "01-" + restClient.getComboBoxMushroomEndOfOccurence().getSelectedItem().toString()
            + "-2000";
    mushroomDto.setEndOfOccurence(formatter.parse(dateInString));

    ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
    String json = ow.writeValueAsString(mushroomDto);
    request = new HttpEntity(json, headers);

    restTemplate.exchange(RestClient.SERVER_URL + "pa165/rest/mushroom", HttpMethod.PUT, request,
            MushroomDto.class);
    return selectedRow;
}

From source file:eu.freme.common.rest.OwnedResourceManagingController.java

@RequestMapping(method = RequestMethod.POST)
@Secured({ "ROLE_USER", "ROLE_ADMIN" })
public ResponseEntity<String> addEntity(
        @RequestParam(value = visibilityParameterName, required = false) String visibility,
        @RequestParam(value = descriptionParameterName, required = false) String description,
        @RequestParam Map<String, String> allParams, @RequestHeader Map<String, String> allHeaders,
        @RequestBody(required = false) String postBody) {
    try {/*from   w w w  .j a  v a2s  .c o m*/

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication instanceof AnonymousAuthenticationToken)
            throw new AccessDeniedException("Access denied");

        Entity entity = createEntity(postBody, allParams, allHeaders);

        if (entity.getOwner() == null)
            entity.setCurrentUserAsOwner();

        if (!Strings.isNullOrEmpty(visibility)) {
            entity.setVisibility(OwnedResource.Visibility.getByString(visibility));
        }

        if (!Strings.isNullOrEmpty(description)) {
            entity.setDescription(description);
        }

        entity = entityDAO.save(entity);

        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", SerializationFormatMapper.JSON);
        return new ResponseEntity<>(entity.toJson(), responseHeaders, HttpStatus.OK);
    } catch (AccessDeniedException ex) {
        logger.error(ex.getMessage(), ex);
        throw new eu.freme.common.exception.AccessDeniedException(ex.getMessage());
    } catch (BadRequestException ex) {
        logger.error(ex.getMessage(), ex);
        throw ex;
    } catch (org.json.JSONException ex) {
        logger.error(ex.getMessage(), ex);
        throw new BadRequestException(ex.getMessage());
    } catch (FREMEHttpException ex) {
        logger.error(ex.getMessage());
        throw ex;
    } catch (Exception ex) {
        logger.error(ex.getMessage());
        throw new FREMEHttpException(ex.getMessage());
    }
}