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:jp.go.aist.six.util.core.web.spring.SpringHttpClientImpl.java

/**
 * HTTP POST// w  w  w .  j  ava2 s. com
 *
 * @return
 *  the location, as an URI, where the resource is created.
 * @throws  HttpException
 *  when an exceptional condition occurred during the HTTP method execution.
 */
public <T> String postObject(final String url, final T object, final Class<T> type) {
    _LOG_.debug("HTTP POST: URL=" + url + ", request type=" + type);

    HttpHeaders request_headers = new HttpHeaders();
    request_headers.setContentType(getObjectMediaType());
    HttpEntity<T> request_entity = new HttpEntity<T>(object, request_headers);

    URI location = null;
    try {
        location = _newRestTemplate().postForLocation(url, request_entity);
        //throws RestClientException
    } catch (Exception ex) {
        throw new HttpException(ex);
    }

    return location.toString();
}

From source file:com.cloud.baremetal.networkservice.Force10BaremetalSwitchBackend.java

private HttpHeaders createBasicAuthenticationHeader(BaremetalVlanStruct struct) {
    String plainCreds = String.format("%s:%s", struct.getSwitchUsername(), struct.getSwitchPassword());
    byte[] plainCredsBytes = plainCreds.getBytes();
    byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
    String base64Creds = new String(base64CredsBytes);
    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Basic " + base64Creds);
    headers.setAccept(Arrays.asList(MediaType.ALL));
    headers.setContentType(MediaType.valueOf("application/vnd.yang.data+xml"));
    return headers;
}

From source file:edu.mayo.qdm.webapp.rest.controller.TranslatorController.java

/**
 * Builds the response./*ww w.jav  a 2  s. c  o m*/
 *
 * @param request the request
 * @param bean the bean
 * @param xml the xml
 * @return the object
 */
protected Object buildResponse(HttpServletRequest request, String view, Object bean, String xml) {

    if (this.isHtmlRequest(request)) {
        ModelAndView mav;
        if (StringUtils.isNotBlank(view)) {
            mav = new ModelAndView(view);
        } else {
            mav = new ModelAndView();
        }
        mav.addObject(bean.getClass().getSimpleName(), bean);
        return mav;
    } else {
        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_XML);

        return new ResponseEntity<Object>(xml, headers, HttpStatus.OK);
    }
}

From source file:jp.go.aist.six.util.core.web.spring.SpringHttpClientImpl.java

public <T> T getObject(final String url, final Class<T> response_type, final Object... uri_variables) {
    _LOG_.debug("HTTP GET: URL=" + url + ", response type=" + response_type + ", variables="
            + Arrays.toString(uri_variables));

    HttpHeaders request_headers = new HttpHeaders();
    request_headers.setContentType(getObjectMediaType());
    HttpEntity<?> request_entity = new HttpEntity<Void>(request_headers);

    HttpEntity<T> response = null;
    try {/*ww  w .j  ava 2 s  . co m*/
        response = _newRestTemplate().exchange(url, HttpMethod.GET, request_entity, response_type,
                uri_variables);
        //throws RestClientException
    } catch (Exception ex) {
        throw new HttpException(ex);
    }

    T body = response.getBody();

    return body;
}

From source file:business.services.FileService.java

public HttpEntity<InputStreamResource> download(Long id) {
    try {/*  w  w  w . ja v a2s  . c  o  m*/
        File attachment = fileRepository.findOne(id);
        if (attachment == null) {
            throw new FileNotFound();
        }
        FileSystem fileSystem = FileSystems.getDefault();
        Path path = fileSystem.getPath(uploadPath, attachment.getFilename());
        InputStream input = new FileInputStream(path.toFile());
        InputStreamResource resource = new InputStreamResource(input);
        HttpHeaders headers = new HttpHeaders();
        if (attachment.getMimeType() != null) {
            headers.setContentType(MediaType.valueOf(attachment.getMimeType()));
        } else {
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        }
        headers.set("Content-Disposition", "attachment; filename=" + attachment.getName().replace(" ", "_"));
        HttpEntity<InputStreamResource> response = new HttpEntity<InputStreamResource>(resource, headers);
        return response;
    } catch (IOException e) {
        log.error(e);
        throw new FileDownloadError();
    }
}

From source file:com.courtalon.gigaMvcGalerie.web.ImageController.java

@RequestMapping(value = "/images/thumbdata/{id:[0-9]+}", method = RequestMethod.GET)
@ResponseBody/*from w w w . j  a  va2s. c  o  m*/
public ResponseEntity<FileSystemResource> downloadThumbImage(@PathVariable("id") int id) {
    Image img = imageRepository.findOne(id);
    HttpHeaders respHeaders = new HttpHeaders();
    respHeaders.setContentType(MediaType.parseMediaType("image/jpeg"));
    respHeaders.setContentDispositionFormData("attachment", "thumb_" + id + ".jpeg");

    Optional<File> f = getImageRepository().getImageThumbFile(img.getId());
    if (f.isPresent()) {
        log.info("fichier pour thumbnail image no " + id + " trouv");
        FileSystemResource fsr = new FileSystemResource(f.get());
        return new ResponseEntity<FileSystemResource>(fsr, respHeaders, HttpStatus.OK);
    } else {
        log.info("fichier pour thumbnail image no " + id + " introuvable");
        return new ResponseEntity<FileSystemResource>(HttpStatus.NOT_FOUND);
    }
}

From source file:com.boundlessgeo.geoserver.api.controllers.ThumbnailController.java

/**
 * Retrieve or create the thumbnail for a PublishedInfo
 * @param ws Workspace for the layer/*from  w ww.  j a  v  a  2  s. c o  m*/
 * @param layer LayerInfo or LayerGroupInfo to get the thumbnail of
 * @param hiRes Flag to return hi-res (x2) thumbnail
 * @return HttpEntity containing the thumbnail image as a byte array
 * @throws Exception
 */
public HttpEntity<byte[]> get(WorkspaceInfo ws, PublishedInfo layer, boolean hiRes, HttpServletRequest request)
        throws Exception {
    String path = thumbnailFilename(layer, hiRes);
    FileInputStream in = null;

    File thumbnailFile;
    //If the file has been deleted, recreate it
    if (!config.cacheFile(path).exists()) {
        createThumbnail(ws, layer, request);
    }
    try {
        thumbnailFile = config.cacheFile(path);
        in = new FileInputStream(thumbnailFile);
        byte[] bytes = IOUtils.toByteArray(in);
        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType(MIME_TYPE));
        headers.setLastModified(thumbnailFile.lastModified());
        return new HttpEntity<byte[]>(bytes, headers);
    } finally {
        if (in != null) {
            in.close();
        }
    }
}

From source file:com.courtalon.gigaMvcGalerie.web.ImageController.java

@RequestMapping(value = "/images/data/{id:[0-9]+}", method = RequestMethod.GET)
@ResponseBody//from  www .  j a v  a2s .com
public ResponseEntity<FileSystemResource> downloadImage(@PathVariable("id") int id) {
    Image img = imageRepository.findOne(id);
    if (img == null)
        throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "image not found");
    HttpHeaders respHeaders = new HttpHeaders();
    respHeaders.setContentType(MediaType.parseMediaType(img.getContentType()));
    respHeaders.setContentLength(img.getFileSize());
    respHeaders.setContentDispositionFormData("attachment", img.getFileName());

    Optional<File> f = getImageRepository().getImageFile(img.getId());
    if (f.isPresent()) {
        log.info("fichier pour image no " + id + " trouv");
        FileSystemResource fsr = new FileSystemResource(f.get());
        return new ResponseEntity<FileSystemResource>(fsr, respHeaders, HttpStatus.OK);
    } else {
        log.info("fichier pour image no " + id + " introuvable");
        throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "image file not found");
    }
}

From source file:business.services.ExcerptListService.java

/**
 * Write the excerpt list as a file./*  w w  w.  j  a  v a2s.c  o m*/
 * @param list - the list
 * @param selectedOnly - writes only selected excerpts if true; all excerpts otherwise.
 * @return the resource holding selected excerpts or all (depends on the value of {@value selected}
 * in CSV format.
 */
public HttpEntity<InputStreamResource> writeExcerptList(ExcerptList list, boolean selectedOnly) {
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Writer writer = new OutputStreamWriter(out, EXCERPT_LIST_CHARACTER_ENCODING);
        CSVWriter csvwriter = new CSVWriter(writer, ';', '"');
        csvwriter.writeNext(list.getCsvColumnNames());
        for (ExcerptEntry entry : list.getEntries()) {
            if (!selectedOnly || entry.isSelected()) {
                csvwriter.writeNext(entry.getCsvValues());
            }
        }
        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=" + EXCERPT_LIST_CHARACTER_ENCODING));
        String filename = (selectedOnly ? "selection" : "excerpts") + "_" + list.getProcessInstanceId()
                + ".csv";
        headers.set("Content-Disposition", "attachment; filename=" + filename);
        HttpEntity<InputStreamResource> response = new HttpEntity<InputStreamResource>(resource, headers);
        log.info("Returning reponse.");
        return response;
    } catch (IOException e) {
        log.error(e.getStackTrace());
        log.error(e.getMessage());
        throw new ExcerptListDownloadError();
    }
}