001package org.hl7.fhir.r5.utils.client;
002
003/*-
004 * #%L
005 * org.hl7.fhir.r5
006 * %%
007 * Copyright (C) 2014 - 2019 Health Level 7
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
023
024
025/*
026  Copyright (c) 2011+, HL7, Inc.
027  All rights reserved.
028  
029  Redistribution and use in source and binary forms, with or without modification, 
030  are permitted provided that the following conditions are met:
031  
032   * Redistributions of source code must retain the above copyright notice, this 
033     list of conditions and the following disclaimer.
034   * Redistributions in binary form must reproduce the above copyright notice, 
035     this list of conditions and the following disclaimer in the documentation 
036     and/or other materials provided with the distribution.
037   * Neither the name of HL7 nor the names of its contributors may be used to 
038     endorse or promote products derived from this software without specific 
039     prior written permission.
040  
041  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
042  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
043  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
044  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
045  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
046  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
047  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
048  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
049  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
050  POSSIBILITY OF SUCH DAMAGE.
051  
052*/
053
054
055import java.net.URI;
056import java.net.URISyntaxException;
057import java.text.SimpleDateFormat;
058import java.util.Calendar;
059import java.util.Date;
060import java.util.HashMap;
061import java.util.Locale;
062import java.util.Map;
063import java.util.Set;
064import java.util.TimeZone;
065import java.util.regex.Matcher;
066import java.util.regex.Pattern;
067
068import org.apache.commons.lang3.StringUtils;
069import org.apache.http.client.utils.URIBuilder;
070import org.hl7.fhir.r5.model.Resource;
071import org.hl7.fhir.r5.model.ResourceType;
072import org.hl7.fhir.utilities.Utilities;
073
074//Make resources address subclass of URI
075/**
076 * Helper class to manage FHIR Resource URIs
077 * 
078 * @author Claude Nanjo
079 *
080 */
081public class ResourceAddress {
082        
083        public static final String REGEX_ID_WITH_HISTORY = "(.*)(/)([a-zA-Z0-9]*)(/)([a-z0-9\\-\\.]{1,64})(/_history/)([a-z0-9\\-\\.]{1,64})$";
084        
085        private URI baseServiceUri;
086        
087        public ResourceAddress(String endpointPath) throws URISyntaxException {//TODO Revisit this exception
088                this.baseServiceUri = ResourceAddress.buildAbsoluteURI(endpointPath);
089        }
090        
091        public ResourceAddress(URI baseServiceUri) {
092                this.baseServiceUri = baseServiceUri;
093        }
094        
095        public URI getBaseServiceUri() {
096                return this.baseServiceUri;
097        }
098        
099        public <T extends Resource> URI resolveOperationURLFromClass(Class<T> resourceClass, String name, String parameters) {
100                return baseServiceUri.resolve(nameForClassWithSlash(resourceClass) +"$"+name+"?"+ parameters);
101        }
102        
103        public <T extends Resource> URI resolveSearchUri(Class<T> resourceClass, Map<String,String> parameters) {
104                return appendHttpParameters(baseServiceUri.resolve(nameForClassWithSlash(resourceClass) +"_search"), parameters);
105        }
106        
107  private <T extends Resource> String nameForClassWithSlash(Class<T> resourceClass) {
108    String n = nameForClass(resourceClass);
109    return n == null ? "" : n +"/";
110        }
111        
112  public <T extends Resource> URI resolveOperationUri(Class<T> resourceClass, String opName) {
113    return baseServiceUri.resolve(nameForClassWithSlash(resourceClass) +"/"+opName);
114  }
115  
116  public <T extends Resource> URI resolveOperationUri(Class<T> resourceClass, String opName, Map<String,String> parameters) {
117    return appendHttpParameters(baseServiceUri.resolve(nameForClassWithSlash(resourceClass) +"$"+opName), parameters);
118  }
119  
120        public <T extends Resource> URI resolveValidateUri(Class<T> resourceClass, String id) {
121                return baseServiceUri.resolve(nameForClassWithSlash(resourceClass) +"$validate/"+id);
122        }
123        
124        public <T extends Resource> URI resolveGetUriFromResourceClass(Class<T> resourceClass) {
125                return baseServiceUri.resolve(nameForClass(resourceClass));
126        }
127        
128        public <T extends Resource> URI resolveGetUriFromResourceClassAndId(Class<T> resourceClass, String id) {
129                return baseServiceUri.resolve(nameForClass(resourceClass) +"/"+id);
130        }
131        
132        public <T extends Resource> URI resolveGetUriFromResourceClassAndIdAndVersion(Class<T> resourceClass, String id, String version) {
133                return baseServiceUri.resolve(nameForClass(resourceClass) +"/"+id+"/_history/"+version);
134        }
135        
136  public <T extends Resource> URI resolveGetUriFromResourceClassAndCanonical(Class<T> resourceClass, String canonicalUrl) {
137    if (canonicalUrl.contains("|"))
138      return baseServiceUri.resolve(nameForClass(resourceClass)+"?url="+canonicalUrl.substring(0, canonicalUrl.indexOf("|"))+"&version="+canonicalUrl.substring(canonicalUrl.indexOf("|")+1));      
139    else
140      return baseServiceUri.resolve(nameForClass(resourceClass)+"?url="+canonicalUrl);
141  }
142  
143        public URI resolveGetHistoryForAllResources(int count) {
144                if(count > 0) {
145                        return appendHttpParameter(baseServiceUri.resolve("_history"), "_count", ""+count);
146                } else {
147                        return baseServiceUri.resolve("_history");
148                }
149}
150        
151        public <T extends Resource> URI resolveGetHistoryForResourceId(Class<T> resourceClass, String id, int count) {
152                return resolveGetHistoryUriForResourceId(resourceClass, id, null, count);
153        }
154        
155        protected <T extends Resource> URI resolveGetHistoryUriForResourceId(Class<T> resourceClass, String id, Object since, int count) {
156                Map<String,String>  parameters = getHistoryParameters(since, count);
157                return appendHttpParameters(baseServiceUri.resolve(nameForClass(resourceClass) + "/" + id + "/_history"), parameters);
158        }
159        
160        public <T extends Resource> URI resolveGetHistoryForResourceType(Class<T> resourceClass, int count) {
161                Map<String,String>  parameters = getHistoryParameters(null, count);
162                return appendHttpParameters(baseServiceUri.resolve(nameForClass(resourceClass) + "/_history"), parameters);
163        }
164        
165        public <T extends Resource> URI resolveGetHistoryForResourceType(Class<T> resourceClass, Object since, int count) {
166                Map<String,String>  parameters = getHistoryParameters(since, count);
167                return appendHttpParameters(baseServiceUri.resolve(nameForClass(resourceClass) + "/_history"), parameters);
168        }
169        
170        public URI resolveGetHistoryForAllResources(Calendar since, int count) {
171                Map<String,String>  parameters = getHistoryParameters(since, count);
172                return appendHttpParameters(baseServiceUri.resolve("_history"), parameters);
173        }
174        
175        public URI resolveGetHistoryForAllResources(Date since, int count) {
176                Map<String,String>  parameters = getHistoryParameters(since, count);
177                return appendHttpParameters(baseServiceUri.resolve("_history"), parameters);
178        }
179        
180        public Map<String,String> getHistoryParameters(Object since, int count) {
181                Map<String,String>  parameters = new HashMap<String,String>();
182                if (since != null) {
183                        parameters.put("_since", since.toString());
184                }
185                if(count > 0) {
186                        parameters.put("_count", ""+count);
187                }
188                return parameters;
189        }
190        
191        public <T extends Resource> URI resolveGetHistoryForResourceId(Class<T> resourceClass, String id, Calendar since, int count) {
192                return resolveGetHistoryUriForResourceId(resourceClass, id, since, count);
193        }
194        
195        public <T extends Resource> URI resolveGetHistoryForResourceId(Class<T> resourceClass, String id, Date since, int count) {
196                return resolveGetHistoryUriForResourceId(resourceClass, id, since, count);
197        }
198        
199        public <T extends Resource> URI resolveGetHistoryForResourceType(Class<T> resourceClass, Calendar since, int count) {
200                return resolveGetHistoryForResourceType(resourceClass, getCalendarDateInIsoTimeFormat(since), count);
201        }
202        
203        public <T extends Resource> URI resolveGetHistoryForResourceType(Class<T> resourceClass, Date since, int count) {
204                return resolveGetHistoryForResourceType(resourceClass, since.toString(), count);
205        }
206        
207        public <T extends Resource> URI resolveGetAllTags() {
208                return baseServiceUri.resolve("_tags");
209        }
210        
211        public <T extends Resource> URI resolveGetAllTagsForResourceType(Class<T> resourceClass) {
212                return baseServiceUri.resolve(nameForClass(resourceClass) + "/_tags");
213        }
214        
215        public <T extends Resource> URI resolveGetTagsForReference(Class<T> resourceClass, String id) {
216                return baseServiceUri.resolve(nameForClass(resourceClass) + "/" + id + "/_tags");
217        }
218        
219        public <T extends Resource> URI resolveGetTagsForResourceVersion(Class<T> resourceClass, String id, String version) {
220                return baseServiceUri.resolve(nameForClass(resourceClass) +"/"+id+"/_history/"+version + "/_tags");
221        }
222        
223        public <T extends Resource> URI resolveDeleteTagsForResourceVersion(Class<T> resourceClass, String id, String version) {
224                return baseServiceUri.resolve(nameForClass(resourceClass) +"/"+id+"/_history/"+version + "/_tags/_delete");
225        }
226        
227
228        public <T extends Resource> String nameForClass(Class<T> resourceClass) {
229          if (resourceClass == null)
230            return null;
231                String res = resourceClass.getSimpleName();
232                if (res.equals("List_"))
233                        return "List";
234                else
235                        return res;
236        }
237        
238  public URI resolveMetadataUri(boolean quick) {
239    return baseServiceUri.resolve(quick ? "metadata?_summary=true" : "metadata");
240  }
241  
242  public URI resolveMetadataTxCaps() {
243    return baseServiceUri.resolve("metadata?mode=terminology");
244  }
245  
246        /**
247         * For now, assume this type of location header structure.
248         * Generalize later: http://hl7connect.healthintersections.com.au/svc/fhir/318/_history/1
249         * 
250         * @param serviceBase
251         * @param locationHeader
252         */
253        public static ResourceAddress.ResourceVersionedIdentifier parseCreateLocation(String locationResponseHeader) {
254                Pattern pattern = Pattern.compile(REGEX_ID_WITH_HISTORY);
255                Matcher matcher = pattern.matcher(locationResponseHeader);
256                ResourceVersionedIdentifier parsedHeader = null;
257                if(matcher.matches()){
258                        String serviceRoot = matcher.group(1);
259                        String resourceType = matcher.group(3);
260                        String id = matcher.group(5);
261                        String version = matcher.group(7);
262                        parsedHeader = new ResourceVersionedIdentifier(serviceRoot, resourceType, id, version);
263                }
264                return parsedHeader;
265        }
266        
267        public static URI buildAbsoluteURI(String absoluteURI) {
268                
269                if(StringUtils.isBlank(absoluteURI)) {
270                        throw new EFhirClientException("Invalid URI", new URISyntaxException(absoluteURI, "URI/URL cannot be blank"));
271                } 
272                
273                String endpoint = appendForwardSlashToPath(absoluteURI);
274
275                return buildEndpointUriFromString(endpoint);
276        }
277        
278        public static String appendForwardSlashToPath(String path) {
279                if(path.lastIndexOf('/') != path.length() - 1) {
280                        path += "/";
281                }
282                return path;
283        }
284        
285        public static URI buildEndpointUriFromString(String endpointPath) {
286                URI uri = null; 
287                try {
288                        URIBuilder uriBuilder = new URIBuilder(endpointPath);
289                        uri = uriBuilder.build();
290                        String scheme = uri.getScheme();
291                        String host = uri.getHost();
292                        if(!scheme.equalsIgnoreCase("http") && !scheme.equalsIgnoreCase("https")) {
293                                throw new EFhirClientException("Scheme must be 'http' or 'https': " + uri);
294                        }
295                        if(StringUtils.isBlank(host)) {
296                                throw new EFhirClientException("host cannot be blank: " + uri);
297                        }
298                } catch(URISyntaxException e) {
299                        throw new EFhirClientException("Invalid URI", e);
300                }
301                return uri;
302        }
303        
304        public static URI appendQueryStringToUri(URI uri, String parameterName, String parameterValue) {
305                URI modifiedUri = null;
306                try {
307                        URIBuilder uriBuilder = new URIBuilder(uri);
308                        uriBuilder.setQuery(parameterName + "=" + parameterValue);
309                        modifiedUri = uriBuilder.build();
310                } catch(Exception e) {
311                        throw new EFhirClientException("Unable to append query parameter '" + parameterName + "=" + parameterValue + " to URI " + uri, e);
312                }
313                return modifiedUri;
314        }
315        
316        public static String buildRelativePathFromResourceType(ResourceType resourceType) {
317                //return resourceType.toString().toLowerCase()+"/";
318                return resourceType.toString() + "/";
319        }
320        
321        public static String buildRelativePathFromResourceType(ResourceType resourceType, String id) {
322                return buildRelativePathFromResourceType(resourceType)+ "@" + id;
323        }
324        
325        public static String buildRelativePathFromReference(Resource resource) {
326                return buildRelativePathFromResourceType(resource.getResourceType());
327        }
328        
329        public static String buildRelativePathFromReference(Resource resource, String id) {
330                return buildRelativePathFromResourceType(resource.getResourceType(), id);
331        }
332        
333        public static class ResourceVersionedIdentifier {
334                
335                private String serviceRoot;
336                private String resourceType;
337                private String id;
338                private String version;
339                private URI resourceLocation;
340                
341                public ResourceVersionedIdentifier(String serviceRoot, String resourceType, String id, String version, URI resourceLocation) {
342                        this.serviceRoot = serviceRoot;
343                        this.resourceType = resourceType;
344                        this.id = id;
345                        this.version = version;
346                        this.resourceLocation = resourceLocation;
347                }
348                
349                public ResourceVersionedIdentifier(String resourceType, String id, String version, URI resourceLocation) {
350                        this(null, resourceType, id, version, resourceLocation);
351                }
352                
353                public ResourceVersionedIdentifier(String serviceRoot, String resourceType, String id, String version) {
354                        this(serviceRoot, resourceType, id, version, null);
355                }
356                
357                public ResourceVersionedIdentifier(String resourceType, String id, String version) {
358                        this(null, resourceType, id, version, null);
359                }
360                
361                public ResourceVersionedIdentifier(String resourceType, String id) {
362                        this.id = id;
363                }
364                
365                public String getId() {
366                        return this.id;
367                }
368                
369                protected void setId(String id) {
370                        this.id = id;
371                }
372                
373                public String getVersionId() {
374                        return this.version;
375                }
376                
377                protected void setVersionId(String version) {
378                        this.version = version;
379                }
380                
381                public String getResourceType() {
382                        return resourceType;
383                }
384
385                public void setResourceType(String resourceType) {
386                        this.resourceType = resourceType;
387                }
388                
389                public String getServiceRoot() {
390                        return serviceRoot;
391                }
392
393                public void setServiceRoot(String serviceRoot) {
394                        this.serviceRoot = serviceRoot;
395                }
396                
397                public String getResourcePath() {
398                        return this.serviceRoot + "/" + this.resourceType + "/" + this.id;
399                }
400
401                public String getVersion() {
402                        return version;
403                }
404
405                public void setVersion(String version) {
406                        this.version = version;
407                }
408
409                public URI getResourceLocation() {
410                        return this.resourceLocation;
411                }
412                
413                public void setResourceLocation(URI resourceLocation) {
414                        this.resourceLocation = resourceLocation;
415                }
416        }
417        
418        public static String getCalendarDateInIsoTimeFormat(Calendar calendar) {
419                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss", new Locale("en", "US"));//TODO Move out
420                format.setTimeZone(TimeZone.getTimeZone("GMT"));
421            return format.format(calendar.getTime());
422        }
423        
424        public static URI appendHttpParameter(URI basePath, String httpParameterName, String httpParameterValue) {
425                Map<String, String> parameters = new HashMap<String, String>();
426                parameters.put(httpParameterName, httpParameterValue);
427                return appendHttpParameters(basePath, parameters);
428        }
429        
430        public static URI appendHttpParameters(URI basePath, Map<String,String> parameters) {
431        try {
432                Set<String> httpParameterNames = parameters.keySet();
433                String query = basePath.getQuery();
434                
435                for(String httpParameterName : httpParameterNames) {
436                        if(query != null) {
437                                query += "&";
438                        } else {
439                                query = "";
440                        }
441                        query += httpParameterName + "=" + Utilities.encodeUri(parameters.get(httpParameterName));
442                }
443        
444                return new URI(basePath.getScheme(), basePath.getUserInfo(), basePath.getHost(),basePath.getPort(), basePath.getPath(), query, basePath.getFragment());
445        } catch(Exception e) {
446                throw new EFhirClientException("Error appending http parameter", e);
447        }
448    }
449        
450}