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