Example usage for org.springframework.http HttpHeaders setContentType

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

Introduction

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

Prototype

public void setContentType(@Nullable MediaType mediaType) 

Source Link

Document

Set the MediaType media type of the body, as specified by the Content-Type header.

Usage

From source file:org.fao.geonet.services.inspireatom.AtomPredefinedFeed.java

private HttpEntity<byte[]> writeOutResponse(String content, String contentType, String contentSubType)
        throws Exception {
    byte[] documentBody = content.getBytes(Constants.ENCODING);

    HttpHeaders header = new HttpHeaders();
    // TODO: character-set encoding ?
    header.setContentType(new MediaType(contentType, contentSubType, Charset.forName(Constants.ENCODING)));
    header.setContentLength(documentBody.length);
    return new HttpEntity<>(documentBody, header);
}

From source file:org.fao.geonet.services.inspireatom.AtomPredefinedFeed.java

private HttpEntity<byte[]> redirectResponse(String location) throws Exception {
    HttpHeaders header = new HttpHeaders();
    // TODO: character-set encoding ?
    header.setContentType(new MediaType("text", "plain", Charset.forName(Constants.ENCODING)));
    header.setContentLength(0);// w w  w . ja v a 2s .c o  m
    header.setLocation(new URI(location));
    return new HttpEntity<>(header);
}

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.glytoucan.web.controller.GlycanController.java

@RequestMapping(value = "/{accessionNumber}/image", method = RequestMethod.GET, produces = {
        MediaType.IMAGE_PNG_VALUE, MediaType.APPLICATION_XML_VALUE, MediaType.IMAGE_JPEG_VALUE })
@ApiOperation(value = "Retrieves glycan image by accession number", response = Byte[].class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Success"),
        @ApiResponse(code = 400, message = "Illegal argument"),
        @ApiResponse(code = 404, message = "Glycan does not exist"),
        @ApiResponse(code = 500, message = "Internal Server Error") })
public @ResponseBody ResponseEntity<byte[]> getGlycanImage(
        @ApiParam(required = true, value = "id of the glycan") @PathVariable("accessionNumber") String accessionNumber,
        @ApiParam(required = false, value = "format of the the glycan image", defaultValue = "png") @RequestParam("format") String format,
        @ApiParam(required = false, value = "notation to use to generate the image", defaultValue = "cfg") @RequestParam("notation") String notation,
        @ApiParam(required = false, value = "style of the image", defaultValue = "compact") @RequestParam("style") String style)
        throws Exception {

    HashMap<String, Object> data = new HashMap<String, Object>();
    data.put(GlycanClientQuerySpec.IMAGE_FORMAT, format);
    data.put(GlycanClientQuerySpec.IMAGE_NOTATION, notation);
    data.put(GlycanClientQuerySpec.IMAGE_STYLE, style);
    data.put(GlycanClientQuerySpec.ID, accessionNumber);
    byte[] bytes = gtcClient.getImage(data);

    HttpHeaders headers = new HttpHeaders();
    if (format == null || format.equalsIgnoreCase("png")) {
        headers.setContentType(MediaType.IMAGE_PNG);
    } else if (format.equalsIgnoreCase("svg")) {
        headers.setContentType(MediaType.APPLICATION_XML);
    } else if (format.equalsIgnoreCase("jpg") || format.equalsIgnoreCase("jpeg")) {
        headers.setContentType(MediaType.IMAGE_JPEG);
    }//from  w  ww.  jav a  2 s.  c  o  m

    int noOfDays = 3650; // 10 years
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DAY_OF_YEAR, noOfDays);
    Date date = calendar.getTime();
    headers.setExpires(date.getTime());
    logger.debug("expires on :>" + date.getTime() + "<");

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

From source file:org.glytoucan.web.controller.GlycanController.java

@RequestMapping(value = "/image/glycan", method = RequestMethod.POST, consumes = { "application/xml",
        "application/json" }, produces = { MediaType.IMAGE_PNG_VALUE, MediaType.APPLICATION_XML_VALUE,
                MediaType.IMAGE_JPEG_VALUE })
@ApiOperation(value = "Retrieves glycan image by accession number", response = Byte[].class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Success"),
        @ApiResponse(code = 400, message = "Illegal argument"),
        @ApiResponse(code = 404, message = "Glycan does not exist"),
        @ApiResponse(code = 415, message = "Media type is not supported"),
        @ApiResponse(code = 500, message = "Internal Server Error") })
public @ResponseBody ResponseEntity<byte[]> getGlycanImageByStructure(
        @RequestBody(required = true) @ApiParam(required = true, value = "Glycan") @Valid GlycanInput glycan,
        @ApiParam(required = false, value = "format of the the glycan image", defaultValue = "png") @RequestParam("format") String format,
        @ApiParam(required = false, value = "notation to use to generate the image", defaultValue = "cfg") @RequestParam("notation") String notation,
        @ApiParam(required = false, value = "style of the image", defaultValue = "compact") @RequestParam("style") String style)
        throws Exception {

    Sugar sugarStructure = importParseValidate(glycan);
    if (sugarStructure == null) {
        throw new IllegalArgumentException("Structure cannot be imported");
    }/* ww  w  .  j  a  v a  2s .  c  om*/
    String exportedStructure;

    // export into GlycoCT
    try {
        exportedStructure = StructureParserValidator.exportStructure(sugarStructure);
    } catch (Exception e) {
        throw new IllegalArgumentException("Cannot export into common encoding: " + e.getMessage());
    }

    logger.debug(exportedStructure);
    byte[] bytes = imageGenerator.getImage(exportedStructure, format, notation, style);

    HttpHeaders headers = new HttpHeaders();
    if (format == null || format.equalsIgnoreCase("png")) {
        headers.setContentType(MediaType.IMAGE_PNG);
    } else if (format.equalsIgnoreCase("svg")) {
        headers.setContentType(MediaType.APPLICATION_XML);
    } else if (format.equalsIgnoreCase("jpg") || format.equalsIgnoreCase("jpeg")) {
        headers.setContentType(MediaType.IMAGE_JPEG);
    }
    return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
}

From source file:org.hoteia.qalingo.web.mvc.controller.customer.CustomerDocumentController.java

@RequestMapping(value = "/documents/**", method = RequestMethod.GET)
public ResponseEntity<byte[]> customerDetails(final HttpServletRequest request, final Model model)
        throws Exception {
    final RequestData requestData = requestUtil.getRequestData(request);
    final String requestURL = request.getRequestURL().toString();
    final Customer customer = requestData.getCustomer();

    if (customer != null) {
        final List<OrderPurchase> orders = orderPurchaseService
                .findOrdersByCustomerId(customer.getId().toString());
        for (Iterator<OrderPurchase> iterator = orders.iterator(); iterator.hasNext();) {
            OrderPurchase order = (OrderPurchase) iterator.next();
            if (requestURL.contains(order.getPrefixHashFolder())) {
                String filename = null;
                String filePath = null;
                if (requestURL.contains(OrderDocumentType.ORDER_CONFIRMATION.getPropertyKey())) {
                    filename = documentService.buildOrderConfirmationFileName(order);
                    filePath = documentService.getOrderConfirmationFilePath(order);

                } else if (requestURL.contains(OrderDocumentType.SHIPPING_CONFIRMATION.getPropertyKey())) {
                    filename = documentService.buildShippingConfirmationFileName(order);
                    filePath = documentService.getShippingConfirmationFilePath(order);

                } else if (requestURL.contains(OrderDocumentType.INVOICE.getPropertyKey())) {
                    filename = documentService.buildInvoiceFileName(order);
                    filePath = documentService.getInvoiceFilePath(order);
                }// www  . jav a2 s  . com

                if (StringUtils.isNotEmpty(filename) && StringUtils.isNotEmpty(filePath)) {
                    Path path = Paths.get(filePath);
                    byte[] contents = Files.readAllBytes(path);

                    HttpHeaders headers = new HttpHeaders();
                    headers.setContentType(MediaType.parseMediaType("application/pdf"));
                    headers.setContentDispositionFormData(filename, filename);
                    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
                    ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(contents, headers,
                            HttpStatus.OK);
                    return response;
                }
            }
        }
        logger.warn("This request can't be display, customer " + customer.getEmail()
                + " is logged, but the Hash doesn't matched:" + requestURL);
    } else {
        logger.warn("This request can't be display, customer is not logged:" + requestURL);
    }
    return null;
}

From source file:org.jasig.cas.support.rest.TicketsResource.java

/**
 * Create new ticket granting ticket.//from  w w w  .  j ava  2  s.co m
 *
 * @param requestBody username and password application/x-www-form-urlencoded values
 * @param request raw HttpServletRequest used to call this method
 * @return ResponseEntity representing RESTful response
 */
@RequestMapping(value = "/tickets", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public final ResponseEntity<String> createTicketGrantingTicket(
        @RequestBody final MultiValueMap<String, String> requestBody, final HttpServletRequest request) {

    Formatter fmt = null;
    try {
        final String tgtId = this.cas.createTicketGrantingTicket(obtainCredential(requestBody));
        final URI ticketReference = new URI(request.getRequestURL().toString() + "/" + tgtId);
        final HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ticketReference);
        headers.setContentType(MediaType.TEXT_HTML);

        fmt = new Formatter();
        fmt.format("<!DOCTYPE HTML PUBLIC \\\"-//IETF//DTD HTML 2.0//EN\\\"><html><head><title>");
        fmt.format("%s %s", HttpStatus.CREATED, HttpStatus.CREATED.getReasonPhrase())
                .format("</title></head><body><h1>TGT Created</h1><form action=\"%s",
                        ticketReference.toString())
                .format("\" method=\"POST\">Service:<input type=\"text\" name=\"service\" value=\"\">")
                .format("<br><input type=\"submit\" value=\"Submit\"></form></body></html>");

        return new ResponseEntity<String>(fmt.toString(), headers, HttpStatus.CREATED);
    } catch (final Throwable e) {
        LOGGER.error(e.getMessage(), e);
        return new ResponseEntity<String>(e.getMessage(), HttpStatus.BAD_REQUEST);
    } finally {
        IOUtils.closeQuietly(fmt);
    }
}

From source file:org.jgrades.rest.client.lic.LicenceManagerServiceClient.java

@Override
public Licence uploadAndInstall(MultipartFile licence, MultipartFile signature) throws IOException {
    Resource licenceResource = getResource(licence);
    Resource signatureResource = getResource(signature);
    try {//  w  ww .  j  av  a  2 s . co  m
        String serviceUrl = backendBaseUrl + "/licence";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        LinkedMultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("licence", licenceResource);
        params.add("signature", signatureResource);

        HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, headers);

        ResponseEntity<Licence> response = restTemplate.exchange(serviceUrl, HttpMethod.POST, requestEntity,
                Licence.class);
        return response.getBody();
    } finally {
        FileUtils.deleteQuietly(licenceResource.getFile());
        FileUtils.deleteQuietly(signatureResource.getFile());
    }
}

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

private Object insertCookieToHeaderIfApplicable(Object requestBody) {
    HttpEntity<?> httpEntity;//from  www  . j  av  a2  s .com

    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.jtalks.jcommune.web.controller.ImageUploadController.java

/**
 * Gets uploaded image and generates preview to send back to the client
 *
 * @param file                 file, that contains uploaded image
 * @param imageControllerUtils object for processing the image
 * @return generated preview of the uploaded image
 * @throws IOException//from w ww .j  av a  2s. co  m
 * @throws ImageProcessException
 */
protected ResponseEntity<String> createPreviewOfImage(MultipartFile file,
        ImageControllerUtils imageControllerUtils) throws IOException, ImageProcessException {
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentType(MediaType.TEXT_HTML);
    Map<String, String> responseContent = new HashMap<>();
    return imageControllerUtils.prepareResponse(file, responseHeaders, responseContent);
}