Example usage for org.springframework.http MediaType IMAGE_JPEG

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

Introduction

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

Prototype

MediaType IMAGE_JPEG

To view the source code for org.springframework.http MediaType IMAGE_JPEG.

Click Source Link

Document

Public constant media type for image/jpeg .

Usage

From source file:com.opopov.cloud.image.service.ImageStitchingServiceImpl.java

@Override
public DeferredResult<ResponseEntity<?>> getStitchedImage(@RequestBody ImageStitchingConfiguration config) {

    validator.validateConfig(config);/*w  w w  .  j  a  v a  2 s  .co m*/

    List<ListenableFuture<ResponseEntity<byte[]>>> futures = config.getUrlList().stream()
            .map(url -> remoteResource.getForEntity(url, byte[].class)).collect(Collectors.toList());

    //wrap the listenable futures into the completable futures
    //writing loop in pre-8 style, since it would be more concise compared to stream api in this case
    CompletableFuture[] imageFutures = new CompletableFuture[futures.size()];
    int taskIndex = 0;
    IndexMap indexMap = new IndexMap(config.getRowCount() * config.getColumnCount());
    for (ListenableFuture<ResponseEntity<byte[]>> f : futures) {
        imageFutures[taskIndex] = imageDataFromResponse(taskIndex, indexMap, utils.fromListenableFuture(f));
        taskIndex++;
    }

    CompletableFuture<Void> allDownloadedAndDecompressed = CompletableFuture.allOf(imageFutures);

    //Synchronous part - start - writing decompressed bytes to the large image
    final int DOWNLOAD_AND_DECOMPRESS_TIMEOUT = 30; //30 seconds for each of the individual tasks
    DeferredResult<ResponseEntity<?>> response = new DeferredResult<>();
    boolean allSuccessful = false;
    byte[] imageBytes = null;
    try {
        Void finishResult = allDownloadedAndDecompressed.get(DOWNLOAD_AND_DECOMPRESS_TIMEOUT, TimeUnit.SECONDS);

        imageBytes = combineImagesIntoStitchedImage(config, indexMap);

        HttpHeaders headers = new HttpHeaders();
        headers.setCacheControl(CacheControl.noCache().getHeaderValue());
        headers.setContentType(MediaType.IMAGE_JPEG);
        allSuccessful = true;
    } catch (InterruptedException | ExecutionException e) {
        // basically either download or decompression of the source image failed
        // just skip it then, we have no image to show
        response.setErrorResult(
                new SourceImageLoadException("Unable to load and decode one or more source images", e));
    } catch (TimeoutException e) {
        //send timeout response, via ImageLoadTimeoutException
        response.setErrorResult(new ImageLoadTimeoutException(
                String.format("Some of the images were not loaded and decoded before timeout of %d seconds",
                        DOWNLOAD_AND_DECOMPRESS_TIMEOUT),
                e

        ));
    } catch (IOException e) {
        response.setErrorResult(new ImageWriteException("Error writing image into output buffer", e));
    }

    //Synchronous part - end

    if (!allSuccessful) {
        //shoud not get here, some unknown error
        response.setErrorResult(
                new ImageLoadTimeoutException("Unknown error", new RuntimeException("Something went wrong")

                ));

        return response;
    }

    ResponseEntity<?> successResult = ResponseEntity.ok(imageBytes);
    response.setResult(successResult);

    return response;

}

From source file:com.trenako.web.controllers.admin.AdminBrandsControllerMappingTests.java

@Test
public void shouldUploadNewBrandImages() throws Exception {
    MockMultipartFile mockFile = new MockMultipartFile("file", "image.jpg", MediaType.IMAGE_JPEG.toString(),
            "file content".getBytes());

    mockMvc()/*  www .j  a va2s  .co  m*/
            .perform(fileUpload("/admin/brands/upload").file(mockFile).param("entity", "brand").param("slug",
                    ACME))
            .andExpect(status().isOk()).andExpect(flash().attributeCount(1))
            .andExpect(flash().attribute("message", equalTo(AdminBrandsController.BRAND_LOGO_UPLOADED_MSG)))
            .andExpect(redirectedUrl("/admin/brands/acme"));
}

From source file:com.trenako.web.controllers.admin.AdminRailwaysControllerMappingTests.java

@Test
public void shouldUploadNewRailwayImages() throws Exception {
    MockMultipartFile mockFile = new MockMultipartFile("file", "image.jpg", MediaType.IMAGE_JPEG.toString(),
            "file content".getBytes());

    mockMvc()// w  ww . jav  a2  s  .  co  m
            .perform(fileUpload("/admin/railways/upload").file(mockFile).param("entity", "railway")
                    .param("slug", DB))
            .andExpect(status().isOk()).andExpect(flash().attributeCount(1))
            .andExpect(flash().attribute("message", equalTo(AdminRailwaysController.RAILWAY_LOGO_UPLOADED_MSG)))
            .andExpect(redirectedUrl("/admin/railways/db"));
}

From source file:com.trenako.web.controllers.RollingStocksControllerTests.java

@Test
public void shouldCreateNewRollingStocks() {
    when(mockResult.hasErrors()).thenReturn(false);

    MultipartFile file = buildFile(MediaType.IMAGE_JPEG);
    UploadRequest req = UploadRequest.create(rollingStock(), file);
    RollingStockForm form = rsForm(file);
    form.setTags("one, two");

    ModelMap model = new ModelMap();

    String viewName = controller.create(form, mockResult, model, mockRedirect);

    assertEquals("redirect:/rollingstocks/{slug}", viewName);

    ArgumentCaptor<RollingStock> arg = ArgumentCaptor.forClass(RollingStock.class);
    verify(service, times(1)).createNew(arg.capture());

    RollingStock savedRs = arg.getValue();
    assertEquals(rollingStock(), savedRs);
    assertTrue("Brand not loaded", savedRs.getBrand().isLoaded());
    assertTrue("Scale not loaded", savedRs.getRailway().isLoaded());
    assertTrue("Scale not loaded", savedRs.getScale().isLoaded());
    assertEquals("[one, two]", savedRs.getTags().toString());

    verify(imgService, times(1)).saveImageWithThumb(eq(req), eq(100));
    verify(mockRedirect, times(1)).addAttribute(eq("slug"), eq("acme-123456"));
    verify(mockRedirect, times(1)).addFlashAttribute(eq("message"),
            eq(RollingStocksController.ROLLING_STOCK_CREATED_MSG));
}

From source file:com.aspose.showcase.qrcodegen.web.api.controller.QRCodeManagementController.java

private ImageFormatDTO getRequestedImageFormat(HttpHeaders responseHeaders, String acceptHeaderValue,
        String format) {/*from w  w  w  .  j a  v a2  s.c  om*/

    ImageFormatDTO generatedImageFormat = new ImageFormatDTO(ImageFormat.getPng(), MediaType.IMAGE_PNG,
            com.aspose.barcode.BarCodeImageFormat.Png);
    responseHeaders.setContentType(MediaType.IMAGE_PNG);

    if (StringUtils.isBlank(acceptHeaderValue) && StringUtils.isBlank(format)) {
        return new ImageFormatDTO(ImageFormat.getPng(), MediaType.IMAGE_PNG,
                com.aspose.barcode.BarCodeImageFormat.Png);
    }

    String requestedFormat = "Png";

    if (StringUtils.isNotBlank(format)) {
        requestedFormat = format.trim();

    } else if (StringUtils.isNotBlank(acceptHeaderValue)) {
        requestedFormat = StringUtils.removeStartIgnoreCase(acceptHeaderValue.trim(), "image/");
    }

    if ("Jpeg".equalsIgnoreCase(requestedFormat)) {

        generatedImageFormat = new ImageFormatDTO(ImageFormat.getJpeg(), MediaType.IMAGE_JPEG,
                com.aspose.barcode.BarCodeImageFormat.Jpeg);
        responseHeaders.setContentType(MediaType.IMAGE_JPEG);

    } else if ("Png".equalsIgnoreCase(requestedFormat)) {

        generatedImageFormat = new ImageFormatDTO(ImageFormat.getPng(), MediaType.IMAGE_PNG,
                com.aspose.barcode.BarCodeImageFormat.Png);
        responseHeaders.setContentType(MediaType.IMAGE_PNG);

    } else if ("Gif".equalsIgnoreCase(requestedFormat)) {

        generatedImageFormat = new ImageFormatDTO(ImageFormat.getGif(), MediaType.IMAGE_GIF,
                com.aspose.barcode.BarCodeImageFormat.Gif);
        responseHeaders.setContentType(MediaType.IMAGE_GIF);

    } else if ("Tiff".equalsIgnoreCase(requestedFormat)) {

        generatedImageFormat = new ImageFormatDTO(ImageFormat.getTiff(),
                new MediaType(MEDIATYPE_IMAGE, MEDIATYPE_IMAGE_TIFF),
                com.aspose.barcode.BarCodeImageFormat.Tiff);
        responseHeaders.setContentType(new MediaType("image", MEDIATYPE_IMAGE_TIFF));

    } else if ("Bmp".equalsIgnoreCase(requestedFormat)) {

        generatedImageFormat = new ImageFormatDTO(ImageFormat.getBmp(),
                new MediaType(MEDIATYPE_IMAGE, MEDIATYPE_IMAGE_BMP), com.aspose.barcode.BarCodeImageFormat.Bmp);
        responseHeaders.setContentType(new MediaType("image", MEDIATYPE_IMAGE_BMP));

    } else {

        generatedImageFormat = new ImageFormatDTO(ImageFormat.getPng(), MediaType.IMAGE_PNG,
                com.aspose.barcode.BarCodeImageFormat.Png);
        responseHeaders.setContentType(MediaType.IMAGE_PNG);
    }

    return generatedImageFormat;
}

From source file:com.founder.zykc.controller.FdbzcrjryController.java

@SuppressWarnings("static-access")
@RequestMapping(value = "/queryFdbzcrjryPhoto.jpg", method = RequestMethod.GET)
public HttpEntity<byte[]> queryFdbzcrjryPhoto(String rydh, SessionBean sessionBean) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_JPEG);
    sessionBean = getSessionBean(sessionBean);

    byte[] pictureByte = null;

    String url = "http://10.78.17.154:9999/lbs";
    String zpParameter = "operation=ForbiddenDepartureManagement_GetPhotoByID_v001&license=a756244eb0236bdc26061cb6b6bdb481&content=";
    String zpContent = "{\"data\":[{\"RYDH\":\"" + rydh + "\"}]}";
    try {//from   w w w .  j ava 2s  .com

        zpContent = zpParameter + java.net.URLEncoder.encode(zpContent, "UTF-8");
        PostMethod postMethod = new PostMethod(url);
        byte[] b = zpContent.getBytes("utf-8");
        InputStream is = new ByteArrayInputStream(b, 0, b.length);
        RequestEntity re = new InputStreamRequestEntity(is, b.length, "application/soap+xml; charset=utf-8");
        postMethod.setRequestEntity(re);
        HttpClient httpClient = new HttpClient();
        HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();
        managerParams.setConnectionTimeout(50000);
        int statusCode = httpClient.executeMethod(postMethod);
        if (statusCode == 200) {
            String soapResponseData = postMethod.getResponseBodyAsString();
            JSONObject jb = JSONObject.fromObject(soapResponseData);
            if ((Integer) jb.get("datalen") > 0) {
                JSONObject jo = jb.getJSONArray("data").getJSONObject(0);

                try {
                    pictureByte = new BASE64Decoder().decodeBuffer(jo.getString("PHOTO"));
                } catch (Exception ex) {
                }
                if (pictureByte != null) {

                } else {
                    System.out.println("??" + statusCode);
                    byte[] empty_ryzp = SystemConfig.getByteArray("empty_ryzp");
                    headers.setContentLength(empty_ryzp.length);
                    return new HttpEntity(empty_ryzp, headers);
                }

            } else {
                System.out.println("??" + statusCode);
                byte[] empty_ryzp = SystemConfig.getByteArray("empty_ryzp");
                headers.setContentLength(empty_ryzp.length);
                return new HttpEntity(empty_ryzp, headers);
            }

        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    headers.setContentLength(pictureByte.length);
    return new HttpEntity(pictureByte, headers);

}

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)/* www . ja  va2  s  . 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.AlbumController.java

@ApiMethod(path = "/services/albums/{albumSid}/cover", verb = ApiVerb.GET, description = "Get cover for a certain album", produces = {
        MediaType.IMAGE_JPEG_VALUE })//  w w w .  jav  a  2 s  . co m
@ApiErrors(apierrors = { @ApiError(code = UnknownMessicRESTException.VALUE, description = "Unknown error"),
        @ApiError(code = NotAuthorizedMessicRESTException.VALUE, description = "Forbidden access"),
        @ApiError(code = NotFoundMessicRESTException.VALUE, description = "Album or Cover not found"),
        @ApiError(code = IOMessicRESTException.VALUE, description = "IO internal server error"), })
@RequestMapping(value = "/{albumSid}/cover", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
@ApiResponseObject
public ResponseEntity<byte[]> getAlbumCover(
        @PathVariable @ApiParam(name = "albumSid", description = "SID of the album to get the cover", paramType = ApiParamType.PATH, required = true) Long albumSid,
        @RequestParam(value = "preferredWidth", required = false) @ApiParam(name = "preferredWidth", description = "desired width for the image returned.  The service will try to provide the desired width, it is just only informative, to try to optimize the performance, avoiding to return images too much big", paramType = ApiParamType.QUERY, required = false, format = "Integer") Integer preferredWidth,
        @RequestParam(value = "preferredHeight", required = false) @ApiParam(name = "preferredHeight", description = "desired height for the image returned.  The service will try to provide the desired height, it is just only informative, to try to optimize the performance, avoiding to return images too much big", paramType = ApiParamType.QUERY, required = false, format = "Integer") Integer preferredHeight)
        throws UnknownMessicRESTException, NotAuthorizedMessicRESTException, NotFoundMessicRESTException,
        IOMessicRESTException {

    User user = SecurityUtil.getCurrentUser();
    try {
        byte[] content = albumAPI.getAlbumCover(user, albumSid, preferredWidth, preferredHeight);
        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) {
        InputStream is = AlbumController.class.getResourceAsStream("/org/messic/img/unknowncover.jpg");
        byte[] content = null;
        try {
            content = Util.readInputStream(is);
        } catch (IOException e1) {
            throw new NotFoundMessicRESTException(e);
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG);
        return new ResponseEntity<byte[]>(content, headers, HttpStatus.OK);
    } catch (IOException e) {
        throw new IOMessicRESTException(e);
    }
}

From source file:com.viewer.controller.ViewerController.java

@SuppressWarnings("unused")
private MediaType GetContentType(ConvertImageFileType convertImageFileType) {
    MediaType contentType;/*w w w. ja  va2s. c o m*/
    switch (convertImageFileType) {
    case JPG:
        contentType = MediaType.IMAGE_JPEG;
        break;
    case BMP:
        contentType = MediaType.ALL;
        break;
    case PNG:
        contentType = MediaType.IMAGE_PNG;
        break;
    default:
        throw new IllegalArgumentException();
    }

    return contentType;
}

From source file:org.apigw.authserver.web.controller.ApplicationManagementController.java

@RequestMapping(value = "/app/image", method = RequestMethod.GET, params = { "id" })
public ResponseEntity<byte[]> getIcon(@RequestParam("id") Long id) {
    Application application = appManagement.getApplication(id);

    if (application == null) {
        throw new IllegalArgumentException("No application found with id " + id);
    }//from w ww  .  jav  a  2 s.  c o m
    byte[] content = application.getIcon();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_JPEG);
    return new ResponseEntity<byte[]>(content, headers, HttpStatus.OK);
}