Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP media type registry with singleton instance #24

Draft
wants to merge 7 commits into
base: compat_plugin_inside_rest_request
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@

package org.elasticsearch.common.xcontent;

import java.util.Collections;
import java.util.Map;
import java.util.regex.Pattern;

/**
* Abstracts a <a href="http://en.wikipedia.org/wiki/Internet_media_type">Media Type</a> and a format parameter.
* Media types are used as values on Content-Type and Accept headers
Expand Down Expand Up @@ -46,7 +50,11 @@ public interface MediaType {
/**
* returns a string representation of a media type.
*/
default String typeWithSubtype(){
default String typeWithSubtype() {
return type() + "/" + subtype();
}

default Map<String, Pattern> validatedParameters() {
return Collections.emptyMap();
}
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
Expand Down Expand Up @@ -25,27 +26,22 @@
import java.util.regex.Pattern;

public class MediaTypeParser<T extends MediaType> {
private final Map<String, T> formatToMediaType;
private final Map<String, T> typeWithSubtypeToMediaType;
private final Map<String, Map<String, Pattern>> parametersMap;

public MediaTypeParser(Map<String, T> formatToMediaType, Map<String, T> typeWithSubtypeToMediaType,
Map<String, Map<String, Pattern>> parametersMap) {
this.formatToMediaType = Map.copyOf(formatToMediaType);
this.typeWithSubtypeToMediaType = Map.copyOf(typeWithSubtypeToMediaType);
this.parametersMap = Map.copyOf(parametersMap);
}
private MediaTypeRegistry mediaTypeRegistry;

public MediaTypeParser(MediaTypeRegistry mediaTypeRegistry) {
this.mediaTypeRegistry = mediaTypeRegistry;
}
@SuppressWarnings("unchecked")
public T fromMediaType(String mediaType) {
ParsedMediaType parsedMediaType = parseMediaType(mediaType);
return parsedMediaType != null ? parsedMediaType.getMediaType() : null;
return parsedMediaType != null ? (T)parsedMediaType.getMediaType() : null;
}

@SuppressWarnings("unchecked")
public T fromFormat(String format) {
if (format == null) {
return null;
}
return formatToMediaType.get(format.toLowerCase(Locale.ROOT));
return (T)mediaTypeRegistry.formatToMediaType(format.toLowerCase(Locale.ROOT));
}

/**
Expand All @@ -65,7 +61,7 @@ public ParsedMediaType parseMediaType(String headerValue) {
String type = typeSubtype[0];
String subtype = typeSubtype[1];
String typeWithSubtype = type + "/" + subtype;
T xContentType = typeWithSubtypeToMediaType.get(typeWithSubtype);
MediaType xContentType = mediaTypeRegistry.typeWithSubtypeToMediaType(typeWithSubtype);
if (xContentType != null) {
Map<String, String> parameters = new HashMap<>();
for (int i = 1; i < split.length; i++) {
Expand All @@ -90,8 +86,8 @@ public ParsedMediaType parseMediaType(String headerValue) {
}

private boolean isValidParameter(String typeWithSubtype, String parameterName, String parameterValue) {
if (parametersMap.containsKey(typeWithSubtype)) {
Map<String, Pattern> parameters = parametersMap.get(typeWithSubtype);
if (mediaTypeRegistry.parametersFor(typeWithSubtype) != null) {
Map<String, Pattern> parameters = mediaTypeRegistry.parametersFor(typeWithSubtype);
if (parameters.containsKey(parameterName)) {
Pattern regex = parameters.get(parameterName);
return regex.matcher(parameterValue).matches();
Expand All @@ -104,19 +100,32 @@ private boolean hasSpaces(String s) {
return s.trim().equals(s) == false;
}

private static final String COMPATIBLE_WITH_PARAMETER_NAME = "compatible-with";

public Byte parseVersion(String mediaType) {
ParsedMediaType parsedMediaType = parseMediaType(mediaType);
if (parsedMediaType != null) {
String version = parsedMediaType
.getParameters()
.get(COMPATIBLE_WITH_PARAMETER_NAME);
return version != null ? Byte.parseByte(version) : null;
}
return null;
}

/**
* A media type object that contains all the information provided on a Content-Type or Accept header
*/
public class ParsedMediaType {
private final Map<String, String> parameters;
private final T mediaType;
private final MediaType mediaType;

public ParsedMediaType(T mediaType, Map<String, String> parameters) {
public ParsedMediaType(MediaType mediaType, Map<String, String> parameters) {
this.parameters = parameters;
this.mediaType = mediaType;
}

public T getMediaType() {
public MediaType getMediaType() {
return mediaType;
}

Expand All @@ -125,36 +134,4 @@ public Map<String, String> getParameters() {
}
}

public static class Builder<T extends MediaType> {
private final Map<String, T> formatToMediaType = new HashMap<>();
private final Map<String, T> typeWithSubtypeToMediaType = new HashMap<>();
private final Map<String, Map<String, Pattern>> parametersMap = new HashMap<>();

public Builder<T> withMediaTypeAndParams(String alternativeMediaType, T mediaType, Map<String, String> paramNameAndValueRegex) {
typeWithSubtypeToMediaType.put(alternativeMediaType.toLowerCase(Locale.ROOT), mediaType);
formatToMediaType.put(mediaType.format(), mediaType);

Map<String, Pattern> parametersForMediaType = new HashMap<>(paramNameAndValueRegex.size());
for (Map.Entry<String, String> params : paramNameAndValueRegex.entrySet()) {
String parameterName = params.getKey().toLowerCase(Locale.ROOT);
String parameterRegex = params.getValue();
Pattern pattern = Pattern.compile(parameterRegex, Pattern.CASE_INSENSITIVE);
parametersForMediaType.put(parameterName, pattern);
}
parametersMap.put(alternativeMediaType, parametersForMediaType);

return this;
}

public Builder<T> copyFromMediaTypeParser(MediaTypeParser<? extends T> mediaTypeParser) {
formatToMediaType.putAll(mediaTypeParser.formatToMediaType);
typeWithSubtypeToMediaType.putAll(mediaTypeParser.typeWithSubtypeToMediaType);
parametersMap.putAll(mediaTypeParser.parametersMap);
return this;
}

public MediaTypeParser<T> build() {
return new MediaTypeParser<>(formatToMediaType, typeWithSubtypeToMediaType, parametersMap);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package org.elasticsearch.common.xcontent;

import java.util.Collection;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;

public class MediaTypeRegistry {

private Map<String, MediaType> formatToMediaType = new ConcurrentHashMap<>();
private Map<String, MediaType> typeWithSubtypeToMediaType = new ConcurrentHashMap<>();
private Map<String, Map<String, Pattern>> parametersMap = new ConcurrentHashMap<>();

public <T extends MediaType> MediaTypeRegistry register(Map<String, T> formatToMediaType, Map<String, T> typeWithSubtypeToMediaType, Map<String, Map<String, Pattern>> parametersMap) {
this.formatToMediaType.putAll(formatToMediaType);
this.typeWithSubtypeToMediaType.putAll(typeWithSubtypeToMediaType);
this.parametersMap.putAll(parametersMap);
return this;
}

public <T extends MediaType> MediaTypeRegistry register(String typeWithSubtype, T mediaType, String format, Map<String, String> parametersMap) {
if (format != null) {
this.formatToMediaType.put(format, mediaType);
}
this.typeWithSubtypeToMediaType.put(typeWithSubtype,mediaType);
Map<String, Pattern> parametersForMediaType = new HashMap<>(parametersMap.size());
for (Map.Entry<String, String> params : parametersMap.entrySet()) {
String parameterName = params.getKey().toLowerCase(Locale.ROOT);
String parameterRegex = params.getValue();
Pattern pattern = Pattern.compile(parameterRegex, Pattern.CASE_INSENSITIVE);
parametersForMediaType.put(parameterName, pattern);
}
this.parametersMap.put(typeWithSubtype,parametersForMediaType);
return this;
}
public MediaType formatToMediaType(String format) {
return formatToMediaType.get(format);
}

public MediaType typeWithSubtypeToMediaType(String typeWithSubtype) {
return typeWithSubtypeToMediaType.get(typeWithSubtype);
}

public Map<String, Pattern> parametersFor(String typeWithSubtype) {
return parametersMap.get(typeWithSubtype);
}

public MediaTypeRegistry register(String alternativeMediaType, MediaType mediaType, Map<String, String> paramNameAndValueRegex) {
typeWithSubtypeToMediaType.put(alternativeMediaType.toLowerCase(Locale.ROOT), mediaType);
formatToMediaType.put(mediaType.format(), mediaType);

Map<String, Pattern> parametersForMediaType = new HashMap<>(paramNameAndValueRegex.size());
for (Map.Entry<String, String> params : paramNameAndValueRegex.entrySet()) {
String parameterName = params.getKey().toLowerCase(Locale.ROOT);
String parameterRegex = params.getValue();
Pattern pattern = Pattern.compile(parameterRegex, Pattern.CASE_INSENSITIVE);
parametersForMediaType.put(parameterName, pattern);
}
parametersMap.put(alternativeMediaType, parametersForMediaType);
return this;
}

public MediaTypeRegistry register(MediaTypeRegistry xContentTypeRegistry) {
formatToMediaType.putAll(xContentTypeRegistry.formatToMediaType);
typeWithSubtypeToMediaType.putAll(xContentTypeRegistry.typeWithSubtypeToMediaType);
parametersMap.putAll(xContentTypeRegistry.parametersMap);
return this;
}
public MediaTypeRegistry register(Collection<MediaTypeRegistry> mediaTypeRegistries ) {
for (MediaTypeRegistry mediaTypeRegistry : mediaTypeRegistries) {
register(mediaTypeRegistry);
}
return this;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -114,26 +114,32 @@ public XContent xContent() {
}
};

private static final String COMPATIBLE_WITH_PARAMETER_NAME = "compatible-with";
private static final String VERSION_PATTERN = "\\d+";
public static final MediaTypeParser<XContentType> mediaTypeParser = new MediaTypeParser.Builder<XContentType>()
.withMediaTypeAndParams("application/smile", SMILE, Collections.emptyMap())
.withMediaTypeAndParams("application/cbor", CBOR, Collections.emptyMap())
.withMediaTypeAndParams("application/json", JSON, Map.of("charset", "UTF-8"))
.withMediaTypeAndParams("application/yaml", YAML, Map.of("charset", "UTF-8"))
.withMediaTypeAndParams("application/*", JSON, Map.of("charset", "UTF-8"))
.withMediaTypeAndParams("application/x-ndjson", JSON, Map.of("charset", "UTF-8"))
.withMediaTypeAndParams("application/vnd.elasticsearch+json", JSON,
public static final String COMPATIBLE_WITH_PARAMETER_NAME = "compatible-with";
public static final String VERSION_PATTERN = "\\d+";

private static final MediaTypeRegistry mediaTypeRegistry = new MediaTypeRegistry()
.register("application/smile", SMILE, Collections.emptyMap())
.register("application/cbor", CBOR, Collections.emptyMap())
.register("application/json", JSON, Map.of("charset", "UTF-8"))
.register("application/yaml", YAML, Map.of("charset", "UTF-8"))
.register("application/*", JSON, Map.of("charset", "UTF-8"))
.register("application/x-ndjson", JSON, Map.of("charset", "UTF-8"))
.register("application/vnd.elasticsearch+json", JSON,
Map.of(COMPATIBLE_WITH_PARAMETER_NAME, VERSION_PATTERN, "charset", "UTF-8"))
.withMediaTypeAndParams("application/vnd.elasticsearch+smile", SMILE,
.register("application/vnd.elasticsearch+smile", SMILE,
Map.of(COMPATIBLE_WITH_PARAMETER_NAME, VERSION_PATTERN, "charset", "UTF-8"))
.withMediaTypeAndParams("application/vnd.elasticsearch+yaml", YAML,
.register("application/vnd.elasticsearch+yaml", YAML,
Map.of(COMPATIBLE_WITH_PARAMETER_NAME, VERSION_PATTERN, "charset", "UTF-8"))
.withMediaTypeAndParams("application/vnd.elasticsearch+cbor", CBOR,
.register("application/vnd.elasticsearch+cbor", CBOR,
Map.of(COMPATIBLE_WITH_PARAMETER_NAME, VERSION_PATTERN, "charset", "UTF-8"))
.withMediaTypeAndParams("application/vnd.elasticsearch+x-ndjson", JSON,
Map.of(COMPATIBLE_WITH_PARAMETER_NAME, VERSION_PATTERN, "charset", "UTF-8"))
.build();
.register("application/vnd.elasticsearch+x-ndjson", JSON,
Map.of(COMPATIBLE_WITH_PARAMETER_NAME, VERSION_PATTERN, "charset", "UTF-8"));

private static MediaTypeParser<XContentType> mediaTypeParser = new MediaTypeParser<>(mediaTypeRegistry);

public static MediaTypeRegistry getMediaTypeRegistry() {
return mediaTypeRegistry;
}

/**
* Accepts a format string, which is most of the time is equivalent to {@link XContentType#subtype()}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,12 @@
import static org.hamcrest.Matchers.nullValue;

public class MediaTypeParserTests extends ESTestCase {

MediaTypeParser<XContentType> mediaTypeParser = new MediaTypeParser.Builder<XContentType>()
MediaTypeRegistry mediaTypeRegistry = new MediaTypeRegistry();
MediaTypeParser<XContentType> mediaTypeParser = new MediaTypeParser.Builder()
.withMediaTypeAndParams("application/vnd.elasticsearch+json",
XContentType.JSON, Map.of("compatible-with", "\\d+",
"charset", "UTF-8"))
.build();
.build(mediaTypeRegistry);

public void testJsonWithParameters() throws Exception {
String mediaType = "application/vnd.elasticsearch+json";
Expand Down Expand Up @@ -74,4 +74,26 @@ public void testInvalidParameters() {
assertThat(mediaTypeParser.parseMediaType(mediaType + "; key=") ,
is(nullValue()));
}

public void testVersionParsing() {
byte version = (byte) Math.abs(randomByte());
assertThat(mediaTypeParser.parseVersion("application/vnd.elasticsearch+json;compatible-with=" + version),
equalTo(version));
assertThat(mediaTypeParser.parseVersion("application/json"),
nullValue());


assertThat(mediaTypeParser.parseVersion("APPLICATION/VND.ELASTICSEARCH+JSON;COMPATIBLE-WITH=" + version),
equalTo(version));
assertThat(mediaTypeParser.parseVersion("APPLICATION/JSON"),
nullValue());

assertThat(mediaTypeParser.parseVersion("application/json;compatible-with=" + version + ".0"),
is(nullValue()));
}

public void testUnrecognizedParameter() {
assertThat(mediaTypeParser.parseVersion("application/json; sth=123"),
is(nullValue())); }

}
Loading