Example usage for org.springframework.http HttpHeaders setContentLength

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

Introduction

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

Prototype

public void setContentLength(long contentLength) 

Source Link

Document

Set the length of the body in bytes, as specified by the Content-Length header.

Usage

From source file:net.sf.jsog.spring.StringJsogHttpMessageConverterTest.java

@Test
public void testWriteNoDefaultContentTypeCharset() throws Exception {

    // Setup/*from   ww  w.  j a v a2  s .  c o  m*/
    instance.setOutputContentType(MediaType.APPLICATION_JSON);

    String expected = "\"foobar\"";
    String encoding = "ISO-8859-1";

    HttpOutputMessage output = createMock(HttpOutputMessage.class);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    expect(output.getBody()).andReturn(baos);

    HttpHeaders headers = createMock(HttpHeaders.class);
    expect(output.getHeaders()).andReturn(headers).anyTimes();

    headers.setContentType(JSON_CONTENT_TYPE);
    expectLastCall();
    headers.setContentLength(expected.getBytes(encoding).length);
    expectLastCall();

    // Execution
    replay(headers, output);
    instance.write(JSOG.parse(expected), JSON_CONTENT_TYPE, output);

    // Verification
    verify(headers, output);
    assertEquals(expected, baos.toString(encoding));
}

From source file:com.highcharts.export.controller.ExportController.java

@RequestMapping(value = "/json/{name}.{ext}", method = RequestMethod.POST)
public HttpEntity<byte[]> exportFromJson(@PathVariable("name") String name,
        @PathVariable("ext") String extension, @RequestBody String requestBody)
        throws SVGConverterException, TimeoutException, NoSuchElementException, PoolException {

    String randomFilename;//  w ww  . j  a v a 2 s.  c om
    randomFilename = null;
    String json = requestBody;
    MimeType mime = getMime(extension);

    // add outfile parameter to the json with a simple string replace
    if (MimeType.PDF.equals(mime)) {
        randomFilename = createRandomFileName(mime.name().toLowerCase());
        int ind = json.lastIndexOf("}");
        json = new StringBuilder(json).replace(ind, ind + 1, ",\"outfile\":\"" + randomFilename).toString()
                + "\"}";
    }

    String result = converter.requestServer(json);
    ByteArrayOutputStream stream;
    if (randomFilename != null && randomFilename.equals(result)) {
        stream = writeFileToStream(randomFilename);
    } else {
        boolean base64 = !mime.getExtension().equals("svg");
        stream = outputToStream(result, base64);
    }

    HttpHeaders headers = new HttpHeaders();

    headers.add("Content-Type", mime.getType() + "; charset=utf-8");
    headers.add("Content-Disposition", "attachment; filename=" + name + "." + extension);
    headers.setContentLength(stream.size());

    return new HttpEntity<byte[]>(stream.toByteArray(), headers);
}

From source file:access.controller.AccessController.java

/**
 * @param type//from  w w  w  .  ja va  2s. c o  m
 *            MediaType to set http header content type
 * @param fileName
 *            file name to set for content disposition
 * @param bytes
 *            file bytes
 * @return ResponseEntity
 */
private ResponseEntity<byte[]> getResponse(MediaType type, String fileName, byte[] bytes) {
    HttpHeaders header = new HttpHeaders();
    header.setContentType(type);
    header.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
    header.setContentLength(bytes.length);
    return new ResponseEntity<>(bytes, header, HttpStatus.OK);
}

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  www.  j  a  v a  2s . c o m*/

        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.dspace.EDMExport.controller.homeController.java

/**
 * Mtodo para generar un objeto HttpEntity con un array de bytes a partir del contenido xml
 * //w w  w.j av  a 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.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: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));
            }//from   w w  w . j a  v  a2  s. c om
        }
    }
    return headers;
}

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)//from   w w  w.j av  a  2 s.c o m
@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:com.highcharts.export.controller.ExportController.java

@RequestMapping(method = { RequestMethod.POST, RequestMethod.GET })
public HttpEntity<byte[]> exporter(@RequestParam(value = "svg", required = false) String svg,
        @RequestParam(value = "type", required = false) String type,
        @RequestParam(value = "filename", required = false) String filename,
        @RequestParam(value = "width", required = false) String width,
        @RequestParam(value = "scale", required = false) String scale,
        @RequestParam(value = "options", required = false) String options,
        @RequestParam(value = "globaloptions", required = false) String globalOptions,
        @RequestParam(value = "constr", required = false) String constructor,
        @RequestParam(value = "callback", required = false) String callback,
        @RequestParam(value = "callbackHC", required = false) String callbackHC,
        @RequestParam(value = "async", required = false, defaultValue = "false") Boolean async,
        @RequestParam(value = "jsonp", required = false, defaultValue = "false") Boolean jsonp,
        HttpServletRequest request, HttpSession session)
        throws ServletException, InterruptedException, SVGConverterException, NoSuchElementException,
        PoolException, TimeoutException, IOException, ZeroRequestParameterException {

    MimeType mime = getMime(type);
    String randomFilename = null;
    String jsonpCallback = "";
    boolean isAndroid = request.getHeader("user-agent") != null
            && request.getHeader("user-agent").contains("Android");

    if ("GET".equalsIgnoreCase(request.getMethod())) {

        // Handle redirect downloads for Android devices, these come in without request parameters
        String tempFile = (String) session.getAttribute("tempFile");
        session.removeAttribute("tempFile");

        if (tempFile != null && !tempFile.isEmpty()) {
            logger.debug("filename stored in session, read and stream from filesystem");
            String basename = FilenameUtils.getBaseName(tempFile);
            String extension = FilenameUtils.getExtension(tempFile);

            return getFile(basename, extension);

        }//from  w  w  w  .  ja v  a  2  s  .  c  o m
    }

    // check for visitors who don't know this domain is really only for the exporting service ;)
    if (request.getParameterMap().isEmpty()) {
        throw new ZeroRequestParameterException();
    }

    /* Most JSONP implementations use the 'callback' request parameter and this overwrites
     * the original callback parameter for chart creation with Highcharts. If JSONP is
     * used we recommend using the requestparameter callbackHC as the callback for Highcharts.
     * store the callback method name and reset the callback parameter,
     * otherwise it will be used when creation charts
     */
    if (jsonp) {
        async = true;
        jsonpCallback = callback;
        callback = null;

        if (callbackHC != null) {
            callback = callbackHC;
        }
    }

    if (isAndroid || MimeType.PDF.equals(mime) || async) {
        randomFilename = createRandomFileName(mime.name().toLowerCase());
    }

    /* If randomFilename is not null, then we want to save the filename in session, in case of GET is used later on*/
    if (isAndroid) {
        logger.debug("storing randomfile in session: " + FilenameUtils.getName(randomFilename));
        session.setAttribute("tempFile", FilenameUtils.getName(randomFilename));
    }

    String output = convert(svg, mime, width, scale, options, constructor, callback, globalOptions,
            randomFilename);
    ByteArrayOutputStream stream;

    HttpHeaders headers = new HttpHeaders();

    if (async) {
        String link = TempDir.getDownloadLink(randomFilename);
        stream = new ByteArrayOutputStream();
        if (jsonp) {
            StringBuilder sb = new StringBuilder(jsonpCallback);
            sb.append("('");
            sb.append(link);
            sb.append("')");
            stream.write(sb.toString().getBytes("utf-8"));
            headers.add("Content-Type", "text/javascript; charset=utf-8");
        } else {
            stream.write(link.getBytes("utf-8"));
            headers.add("Content-Type", "text/html; charset=UTF-8");
        }
    } else {
        headers.add("Content-Type", mime.getType() + "; charset=utf-8");
        if (randomFilename != null && randomFilename.equals(output)) {
            stream = writeFileToStream(randomFilename);
        } else {
            boolean base64 = !mime.getExtension().equals("svg");
            stream = outputToStream(output, base64);
        }
        filename = getFilename(filename);
        headers.add("Content-Disposition",
                "attachment; filename=" + filename.replace(" ", "_") + "." + mime.name().toLowerCase());
    }

    headers.setContentLength(stream.size());

    return new HttpEntity<byte[]>(stream.toByteArray(), headers);
}