001package org.hl7.fhir.dstu3.hapi.rest.server;
002
003import ca.uhn.fhir.context.FhirVersionEnum;
004import ca.uhn.fhir.context.RuntimeResourceDefinition;
005import ca.uhn.fhir.context.RuntimeSearchParam;
006import ca.uhn.fhir.parser.DataFormatException;
007import ca.uhn.fhir.rest.annotation.IdParam;
008import ca.uhn.fhir.rest.annotation.Initialize;
009import ca.uhn.fhir.rest.annotation.Metadata;
010import ca.uhn.fhir.rest.annotation.Read;
011import ca.uhn.fhir.rest.api.Constants;
012import ca.uhn.fhir.rest.server.IServerConformanceProvider;
013import ca.uhn.fhir.rest.server.ResourceBinding;
014import ca.uhn.fhir.rest.server.RestfulServer;
015import ca.uhn.fhir.rest.server.RestulfulServerConfiguration;
016import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
017import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException;
018import ca.uhn.fhir.rest.server.method.*;
019import ca.uhn.fhir.rest.server.method.OperationMethodBinding.ReturnType;
020import ca.uhn.fhir.rest.server.method.SearchParameter;
021import org.apache.commons.lang3.StringUtils;
022import org.hl7.fhir.dstu3.model.*;
023import org.hl7.fhir.dstu3.model.CapabilityStatement.*;
024import org.hl7.fhir.dstu3.model.Enumerations.PublicationStatus;
025import org.hl7.fhir.dstu3.model.OperationDefinition.OperationDefinitionParameterComponent;
026import org.hl7.fhir.dstu3.model.OperationDefinition.OperationKind;
027import org.hl7.fhir.dstu3.model.OperationDefinition.OperationParameterUse;
028import org.hl7.fhir.exceptions.FHIRException;
029import org.hl7.fhir.instance.model.api.IBaseResource;
030import org.hl7.fhir.instance.model.api.IPrimitiveType;
031
032import javax.servlet.ServletContext;
033import javax.servlet.http.HttpServletRequest;
034import java.util.*;
035import java.util.Map.Entry;
036import java.util.concurrent.Callable;
037
038import static org.apache.commons.lang3.StringUtils.isBlank;
039import static org.apache.commons.lang3.StringUtils.isNotBlank;
040
041/*
042 * #%L
043 * HAPI FHIR Structures - DSTU2 (FHIR v1.0.0)
044 * %%
045 * Copyright (C) 2014 - 2015 University Health Network
046 * %%
047 * Licensed under the Apache License, Version 2.0 (the "License");
048 * you may not use this file except in compliance with the License.
049 * You may obtain a copy of the License at
050 *
051 *      http://www.apache.org/licenses/LICENSE-2.0
052 *
053 * Unless required by applicable law or agreed to in writing, software
054 * distributed under the License is distributed on an "AS IS" BASIS,
055 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
056 * See the License for the specific language governing permissions and
057 * limitations under the License.
058 * #L%
059 */
060
061/**
062 * Server FHIR Provider which serves the conformance statement for a RESTful server implementation
063 *
064 * <p>
065 * Note: This class is safe to extend, but it is important to note that the same instance of {@link CapabilityStatement} is always returned unless {@link #setCache(boolean)} is called with a value of
066 * <code>false</code>. This means that if you are adding anything to the returned conformance instance on each call you should call <code>setCache(false)</code> in your provider constructor.
067 * </p>
068 */
069public class ServerCapabilityStatementProvider implements IServerConformanceProvider<CapabilityStatement> {
070
071  private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(ServerCapabilityStatementProvider.class);
072  private boolean myCache = true;
073  private volatile CapabilityStatement myCapabilityStatement;
074  private IdentityHashMap<SearchMethodBinding, String> myNamedSearchMethodBindingToName;
075  private HashMap<String, List<SearchMethodBinding>> mySearchNameToBindings;
076  private IdentityHashMap<OperationMethodBinding, String> myOperationBindingToName;
077  private HashMap<String, List<OperationMethodBinding>> myOperationNameToBindings;
078  private String myPublisher = "Not provided";
079  private Callable<RestulfulServerConfiguration> myServerConfiguration;
080
081  /**
082   * No-arg constructor and setter so that the ServerConformanceProvider can be Spring-wired with the RestfulService avoiding the potential reference cycle that would happen.
083   */
084  public ServerCapabilityStatementProvider() {
085    super();
086  }
087
088  /**
089   * Constructor
090   */
091  public ServerCapabilityStatementProvider(RestfulServer theRestfulServer) {
092    this.myServerConfiguration = theRestfulServer::createConfiguration;
093  }
094
095  /**
096   * Constructor
097   */
098  public ServerCapabilityStatementProvider(RestulfulServerConfiguration theServerConfiguration) {
099    this.myServerConfiguration = () -> theServerConfiguration;
100  }
101
102  private void checkBindingForSystemOps(CapabilityStatementRestComponent rest, Set<SystemRestfulInteraction> systemOps, BaseMethodBinding<?> nextMethodBinding) {
103    if (nextMethodBinding.getRestOperationType() != null) {
104      String sysOpCode = nextMethodBinding.getRestOperationType().getCode();
105      if (sysOpCode != null) {
106        SystemRestfulInteraction sysOp;
107        try {
108          sysOp = SystemRestfulInteraction.fromCode(sysOpCode);
109        } catch (FHIRException e) {
110          return;
111        }
112        if (sysOp == null) {
113          return;
114        }
115        if (systemOps.contains(sysOp) == false) {
116          systemOps.add(sysOp);
117          rest.addInteraction().setCode(sysOp);
118        }
119      }
120    }
121  }
122
123  private Map<String, List<BaseMethodBinding<?>>> collectMethodBindings() {
124    Map<String, List<BaseMethodBinding<?>>> resourceToMethods = new TreeMap<String, List<BaseMethodBinding<?>>>();
125    for (ResourceBinding next : getServerConfiguration().getResourceBindings()) {
126      String resourceName = next.getResourceName();
127      for (BaseMethodBinding<?> nextMethodBinding : next.getMethodBindings()) {
128        if (resourceToMethods.containsKey(resourceName) == false) {
129          resourceToMethods.put(resourceName, new ArrayList<BaseMethodBinding<?>>());
130        }
131        resourceToMethods.get(resourceName).add(nextMethodBinding);
132      }
133    }
134    for (BaseMethodBinding<?> nextMethodBinding : getServerConfiguration().getServerBindings()) {
135      String resourceName = "";
136      if (resourceToMethods.containsKey(resourceName) == false) {
137        resourceToMethods.put(resourceName, new ArrayList<>());
138      }
139      resourceToMethods.get(resourceName).add(nextMethodBinding);
140    }
141    return resourceToMethods;
142  }
143
144  private DateTimeType conformanceDate() {
145    IPrimitiveType<Date> buildDate = getServerConfiguration().getConformanceDate();
146    if (buildDate != null && buildDate.getValue() != null) {
147      try {
148        return new DateTimeType(buildDate.getValueAsString());
149      } catch (DataFormatException e) {
150        // fall through
151      }
152    }
153    return DateTimeType.now();
154  }
155
156  private String createNamedQueryName(SearchMethodBinding searchMethodBinding) {
157      StringBuilder retVal = new StringBuilder();
158      if (searchMethodBinding.getResourceName() != null) {
159          retVal.append(searchMethodBinding.getResourceName());
160      }
161      retVal.append("-query-");
162      retVal.append(searchMethodBinding.getQueryName());
163      
164      return retVal.toString();
165  }
166  
167  private String createOperationName(OperationMethodBinding theMethodBinding) {
168    StringBuilder retVal = new StringBuilder();
169    if (theMethodBinding.getResourceName() != null) {
170      retVal.append(theMethodBinding.getResourceName());
171    }
172
173    retVal.append('-');
174    if (theMethodBinding.isCanOperateAtInstanceLevel()) {
175      retVal.append('i');
176    }
177    if (theMethodBinding.isCanOperateAtServerLevel()) {
178      retVal.append('s');
179    }
180    retVal.append('-');
181
182    // Exclude the leading $
183    retVal.append(theMethodBinding.getName(), 1, theMethodBinding.getName().length());
184
185    return retVal.toString();
186  }
187
188  /**
189   * Gets the value of the "publisher" that will be placed in the generated conformance statement. As this is a mandatory element, the value should not be null (although this is not enforced). The
190   * value defaults to "Not provided" but may be set to null, which will cause this element to be omitted.
191   */
192  public String getPublisher() {
193    return myPublisher;
194  }
195
196  /**
197   * Sets the value of the "publisher" that will be placed in the generated conformance statement. As this is a mandatory element, the value should not be null (although this is not enforced). The
198   * value defaults to "Not provided" but may be set to null, which will cause this element to be omitted.
199   */
200  public void setPublisher(String thePublisher) {
201    myPublisher = thePublisher;
202  }
203
204  RestulfulServerConfiguration getServerConfiguration() {
205    try {
206      return myServerConfiguration.call();
207    } catch (Exception e) {
208      throw new InternalErrorException(e);
209    }
210  }
211
212  @Override
213  @Metadata
214  public CapabilityStatement getServerConformance(HttpServletRequest theRequest) {
215    if (myCapabilityStatement != null && myCache) {
216      return myCapabilityStatement;
217    }
218
219    CapabilityStatement retVal = new CapabilityStatement();
220
221    retVal.setPublisher(myPublisher);
222    retVal.setDateElement(conformanceDate());
223    retVal.setFhirVersion(FhirVersionEnum.DSTU3.getFhirVersionString());
224    retVal.setAcceptUnknown(UnknownContentCode.EXTENSIONS); // TODO: make this configurable - this is a fairly big
225    // effort since the parser
226    // needs to be modified to actually allow it
227
228    ServletContext servletContext = (ServletContext) (theRequest == null ? null : theRequest.getAttribute(RestfulServer.SERVLET_CONTEXT_ATTRIBUTE));
229    String serverBase = getServerConfiguration().getServerAddressStrategy().determineServerBase(servletContext, theRequest);
230    retVal
231      .getImplementation()
232      .setUrl(serverBase)
233      .setDescription(getServerConfiguration().getImplementationDescription());
234
235    retVal.setKind(CapabilityStatementKind.INSTANCE);
236    retVal.getSoftware().setName(getServerConfiguration().getServerName());
237    retVal.getSoftware().setVersion(getServerConfiguration().getServerVersion());
238    retVal.addFormat(Constants.CT_FHIR_XML_NEW);
239    retVal.addFormat(Constants.CT_FHIR_JSON_NEW);
240    retVal.setStatus(PublicationStatus.ACTIVE);
241
242    CapabilityStatementRestComponent rest = retVal.addRest();
243    rest.setMode(RestfulCapabilityMode.SERVER);
244
245    Set<SystemRestfulInteraction> systemOps = new HashSet<>();
246    Set<String> operationNames = new HashSet<>();
247
248    Map<String, List<BaseMethodBinding<?>>> resourceToMethods = collectMethodBindings();
249    for (Entry<String, List<BaseMethodBinding<?>>> nextEntry : resourceToMethods.entrySet()) {
250
251      if (nextEntry.getKey().isEmpty() == false) {
252        Set<TypeRestfulInteraction> resourceOps = new HashSet<>();
253        CapabilityStatementRestResourceComponent resource = rest.addResource();
254        String resourceName = nextEntry.getKey();
255        RuntimeResourceDefinition def = getServerConfiguration().getFhirContext().getResourceDefinition(resourceName);
256        resource.getTypeElement().setValue(def.getName());
257        resource.getProfile().setReference((def.getResourceProfile(serverBase)));
258
259        TreeSet<String> includes = new TreeSet<>();
260
261        // Map<String, CapabilityStatement.RestResourceSearchParam> nameToSearchParam = new HashMap<String,
262        // CapabilityStatement.RestResourceSearchParam>();
263        for (BaseMethodBinding<?> nextMethodBinding : nextEntry.getValue()) {
264          if (nextMethodBinding.getRestOperationType() != null) {
265            String resOpCode = nextMethodBinding.getRestOperationType().getCode();
266            if (resOpCode != null) {
267              TypeRestfulInteraction resOp;
268              try {
269                resOp = TypeRestfulInteraction.fromCode(resOpCode);
270              } catch (Exception e) {
271                resOp = null;
272              }
273              if (resOp != null) {
274                if (resourceOps.contains(resOp) == false) {
275                  resourceOps.add(resOp);
276                  resource.addInteraction().setCode(resOp);
277                }
278                if ("vread".equals(resOpCode)) {
279                  // vread implies read
280                  resOp = TypeRestfulInteraction.READ;
281                  if (resourceOps.contains(resOp) == false) {
282                    resourceOps.add(resOp);
283                    resource.addInteraction().setCode(resOp);
284                  }
285                }
286
287                if (nextMethodBinding.isSupportsConditional()) {
288                  switch (resOp) {
289                    case CREATE:
290                      resource.setConditionalCreate(true);
291                      break;
292                    case DELETE:
293                      if (nextMethodBinding.isSupportsConditionalMultiple()) {
294                        resource.setConditionalDelete(ConditionalDeleteStatus.MULTIPLE);
295                      } else {
296                        resource.setConditionalDelete(ConditionalDeleteStatus.SINGLE);
297                      }
298                      break;
299                    case UPDATE:
300                      resource.setConditionalUpdate(true);
301                      break;
302                    default:
303                      break;
304                  }
305                }
306              }
307            }
308          }
309
310          checkBindingForSystemOps(rest, systemOps, nextMethodBinding);
311
312          if (nextMethodBinding instanceof SearchMethodBinding) {
313            SearchMethodBinding methodBinding = (SearchMethodBinding) nextMethodBinding;
314            if (methodBinding.getQueryName() != null) {
315                String queryName = myNamedSearchMethodBindingToName.get(methodBinding);
316                if (operationNames.add(queryName)) {
317                    rest.addOperation().setName(methodBinding.getQueryName()).setDefinition(new Reference("OperationDefinition/" + queryName));
318                }
319            } else {
320                handleNamelessSearchMethodBinding(rest, resource, resourceName, def, includes, (SearchMethodBinding) nextMethodBinding);
321            }
322          } else if (nextMethodBinding instanceof OperationMethodBinding) {
323            OperationMethodBinding methodBinding = (OperationMethodBinding) nextMethodBinding;
324            String opName = myOperationBindingToName.get(methodBinding);
325            if (operationNames.add(opName)) {
326              // Only add each operation (by name) once
327              rest.addOperation().setName(methodBinding.getName().substring(1)).setDefinition(new Reference("OperationDefinition/" + opName));
328            }
329          }
330
331          resource.getInteraction().sort(new Comparator<ResourceInteractionComponent>() {
332            @Override
333            public int compare(ResourceInteractionComponent theO1, ResourceInteractionComponent theO2) {
334              TypeRestfulInteraction o1 = theO1.getCode();
335              TypeRestfulInteraction o2 = theO2.getCode();
336              if (o1 == null && o2 == null) {
337                return 0;
338              }
339              if (o1 == null) {
340                return 1;
341              }
342              if (o2 == null) {
343                return -1;
344              }
345              return o1.ordinal() - o2.ordinal();
346            }
347          });
348
349        }
350
351        for (String nextInclude : includes) {
352          resource.addSearchInclude(nextInclude);
353        }
354      } else {
355        for (BaseMethodBinding<?> nextMethodBinding : nextEntry.getValue()) {
356          checkBindingForSystemOps(rest, systemOps, nextMethodBinding);
357          if (nextMethodBinding instanceof OperationMethodBinding) {
358            OperationMethodBinding methodBinding = (OperationMethodBinding) nextMethodBinding;
359            String opName = myOperationBindingToName.get(methodBinding);
360            if (operationNames.add(opName)) {
361              ourLog.debug("Found bound operation: {}", opName);
362              rest.addOperation().setName(methodBinding.getName().substring(1)).setDefinition(new Reference("OperationDefinition/" + opName));
363            }
364          }
365        }
366      }
367    }
368
369    myCapabilityStatement = retVal;
370    return retVal;
371  }
372
373  private void handleNamelessSearchMethodBinding(CapabilityStatementRestComponent rest, CapabilityStatementRestResourceComponent resource, String resourceName, RuntimeResourceDefinition def, TreeSet<String> includes,
374                                         SearchMethodBinding searchMethodBinding) {
375    includes.addAll(searchMethodBinding.getIncludes());
376
377    List<IParameter> params = searchMethodBinding.getParameters();
378    List<SearchParameter> searchParameters = new ArrayList<SearchParameter>();
379    for (IParameter nextParameter : params) {
380      if ((nextParameter instanceof SearchParameter)) {
381        searchParameters.add((SearchParameter) nextParameter);
382      }
383    }
384    sortSearchParameters(searchParameters);
385    if (!searchParameters.isEmpty()) {
386      // boolean allOptional = searchParameters.get(0).isRequired() == false;
387      //
388      // OperationDefinition query = null;
389      // if (!allOptional) {
390      // RestOperation operation = rest.addOperation();
391      // query = new OperationDefinition();
392      // operation.setDefinition(new ResourceReferenceDt(query));
393      // query.getDescriptionElement().setValue(searchMethodBinding.getDescription());
394      // query.addUndeclaredExtension(false, ExtensionConstants.QUERY_RETURN_TYPE, new CodeDt(resourceName));
395      // for (String nextInclude : searchMethodBinding.getIncludes()) {
396      // query.addUndeclaredExtension(false, ExtensionConstants.QUERY_ALLOWED_INCLUDE, new StringDt(nextInclude));
397      // }
398      // }
399
400      for (SearchParameter nextParameter : searchParameters) {
401
402        String nextParamName = nextParameter.getName();
403
404        String chain = null;
405        String nextParamUnchainedName = nextParamName;
406        if (nextParamName.contains(".")) {
407          chain = nextParamName.substring(nextParamName.indexOf('.') + 1);
408          nextParamUnchainedName = nextParamName.substring(0, nextParamName.indexOf('.'));
409        }
410
411        String nextParamDescription = nextParameter.getDescription();
412
413        /*
414         * If the parameter has no description, default to the one from the resource
415         */
416        if (StringUtils.isBlank(nextParamDescription)) {
417          RuntimeSearchParam paramDef = def.getSearchParam(nextParamUnchainedName);
418          if (paramDef != null) {
419            nextParamDescription = paramDef.getDescription();
420          }
421        }
422
423        CapabilityStatementRestResourceSearchParamComponent param = resource.addSearchParam();
424        param.setName(nextParamUnchainedName);
425
426//                              if (StringUtils.isNotBlank(chain)) {
427//                                      param.addChain(chain);
428//                              }
429//
430//                              if (nextParameter.getParamType() == RestSearchParameterTypeEnum.REFERENCE) {
431//                                      for (String nextWhitelist : new TreeSet<String>(nextParameter.getQualifierWhitelist())) {
432//                                              if (nextWhitelist.startsWith(".")) {
433//                                                      param.addChain(nextWhitelist.substring(1));
434//                                              }
435//                                      }
436//                              }
437
438        param.setDocumentation(nextParamDescription);
439        if (nextParameter.getParamType() != null) {
440          param.getTypeElement().setValueAsString(nextParameter.getParamType().getCode());
441        }
442        for (Class<? extends IBaseResource> nextTarget : nextParameter.getDeclaredTypes()) {
443          RuntimeResourceDefinition targetDef = getServerConfiguration().getFhirContext().getResourceDefinition(nextTarget);
444          if (targetDef != null) {
445            ResourceType code;
446            try {
447              code = ResourceType.fromCode(targetDef.getName());
448            } catch (FHIRException e) {
449              code = null;
450            }
451//                                              if (code != null) {
452//                                                      param.addTarget(targetDef.getName());
453//                                              }
454          }
455        }
456      }
457    }
458  }
459
460  @Initialize
461  public void initializeOperations() {
462    myNamedSearchMethodBindingToName = new IdentityHashMap<>();
463    mySearchNameToBindings = new HashMap<>();
464    myOperationBindingToName = new IdentityHashMap<>();
465    myOperationNameToBindings = new HashMap<>();
466
467    Map<String, List<BaseMethodBinding<?>>> resourceToMethods = collectMethodBindings();
468    for (Entry<String, List<BaseMethodBinding<?>>> nextEntry : resourceToMethods.entrySet()) {
469      List<BaseMethodBinding<?>> nextMethodBindings = nextEntry.getValue();
470      for (BaseMethodBinding<?> nextMethodBinding : nextMethodBindings) {
471        if (nextMethodBinding instanceof OperationMethodBinding) {
472          OperationMethodBinding methodBinding = (OperationMethodBinding) nextMethodBinding;
473          if (myOperationBindingToName.containsKey(methodBinding)) {
474            continue;
475          }
476
477          String name = createOperationName(methodBinding);
478          ourLog.debug("Detected operation: {}", name);
479
480          myOperationBindingToName.put(methodBinding, name);
481          if (myOperationNameToBindings.containsKey(name) == false) {
482            myOperationNameToBindings.put(name, new ArrayList<>());
483          }
484          myOperationNameToBindings.get(name).add(methodBinding);
485        } else if (nextMethodBinding instanceof SearchMethodBinding) {
486            SearchMethodBinding methodBinding = (SearchMethodBinding) nextMethodBinding;
487            if (myNamedSearchMethodBindingToName.containsKey(methodBinding)) {
488                continue;
489            }
490            
491            String name = createNamedQueryName(methodBinding);
492            ourLog.debug("Detected named query: {}", name);
493            
494            myNamedSearchMethodBindingToName.put(methodBinding, name);
495            if (!mySearchNameToBindings.containsKey(name)) {
496                mySearchNameToBindings.put(name, new ArrayList<>());
497            }
498            mySearchNameToBindings.get(name).add(methodBinding);
499        }
500      }
501    }
502  }
503  
504  @Read(type = OperationDefinition.class)
505  public OperationDefinition readOperationDefinition(@IdParam IdType theId) {
506    if (theId == null || theId.hasIdPart() == false) {
507      throw new ResourceNotFoundException(theId);
508    }
509    List<OperationMethodBinding> operationBindings = myOperationNameToBindings.get(theId.getIdPart());
510    if (operationBindings != null && !operationBindings.isEmpty()) {
511        return readOperationDefinitionForOperation(operationBindings);
512    }
513    List<SearchMethodBinding> searchBindings = mySearchNameToBindings.get(theId.getIdPart());
514    if (searchBindings != null && !searchBindings.isEmpty()) {
515        return readOperationDefinitionForNamedSearch(searchBindings);
516    }
517    throw new ResourceNotFoundException(theId);
518  }
519  
520  private OperationDefinition readOperationDefinitionForNamedSearch(List<SearchMethodBinding> bindings) {
521    OperationDefinition op = new OperationDefinition();
522    op.setStatus(PublicationStatus.ACTIVE);
523    op.setKind(OperationKind.QUERY);
524    op.setIdempotent(true);
525
526    op.setSystem(false);
527    op.setType(false);
528    op.setInstance(false);
529
530    Set<String> inParams = new HashSet<>();
531
532    for (SearchMethodBinding binding : bindings) {
533      if (isNotBlank(binding.getDescription())) {
534        op.setDescription(binding.getDescription());
535      }
536      if (isBlank(binding.getResourceProviderResourceName())) {
537        op.setSystem(true);
538      } else {
539        op.setType(true);
540        op.addResourceElement().setValue(binding.getResourceProviderResourceName());
541      }
542      op.setCode(binding.getQueryName());
543      for (IParameter nextParamUntyped : binding.getParameters()) {
544        if (nextParamUntyped instanceof SearchParameter) {
545          SearchParameter nextParam = (SearchParameter) nextParamUntyped;
546          if (!inParams.add(nextParam.getName())) {
547            continue;
548          }
549          OperationDefinitionParameterComponent param = op.addParameter();
550          param.setUse(OperationParameterUse.IN);
551          param.setType("string");
552          param.getSearchTypeElement().setValueAsString(nextParam.getParamType().getCode());
553          param.setMin(nextParam.isRequired() ? 1 : 0);
554          param.setMax("1");
555          param.setName(nextParam.getName());
556        }
557      }
558
559      if (isBlank(op.getName())) {
560        if (isNotBlank(op.getDescription())) {
561          op.setName(op.getDescription());
562        } else {
563          op.setName(op.getCode());
564        }
565      }
566    }
567
568    return op;
569  }
570  
571  private OperationDefinition readOperationDefinitionForOperation(List<OperationMethodBinding> bindings) {
572    OperationDefinition op = new OperationDefinition();
573    op.setStatus(PublicationStatus.ACTIVE);
574    op.setKind(OperationKind.OPERATION);
575    op.setIdempotent(true);
576
577    // We reset these to true below if we find a binding that can handle the level
578    op.setSystem(false);
579    op.setType(false);
580    op.setInstance(false);
581
582    Set<String> inParams = new HashSet<>();
583    Set<String> outParams = new HashSet<>();
584
585    for (OperationMethodBinding sharedDescription : bindings) {
586      if (isNotBlank(sharedDescription.getDescription())) {
587        op.setDescription(sharedDescription.getDescription());
588      }
589      if (sharedDescription.isCanOperateAtInstanceLevel()) {
590        op.setInstance(true);
591      }
592      if (sharedDescription.isCanOperateAtServerLevel()) {
593        op.setSystem(true);
594      }
595      if (sharedDescription.isCanOperateAtTypeLevel()) {
596        op.setType(true);
597      }
598      if (!sharedDescription.isIdempotent()) {
599        op.setIdempotent(sharedDescription.isIdempotent());
600      }
601      op.setCode(sharedDescription.getName().substring(1));
602      if (sharedDescription.isCanOperateAtInstanceLevel()) {
603        op.setInstance(sharedDescription.isCanOperateAtInstanceLevel());
604      }
605      if (sharedDescription.isCanOperateAtServerLevel()) {
606        op.setSystem(sharedDescription.isCanOperateAtServerLevel());
607      }
608      if (isNotBlank(sharedDescription.getResourceName())) {
609        op.addResourceElement().setValue(sharedDescription.getResourceName());
610      }
611
612      for (IParameter nextParamUntyped : sharedDescription.getParameters()) {
613        if (nextParamUntyped instanceof OperationParameter) {
614          OperationParameter nextParam = (OperationParameter) nextParamUntyped;
615          OperationDefinitionParameterComponent param = op.addParameter();
616          if (!inParams.add(nextParam.getName())) {
617            continue;
618          }
619          param.setUse(OperationParameterUse.IN);
620          if (nextParam.getParamType() != null) {
621            param.setType(nextParam.getParamType());
622          }
623          if (nextParam.getSearchParamType() != null) {
624            param.getSearchTypeElement().setValueAsString(nextParam.getSearchParamType());
625          }
626          param.setMin(nextParam.getMin());
627          param.setMax(nextParam.getMax() == -1 ? "*" : Integer.toString(nextParam.getMax()));
628          param.setName(nextParam.getName());
629        }
630      }
631
632      for (ReturnType nextParam : sharedDescription.getReturnParams()) {
633        if (!outParams.add(nextParam.getName())) {
634          continue;
635        }
636        OperationDefinitionParameterComponent param = op.addParameter();
637        param.setUse(OperationParameterUse.OUT);
638        if (nextParam.getType() != null) {
639          param.setType(nextParam.getType());
640        }
641        param.setMin(nextParam.getMin());
642        param.setMax(nextParam.getMax() == -1 ? "*" : Integer.toString(nextParam.getMax()));
643        param.setName(nextParam.getName());
644      }
645    }
646
647    if (isBlank(op.getName())) {
648      if (isNotBlank(op.getDescription())) {
649        op.setName(op.getDescription());
650      } else {
651        op.setName(op.getCode());
652      }
653    }
654
655    if (op.hasSystem() == false) {
656      op.setSystem(false);
657    }
658    if (op.hasInstance() == false) {
659      op.setInstance(false);
660    }
661
662    return op;
663  }
664
665  /**
666   * Sets the cache property (default is true). If set to true, the same response will be returned for each invocation.
667   * <p>
668   * See the class documentation for an important note if you are extending this class
669   * </p>
670   */
671  public ServerCapabilityStatementProvider setCache(boolean theCache) {
672    myCache = theCache;
673    return this;
674  }
675
676  @Override
677  public void setRestfulServer(RestfulServer theRestfulServer) {
678    myServerConfiguration = theRestfulServer::createConfiguration;
679  }
680
681  private void sortRuntimeSearchParameters(List<RuntimeSearchParam> searchParameters) {
682    Collections.sort(searchParameters, new Comparator<RuntimeSearchParam>() {
683      @Override
684      public int compare(RuntimeSearchParam theO1, RuntimeSearchParam theO2) {
685        return theO1.getName().compareTo(theO2.getName());
686      }
687    });
688  }
689
690  private void sortSearchParameters(List<SearchParameter> searchParameters) {
691    Collections.sort(searchParameters, new Comparator<SearchParameter>() {
692      @Override
693      public int compare(SearchParameter theO1, SearchParameter theO2) {
694        if (theO1.isRequired() == theO2.isRequired()) {
695          return theO1.getName().compareTo(theO2.getName());
696        }
697        if (theO1.isRequired()) {
698          return -1;
699        }
700        return 1;
701      }
702    });
703  }
704}