001package ca.uhn.fhir.parser;
002
003/*
004 * #%L
005 * HAPI FHIR - Core Library
006 * %%
007 * Copyright (C) 2014 - 2017 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 */
022import java.io.*;
023import java.util.*;
024
025import org.hl7.fhir.instance.model.api.*;
026
027import ca.uhn.fhir.context.*;
028import ca.uhn.fhir.model.api.IResource;
029import ca.uhn.fhir.rest.api.EncodingEnum;
030
031/**
032 * A parser, which can be used to convert between HAPI FHIR model/structure objects, and their respective String wire
033 * formats, in either XML or JSON.
034 * <p>
035 * Thread safety: <b>Parsers are not guaranteed to be thread safe</b>. Create a new parser instance for every thread or
036 * every message being parsed/encoded.
037 * </p>
038 */
039public interface IParser {
040
041        String encodeResourceToString(IBaseResource theResource) throws DataFormatException;
042
043        void encodeResourceToWriter(IBaseResource theResource, Writer theWriter) throws IOException, DataFormatException;
044
045        /**
046         * See {@link #setEncodeElements(Set)}
047         */
048        Set<String> getEncodeElements();
049
050        /**
051         * See {@link #setEncodeElementsAppliesToResourceTypes(Set)}
052         */
053        Set<String> getEncodeElementsAppliesToResourceTypes();
054
055        /**
056         * If not set to null (as is the default) this ID will be used as the ID in any
057         * resources encoded by this parser
058         */
059        IIdType getEncodeForceResourceId();
060
061        /**
062         * Which encoding does this parser instance produce?
063         */
064        EncodingEnum getEncoding();
065
066        /**
067         * Gets the preferred types, as set using {@link #setPreferTypes(List)}
068         * 
069         * @return Returns the preferred types, or <code>null</code>
070         * @see #setPreferTypes(List)
071         */
072        List<Class<? extends IBaseResource>> getPreferTypes();
073
074        /**
075         * Returns true if resource IDs should be omitted
076         * 
077         * @see #setOmitResourceId(boolean)
078         * @since 1.1
079         */
080        boolean isOmitResourceId();
081
082        /**
083         * If set to <code>true<code> (which is the default), resource references containing a version
084         * will have the version removed when the resource is encoded. This is generally good behaviour because
085         * in most situations, references from one resource to another should be to the resource by ID, not
086         * by ID and version. In some cases though, it may be desirable to preserve the version in resource
087         * links. In that case, this value should be set to <code>false</code>.
088         * 
089         * @return Returns the parser instance's configuration setting for stripping versions from resource references when
090         *         encoding. This method will retun <code>null</code> if no value is set, in which case
091         *         the value from the {@link ParserOptions} will be used (default is <code>true</code>)
092         * @see ParserOptions
093         */
094        Boolean getStripVersionsFromReferences();
095
096        /**
097         * If set to <code>true</code> (which is the default), the Bundle.entry.fullUrl will override the Bundle.entry.resource's
098         * resource id if the fullUrl is defined. This behavior happens when parsing the source data into a Bundle object. Set this
099         * to <code>false</code> if this is not the desired behavior (e.g. the client code wishes to perform additional
100         * validation checks between the fullUrl and the resource id).
101         *
102         * @return Returns the parser instance's configuration setting for overriding resource ids with Bundle.entry.fullUrl when
103         *         parsing the source data into a Bundle object. This method will return <code>null</code> if no value is set, in
104         *         which case the value from the {@link ParserOptions} will be used (default is <code>true</code>)
105         * @see ParserOptions
106         */
107        Boolean getOverrideResourceIdWithBundleEntryFullUrl();
108
109        /**
110         * Is the parser in "summary mode"? See {@link #setSummaryMode(boolean)} for information
111         * 
112         * @see {@link #setSummaryMode(boolean)} for information
113         */
114        boolean isSummaryMode();
115
116        /**
117         * Parses a resource
118         * 
119         * @param theResourceType
120         *           The resource type to use. This can be used to explicitly specify a class which extends a built-in type
121         *           (e.g. a custom type extending the default Patient class)
122         * @param theReader
123         *           The reader to parse input from. Note that the Reader will not be closed by the parser upon completion.
124         * @return A parsed resource
125         * @throws DataFormatException
126         *            If the resource can not be parsed because the data is not recognized or invalid for any reason
127         */
128        <T extends IBaseResource> T parseResource(Class<T> theResourceType, Reader theReader) throws DataFormatException;
129
130        /**
131         * Parses a resource
132         * 
133         * @param theResourceType
134         *           The resource type to use. This can be used to explicitly specify a class which extends a built-in type
135         *           (e.g. a custom type extending the default Patient class)
136         * @param theString
137         *           The string to parse
138         * @return A parsed resource
139         * @throws DataFormatException
140         *            If the resource can not be parsed because the data is not recognized or invalid for any reason
141         */
142        <T extends IBaseResource> T parseResource(Class<T> theResourceType, String theString) throws DataFormatException;
143
144        /**
145         * Parses a resource
146         * 
147         * @param theReader
148         *           The reader to parse input from. Note that the Reader will not be closed by the parser upon completion.
149         * @return A parsed resource. Note that the returned object will be an instance of {@link IResource} or
150         *         {@link IAnyResource} depending on the specific FhirContext which created this parser.
151         * @throws DataFormatException
152         *            If the resource can not be parsed because the data is not recognized or invalid for any reason
153         */
154        IBaseResource parseResource(Reader theReader) throws ConfigurationException, DataFormatException;
155
156        /**
157         * Parses a resource
158         * 
159         * @param theMessageString
160         *           The string to parse
161         * @return A parsed resource. Note that the returned object will be an instance of {@link IResource} or
162         *         {@link IAnyResource} depending on the specific FhirContext which created this parser.
163         * @throws DataFormatException
164         *            If the resource can not be parsed because the data is not recognized or invalid for any reason
165         */
166        IBaseResource parseResource(String theMessageString) throws ConfigurationException, DataFormatException;
167
168        /**
169         * If provided, specifies the elements which should NOT be encoded. Valid values for this
170         * field would include:
171         * <ul>
172         * <li><b>Patient</b> - Don't encode patient and all its children</li>
173         * <li><b>Patient.name</b> - Don't encode the patient's name</li>
174         * <li><b>Patient.name.family</b> - Don't encode the patient's family name</li>
175         * <li><b>*.text</b> - Don't encode the text element on any resource (only the very first position may contain a
176         * wildcard)</li>
177         * </ul>
178         * <p>
179         * DSTU2 note: Note that values including meta, such as <code>Patient.meta</code>
180         * will work for DSTU2 parsers, but values with subelements on meta such
181         * as <code>Patient.meta.lastUpdated</code> will only work in
182         * DSTU3+ mode.
183         * </p>
184         * 
185         * @param theDontEncodeElements
186         *           The elements to encode
187         * @see #setEncodeElements(Set)
188         */
189        void setDontEncodeElements(Set<String> theDontEncodeElements);
190
191        /**
192         * If provided, specifies the elements which should be encoded, to the exclusion of all others. Valid values for this
193         * field would include:
194         * <ul>
195         * <li><b>Patient</b> - Encode patient and all its children</li>
196         * <li><b>Patient.name</b> - Encode only the patient's name</li>
197         * <li><b>Patient.name.family</b> - Encode only the patient's family name</li>
198         * <li><b>*.text</b> - Encode the text element on any resource (only the very first position may contain a
199         * wildcard)</li>
200         * <li><b>*.(mandatory)</b> - This is a special case which causes any mandatory fields (min > 0) to be encoded</li>
201         * </ul>
202         * 
203         * @param theEncodeElements
204         *           The elements to encode
205         * @see #setDontEncodeElements(Set)
206         */
207        void setEncodeElements(Set<String> theEncodeElements);
208
209        /**
210         * If provided, tells the parse which resource types to apply {@link #setEncodeElements(Set) encode elements} to. Any
211         * resource types not specified here will be encoded completely, with no elements excluded.
212         * 
213         * @param theEncodeElementsAppliesToResourceTypes
214         */
215        void setEncodeElementsAppliesToResourceTypes(Set<String> theEncodeElementsAppliesToResourceTypes);
216
217        /**
218         * When encoding, force this resource ID to be encoded as the resource ID
219         */
220        IParser setEncodeForceResourceId(IIdType theForceResourceId);
221
222        /**
223         * If set to <code>true</code> (default is <code>false</code>) the ID of any resources being encoded will not be
224         * included in the output. Note that this does not apply to contained resources, only to root resources. In other
225         * words, if this is set to <code>true</code>, contained resources will still have local IDs but the outer/containing
226         * ID will not have an ID.
227         * 
228         * @param theOmitResourceId
229         *           Should resource IDs be omitted
230         * @return Returns a reference to <code>this</code> parser so that method calls can be chained together
231         * @since 1.1
232         */
233        IParser setOmitResourceId(boolean theOmitResourceId);
234
235        /**
236         * Registers an error handler which will be invoked when any parse errors are found
237         * 
238         * @param theErrorHandler
239         *           The error handler to set. Must not be null.
240         */
241        IParser setParserErrorHandler(IParserErrorHandler theErrorHandler);
242
243        /**
244         * If set, when parsing resources the parser will try to use the given types when possible, in
245         * the order that they are provided (from highest to lowest priority). For example, if a custom
246         * type which declares to implement the Patient resource is passed in here, and the
247         * parser is parsing a Bundle containing a Patient resource, the parser will use the given
248         * custom type.
249         * <p>
250         * This feature is related to, but not the same as the
251         * {@link FhirContext#setDefaultTypeForProfile(String, Class)} feature.
252         * <code>setDefaultTypeForProfile</code> is used to specify a type to be used
253         * when a resource explicitly declares support for a given profile. This
254         * feature specifies a type to be used irrespective of the profile declaration
255         * in the metadata statement.
256         * </p>
257         * 
258         * @param thePreferTypes
259         *           The preferred types, or <code>null</code>
260         */
261        void setPreferTypes(List<Class<? extends IBaseResource>> thePreferTypes);
262
263        /**
264         * Sets the "pretty print" flag, meaning that the parser will encode resources with human-readable spacing and
265         * newlines between elements instead of condensing output as much as possible.
266         * 
267         * @param thePrettyPrint
268         *           The flag
269         * @return Returns an instance of <code>this</code> parser so that method calls can be chained together
270         */
271        IParser setPrettyPrint(boolean thePrettyPrint);
272
273        /**
274         * Sets the server's base URL used by this parser. If a value is set, resource references will be turned into
275         * relative references if they are provided as absolute URLs but have a base matching the given base.
276         * 
277         * @param theUrl
278         *           The base URL, e.g. "http://example.com/base"
279         * @return Returns an instance of <code>this</code> parser so that method calls can be chained together
280         */
281        IParser setServerBaseUrl(String theUrl);
282
283        /**
284         * If set to <code>true<code> (which is the default), resource references containing a version
285         * will have the version removed when the resource is encoded. This is generally good behaviour because
286         * in most situations, references from one resource to another should be to the resource by ID, not
287         * by ID and version. In some cases though, it may be desirable to preserve the version in resource
288         * links. In that case, this value should be set to <code>false</code>.
289         * <p>
290         * This method provides the ability to globally disable reference encoding. If finer-grained
291         * control is needed, use {@link #setDontStripVersionsFromReferencesAtPaths(String...)}
292         * </p>
293         * 
294         * @param theStripVersionsFromReferences
295         *           Set this to <code>false<code> to prevent the parser from removing resource versions from references (or <code>null</code> to apply the default setting from the {@link ParserOptions}
296         * @see #setDontStripVersionsFromReferencesAtPaths(String...)
297         * @see ParserOptions
298         * @return Returns a reference to <code>this</code> parser so that method calls can be chained together
299         */
300        IParser setStripVersionsFromReferences(Boolean theStripVersionsFromReferences);
301
302        /**
303         * If set to <code>true</code> (which is the default), the Bundle.entry.fullUrl will override the Bundle.entry.resource's
304         * resource id if the fullUrl is defined. This behavior happens when parsing the source data into a Bundle object. Set this
305         * to <code>false</code> if this is not the desired behavior (e.g. the client code wishes to perform additional
306         * validation checks between the fullUrl and the resource id).
307         *
308         * @param theOverrideResourceIdWithBundleEntryFullUrl
309         *           Set this to <code>false</code> to prevent the parser from overriding resource ids with the
310         *           Bundle.entry.fullUrl (or <code>null</code> to apply the default setting from the {@link ParserOptions})
311         *
312         * @see ParserOptions
313         *
314         * @return Returns a reference to <code>this</code> parser so that method calls can be chained together
315         */
316        IParser setOverrideResourceIdWithBundleEntryFullUrl(Boolean theOverrideResourceIdWithBundleEntryFullUrl);
317
318        /**
319         * If set to <code>true</code> (default is <code>false</code>) only elements marked by the FHIR specification as
320         * being "summary elements" will be included.
321         * 
322         * @return Returns a reference to <code>this</code> parser so that method calls can be chained together
323         */
324        IParser setSummaryMode(boolean theSummaryMode);
325
326        /**
327         * If set to <code>true</code> (default is <code>false</code>), narratives will not be included in the encoded
328         * values.
329         */
330        IParser setSuppressNarratives(boolean theSuppressNarratives);
331
332        /**
333         * If supplied value(s), any resource references at the specified paths will have their
334         * resource versions encoded instead of being automatically stripped during the encoding
335         * process. This setting has no effect on the parsing process.
336         * <p>
337         * This method provides a finer-grained level of control than {@link #setStripVersionsFromReferences(Boolean)}
338         * and any paths specified by this method will be encoded even if {@link #setStripVersionsFromReferences(Boolean)}
339         * has been set to <code>true</code> (which is the default)
340         * </p>
341         *
342         * @param thePaths
343         *           A collection of paths for which the resource versions will not be removed automatically
344         *           when serializing, e.g. "Patient.managingOrganization" or "AuditEvent.object.reference". Note that
345         *           only resource name and field names with dots separating is allowed here (no repetition
346         *           indicators, FluentPath expressions, etc.). Set to <code>null</code> to use the value
347         *           set in the {@link ParserOptions}
348         * @see #setStripVersionsFromReferences(Boolean)
349         * @see ParserOptions
350         * @return Returns a reference to <code>this</code> parser so that method calls can be chained together
351         */
352        IParser setDontStripVersionsFromReferencesAtPaths(String... thePaths);
353
354        /**
355         * If supplied value(s), any resource references at the specified paths will have their
356         * resource versions encoded instead of being automatically stripped during the encoding
357         * process. This setting has no effect on the parsing process.
358         * <p>
359         * This method provides a finer-grained level of control than {@link #setStripVersionsFromReferences(Boolean)}
360         * and any paths specified by this method will be encoded even if {@link #setStripVersionsFromReferences(Boolean)}
361         * has been set to <code>true</code> (which is the default)
362         * </p>
363         *
364         * @param thePaths
365         *           A collection of paths for which the resource versions will not be removed automatically
366         *           when serializing, e.g. "Patient.managingOrganization" or "AuditEvent.object.reference". Note that
367         *           only resource name and field names with dots separating is allowed here (no repetition
368         *           indicators, FluentPath expressions, etc.). Set to <code>null</code> to use the value
369         *           set in the {@link ParserOptions}
370         * @see #setStripVersionsFromReferences(Boolean)
371         * @see ParserOptions
372         * @return Returns a reference to <code>this</code> parser so that method calls can be chained together
373         */
374        IParser setDontStripVersionsFromReferencesAtPaths(Collection<String> thePaths);
375
376        /**
377         * Returns the value supplied to {@link IParser#setDontStripVersionsFromReferencesAtPaths(String...)}
378         * or <code>null</code> if no value has been set for this parser (in which case the default from
379         * the {@link ParserOptions} will be used}
380         * 
381         * @see #setDontStripVersionsFromReferencesAtPaths(String...)
382         * @see #setStripVersionsFromReferences(Boolean)
383         * @see ParserOptions
384         */
385        Set<String> getDontStripVersionsFromReferencesAtPaths();
386
387}