001package org.hl7.fhir.instance.conf;
002
003/*
004 * #%L
005 * HAPI FHIR Structures - DSTU2 (FHIR v0.5.0)
006 * %%
007 * Copyright (C) 2014 - 2015 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 static org.apache.commons.lang3.StringUtils.isNotBlank;
023
024import java.text.*;
025import java.util.*;
026import java.util.Map.Entry;
027import java.util.concurrent.Callable;
028
029import javax.servlet.ServletContext;
030import javax.servlet.http.HttpServletRequest;
031
032import ca.uhn.fhir.context.FhirVersionEnum;
033import ca.uhn.fhir.parser.DataFormatException;
034import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
035import org.apache.commons.lang3.StringUtils;
036import org.hl7.fhir.instance.model.*;
037import org.hl7.fhir.instance.model.Conformance.*;
038import org.hl7.fhir.instance.model.Enumerations.ConformanceResourceStatus;
039import org.hl7.fhir.instance.model.Enumerations.ResourceType;
040import org.hl7.fhir.instance.model.OperationDefinition.OperationDefinitionParameterComponent;
041import org.hl7.fhir.instance.model.OperationDefinition.OperationParameterUse;
042import org.hl7.fhir.instance.model.api.IBaseResource;
043
044import ca.uhn.fhir.context.RuntimeResourceDefinition;
045import ca.uhn.fhir.context.RuntimeSearchParam;
046import ca.uhn.fhir.rest.annotation.*;
047import ca.uhn.fhir.rest.api.Constants;
048import ca.uhn.fhir.rest.server.*;
049import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException;
050import ca.uhn.fhir.rest.server.method.*;
051import ca.uhn.fhir.rest.server.method.OperationMethodBinding.ReturnType;
052import ca.uhn.fhir.rest.server.method.SearchParameter;
053import org.hl7.fhir.instance.model.api.IPrimitiveType;
054
055/**
056 * Server FHIR Provider which serves the conformance statement for a RESTful
057 * server implementation
058 * 
059 * <p>
060 * Note: This class is safe to extend, but it is important to note that the same
061 * instance of {@link Conformance} is always returned unless
062 * {@link #setCache(boolean)} is called with a value of <code>false</code>. This
063 * means that if you are adding anything to the returned conformance instance on
064 * each call you should call <code>setCache(false)</code> in your provider
065 * constructor.
066 * </p>
067 */
068public class ServerConformanceProvider implements IServerConformanceProvider<Conformance> {
069
070        private boolean myCache = true;
071        private volatile Conformance myConformance;
072        private IdentityHashMap<OperationMethodBinding, String> myOperationBindingToName;
073        private HashMap<String, List<OperationMethodBinding>> myOperationNameToBindings;
074        private String myPublisher = "Not provided";
075  private Callable<RestulfulServerConfiguration> myServerConfiguration;
076
077  /**
078   * No-arg constructor and seetter so that the ServerConfirmanceProvider can be Spring-wired with the RestfulService avoiding the potential reference cycle that would happen.
079   */
080  public ServerConformanceProvider() {
081    super();
082  }
083
084  /**
085   * Constructor
086   */
087  public ServerConformanceProvider(RestfulServer theRestfulServer) {
088    this.myServerConfiguration = theRestfulServer::createConfiguration;
089  }
090
091  /**
092   * Constructor
093   */
094  public ServerConformanceProvider(RestulfulServerConfiguration theServerConfiguration) {
095    this.myServerConfiguration = () -> theServerConfiguration;
096  }
097
098   @Override
099   public void setRestfulServer (RestfulServer theRestfulServer) {
100     myServerConfiguration = theRestfulServer::createConfiguration;
101   }
102
103  RestulfulServerConfiguration getServerConfiguration() {
104    try {
105      return myServerConfiguration.call();
106    } catch (Exception e) {
107      throw new InternalErrorException(e);
108    }
109  }
110
111  private void checkBindingForSystemOps(ConformanceRestComponent rest, Set<SystemRestfulInteraction> systemOps,
112      BaseMethodBinding<?> nextMethodBinding) {
113    if (nextMethodBinding.getRestOperationType() != null) {
114      String sysOpCode = nextMethodBinding.getRestOperationType().getCode();
115      if (sysOpCode != null) {
116        SystemRestfulInteraction sysOp;
117        try {
118          sysOp = SystemRestfulInteraction.fromCode(sysOpCode);
119        } catch (Exception e) {
120          sysOp = null;
121        }
122        if (sysOp == null) {
123          return;
124        }
125        if (systemOps.contains(sysOp) == false) {
126          systemOps.add(sysOp);
127          rest.addInteraction().setCode(sysOp);
128        }
129      }
130    }
131  }
132
133  private Map<String, List<BaseMethodBinding<?>>> collectMethodBindings() {
134    Map<String, List<BaseMethodBinding<?>>> resourceToMethods = new TreeMap<String, List<BaseMethodBinding<?>>>();
135    for (ResourceBinding next : getServerConfiguration().getResourceBindings()) {
136      String resourceName = next.getResourceName();
137      for (BaseMethodBinding<?> nextMethodBinding : next.getMethodBindings()) {
138        if (resourceToMethods.containsKey(resourceName) == false) {
139          resourceToMethods.put(resourceName, new ArrayList<BaseMethodBinding<?>>());
140        }
141        resourceToMethods.get(resourceName).add(nextMethodBinding);
142      }
143    }
144    for (BaseMethodBinding<?> nextMethodBinding : getServerConfiguration().getServerBindings()) {
145      String resourceName = "";
146      if (resourceToMethods.containsKey(resourceName) == false) {
147        resourceToMethods.put(resourceName, new ArrayList<BaseMethodBinding<?>>());
148      }
149      resourceToMethods.get(resourceName).add(nextMethodBinding);
150    }
151    return resourceToMethods;
152  }
153
154  private String createOperationName(OperationMethodBinding theMethodBinding) {
155    return theMethodBinding.getName().substring(1);
156  }
157
158  /**
159   * Gets the value of the "publisher" that will be placed in the generated
160   * conformance statement. As this is a mandatory element, the value should not
161   * be null (although this is not enforced). The value defaults to
162   * "Not provided" but may be set to null, which will cause this element to be
163   * omitted.
164   */
165  public String getPublisher() {
166    return myPublisher;
167  }
168
169  @Override
170  @Metadata
171  public Conformance getServerConformance(HttpServletRequest theRequest) {
172    if (myConformance != null && myCache) {
173      return myConformance;
174    }
175
176    Conformance retVal = new Conformance();
177
178    retVal.setPublisher(myPublisher);
179    retVal.setDateElement(conformanceDate());
180    retVal.setFhirVersion(FhirVersionEnum.DSTU2_HL7ORG.getFhirVersionString());
181    retVal.setAcceptUnknown(UnknownContentCode.EXTENSIONS); // TODO: make this configurable - this is a fairly big effort since the parser
182    // needs to be modified to actually allow it
183
184    retVal.getImplementation().setDescription(getServerConfiguration().getImplementationDescription());
185    retVal.setKind(ConformanceStatementKind.INSTANCE);
186    retVal.getSoftware().setName(getServerConfiguration().getServerName());
187    retVal.getSoftware().setVersion(getServerConfiguration().getServerVersion());
188    retVal.addFormat(Constants.CT_FHIR_XML);
189    retVal.addFormat(Constants.CT_FHIR_JSON);
190
191    ConformanceRestComponent rest = retVal.addRest();
192    rest.setMode(RestfulConformanceMode.SERVER);
193
194    Set<SystemRestfulInteraction> systemOps = new HashSet<SystemRestfulInteraction>();
195    Set<String> operationNames = new HashSet<String>();
196
197    Map<String, List<BaseMethodBinding<?>>> resourceToMethods = collectMethodBindings();
198    for (Entry<String, List<BaseMethodBinding<?>>> nextEntry : resourceToMethods.entrySet()) {
199
200      if (nextEntry.getKey().isEmpty() == false) {
201        Set<TypeRestfulInteraction> resourceOps = new HashSet<TypeRestfulInteraction>();
202        ConformanceRestResourceComponent resource = rest.addResource();
203        String resourceName = nextEntry.getKey();
204        RuntimeResourceDefinition def = getServerConfiguration().getFhirContext().getResourceDefinition(resourceName);
205        resource.getTypeElement().setValue(def.getName());
206        ServletContext servletContext = (ServletContext) (theRequest == null ? null : theRequest.getAttribute(RestfulServer.SERVLET_CONTEXT_ATTRIBUTE));
207        String serverBase = getServerConfiguration().getServerAddressStrategy().determineServerBase(servletContext, theRequest);
208        resource.getProfile().setReference((def.getResourceProfile(serverBase)));
209
210        TreeSet<String> includes = new TreeSet<>();
211
212        // Map<String, Conformance.RestResourceSearchParam> nameToSearchParam =
213        // new HashMap<String,
214        // Conformance.RestResourceSearchParam>();
215        for (BaseMethodBinding<?> nextMethodBinding : nextEntry.getValue()) {
216          if (nextMethodBinding.getRestOperationType() != null) {
217            String resOpCode = nextMethodBinding.getRestOperationType().getCode();
218            if (resOpCode != null) {
219              TypeRestfulInteraction resOp;
220              try {
221                resOp = TypeRestfulInteraction.fromCode(resOpCode);
222              } catch (Exception e) {
223                resOp = null;
224              }
225              if (resOp != null) {
226                if (resourceOps.contains(resOp) == false) {
227                  resourceOps.add(resOp);
228                  resource.addInteraction().setCode(resOp);
229                }
230                if ("vread".equals(resOpCode)) {
231                  // vread implies read
232                  resOp = TypeRestfulInteraction.READ;
233                  if (resourceOps.contains(resOp) == false) {
234                    resourceOps.add(resOp);
235                    resource.addInteraction().setCode(resOp);
236                  }
237                }
238
239                if (nextMethodBinding.isSupportsConditional()) {
240                  switch (resOp) {
241                  case CREATE:
242                    resource.setConditionalCreate(true);
243                    break;
244                  case DELETE:
245                    resource.setConditionalDelete(ConditionalDeleteStatus.SINGLE);
246                    break;
247                  case UPDATE:
248                    resource.setConditionalUpdate(true);
249                    break;
250                  default:
251                    break;
252                  }
253                }
254              }
255            }
256          }
257
258          checkBindingForSystemOps(rest, systemOps, nextMethodBinding);
259
260          if (nextMethodBinding instanceof SearchMethodBinding) {
261            handleSearchMethodBinding(rest, resource, resourceName, def, includes,
262                (SearchMethodBinding) nextMethodBinding);
263          } else if (nextMethodBinding instanceof OperationMethodBinding) {
264            OperationMethodBinding methodBinding = (OperationMethodBinding) nextMethodBinding;
265            String opName = myOperationBindingToName.get(methodBinding);
266            if (operationNames.add(opName)) {
267              // Only add each operation (by name) once
268              rest.addOperation().setName(methodBinding.getName()).getDefinition()
269                  .setReference("OperationDefinition/" + opName);
270            }
271          }
272
273          Collections.sort(resource.getInteraction(), new Comparator<ResourceInteractionComponent>() {
274            @Override
275            public int compare(ResourceInteractionComponent theO1, ResourceInteractionComponent theO2) {
276              TypeRestfulInteraction o1 = theO1.getCode();
277              TypeRestfulInteraction o2 = theO2.getCode();
278              if (o1 == null && o2 == null) {
279                return 0;
280              }
281              if (o1 == null) {
282                return 1;
283              }
284              if (o2 == null) {
285                return -1;
286              }
287              return o1.ordinal() - o2.ordinal();
288            }
289          });
290
291        }
292
293        for (String nextInclude : includes) {
294          resource.addSearchInclude(nextInclude);
295        }
296      } else {
297        for (BaseMethodBinding<?> nextMethodBinding : nextEntry.getValue()) {
298          checkBindingForSystemOps(rest, systemOps, nextMethodBinding);
299          if (nextMethodBinding instanceof OperationMethodBinding) {
300            OperationMethodBinding methodBinding = (OperationMethodBinding) nextMethodBinding;
301            String opName = myOperationBindingToName.get(methodBinding);
302            if (operationNames.add(opName)) {
303              rest.addOperation().setName(methodBinding.getName()).getDefinition()
304                  .setReference("OperationDefinition/" + opName);
305            }
306          }
307        }
308      }
309    }
310
311    myConformance = retVal;
312    return retVal;
313  }
314
315  private DateTimeType conformanceDate() {
316    IPrimitiveType<Date> buildDate = getServerConfiguration().getConformanceDate();
317    if (buildDate != null && buildDate.getValue() != null) {
318      try {
319        return new DateTimeType(buildDate.getValueAsString());
320      } catch (DataFormatException e) {
321        // fall through
322      }
323    }
324    return DateTimeType.now();
325  }
326
327  private void handleSearchMethodBinding(ConformanceRestComponent rest, ConformanceRestResourceComponent resource,
328      String resourceName, RuntimeResourceDefinition def, TreeSet<String> includes,
329      SearchMethodBinding searchMethodBinding) {
330    includes.addAll(searchMethodBinding.getIncludes());
331
332    List<IParameter> params = searchMethodBinding.getParameters();
333    List<SearchParameter> searchParameters = new ArrayList<SearchParameter>();
334    for (IParameter nextParameter : params) {
335      if ((nextParameter instanceof SearchParameter)) {
336        searchParameters.add((SearchParameter) nextParameter);
337      }
338    }
339    sortSearchParameters(searchParameters);
340    if (!searchParameters.isEmpty()) {
341      // boolean allOptional = searchParameters.get(0).isRequired() == false;
342      //
343      // OperationDefinition query = null;
344      // if (!allOptional) {
345      // RestOperation operation = rest.addOperation();
346      // query = new OperationDefinition();
347      // operation.setDefinition(new ResourceReferenceDt(query));
348      // query.getDescriptionElement().setValue(searchMethodBinding.getDescription());
349      // query.addUndeclaredExtension(false,
350      // ExtensionConstants.QUERY_RETURN_TYPE, new CodeDt(resourceName));
351      // for (String nextInclude : searchMethodBinding.getIncludes()) {
352      // query.addUndeclaredExtension(false,
353      // ExtensionConstants.QUERY_ALLOWED_INCLUDE, new StringDt(nextInclude));
354      // }
355      // }
356
357      for (SearchParameter nextParameter : searchParameters) {
358
359        String nextParamName = nextParameter.getName();
360
361        String chain = null;
362        String nextParamUnchainedName = nextParamName;
363        if (nextParamName.contains(".")) {
364          chain = nextParamName.substring(nextParamName.indexOf('.') + 1);
365          nextParamUnchainedName = nextParamName.substring(0, nextParamName.indexOf('.'));
366        }
367
368        String nextParamDescription = nextParameter.getDescription();
369
370        /*
371         * If the parameter has no description, default to the one from the
372         * resource
373         */
374        if (StringUtils.isBlank(nextParamDescription)) {
375          RuntimeSearchParam paramDef = def.getSearchParam(nextParamUnchainedName);
376          if (paramDef != null) {
377            nextParamDescription = paramDef.getDescription();
378          }
379        }
380
381        ConformanceRestResourceSearchParamComponent param = resource.addSearchParam();
382        param.setName(nextParamUnchainedName);
383        if (StringUtils.isNotBlank(chain)) {
384          param.addChain(chain);
385        }
386        param.setDocumentation(nextParamDescription);
387        if (nextParameter.getParamType() != null) {
388          param.getTypeElement().setValueAsString(nextParameter.getParamType().getCode());
389        }
390        for (Class<? extends IBaseResource> nextTarget : nextParameter.getDeclaredTypes()) {
391          RuntimeResourceDefinition targetDef = getServerConfiguration().getFhirContext().getResourceDefinition(nextTarget);
392          if (targetDef != null) {
393            ResourceType code;
394            try {
395              code = ResourceType.fromCode(targetDef.getName());
396            } catch (Exception e) {
397              code = null;
398            }
399            if (code != null) {
400              param.addTarget(code.toCode());
401            }
402          }
403        }
404      }
405    }
406  }
407
408  @Initialize
409  public void initializeOperations() {
410    myOperationBindingToName = new IdentityHashMap<>();
411    myOperationNameToBindings = new HashMap<>();
412
413    Map<String, List<BaseMethodBinding<?>>> resourceToMethods = collectMethodBindings();
414    for (Entry<String, List<BaseMethodBinding<?>>> nextEntry : resourceToMethods.entrySet()) {
415      List<BaseMethodBinding<?>> nextMethodBindings = nextEntry.getValue();
416      for (BaseMethodBinding<?> nextMethodBinding : nextMethodBindings) {
417        if (nextMethodBinding instanceof OperationMethodBinding) {
418          OperationMethodBinding methodBinding = (OperationMethodBinding) nextMethodBinding;
419          if (myOperationBindingToName.containsKey(methodBinding)) {
420            continue;
421          }
422
423          String name = createOperationName(methodBinding);
424          myOperationBindingToName.put(methodBinding, name);
425          if (myOperationNameToBindings.containsKey(name) == false) {
426            myOperationNameToBindings.put(name, new ArrayList<>());
427          }
428          myOperationNameToBindings.get(name).add(methodBinding);
429        }
430      }
431    }
432  }
433
434  @Read(type = OperationDefinition.class)
435  public OperationDefinition readOperationDefinition(@IdParam IdType theId) {
436    if (theId == null || theId.hasIdPart() == false) {
437      throw new ResourceNotFoundException(theId);
438    }
439    List<OperationMethodBinding> sharedDescriptions = myOperationNameToBindings.get(theId.getIdPart());
440    if (sharedDescriptions == null || sharedDescriptions.isEmpty()) {
441      throw new ResourceNotFoundException(theId);
442    }
443
444    OperationDefinition op = new OperationDefinition();
445    op.setStatus(ConformanceResourceStatus.ACTIVE);
446    op.setIdempotent(true);
447
448    Set<String> inParams = new HashSet<>();
449    Set<String> outParams = new HashSet<>();
450
451    for (OperationMethodBinding sharedDescription : sharedDescriptions) {
452      if (isNotBlank(sharedDescription.getDescription())) {
453        op.setDescription(sharedDescription.getDescription());
454      }
455      if (!sharedDescription.isIdempotent()) {
456        op.setIdempotent(sharedDescription.isIdempotent());
457      }
458      op.setCode(sharedDescription.getName());
459      if (sharedDescription.isCanOperateAtInstanceLevel()) {
460        op.setInstance(sharedDescription.isCanOperateAtInstanceLevel());
461      }
462      if (sharedDescription.isCanOperateAtServerLevel()) {
463        op.setSystem(sharedDescription.isCanOperateAtServerLevel());
464      }
465      if (isNotBlank(sharedDescription.getResourceName())) {
466        op.addTypeElement().setValue(sharedDescription.getResourceName());
467      }
468
469      for (IParameter nextParamUntyped : sharedDescription.getParameters()) {
470        if (nextParamUntyped instanceof OperationParameter) {
471          OperationParameter nextParam = (OperationParameter) nextParamUntyped;
472          OperationDefinitionParameterComponent param = op.addParameter();
473          if (!inParams.add(nextParam.getName())) {
474            continue;
475          }
476          param.setUse(OperationParameterUse.IN);
477          if (nextParam.getParamType() != null) {
478            param.setType(nextParam.getParamType());
479          }
480          param.setMin(nextParam.getMin());
481          param.setMax(nextParam.getMax() == -1 ? "*" : Integer.toString(nextParam.getMax()));
482          param.setName(nextParam.getName());
483        }
484      }
485
486      for (ReturnType nextParam : sharedDescription.getReturnParams()) {
487        if (!outParams.add(nextParam.getName())) {
488          continue;
489        }
490        OperationDefinitionParameterComponent param = op.addParameter();
491        param.setUse(OperationParameterUse.OUT);
492        if (nextParam.getType() != null) {
493          param.setType(nextParam.getType());
494        }
495        param.setMin(nextParam.getMin());
496        param.setMax(nextParam.getMax() == -1 ? "*" : Integer.toString(nextParam.getMax()));
497        param.setName(nextParam.getName());
498      }
499    }
500
501    return op;
502  }
503
504  /**
505   * Sets the cache property (default is true). If set to true, the same
506   * response will be returned for each invocation.
507   * <p>
508   * See the class documentation for an important note if you are extending this
509   * class
510   * </p>
511   */
512  public void setCache(boolean theCache) {
513    myCache = theCache;
514  }
515
516  /**
517   * Sets the value of the "publisher" that will be placed in the generated
518   * conformance statement. As this is a mandatory element, the value should not
519   * be null (although this is not enforced). The value defaults to
520   * "Not provided" but may be set to null, which will cause this element to be
521   * omitted.
522   */
523  public void setPublisher(String thePublisher) {
524    myPublisher = thePublisher;
525  }
526
527  private void sortRuntimeSearchParameters(List<RuntimeSearchParam> searchParameters) {
528    Collections.sort(searchParameters, new Comparator<RuntimeSearchParam>() {
529      @Override
530      public int compare(RuntimeSearchParam theO1, RuntimeSearchParam theO2) {
531        return theO1.getName().compareTo(theO2.getName());
532      }
533    });
534  }
535
536  private void sortSearchParameters(List<SearchParameter> searchParameters) {
537    Collections.sort(searchParameters, new Comparator<SearchParameter>() {
538      @Override
539      public int compare(SearchParameter theO1, SearchParameter theO2) {
540        if (theO1.isRequired() == theO2.isRequired()) {
541          return theO1.getName().compareTo(theO2.getName());
542        }
543        if (theO1.isRequired()) {
544          return -1;
545        }
546        return 1;
547      }
548    });
549  }
550}