Example usage for org.springframework.http HttpHeaders set

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

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:business.services.PaNumberService.java

public HttpEntity<InputStreamResource> writeAllPaNumbers(List<LabRequestRepresentation> labRequests)
        throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Writer writer = new OutputStreamWriter(out, PA_NUMBERS_DOWNLOAD_CHARACTER_ENCODING);
    CSVWriter csvwriter = new CSVWriter(writer, ',', '"');
    csvwriter.writeNext(PA_NUMBERS_HEADER);
    for (LabRequestRepresentation labRequest : labRequests) {
        String labRequestCode = labRequest.getLabRequestCode();
        String status = labRequest.getStatus().toString();
        String labName = labRequest.getLab().getName();
        String requesterName = labRequest.getRequesterName();
        String requesterEmail = labRequest.getRequesterEmail();
        String requesterTelephone = labRequest.getRequesterTelephone();
        String labRequestSentDate = labRequest.getSendDate() == null ? "" : labRequest.getSendDate().toString();
        for (PathologyRepresentation item : labRequest.getPathologyList()) {
            csvwriter.writeNext(new String[] { labRequestCode, status, item.getPaNumber(), labName,
                    requesterName, requesterEmail, requesterTelephone, labRequestSentDate });
        }/*  w  w  w . jav  a 2 s.  c  om*/
    }
    csvwriter.flush();
    writer.flush();
    out.flush();
    InputStream in = new ByteArrayInputStream(out.toByteArray());
    csvwriter.close();
    writer.close();
    out.close();
    InputStreamResource resource = new InputStreamResource(in);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.valueOf("text/csv;charset=" + PA_NUMBERS_DOWNLOAD_CHARACTER_ENCODING));
    String filename = "pa_numbers.csv";
    headers.set("Content-Disposition", "attachment; filename=" + filename);
    HttpEntity<InputStreamResource> response = new HttpEntity<InputStreamResource>(resource, headers);
    return response;
}

From source file:org.apigw.util.OAuthTestHelper.java

public ResponseEntity<Void> attemptToGetConfirmationPage(String clientId, String redirectUri, String scope) {

    String cookie = loginAndGrabCookie();

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
    headers.set("Cookie", cookie);

    return serverRunning.getForResponse(getAuthorizeUrl(clientId, redirectUri, scope), headers);

}

From source file:io.kahu.hawaii.util.spring.HawaiiControllerExceptionHandler.java

private ResponseEntity<String> handleException(Throwable throwable, int httpStatusCode, JSONObject error) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    Object hawaiiTxId = LoggingContext.get().get("tx.id");
    if (hawaiiTxId != null) {
        headers.set(X_HAWAII_TRANSACTION_ID_HEADER, hawaiiTxId.toString());
    }/*from w  w w . java  2  s .co  m*/
    JSONObject json = new JSONObject();
    try {
        json.put("status", httpStatusCode);
        json.put("data", new JSONArray());
        json.put("error", error);
    } catch (JSONException exc) {
        logManager.debug(CoreLoggers.SERVER_EXCEPTION, exc.getMessage(), exc);
    }

    log(throwable);

    return ResponseEntity.ok().headers(headers).body(json.toString());
}

From source file:org.apigw.util.OAuthTestHelper.java

public String getAuthorizationCode(String clientId, String redirectUri, String scope) {
    String cookie = loginAndGetConfirmationPage(clientId, redirectUri, scope);
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
    headers.set("Cookie", cookie);
    MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    formData.add("user_oauth_approval", "true");
    ResponseEntity<Void> result = serverRunning.postForStatus("/apigw-auth-server-web/oauth/authorize", headers,
            formData);/*  w w w.j  a  va2 s.co  m*/
    assertEquals(HttpStatus.FOUND, result.getStatusCode());
    // Get the authorization code using the same session
    return getAuthorizationCode(result);
}

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

public Cancion[] getRatings(String apiKey) throws IOException {
    HttpHeaders header = new HttpHeaders();
    header.set("Authorization", apiKey);
    HttpEntity entity = new HttpEntity(header);
    String lista = new String();
    HttpEntity<String> response;
    response = new RestTemplate().exchange("http://ceatic.ujaen.es:8075/radioapi/v2/ratings", HttpMethod.GET,
            entity, String.class, lista);

    String canc = response.getBody();
    StringTokenizer st = new StringTokenizer(canc, "[", true);
    st.nextToken();/*from   www .jav a  2 s  .co  m*/
    if (!st.hasMoreTokens()) {
        return null;
    }
    st.nextToken();
    canc = "[" + st.nextToken();

    try {

        ObjectMapper a = new ObjectMapper();
        ItemPuntu[] listilla = a.readValue(canc, ItemPuntu[].class);
        Vector<Integer> ids = new Vector<>();
        Vector<Cancion> punt = new Vector<>();
        //como jamendo solo devuelve 10 canciones llamamos las veces necesarias
        for (int i = 0; i < (listilla.length / 10) + 1; ++i) {
            ids.clear();
            //aunque le mandemos mas ids de la cuenta solo devolvera las 10 primeras canciones y 
            //de esta forma controlamos el desborde
            for (int j = i * 10; j < listilla.length; ++j) {
                ids.add(listilla[j].getId());
            }
            Cancion[] listilla1 = jamendo.canciones(ids);
            for (int k = 0; k < listilla1.length; ++k) {
                punt.add(listilla1[k]);
            }
        }

        for (int i = 0; i < punt.size(); ++i) {
            punt.get(i).setRating(listilla[i].getRating());
            punt.get(i).setFav(listilla[i].getFav());
        }

        return punt.toArray(new Cancion[punt.size()]);

    } catch (Exception e) {
        //return null;
        throw new IOException("no se han recibido canciones");
    }

}

From source file:us.polygon4.izzymongo.controller.AppController.java

/**
 * Exports database schema as FreeMind map
 * /*from w  w  w  .  ja va2  s  .com*/
* @param fileName database name
* @return fileName + ".mm"
* @throws Exception
*/
@RequestMapping(value = "/export/{fileName}", method = RequestMethod.GET)
public HttpEntity<byte[]> createExport(@PathVariable("fileName") String fileName) throws Exception {
    byte[] documentBody = null;
    documentBody = service.getDbSchema(fileName);
    fileName = fileName + ".mm";
    HttpHeaders header = new HttpHeaders();
    header.setContentType(new MediaType("application", "xml"));
    header.set("Content-Disposition", "attachment; filename=" + fileName.replace(" ", "_"));
    header.setContentLength(documentBody.length);

    return new HttpEntity<byte[]>(documentBody, header);
}

From source file:org.starfishrespect.myconsumption.server.business.sensors.flukso.FluksoRetriever.java

/**
 * Retrieves the parameters of the sensor from the API
 *
 * @return The parameters of this sensor
 * @throws RetrieveException if any error occurs
 *///from  www  .  jav a  2 s.  co m
private FluksoParams retrieveParams() throws RetrieveException {
    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", "application/json");
    headers.set("X-Version", "1.0");
    headers.set("X-Token", sensor.getToken());
    HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
    String url = "https://api.flukso.net/sensor/" + sensor.getFluksoId() + "?param=all";
    try {
        FluksoParams params = restTemplate.exchange(url, HttpMethod.GET, entity, FluksoParams.class).getBody();
    } catch (ResourceAccessException e) {
        throw new RetrieveException("Unknown retrieve exceptions");
    } catch (HttpClientErrorException httpError) {
        int errorCode = httpError.getStatusCode().value();
        switch (httpError.getStatusCode().value()) {
        case HttpStatus.SC_UNAUTHORIZED:
        case HttpStatus.SC_BAD_REQUEST:
            throw new RequestException(errorCode, "Bad sensor id or token");
        case HttpStatus.SC_NOT_FOUND:
            throw new RequestException(errorCode, "API not found");
        case HttpStatus.SC_INTERNAL_SERVER_ERROR:
            throw new ServerException(errorCode, "Resource not found");
        default:
            throw new RetrieveException("Unknown retrieve exceptions");
        }
    }
    return params;
}

From source file:edu.colorado.orcid.impl.OrcidServicePublicImpl.java

public String createOrcid(String email, String givenNames, String familyName)
        throws OrcidException, OrcidEmailExistsException, OrcidHttpException {

    String newOrcid = null;//w w w. j  av a 2  s. c o  m

    log.debug("Creating ORCID...");
    log.debug("email: " + email);
    log.debug("givenNames: " + givenNames);
    log.debug("familyName: " + familyName);

    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", "application/xml");
    headers.set("Content-Type", "application/vdn.orcid+xml");
    headers.set("Authorization", "Bearer " + orcidCreateToken);

    OrcidMessage message = new OrcidMessage();
    message.setEmail(email);
    message.setGivenNames(givenNames);
    message.setFamilyName(familyName);
    message.setMessageVersion(orcidMessageVersion);
    //TODO Affiliation should be set based on organization once faculty from more than one organization are processed
    message.setAffiliationType(OrcidMessage.AFFILIATION_TYPE_EMPLOYMENT);
    message.setAffiliationOrganizationName(OrcidMessage.CU_BOULDER);
    message.setAffiliationOrganizationAddressCity(OrcidMessage.BOULDER);
    message.setAffiliationOrganizationAddressRegion(OrcidMessage.CO);
    message.setAffiliationOrganizationAddressCountry(OrcidMessage.US);
    message.setAffiliationOrganizationDisambiguatedId(OrcidMessage.DISAMBIGUATED_ID_CU_BOULDER);
    message.setAffiliationOrganizationDisambiguationSource(OrcidMessage.DISAMBIGUATION_SOURCE_RINGOLD);

    HttpEntity entity = new HttpEntity(message, headers);

    log.debug("Configured RestTemplate Message Converters...");
    List<HttpMessageConverter<?>> converters = orcidRestTemplate.getMessageConverters();
    for (HttpMessageConverter<?> converter : converters) {
        log.debug("converter: " + converter);
        log.debug("supported media types: " + converter.getSupportedMediaTypes());
        log.debug("converter.canWrite(String.class, MediaType.APPLICATION_XML): "
                + converter.canWrite(String.class, MediaType.APPLICATION_XML));
        log.debug("converter.canWrite(Message.class, MediaType.APPLICATION_XML): "
                + converter.canWrite(OrcidMessage.class, MediaType.APPLICATION_XML));
    }

    log.debug("Request headers: " + headers);

    HttpStatus responseStatusCode = null;
    String responseBody = null;

    try {
        if (useTestHttpProxy.equalsIgnoreCase("TRUE")) {
            log.info("Using HTTP ***TEST*** proxy...");
            System.setProperty("http.proxyHost", testHttpProxyHost);
            System.setProperty("http.proxyPort", testHttpProxyPort);
            log.info("http.proxyHost: " + System.getProperty("http.proxyHost"));
            log.info("http.proxyPort: " + System.getProperty("http.proxyPort"));
        }
        ResponseEntity<String> responseEntity = orcidRestTemplate.postForEntity(orcidCreateURL, entity,
                String.class);
        responseStatusCode = responseEntity.getStatusCode();
        responseBody = responseEntity.getBody();
        HttpHeaders responseHeaders = responseEntity.getHeaders();
        URI locationURI = responseHeaders.getLocation();
        String uriString = locationURI.toString();
        newOrcid = extractOrcid(uriString);
        log.debug("HTTP response status code: " + responseStatusCode);
        log.debug("HTTP response headers:     " + responseHeaders);
        log.debug("HTTP response body:        " + responseBody);
        log.debug("HTTP response location:    " + locationURI);
        log.debug("New ORCID:                 " + newOrcid);
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode().equals(HttpStatus.BAD_REQUEST)) {
            log.debug(e.getStatusCode());
            log.debug(e.getResponseBodyAsString());
            log.debug(e.getMessage());
            throw new OrcidEmailExistsException(e);
        }
        OrcidHttpException ohe = new OrcidHttpException(e);
        ohe.setStatusCode(e.getStatusCode());
        throw ohe;
    }

    return newOrcid;
}

From source file:fr.mby.opa.pics.web.controller.ImageController.java

@RequestMapping(value = "{id}", method = RequestMethod.GET)
public ResponseEntity<byte[]> getImage(@PathVariable final Long id, final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {

    ResponseEntity<byte[]> responseEntity = null;

    if (id != null) {

        final BinaryImage image = this.pictureDao.findImageById(id);
        if (image != null) {
            final byte[] thumbnailData = image.getData();

            final HttpHeaders responseHeaders = new HttpHeaders();
            responseHeaders.setContentType(MediaType.parseMediaType("image/" + image.getFormat()));
            responseHeaders.setContentLength(thumbnailData.length);
            responseHeaders.set("Content-Disposition", "filename=\"" + image.getFilename() + '\"');

            responseEntity = new ResponseEntity<byte[]>(thumbnailData, responseHeaders, HttpStatus.OK);
        }/*  w  w  w .j a  va  2s  .  c  o m*/
    }

    if (responseEntity == null) {
        responseEntity = new ResponseEntity<byte[]>(null, null, HttpStatus.NOT_FOUND);
    }

    return responseEntity;
}

From source file:org.apigw.util.OAuthTestHelper.java

public String loginAndGetConfirmationPage(String clientId, String redirectUri, String scope) {

    String cookie = loginAndGrabCookie();

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
    headers.set("Cookie", cookie);

    ServerRunning.UriBuilder uri = serverRunning.buildUri("/apigw-auth-server-web/oauth/authorize")
            .queryParam("response_type", "code").queryParam("state", "gzzFqB!!!").queryParam("scope", scope);
    if (clientId != null) {
        uri.queryParam("client_id", clientId);
    }/*from w ww.  j a  va  2 s .  co m*/
    if (redirectUri != null) {
        uri.queryParam("redirect_uri", redirectUri);
    }

    ResponseEntity<String> response = serverRunning.getForString(uri.pattern(), headers, uri.params());

    // The confirm access page should be returned

    assertTrue(response.getBody().contains("API Test"));

    return cookie;

}