/** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * @param expression a boolean expression * @param message a message to pass to the {@link IllegalStateException} that is possibly thrown * @throws IllegalStateException if {@code expression} is false */ static void checkState(boolean expression, String message) { checkState(expression, () -> message); }
String consumeToken(CharMatcher matcher) { int startPosition = position; String token = consumeTokenIfPresent(matcher); checkState(position != startPosition, () -> String.format("Position '%d' should not be '%d'!", position, startPosition)); return token; }
char consumeCharacter(char c) { checkState(hasMore(), "No more elements!"); checkState(previewChar() == c, () -> "Unexpected character: " + c); position++; return c; }
char previewChar() { checkState(hasMore(), "No more elements!"); return input.charAt(position); }
char consumeCharacter(CharMatcher matcher) { checkState(hasMore(), "No more elements!"); char c = previewChar(); checkState(matcher.matches(c), "Unexpected character matched: " + c); position++; return c; }
private static String normalizeToken(String token) { checkState(TOKEN_MATCHER.matchesAllOf(token), () -> String.format("Parameter '%s' doesn't match token matcher: %s", token, TOKEN_MATCHER)); return Ascii.toLowerCase(token); }
String consumeTokenIfPresent(CharMatcher matcher) { checkState(hasMore(), "No more elements!"); int startPosition = position; position = matcher.negate().indexIn(input, startPosition); return hasMore() ? input.substring(startPosition, position) : input.substring(startPosition); }
private static MediaType create( String type, String subtype, Map<String, String> parameters) { Objects.requireNonNull(type, "Parameter 'type' is null!"); Objects.requireNonNull(subtype, "Parameter 'subtype' is null!"); Objects.requireNonNull(parameters, "Parameter 'parameters' is null!"); String normalizedType = normalizeToken(type); String normalizedSubtype = normalizeToken(subtype); checkState( !WILDCARD.type.equals(normalizedType) || WILDCARD.type.equals(normalizedSubtype), "A wildcard type cannot be used with a non-wildcard subtype"); Map<String, String> builder = new HashMap<>(); for (Map.Entry<String, String> entry : parameters.entrySet()) { String attribute = normalizeToken(entry.getKey()); builder.put(attribute, normalizeParameterValue(attribute, entry.getValue())); } MediaType mediaType = MediaType.builder() .type(normalizedType) .subtype(normalizedSubtype) .parameters(builder) .build(); // Return one of the constants if the media type is a known type. //TODO or else get? return Optional.ofNullable(KNOWN_TYPES.get(mediaType)).orElse(mediaType); }