001package org.hl7.fhir.r5.utils;
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
024import org.hl7.fhir.exceptions.FHIRException;
025import org.hl7.fhir.instance.model.api.IBaseResource;
026import org.hl7.fhir.r5.context.IWorkerContext;
027import org.hl7.fhir.r5.model.*;
028import org.hl7.fhir.r5.model.Bundle.BundleEntryComponent;
029import org.hl7.fhir.r5.model.Bundle.BundleLinkComponent;
030import org.hl7.fhir.utilities.Utilities;
031import org.hl7.fhir.utilities.graphql.*;
032import org.hl7.fhir.utilities.graphql.Argument.ArgumentListStatus;
033import org.hl7.fhir.utilities.graphql.Package;
034import org.hl7.fhir.utilities.graphql.Operation.OperationType;
035
036import java.io.UnsupportedEncodingException;
037import java.net.URLDecoder;
038import java.util.ArrayList;
039import java.util.HashMap;
040import java.util.List;
041import java.util.Map;
042
043import static org.hl7.fhir.utilities.graphql.IGraphQLStorageServices.ReferenceResolution;
044
045public class GraphQLEngine implements IGraphQLEngine {
046  
047  public static class SearchEdge extends Base {
048
049    private BundleEntryComponent be;
050    private String type;
051    
052    SearchEdge(String type, BundleEntryComponent be) {
053      this.type = type;
054      this.be = be;
055    }
056    @Override
057    public String fhirType() {
058      return type;
059    }
060
061    @Override
062    protected void listChildren(List<Property> result) {
063      throw new Error("Not Implemented");
064    }
065
066    @Override
067    public String getIdBase() {
068      throw new Error("Not Implemented");
069    }
070
071    @Override
072    public void setIdBase(String value) {
073      throw new Error("Not Implemented");
074    }
075
076    @Override
077    public Property getNamedProperty(int _hash, String _name, boolean _checkValid) throws FHIRException {
078      switch (_hash) {
079      case 3357091:    /*mode*/     return new Property(_name, "string",   "n/a", 0, 1, be.getSearch().hasMode() ? be.getSearch().getModeElement() : null);
080      case 109264530:  /*score*/    return new Property(_name, "string",   "n/a", 0, 1, be.getSearch().hasScore() ? be.getSearch().getScoreElement() : null);
081      case -341064690: /*resource*/ return new Property(_name, "resource",  "n/a", 0, 1, be.hasResource() ? be.getResource() : null);
082      default: return super.getNamedProperty(_hash, _name, _checkValid);
083      }
084    }
085  }
086
087  public static class SearchWrapper extends Base {
088
089    private Bundle bnd;
090    private String type;
091    private Map<String, String> map;
092
093    SearchWrapper(String type, Bundle bnd) throws FHIRException {
094      this.type = type;
095      this.bnd = bnd;
096      for (BundleLinkComponent bl : bnd.getLink()) 
097        if (bl.getRelation().equals("self"))
098          map = parseURL(bl.getUrl());
099    }
100
101    @Override
102    public String fhirType() {
103      return type;
104    }
105
106    @Override
107    protected void listChildren(List<Property> result) {
108      throw new Error("Not Implemented");
109    }
110
111    @Override
112    public String getIdBase() {
113      throw new Error("Not Implemented");
114    }
115
116    @Override
117    public void setIdBase(String value) {
118      throw new Error("Not Implemented");
119    }
120
121    @Override
122    public Property getNamedProperty(int _hash, String _name, boolean _checkValid) throws FHIRException {
123      switch (_hash) {
124      case 97440432:   /*first*/     return new Property(_name, "string",  "n/a", 0, 1, extractLink(_name));
125      case -1273775369: /*previous*/  return new Property(_name, "string",  "n/a", 0, 1, extractLink(_name));
126      case 3377907:    /*next*/      return new Property(_name, "string",  "n/a", 0, 1, extractLink(_name));
127      case 3314326:    /*last*/      return new Property(_name, "string",  "n/a", 0, 1, extractLink(_name));
128      case 94851343:   /*count*/     return new Property(_name, "integer", "n/a", 0, 1, bnd.getTotalElement());
129      case -1019779949:/*offset*/    return new Property(_name, "integer", "n/a", 0, 1, extractParam("search-offset"));
130      case 860381968:  /*pagesize*/  return new Property(_name, "integer", "n/a", 0, 1, extractParam("_count"));
131      case 96356950:  /*edges*/      return new Property(_name, "edge",    "n/a", 0, Integer.MAX_VALUE, getEdges());
132      default: return super.getNamedProperty(_hash, _name, _checkValid);
133      }
134    }
135
136    private List<Base> getEdges() {
137      List<Base> list = new ArrayList<>();
138      for (BundleEntryComponent be : bnd.getEntry())
139        list.add(new SearchEdge(type.substring(0, type.length() - 10) + "Edge", be));
140      return list;
141    }
142
143    private Base extractParam(String name) throws FHIRException {
144      return map != null ? new IntegerType(map.get(name)) : null;
145    }
146
147    private Map<String, String> parseURL(String url) throws FHIRException {
148      try {
149        Map<String, String> map = new HashMap<String, String>();
150        String[] pairs = url.split("&");
151        for (String pair : pairs) {
152          int idx = pair.indexOf("=");
153          String key;
154          key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair;
155          String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : null;
156          map.put(key, value);
157        }
158        return map;
159      } catch (UnsupportedEncodingException e) {
160        throw new FHIRException(e);
161      }
162    }
163
164    private Base extractLink(String _name) throws FHIRException {
165      for (BundleLinkComponent bl : bnd.getLink()) {
166        if (bl.getRelation().equals(_name)) {
167          Map<String, String> map = parseURL(bl.getUrl());
168          return new StringType(map.get("search-id")+':'+map.get("search-offset"));
169        }
170      }
171      return null;
172    }
173
174  }
175  
176  private IWorkerContext context;
177  
178  public GraphQLEngine(IWorkerContext context) {
179    super();
180    this.context = context;
181  }
182
183  /**
184   *  for the host to pass context into and get back on the reference resolution interface
185   */
186  private Object appInfo;
187
188  /**
189   *  the focus resource - if (there instanceof one. if (there isn"t,) there instanceof no focus
190   */
191  private Resource focus;
192
193  /**
194   * The package that describes the graphQL to be executed, operation name, and variables
195   */
196  private Package graphQL;
197
198  /**
199   * where the output from executing the query instanceof going to go
200   */
201  private GraphQLResponse output;
202
203  /** 
204   * Application provided reference resolution services 
205   */
206  private IGraphQLStorageServices services;
207
208  // internal stuff 
209  private Map<String, Argument> workingVariables = new HashMap<String, Argument>();
210
211  private FHIRPathEngine fpe;
212
213  private ExpressionNode magicExpression;
214
215  @Override
216  public void execute() throws EGraphEngine, EGraphQLException, FHIRException {
217    if (graphQL == null)
218      throw new EGraphEngine("Unable to process graphql - graphql document missing");
219    fpe = new FHIRPathEngine(this.context);
220    magicExpression = new ExpressionNode(0);
221
222    output = new GraphQLResponse();
223
224    Operation op = null;
225    // todo: initial conditions
226    if (!Utilities.noString(graphQL.getOperationName())) {
227      op = graphQL.getDocument().operation(graphQL.getOperationName());
228      if (op == null)
229        throw new EGraphEngine("Unable to find operation \""+graphQL.getOperationName()+"\"");
230    } else if ((graphQL.getDocument().getOperations().size() == 1))
231      op = graphQL.getDocument().getOperations().get(0);
232    else
233      throw new EGraphQLException("No operation name provided, so expected to find a single operation");
234
235    if (op.getOperationType() == OperationType.qglotMutation)
236      throw new EGraphQLException("Mutation operations are not supported (yet)");
237
238    checkNoDirectives(op.getDirectives());
239    processVariables(op);
240    if (focus == null)
241      processSearch(output, op.getSelectionSet(), false, "");
242    else
243      processObject(focus, focus, output, op.getSelectionSet(), false, "");
244  }
245
246  private boolean checkBooleanDirective(Directive dir) throws EGraphQLException {
247    if (dir.getArguments().size() != 1)
248      throw new EGraphQLException("Unable to process @"+dir.getName()+": expected a single argument \"if\"");
249    if (!dir.getArguments().get(0).getName().equals("if"))
250      throw new EGraphQLException("Unable to process @"+dir.getName()+": expected a single argument \"if\"");
251    List<Value> vl = resolveValues(dir.getArguments().get(0), 1);
252    return vl.get(0).toString().equals("true");
253  }
254
255  private boolean checkDirectives(List<Directive> directives) throws EGraphQLException {
256    Directive skip = null;
257    Directive include = null;
258    for (Directive dir : directives) {
259      if (dir.getName().equals("skip")) {
260        if ((skip == null))
261          skip = dir;
262        else
263          throw new EGraphQLException("Duplicate @skip directives");
264      } else if (dir.getName().equals("include")) {
265        if ((include == null))
266          include = dir;
267        else
268          throw new EGraphQLException("Duplicate @include directives");
269      }
270      else if (!Utilities.existsInList(dir.getName(), "flatten", "first", "singleton", "slice"))
271        throw new EGraphQLException("Directive \""+dir.getName()+"\" instanceof not recognised");
272    }
273    if ((skip != null && include != null))
274      throw new EGraphQLException("Cannot mix @skip and @include directives");
275    if (skip != null)
276      return !checkBooleanDirective(skip);
277    else if (include != null)
278      return checkBooleanDirective(include);
279    else
280      return true;
281  }
282
283  private void checkNoDirectives(List<Directive> directives) {
284
285  }
286
287  private boolean targetTypeOk(List<Argument> arguments, IBaseResource dest) throws EGraphQLException {
288    List<String> list = new ArrayList<String>();
289    for (Argument arg : arguments) {
290      if ((arg.getName().equals("type"))) {
291        List<Value> vl = resolveValues(arg);
292        for (Value v : vl)
293          list.add(v.toString());
294      }
295    }
296    if (list.size() == 0)
297      return true;
298    else
299      return list.indexOf(dest.fhirType()) > -1;
300  }
301
302  private boolean hasExtensions(Base obj) {
303    if (obj instanceof BackboneElement)
304      return ((BackboneElement) obj).getExtension().size() > 0 || ((BackboneElement) obj).getModifierExtension().size() > 0;
305      else if (obj instanceof DomainResource)
306        return ((DomainResource)obj).getExtension().size() > 0 || ((DomainResource)obj).getModifierExtension().size() > 0;
307        else if (obj instanceof Element)
308          return ((Element)obj).getExtension().size() > 0;
309          else
310            return false;
311  }
312
313  private boolean passesExtensionMode(Base obj, boolean extensionMode) {
314    if (!obj.isPrimitive())
315      return !extensionMode;
316    else if (extensionMode)
317      return !Utilities.noString(obj.getIdBase()) || hasExtensions(obj);
318    else
319      return obj.primitiveValue() != "";
320  }
321
322  private List<Base> filter(Resource context, Property prop, List<Argument> arguments, List<Base> values, boolean extensionMode) throws FHIRException, EGraphQLException {
323    List<Base> result = new ArrayList<Base>();
324    if (values.size() > 0) {
325      int count = Integer.MAX_VALUE;
326      int offset = 0;
327      StringBuilder fp = new StringBuilder();
328      for (Argument arg : arguments) {
329        List<Value> vl = resolveValues(arg);
330        if ((vl.size() != 1))
331          throw new EGraphQLException("Incorrect number of arguments");
332        if (values.get(0).isPrimitive())
333          throw new EGraphQLException("Attempt to use a filter ("+arg.getName()+") on a primtive type ("+prop.getTypeCode()+")");
334        if ((arg.getName().equals("fhirpath")))
335          fp.append(" and "+vl.get(0).toString());
336        else if ((arg.getName().equals("_count")))
337          count = Integer.valueOf(vl.get(0).toString());
338        else if ((arg.getName().equals("_offset")))
339          offset = Integer.valueOf(vl.get(0).toString());
340        else {
341          Property p = values.get(0).getNamedProperty(arg.getName());
342          if (p == null)
343            throw new EGraphQLException("Attempt to use an unknown filter ("+arg.getName()+") on a type ("+prop.getTypeCode()+")");
344          fp.append(" and "+arg.getName()+" = '"+vl.get(0).toString()+"'");
345        }
346      }
347      int i = 0;
348      int t = 0;
349      if (fp.length() == 0)
350        for (Base v : values) {
351          if ((i >= offset) && passesExtensionMode(v, extensionMode)) {
352            result.add(v);
353            t++;
354            if (t >= count)
355              break;
356          }
357          i++;
358        } else {
359          ExpressionNode node = fpe.parse(fp.toString().substring(5));
360          for (Base v : values) {
361            if ((i >= offset) && passesExtensionMode(v, extensionMode) && fpe.evaluateToBoolean(null, context, v, node)) {
362              result.add(v);
363              t++;
364              if (t >= count)
365                break;
366            }
367            i++;
368          }
369        }
370    }
371    return result;
372  }
373
374  private List<Resource> filterResources(Argument fhirpath, Bundle bnd) throws EGraphQLException, FHIRException {
375    List<Resource> result = new ArrayList<Resource>();
376    if (bnd.getEntry().size() > 0) {
377      if ((fhirpath == null))
378        for (BundleEntryComponent be : bnd.getEntry())
379          result.add(be.getResource());
380      else {
381        FHIRPathEngine fpe = new FHIRPathEngine(context);
382        ExpressionNode node = fpe.parse(getSingleValue(fhirpath));
383        for (BundleEntryComponent be : bnd.getEntry())
384          if (fpe.evaluateToBoolean(null, be.getResource(), be.getResource(), node))
385            result.add(be.getResource());
386      }
387    }
388    return result;
389  }
390
391  private List<Resource> filterResources(Argument fhirpath, List<IBaseResource> list) throws EGraphQLException, FHIRException {
392    List<Resource> result = new ArrayList<Resource>();
393    if (list.size() > 0) {
394      if ((fhirpath == null))
395        for (IBaseResource v : list)
396          result.add((Resource) v);
397      else {
398        FHIRPathEngine fpe = new FHIRPathEngine(context);
399        ExpressionNode node = fpe.parse(getSingleValue(fhirpath));
400        for (IBaseResource v : list)
401          if (fpe.evaluateToBoolean(null, (Resource)v, (Base) v, node))
402            result.add((Resource) v);
403      }
404    }
405    return result;
406  }
407
408  private boolean hasArgument(List<Argument> arguments, String name, String value) {
409    for (Argument arg : arguments)
410      if ((arg.getName().equals(name)) && arg.hasValue(value))
411        return true;
412    return false;
413  }
414
415  private void processValues(Resource context, Selection sel, Property prop, ObjectValue target, List<Base> values, boolean extensionMode, boolean inheritedList, String suffix) throws EGraphQLException, FHIRException {
416    boolean il = false;
417    Argument arg = null;
418    ExpressionNode expression = null;
419    if (sel.getField().hasDirective("slice")) {
420      Directive dir = sel.getField().directive("slice");
421      String s = ((StringValue) dir.getArguments().get(0).getValues().get(0)).getValue();
422      if (s.equals("$index"))
423        expression = magicExpression;
424      else
425        expression = fpe.parse(s);
426    }
427    if (sel.getField().hasDirective("flatten")) // special: instruction to drop this node...
428      il = prop.isList() && !sel.getField().hasDirective("first");
429    else if (sel.getField().hasDirective("first")) {
430      if (expression != null) 
431        throw new FHIRException("You cannot mix @slice and @first");
432      arg = target.addField(sel.getField().getAlias()+suffix, listStatus(sel.getField(), inheritedList));
433    } else if (expression == null)
434      arg = target.addField(sel.getField().getAlias()+suffix, listStatus(sel.getField(), prop.isList() || inheritedList));
435
436    
437    int index = 0;
438    for (Base value : values) {
439      String ss = "";
440      if (expression != null) {
441        if (expression == magicExpression)
442          ss = suffix+'.'+Integer.toString(index);
443        else
444          ss = suffix+'.'+fpe.evaluateToString(null, null, null, value, expression);
445        if (!sel.getField().hasDirective("flatten"))
446          arg = target.addField(sel.getField().getAlias()+suffix, listStatus(sel.getField(), prop.isList() || inheritedList));
447      }
448
449      if (value.isPrimitive() && !extensionMode) {
450        if (!sel.getField().getSelectionSet().isEmpty())
451          throw new EGraphQLException("Encountered a selection set on a scalar field type");
452        processPrimitive(arg, value);
453      } else {
454        if (sel.getField().getSelectionSet().isEmpty())
455          throw new EGraphQLException("No Fields selected on a complex object");
456        if (arg == null)
457          processObject(context, value, target, sel.getField().getSelectionSet(), il, ss);
458        else {
459          ObjectValue n = new ObjectValue();
460          arg.addValue(n);
461          processObject(context, value, n, sel.getField().getSelectionSet(), il, ss);
462        }
463      }
464      if (sel.getField().hasDirective("first"))
465        return;
466      index++;
467    }
468  }
469
470  private void processVariables(Operation op) throws EGraphQLException {
471    for (Variable varRef : op.getVariables()) {
472      Argument varDef = null;
473      for (Argument v : graphQL.getVariables()) 
474        if (v.getName().equals(varRef.getName()))
475          varDef = v;
476      if (varDef != null)
477        workingVariables.put(varRef.getName(), varDef); // todo: check type?
478      else if (varRef.getDefaultValue() != null)
479        workingVariables.put(varRef.getName(), new Argument(varRef.getName(), varRef.getDefaultValue()));
480      else
481        throw new EGraphQLException("No value found for variable ");
482    }
483  }
484
485  private boolean isPrimitive(String typename) {
486    return Utilities.existsInList(typename, "boolean", "integer", "string", "decimal", "uri", "base64Binary", "instant", "date", "dateTime", "time", "code", "oid", "id", "markdown", "unsignedInt", "positiveInt", "url", "canonical");
487  }
488
489  private boolean isResourceName(String name, String suffix) {
490    if (!name.endsWith(suffix))
491      return false;
492    name = name.substring(0, name.length()-suffix.length());
493    return context.getResourceNamesAsSet().contains(name);
494  }
495
496  private void processObject(Resource context, Base source, ObjectValue target, List<Selection> selection, boolean inheritedList, String suffix) throws EGraphQLException, FHIRException {
497    for (Selection sel : selection) {
498      if (sel.getField() != null) {
499        if (checkDirectives(sel.getField().getDirectives())) {
500          Property prop = source.getNamedProperty(sel.getField().getName());
501          if ((prop == null) && sel.getField().getName().startsWith("_"))
502            prop = source.getNamedProperty(sel.getField().getName().substring(1));
503          if (prop == null) {
504            if ((sel.getField().getName().equals("resourceType") && source instanceof Resource))
505              target.addField("resourceType", listStatus(sel.getField(), false)).addValue(new StringValue(source.fhirType()));
506            else if ((sel.getField().getName().equals("resource") && source.fhirType().equals("Reference")))
507              processReference(context, source, sel.getField(), target, inheritedList, suffix);
508            else if ((sel.getField().getName().equals("resource") && source.fhirType().equals("canonical")))
509              processCanonicalReference(context, source, sel.getField(), target, inheritedList, suffix);
510            else if (isResourceName(sel.getField().getName(), "List") && (source instanceof Resource))
511              processReverseReferenceList((Resource) source, sel.getField(), target, inheritedList, suffix);
512            else if (isResourceName(sel.getField().getName(), "Connection") && (source instanceof Resource))
513              processReverseReferenceSearch((Resource) source, sel.getField(), target, inheritedList, suffix);
514            else
515              throw new EGraphQLException("Unknown property "+sel.getField().getName()+" on "+source.fhirType());
516          } else {
517            if (!isPrimitive(prop.getTypeCode()) && sel.getField().getName().startsWith("_"))
518              throw new EGraphQLException("Unknown property "+sel.getField().getName()+" on "+source.fhirType());
519
520            List<Base> vl = filter(context, prop, sel.getField().getArguments(), prop.getValues(), sel.getField().getName().startsWith("_"));
521            if (!vl.isEmpty())
522              processValues(context, sel, prop, target, vl, sel.getField().getName().startsWith("_"), inheritedList, suffix);
523          }
524        }
525      } else if (sel.getInlineFragment() != null) {
526        if (checkDirectives(sel.getInlineFragment().getDirectives())) {
527          if (Utilities.noString(sel.getInlineFragment().getTypeCondition()))
528            throw new EGraphQLException("Not done yet - inline fragment with no type condition"); // cause why? why instanceof it even valid?
529          if (source.fhirType().equals(sel.getInlineFragment().getTypeCondition())) 
530            processObject(context, source, target, sel.getInlineFragment().getSelectionSet(), inheritedList, suffix);
531        }
532      } else if (checkDirectives(sel.getFragmentSpread().getDirectives())) {
533        Fragment fragment = graphQL.getDocument().fragment(sel.getFragmentSpread().getName());
534        if (fragment == null)
535          throw new EGraphQLException("Unable to resolve fragment "+sel.getFragmentSpread().getName());
536
537        if (Utilities.noString(fragment.getTypeCondition()))
538          throw new EGraphQLException("Not done yet - inline fragment with no type condition"); // cause why? why instanceof it even valid?
539        if (source.fhirType().equals(fragment.getTypeCondition()))
540          processObject(context, source, target, fragment.getSelectionSet(), inheritedList, suffix);
541      }
542    }
543  }
544
545  private void processPrimitive(Argument arg, Base value) {
546    String s = value.fhirType();
547    if (s.equals("integer") || s.equals("decimal") || s.equals("unsignedInt") || s.equals("positiveInt"))
548      arg.addValue(new NumberValue(value.primitiveValue()));
549    else if (s.equals("boolean"))
550      arg.addValue(new NameValue(value.primitiveValue()));
551    else
552      arg.addValue(new StringValue(value.primitiveValue()));
553  }
554
555  private void processReference(Resource context, Base source, Field field, ObjectValue target, boolean inheritedList, String suffix) throws EGraphQLException, FHIRException {
556    if (!(source instanceof Reference))
557      throw new EGraphQLException("Not done yet");
558    if (services == null)
559      throw new EGraphQLException("Resource Referencing services not provided");
560
561    Reference ref = (Reference) source;
562    ReferenceResolution res = services.lookup(appInfo, context, ref);
563    if (res != null) {
564      if (targetTypeOk(field.getArguments(), res.getTarget())) {
565        Argument arg = target.addField(field.getAlias() + suffix, listStatus(field, inheritedList));
566        ObjectValue obj = new ObjectValue();
567        arg.addValue(obj);
568        processObject((Resource)res.getTargetContext(), (Base) res.getTarget(), obj, field.getSelectionSet(), inheritedList, suffix);
569      }
570    }
571    else if (!hasArgument(field.getArguments(), "optional", "true"))
572      throw new EGraphQLException("Unable to resolve reference to "+ref.getReference());
573  }
574
575  private void processCanonicalReference(Resource context, Base source, Field field, ObjectValue target, boolean inheritedList, String suffix) throws EGraphQLException, FHIRException {
576    if (!(source instanceof CanonicalType))
577      throw new EGraphQLException("Not done yet");
578    if (services == null)
579      throw new EGraphQLException("Resource Referencing services not provided");
580
581    Reference ref = new Reference(source.primitiveValue());
582    ReferenceResolution res = services.lookup(appInfo, context, ref);
583    if (res != null) {
584      if (targetTypeOk(field.getArguments(), res.getTarget())) {
585        Argument arg = target.addField(field.getAlias() + suffix, listStatus(field, inheritedList));
586        ObjectValue obj = new ObjectValue();
587        arg.addValue(obj);
588        processObject((Resource)res.getTargetContext(), (Base) res.getTarget(), obj, field.getSelectionSet(), inheritedList, suffix);
589      }
590    }
591    else if (!hasArgument(field.getArguments(), "optional", "true"))
592      throw new EGraphQLException("Unable to resolve reference to "+ref.getReference());
593  }
594
595  private ArgumentListStatus listStatus(Field field, boolean isList) {
596    if (field.hasDirective("singleton"))
597      return ArgumentListStatus.SINGLETON;
598    else if (isList)
599      return ArgumentListStatus.REPEATING;
600    else
601      return ArgumentListStatus.NOT_SPECIFIED;
602  }
603
604  private void processReverseReferenceList(Resource source, Field field, ObjectValue target, boolean inheritedList, String suffix) throws EGraphQLException, FHIRException {
605    if (services == null)
606      throw new EGraphQLException("Resource Referencing services not provided");
607    List<IBaseResource> list = new ArrayList<>();
608    List<Argument> params = new ArrayList<>();
609    Argument parg = null;
610    for (Argument a : field.getArguments())
611      if (!(a.getName().equals("_reference")))
612        params.add(a);
613      else if ((parg == null))
614        parg = a;
615      else
616        throw new EGraphQLException("Duplicate parameter _reference");
617    if (parg == null)
618      throw new EGraphQLException("Missing parameter _reference");
619    Argument arg = new Argument();
620    params.add(arg);
621    arg.setName(getSingleValue(parg));
622    arg.addValue(new StringValue(source.fhirType()+"/"+source.getId()));
623    services.listResources(appInfo, field.getName().substring(0, field.getName().length() - 4), params, list);
624    arg = null;
625    ObjectValue obj = null;
626
627    List<Resource> vl = filterResources(field.argument("fhirpath"), list);
628    if (!vl.isEmpty()) {
629      arg = target.addField(field.getAlias()+suffix, listStatus(field, true));
630      for (Resource v : vl) {
631        obj = new ObjectValue();
632        arg.addValue(obj);
633        processObject(v, v, obj, field.getSelectionSet(), inheritedList, suffix);
634      }
635    }
636  }
637  
638  private void processReverseReferenceSearch(Resource source, Field field, ObjectValue target, boolean inheritedList, String suffix) throws EGraphQLException, FHIRException {
639    if (services == null)
640      throw new EGraphQLException("Resource Referencing services not provided");
641    List<Argument> params = new ArrayList<Argument>();
642    Argument parg = null;
643    for (Argument a : field.getArguments())
644      if (!(a.getName().equals("_reference")))
645        params.add(a);
646      else if ((parg == null))
647        parg = a;
648      else
649        throw new EGraphQLException("Duplicate parameter _reference");
650    if (parg == null)
651      throw new EGraphQLException("Missing parameter _reference");
652    Argument arg = new Argument();
653    params.add(arg);
654    arg.setName(getSingleValue(parg));
655    arg.addValue(new StringValue(source.fhirType()+"/"+source.getId()));
656    Bundle bnd = (Bundle) services.search(appInfo, field.getName().substring(0, field.getName().length()-10), params);
657    Base bndWrapper = new SearchWrapper(field.getName(), bnd);
658    arg = target.addField(field.getAlias()+suffix, listStatus(field, false));
659    ObjectValue obj = new ObjectValue();
660    arg.addValue(obj);
661    processObject(null, bndWrapper, obj, field.getSelectionSet(), inheritedList, suffix);
662  }
663
664  private void processSearch(ObjectValue target, List<Selection> selection, boolean inheritedList, String suffix) throws EGraphQLException, FHIRException {
665    for (Selection sel : selection) {
666      if ((sel.getField() == null))
667        throw new EGraphQLException("Only field selections are allowed in this context");
668      checkNoDirectives(sel.getField().getDirectives());
669
670      if ((isResourceName(sel.getField().getName(), "")))
671        processSearchSingle(target, sel.getField(), inheritedList, suffix);
672      else if ((isResourceName(sel.getField().getName(), "List")))
673        processSearchSimple(target, sel.getField(), inheritedList, suffix);
674      else if ((isResourceName(sel.getField().getName(), "Connection")))
675        processSearchFull(target, sel.getField(), inheritedList, suffix);
676    }
677  }
678
679  private void processSearchSingle(ObjectValue target, Field field, boolean inheritedList, String suffix) throws EGraphQLException, FHIRException {
680    if (services == null)
681      throw new EGraphQLException("Resource Referencing services not provided");
682    String id = "";
683    for (Argument arg : field.getArguments())
684      if ((arg.getName().equals("id")))
685        id = getSingleValue(arg);
686      else
687        throw new EGraphQLException("Unknown/invalid parameter "+arg.getName());
688    if (Utilities.noString(id))
689      throw new EGraphQLException("No id found");
690    Resource res = (Resource) services.lookup(appInfo, field.getName(), id);
691    if (res == null)
692      throw new EGraphQLException("Resource "+field.getName()+"/"+id+" not found");
693    Argument arg = target.addField(field.getAlias()+suffix, listStatus(field, false));
694    ObjectValue obj = new ObjectValue();
695    arg.addValue(obj);
696    processObject(res, res, obj, field.getSelectionSet(), inheritedList, suffix);
697  }
698
699  private void processSearchSimple(ObjectValue target, Field field, boolean inheritedList, String suffix) throws EGraphQLException, FHIRException {
700    if (services == null)
701      throw new EGraphQLException("Resource Referencing services not provided");
702    List<IBaseResource> list = new ArrayList<>();
703    services.listResources(appInfo, field.getName().substring(0, field.getName().length() - 4), field.getArguments(), list);
704    Argument arg = null;
705    ObjectValue obj = null;
706
707    List<Resource> vl = filterResources(field.argument("fhirpath"), list);
708    if (!vl.isEmpty()) {
709      arg = target.addField(field.getAlias()+suffix, listStatus(field, true));
710      for (Resource v : vl) {
711        obj = new ObjectValue();
712        arg.addValue(obj);
713        processObject(v, v, obj, field.getSelectionSet(), inheritedList, suffix);
714      }
715    }
716  }
717  
718  private void processSearchFull(ObjectValue target, Field field, boolean inheritedList, String suffix) throws EGraphQLException, FHIRException {
719    if (services == null)
720      throw new EGraphQLException("Resource Referencing services not provided");
721    List<Argument> params = new ArrayList<Argument>();
722    Argument carg = null;
723    for ( Argument arg : field.getArguments())
724      if (arg.getName().equals("cursor"))
725        carg = arg;
726      else
727        params.add(arg);
728    if ((carg != null)) {
729      params.clear();;
730      String[] parts = getSingleValue(carg).split(":");
731      params.add(new Argument("search-id", new StringValue(parts[0])));
732      params.add(new Argument("search-offset", new StringValue(parts[1])));
733    }
734
735    Bundle bnd = (Bundle) services.search(appInfo, field.getName().substring(0, field.getName().length()-10), params);
736    SearchWrapper bndWrapper = new SearchWrapper(field.getName(), bnd);
737    Argument arg = target.addField(field.getAlias()+suffix, listStatus(field, false));
738    ObjectValue obj = new ObjectValue();
739    arg.addValue(obj);
740    processObject(null, bndWrapper, obj, field.getSelectionSet(), inheritedList, suffix);
741  }
742
743  private String getSingleValue(Argument arg) throws EGraphQLException {
744    List<Value> vl = resolveValues(arg, 1);
745    if (vl.size() == 0)
746      return "";
747    return vl.get(0).toString();
748  }
749
750  private List<Value> resolveValues(Argument arg) throws EGraphQLException {
751    return resolveValues(arg, -1, "");
752  }
753  
754  private List<Value> resolveValues(Argument arg, int max) throws EGraphQLException {
755    return resolveValues(arg, max, "");
756  }
757  
758  private List<Value> resolveValues(Argument arg, int max, String vars) throws EGraphQLException {
759    List<Value> result = new ArrayList<Value>();
760    for (Value v : arg.getValues()) {
761      if (! (v instanceof VariableValue))
762        result.add(v);
763      else {
764        if (vars.contains(":"+v.toString()+":"))
765          throw new EGraphQLException("Recursive reference to variable "+v.toString());
766        Argument a = workingVariables.get(v.toString());
767        if (a == null)
768          throw new EGraphQLException("No value found for variable \""+v.toString()+"\" in \""+arg.getName()+"\"");
769        List<Value> vl = resolveValues(a, -1, vars+":"+v.toString()+":");
770        result.addAll(vl);
771      }
772    }
773    if ((max != -1 && result.size() > max))
774      throw new EGraphQLException("Only "+Integer.toString(max)+" values are allowed for \""+arg.getName()+"\", but "+Integer.toString(result.size())+" enoucntered");
775    return result;
776  }
777
778
779  
780  
781  public Object getAppInfo() {
782    return appInfo;
783  }
784
785  @Override
786  public void setAppInfo(Object appInfo) {
787    this.appInfo = appInfo;
788  }
789
790  public Resource getFocus() {
791    return focus;
792  }
793
794  @Override
795  public void setFocus(IBaseResource focus) {
796    this.focus = (Resource) focus;
797  }
798
799  public Package getGraphQL() {
800    return graphQL;
801  }
802
803  @Override
804  public void setGraphQL(Package graphQL) {
805    this.graphQL = graphQL;
806  }
807
808  @Override
809  public GraphQLResponse getOutput() {
810    return output;
811  }
812
813  public IGraphQLStorageServices getServices() {
814    return services;
815  }
816
817  @Override
818  public void setServices(IGraphQLStorageServices services) {
819    this.services = services;
820  }
821
822
823  //
824//{ GraphQLSearchWrapper }
825//
826//constructor GraphQLSearchWrapper.Create(bundle : Bundle);
827//var
828//  s : String;
829//{
830//  inherited Create;
831//  FBundle = bundle;
832//  s = bundle_List.Matches["self"];
833//  FParseMap = TParseMap.create(s.Substring(s.IndexOf("?")+1));
834//}
835//
836//destructor GraphQLSearchWrapper.Destroy;
837//{
838//  FParseMap.free;
839//  FBundle.Free;
840//  inherited;
841//}
842//
843//function GraphQLSearchWrapper.extractLink(name: String): String;
844//var
845//  s : String;
846//  pm : TParseMap;
847//{
848//  s = FBundle_List.Matches[name];
849//  if (s == "")
850//    result = null
851//  else
852//  {
853//    pm = TParseMap.create(s.Substring(s.IndexOf("?")+1));
854//    try
855//      result = String.Create(pm.GetVar("search-id")+":"+pm.GetVar("search-offset"));
856//    finally
857//      pm.Free;
858//    }
859//  }
860//}
861//
862//function GraphQLSearchWrapper.extractParam(name: String; int : boolean): Base;
863//var
864//  s : String;
865//{
866//  s = FParseMap.GetVar(name);
867//  if (s == "")
868//    result = null
869//  else if (int)
870//    result = Integer.Create(s)
871//  else
872//    result = String.Create(s);
873//}
874//
875//function GraphQLSearchWrapper.fhirType(): String;
876//{
877//  result = "*Connection";
878//}
879//
880//  // http://test.fhir.org/r4/Patient?_format==text/xhtml&search-id==77c97e03-8a6c-415f-a63d-11c80cf73f&&active==true&_sort==_id&search-offset==50&_count==50
881//
882//function GraphQLSearchWrapper.getPropertyValue(propName: string): Property;
883//var
884//  list : List<GraphQLSearchEdge>;
885//  be : BundleEntry;
886//{
887//  if (propName == "first")
888//    result = Property.Create(self, propname, "string", false, String, extractLink("first"))
889//  else if (propName == "previous")
890//    result = Property.Create(self, propname, "string", false, String, extractLink("previous"))
891//  else if (propName == "next")
892//    result = Property.Create(self, propname, "string", false, String, extractLink("next"))
893//  else if (propName == "last")
894//    result = Property.Create(self, propname, "string", false, String, extractLink("last"))
895//  else if (propName == "count")
896//    result = Property.Create(self, propname, "integer", false, String, FBundle.totalElement)
897//  else if (propName == "offset")
898//    result = Property.Create(self, propname, "integer", false, Integer, extractParam("search-offset", true))
899//  else if (propName == "pagesize")
900//    result = Property.Create(self, propname, "integer", false, Integer, extractParam("_count", true))
901//  else if (propName == "edges")
902//  {
903//    list = ArrayList<GraphQLSearchEdge>();
904//    try
905//      for be in FBundle.getEntry() do
906//        list.add(GraphQLSearchEdge.create(be));
907//      result = Property.Create(self, propname, "integer", true, Integer, List<Base>(list));
908//    finally
909//      list.Free;
910//    }
911//  }
912//  else
913//    result = null;
914//}
915//
916//private void GraphQLSearchWrapper.SetBundle(const Value: Bundle);
917//{
918//  FBundle.Free;
919//  FBundle = Value;
920//}
921//
922//{ GraphQLSearchEdge }
923//
924//constructor GraphQLSearchEdge.Create(entry: BundleEntry);
925//{
926//  inherited Create;
927//  FEntry = entry;
928//}
929//
930//destructor GraphQLSearchEdge.Destroy;
931//{
932//  FEntry.Free;
933//  inherited;
934//}
935//
936//function GraphQLSearchEdge.fhirType(): String;
937//{
938//  result = "*Edge";
939//}
940//
941//function GraphQLSearchEdge.getPropertyValue(propName: string): Property;
942//{
943//  if (propName == "mode")
944//  {
945//    if (FEntry.search != null)
946//      result = Property.Create(self, propname, "code", false, Enum, FEntry.search.modeElement)
947//    else
948//      result = Property.Create(self, propname, "code", false, Enum, Base(null));
949//  }
950//  else if (propName == "score")
951//  {
952//    if (FEntry.search != null)
953//      result = Property.Create(self, propname, "decimal", false, Decimal, FEntry.search.scoreElement)
954//    else
955//      result = Property.Create(self, propname, "decimal", false, Decimal, Base(null));
956//  }
957//  else if (propName == "resource")
958//    result = Property.Create(self, propname, "resource", false, Resource, FEntry.getResource())
959//  else
960//    result = null;
961//}
962//
963//private void GraphQLSearchEdge.SetEntry(const Value: BundleEntry);
964//{
965//  FEntry.Free;
966//  FEntry = value;
967//}
968//
969}