Example usage for org.springframework.http MediaType parseMediaType

List of usage examples for org.springframework.http MediaType parseMediaType

Introduction

In this page you can find the example usage for org.springframework.http MediaType parseMediaType.

Prototype

public static MediaType parseMediaType(String mediaType) 

Source Link

Document

Parse the given String into a single MediaType .

Usage

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

@RequestMapping(value = "/images/data/{id:[0-9]+}", method = RequestMethod.GET)
@ResponseBody/*from  w w  w.  ja v  a2  s  .co  m*/
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:com.courtalon.gigaMvcGalerie.web.ImageController.java

@RequestMapping(value = "/images/thumbdata/{id:[0-9]+}", method = RequestMethod.GET)
@ResponseBody// w ww .ja v a2 s. 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.viewer.controller.ViewerController.java

@RequestMapping(value = "/GetPdfWithPrintDialog")
@ResponseBody/*  w w w .j  av  a2  s  .  com*/
public ResponseEntity<InputStreamResource> GetPdfWithPrintDialog(@RequestParam String path, Boolean getPdf,
        Boolean useHtmlBasedEngine, Boolean supportPageRotation, HttpServletResponse response)
        throws Exception {

    PdfFileOptions options = new PdfFileOptions();
    options.setGuid(path);
    options.setAddPrintAction(true);

    FileContainer result = _imageHandler.getPdfFile(options);

    return ResponseEntity.ok().contentType(MediaType.parseMediaType("application/pdf"))
            .body(new InputStreamResource(result.getStream()));
}

From source file:org.mitre.openid.connect.web.ClientAPI.java

/**
 * Get the logo image for a client//from w w w  . j a v  a2 s . c  om
 * @param id
 */
@RequestMapping(value = "/{id}/logo", method = RequestMethod.GET, produces = { MediaType.IMAGE_GIF_VALUE,
        MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_PNG_VALUE })
public ResponseEntity<byte[]> getClientLogo(@PathVariable("id") Long id, Model model) {

    ClientDetailsEntity client = clientService.getClientById(id);

    if (client == null) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    } else if (Strings.isNullOrEmpty(client.getLogoUri())) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    } else {
        // get the image from cache
        CachedImage image = clientLogoLoadingService.getLogo(client);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType(image.getContentType()));
        headers.setContentLength(image.getLength());

        return new ResponseEntity<>(image.getData(), headers, HttpStatus.OK);
    }
}

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)/*  ww  w  . j a v  a2  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);
    }
}

From source file:io.restassured.module.mockmvc.internal.MockMvcRequestSenderImpl.java

private void setContentTypeToApplicationFormUrlEncoded(MockHttpServletRequestBuilder request) {
    String contentType = APPLICATION_FORM_URLENCODED_VALUE;
    EncoderConfig encoderConfig = config.getEncoderConfig();
    if (encoderConfig.shouldAppendDefaultContentCharsetToContentTypeIfUndefined()) {
        contentType += "; charset=";
        if (encoderConfig.hasDefaultCharsetForContentType(contentType)) {
            contentType += encoderConfig.defaultCharsetForContentType(contentType);
        } else {/* w  w  w  .j  ava2  s. c  om*/
            contentType += encoderConfig.defaultContentCharset();

        }
    }
    MediaType mediaType = MediaType.parseMediaType(contentType);
    request.contentType(mediaType);
    List<Header> newHeaders = new ArrayList<Header>(headers.asList());
    newHeaders.add(new Header(CONTENT_TYPE, mediaType.toString()));
    headers = new Headers(newHeaders);
}

From source file:com.sastix.cms.server.services.content.impl.hazelcast.HazelcastResourceServiceImpl.java

@Override
@Transactional(readOnly = true)/*from w w w . j  ava 2 s.c  o m*/
public ResponseEntity<InputStreamResource> getResponseInputStream(String uuid)
        throws ResourceAccessError, IOException {
    // Find Resource
    final Resource resource = resourceRepository.findOneByUid(uuid);
    if (resource == null) {
        return null;
    }

    InputStream inputStream;
    int size;
    //check cache first
    QueryCacheDTO queryCacheDTO = new QueryCacheDTO(resource.getUri());
    CacheDTO cacheDTO = null;
    try {
        cacheDTO = cacheService.getCachedResource(queryCacheDTO);
    } catch (DataNotFound e) {
        LOG.warn("Resource '{}' is not cached.", resource.getUri());
    } catch (Exception e) {
        LOG.error("Exception: {}", e.getLocalizedMessage());
    }
    if (cacheDTO != null && cacheDTO.getCacheBlobBinary() != null) {
        LOG.info("Getting resource {} from cache", resource.getUri());
        inputStream = new ByteArrayInputStream(cacheDTO.getCacheBlobBinary());
        size = cacheDTO.getCacheBlobBinary().length;
    } else {
        try {
            final Path responseFile = hashedDirectoryService.getDataByURI(resource.getUri(),
                    resource.getResourceTenantId());
            inputStream = Files.newInputStream(responseFile);
            size = (int) Files.size(responseFile);

            // Adding resource to cache
            distributedCacheService.cacheIt(resource.getUri(), resource.getResourceTenantId());
        } catch (IOException ex) {
            LOG.info("Error writing file to output stream. Filename was '{}'", resource.getUri(), ex);
            throw new RuntimeException("IOError writing file to output stream");
        } catch (URISyntaxException e) {
            e.printStackTrace();
            throw new RuntimeException("IOError writing file to output stream");
        }
    }

    return ResponseEntity.ok().contentLength(size)
            .contentType(MediaType.parseMediaType(resource.getMediaType()))
            .body(new InputStreamResource(inputStream));
}

From source file:de.metas.ui.web.window.controller.WindowRestController.java

@RequestMapping(value = "/{windowId}/{documentId}/print/{filename:.*}", method = RequestMethod.GET)
public ResponseEntity<byte[]> getDocumentPrint(@PathVariable("windowId") final int adWindowId //
        , @PathVariable("documentId") final String documentId //
        , @PathVariable("filename") final String filename) {
    userSession.assertLoggedIn();//from   w ww . j  a v  a  2s . com

    final DocumentPath documentPath = DocumentPath.rootDocumentPath(DocumentType.Window, adWindowId,
            documentId);

    final Document document = documentCollection.getDocument(documentPath);
    final DocumentEntityDescriptor entityDescriptor = document.getEntityDescriptor();

    final ProcessExecutionResult processExecutionResult = ProcessInfo.builder().setCtx(userSession.getCtx())
            .setAD_Process_ID(entityDescriptor.getPrintProcessId())
            .setRecord(entityDescriptor.getTableName(), document.getDocumentIdAsInt()).setPrintPreview(true)
            .setJRDesiredOutputType(OutputType.PDF)
            //
            .buildAndPrepareExecution().onErrorThrowException().switchContextWhenRunning().executeSync()
            .getResult();

    final byte[] reportData = processExecutionResult.getReportData();
    final String reportContentType = processExecutionResult.getReportContentType();

    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType(reportContentType));
    headers.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\"");
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    final ResponseEntity<byte[]> response = new ResponseEntity<>(reportData, headers, HttpStatus.OK);
    return response;
}