Example usage for org.springframework.http MediaType getSubtype

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

Introduction

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

Prototype

public String getSubtype() 

Source Link

Document

Return the subtype.

Usage

From source file:org.unitedinternet.cosmo.dav.property.ContentType.java

private static String mt(String type, String encoding) {
    final MediaType mediaType = MediaType.parseMediaType(type);
    if (StringUtils.hasText(encoding)) {
        return new MediaType(mediaType.getType(), mediaType.getSubtype(), Charset.forName(encoding)).toString();
    }//  ww w.j  a  v  a 2s .  c  o  m
    return mediaType.toString();
}

From source file:net.acesinc.convergentui.content.TextHttpMessageConverter.java

@Override
public boolean canRead(Class<?> type, MediaType mt) {
    return mt != null && ("text".equalsIgnoreCase(mt.getType())
            || (mt.getSubtype() != null && mt.getSubtype().contains("javascript")));
}

From source file:ar.com.zauber.commons.web.filter.webkit.WebKitContentTypeFilter.java

/**
 * @param request/*from w  w  w. j a  v a  2s. c  om*/
 *            con user Agent de webkit
 * @return si existe un text/html con q < 1.
 */
private boolean wrongMediaType(final HttpServletRequest request) {
    for (MediaType mediaType : getMediaTypes(request)) {
        if (mediaType.getType().contains(TEXT) && mediaType.getSubtype().contains(HTML)
                && mediaType.getQualityValue() < 1.0) {
            // si tiene prioridad menor a 1 y es de tipo text/html
            return true;
        }
    }
    return false;
}

From source file:org.terasoluna.gfw.functionaltest.app.download.DownloadTest.java

@Test
public void test01_02_fileDownload() {
    ResponseEntity<String> response = restTemplate.getForEntity(applicationContextUrl + "/download/1_2",
            String.class);

    HttpHeaders headers = response.getHeaders();
    System.out.println("test01_02_fileDownload: X-Track=" + headers.getFirst("X-Track"));

    assertThat(headers.getFirst("Content-Disposition"), is("attachment; filename=framework.txt"));

    MediaType contentType = headers.getContentType();
    assertThat(contentType.getType(), is("text"));
    assertThat(contentType.getSubtype(), is("plain"));
    assertThat(contentType.getParameter("charset"), equalToIgnoringCase("UTF-8"));

    assertThat(response.getBody(), is("Spring Framework"));

}

From source file:org.terasoluna.gfw.functionaltest.app.download.DownloadTest.java

@Test
public void test01_01_fileDownload() throws IOException {
    ResponseEntity<byte[]> response = restTemplate.getForEntity(applicationContextUrl + "/download/1_1",
            byte[].class);
    ClassPathResource images = new ClassPathResource("/image/Duke.png");

    byte[] expected = StreamUtils.copyToByteArray(images.getInputStream());

    HttpHeaders headers = response.getHeaders();
    System.out.println("test01_01_fileDownload: X-Track=" + headers.getFirst("X-Track"));
    assertThat(headers.getFirst("Content-Disposition"), is("attachment; filename=Duke.png"));

    MediaType contentType = headers.getContentType();
    assertThat(contentType.getType(), is("image"));
    assertThat(contentType.getSubtype(), is("png"));

    assertThat(response.getBody(), is(expected));
}

From source file:net.eusashead.hateoas.hal.http.converter.HalHttpMessageConverter.java

@Override
protected void writeInternal(Object target, HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {
    ReadableRepresentation rep = getRepresentation(target);
    MediaType contentType = outputMessage.getHeaders().getContentType();
    String mediaType = contentType.getType() + "/" + contentType.getSubtype();
    Writer writer = new OutputStreamWriter(outputMessage.getBody());
    rep.toString(mediaType, writer);/*w  w  w.j  av  a 2 s  .  c  om*/
}

From source file:be.solidx.hot.utils.AbstractHttpDataDeserializer.java

@Override
public Object processRequestData(byte[] data, String contentType) {
    MediaType ct = MediaType.parseMediaType(contentType);

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Content-type: " + contentType);

    Charset charset = ct.getCharSet() == null ? Charset.forName("UTF-8") : ct.getCharSet();

    // Subtypes arre used because of possible encoding definitions
    if (ct.getSubtype().equals(MediaType.APPLICATION_OCTET_STREAM.getSubtype())) {
        return data;
    } else if (ct.getSubtype().equals(MediaType.APPLICATION_JSON.getSubtype())) {
        try {/*  w  w  w. ja v a  2 s.  c o  m*/
            return fromJSON(data);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    } else if (ct.getSubtype().equals(MediaType.APPLICATION_XML.getSubtype())) {
        try {
            return toXML(data, ct.getCharSet() == null ? Charset.forName("UTF-8") : ct.getCharSet());
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    } else if (ct.getSubtype().equals(MediaType.APPLICATION_FORM_URLENCODED.getSubtype())) {
        String decoded;
        try {
            decoded = URLDecoder.decode(new String(data, charset), charset.toString());
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
        return fromFormUrlEncoded(decoded);
    } else {
        return new String(data, ct.getCharSet() == null ? Charset.forName("UTF-8") : ct.getCharSet());
    }
}

From source file:org.lightadmin.core.web.util.ImageResourceControllerSupport.java

private ResponseEntity<?> scaledImageResourceResponse(byte[] bytes, int width, int height, MediaType mediaType)
        throws IOException {
    BufferedImage sourceImage = read(new ByteArrayInputStream(bytes));
    BufferedImage image = resizeImage(sourceImage, width, height);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    ImageIO.write(image, mediaType.getSubtype(), byteArrayOutputStream);

    return imageResourceResponse(byteArrayOutputStream.toByteArray(), mediaType);
}

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

/**
 * generateQRCode - Main API to generate QR Code
 * //from  w w  w .  j  a  v  a2s . com
 * @throws Exception
 * 
 * 
 */
@RequestMapping(value = "generate", method = RequestMethod.GET, produces = { MediaType.IMAGE_JPEG_VALUE,
        MediaType.IMAGE_PNG_VALUE, MediaType.IMAGE_GIF_VALUE, MEDIATYPE_IMAGE_TIFF_VALUE,
        MEDIATYPE_IMAGE_BMP_VALUE })
@ApiOperation(value = "Generate QR Code.")
public ResponseEntity<byte[]> generateQRCode(
        @ApiParam(value = "data", name = "data", required = true) @RequestParam("data") String data,
        @ApiParam(value = "A user-chosen password that can be used with password-based encryption (PBE) Algo PBEWITHMD5AND128BITAES-CBC-OPENSSL)", name = "passKey", required = false) @RequestParam(required = false, value = "passKey") String passKey,
        @ApiParam(value = "ForeColor e.g #000000 (Black - RGB(hex))", name = "foreColor", required = false) @RequestParam(required = false, value = "foreColor") String foreColor,
        @ApiParam(value = "BackgroundColor e.g #FFFFFF (White - RGB(hex))", name = "bgColor", required = false) @RequestParam(required = false, value = "bgColor") String bgColor,
        @ApiParam(value = "L|M|Q|H - Reed-Solomon error correctionCode Level(from low to high) default=Low", name = "ecc", required = false) @RequestParam(required = false, value = "ecc") String ecc,
        @ApiParam(value = "Image Size e.g #150x150", name = "size", required = false) @RequestParam(required = false, value = "size") String size,
        @ApiParam(value = "jpeg|tiff|gif|png|bmp - default=png", name = "format", required = false) @RequestParam(required = false, value = "format") String format,
        @ApiParam(value = "true|false default=false", name = "download", required = false) @RequestParam(required = false, value = "download") boolean download,
        @ApiIgnore @Value("#{request.getHeader('" + ACCEPT_HEADER + "')}") String acceptHeaderValue)
        throws Exception {

    Assert.isTrue(StringUtils.isNotEmpty(data), "Please provide valid data param.");

    LOGGER.debug("Accept Header::" + acceptHeaderValue);

    HttpHeaders responseHeaders = new HttpHeaders();

    if (!(StringUtils.isBlank(passKey))) {
        builder.setCodeText(StringEncryptor.encrypt(data, passKey));
    } else {
        builder.setCodeText(data);
    }

    builder.setImageQuality(ImageQualityMode.Default);
    builder.setSymbologyType(Symbology.QR);
    builder.setCodeLocation(CodeLocation.None);

    builder.setForeColor(getColorValue(foreColor, "#000000"));

    builder.setBackColor(getColorValue(bgColor, "#FFFFFF"));

    builder.setQRErrorLevel(getErrorCorrectCode(ecc, QRErrorLevel.LevelL));

    Dimension imageDimention = geCustomImageSizeDimention(size);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageFormatDTO responseImageTypeDto = getRequestedImageFormat(responseHeaders, acceptHeaderValue, format);

    long startTime = System.currentTimeMillis();

    LOGGER.debug("builder.save Start @  " + startTime);
    byte[] imageInByte;

    if (imageDimention != null) {

        // Set graphics unit
        builder.setGraphicsUnit(GraphicsUnit.Millimeter);

        // Set margins
        builder.getMargins().set(0);

        builder.setForeColor(getColorValue(foreColor, "#000000"));

        builder.setBackColor(getColorValue(bgColor, "#FFFFFF"));

        LOGGER.debug("builder.getGraphicsUnit() ::" + builder.getGraphicsUnit());

        // Get BufferedImage with exact bar code only
        BufferedImage img = builder.getOnlyBarCodeImage();

        LOGGER.debug("img.getWidth() : :" + img.getWidth());
        LOGGER.debug("img.getHeight() :: " + img.getHeight());

        if (imageDimention.getWidth() < img.getWidth()) {
            imageDimention.width = img.getWidth();
        }

        if (imageDimention.getHeight() < img.getHeight()) {
            imageDimention.height = img.getHeight();
        }

        BufferedImage img2 = builder.getCustomSizeBarCodeImage(imageDimention, true);

        MediaType responseType = responseImageTypeDto.getMediaType();
        ImageIO.write(img2, responseType.getSubtype(), baos);
        baos.flush();
        imageInByte = baos.toByteArray();
        baos.close();

    } else {

        builder.setxDimension(1.0f);
        builder.setyDimension(1.0f);

        builder.save(baos, responseImageTypeDto.getBarCodeImageFormat());
        baos.flush();
        imageInByte = baos.toByteArray();
        baos.close();
    }

    long endTime = System.currentTimeMillis();

    LOGGER.debug("builder.save took " + (endTime - startTime) + " milliseconds");

    if (download) {

        MediaType responseType = responseImageTypeDto.getMediaType();
        responseHeaders.setContentType(responseType);
        responseHeaders.add("Content-Disposition",
                "attachment; filename=" + "Aspose_BarCode_QRCodeGen." + responseType.getSubtype());
    }

    return new ResponseEntity<byte[]>(imageInByte, responseHeaders, HttpStatus.CREATED);

}

From source file:net.acesinc.convergentui.BaseFilter.java

protected void writeResponse(BufferedImage image, MediaType type) throws Exception {
    RequestContext context = RequestContext.getCurrentContext();
    // there is no body to send
    if (image == null) {
        return;//  www  .j a v a  2 s .  c o  m
    }
    HttpServletResponse servletResponse = context.getResponse();
    //        servletResponse.setCharacterEncoding("UTF-8");
    servletResponse.setContentType(type.toString());

    ByteArrayOutputStream tmp = new ByteArrayOutputStream();
    ImageIO.write(image, type.getSubtype(), tmp);
    tmp.close();
    Integer contentLength = tmp.size();

    servletResponse.setContentLength(contentLength);

    OutputStream outStream = servletResponse.getOutputStream();
    ByteArrayOutputStream os = new ByteArrayOutputStream();

    ImageIO.write(image, type.getSubtype(), os);
    InputStream is = new ByteArrayInputStream(os.toByteArray());

    try {
        writeResponse(is, outStream);
    } finally {
        try {
            if (is != null) {
                is.close();
            }
            outStream.flush();
            outStream.close();
        } catch (IOException ex) {
        }
    }
}