List of usage examples for org.springframework.http MediaType APPLICATION_OCTET_STREAM_VALUE
String APPLICATION_OCTET_STREAM_VALUE
To view the source code for org.springframework.http MediaType APPLICATION_OCTET_STREAM_VALUE.
Click Source Link
From source file:org.messic.server.facade.controllers.rest.PlaylistController.java
@ApiMethod(path = "/services/playlists/{playlistSid}/zip", verb = ApiVerb.GET, description = "return a zip with the content (songs) of a certain playlist", produces = { MediaType.APPLICATION_OCTET_STREAM_VALUE }) @ApiErrors(apierrors = { @ApiError(code = UnknownMessicRESTException.VALUE, description = "Unknown error"), @ApiError(code = NotFoundMessicRESTException.VALUE, description = "Sid not found"), @ApiError(code = IOMessicRESTException.VALUE, description = "IO error") }) @RequestMapping(value = "/{playlistSid}/zip", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK)/*from w ww . j a v a2 s.com*/ @ResponseBody @ApiResponseObject public void getZip( @ApiParam(name = "playlistSid", description = "sid of the playlist to be zipped", paramType = ApiParamType.PATH, required = true) @PathVariable Long playlistSid, HttpServletResponse response) throws UnknownMessicRESTException, NotAuthorizedMessicRESTException, NotFoundMessicRESTException, IOMessicRESTException { User user = SecurityUtil.getCurrentUser(); try { Playlist pl = playlistAPI.getPlaylist(user, playlistSid, false); String fileName = pl.getName() + ".zip"; response.setHeader("Content-disposition", "attachment; filename=\"" + fileName + "\""); playlistAPI.getPlaylistZip(user, playlistSid, response.getOutputStream()); } catch (IOException e) { log.error("failed!", e); throw new IOMessicRESTException(e); } catch (SidNotFoundMessicException e) { throw new NotFoundMessicRESTException(e); } catch (Exception e) { throw new UnknownMessicRESTException(e); } }
From source file:org.hsweb.web.controller.file.FileController.java
/** * ,.?GET,POST//from w w w. j a va 2 s .co m * * @param name ?? * @param text * @param response {@link HttpServletResponse} * @throws IOException */ @RequestMapping(value = "/download-text/{name:.+}", method = { RequestMethod.GET, RequestMethod.POST }) @AccessLogger("text") public void downloadTxt(@PathVariable("name") String name, @RequestParam("text") String text, HttpServletResponse response) throws IOException { response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(name, "utf-8")); response.getWriter().write(text); }
From source file:org.messic.server.facade.controllers.rest.SongController.java
@ApiMethod(path = "/services/songs/{songSid}/audio", verb = ApiVerb.GET, description = "Get the audio binary from a song resource of an album", 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}/audio", method = { RequestMethod.GET, RequestMethod.HEAD }) @ResponseStatus(HttpStatus.OK)// www . j a v a 2 s . co m public void getSongWithRanges( @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 { //http://balusc.blogspot.com.es/2009/02/fileservlet-supporting-resume-and.html // Whether the request body should be written (GET) or not (HEAD). boolean content = request.getMethod().equalsIgnoreCase("GET"); APISong.AudioSongStream ass = songAPI.getAudioSong(user, songSid); // Validate and process Range and If-Range headers. String eTag = songSid + "_" + ass.contentLength + "_" + ass.lastModified; long expires = System.currentTimeMillis() + Range.DEFAULT_EXPIRE_TIME; // Validate request headers for caching --------------------------------------------------- // If-None-Match header should contain "*" or ETag. If so, then return 304. String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null && Range.matches(ifNoneMatch, eTag)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", eTag); // Required in 304. response.setDateHeader("Expires", expires); // Postpone cache with 1 week. return; } // If-Modified-Since header should be greater than LastModified. If so, then return 304. // This header is ignored if any If-None-Match header is specified. long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > ass.lastModified) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", eTag); // Required in 304. response.setDateHeader("Expires", expires); // Postpone cache with 1 week. return; } // Validate request headers for resume ---------------------------------------------------- // If-Match header should contain "*" or ETag. If not, then return 412. String ifMatch = request.getHeader("If-Match"); if (ifMatch != null && !Range.matches(ifMatch, eTag)) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // If-Unmodified-Since header should be greater than LastModified. If not, then return 412. long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since"); if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= ass.lastModified) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // Validate and process range ------------------------------------------------------------- // Prepare some variables. The full Range represents the complete file. Range full = new Range(0, ass.contentLength - 1, ass.contentLength); List<Range> ranges = new ArrayList<Range>(); String range = request.getHeader("Range"); if (range != null) { // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416. if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) { response.setHeader("Content-Range", "bytes */" + ass.contentLength); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // If-Range header should either match ETag or be greater then LastModified. If not, // then return full file. String ifRange = request.getHeader("If-Range"); if (ifRange != null && !ifRange.equals(eTag)) { try { long ifRangeTime = request.getDateHeader("If-Range"); // Throws IAE if invalid. if (ifRangeTime != -1 && ifRangeTime + 1000 < ass.lastModified) { ranges.add(full); } } catch (IllegalArgumentException ignore) { ranges.add(full); } } // If any valid If-Range header, then process each part of byte range. if (ranges.isEmpty()) { for (String part : range.substring(6).split(",")) { // Assuming a file with length of 100, the following examples returns bytes at: // 50-80 (50 to 80), 40- (40 to length=100), -20 (length-20=80 to length=100). long start = Range.sublong(part, 0, part.indexOf("-")); long end = Range.sublong(part, part.indexOf("-") + 1, part.length()); if (start == -1) { start = ass.contentLength - end; end = ass.contentLength - 1; } else if (end == -1 || end > ass.contentLength - 1) { end = ass.contentLength - 1; } // Check if Range is syntactically valid. If not, then return 416. if (start > end) { response.setHeader("Content-Range", "bytes */" + ass.contentLength); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // Add range. ranges.add(new Range(start, end, ass.contentLength)); } } } // Prepare and initialize response -------------------------------------------------------- // Get content type by file name and set default GZIP support and content disposition. String contentType = "audio/mpeg"; boolean acceptsGzip = false; String disposition = "inline"; // // If content type is unknown, then set the default value. // // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp // // To add new content types, add new mime-mapping entry in web.xml. // if ( contentType == null ) // { // contentType = "application/octet-stream"; // } // If content type is text, then determine whether GZIP content encoding is supported by // the browser and expand content type with the one and right character encoding. if (contentType.startsWith("text")) { String acceptEncoding = request.getHeader("Accept-Encoding"); acceptsGzip = acceptEncoding != null && Range.accepts(acceptEncoding, "gzip"); contentType += ";charset=UTF-8"; } // Else, expect for images, determine content disposition. If content type is supported by // the browser, then set to inline, else attachment which will pop a 'save as' dialogue. else if (!contentType.startsWith("image")) { String accept = request.getHeader("Accept"); disposition = accept != null && Range.accepts(accept, contentType) ? "inline" : "attachment"; } // Initialize response. response.reset(); response.setBufferSize(Range.DEFAULT_BUFFER_SIZE); response.setHeader("Content-Disposition", disposition + ";filename=\"" + ass.songFileName + "\""); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("ETag", eTag); response.setDateHeader("Last-Modified", ass.lastModified); response.setDateHeader("Expires", expires); // Send requested file (part(s)) to client ------------------------------------------------ // Prepare streams. OutputStream output = null; try { // Open streams. output = response.getOutputStream(); if (ranges.isEmpty() || ranges.get(0) == full) { // Return full file. Range r = full; response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); if (content) { if (acceptsGzip) { // The browser accepts GZIP, so GZIP the content. response.setHeader("Content-Encoding", "gzip"); output = new GZIPOutputStream(output, Range.DEFAULT_BUFFER_SIZE); } else { // Content length is not directly predictable in case of GZIP. // So only add it if there is no means of GZIP, else browser will hang. response.setHeader("Content-Length", String.valueOf(r.length)); } // Copy full range. Range.copy(ass.raf, output, r.start, r.length); } } else if (ranges.size() == 1) { // Return single part of file. Range r = ranges.get(0); response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); response.setHeader("Content-Length", String.valueOf(r.length)); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. if (content) { // Copy single part range. Range.copy(ass.raf, output, r.start, r.length); } } else { // Return multiple parts of file. response.setContentType("multipart/byteranges; boundary=" + Range.MULTIPART_BOUNDARY); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. if (content) { // Cast back to ServletOutputStream to get the easy println methods. ServletOutputStream sos = (ServletOutputStream) output; // Copy multi part range. for (Range r : ranges) { // Add multipart boundary and header fields for every range. sos.println(); sos.println("--" + Range.MULTIPART_BOUNDARY); sos.println("Content-Type: " + contentType); sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total); // Copy single part range of multi part range. Range.copy(ass.raf, output, r.start, r.length); } // End with multipart boundary. sos.println(); sos.println("--" + Range.MULTIPART_BOUNDARY + "--"); } } } finally { // Gently close streams. Range.close(output); Range.close(ass.is); Range.close(ass.raf); } return; } catch (IOException ioe) { log.error("failed!", ioe); throw new IOMessicRESTException(ioe); } catch (Exception e) { throw new UnknownMessicRESTException(e); } }
From source file:com.orange.clara.cloud.servicedbdumper.controllers.ManagerController.java
@RequestMapping(value = Routes.DOWNLOAD_DUMP_FILE_ROOT + "/{dumpFileId:[0-9]+}", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE) public @ResponseBody void download(@PathVariable Integer dumpFileId, HttpServletRequest request, HttpServletResponse resp, @RequestParam(value = "original", required = false) String original) throws IOException, DumpFileDeletedException { DatabaseDumpFile databaseDumpFile = getDatabaseDumpFile(dumpFileId); this.checkDbDumperServiceInstance(databaseDumpFile.getDbDumperServiceInstance()); this.checkDatabaseDumpFile(databaseDumpFile); String userRequest = ""; String passwordRequest = ""; String authorization = request.getHeader("Authorization"); if (authorization != null && authorization.startsWith("Basic")) { String base64Credentials = authorization.substring("Basic".length()).trim(); String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8")); String[] values = credentials.split(":", 2); userRequest = values[0];/*from w w w . j av a 2 s . c o m*/ passwordRequest = values[1]; } else { this.getErrorResponseEntityBasicAuth(resp); return; } if (!userRequest.equals(databaseDumpFile.getUser()) || !passwordRequest.equals(databaseDumpFile.getPassword())) { this.getErrorResponseEntityBasicAuth(resp); return; } String fileName = DumpFileHelper.getFilePath(databaseDumpFile); resp.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); resp.setContentLengthLong(this.filer.getContentLength(fileName)); InputStream inputStream = null; if (original == null || original.isEmpty()) { inputStream = filer.retrieveWithOriginalStream(fileName); } else { inputStream = filer.retrieveWithStream(fileName); File file = new File(fileName); String[] filenames = file.getName().split("\\."); if (filenames.length >= 2) { fileName = filenames[0] + "." + filenames[1]; } } inputStream = new BufferedInputStream(inputStream); File file = new File(fileName); resp.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); OutputStream outputStream = null; outputStream = resp.getOutputStream(); try { ByteStreams.copy(inputStream, outputStream); } finally { Closeables.closeQuietly(inputStream); outputStream.flush(); resp.flushBuffer(); Closeables.close(outputStream, true); } }
From source file:com.epam.ta.reportportal.ws.controller.impl.LogController.java
@Override @RequestMapping(method = RequestMethod.POST, consumes = { MediaType.MULTIPART_FORM_DATA_VALUE }) @ResponseBody// w w w .j a v a2 s . co m // @ApiOperation("Create log (batching operation)") // Specific handler should be added for springfox in case of similar POST // request mappings @ApiIgnore public ResponseEntity<BatchSaveOperatingRS> createLog(@PathVariable String projectName, @RequestPart(value = Constants.LOG_REQUEST_JSON_PART) SaveLogRQ[] createLogRQs, HttpServletRequest request, Principal principal) { String prjName = EntityUtils.normalizeProjectName(projectName); /* * Since this is multipart request we can retrieve list of uploaded * files */ Map<String, MultipartFile> uploadedFiles = getUploadedFiles(request); BatchSaveOperatingRS response = new BatchSaveOperatingRS(); EntryCreatedRS responseItem; /* Go through all provided save log request items */ for (SaveLogRQ createLogRq : createLogRQs) { try { validateSaveRQ(createLogRq); String filename = createLogRq.getFile() == null ? null : createLogRq.getFile().getName(); if (StringUtils.isEmpty(filename)) { /* * There is no filename in request. Use simple save * method */ responseItem = createLog(prjName, createLogRq, principal); } else { /* Find by request part */ MultipartFile data = findByFileName(filename, uploadedFiles); BusinessRule.expect(data, Predicates.notNull()).verify(ErrorType.BINARY_DATA_CANNOT_BE_SAVED, Suppliers.formattedSupplier("There is no request part or file with name {}", filename)); /* * If provided content type is null or this is octet * stream, try to detect real content type of binary * data */ if (!StringUtils.isEmpty(data.getContentType()) && !MediaType.APPLICATION_OCTET_STREAM_VALUE.equals(data.getContentType())) { responseItem = createLogMessageHandler.createLog(createLogRq, new BinaryData(data.getContentType(), data.getSize(), data.getInputStream()), data.getOriginalFilename(), prjName); } else { byte[] consumedData = IOUtils.toByteArray(data.getInputStream()); responseItem = createLogMessageHandler.createLog(createLogRq, new BinaryData(contentTypeResolver.detectContentType(consumedData), data.getSize(), new ByteArrayInputStream(consumedData)), data.getOriginalFilename(), prjName); } } response.addResponse(new BatchElementCreatedRS(responseItem.getId())); } catch (Exception e) { response.addResponse( new BatchElementCreatedRS(ExceptionUtils.getStackTrace(e), ExceptionUtils.getMessage(e))); } } return new ResponseEntity<>(response, HttpStatus.CREATED); }
From source file:org.messic.server.facade.controllers.rest.AlbumController.java
@ApiMethod(path = "/services/albums/{albumSid}/zip", verb = ApiVerb.GET, description = "Get the album binary, get the whole album zipped", 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 album resource") }) @RequestMapping(value = "/{albumSid}/zip", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK)/*from ww w . j a v a 2s . c o m*/ @ResponseBody @ApiResponseObject public void getAlbumZip( @ApiParam(name = "albumSid", description = "SID of the album resource we want to download", paramType = ApiParamType.PATH, required = true) @PathVariable Long albumSid, HttpServletResponse response) throws NotAuthorizedMessicRESTException, IOMessicRESTException, UnknownMessicRESTException { User user = SecurityUtil.getCurrentUser(); try { Album album = albumAPI.getAlbum(user, albumSid, true, false, false); String fileName = album.getAuthor().getName() + "-" + album.getName() + ".zip"; response.setHeader("Content-disposition", "attachment; filename=\"" + fileName + "\""); albumAPI.getAlbumZip(user, albumSid, response.getOutputStream()); } catch (IOException ioe) { log.error("failed!", ioe); throw new IOMessicRESTException(ioe); } catch (Exception e) { log.error("failed!", e); throw new UnknownMessicRESTException(e); } }
From source file:de.unimannheim.spa.process.rest.ProjectRestControllerTest.java
private String createProcessAndReturnID(String projectID, String format) throws Exception { ObjectMapper mapper = new ObjectMapper(); String processCreatedID = ""; final String processLabel = "newProcessLabelToTest"; MockMultipartFile processFile = new MockMultipartFile("processFile", "example-spa.bpmn", MediaType.APPLICATION_OCTET_STREAM_VALUE, Files.toByteArray(getFilePath("example-spa.bpmn").toFile())); String JSONFromServer = mockMvc .perform(fileUpload("/projects/" + projectID + "/processes").file(processFile) .param("processLabel", processLabel).param("format", format)) .andReturn().getResponse().getContentAsString(); try {// ww w . j av a 2 s .c o m Map<String, Object> map = mapper.readValue(JSONFromServer, new TypeReference<Map<String, Object>>() { }); processCreatedID = ((String) map.get("id")).substring(42); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return processCreatedID; }
From source file:org.syncope.core.rest.controller.ReportController.java
@PreAuthorize("hasRole('REPORT_READ')") @RequestMapping(method = RequestMethod.GET, value = "/execution/export/{executionId}") @Transactional(readOnly = true)/*ww w . ja v a 2s . com*/ public void exportExecutionResult(final HttpServletResponse response, @PathVariable("executionId") final Long executionId, @RequestParam(value = "fmt", required = false) final ReportExecExportFormat fmt) throws NotFoundException { ReportExec reportExec = reportExecDAO.find(executionId); if (reportExec == null) { throw new NotFoundException("Report execution " + executionId); } if (!ReportExecStatus.SUCCESS.name().equals(reportExec.getStatus()) || reportExec.getExecResult() == null) { SyncopeClientCompositeErrorException sccee = new SyncopeClientCompositeErrorException( HttpStatus.BAD_REQUEST); SyncopeClientException sce = new SyncopeClientException(SyncopeClientExceptionType.InvalidReportExec); sce.addElement(reportExec.getExecResult() == null ? "No report data produced" : "Report did not run successfully"); sccee.addException(sce); throw sccee; } ReportExecExportFormat format = fmt == null ? ReportExecExportFormat.XML : fmt; LOG.debug("Exporting result of {} as {}", reportExec, format); response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); response.addHeader("Content-Disposition", "attachment; filename=" + reportExec.getReport().getName() + "." + format.name().toLowerCase()); // streaming SAX handler from a compressed byte array stream ByteArrayInputStream bais = new ByteArrayInputStream(reportExec.getExecResult()); ZipInputStream zis = new ZipInputStream(bais); try { // a single ZipEntry in the ZipInputStream (see ReportJob) zis.getNextEntry(); Pipeline<SAXPipelineComponent> pipeline = new NonCachingPipeline<SAXPipelineComponent>(); pipeline.addComponent(new XMLGenerator(zis)); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("status", reportExec.getStatus()); parameters.put("message", reportExec.getMessage()); parameters.put("startDate", reportExec.getStartDate()); parameters.put("endDate", reportExec.getEndDate()); switch (format) { case HTML: XSLTTransformer xsl2html = new XSLTTransformer(getClass().getResource("/report/report2html.xsl")); xsl2html.setParameters(parameters); pipeline.addComponent(xsl2html); pipeline.addComponent(XMLSerializer.createXHTMLSerializer()); break; case PDF: XSLTTransformer xsl2pdf = new XSLTTransformer(getClass().getResource("/report/report2fo.xsl")); xsl2pdf.setParameters(parameters); pipeline.addComponent(xsl2pdf); pipeline.addComponent(new FopSerializer(MimeConstants.MIME_PDF)); break; case RTF: XSLTTransformer xsl2rtf = new XSLTTransformer(getClass().getResource("/report/report2fo.xsl")); xsl2rtf.setParameters(parameters); pipeline.addComponent(xsl2rtf); pipeline.addComponent(new FopSerializer(MimeConstants.MIME_RTF)); break; case XML: default: pipeline.addComponent(XMLSerializer.createXMLSerializer()); } pipeline.setup(response.getOutputStream()); pipeline.execute(); LOG.debug("Result of {} successfully exported as {}", reportExec, format); } catch (Throwable t) { LOG.error("While exporting content", t); } finally { try { zis.close(); bais.close(); } catch (IOException e) { LOG.error("While closing stream for execution result", e); } } }
From source file:org.messic.server.facade.controllers.rest.AlbumController.java
@ApiMethod(path = "/services/albums/{resourceSid}/resource", verb = ApiVerb.GET, description = "Get a resource of an album", produces = { MediaType.APPLICATION_OCTET_STREAM_VALUE }) @ApiErrors(apierrors = { @ApiError(code = UnknownMessicRESTException.VALUE, description = "Unknown error"), @ApiError(code = NotAuthorizedMessicRESTException.VALUE, description = "Forbidden access"), @ApiError(code = NotFoundMessicRESTException.VALUE, description = "Resource not found"), @ApiError(code = IOMessicRESTException.VALUE, description = "IO internal server error"), }) @RequestMapping(value = "/{resourceSid}/resource", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK)//from w w w . j a va 2s .c o m @ResponseBody @ApiResponseObject public ResponseEntity<byte[]> getAlbumResource( @PathVariable @ApiParam(name = "resourceSid", description = "SID of the resource to get", paramType = ApiParamType.PATH, required = true) Long resourceSid) throws UnknownMessicRESTException, NotAuthorizedMessicRESTException, NotFoundMessicRESTException, IOMessicRESTException { User user = SecurityUtil.getCurrentUser(); try { byte[] content = albumAPI.getAlbumResource(user, resourceSid); if (content == null || content.length == 0) { InputStream is = AlbumController.class.getResourceAsStream("/org/messic/img/unknowncover.jpg"); content = Util.readInputStream(is); } HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.IMAGE_JPEG); return new ResponseEntity<byte[]>(content, headers, HttpStatus.OK); } catch (SidNotFoundMessicException e) { throw new NotFoundMessicRESTException(e); } catch (ResourceNotFoundMessicException e) { throw new NotFoundMessicRESTException(e); } catch (IOException e) { throw new IOMessicRESTException(e); } }
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 .co 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); } }