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:org.flowable.rest.service.api.runtime.task.TaskAttachmentContentResource.java

@ApiOperation(value = "Get the content for an attachment", tags = {
        "Tasks" }, notes = "The response body contains the binary content. By default, the content-type of the response is set to application/octet-stream unless the attachment type contains a valid Content-type.")
@ApiResponses(value = {/*w  w  w.  j av  a2 s.c om*/
        @ApiResponse(code = 200, message = "Indicates the task and attachment was found and the requested content is returned."),
        @ApiResponse(code = 404, message = "Indicates the requested task was not found or the task doesnt have an attachment with the given id or the attachment doesnt have a binary stream available. Status message provides additional information.") })
@RequestMapping(value = "/runtime/tasks/{taskId}/attachments/{attachmentId}/content", method = RequestMethod.GET)
public ResponseEntity<byte[]> getAttachmentContent(
        @ApiParam(name = "taskId") @PathVariable("taskId") String taskId,
        @ApiParam(name = "attachmentId") @PathVariable("attachmentId") String attachmentId,
        HttpServletResponse response) {

    HistoricTaskInstance task = getHistoricTaskFromRequest(taskId);
    Attachment attachment = taskService.getAttachment(attachmentId);

    if (attachment == null || !task.getId().equals(attachment.getTaskId())) {
        throw new FlowableObjectNotFoundException(
                "Task '" + task.getId() + "' doesn't have an attachment with id '" + attachmentId + "'.",
                Attachment.class);
    }

    InputStream attachmentStream = taskService.getAttachmentContent(attachmentId);
    if (attachmentStream == null) {
        throw new FlowableObjectNotFoundException(
                "Attachment with id '" + attachmentId + "' doesn't have content associated with it.",
                Attachment.class);
    }

    HttpHeaders responseHeaders = new HttpHeaders();
    MediaType mediaType = null;
    if (attachment.getType() != null) {
        try {
            mediaType = MediaType.valueOf(attachment.getType());
            responseHeaders.set("Content-Type", attachment.getType());
        } catch (Exception e) {
            // ignore if unknown media type
        }
    }

    if (mediaType == null) {
        responseHeaders.set("Content-Type", "application/octet-stream");
    }

    try {
        return new ResponseEntity<byte[]>(IOUtils.toByteArray(attachmentStream), responseHeaders,
                HttpStatus.OK);
    } catch (Exception e) {
        throw new FlowableException("Error creating attachment data", e);
    }
}

From source file:org.jasig.portlet.courses.dao.xml.HttpClientCoursesDaoImpl.java

/**
 * Get a request entity prepared for basic authentication.
 *//*from   ww  w .  j  a  v a  2  s . co  m*/
protected HttpEntity<?> getRequestEntity(CoursesCacheKey credentials) {
    final String username = credentials.getUsername();
    final char[] password = credentials.getPassword();

    if (log.isDebugEnabled()) {
        boolean hasPassword = password != null;
        log.debug("Preparing HttpEntity for user '" + username + "' (password provided = " + hasPassword + ")");
    }

    HttpHeaders requestHeaders = new HttpHeaders();
    String authString = username.concat(":").concat(new String(password));
    String encodedAuthString = new Base64().encodeToString(authString.getBytes());
    requestHeaders.set("Authorization", "Basic ".concat(encodedAuthString));

    HttpEntity<?> rslt = new HttpEntity<Object>(requestHeaders);
    return rslt;

}

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

private Object insertCookieToHeaderIfApplicable(Object requestBody) {
    HttpEntity<?> httpEntity;//from   w  w w  .j  av 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.kuali.student.cm.course.service.impl.AbstractExportCourseHelperImpl.java

/**
 * Generates a response for the report./*from www  . ja v a 2s  .  co  m*/
 * @return
 */
public ResponseEntity<byte[]> getResponseEntity() {

    byte[] bytes = getBytes();

    HttpHeaders headers = new HttpHeaders();

    /*
     * Setup the header for the response.
     */
    if (isSaveDocument()) {
        // Try to persuade the agent to save the document (in accordance with http://tools.ietf.org/html/rfc2616#section-19.5.1)
        headers.setContentType(MediaType.parseMediaType("application/octet-stream"));
        String contentDisposition = String.format("attachment; filename=%s", getFileName());
        headers.set("Content-Disposition", contentDisposition);
    } else {
        headers.setContentType(MediaType.parseMediaType(getExportFileType().getMimeType()));
        headers.setContentDispositionFormData(getFileName(), getFileName());
    }

    headers.setCacheControl(CurriculumManagementConstants.Export.DOCUMENT_DOWNLOAD_CACHE_CONTROL);

    return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
}

From source file:org.openflamingo.web.fs.HdfsBrowserController.java

/**
 * ?? ./*from www  . j a  v a 2 s .  c o m*/
 *
 * @return REST Response JAXB Object
 */
@RequestMapping(value = "download", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public ResponseEntity download(HttpServletResponse res, @RequestParam String path,
        @RequestParam(defaultValue = "") String engineId) {
    HttpHeaders headers = new HttpHeaders();
    if (org.apache.commons.lang.StringUtils.isEmpty(path)) {
        headers.set("message", message("S_FS_SERVICE", "INVALID_PARAMETER", null));
        return new ResponseEntity(headers, HttpStatus.BAD_REQUEST);
    }

    String filename = FileUtils.getFilename(path);

    try {
        FileSystemCommand command = new FileSystemCommand();
        command.putObject("path", path);
        command.putObject("filename", filename);

        Engine engine = engineService.getEngine(Long.parseLong(engineId));
        FileSystemService fileSystemService = (FileSystemService) lookupService.getService(RemoteService.HDFS,
                engine);
        byte[] bytes = fileSystemService.load(getContext(engine), command);

        res.setHeader("Content-Length", "" + bytes.length);
        res.setHeader("Content-Type", MediaType.APPLICATION_OCTET_STREAM_VALUE);
        res.setHeader("Content-Disposition", MessageFormatter.format("form-data; name={}; filename={}",
                URLEncoder.encode(path, CHARSET), URLEncoder.encode(filename, CHARSET)).getMessage());
        res.setStatus(200);
        FileCopyUtils.copy(bytes, res.getOutputStream());
        res.flushBuffer();
        return new ResponseEntity(HttpStatus.OK);
    } catch (Exception ex) {
        headers.set("message", ex.getMessage());
        if (ex.getCause() != null)
            headers.set("cause", ex.getCause().getMessage());
        return new ResponseEntity(headers, HttpStatus.BAD_REQUEST);
    }
}

From source file:org.openmhealth.shim.runkeeper.RunkeeperShim.java

protected ResponseEntity<ShimDataResponse> getData(OAuth2RestOperations restTemplate,
        ShimDataRequest shimDataRequest) throws ShimException {

    String dataTypeKey = shimDataRequest.getDataTypeKey().trim().toUpperCase();

    RunkeeperDataType runkeeperDataType;
    try {// w w w  . j a  v  a  2 s . co m
        runkeeperDataType = RunkeeperDataType.valueOf(dataTypeKey);
    } catch (NullPointerException | IllegalArgumentException e) {
        throw new ShimException("Null or Invalid data type parameter: " + dataTypeKey
                + " in shimDataRequest, cannot retrieve data.");
    }

    /***
     * Setup default date parameters
     */
    OffsetDateTime now = OffsetDateTime.now();

    OffsetDateTime startDateTime = shimDataRequest.getStartDateTime() == null ? now.minusDays(1)
            : shimDataRequest.getStartDateTime();

    OffsetDateTime endDateTime = shimDataRequest.getEndDateTime() == null ? now.plusDays(1)
            : shimDataRequest.getEndDateTime();

    /*
    Runkeeper defaults to returning a maximum of 25 entries per request (pageSize = 25 by default), so
    we override the default by specifying an arbitrarily large number as the pageSize.
     */
    long numToReturn = 100_000;

    UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(DATA_URL)
            .pathSegment(runkeeperDataType.getEndPointUrl())
            .queryParam("noEarlierThan", startDateTime.toLocalDate())
            .queryParam("noLaterThan", endDateTime.toLocalDate()).queryParam("pageSize", numToReturn)
            .queryParam("detail", true); // added to all endpoints to support summaries

    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", runkeeperDataType.getDataTypeHeader());

    ResponseEntity<JsonNode> responseEntity;
    try {
        responseEntity = restTemplate.exchange(uriBuilder.build().encode().toUri(), GET,
                new HttpEntity<JsonNode>(headers), JsonNode.class);
    } catch (HttpClientErrorException | HttpServerErrorException e) {
        // FIXME figure out how to handle this
        logger.error("A request for RunKeeper data failed.", e);
        throw e;
    }

    if (shimDataRequest.getNormalize()) {
        RunkeeperDataPointMapper<?> dataPointMapper;
        switch (runkeeperDataType) {
        case ACTIVITY:
            dataPointMapper = new RunkeeperPhysicalActivityDataPointMapper();
            break;
        case CALORIES:
            dataPointMapper = new RunkeeperCaloriesBurnedDataPointMapper();
            break;
        default:
            throw new UnsupportedOperationException();
        }

        return ok().body(ShimDataResponse.result(SHIM_KEY,
                dataPointMapper.asDataPoints(singletonList(responseEntity.getBody()))));
    } else {
        return ok().body(ShimDataResponse.result(SHIM_KEY, responseEntity.getBody()));
    }
}

From source file:org.openmrs.module.amrscustomization.web.controller.MRNGeneratorFormController.java

/**
 * handler for mrnGenerator file requests
 * /*from  ww w  . ja v a2s .com*/
 * @param site
 * @param first
 * @param prefix
 * @param count
 * @param response
 * @return
 * @throws ServletException
 */
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<String> generateMRNs(@RequestParam("site") String site, @RequestParam("first") int first,
        @RequestParam("prefix") String prefix, @RequestParam("count") int count) throws Exception {

    // fix prefix
    if (prefix == null)
        prefix = "";

    // render filename
    String filename = site + "_" + first + "-" + (first + (count - 1)) + prefix + ".txt";

    // set headers
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.set("Content-Type", "text/plain");
    responseHeaders.set("Content-Disposition", "attachment; filename=" + filename);

    // render the identifiers
    IdentifierValidator validator = Context.getPatientService().getDefaultIdentifierValidator();
    StringBuilder out = new StringBuilder();
    for (int i = first; i < count + first; i++) {
        try {
            out.append(validator.getValidIdentifier(prefix + i + site) + "\n");
        } catch (UnallowedIdentifierException e) {
            throw new Exception("invalid identifier created");
        }
    }

    // log who generated this list
    log.info("generated " + count + " MRNs for " + site + " starting at " + first);
    AMRSCustomizationService as = Context.getService(AMRSCustomizationService.class);
    as.addMRNGeneratorLogEntry(site, first, count);

    // send the file
    return new ResponseEntity<String>(out.toString(), responseHeaders, HttpStatus.CREATED);
}

From source file:org.paxml.bean.RestTag.java

@Override
protected Object doInvoke(Context context) throws Exception {

    RestTemplate t = new RestTemplate();
    if (!simple) {
        // cancel default error handling
        t.setErrorHandler(new ResponseErrorHandler() {

            @Override//from  w  w  w .java2s .  c  om
            public boolean hasError(ClientHttpResponse response) throws IOException {
                // always say no error
                return false;
            }

            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
                // do nothing
            }

        });
    }
    Object value = getValue();
    HttpHeaders hds = new HttpHeaders();
    if (username != null) {
        String[] auth = PaxmlUtils.makeHttpClientAutorizationHeader(username, password);
        hds.set(auth[0], auth[1]);
    }
    if (headers != null) {
        Map<String, String> map = new LinkedHashMap<String, String>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            hds.set(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
        }
    }
    if (StringUtils.isNotBlank(contentType)) {
        hds.setContentType(org.springframework.http.MediaType.parseMediaType(contentType));
    }
    String reqBody = makeRequestBody(value);
    log.debug("REST request body=" + reqBody);
    HttpEntity<String> entity = new HttpEntity<String>(reqBody, hds);

    ResponseEntity<String> rsp = t.exchange(target, _method, entity, String.class);

    Object body = parseResponse ? parseResponse(rsp) : rsp.getBody();
    if (simple) {
        return body;
    }
    return new RestResult(body, rsp.getHeaders(), rsp.getStatusCode().value());

}

From source file:org.slc.sli.api.security.oauth.AuthController.java

@RequestMapping(value = "token", method = { RequestMethod.POST, RequestMethod.GET })
public ResponseEntity<String> getAccessToken(@RequestParam("code") String authorizationCode,
        @RequestParam("redirect_uri") String redirectUri,
        @RequestHeader(value = "Authorization", required = false) String authz,
        @RequestParam("client_id") String clientId, @RequestParam("client_secret") String clientSecret,
        Model model) throws BadCredentialsException {
    Map<String, String> parameters = new HashMap<String, String>();
    parameters.put("code", authorizationCode);
    parameters.put("redirect_uri", redirectUri);

    String token;/*from w  ww . ja  va  2  s.c  o  m*/
    try {
        token = this.sessionManager.verify(authorizationCode, Pair.of(clientId, clientSecret));
    } catch (OAuthAccessException e) {
        return handleAccessException(e);
    }

    HttpHeaders headers = new HttpHeaders();
    headers.set("Cache-Control", "no-store");
    headers.setContentType(MediaType.APPLICATION_JSON);

    String response = String.format("{\"access_token\":\"%s\"}", token);

    return new ResponseEntity<String>(response, headers, HttpStatus.OK);
}

From source file:org.springframework.boot.actuate.metrics.atsd.AtsdMetricWriter.java

protected HttpHeaders createHeaders() {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(ACCEPTABLE_MEDIA_TYPES);
    headers.setContentType(CONTENT_TYPE);
    headers.set(HttpHeaders.AUTHORIZATION, this.basicAuthorizationHeader);
    return headers;
}