Search in sources :

Example 51 with MediaType

use of org.springframework.http.MediaType in project engine by craftercms.

the class StaticAssetsRequestHandler method handleRequest.

@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    checkAndPrepare(request, response, true);
    SiteContext siteContext = SiteContext.getCurrent();
    String path = getPath(request, siteContext);
    if (siteContext == null) {
        throw new IllegalStateException("No current site context found");
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Trying to get content for static asset at [context=" + siteContext + ", path='" + path + "']");
    }
    Content content = getContent(siteContext, path);
    if (content == null) {
        if (logger.isDebugEnabled()) {
            logger.debug("No static asset found at [context=" + siteContext + ", path='" + path + "'] - returning 404");
        }
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    MediaType mediaType = getMediaType(path);
    if (mediaType != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Determined media type '" + mediaType + "' for static asset at [context=" + siteContext + ", path='" + path + "']");
        }
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("No media type found for static asset at [context=" + siteContext + ", path='" + path + "'] - not sending a content-type header");
        }
    }
    if ((new ServletWebRequest(request, response)).checkNotModified(content.getLastModified())) {
        if (logger.isDebugEnabled()) {
            logger.debug("Static asset not modified - returning 304");
        }
        return;
    }
    setHeaders(response, content, mediaType);
    if (disableCaching) {
        if (logger.isDebugEnabled()) {
            logger.debug("Caching disabled on client");
        }
        HttpUtils.disableCaching(response);
    }
    if (METHOD_HEAD.equals(request.getMethod())) {
        logger.trace("HEAD request - skipping content");
        return;
    }
    writeContent(response, content);
}
Also used : SiteContext(org.craftercms.engine.service.context.SiteContext) Content(org.craftercms.core.service.Content) MediaType(org.springframework.http.MediaType) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest)

Example 52 with MediaType

use of org.springframework.http.MediaType in project webapp by elimu-ai.

the class MarkupValidationHelper method verifyNoMarkupError.

/**
 * Verifies that the HTML is well formed.
 *
 * @param markup The HTML markup to be tested.
 */
public static void verifyNoMarkupError(String markup) {
    // List<MediaType> supportedMediaTypes = new ArrayList<>();
    List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
    supportedMediaTypes.add(new MediaType("text", "html", Charset.forName("UTF-8")));
    StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
    stringHttpMessageConverter.setSupportedMediaTypes(supportedMediaTypes);
    // List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
    List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
    messageConverters.add(stringHttpMessageConverter);
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setMessageConverters(messageConverters);
    String result = restTemplate.postForObject(URL, markup, String.class);
    System.out.println("result: " + result);
    assertTrue("The document is not valid HTML5: " + markup, result.contains("The document is valid HTML5"));
}
Also used : ArrayList(java.util.ArrayList) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) StringHttpMessageConverter(org.springframework.http.converter.StringHttpMessageConverter) RestTemplate(org.springframework.web.client.RestTemplate) MediaType(org.springframework.http.MediaType) StringHttpMessageConverter(org.springframework.http.converter.StringHttpMessageConverter)

Example 53 with MediaType

use of org.springframework.http.MediaType in project pigatron-web by pigatron-industries.

the class PublicImageController method createHeaders.

private HttpHeaders createHeaders(Image image) {
    String[] mimeType = image.getMimeType().split("/");
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentType(new MediaType(mimeType[0], mimeType[1]));
    return responseHeaders;
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) MediaType(org.springframework.http.MediaType)

Example 54 with MediaType

use of org.springframework.http.MediaType in project spring-boot-api-seed-project by selfassu.

the class WebMvcConfigurer method configureMessageConverters.

// 设置 FastJson 作为 Json 对象的转换器
@Override
protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
    FastJsonConfig config = new FastJsonConfig();
    // 设置转换 json 之后的属性
    // SerializerFeature.WriteMapNullValue 保留空的字段
    config.setSerializerFeatures(SerializerFeature.WriteMapNullValue, // Number 类型为 null 直接转换成 0
    SerializerFeature.WriteNullNumberAsZero, // 字符串类型为 null 直接转换成 ""
    SerializerFeature.WriteNullStringAsEmpty, // 禁止循环引用
    SerializerFeature.DisableCircularReferenceDetect);
    // fastjson 版本过高的时候会报错
    // json java.lang.IllegalArgumentException: 'Content-Type' cannot contain wildcard type '*'
    // 需要自己指定 Content-Type , 老版本中默认指定的是 MediaType.ALL
    List<MediaType> mediaTypes = new ArrayList<>();
    mediaTypes.add(MediaType.APPLICATION_JSON);
    mediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
    mediaTypes.add(MediaType.APPLICATION_ATOM_XML);
    mediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
    mediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
    mediaTypes.add(MediaType.APPLICATION_PDF);
    mediaTypes.add(MediaType.APPLICATION_RSS_XML);
    mediaTypes.add(MediaType.APPLICATION_XHTML_XML);
    mediaTypes.add(MediaType.APPLICATION_XML);
    mediaTypes.add(MediaType.IMAGE_GIF);
    mediaTypes.add(MediaType.IMAGE_JPEG);
    mediaTypes.add(MediaType.IMAGE_PNG);
    mediaTypes.add(MediaType.TEXT_EVENT_STREAM);
    mediaTypes.add(MediaType.TEXT_HTML);
    mediaTypes.add(MediaType.TEXT_MARKDOWN);
    mediaTypes.add(MediaType.TEXT_PLAIN);
    mediaTypes.add(MediaType.TEXT_XML);
    converter.setSupportedMediaTypes(mediaTypes);
    converter.setFastJsonConfig(config);
    converter.setDefaultCharset(Charset.forName("UTF-8"));
    converters.add(converter);
}
Also used : FastJsonConfig(com.alibaba.fastjson.support.config.FastJsonConfig) ArrayList(java.util.ArrayList) FastJsonHttpMessageConverter(com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter) MediaType(org.springframework.http.MediaType)

Example 55 with MediaType

use of org.springframework.http.MediaType in project tutorials by eugenp.

the class PetApi method findPetsByStatus.

/**
 * Finds Pets by status
 * Multiple status values can be provided with comma separated strings
 * <p><b>200</b> - successful operation
 * <p><b>400</b> - Invalid status value
 * @param status Status values that need to be considered for filter
 * @return List&lt;Pet&gt;
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public List<Pet> findPetsByStatus(List<String> status) throws RestClientException {
    Object postBody = null;
    // verify the required parameter 'status' is set
    if (status == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'status' when calling findPetsByStatus");
    }
    String path = UriComponentsBuilder.fromPath("/pet/findByStatus").build().toUriString();
    final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
    final HttpHeaders headerParams = new HttpHeaders();
    final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
    queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase()), "status", status));
    final String[] accepts = { "application/xml", "application/json" };
    final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
    final String[] contentTypes = {};
    final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
    String[] authNames = new String[] { "petstore_auth" };
    ParameterizedTypeReference<List<Pet>> returnType = new ParameterizedTypeReference<List<Pet>>() {
    };
    return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) ParameterizedTypeReference(org.springframework.core.ParameterizedTypeReference) MediaType(org.springframework.http.MediaType) ArrayList(java.util.ArrayList) List(java.util.List) Pet(com.baeldung.petstore.client.model.Pet)

Aggregations

MediaType (org.springframework.http.MediaType)477 Test (org.junit.jupiter.api.Test)177 HttpHeaders (org.springframework.http.HttpHeaders)97 Test (org.junit.Test)61 ArrayList (java.util.ArrayList)58 Charset (java.nio.charset.Charset)42 MockHttpOutputMessage (org.springframework.http.MockHttpOutputMessage)34 List (java.util.List)33 MockHttpInputMessage (org.springframework.http.MockHttpInputMessage)33 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)33 HashMap (java.util.HashMap)30 ParameterizedTypeReference (org.springframework.core.ParameterizedTypeReference)30 IOException (java.io.IOException)26 Resource (org.springframework.core.io.Resource)23 ResolvableType (org.springframework.core.ResolvableType)22 HttpEntity (org.springframework.http.HttpEntity)21 ServerWebExchange (org.springframework.web.server.ServerWebExchange)20 MockServerWebExchange (org.springframework.web.testfixture.server.MockServerWebExchange)20 Nullable (org.springframework.lang.Nullable)18 HttpClientErrorException (org.springframework.web.client.HttpClientErrorException)18