001package ca.uhn.fhir.rest.api;
002
003/*
004 * #%L
005 * HAPI FHIR - Core Library
006 * %%
007 * Copyright (C) 2014 - 2020 University Health Network
008 * %%
009 * Licensed under the Apache License, Version 2.0 (the "License");
010 * you may not use this file except in compliance with the License.
011 * You may obtain a copy of the License at
012 *
013 *      http://www.apache.org/licenses/LICENSE-2.0
014 *
015 * Unless required by applicable law or agreed to in writing, software
016 * distributed under the License is distributed on an "AS IS" BASIS,
017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
018 * See the License for the specific language governing permissions and
019 * limitations under the License.
020 * #L%
021 */
022
023import ca.uhn.fhir.context.FhirContext;
024import ca.uhn.fhir.parser.IParser;
025import org.apache.commons.lang3.ObjectUtils;
026
027import java.util.Collections;
028import java.util.HashMap;
029import java.util.Map;
030
031import static org.apache.commons.lang3.StringUtils.isBlank;
032
033public enum EncodingEnum {
034
035        JSON(Constants.CT_FHIR_JSON, Constants.CT_FHIR_JSON_NEW, Constants.FORMAT_JSON) {
036                @Override
037                public IParser newParser(FhirContext theContext) {
038                        return theContext.newJsonParser();
039                }
040        },
041
042        XML(Constants.CT_FHIR_XML, Constants.CT_FHIR_XML_NEW, Constants.FORMAT_XML) {
043                @Override
044                public IParser newParser(FhirContext theContext) {
045                        return theContext.newXmlParser();
046                }
047        },
048
049        RDF(Constants.CT_RDF_TURTLE, Constants.CT_RDF_TURTLE, Constants.FORMAT_TURTLE) {
050                @Override
051                public IParser newParser(FhirContext theContext) {
052                        return theContext.newRDFParser();
053                }
054        },
055
056        ;
057
058        /**
059         * "json"
060         */
061        public static final String JSON_PLAIN_STRING = "json";
062
063        /**
064         * "xml"
065         */
066        public static final String XML_PLAIN_STRING = "xml";
067
068        private static Map<String, EncodingEnum> ourContentTypeToEncoding;
069        private static Map<String, EncodingEnum> ourContentTypeToEncodingLegacy;
070        private static Map<String, EncodingEnum> ourContentTypeToEncodingStrict;
071
072        static {
073                ourContentTypeToEncoding = new HashMap<>();
074                ourContentTypeToEncodingLegacy = new HashMap<>();
075
076                for (EncodingEnum next : values()) {
077                        ourContentTypeToEncoding.put(next.myResourceContentTypeNonLegacy, next);
078                        ourContentTypeToEncoding.put(next.myResourceContentTypeLegacy, next);
079                        ourContentTypeToEncodingLegacy.put(next.myResourceContentTypeLegacy, next);
080
081                        /*
082                         * See #346
083                         */
084                        ourContentTypeToEncoding.put(next.myResourceContentTypeNonLegacy.replace('+', ' '), next);
085                        ourContentTypeToEncoding.put(next.myResourceContentTypeLegacy.replace('+', ' '), next);
086                        ourContentTypeToEncodingLegacy.put(next.myResourceContentTypeLegacy.replace('+', ' '), next);
087
088                }
089
090                // Add before we add the lenient ones
091                ourContentTypeToEncodingStrict = Collections.unmodifiableMap(new HashMap<>(ourContentTypeToEncoding));
092
093                /*
094                 * These are wrong, but we add them just to be tolerant of other
095                 * people's mistakes
096                 */
097                ourContentTypeToEncoding.put("application/json", JSON);
098                ourContentTypeToEncoding.put("application/xml", XML);
099                ourContentTypeToEncoding.put("text/json", JSON);
100                ourContentTypeToEncoding.put("text/xml", XML);
101
102                /*
103                 * Plain values, used for parameter values
104                 */
105                ourContentTypeToEncoding.put(JSON_PLAIN_STRING, JSON);
106                ourContentTypeToEncoding.put(XML_PLAIN_STRING, XML);
107
108                ourContentTypeToEncodingLegacy = Collections.unmodifiableMap(ourContentTypeToEncodingLegacy);
109
110        }
111
112        private String myFormatContentType;
113        private String myResourceContentTypeLegacy;
114        private String myResourceContentTypeNonLegacy;
115
116        EncodingEnum(String theResourceContentTypeLegacy, String theResourceContentType, String theFormatContentType) {
117                myResourceContentTypeLegacy = theResourceContentTypeLegacy;
118                myResourceContentTypeNonLegacy = theResourceContentType;
119                myFormatContentType = theFormatContentType;
120        }
121
122        /**
123         * Returns <code>xml</code> or <code>json</code> as used on the <code>_format</code> search parameter
124         */
125        public String getFormatContentType() {
126                return myFormatContentType;
127        }
128
129        /**
130         * Will return application/xml+fhir style
131         */
132        public String getResourceContentType() {
133                return myResourceContentTypeLegacy;
134        }
135
136        /**
137         * Will return application/fhir+xml style
138         */
139        public String getResourceContentTypeNonLegacy() {
140                return myResourceContentTypeNonLegacy;
141        }
142
143        public abstract IParser newParser(final FhirContext theContext);
144
145        public static EncodingEnum detectEncoding(final String theBody) {
146                EncodingEnum retVal = detectEncodingNoDefault(theBody);
147                retVal = ObjectUtils.defaultIfNull(retVal, EncodingEnum.XML);
148                return retVal;
149        }
150
151        public static EncodingEnum detectEncodingNoDefault(String theBody) {
152                EncodingEnum retVal = null;
153                for (int i = 0; i < theBody.length() && retVal == null; i++) {
154                        switch (theBody.charAt(i)) {
155                                case '<':
156                                        retVal = EncodingEnum.XML;
157                                        break;
158                                case '{':
159                                        retVal = EncodingEnum.JSON;
160                                        break;
161                        }
162                }
163                return retVal;
164        }
165
166        /**
167         * Returns the encoding for a given content type, or <code>null</code> if no encoding
168         * is found.
169         * <p>
170         * <b>This method is lenient!</b> Things like "application/xml" will return {@link EncodingEnum#XML}
171         * even if the "+fhir" part is missing from the expected content type. Also,
172         * spaces are treated as a plus (i.e. "application/fhir json" will be treated as
173         * "application/fhir+json" in order to account for unescaped spaces in URL
174         * parameters)
175         * </p>
176         */
177        public static EncodingEnum forContentType(final String theContentType) {
178                String contentTypeSplitted = getTypeWithoutCharset(theContentType);
179                if (contentTypeSplitted == null) {
180                        return null;
181                } else {
182                        return ourContentTypeToEncoding.get(contentTypeSplitted );
183                }
184        }
185
186
187        /**
188         * Returns the encoding for a given content type, or <code>null</code> if no encoding
189         * is found.
190         * <p>
191         * <b>This method is NOT lenient!</b> Things like "application/xml" will return <code>null</code>
192         * </p>
193         *
194         * @see #forContentType(String)
195         */
196        public static EncodingEnum forContentTypeStrict(final String theContentType) {
197                String contentTypeSplitted = getTypeWithoutCharset(theContentType);
198                if (contentTypeSplitted == null) {
199                        return null;
200                } else {
201                        return ourContentTypeToEncodingStrict.get(contentTypeSplitted);
202                }
203        }
204
205        static String getTypeWithoutCharset(final String theContentType) {
206                if (isBlank(theContentType)) {
207                        return null;
208                } else {
209
210                        int start = 0;
211                        for (; start < theContentType.length(); start++) {
212                                if (theContentType.charAt(start) != ' ') {
213                                        break;
214                                }
215                        }
216                        int end = start;
217                        for (; end < theContentType.length(); end++) {
218                                if (theContentType.charAt(end) == ';') {
219                                        break;
220                                }
221                        }
222                        for (; end > start; end--) {
223                                if (theContentType.charAt(end - 1) != ' ') {
224                                        break;
225                                }
226                        }
227
228                        String retVal = theContentType.substring(start, end);
229
230                        if (retVal.contains(" ")) {
231                                retVal = retVal.replace(' ', '+');
232                        }
233                        return retVal;
234                }
235        }
236
237        /**
238         * Is the given type a FHIR legacy (pre-DSTU3) content type?
239         */
240        public static boolean isLegacy(final String theContentType) {
241                String contentTypeSplitted = getTypeWithoutCharset(theContentType);
242                if (contentTypeSplitted == null) {
243                        return false;
244                } else {
245                        return ourContentTypeToEncodingLegacy.containsKey(contentTypeSplitted);
246                }
247        }
248
249
250}