Example usage for org.springframework.http MediaType valueOf

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

Introduction

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

Prototype

public static MediaType valueOf(String value) 

Source Link

Document

Parse the given String value into a MediaType object, with this method name following the 'valueOf' naming convention (as supported by org.springframework.core.convert.ConversionService .

Usage

From source file:org.flowable.content.rest.service.api.content.ContentItemDataResource.java

@ApiOperation(value = "Get the data of a content item", tags = {
        "Content item" }, notes = "The response body contains the binary content. By default, the content-type of the response is set to application/octet-stream unless the content item type contains a valid mime type.")
@ApiResponses(value = {//  w  w w .  j  av a2s .com
        @ApiResponse(code = 200, message = "Indicates the content item was found and the requested content is returned."),
        @ApiResponse(code = 404, message = "Indicates the content item was not found or the content item does not have a binary stream available. Status message provides additional information.") })
@GetMapping(value = "/content-service/content-items/{contentItemId}/data")
public ResponseEntity<byte[]> getContentItemData(
        @ApiParam(name = "contentItemId") @PathVariable("contentItemId") String contentItemId,
        HttpServletResponse response) {

    ContentItem contentItem = getContentItemFromRequest(contentItemId);
    if (!contentItem.isContentAvailable()) {
        throw new FlowableException("No data available for content item " + contentItemId);
    }

    InputStream dataStream = contentService.getContentItemData(contentItemId);
    if (dataStream == null) {
        throw new FlowableObjectNotFoundException(
                "Content item with id '" + contentItemId + "' doesn't have content associated with it.");
    }

    HttpHeaders responseHeaders = new HttpHeaders();
    MediaType mediaType = null;
    if (contentItem.getMimeType() != null) {
        try {
            mediaType = MediaType.valueOf(contentItem.getMimeType());
            responseHeaders.set("Content-Type", contentItem.getMimeType());
        } catch (Exception e) {
            // ignore if unknown media type
        }
    }

    if (mediaType == null) {
        responseHeaders.set("Content-Type", "application/octet-stream");
    }

    try {
        return new ResponseEntity<>(IOUtils.toByteArray(dataStream), responseHeaders, HttpStatus.OK);
    } catch (Exception e) {
        throw new FlowableException("Error getting content item data " + contentItemId, e);
    }
}

From source file:org.flowable.rest.content.service.api.content.ContentItemDataResource.java

@ApiOperation(value = "Get the data of a content item", tags = {
        "Content item" }, notes = "The response body contains the binary content. By default, the content-type of the response is set to application/octet-stream unless the content item type contains a valid mime type.")
@ApiResponses(value = {/*from ww  w  . j  ava 2 s .  c om*/
        @ApiResponse(code = 200, message = "Indicates the content item was found and the requested content is returned."),
        @ApiResponse(code = 404, message = "Indicates the content item was not found or the content item doesnt have a binary stream available. Status message provides additional information.") })
@RequestMapping(value = "/content-service/content-items/{contentItemId}/data", method = RequestMethod.GET)
public ResponseEntity<byte[]> getContentItemData(
        @ApiParam(name = "contentItemId") @PathVariable("contentItemId") String contentItemId,
        HttpServletResponse response) {

    ContentItem contentItem = getContentItemFromRequest(contentItemId);
    if (!contentItem.isContentAvailable()) {
        throw new FlowableException("No data available for content item " + contentItemId);
    }

    InputStream dataStream = contentService.getContentItemData(contentItemId);
    if (dataStream == null) {
        throw new FlowableObjectNotFoundException(
                "Content item with id '" + contentItemId + "' doesn't have content associated with it.");
    }

    HttpHeaders responseHeaders = new HttpHeaders();
    MediaType mediaType = null;
    if (contentItem.getMimeType() != null) {
        try {
            mediaType = MediaType.valueOf(contentItem.getMimeType());
            responseHeaders.set("Content-Type", contentItem.getMimeType());
        } catch (Exception e) {
            // ignore if unknown media type
        }
    }

    if (mediaType == null) {
        responseHeaders.set("Content-Type", "application/octet-stream");
    }

    try {
        return new ResponseEntity<byte[]>(IOUtils.toByteArray(dataStream), responseHeaders, HttpStatus.OK);
    } catch (Exception e) {
        throw new FlowableException("Error getting content item data " + contentItemId, e);
    }
}

From source file:org.flowable.rest.service.api.runtime.task.TaskAttachmentContentResource.java

@ApiOperation(value = "Get the content for an attachment", tags = {
        "Tasks" }, notes = "The response body contains the binary content. By default, the content-type of the response is set to application/octet-stream unless the attachment type contains a valid Content-type.")
@ApiResponses(value = {//  ww  w .ja  v a 2 s .  com
        @ApiResponse(code = 200, message = "Indicates the task and attachment was found and the requested content is returned."),
        @ApiResponse(code = 404, message = "Indicates the requested task was not found or the task doesnt have an attachment with the given id or the attachment doesnt have a binary stream available. Status message provides additional information.") })
@RequestMapping(value = "/runtime/tasks/{taskId}/attachments/{attachmentId}/content", method = RequestMethod.GET)
public ResponseEntity<byte[]> getAttachmentContent(
        @ApiParam(name = "taskId") @PathVariable("taskId") String taskId,
        @ApiParam(name = "attachmentId") @PathVariable("attachmentId") String attachmentId,
        HttpServletResponse response) {

    HistoricTaskInstance task = getHistoricTaskFromRequest(taskId);
    Attachment attachment = taskService.getAttachment(attachmentId);

    if (attachment == null || !task.getId().equals(attachment.getTaskId())) {
        throw new FlowableObjectNotFoundException(
                "Task '" + task.getId() + "' doesn't have an attachment with id '" + attachmentId + "'.",
                Attachment.class);
    }

    InputStream attachmentStream = taskService.getAttachmentContent(attachmentId);
    if (attachmentStream == null) {
        throw new FlowableObjectNotFoundException(
                "Attachment with id '" + attachmentId + "' doesn't have content associated with it.",
                Attachment.class);
    }

    HttpHeaders responseHeaders = new HttpHeaders();
    MediaType mediaType = null;
    if (attachment.getType() != null) {
        try {
            mediaType = MediaType.valueOf(attachment.getType());
            responseHeaders.set("Content-Type", attachment.getType());
        } catch (Exception e) {
            // ignore if unknown media type
        }
    }

    if (mediaType == null) {
        responseHeaders.set("Content-Type", "application/octet-stream");
    }

    try {
        return new ResponseEntity<byte[]>(IOUtils.toByteArray(attachmentStream), responseHeaders,
                HttpStatus.OK);
    } catch (Exception e) {
        throw new FlowableException("Error creating attachment data", e);
    }
}

From source file:org.geoserver.importer.rest.ImportTaskController.java

@PostMapping(consumes = { MediaType.MULTIPART_FORM_DATA_VALUE, MediaType.APPLICATION_FORM_URLENCODED_VALUE })
public Object taskPost(@PathVariable Long id, @RequestParam(required = false) String expand,
        HttpServletRequest request, HttpServletResponse response) {
    ImportData data = null;/*from www .  ja  v  a2  s .  c o m*/

    LOGGER.info("Handling POST of " + request.getContentType());
    //file posted from form
    MediaType mimeType = MediaType.valueOf(request.getContentType());
    if (request.getContentType().startsWith(MediaType.MULTIPART_FORM_DATA_VALUE)) {
        data = handleMultiPartFormUpload(request, context(id));
    } else if (request.getContentType().startsWith(MediaType.APPLICATION_FORM_URLENCODED_VALUE)) {
        try {
            data = handleFormPost(request);
        } catch (IOException | ServletException e) {
            throw new RestException(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR, e);
        }
    }

    if (data == null) {
        throw new RestException("Unsupported POST", HttpStatus.FORBIDDEN);
    }

    //Construct response
    return acceptData(data, context(id), response, expand);
}

From source file:org.geoserver.rest.converters.StyleWriterConverter.java

public StyleWriterConverter(String mimeType, Version version, StyleHandler handler) {
    super(MediaType.valueOf(mimeType));
    this.handler = handler;
    this.version = version;
}

From source file:org.springframework.cloud.config.server.config.ConfigServerMvcConfiguration.java

@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    configurer.mediaType("properties", MediaType.valueOf("text/plain"));
    configurer.mediaType("yml", MediaType.valueOf("text/yaml"));
    configurer.mediaType("yaml", MediaType.valueOf("text/yaml"));
}

From source file:org.springframework.cloud.function.web.flux.request.FluxHandlerMethodArgumentResolver.java

private boolean isPlainText(NativeWebRequest webRequest) {
    String value = webRequest.getHeader("Content-Type");
    if (value != null) {
        return MediaType.valueOf(value).isCompatibleWith(MediaType.TEXT_PLAIN);
    }/*from w  ww.j a v a  2 s. c  o  m*/
    return false;
}

From source file:org.springframework.cloud.netflix.feign.support.SpringEncoder.java

@Override
public void encode(Object requestBody, Type bodyType, RequestTemplate request) throws EncodeException {
    // template.body(conversionService.convert(object, String.class));
    if (requestBody != null) {
        Class<?> requestType = requestBody.getClass();
        Collection<String> contentTypes = request.headers().get("Content-Type");

        MediaType requestContentType = null;
        if (contentTypes != null && !contentTypes.isEmpty()) {
            String type = contentTypes.iterator().next();
            requestContentType = MediaType.valueOf(type);
        }//from  w  w  w  .  j  a  v  a 2 s.  c  om

        for (HttpMessageConverter<?> messageConverter : this.messageConverters.getObject().getConverters()) {
            if (messageConverter.canWrite(requestType, requestContentType)) {
                if (log.isDebugEnabled()) {
                    if (requestContentType != null) {
                        log.debug("Writing [" + requestBody + "] as \"" + requestContentType + "\" using ["
                                + messageConverter + "]");
                    } else {
                        log.debug("Writing [" + requestBody + "] using [" + messageConverter + "]");
                    }

                }

                FeignOutputMessage outputMessage = new FeignOutputMessage(request);
                try {
                    @SuppressWarnings("unchecked")
                    HttpMessageConverter<Object> copy = (HttpMessageConverter<Object>) messageConverter;
                    copy.write(requestBody, requestContentType, outputMessage);
                } catch (IOException ex) {
                    throw new EncodeException("Error converting request body", ex);
                }
                // clear headers
                request.headers(null);
                // converters can modify headers, so update the request
                // with the modified headers
                request.headers(getHeaders(outputMessage.getHeaders()));

                // do not use charset for binary data
                if (messageConverter instanceof ByteArrayHttpMessageConverter) {
                    request.body(outputMessage.getOutputStream().toByteArray(), null);
                } else {
                    request.body(outputMessage.getOutputStream().toByteArray(), Charset.forName("UTF-8"));
                }
                return;
            }
        }
        String message = "Could not write request: no suitable HttpMessageConverter "
                + "found for request type [" + requestType.getName() + "]";
        if (requestContentType != null) {
            message += " and content type [" + requestContentType + "]";
        }
        throw new EncodeException(message);
    }
}

From source file:org.springframework.cloud.netflix.metrics.atlas.AtlasMetricObserver.java

private void sendMetricsBatch(List<Metric> metrics) {
    try {//w  ww.  ja v a  2  s  .  c  om
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        JsonGenerator gen = smileFactory.createGenerator(output, JsonEncoding.UTF8);

        gen.writeStartObject();

        writeCommonTags(gen);
        if (writeMetrics(gen, metrics) == 0)
            return; // short circuit this batch if no valid/numeric metrics existed

        gen.writeEndObject();
        gen.flush();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf("application/x-jackson-smile"));
        HttpEntity<byte[]> entity = new HttpEntity<>(output.toByteArray(), headers);
        try {
            restTemplate.exchange(uri, HttpMethod.POST, entity, Map.class);
        } catch (HttpClientErrorException e) {
            logger.error("Failed to write metrics to atlas: " + e.getResponseBodyAsString(), e);
        } catch (RestClientException e) {
            logger.error("Failed to write metrics to atlas", e);
        }
    } catch (IOException e) {
        // an IOException stemming from the generator writing to a
        // ByteArrayOutputStream is impossible
        throw new RuntimeException(e);
    }
}

From source file:org.springframework.cloud.netflix.zuul.FormZuulServletProxyApplicationTests.java

@Test
public void postWithUTF8Form() {
    MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
    form.set("foo", "bar");
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED_VALUE + "; charset=UTF-8"));
    ResponseEntity<String> result = testRestTemplate.exchange("/zuul/simplefzspat/form", HttpMethod.POST,
            new HttpEntity<>(form, headers), String.class);
    assertEquals(HttpStatus.OK, result.getStatusCode());
    assertEquals("Posted! {foo=[bar]}", result.getBody());
}