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.messic.server.facade.controllers.rest.SongController.java

@ApiMethod(path = "/services/songs/{songSid}/dlna", verb = ApiVerb.GET, description = "Get the audio binary from a song resource of an album for a dlna service", produces = {
        MediaType.APPLICATION_OCTET_STREAM_VALUE })
@ApiErrors(apierrors = { @ApiError(code = UnknownMessicRESTException.VALUE, description = "Unknown error"),
        @ApiError(code = NotAuthorizedMessicRESTException.VALUE, description = "Forbidden access"),
        @ApiError(code = IOMessicRESTException.VALUE, description = "IO error trying to get the audio resource") })
@RequestMapping(value = "/{songSid}/dlna", method = { RequestMethod.GET, RequestMethod.HEAD })
@ResponseStatus(HttpStatus.OK)//  w w w . j av a  2  s  .  c  om
@ResponseBody
@ApiResponseObject
public ResponseEntity getSongDLNA(
        @ApiParam(name = "songSid", description = "SID of the song resource we want to download", paramType = ApiParamType.PATH, required = true) @PathVariable Long songSid,
        HttpServletRequest request, HttpServletResponse response)
        throws NotAuthorizedMessicRESTException, IOMessicRESTException, UnknownMessicRESTException {
    User user = SecurityUtil.getCurrentUser();

    try {

        HttpHeaders headers = new HttpHeaders();

        // TODO some mp3 songs fail with application/octet-stream
        // MP3 files must have the content type of audio/mpeg or application/octet-stream
        // ogg files must have the content type of application/ogg

        headers.setContentType(MediaType.parseMediaType("audio/mpeg"));

        headers.setConnection("close");
        headers.add("EXT", null);
        headers.add("Accept-Ranges", "bytes");
        headers.add("transferMode.dlna.org", "Streaming");
        headers.add("contentFeatures.dlna.org", "DLNA.ORG_PN=MP3;DLNA.ORG_OP=01;DLNA.ORG_CI=0");
        headers.add("realTimeInfo.dlna.org", "DLNA.ORG_TLAG=*");
        headers.setDate(System.currentTimeMillis());

        if (request.getHeader("Range") == null) {
            APISong.AudioSongStream ass = songAPI.getAudioSong(user, songSid);
            headers.setContentLength(ass.contentLength);

            headers.add("Content-Range", "bytes 0-" + ass.contentLength + "/" + ass.contentLength);

            InputStreamResource inputStreamResource = new InputStreamResource(ass.is);

            if (request.getMethod().equalsIgnoreCase("GET")) {
                return new ResponseEntity(inputStreamResource, headers, HttpStatus.OK);
            } else {
                return new ResponseEntity<byte[]>(new byte[0], headers, HttpStatus.OK);
            }
        } else {
            APISong.AudioSongStream ass = songAPI.getAudioSong(user, songSid);

            String range = request.getHeader("Range");
            String[] sbytes = range.split("=")[1].split("-");
            int from = Integer.valueOf(sbytes[0]);
            int to = (int) ass.contentLength;
            if (sbytes.length > 1) {
                to = Integer.valueOf(sbytes[1]);
            }

            headers.setContentLength(to - from);
            headers.add("Content-Range", "bytes " + from + "-" + to + "/" + ass.contentLength);

            if (request.getMethod().equalsIgnoreCase("GET")) {
                UtilSubInputStream usi = new UtilSubInputStream(ass.is, from, to);
                InputStreamResource inputStreamResource = new InputStreamResource(usi);
                return new ResponseEntity(inputStreamResource, headers, HttpStatus.OK);
            } else {
                return new ResponseEntity<byte[]>(new byte[0], headers, HttpStatus.OK);
            }
        }
    } catch (IOException ioe) {
        log.error("failed!", ioe);
        throw new IOMessicRESTException(ioe);
    } catch (Exception e) {
        throw new UnknownMessicRESTException(e);
    }
}

From source file:org.dspace.EDMExport.controller.homeController.java

/**
 * Mtodo para generar un objeto HttpEntity con un array de bytes a partir del contenido xml
 * /*from www. ja va 2  s .co  m*/
 * @param xml cadena con el contenido xml
 * @return objeto HttpEntity {@link HttpEntity}
 * @throws UnsupportedEncodingException
 */
private HttpEntity<byte[]> getHttpEntityFromXml(String xml, String format) throws UnsupportedEncodingException {
    byte[] EDMXmlBytes;
    EDMXmlBytes = xml.getBytes("UTF-8");
    HttpHeaders header = new HttpHeaders();
    header.setContentType(new MediaType("text", "xml", Charset.forName("UTF-8")));
    header.set("Content-Disposition", "attachment; filename=" + format + "Xml.xml");
    header.setContentLength(EDMXmlBytes.length);
    return new HttpEntity<byte[]>(EDMXmlBytes, header);
}

From source file:org.fon.documentmanagementsystem.controllers.DocumentController.java

@RequestMapping(path = "/download/{id}", method = RequestMethod.GET)
public ResponseEntity<byte[]> downloadFile(@PathVariable("id") long id) {
    try {/*from w  w w .j a  va 2s.com*/

        Dokument document = dokumentService.findOne(id);

        HttpHeaders header = new HttpHeaders();
        //header.setContentType(MediaType.valueOf(document.getFajlTip()));

        String nazivfajla = document.getFajl();
        int li = nazivfajla.lastIndexOf('\\');
        String subsnaziv = nazivfajla.substring(li + 1, nazivfajla.length());
        header.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + subsnaziv);
        File file = new File(nazivfajla);

        Path path = file.toPath();

        byte[] outputByte = Files.readAllBytes(path);

        String fajltype = Files.probeContentType(path);
        System.out.println(fajltype + " je tip");

        header.setContentType(MediaType.valueOf(fajltype));

        header.setContentLength(outputByte.length);

        return new ResponseEntity<>(outputByte, header, HttpStatus.OK);
    } catch (Exception e) {
        return null;
    }
}

From source file:org.openscience.cdk.app.DepictController.java

private HttpEntity<byte[]> makeResponse(byte[] bytes, String contentType) {
    HttpHeaders header = new HttpHeaders();
    String type = contentType.substring(0, contentType.indexOf('/'));
    String subtype = contentType.substring(contentType.indexOf('/') + 1, contentType.length());
    header.setContentType(new MediaType(type, subtype));
    header.add("Access-Control-Allow-Origin", "*");
    header.set(HttpHeaders.CACHE_CONTROL, "max-age=31536000");
    header.setContentLength(bytes.length);
    return new HttpEntity<>(bytes, header);
}

From source file:com.formkiq.web.AbstractIntegrationTest.java

/**
 * Send Rest API with object./* ww  w  .  jav a 2 s  .c  om*/
 * @param method HttpMethod
 * @param url String
 * @param obj Object
 * @param clazz Class&lt;T&gt;
 * @param <T> Type of class
 * @param mediaType {@link MediaType}
 * @return ResponseEntity&lt;String&gt;
 */
protected <T> ResponseEntity<T> exchangeRest(final HttpMethod method, final String url, final Object obj,
        final Class<T> clazz, final MediaType mediaType) {

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(mediaType);
    headers.setAccept(Arrays.asList(ACCEPT_HEADER_V1_JSON));
    HttpEntity<Object> entity = new HttpEntity<>(obj, headers);
    ResponseEntity<T> out = getTemplate().exchange(url, method, entity, clazz);

    return out;
}

From source file:it.geosolutions.opensdi2.mvc.BaseFileManager.java

/**
 * Download a file with a stream/*from w w w .ja  v  a 2  s.c  om*/
 * 
 * @param contentType
 * @param contentDisposition
 * @param resp
 * @param fileName
 * @param filePath
 * @return
 */
protected ResponseEntity<byte[]> download(String contentType, String contentDisposition,
        HttpServletResponse resp, String fileName, String filePath) {

    final HttpHeaders headers = new HttpHeaders();
    File toServeUp = new File(filePath);
    InputStream inputStream = null;

    try {
        inputStream = new FileInputStream(toServeUp);
    } catch (FileNotFoundException e) {

        // Also useful, this is a good was to serve down an error message
        String msg = "ERROR: Could not find the file specified.";
        headers.setContentType(MediaType.TEXT_PLAIN);
        return new ResponseEntity<byte[]>(msg.getBytes(), headers, HttpStatus.NOT_FOUND);

    }

    // content type
    if (contentType != null) {
        resp.setContentType(contentType);
    }

    // content disposition
    if (contentDisposition != null) {
        resp.setHeader("Content-Disposition", contentDisposition);
    }

    Long fileSize = toServeUp.length();
    resp.setContentLength(fileSize.intValue());

    OutputStream outputStream = null;

    try {
        outputStream = resp.getOutputStream();
    } catch (IOException e) {
        String msg = "ERROR: Could not generate output stream.";
        headers.setContentType(MediaType.TEXT_PLAIN);
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e1) {
                // nothing
            }
        }
        return new ResponseEntity<byte[]>(msg.getBytes(), headers, HttpStatus.NOT_FOUND);
    }

    byte[] buffer = new byte[1024];

    int read = 0;
    try {

        while ((read = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, read);
        }

        // close the streams to prevent memory leaks
        outputStream.flush();
        outputStream.close();
        inputStream.close();

    } catch (Exception e) {
        String msg = "ERROR: Could not read file.";
        headers.setContentType(MediaType.TEXT_PLAIN);
        return new ResponseEntity<byte[]>(msg.getBytes(), headers, HttpStatus.NOT_FOUND);
    }

    return null;
}

From source file:it.geosolutions.opensdi2.mvc.BaseFileManager.java

/**
 * Download a file with a stream//from w w w  .jav  a2  s  .  c  o  m
 * 
 * @param contentType
 * @param contentDisposition
 * @param resp
 * @param fileName
 * @param filePath
 * @return
 */
protected ResponseEntity<byte[]> serveImageThumb(HttpServletResponse resp, String fileName, String filePath) {

    String contentType = "image/jpg";

    final HttpHeaders headers = new HttpHeaders();
    File toServeUp = new File(filePath);
    InputStream inputStream = null;
    String thumbPath = filePath + "_thumb";
    File fileThumb = new File(thumbPath);

    if (fileThumb.exists()) {
        try {
            inputStream = new FileInputStream(fileThumb);
        } catch (FileNotFoundException e) {

            // Also useful, this is a good was to serve down an error
            // message
            String msg = "ERROR: Could not find the file specified.";
            headers.setContentType(MediaType.TEXT_PLAIN);
            return new ResponseEntity<byte[]>(msg.getBytes(), headers, HttpStatus.NOT_FOUND);

        }
    } else {
        try {
            inputStream = getImageThumb(toServeUp, thumbPath);
            fileThumb = new File(thumbPath);
        } catch (Exception e) {

            // Also useful, this is a good was to serve down an error
            // message
            String msg = "ERROR: Could not find the file specified.";
            headers.setContentType(MediaType.TEXT_PLAIN);
            return new ResponseEntity<byte[]>(msg.getBytes(), headers, HttpStatus.NOT_FOUND);

        }
    }

    // content type
    resp.setContentType(contentType);

    Long fileSize = fileThumb.length();
    resp.setContentLength(fileSize.intValue());

    OutputStream outputStream = null;

    try {
        outputStream = resp.getOutputStream();
    } catch (IOException e) {
        String msg = "ERROR: Could not generate output stream.";
        headers.setContentType(MediaType.TEXT_PLAIN);
        return new ResponseEntity<byte[]>(msg.getBytes(), headers, HttpStatus.NOT_FOUND);
    }

    byte[] buffer = new byte[1024];

    int read = 0;
    try {

        while ((read = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, read);
        }

        // close the streams to prevent memory leaks
        outputStream.flush();
        outputStream.close();
        inputStream.close();

    } catch (Exception e) {
        String msg = "ERROR: Could not read file.";
        headers.setContentType(MediaType.TEXT_PLAIN);
        return new ResponseEntity<byte[]>(msg.getBytes(), headers, HttpStatus.NOT_FOUND);
    }

    return null;
}

From source file:net.paslavsky.springrest.HttpHeadersHelper.java

public HttpHeaders getHttpHeaders(Map<String, Integer> headerParameters, Object[] arguments) {
    HttpHeaders headers = new HttpHeaders();
    for (String headerName : headerParameters.keySet()) {
        Object headerValue = arguments[headerParameters.get(headerName)];
        if (headerValue != null) {
            if (ACCEPT.equalsIgnoreCase(headerName)) {
                headers.setAccept(toList(headerValue, MediaType.class));
            } else if (ACCEPT_CHARSET.equalsIgnoreCase(headerName)) {
                headers.setAcceptCharset(toList(headerValue, Charset.class));
            } else if (ALLOW.equalsIgnoreCase(headerName)) {
                headers.setAllow(toSet(headerValue, HttpMethod.class));
            } else if (CONNECTION.equalsIgnoreCase(headerName)) {
                headers.setConnection(toList(headerValue, String.class));
            } else if (CONTENT_DISPOSITION.equalsIgnoreCase(headerName)) {
                setContentDisposition(headers, headerName, headerValue);
            } else if (CONTENT_LENGTH.equalsIgnoreCase(headerName)) {
                headers.setContentLength(toLong(headerValue));
            } else if (CONTENT_TYPE.equalsIgnoreCase(headerName)) {
                headers.setContentType(toMediaType(headerValue));
            } else if (DATE.equalsIgnoreCase(headerName)) {
                headers.setDate(toLong(headerValue));
            } else if (ETAG.equalsIgnoreCase(headerName)) {
                headers.setETag(toString(headerValue));
            } else if (EXPIRES.equalsIgnoreCase(headerName)) {
                headers.setExpires(toLong(headerValue));
            } else if (IF_MODIFIED_SINCE.equalsIgnoreCase(headerName)) {
                headers.setIfModifiedSince(toLong(headerValue));
            } else if (IF_NONE_MATCH.equalsIgnoreCase(headerName)) {
                headers.setIfNoneMatch(toList(headerValue, String.class));
            } else if (LAST_MODIFIED.equalsIgnoreCase(headerName)) {
                headers.setLastModified(toLong(headerValue));
            } else if (LOCATION.equalsIgnoreCase(headerName)) {
                headers.setLocation(toURI(headerValue));
            } else if (ORIGIN.equalsIgnoreCase(headerName)) {
                headers.setOrigin(toString(headerValue));
            } else if (PRAGMA.equalsIgnoreCase(headerName)) {
                headers.setPragma(toString(headerValue));
            } else if (UPGRADE.equalsIgnoreCase(headerName)) {
                headers.setUpgrade(toString(headerValue));
            } else if (headerValue instanceof String) {
                headers.set(headerName, (String) headerValue);
            } else if (headerValue instanceof String[]) {
                headers.put(headerName, Arrays.asList((String[]) headerValue));
            } else if (instanceOf(headerValue, String.class)) {
                headers.put(headerName, toList(headerValue, String.class));
            } else {
                headers.set(headerName, conversionService.convert(headerValue, String.class));
            }/* w w w. ja  va 2  s .c  o  m*/
        }
    }
    return headers;
}