Java Code Examples for org.springframework.http.MediaType#parseMediaTypes()

The following examples show how to use org.springframework.http.MediaType#parseMediaTypes() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConsumesRequestCondition.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private static Set<ConsumeMediaTypeExpression> parseExpressions(String[] consumes, @Nullable String[] headers) {
	Set<ConsumeMediaTypeExpression> result = new LinkedHashSet<>();
	if (headers != null) {
		for (String header : headers) {
			HeaderExpression expr = new HeaderExpression(header);
			if ("Content-Type".equalsIgnoreCase(expr.name) && expr.value != null) {
				for (MediaType mediaType : MediaType.parseMediaTypes(expr.value)) {
					result.add(new ConsumeMediaTypeExpression(mediaType, expr.isNegated));
				}
			}
		}
	}
	for (String consume : consumes) {
		result.add(new ConsumeMediaTypeExpression(consume));
	}
	return result;
}
 
Example 2
Source File: ProducesRequestCondition.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private Set<ProduceMediaTypeExpression> parseExpressions(String[] produces, @Nullable String[] headers) {
	Set<ProduceMediaTypeExpression> result = new LinkedHashSet<>();
	if (headers != null) {
		for (String header : headers) {
			HeaderExpression expr = new HeaderExpression(header);
			if ("Accept".equalsIgnoreCase(expr.name) && expr.value != null) {
				for (MediaType mediaType : MediaType.parseMediaTypes(expr.value)) {
					result.add(new ProduceMediaTypeExpression(mediaType, expr.isNegated));
				}
			}
		}
	}
	for (String produce : produces) {
		result.add(new ProduceMediaTypeExpression(produce));
	}
	return result;
}
 
Example 3
Source File: ConsumesRequestCondition.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private static Set<ConsumeMediaTypeExpression> parseExpressions(String[] consumes, String[] headers) {
	Set<ConsumeMediaTypeExpression> result = new LinkedHashSet<ConsumeMediaTypeExpression>();
	if (headers != null) {
		for (String header : headers) {
			HeaderExpression expr = new HeaderExpression(header);
			if ("Content-Type".equalsIgnoreCase(expr.name)) {
				for (MediaType mediaType : MediaType.parseMediaTypes(expr.value)) {
					result.add(new ConsumeMediaTypeExpression(mediaType, expr.isNegated));
				}
			}
		}
	}
	if (consumes != null) {
		for (String consume : consumes) {
			result.add(new ConsumeMediaTypeExpression(consume));
		}
	}
	return result;
}
 
Example 4
Source File: ProducesRequestCondition.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private Set<ProduceMediaTypeExpression> parseExpressions(String[] produces, String[] headers) {
	Set<ProduceMediaTypeExpression> result = new LinkedHashSet<ProduceMediaTypeExpression>();
	if (headers != null) {
		for (String header : headers) {
			HeaderExpression expr = new HeaderExpression(header);
			if ("Accept".equalsIgnoreCase(expr.name)) {
				for (MediaType mediaType : MediaType.parseMediaTypes(expr.value)) {
					result.add(new ProduceMediaTypeExpression(mediaType, expr.isNegated));
				}
			}
		}
	}
	if (produces != null) {
		for (String produce : produces) {
			result.add(new ProduceMediaTypeExpression(produce));
		}
	}
	return result;
}
 
Example 5
Source File: HeaderContentNegotiationStrategy.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 * @throws HttpMediaTypeNotAcceptableException if the 'Accept' header cannot be parsed
 */
@Override
public List<MediaType> resolveMediaTypes(NativeWebRequest request)
		throws HttpMediaTypeNotAcceptableException {

	String[] headerValueArray = request.getHeaderValues(HttpHeaders.ACCEPT);
	if (headerValueArray == null) {
		return MEDIA_TYPE_ALL_LIST;
	}

	List<String> headerValues = Arrays.asList(headerValueArray);
	try {
		List<MediaType> mediaTypes = MediaType.parseMediaTypes(headerValues);
		MediaType.sortBySpecificityAndQuality(mediaTypes);
		return !CollectionUtils.isEmpty(mediaTypes) ? mediaTypes : MEDIA_TYPE_ALL_LIST;
	}
	catch (InvalidMediaTypeException ex) {
		throw new HttpMediaTypeNotAcceptableException(
				"Could not parse 'Accept' header " + headerValues + ": " + ex.getMessage());
	}
}
 
Example 6
Source File: WelcomePageHandlerMapping.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
@Override
public Object getHandlerInternal(HttpServletRequest request) throws Exception {
    String req = request.getRequestURI();
    //this prevent recursion and unnecessary mapping
    if(target.equals(req)) {
        return null;
    }
    List<MediaType> mediaTypes = MediaType
      .parseMediaTypes(request.getHeader(HttpHeaders.ACCEPT));
    for (MediaType mediaType : mediaTypes) {
        if (mediaType.includes(MediaType.TEXT_HTML)) {
            return super.getHandlerInternal(request);
        }
    }
    return null;
}
 
Example 7
Source File: HeaderContentNegotiationStrategy.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 * @throws HttpMediaTypeNotAcceptableException if the 'Accept' header
 * cannot be parsed.
 */
@Override
public List<MediaType> resolveMediaTypes(NativeWebRequest request)
		throws HttpMediaTypeNotAcceptableException {

	String header = request.getHeader(HttpHeaders.ACCEPT);
	if (!StringUtils.hasText(header)) {
		return Collections.emptyList();
	}
	try {
		List<MediaType> mediaTypes = MediaType.parseMediaTypes(header);
		MediaType.sortBySpecificityAndQuality(mediaTypes);
		return mediaTypes;
	}
	catch (InvalidMediaTypeException ex) {
		throw new HttpMediaTypeNotAcceptableException(
				"Could not parse 'Accept' header [" + header + "]: " + ex.getMessage());
	}
}
 
Example 8
Source File: ConsumesRequestCondition.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static Set<ConsumeMediaTypeExpression> parseExpressions(String[] consumes, String[] headers) {
	Set<ConsumeMediaTypeExpression> result = new LinkedHashSet<ConsumeMediaTypeExpression>();
	if (headers != null) {
		for (String header : headers) {
			HeaderExpression expr = new HeaderExpression(header);
			if ("Content-Type".equalsIgnoreCase(expr.name)) {
				for (MediaType mediaType : MediaType.parseMediaTypes(expr.value)) {
					result.add(new ConsumeMediaTypeExpression(mediaType, expr.isNegated));
				}
			}
		}
	}
	if (consumes != null) {
		for (String consume : consumes) {
			result.add(new ConsumeMediaTypeExpression(consume));
		}
	}
	return result;
}
 
Example 9
Source File: AnotherFakeApiController.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * PATCH /another-fake/dummy : To test special tags
 * To test special tags and operation ID starting with number
 *
 * @param body client model (required)
 * @return successful operation (status code 200)
 * @see AnotherFakeApi#call123testSpecialTags
 */
public ResponseEntity<Client> call123testSpecialTags(@ApiParam(value = "client model" ,required=true )  @Valid @RequestBody Client body) {
    for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) {
        if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) {
            String exampleString = "{ \"client\" : \"client\" }";
            ApiUtil.setExampleResponse(request, "application/json", exampleString);
            break;
        }
    }
    return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);

}
 
Example 10
Source File: FakeApiController.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * POST /fake/outer/composite
 * Test serialization of object with outer number type
 *
 * @param body Input composite as post body (optional)
 * @return Output composite (status code 200)
 * @see FakeApi#fakeOuterCompositeSerialize
 */
public ResponseEntity<OuterComposite> fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body"  )  @Valid @RequestBody(required = false) OuterComposite body) {
    for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) {
        if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) {
            String exampleString = "{ \"my_string\" : \"my_string\", \"my_number\" : 0.8008281904610115, \"my_boolean\" : true }";
            ApiUtil.setExampleResponse(request, "*/*", exampleString);
            break;
        }
    }
    return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);

}
 
Example 11
Source File: FakeClassnameTestApiController.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * PATCH /fake_classname_test : To test class name in snake case
 * To test class name in snake case
 *
 * @param body client model (required)
 * @return successful operation (status code 200)
 * @see FakeClassnameTestApi#testClassname
 */
public ResponseEntity<Client> testClassname(@ApiParam(value = "client model" ,required=true )  @Valid @RequestBody Client body) {
    for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) {
        if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) {
            String exampleString = "{ \"client\" : \"client\" }";
            ApiUtil.setExampleResponse(request, "application/json", exampleString);
            break;
        }
    }
    return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);

}
 
Example 12
Source File: AnnotationMethodHandlerAdapter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private List<MediaType> getAcceptHeaderValue(RequestMappingInfo info) {
	for (String header : info.headers) {
		int separator = header.indexOf('=');
		if (separator != -1) {
			String key = header.substring(0, separator);
			String value = header.substring(separator + 1);
			if ("Accept".equalsIgnoreCase(key)) {
				return MediaType.parseMediaTypes(value);
			}
		}
	}
	return Collections.emptyList();
}
 
Example 13
Source File: ApiClient.java    From tutorials with MIT License 5 votes vote down vote up
/**
 * Select the Accept header's value from the given accepts array:
 *     if JSON exists in the given array, use it;
 *     otherwise use all of them (joining into a string)
 *
 * @param accepts The accepts array to select from
 * @return List The list of MediaTypes to use for the Accept header
 */
public List<MediaType> selectHeaderAccept(String[] accepts) {
    if (accepts.length == 0) {
        return null;
    }
    for (String accept : accepts) {
        MediaType mediaType = MediaType.parseMediaType(accept);
        if (isJsonMime(mediaType)) {
            return Collections.singletonList(mediaType);
        }
    }
    return MediaType.parseMediaTypes(StringUtils.arrayToCommaDelimitedString(accepts));
}
 
Example 14
Source File: ApiClient.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Select the Accept header's value from the given accepts array:
 *     if JSON exists in the given array, use it;
 *     otherwise use all of them (joining into a string)
 *
 * @param accepts The accepts array to select from
 * @return List The list of MediaTypes to use for the Accept header
 */
public List<MediaType> selectHeaderAccept(String[] accepts) {
    if (accepts.length == 0) {
        return null;
    }
    for (String accept : accepts) {
        MediaType mediaType = MediaType.parseMediaType(accept);
        if (isJsonMime(mediaType)) {
            return Collections.singletonList(mediaType);
        }
    }
    return MediaType.parseMediaTypes(StringUtils.arrayToCommaDelimitedString(accepts));
}
 
Example 15
Source File: PetApiController.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * POST /pet/{petId}/uploadImage : uploads an image
 *
 * @param petId ID of pet to update (required)
 * @param additionalMetadata Additional data to pass to server (optional)
 * @param file file to upload (optional)
 * @return successful operation (status code 200)
 * @see PetApi#uploadFile
 */
public ResponseEntity<ModelApiResponse> uploadFile(@ApiParam(value = "ID of pet to update",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "Additional data to pass to server") @Valid @RequestPart(value = "additionalMetadata", required = false)  String additionalMetadata,@ApiParam(value = "file to upload") @Valid @RequestPart(value = "file", required = false) MultipartFile file) {
    for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) {
        if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) {
            String exampleString = "{ \"code\" : 0, \"type\" : \"type\", \"message\" : \"message\" }";
            ApiUtil.setExampleResponse(request, "application/json", exampleString);
            break;
        }
    }
    return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);

}
 
Example 16
Source File: ApiClient.java    From tutorials with MIT License 5 votes vote down vote up
/**
 * Select the Accept header's value from the given accepts array:
 *     if JSON exists in the given array, use it;
 *     otherwise use all of them (joining into a string)
 *
 * @param accepts The accepts array to select from
 * @return List The list of MediaTypes to use for the Accept header
 */
public List<MediaType> selectHeaderAccept(String[] accepts) {
    if (accepts.length == 0) {
        return null;
    }
    for (String accept : accepts) {
        MediaType mediaType = MediaType.parseMediaType(accept);
        if (isJsonMime(mediaType)) {
            return Collections.singletonList(mediaType);
        }
    }
    return MediaType.parseMediaTypes(StringUtils.arrayToCommaDelimitedString(accepts));
}
 
Example 17
Source File: MetricsResponse.java    From timely with Apache License 2.0 5 votes vote down vote up
public FullHttpResponse toHttpResponse(String acceptHeader) throws Exception {
    MediaType negotiatedType = MediaType.TEXT_HTML;
    if (null != acceptHeader) {
        List<MediaType> requestedTypes = MediaType.parseMediaTypes(acceptHeader);
        MediaType.sortBySpecificityAndQuality(requestedTypes);
        LOG.trace("Acceptable response types: {}", MediaType.toString(requestedTypes));
        for (MediaType t : requestedTypes) {
            if (t.includes(MediaType.TEXT_HTML)) {
                negotiatedType = MediaType.TEXT_HTML;
                LOG.trace("{} allows HTML", t.toString());
                break;
            }
            if (t.includes(MediaType.APPLICATION_JSON)) {
                negotiatedType = MediaType.APPLICATION_JSON;
                LOG.trace("{} allows JSON", t.toString());
                break;
            }
        }
    }
    byte[] buf = null;
    Object responseType = Constants.HTML_TYPE;
    if (negotiatedType.equals(MediaType.APPLICATION_JSON)) {
        buf = this.generateJson(JsonUtil.getObjectMapper()).getBytes(StandardCharsets.UTF_8);
        responseType = Constants.JSON_TYPE;
    } else {
        buf = this.generateHtml().toString().getBytes(StandardCharsets.UTF_8);
    }
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
            Unpooled.copiedBuffer(buf));
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, responseType);
    response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
    return response;
}
 
Example 18
Source File: FakeApiController.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * POST /fake/{petId}/uploadImageWithRequiredFile : uploads an image (required)
 *
 * @param petId ID of pet to update (required)
 * @param requiredFile file to upload (required)
 * @param additionalMetadata Additional data to pass to server (optional)
 * @return successful operation (status code 200)
 * @see FakeApi#uploadFileWithRequiredFile
 */
public ResponseEntity<ModelApiResponse> uploadFileWithRequiredFile(@ApiParam(value = "ID of pet to update",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "file to upload") @Valid @RequestPart(value = "requiredFile", required = true) MultipartFile requiredFile,@ApiParam(value = "Additional data to pass to server") @Valid @RequestPart(value = "additionalMetadata", required = false)  String additionalMetadata) {
    for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) {
        if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) {
            String exampleString = "{ \"code\" : 0, \"type\" : \"type\", \"message\" : \"message\" }";
            ApiUtil.setExampleResponse(request, "application/json", exampleString);
            break;
        }
    }
    return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);

}
 
Example 19
Source File: SupportedMediaTypeExtractor.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Override
public List<MediaType> load(Type type) throws Exception {
	if(!Class.class.isInstance(type)){
		return Collections.emptyList();
	}
	Class<?> clazz = (Class<?>) type;
	List<MediaType> mediaTypes = Collections.emptyList();
	SupportedMediaType mediaTypeAnnotation = AnnotatedElementUtils.getMergedAnnotation(clazz, SupportedMediaType.class);
	if(mediaTypeAnnotation!=null){
		String[] mediaTypeStrs = mediaTypeAnnotation.value();
		mediaTypeStrs = mediaTypeStrs==null?LangUtils.EMPTY_STRING_ARRAY:mediaTypeStrs;
		mediaTypes = MediaType.parseMediaTypes(Arrays.asList(mediaTypeStrs));
	}
	return mediaTypes;
}
 
Example 20
Source File: ServletAnnotationMappingUtils.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * Check whether the given request matches the specified header conditions.
 * @param headers the header conditions, following
 * {@link org.springframework.web.bind.annotation.RequestMapping#headers() RequestMapping.headers()}
 * @param request the current HTTP request to check
 */
public static boolean checkHeaders(String[] headers, HttpServletRequest request) {
	if (!ObjectUtils.isEmpty(headers)) {
		for (String header : headers) {
			int separator = header.indexOf('=');
			if (separator == -1) {
				if (header.startsWith("!")) {
					if (request.getHeader(header.substring(1)) != null) {
						return false;
					}
				}
				else if (request.getHeader(header) == null) {
					return false;
				}
			}
			else {
				boolean negated = (separator > 0 && header.charAt(separator - 1) == '!');
				String key = !negated ? header.substring(0, separator) : header.substring(0, separator - 1);
				String value = header.substring(separator + 1);
				if (isMediaTypeHeader(key)) {
					List<MediaType> requestMediaTypes = MediaType.parseMediaTypes(request.getHeader(key));
					List<MediaType> valueMediaTypes = MediaType.parseMediaTypes(value);
					boolean found = false;
					for (Iterator<MediaType> valIter = valueMediaTypes.iterator(); valIter.hasNext() && !found;) {
						MediaType valueMediaType = valIter.next();
						for (Iterator<MediaType> reqIter = requestMediaTypes.iterator();
								reqIter.hasNext() && !found;) {
							MediaType requestMediaType = reqIter.next();
							if (valueMediaType.includes(requestMediaType)) {
								found = true;
							}
						}

					}
					if (negated) {
						found = !found;
					}
					if (!found) {
						return false;
					}
				}
				else {
					boolean match = value.equals(request.getHeader(key));
					if (negated) {
						match = !match;
					}
					if (!match) {
						return false;
					}
				}
			}
		}
	}
	return true;
}