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
024// remember group resolution
025// trace - account for which wasn't transformed in the source
026
027import java.io.IOException;
028import java.util.ArrayList;
029import java.util.EnumSet;
030import java.util.HashMap;
031import java.util.HashSet;
032import java.util.List;
033import java.util.Map;
034import java.util.Set;
035import java.util.UUID;
036
037import org.apache.commons.lang3.NotImplementedException;
038import org.hl7.fhir.exceptions.DefinitionException;
039import org.hl7.fhir.exceptions.FHIRException;
040import org.hl7.fhir.exceptions.FHIRFormatError;
041import org.hl7.fhir.exceptions.PathEngineException;
042import org.hl7.fhir.r5.conformance.ProfileUtilities;
043import org.hl7.fhir.r5.conformance.ProfileUtilities.ProfileKnowledgeProvider;
044import org.hl7.fhir.r5.context.IWorkerContext;
045import org.hl7.fhir.r5.context.IWorkerContext.ValidationResult;
046import org.hl7.fhir.r5.elementmodel.Element;
047import org.hl7.fhir.r5.elementmodel.Property;
048import org.hl7.fhir.r5.model.Base;
049import org.hl7.fhir.r5.model.BooleanType;
050import org.hl7.fhir.r5.model.CanonicalType;
051import org.hl7.fhir.r5.model.CodeType;
052import org.hl7.fhir.r5.model.CodeableConcept;
053import org.hl7.fhir.r5.model.Coding;
054import org.hl7.fhir.r5.model.ConceptMap;
055import org.hl7.fhir.r5.model.ConceptMap.ConceptMapGroupComponent;
056import org.hl7.fhir.r5.model.ConceptMap.ConceptMapGroupUnmappedMode;
057import org.hl7.fhir.r5.model.ConceptMap.SourceElementComponent;
058import org.hl7.fhir.r5.model.ConceptMap.TargetElementComponent;
059import org.hl7.fhir.r5.model.Constants;
060import org.hl7.fhir.r5.model.ContactDetail;
061import org.hl7.fhir.r5.model.ContactPoint;
062import org.hl7.fhir.r5.model.DecimalType;
063import org.hl7.fhir.r5.model.ElementDefinition;
064import org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionMappingComponent;
065import org.hl7.fhir.r5.model.ElementDefinition.TypeRefComponent;
066import org.hl7.fhir.r5.model.Enumeration;
067import org.hl7.fhir.r5.model.Enumerations.ConceptMapRelationship;
068import org.hl7.fhir.r5.model.Enumerations.FHIRVersion;
069import org.hl7.fhir.r5.model.Enumerations.PublicationStatus;
070import org.hl7.fhir.r5.model.ExpressionNode;
071import org.hl7.fhir.r5.model.ExpressionNode.CollectionStatus;
072import org.hl7.fhir.r5.model.IdType;
073import org.hl7.fhir.r5.model.IntegerType;
074import org.hl7.fhir.r5.model.Narrative.NarrativeStatus;
075import org.hl7.fhir.r5.model.PrimitiveType;
076import org.hl7.fhir.r5.model.Reference;
077import org.hl7.fhir.r5.model.Resource;
078import org.hl7.fhir.r5.model.ResourceFactory;
079import org.hl7.fhir.r5.model.StringType;
080import org.hl7.fhir.r5.model.StructureDefinition;
081import org.hl7.fhir.r5.model.StructureDefinition.StructureDefinitionMappingComponent;
082import org.hl7.fhir.r5.model.StructureDefinition.TypeDerivationRule;
083import org.hl7.fhir.r5.model.StructureMap;
084import org.hl7.fhir.r5.model.StructureMap.StructureMapContextType;
085import org.hl7.fhir.r5.model.StructureMap.StructureMapGroupComponent;
086import org.hl7.fhir.r5.model.StructureMap.StructureMapGroupInputComponent;
087import org.hl7.fhir.r5.model.StructureMap.StructureMapGroupRuleComponent;
088import org.hl7.fhir.r5.model.StructureMap.StructureMapGroupRuleDependentComponent;
089import org.hl7.fhir.r5.model.StructureMap.StructureMapGroupRuleSourceComponent;
090import org.hl7.fhir.r5.model.StructureMap.StructureMapGroupRuleTargetComponent;
091import org.hl7.fhir.r5.model.StructureMap.StructureMapGroupRuleTargetParameterComponent;
092import org.hl7.fhir.r5.model.StructureMap.StructureMapGroupTypeMode;
093import org.hl7.fhir.r5.model.StructureMap.StructureMapInputMode;
094import org.hl7.fhir.r5.model.StructureMap.StructureMapModelMode;
095import org.hl7.fhir.r5.model.StructureMap.StructureMapSourceListMode;
096import org.hl7.fhir.r5.model.StructureMap.StructureMapStructureComponent;
097import org.hl7.fhir.r5.model.StructureMap.StructureMapTargetListMode;
098import org.hl7.fhir.r5.model.StructureMap.StructureMapTransform;
099import org.hl7.fhir.r5.model.DataType;
100import org.hl7.fhir.r5.model.TypeDetails;
101import org.hl7.fhir.r5.model.TypeDetails.ProfiledType;
102import org.hl7.fhir.r5.model.UriType;
103import org.hl7.fhir.r5.model.ValueSet;
104import org.hl7.fhir.r5.model.ValueSet.ValueSetExpansionContainsComponent;
105import org.hl7.fhir.r5.terminologies.ValueSetExpander.ValueSetExpansionOutcome;
106import org.hl7.fhir.r5.utils.FHIRLexer.FHIRLexerException;
107import org.hl7.fhir.r5.utils.FHIRPathEngine.IEvaluationContext;
108import org.hl7.fhir.utilities.CommaSeparatedStringBuilder;
109import org.hl7.fhir.utilities.TerminologyServiceOptions;
110import org.hl7.fhir.utilities.Utilities;
111import org.hl7.fhir.utilities.validation.ValidationOptions;
112import org.hl7.fhir.utilities.validation.ValidationMessage;
113import org.hl7.fhir.utilities.xhtml.NodeType;
114import org.hl7.fhir.utilities.xhtml.XhtmlNode;
115
116/**
117 * Services in this class:
118 * 
119 * string render(map) - take a structure and convert it to text
120 * map parse(text) - take a text representation and parse it 
121 * getTargetType(map) - return the definition for the type to create to hand in 
122 * transform(appInfo, source, map, target) - transform from source to target following the map
123 * analyse(appInfo, map) - generate profiles and other analysis artifacts for the targets of the transform
124 * map generateMapFromMappings(StructureDefinition) - build a mapping from a structure definition with loigcal mappings
125 *  
126 * @author Grahame Grieve
127 *
128 */
129public class StructureMapUtilities {
130
131        public class ResolvedGroup {
132    public StructureMapGroupComponent target;
133    public StructureMap targetMap;
134  }
135  public static final String MAP_WHERE_CHECK = "map.where.check";
136  public static final String MAP_WHERE_LOG = "map.where.log";
137        public static final String MAP_WHERE_EXPRESSION = "map.where.expression";
138        public static final String MAP_SEARCH_EXPRESSION = "map.search.expression";
139        public static final String MAP_EXPRESSION = "map.transform.expression";
140  private static final boolean RENDER_MULTIPLE_TARGETS_ONELINE = true;
141  private static final String AUTO_VAR_NAME = "vvv";
142
143        public interface ITransformerServices {
144                //    public boolean validateByValueSet(Coding code, String valuesetId);
145          public void log(String message); // log internal progress
146          public Base createType(Object appInfo, String name) throws FHIRException;
147    public Base createResource(Object appInfo, Base res, boolean atRootofTransform); // an already created resource is provided; this is to identify/store it
148                public Coding translate(Object appInfo, Coding source, String conceptMapUrl) throws FHIRException;
149                //    public Coding translate(Coding code)
150                //    ValueSet validation operation
151                //    Translation operation
152                //    Lookup another tree of data
153                //    Create an instance tree
154                //    Return the correct string format to refer to a tree (input or output)
155    public Base resolveReference(Object appContext, String url) throws FHIRException;
156    public List<Base> performSearch(Object appContext, String url) throws FHIRException;
157        }
158
159        private class FFHIRPathHostServices implements IEvaluationContext{
160
161    public Base resolveConstant(Object appContext, String name, boolean beforeContext) throws PathEngineException {
162      Variables vars = (Variables) appContext;
163      Base res = vars.get(VariableMode.INPUT, name);
164      if (res == null)
165        res = vars.get(VariableMode.OUTPUT, name);
166      return res;
167    }
168
169    @Override
170    public TypeDetails resolveConstantType(Object appContext, String name) throws PathEngineException {
171      if (!(appContext instanceof VariablesForProfiling)) 
172        throw new Error("Internal Logic Error (wrong type '"+appContext.getClass().getName()+"' in resolveConstantType)");
173      VariablesForProfiling vars = (VariablesForProfiling) appContext;
174      VariableForProfiling v = vars.get(null, name);
175      if (v == null)
176        throw new PathEngineException("Unknown variable '"+name+"' from variables "+vars.summary());
177      return v.property.types;
178    }
179
180    @Override
181    public boolean log(String argument, List<Base> focus) {
182      throw new Error("Not Implemented Yet");
183    }
184
185    @Override
186    public FunctionDetails resolveFunction(String functionName) {
187      return null; // throw new Error("Not Implemented Yet");
188    }
189
190    @Override
191    public TypeDetails checkFunction(Object appContext, String functionName, List<TypeDetails> parameters) throws PathEngineException {
192      throw new Error("Not Implemented Yet");
193    }
194
195    @Override
196    public List<Base> executeFunction(Object appContext, String functionName, List<List<Base>> parameters) {
197      throw new Error("Not Implemented Yet");
198    }
199
200    @Override
201    public Base resolveReference(Object appContext, String url) throws FHIRException {
202      if (services == null)
203        return null;
204      return services.resolveReference(appContext, url);
205    }
206
207    @Override
208    public boolean conformsToProfile(Object appContext, Base item, String url) throws FHIRException {
209      IResourceValidator val = worker.newValidator();
210      List<ValidationMessage> valerrors = new ArrayList<ValidationMessage>();
211      if (item instanceof Resource) {
212        val.validate(appContext, valerrors, (Resource) item, url);
213        boolean ok = true;
214        for (ValidationMessage v : valerrors)
215          ok = ok && v.getLevel().isError();
216        return ok;
217      }
218      throw new NotImplementedException("Not done yet (FFHIRPathHostServices.conformsToProfile), when item is element");
219    }
220
221    @Override
222    public ValueSet resolveValueSet(Object appContext, String url) {
223      throw new Error("Not Implemented Yet");
224    }
225          
226        }
227        private IWorkerContext worker;
228        private FHIRPathEngine fpe;
229        private ITransformerServices services;
230  private ProfileKnowledgeProvider pkp;
231  private Map<String, Integer> ids = new HashMap<String, Integer>();
232  private ValidationOptions terminologyServiceOptions = new ValidationOptions(); 
233
234        public StructureMapUtilities(IWorkerContext worker, ITransformerServices services, ProfileKnowledgeProvider pkp) {
235                super();
236                this.worker = worker;
237                this.services = services;
238                this.pkp = pkp;
239                fpe = new FHIRPathEngine(worker);
240                fpe.setHostServices(new FFHIRPathHostServices());
241        }
242
243        public StructureMapUtilities(IWorkerContext worker, ITransformerServices services) {
244                super();
245                this.worker = worker;
246                this.services = services;
247                fpe = new FHIRPathEngine(worker);
248    fpe.setHostServices(new FFHIRPathHostServices());
249        }
250
251  public StructureMapUtilities(IWorkerContext worker) {
252    super();
253    this.worker = worker;
254    fpe = new FHIRPathEngine(worker);
255    fpe.setHostServices(new FFHIRPathHostServices());
256  }
257
258        public static String render(StructureMap map) {
259                StringBuilder b = new StringBuilder();
260                b.append("map \"");
261                b.append(map.getUrl());
262                b.append("\" = \"");
263                b.append(Utilities.escapeJson(map.getName()));
264                b.append("\"\r\n\r\n");
265
266                renderConceptMaps(b, map);
267                renderUses(b, map);
268                renderImports(b, map);
269                for (StructureMapGroupComponent g : map.getGroup())
270                        renderGroup(b, g);
271                return b.toString();
272        }
273
274        private static void renderConceptMaps(StringBuilder b, StructureMap map) {
275    for (Resource r : map.getContained()) {
276      if (r instanceof ConceptMap) {
277        produceConceptMap(b, (ConceptMap) r);
278      }
279    }
280  }
281
282  private static void produceConceptMap(StringBuilder b, ConceptMap cm) {
283    b.append("conceptmap \"");
284    b.append(cm.getId());
285    b.append("\" {\r\n");
286    Map<String, String> prefixesSrc = new HashMap<String, String>();
287    Map<String, String> prefixesTgt = new HashMap<String, String>();
288    char prefix = 's';
289    for (ConceptMapGroupComponent cg : cm.getGroup()) {
290      if (!prefixesSrc.containsKey(cg.getSource())) {
291        prefixesSrc.put(cg.getSource(), String.valueOf(prefix));
292        b.append("  prefix ");
293        b.append(prefix);
294        b.append(" = \"");
295        b.append(cg.getSource());
296        b.append("\"\r\n");
297        prefix++;
298      }
299      if (!prefixesTgt.containsKey(cg.getTarget())) {
300        prefixesTgt.put(cg.getTarget(), String.valueOf(prefix));
301        b.append("  prefix ");
302        b.append(prefix);
303        b.append(" = \"");
304        b.append(cg.getTarget());
305        b.append("\"\r\n");
306        prefix++;
307      }
308    }
309    b.append("\r\n");
310    for (ConceptMapGroupComponent cg : cm.getGroup()) {
311      if (cg.hasUnmapped()) {
312        b.append("  unmapped for ");
313        b.append(prefixesSrc.get(cg.getSource()));
314        b.append(" = ");
315        b.append(cg.getUnmapped().getMode().toCode());
316        b.append("\r\n"); 
317      }   
318    }
319    
320    for (ConceptMapGroupComponent cg : cm.getGroup()) {
321      for (SourceElementComponent ce : cg.getElement()) {
322        b.append("  ");
323        b.append(prefixesSrc.get(cg.getSource()));
324        b.append(":");
325        if (Utilities.isToken(ce.getCode())) {
326          b.append(ce.getCode());        
327        } else {
328          b.append("\"");
329          b.append(ce.getCode());
330          b.append("\"");
331        }
332        b.append(" ");
333        b.append(getChar(ce.getTargetFirstRep().getRelationship()));
334        b.append(" ");
335        b.append(prefixesTgt.get(cg.getTarget()));
336        b.append(":");
337        if (Utilities.isToken(ce.getTargetFirstRep().getCode())) {
338          b.append(ce.getTargetFirstRep().getCode());
339        } else {
340          b.append("\"");
341          b.append(ce.getTargetFirstRep().getCode());
342          b.append("\"");
343        }
344        b.append("\r\n");
345      }
346    }
347    b.append("}\r\n\r\n");
348  }
349
350  private static Object getChar(ConceptMapRelationship relationship) {
351    switch (relationship) {
352    case RELATEDTO: return "-";
353    case EQUIVALENT: return "==";
354    case NOTRELATEDTO: return "!=";
355    case BROADER: return "<=";
356    case NARROWER: return ">=";
357    default: return "??";
358    }
359  }
360
361  private static void renderUses(StringBuilder b, StructureMap map) {
362                for (StructureMapStructureComponent s : map.getStructure()) {
363                        b.append("uses \"");
364                        b.append(s.getUrl());
365      b.append("\" ");
366      if (s.hasAlias()) {
367        b.append("alias ");
368        b.append(s.getAlias());
369        b.append(" ");
370      }
371      b.append("as ");
372                        b.append(s.getMode().toCode());
373                        b.append("\r\n");
374                        renderDoco(b, s.getDocumentation());
375                }
376                if (map.hasStructure())
377                        b.append("\r\n");
378        }
379
380        private static void renderImports(StringBuilder b, StructureMap map) {
381                for (UriType s : map.getImport()) {
382                        b.append("imports \"");
383                        b.append(s.getValue());
384                        b.append("\"\r\n");
385                }
386                if (map.hasImport())
387                        b.append("\r\n");
388        }
389
390  public static String groupToString(StructureMapGroupComponent g) {
391    StringBuilder b = new StringBuilder();
392    renderGroup(b, g);
393    return b.toString();
394  }
395
396  private static void renderGroup(StringBuilder b, StructureMapGroupComponent g) {
397    b.append("group ");
398    b.append(g.getName());
399    b.append("(");
400    boolean first = true;
401    for (StructureMapGroupInputComponent gi : g.getInput()) {
402      if (first)
403        first = false;
404      else
405        b.append(", ");
406      b.append(gi.getMode().toCode());
407      b.append(" ");
408      b.append(gi.getName());
409      if (gi.hasType()) {
410        b.append(" : ");
411        b.append(gi.getType());
412      }
413    }
414    b.append(")");
415    if (g.hasExtends()) {
416      b.append(" extends ");
417      b.append(g.getExtends());
418    }
419
420    if (g.hasTypeMode()) {
421      switch (g.getTypeMode()) {
422      case TYPES: 
423        b.append(" <<types>>");
424        break;
425      case TYPEANDTYPES: 
426        b.append(" <<type+>>");
427        break;
428      default: // NONE, NULL
429      }
430    }
431    b.append(" {\r\n");
432    for (StructureMapGroupRuleComponent r : g.getRule()) {
433      renderRule(b, r, 2);
434    }
435    b.append("}\r\n\r\n");
436  }
437
438  public static String ruleToString(StructureMapGroupRuleComponent r) {
439    StringBuilder b = new StringBuilder();
440    renderRule(b, r, 0);
441    return b.toString();
442  }
443  
444        private static void renderRule(StringBuilder b, StructureMapGroupRuleComponent r, int indent) {
445                for (int i = 0; i < indent; i++)
446                        b.append(' ');
447                boolean canBeAbbreviated = checkisSimple(r);
448
449                boolean first = true;
450                for (StructureMapGroupRuleSourceComponent rs : r.getSource()) {
451                  if (first)
452                    first = false;
453                  else
454                    b.append(", ");
455                  renderSource(b, rs, canBeAbbreviated);
456                }
457                if (r.getTarget().size() > 1) {
458                  b.append(" -> ");
459                  first = true;
460                  for (StructureMapGroupRuleTargetComponent rt : r.getTarget()) {
461                    if (first)
462                      first = false;
463                    else
464                      b.append(", ");
465                    if (RENDER_MULTIPLE_TARGETS_ONELINE)
466                      b.append(' ');
467                    else {
468                      b.append("\r\n");
469                      for (int i = 0; i < indent+4; i++)
470                        b.append(' ');
471                    }
472                    renderTarget(b, rt, false);
473                  }
474                } else if (r.hasTarget()) { 
475      b.append(" -> ");
476                  renderTarget(b, r.getTarget().get(0), canBeAbbreviated);
477                }
478                if (r.hasRule()) {
479                  b.append(" then {\r\n");
480                  renderDoco(b, r.getDocumentation());
481                  for (StructureMapGroupRuleComponent ir : r.getRule()) {
482                    renderRule(b, ir, indent+2);
483                  }
484                  for (int i = 0; i < indent; i++)
485                    b.append(' ');
486                  b.append("}");
487                } else {
488                  if (r.hasDependent()) {
489                    b.append(" then ");
490                    first = true;
491                    for (StructureMapGroupRuleDependentComponent rd : r.getDependent()) {
492                      if (first)
493                        first = false;
494                      else
495                        b.append(", ");
496                      b.append(rd.getName());
497                      b.append("(");
498                      boolean ifirst = true;
499                      for (StringType rdp : rd.getVariable()) {
500                        if (ifirst)
501                          ifirst = false;
502                        else
503                          b.append(", ");
504                        b.append(rdp.asStringValue());
505                      }
506                      b.append(")");
507                    }
508                  }
509                }
510                if (r.hasName()) {
511                  String n = ntail(r.getName());
512                  if (!n.startsWith("\""))
513                    n = "\""+n+"\"";
514                  if (!matchesName(n, r.getSource())) {
515                    b.append(" ");
516                    b.append(n);
517                  }
518                }
519                b.append(";");
520                renderDoco(b, r.getDocumentation());
521                b.append("\r\n");
522        }
523
524  private static boolean matchesName(String n, List<StructureMapGroupRuleSourceComponent> source) {
525    if (source.size() != 1)
526      return false;
527    if (!source.get(0).hasElement())
528      return false;
529    String s = source.get(0).getElement();
530    if (n.equals(s) || n.equals("\""+s+"\""))
531      return true;
532    if (source.get(0).hasType()) {
533      s = source.get(0).getElement()+"-"+source.get(0).getType();
534      if (n.equals(s) || n.equals("\""+s+"\""))
535        return true;
536    }
537    return false;
538  }
539
540  private static String ntail(String name) {
541    if (name == null)
542      return null;
543    if (name.startsWith("\"")) {
544      name = name.substring(1);
545      name = name.substring(0, name.length()-1);
546    }
547    return "\""+ (name.contains(".") ? name.substring(name.lastIndexOf(".")+1) : name) + "\"";
548  }
549
550  private static boolean checkisSimple(StructureMapGroupRuleComponent r) {
551    return 
552          (r.getSource().size() == 1 && r.getSourceFirstRep().hasElement() && r.getSourceFirstRep().hasVariable()) && 
553          (r.getTarget().size() == 1 && r.getTargetFirstRep().hasVariable() && (r.getTargetFirstRep().getTransform() == null || r.getTargetFirstRep().getTransform() == StructureMapTransform.CREATE) && r.getTargetFirstRep().getParameter().size() == 0) &&
554          (r.getDependent().size() == 0) && (r.getRule().size() == 0) ;
555  }
556
557  public static String sourceToString(StructureMapGroupRuleSourceComponent r) {
558    StringBuilder b = new StringBuilder();
559    renderSource(b, r, false);
560    return b.toString();
561  }
562  
563        private static void renderSource(StringBuilder b, StructureMapGroupRuleSourceComponent rs, boolean abbreviate) {
564                b.append(rs.getContext());
565                if (rs.getContext().equals("@search")) {
566      b.append('(');
567      b.append(rs.getElement());
568      b.append(')');
569                } else if (rs.hasElement()) {
570                        b.append('.');
571                        b.append(rs.getElement());
572                }
573                if (rs.hasType()) {
574      b.append(" : ");
575      b.append(rs.getType());
576      if (rs.hasMin()) {
577        b.append(" ");
578        b.append(rs.getMin());
579        b.append("..");
580        b.append(rs.getMax());
581      }
582                }
583                
584                if (rs.hasListMode()) {
585                        b.append(" ");
586                                b.append(rs.getListMode().toCode());
587                }
588                if (rs.hasDefaultValue()) {
589                  b.append(" default ");
590                  assert rs.getDefaultValue() instanceof StringType;
591                  b.append("\""+Utilities.escapeJson(((StringType) rs.getDefaultValue()).asStringValue())+"\"");
592                }
593                if (!abbreviate && rs.hasVariable()) {
594                        b.append(" as ");
595                        b.append(rs.getVariable());
596                }
597                if (rs.hasCondition())  {
598                        b.append(" where ");
599                        b.append(rs.getCondition());
600                }
601                if (rs.hasCheck())  {
602                        b.append(" check ");
603                        b.append(rs.getCheck());
604                }
605    if (rs.hasLogMessage()) {
606      b.append(" log ");
607      b.append(rs.getLogMessage());
608    }
609        }
610
611  public static String targetToString(StructureMapGroupRuleTargetComponent rt) {
612    StringBuilder b = new StringBuilder();
613    renderTarget(b, rt, false);
614    return b.toString();
615  }
616
617  private static void renderTarget(StringBuilder b, StructureMapGroupRuleTargetComponent rt, boolean abbreviate) {
618    if (rt.hasContext()) {
619      if (rt.getContextType() == StructureMapContextType.TYPE)
620        b.append("@");
621      b.append(rt.getContext());
622      if (rt.hasElement())  {
623        b.append('.');
624        b.append(rt.getElement());
625      }
626    }
627                if (!abbreviate && rt.hasTransform()) {
628            if (rt.hasContext()) 
629                        b.append(" = ");
630                        if (rt.getTransform() == StructureMapTransform.COPY && rt.getParameter().size() == 1) {
631                                renderTransformParam(b, rt.getParameter().get(0));
632      } else if (rt.getTransform() == StructureMapTransform.EVALUATE && rt.getParameter().size() == 1) {
633        b.append("(");
634        b.append("\""+((StringType) rt.getParameter().get(0).getValue()).asStringValue()+"\"");
635        b.append(")");
636                        } else if (rt.getTransform() == StructureMapTransform.EVALUATE && rt.getParameter().size() == 2) {
637                                b.append(rt.getTransform().toCode());
638                                b.append("(");
639                                b.append(((IdType) rt.getParameter().get(0).getValue()).asStringValue());
640                                b.append("\""+((StringType) rt.getParameter().get(1).getValue()).asStringValue()+"\"");
641                                b.append(")");
642                        } else {
643                                b.append(rt.getTransform().toCode());
644                                b.append("(");
645                                boolean first = true;
646                                for (StructureMapGroupRuleTargetParameterComponent rtp : rt.getParameter()) {
647                                        if (first)
648                                                first = false;
649                                        else
650                                                b.append(", ");
651                                        renderTransformParam(b, rtp);
652                                }
653                                b.append(")");
654                        }
655                }
656                if (!abbreviate && rt.hasVariable()) {
657                        b.append(" as ");
658                        b.append(rt.getVariable());
659                }
660                for (Enumeration<StructureMapTargetListMode> lm : rt.getListMode()) {
661                        b.append(" ");
662                        b.append(lm.getValue().toCode());
663                        if (lm.getValue() == StructureMapTargetListMode.SHARE) {
664                                b.append(" ");
665                                b.append(rt.getListRuleId());
666                        }
667                }
668        }
669
670  public static String paramToString(StructureMapGroupRuleTargetParameterComponent rtp) {
671    StringBuilder b = new StringBuilder();
672    renderTransformParam(b, rtp);
673    return b.toString();
674  }
675        
676        private static void renderTransformParam(StringBuilder b, StructureMapGroupRuleTargetParameterComponent rtp) {
677          try {
678                if (rtp.hasValueBooleanType())
679                        b.append(rtp.getValueBooleanType().asStringValue());
680                else if (rtp.hasValueDecimalType())
681                        b.append(rtp.getValueDecimalType().asStringValue());
682                else if (rtp.hasValueIdType())
683                        b.append(rtp.getValueIdType().asStringValue());
684                else if (rtp.hasValueDecimalType())
685                        b.append(rtp.getValueDecimalType().asStringValue());
686                else if (rtp.hasValueIntegerType())
687                        b.append(rtp.getValueIntegerType().asStringValue());
688                else 
689              b.append("'"+Utilities.escapeJava(rtp.getValueStringType().asStringValue())+"'");
690          } catch (FHIRException e) {
691            e.printStackTrace();
692            b.append("error!");
693          }
694        }
695
696        private static void renderDoco(StringBuilder b, String doco) {
697                if (Utilities.noString(doco))
698                        return;
699                b.append(" // ");
700                b.append(doco.replace("\r\n", " ").replace("\r", " ").replace("\n", " "));
701        }
702
703        public StructureMap parse(String text, String srcName) throws FHIRException {
704                FHIRLexer lexer = new FHIRLexer(text, srcName);
705                if (lexer.done())
706                        throw lexer.error("Map Input cannot be empty");
707                lexer.skipComments();
708                lexer.token("map");
709                StructureMap result = new StructureMap();
710                result.setUrl(lexer.readConstant("url"));
711                lexer.token("=");
712                result.setName(lexer.readConstant("name"));
713                lexer.skipComments();
714
715                while (lexer.hasToken("conceptmap"))
716                        parseConceptMap(result, lexer);
717
718                while (lexer.hasToken("uses"))
719                        parseUses(result, lexer);
720                while (lexer.hasToken("imports"))
721                        parseImports(result, lexer);
722                
723                while (!lexer.done()) {
724                        parseGroup(result, lexer);    
725                }
726
727                return result;
728        }
729
730        private void parseConceptMap(StructureMap result, FHIRLexer lexer) throws FHIRLexerException {
731                lexer.token("conceptmap");
732                ConceptMap map = new ConceptMap();
733                String id = lexer.readConstant("map id");
734                if (id.startsWith("#"))
735                        throw lexer.error("Concept Map identifier must start with #");
736                map.setId(id);
737                map.setStatus(PublicationStatus.DRAFT); // todo: how to add this to the text format
738                result.getContained().add(map);
739                lexer.token("{");
740                lexer.skipComments();
741                //        lexer.token("source");
742                //        map.setSource(new UriType(lexer.readConstant("source")));
743                //        lexer.token("target");
744                //        map.setSource(new UriType(lexer.readConstant("target")));
745                Map<String, String> prefixes = new HashMap<String, String>();
746                while (lexer.hasToken("prefix")) {
747                        lexer.token("prefix");
748                        String n = lexer.take();
749                        lexer.token("=");
750                        String v = lexer.readConstant("prefix url");
751                        prefixes.put(n, v);
752                }
753                while (lexer.hasToken("unmapped")) {
754                  lexer.token("unmapped");
755      lexer.token("for");
756      String n = readPrefix(prefixes, lexer);
757      ConceptMapGroupComponent g = getGroup(map, n, null);
758                  lexer.token("=");
759      String v = lexer.take();
760      if (v.equals("provided")) {
761        g.getUnmapped().setMode(ConceptMapGroupUnmappedMode.PROVIDED);
762      } else
763        throw lexer.error("Only unmapped mode PROVIDED is supported at this time");
764                }
765                while (!lexer.hasToken("}")) {
766                  String srcs = readPrefix(prefixes, lexer);
767                        lexer.token(":");
768      String sc = lexer.getCurrent().startsWith("\"") ? lexer.readConstant("code") : lexer.take();
769                  ConceptMapRelationship rel = readRelationship(lexer);
770                  String tgts = readPrefix(prefixes, lexer);
771                  ConceptMapGroupComponent g = getGroup(map, srcs, tgts);
772                        SourceElementComponent e = g.addElement();
773                        e.setCode(sc);
774      if (e.getCode().startsWith("\""))
775        e.setCode(lexer.processConstant(e.getCode()));
776                        TargetElementComponent tgt = e.addTarget();
777                        if (rel != ConceptMapRelationship.EQUIVALENT)
778                          tgt.setRelationship(rel);
779                        lexer.token(":");
780                        tgt.setCode(lexer.take());
781                        if (tgt.getCode().startsWith("\""))
782                          tgt.setCode(lexer.processConstant(tgt.getCode()));
783                        if (lexer.hasComment())
784                                tgt.setComment(lexer.take().substring(2).trim());
785                }
786                lexer.token("}");
787        }
788
789
790        private ConceptMapGroupComponent getGroup(ConceptMap map, String srcs, String tgts) {
791          for (ConceptMapGroupComponent grp : map.getGroup()) {
792            if (grp.getSource().equals(srcs)) 
793              if (!grp.hasTarget() || tgts == null || tgts.equals(grp.getTarget())) {
794                if (!grp.hasTarget() && tgts != null)
795                  grp.setTarget(tgts);
796                return grp;
797              }
798          }
799          ConceptMapGroupComponent grp = map.addGroup(); 
800          grp.setSource(srcs);
801          grp.setTarget(tgts);
802          return grp;
803        }
804
805
806        private String readPrefix(Map<String, String> prefixes, FHIRLexer lexer) throws FHIRLexerException {
807                String prefix = lexer.take();
808                if (!prefixes.containsKey(prefix))
809                        throw lexer.error("Unknown prefix '"+prefix+"'");
810                return prefixes.get(prefix);
811        }
812
813
814        private ConceptMapRelationship readRelationship(FHIRLexer lexer) throws FHIRLexerException {
815                String token = lexer.take();
816    if (token.equals("-"))
817      return ConceptMapRelationship.RELATEDTO;
818                if (token.equals("=="))
819                        return ConceptMapRelationship.EQUIVALENT;
820                if (token.equals("!="))
821                        return ConceptMapRelationship.NOTRELATEDTO;
822                if (token.equals("<="))
823                        return ConceptMapRelationship.BROADER;
824                if (token.equals(">="))
825                        return ConceptMapRelationship.NARROWER;
826                throw lexer.error("Unknown relationship token '"+token+"'");
827        }
828
829
830        private void parseUses(StructureMap result, FHIRLexer lexer) throws FHIRException {
831                lexer.token("uses");
832                StructureMapStructureComponent st = result.addStructure();
833                st.setUrl(lexer.readConstant("url"));
834                if (lexer.hasToken("alias")) {
835            lexer.token("alias");
836                  st.setAlias(lexer.take());
837                }
838                lexer.token("as");
839                st.setMode(StructureMapModelMode.fromCode(lexer.take()));
840                lexer.skipToken(";");
841                if (lexer.hasComment()) {
842                        st.setDocumentation(lexer.take().substring(2).trim());
843                }
844                lexer.skipComments();
845        }
846
847        private void parseImports(StructureMap result, FHIRLexer lexer) throws FHIRException {
848                lexer.token("imports");
849                result.addImport(lexer.readConstant("url"));
850                lexer.skipToken(";");
851                if (lexer.hasComment()) {
852                        lexer.next();
853                }
854                lexer.skipComments();
855        }
856
857        private void parseGroup(StructureMap result, FHIRLexer lexer) throws FHIRException {
858                lexer.token("group");
859                StructureMapGroupComponent group = result.addGroup();
860                boolean newFmt = false;
861                if (lexer.hasToken("for")) {
862                  lexer.token("for");
863                  if ("type".equals(lexer.getCurrent())) {
864        lexer.token("type");
865        lexer.token("+");
866        lexer.token("types");
867        group.setTypeMode(StructureMapGroupTypeMode.TYPEANDTYPES);
868                  } else {
869                    lexer.token("types");
870        group.setTypeMode(StructureMapGroupTypeMode.TYPES);
871                  }
872                } else
873                  group.setTypeMode(StructureMapGroupTypeMode.NONE);
874                group.setName(lexer.take());
875                if (lexer.hasToken("(")) {
876                  newFmt = true;
877                  lexer.take();
878                  while (!lexer.hasToken(")")) {
879                    parseInput(group, lexer, true);
880                    if (lexer.hasToken(","))
881                      lexer.token(",");
882                  }
883                  lexer.take();
884                }
885                if (lexer.hasToken("extends")) {
886                        lexer.next();
887                        group.setExtends(lexer.take());
888                }
889                if (newFmt) {
890      group.setTypeMode(StructureMapGroupTypeMode.NONE);
891                  if (lexer.hasToken("<")) {
892        lexer.token("<");
893        lexer.token("<");
894        if (lexer.hasToken("types")) {
895          group.setTypeMode(StructureMapGroupTypeMode.TYPES);          
896          lexer.token("types");
897        } else {
898          lexer.token("type");
899          lexer.token("+");
900          group.setTypeMode(StructureMapGroupTypeMode.TYPEANDTYPES);
901        }
902        lexer.token(">");
903        lexer.token(">");
904                  }
905                  lexer.token("{");
906                }
907                lexer.skipComments();
908                if (newFmt) {
909      while (!lexer.hasToken("}")) {
910        if (lexer.done())
911          throw lexer.error("premature termination expecting 'endgroup'");
912        parseRule(result, group.getRule(), lexer, true);
913      }
914                } else {
915                  while (lexer.hasToken("input")) 
916                    parseInput(group, lexer, false);
917                  while (!lexer.hasToken("endgroup")) {
918                    if (lexer.done())
919                      throw lexer.error("premature termination expecting 'endgroup'");
920                    parseRule(result, group.getRule(), lexer, false);
921                  }
922                }
923                lexer.next();
924                if (newFmt && lexer.hasToken(";"))
925            lexer.next();
926                lexer.skipComments();
927        }
928
929        private void parseInput(StructureMapGroupComponent group, FHIRLexer lexer, boolean newFmt) throws FHIRException {
930    StructureMapGroupInputComponent input = group.addInput();
931          if (newFmt) {
932            input.setMode(StructureMapInputMode.fromCode(lexer.take()));            
933          } else
934                lexer.token("input");
935                input.setName(lexer.take());
936                if (lexer.hasToken(":")) {
937                        lexer.token(":");
938                        input.setType(lexer.take());
939                }
940                if (!newFmt) {
941                lexer.token("as");
942                input.setMode(StructureMapInputMode.fromCode(lexer.take()));
943                  if (lexer.hasComment()) {
944                          input.setDocumentation(lexer.take().substring(2).trim());
945                }
946                lexer.skipToken(";");
947                  lexer.skipComments();
948                }
949        }
950
951        private void parseRule(StructureMap map, List<StructureMapGroupRuleComponent> list, FHIRLexer lexer, boolean newFmt) throws FHIRException {
952                StructureMapGroupRuleComponent rule = new StructureMapGroupRuleComponent(); 
953                list.add(rule);
954                if (!newFmt) {
955                  rule.setName(lexer.takeDottedToken());
956                  lexer.token(":");
957                  lexer.token("for");
958    }
959                boolean done = false;
960                while (!done) {
961                        parseSource(rule, lexer);
962                        done = !lexer.hasToken(",");
963                        if (!done)
964                                lexer.next();
965                }
966                if ((newFmt && lexer.hasToken("->")) || (!newFmt && lexer.hasToken("make"))) {
967                        lexer.token(newFmt ? "->" : "make");
968                        done = false;
969                        while (!done) {
970                                parseTarget(rule, lexer);
971                                done = !lexer.hasToken(",");
972                                if (!done)
973                                        lexer.next();
974                        }
975                }
976                if (lexer.hasToken("then")) {
977                        lexer.token("then");
978                        if (lexer.hasToken("{")) {
979                                lexer.token("{");
980                                if (lexer.hasComment()) {
981                                        rule.setDocumentation(lexer.take().substring(2).trim());
982                                }
983                                lexer.skipComments();
984                                while (!lexer.hasToken("}")) {
985                                        if (lexer.done())
986                                                throw lexer.error("premature termination expecting '}' in nested group");
987                                        parseRule(map, rule.getRule(), lexer, newFmt);
988                                }      
989                                lexer.token("}");
990                        } else {
991                                done = false;
992                                while (!done) {
993                                        parseRuleReference(rule, lexer);
994                                        done = !lexer.hasToken(",");
995                                        if (!done)
996                                                lexer.next();
997                                }
998                        }
999                } else if (lexer.hasComment()) {
1000                        rule.setDocumentation(lexer.take().substring(2).trim());
1001                }
1002                if (isSimpleSyntax(rule)) {
1003                  rule.getSourceFirstRep().setVariable(AUTO_VAR_NAME);
1004                  rule.getTargetFirstRep().setVariable(AUTO_VAR_NAME);
1005                  rule.getTargetFirstRep().setTransform(StructureMapTransform.CREATE); // with no parameter - e.g. imply what is to be created
1006                  // no dependencies - imply what is to be done based on types
1007                }
1008                if (newFmt) {
1009                  if (lexer.isConstant()) {
1010                    if (lexer.isStringConstant()) {
1011                      rule.setName(lexer.readConstant("ruleName"));
1012                    } else {
1013                      rule.setName(lexer.take());
1014                    }
1015                  } else {
1016                    if (rule.getSource().size() != 1 || !rule.getSourceFirstRep().hasElement())
1017                      throw lexer.error("Complex rules must have an explicit name");
1018                    if (rule.getSourceFirstRep().hasType())
1019                      rule.setName(rule.getSourceFirstRep().getElement()+"-"+rule.getSourceFirstRep().getType());
1020                    else
1021          rule.setName(rule.getSourceFirstRep().getElement());
1022                  }
1023      lexer.token(";");
1024                }
1025                lexer.skipComments();
1026        }
1027
1028        private boolean isSimpleSyntax(StructureMapGroupRuleComponent rule) {
1029    return 
1030        (rule.getSource().size() == 1 && rule.getSourceFirstRep().hasContext() && rule.getSourceFirstRep().hasElement() && !rule.getSourceFirstRep().hasVariable()) &&
1031        (rule.getTarget().size() == 1 && rule.getTargetFirstRep().hasContext() && rule.getTargetFirstRep().hasElement() && !rule.getTargetFirstRep().hasVariable() && !rule.getTargetFirstRep().hasParameter()) &&
1032        (rule.getDependent().size() == 0 && rule.getRule().size() == 0);
1033  }
1034
1035  private void parseRuleReference(StructureMapGroupRuleComponent rule, FHIRLexer lexer) throws FHIRLexerException {
1036                StructureMapGroupRuleDependentComponent ref = rule.addDependent();
1037                ref.setName(lexer.take());
1038                lexer.token("(");
1039                boolean done = false;
1040                while (!done) {
1041                        ref.addVariable(lexer.take());
1042                        done = !lexer.hasToken(",");
1043                        if (!done)
1044                                lexer.next();
1045                }
1046                lexer.token(")");
1047        }
1048
1049        private void parseSource(StructureMapGroupRuleComponent rule, FHIRLexer lexer) throws FHIRException {
1050                StructureMapGroupRuleSourceComponent source = rule.addSource();
1051                source.setContext(lexer.take());
1052                if (source.getContext().equals("search") && lexer.hasToken("(")) {
1053            source.setContext("@search");
1054      lexer.take();
1055      ExpressionNode node = fpe.parse(lexer);
1056      source.setUserData(MAP_SEARCH_EXPRESSION, node);
1057      source.setElement(node.toString());
1058      lexer.token(")");
1059                } else if (lexer.hasToken(".")) {
1060                        lexer.token(".");
1061                        source.setElement(lexer.take());
1062                }
1063                if (lexer.hasToken(":")) {
1064                  // type and cardinality
1065                  lexer.token(":");
1066                  source.setType(lexer.takeDottedToken());
1067                  if (!lexer.hasToken("as", "first", "last", "not_first", "not_last", "only_one", "default")) {
1068                    source.setMin(lexer.takeInt());
1069                    lexer.token("..");
1070                    source.setMax(lexer.take());
1071                  }
1072                }
1073                if (lexer.hasToken("default")) {
1074                  lexer.token("default");
1075                  source.setDefaultValue(new StringType(lexer.readConstant("default value")));
1076                }
1077                if (Utilities.existsInList(lexer.getCurrent(), "first", "last", "not_first", "not_last", "only_one"))
1078                        source.setListMode(StructureMapSourceListMode.fromCode(lexer.take()));
1079
1080                if (lexer.hasToken("as")) {
1081                        lexer.take();
1082                        source.setVariable(lexer.take());
1083                }
1084                if (lexer.hasToken("where")) {
1085                        lexer.take();
1086                        ExpressionNode node = fpe.parse(lexer);
1087                        source.setUserData(MAP_WHERE_EXPRESSION, node);
1088                        source.setCondition(node.toString());
1089                }
1090                if (lexer.hasToken("check")) {
1091                        lexer.take();
1092                        ExpressionNode node = fpe.parse(lexer);
1093                        source.setUserData(MAP_WHERE_CHECK, node);
1094                        source.setCheck(node.toString());
1095                }
1096    if (lexer.hasToken("log")) {
1097      lexer.take();
1098      ExpressionNode node = fpe.parse(lexer);
1099      source.setUserData(MAP_WHERE_CHECK, node);
1100      source.setLogMessage(node.toString());
1101    }
1102        }
1103
1104        private void parseTarget(StructureMapGroupRuleComponent rule, FHIRLexer lexer) throws FHIRException {
1105                StructureMapGroupRuleTargetComponent target = rule.addTarget();
1106                String start = lexer.take();
1107                if (lexer.hasToken(".")) {
1108            target.setContext(start);
1109            target.setContextType(StructureMapContextType.VARIABLE);
1110            start = null;
1111                        lexer.token(".");
1112                        target.setElement(lexer.take());
1113                }
1114                String name;
1115                boolean isConstant = false;
1116                if (lexer.hasToken("=")) {
1117                  if (start != null)
1118              target.setContext(start);
1119                        lexer.token("=");
1120                        isConstant = lexer.isConstant();
1121                        name = lexer.take();
1122                } else 
1123                  name = start;
1124                
1125                if ("(".equals(name)) {
1126                  // inline fluentpath expression
1127      target.setTransform(StructureMapTransform.EVALUATE);
1128      ExpressionNode node = fpe.parse(lexer);
1129      target.setUserData(MAP_EXPRESSION, node);
1130      target.addParameter().setValue(new StringType(node.toString()));
1131      lexer.token(")");
1132                } else if (lexer.hasToken("(")) {
1133                                target.setTransform(StructureMapTransform.fromCode(name));
1134                                lexer.token("(");
1135                                if (target.getTransform() == StructureMapTransform.EVALUATE) {
1136                                        parseParameter(target, lexer);
1137                                        lexer.token(",");
1138                                        ExpressionNode node = fpe.parse(lexer);
1139                                        target.setUserData(MAP_EXPRESSION, node);
1140                                        target.addParameter().setValue(new StringType(node.toString()));
1141                                } else { 
1142                                        while (!lexer.hasToken(")")) {
1143                                                parseParameter(target, lexer);
1144                                                if (!lexer.hasToken(")"))
1145                                                        lexer.token(",");
1146                                        }       
1147                                }
1148                                lexer.token(")");
1149                } else if (name != null) {
1150                                target.setTransform(StructureMapTransform.COPY);
1151                                if (!isConstant) {
1152                                        String id = name;
1153                                        while (lexer.hasToken(".")) {
1154                                                id = id + lexer.take() + lexer.take();
1155                                        }
1156                                        target.addParameter().setValue(new IdType(id));
1157                                }
1158                                else 
1159                                        target.addParameter().setValue(readConstant(name, lexer));
1160                        }
1161                if (lexer.hasToken("as")) {
1162                        lexer.take();
1163                        target.setVariable(lexer.take());
1164                }
1165                while (Utilities.existsInList(lexer.getCurrent(), "first", "last", "share", "collate")) {
1166                        if (lexer.getCurrent().equals("share")) {
1167                                target.addListMode(StructureMapTargetListMode.SHARE);
1168                                lexer.next();
1169                                target.setListRuleId(lexer.take());
1170                        } else {
1171                                if (lexer.getCurrent().equals("first")) 
1172                                        target.addListMode(StructureMapTargetListMode.FIRST);
1173                                else
1174                                        target.addListMode(StructureMapTargetListMode.LAST);
1175                                lexer.next();
1176                        }
1177                }
1178        }
1179
1180
1181        private void parseParameter(StructureMapGroupRuleTargetComponent target, FHIRLexer lexer) throws FHIRLexerException, FHIRFormatError {
1182                if (!lexer.isConstant()) {
1183                        target.addParameter().setValue(new IdType(lexer.take()));
1184                } else if (lexer.isStringConstant())
1185                        target.addParameter().setValue(new StringType(lexer.readConstant("??")));
1186                else {
1187                        target.addParameter().setValue(readConstant(lexer.take(), lexer));
1188                }
1189        }
1190
1191        private DataType readConstant(String s, FHIRLexer lexer) throws FHIRLexerException {
1192                if (Utilities.isInteger(s))
1193                        return new IntegerType(s);
1194                else if (Utilities.isDecimal(s, false))
1195                        return new DecimalType(s);
1196                else if (Utilities.existsInList(s, "true", "false"))
1197                        return new BooleanType(s.equals("true"));
1198                else 
1199                        return new StringType(lexer.processConstant(s));        
1200        }
1201
1202        public StructureDefinition getTargetType(StructureMap map) throws FHIRException {
1203          boolean found = false;
1204          StructureDefinition res = null;
1205          for (StructureMapStructureComponent uses : map.getStructure()) {
1206            if (uses.getMode() == StructureMapModelMode.TARGET) {
1207              if (found)
1208                throw new FHIRException("Multiple targets found in map "+map.getUrl());
1209              found = true;
1210              res = worker.fetchResource(StructureDefinition.class, uses.getUrl());
1211              if (res == null)
1212                throw new FHIRException("Unable to find "+uses.getUrl()+" referenced from map "+map.getUrl());      
1213            }
1214          }
1215          if (res == null)
1216      throw new FHIRException("No targets found in map "+map.getUrl());
1217          return res;
1218        }
1219
1220        public enum VariableMode {
1221                INPUT, OUTPUT, SHARED
1222        }
1223
1224        public class Variable {
1225                private VariableMode mode;
1226                private String name;
1227                private Base object;
1228                public Variable(VariableMode mode, String name, Base object) {
1229                        super();
1230                        this.mode = mode;
1231                        this.name = name;
1232                        this.object = object;
1233                }
1234                public VariableMode getMode() {
1235                        return mode;
1236                }
1237                public String getName() {
1238                        return name;
1239                }
1240                public Base getObject() {
1241                        return object;
1242                }
1243    public String summary() {
1244      if (object == null) 
1245        return null;
1246      else if (object instanceof PrimitiveType)
1247        return name+": \""+((PrimitiveType) object).asStringValue()+'"';
1248      else
1249        return name+": ("+object.fhirType()+")";
1250    }
1251        }
1252
1253        public class Variables {
1254                private List<Variable> list = new ArrayList<Variable>();
1255
1256                public void add(VariableMode mode, String name, Base object) {
1257                        Variable vv = null;
1258                        for (Variable v : list) 
1259                                if ((v.mode == mode) && v.getName().equals(name))
1260                                        vv = v;
1261                        if (vv != null)
1262                                list.remove(vv);
1263                        list.add(new Variable(mode, name, object));
1264                }
1265
1266                public Variables copy() {
1267                        Variables result = new Variables();
1268                        result.list.addAll(list);
1269                        return result;
1270                }
1271
1272                public Base get(VariableMode mode, String name) {
1273                        for (Variable v : list) 
1274                                if ((v.mode == mode) && v.getName().equals(name))
1275                                        return v.getObject();
1276                        return null;
1277                }
1278
1279            public String summary() {
1280              CommaSeparatedStringBuilder s = new CommaSeparatedStringBuilder();
1281              CommaSeparatedStringBuilder t = new CommaSeparatedStringBuilder();
1282              CommaSeparatedStringBuilder sh = new CommaSeparatedStringBuilder();
1283              for (Variable v : list)
1284                switch(v.mode) {
1285                case INPUT:
1286                  s.append(v.summary());
1287                  break;
1288                case OUTPUT:
1289                  t.append(v.summary());
1290                  break;
1291                case SHARED:
1292                  sh.append(v.summary());
1293                  break;
1294                }
1295              return "source variables ["+s.toString()+"], target variables ["+t.toString()+"], shared variables ["+sh.toString()+"]";
1296            }
1297            
1298        }
1299
1300        public class TransformContext {
1301                private Object appInfo;
1302
1303                public TransformContext(Object appInfo) {
1304                        super();
1305                        this.appInfo = appInfo;
1306                }
1307
1308                public Object getAppInfo() {
1309                        return appInfo;
1310                }
1311
1312        }
1313
1314        private void log(String cnt) {
1315          if (services != null)
1316            services.log(cnt);
1317          else
1318            System.out.println(cnt);
1319        }
1320
1321        /**
1322         * Given an item, return all the children that conform to the pattern described in name
1323         * 
1324         * Possible patterns:
1325         *  - a simple name (which may be the base of a name with [] e.g. value[x])
1326         *  - a name with a type replacement e.g. valueCodeableConcept
1327         *  - * which means all children
1328         *  - ** which means all descendents
1329         *  
1330         * @param item
1331         * @param name
1332         * @param result
1333         * @throws FHIRException 
1334         */
1335        protected void getChildrenByName(Base item, String name, List<Base> result) throws FHIRException {
1336                for (Base v : item.listChildrenByName(name, true))
1337                        if (v != null)
1338                                result.add(v);
1339        }
1340
1341        public void transform(Object appInfo, Base source, StructureMap map, Base target) throws FHIRException {
1342                TransformContext context = new TransformContext(appInfo);
1343    log("Start Transform "+map.getUrl());
1344    StructureMapGroupComponent g = map.getGroup().get(0);
1345
1346                Variables vars = new Variables();
1347                vars.add(VariableMode.INPUT, getInputName(g, StructureMapInputMode.SOURCE, "source"), source);
1348                if (target != null)
1349                vars.add(VariableMode.OUTPUT, getInputName(g, StructureMapInputMode.TARGET, "target"), target);
1350                else if (getInputName(g, StructureMapInputMode.TARGET, null) != null) {
1351                  String type = getInputType(g, StructureMapInputMode.TARGET);
1352                  throw new Error("not handled yet: creating a type of "+type);
1353                }
1354
1355    executeGroup("", context, map, vars, g, true);
1356    if (target instanceof Element)
1357      ((Element) target).sort();
1358        }
1359
1360        private String getInputType(StructureMapGroupComponent g, StructureMapInputMode mode) {
1361    String type = null;
1362    for (StructureMapGroupInputComponent inp : g.getInput()) {
1363      if (inp.getMode() == mode)
1364        if (type != null)
1365          throw new DefinitionException("This engine does not support multiple source inputs");
1366        else
1367          type = inp.getType();
1368    }
1369    return type;
1370  }
1371
1372  private String getInputName(StructureMapGroupComponent g, StructureMapInputMode mode, String def) throws DefinitionException {
1373          String name = null;
1374    for (StructureMapGroupInputComponent inp : g.getInput()) {
1375      if (inp.getMode() == mode)
1376        if (name != null)
1377          throw new DefinitionException("This engine does not support multiple source inputs");
1378        else
1379          name = inp.getName();
1380    }
1381    return name == null ? def : name;
1382        }
1383
1384        private void executeGroup(String indent, TransformContext context, StructureMap map, Variables vars, StructureMapGroupComponent group, boolean atRoot) throws FHIRException {
1385                log(indent+"Group : "+group.getName()+"; vars = "+vars.summary());
1386    // todo: check inputs
1387                if (group.hasExtends()) {
1388                  ResolvedGroup rg = resolveGroupReference(map, group, group.getExtends());
1389                  executeGroup(indent+" ", context, rg.targetMap, vars, rg.target, false); 
1390                }
1391                  
1392                for (StructureMapGroupRuleComponent r : group.getRule()) {
1393                        executeRule(indent+"  ", context, map, vars, group, r, atRoot);
1394                }
1395        }
1396
1397        private void executeRule(String indent, TransformContext context, StructureMap map, Variables vars, StructureMapGroupComponent group, StructureMapGroupRuleComponent rule, boolean atRoot) throws FHIRException {
1398                log(indent+"rule : "+rule.getName()+"; vars = "+vars.summary());
1399                Variables srcVars = vars.copy();
1400                if (rule.getSource().size() != 1)
1401                        throw new FHIRException("Rule \""+rule.getName()+"\": not handled yet");
1402                List<Variables> source = processSource(rule.getName(), context, srcVars, rule.getSource().get(0), map.getUrl(), indent);
1403                if (source != null) {
1404                        for (Variables v : source) {
1405                                for (StructureMapGroupRuleTargetComponent t : rule.getTarget()) {
1406                                        processTarget(rule.getName(), context, v, map, group, t, rule.getSource().size() == 1 ? rule.getSourceFirstRep().getVariable() : null, atRoot, vars);
1407                                }
1408                                if (rule.hasRule()) {
1409                                        for (StructureMapGroupRuleComponent childrule : rule.getRule()) {
1410                                                executeRule(indent +"  ", context, map, v, group, childrule, false);
1411                                        }
1412                                } else if (rule.hasDependent()) {
1413                                        for (StructureMapGroupRuleDependentComponent dependent : rule.getDependent()) {
1414                                                executeDependency(indent+"  ", context, map, v, group, dependent);
1415                                        }
1416                                } else if (rule.getSource().size() == 1 && rule.getSourceFirstRep().hasVariable() && rule.getTarget().size() == 1 && rule.getTargetFirstRep().hasVariable() && rule.getTargetFirstRep().getTransform() == StructureMapTransform.CREATE && !rule.getTargetFirstRep().hasParameter()) {
1417                                  // simple inferred, map by type
1418                                  System.out.println(v.summary());
1419                                  Base src = v.get(VariableMode.INPUT, rule.getSourceFirstRep().getVariable());
1420                                  Base tgt = v.get(VariableMode.OUTPUT, rule.getTargetFirstRep().getVariable());
1421                                  String srcType = src.fhirType();
1422                                  String tgtType = tgt.fhirType();
1423                                  ResolvedGroup defGroup = resolveGroupByTypes(map, rule.getName(), group, srcType, tgtType);
1424                            Variables vdef = new Variables();
1425          vdef.add(VariableMode.INPUT, defGroup.target.getInput().get(0).getName(), src);
1426          vdef.add(VariableMode.OUTPUT, defGroup.target.getInput().get(1).getName(), tgt);
1427                                  executeGroup(indent+"  ", context, defGroup.targetMap, vdef, defGroup.target, false);
1428                                }
1429                        }
1430                }
1431        }
1432
1433  private void executeDependency(String indent, TransformContext context, StructureMap map, Variables vin, StructureMapGroupComponent group, StructureMapGroupRuleDependentComponent dependent) throws FHIRException {
1434          ResolvedGroup rg = resolveGroupReference(map, group, dependent.getName());
1435
1436                if (rg.target.getInput().size() != dependent.getVariable().size()) {
1437                        throw new FHIRException("Rule '"+dependent.getName()+"' has "+Integer.toString(rg.target.getInput().size())+" but the invocation has "+Integer.toString(dependent.getVariable().size())+" variables");
1438                }
1439                Variables v = new Variables();
1440                for (int i = 0; i < rg.target.getInput().size(); i++) {
1441                        StructureMapGroupInputComponent input = rg.target.getInput().get(i);
1442                        StringType rdp = dependent.getVariable().get(i);
1443      String var = rdp.asStringValue();
1444                        VariableMode mode = input.getMode() == StructureMapInputMode.SOURCE ? VariableMode.INPUT :   VariableMode.OUTPUT; 
1445                        Base vv = vin.get(mode, var);
1446      if (vv == null && mode == VariableMode.INPUT) //* once source, always source. but target can be treated as source at user convenient
1447        vv = vin.get(VariableMode.OUTPUT, var);
1448                        if (vv == null)
1449                                throw new FHIRException("Rule '"+dependent.getName()+"' "+mode.toString()+" variable '"+input.getName()+"' named as '"+var+"' has no value (vars = "+vin.summary()+")");
1450                        v.add(mode, input.getName(), vv);       
1451                }
1452                executeGroup(indent+"  ", context, rg.targetMap, v, rg.target, false);
1453        }
1454
1455  private String determineTypeFromSourceType(StructureMap map, StructureMapGroupComponent source, Base base, String[] types) throws FHIRException {
1456    String type = base.fhirType();
1457    String kn = "type^"+type;
1458    if (source.hasUserData(kn))
1459      return source.getUserString(kn);
1460    
1461    ResolvedGroup res = new ResolvedGroup();
1462    res.targetMap = null;
1463    res.target = null;
1464    for (StructureMapGroupComponent grp : map.getGroup()) {
1465      if (matchesByType(map, grp, type)) {
1466        if (res.targetMap == null) {
1467          res.targetMap = map;
1468          res.target = grp;
1469        } else 
1470          throw new FHIRException("Multiple possible matches looking for default rule for '"+type+"'");
1471      }
1472    }
1473    if (res.targetMap != null) {
1474      String result = getActualType(res.targetMap, res.target.getInput().get(1).getType());
1475      source.setUserData(kn, result);
1476      return result;
1477    }
1478
1479    for (UriType imp : map.getImport()) {
1480      List<StructureMap> impMapList = findMatchingMaps(imp.getValue());
1481      if (impMapList.size() == 0)
1482        throw new FHIRException("Unable to find map(s) for "+imp.getValue());
1483      for (StructureMap impMap : impMapList) {
1484        if (!impMap.getUrl().equals(map.getUrl())) {
1485          for (StructureMapGroupComponent grp : impMap.getGroup()) {
1486            if (matchesByType(impMap, grp, type)) {
1487              if (res.targetMap == null) {
1488                res.targetMap = impMap;
1489                res.target = grp;
1490              } else 
1491                throw new FHIRException("Multiple possible matches for default rule for '"+type+"' in "+res.targetMap.getUrl()+" ("+res.target.getName()+") and "+impMap.getUrl()+" ("+grp.getName()+")");
1492            }
1493          }
1494        }
1495      }
1496    }
1497    if (res.target == null)
1498      throw new FHIRException("No matches found for default rule for '"+type+"' from "+map.getUrl());
1499    String result = getActualType(res.targetMap, res.target.getInput().get(1).getType()); // should be .getType, but R2...
1500    source.setUserData(kn, result);
1501    return result;
1502  }
1503
1504  private List<StructureMap> findMatchingMaps(String value) {
1505    List<StructureMap> res = new ArrayList<StructureMap>();
1506    if (value.contains("*")) {
1507      for (StructureMap sm : worker.listTransforms()) {
1508        if (urlMatches(value, sm.getUrl())) {
1509          res.add(sm); 
1510        }
1511      }
1512    } else {
1513      StructureMap sm = worker.getTransform(value);
1514      if (sm != null)
1515        res.add(sm); 
1516    }
1517    Set<String> check = new HashSet<String>();
1518    for (StructureMap sm : res) {
1519      if (check.contains(sm.getUrl()))
1520        throw new Error("duplicate");
1521      else
1522        check.add(sm.getUrl());
1523    }
1524    return res;
1525  }
1526
1527  private boolean urlMatches(String mask, String url) {
1528    return url.length() > mask.length() && url.startsWith(mask.substring(0, mask.indexOf("*"))) && url.endsWith(mask.substring(mask.indexOf("*")+1)) ;
1529  }
1530
1531  private ResolvedGroup resolveGroupByTypes(StructureMap map, String ruleid, StructureMapGroupComponent source, String srcType, String tgtType) throws FHIRException {
1532    String kn = "types^"+srcType+":"+tgtType;
1533    if (source.hasUserData(kn))
1534      return (ResolvedGroup) source.getUserData(kn);
1535    
1536    ResolvedGroup res = new ResolvedGroup();
1537    res.targetMap = null;
1538    res.target = null;
1539    for (StructureMapGroupComponent grp : map.getGroup()) {
1540      if (matchesByType(map, grp, srcType, tgtType)) {
1541        if (res.targetMap == null) {
1542          res.targetMap = map;
1543          res.target = grp;
1544        } else 
1545          throw new FHIRException("Multiple possible matches looking for rule for '"+srcType+"/"+tgtType+"', from rule '"+ruleid+"'");
1546      }
1547    }
1548    if (res.targetMap != null) {
1549      source.setUserData(kn, res);
1550      return res;
1551    }
1552
1553    for (UriType imp : map.getImport()) {
1554      List<StructureMap> impMapList = findMatchingMaps(imp.getValue());
1555      if (impMapList.size() == 0)
1556        throw new FHIRException("Unable to find map(s) for "+imp.getValue());
1557      for (StructureMap impMap : impMapList) {
1558        if (!impMap.getUrl().equals(map.getUrl())) {
1559          for (StructureMapGroupComponent grp : impMap.getGroup()) {
1560            if (matchesByType(impMap, grp, srcType, tgtType)) {
1561              if (res.targetMap == null) {
1562                res.targetMap = impMap;
1563                res.target = grp;
1564              } else 
1565                throw new FHIRException("Multiple possible matches for rule for '"+srcType+"/"+tgtType+"' in "+res.targetMap.getUrl()+" and "+impMap.getUrl()+", from rule '"+ruleid+"'");
1566            }
1567          }
1568        }
1569      }
1570    }
1571    if (res.target == null)
1572      throw new FHIRException("No matches found for rule for '"+srcType+" to "+tgtType+"' from "+map.getUrl()+", from rule '"+ruleid+"'");
1573    source.setUserData(kn, res);
1574    return res;
1575  }
1576
1577
1578  private boolean matchesByType(StructureMap map, StructureMapGroupComponent grp, String type) throws FHIRException {
1579    if (grp.getTypeMode() != StructureMapGroupTypeMode.TYPEANDTYPES)
1580      return false;
1581    if (grp.getInput().size() != 2 || grp.getInput().get(0).getMode() != StructureMapInputMode.SOURCE || grp.getInput().get(1).getMode() != StructureMapInputMode.TARGET)
1582      return false;
1583    return matchesType(map, type, grp.getInput().get(0).getType());
1584  }
1585
1586  private boolean matchesByType(StructureMap map, StructureMapGroupComponent grp, String srcType, String tgtType) throws FHIRException {
1587    if (grp.getTypeMode() == StructureMapGroupTypeMode.NONE)
1588      return false;
1589    if (grp.getInput().size() != 2 || grp.getInput().get(0).getMode() != StructureMapInputMode.SOURCE || grp.getInput().get(1).getMode() != StructureMapInputMode.TARGET)
1590      return false;
1591    if (!grp.getInput().get(0).hasType() || !grp.getInput().get(1).hasType())
1592      return false;
1593    return matchesType(map, srcType, grp.getInput().get(0).getType()) && matchesType(map, tgtType, grp.getInput().get(1).getType());
1594  }
1595
1596  private boolean matchesType(StructureMap map, String actualType, String statedType) throws FHIRException {
1597    // check the aliases
1598    for (StructureMapStructureComponent imp : map.getStructure()) {
1599      if (imp.hasAlias() && statedType.equals(imp.getAlias())) {
1600        StructureDefinition sd = worker.fetchResource(StructureDefinition.class, imp.getUrl());
1601        if (sd != null)
1602          statedType = sd.getType();
1603        break;
1604      }
1605    }
1606    
1607    if (Utilities.isAbsoluteUrl(actualType)) {
1608      StructureDefinition sd = worker.fetchResource(StructureDefinition.class, actualType);
1609      if (sd != null)
1610        actualType = sd.getType();
1611    }
1612    if (Utilities.isAbsoluteUrl(statedType)) {
1613      StructureDefinition sd = worker.fetchResource(StructureDefinition.class, statedType);
1614      if (sd != null)
1615        statedType = sd.getType();
1616    }
1617    return actualType.equals(statedType);
1618  }
1619
1620  private String getActualType(StructureMap map, String statedType) throws FHIRException {
1621    // check the aliases
1622    for (StructureMapStructureComponent imp : map.getStructure()) {
1623      if (imp.hasAlias() && statedType.equals(imp.getAlias())) {
1624        StructureDefinition sd = worker.fetchResource(StructureDefinition.class, imp.getUrl());
1625        if (sd == null)
1626          throw new FHIRException("Unable to resolve structure "+imp.getUrl());
1627        return sd.getId(); // should be sd.getType(), but R2...
1628      }
1629    }
1630    return statedType;
1631  }
1632
1633
1634  private ResolvedGroup resolveGroupReference(StructureMap map, StructureMapGroupComponent source, String name) throws FHIRException {
1635    String kn = "ref^"+name;
1636    if (source.hasUserData(kn))
1637      return (ResolvedGroup) source.getUserData(kn);
1638    
1639          ResolvedGroup res = new ResolvedGroup();
1640    res.targetMap = null;
1641    res.target = null;
1642    for (StructureMapGroupComponent grp : map.getGroup()) {
1643      if (grp.getName().equals(name)) {
1644        if (res.targetMap == null) {
1645          res.targetMap = map;
1646          res.target = grp;
1647        } else 
1648          throw new FHIRException("Multiple possible matches for rule '"+name+"'");
1649      }
1650    }
1651    if (res.targetMap != null) {
1652      source.setUserData(kn, res);
1653      return res;
1654    }
1655
1656    for (UriType imp : map.getImport()) {
1657      List<StructureMap> impMapList = findMatchingMaps(imp.getValue());
1658      if (impMapList.size() == 0)
1659        throw new FHIRException("Unable to find map(s) for "+imp.getValue());
1660      for (StructureMap impMap : impMapList) {
1661        if (!impMap.getUrl().equals(map.getUrl())) {
1662          for (StructureMapGroupComponent grp : impMap.getGroup()) {
1663            if (grp.getName().equals(name)) {
1664              if (res.targetMap == null) {
1665                res.targetMap = impMap;
1666                res.target = grp;
1667              } else 
1668                throw new FHIRException("Multiple possible matches for rule group '"+name+"' in "+
1669                 res.targetMap.getUrl()+"#"+res.target.getName()+" and "+
1670                 impMap.getUrl()+"#"+grp.getName());
1671            }
1672          }
1673        }
1674      }
1675    }
1676    if (res.target == null)
1677      throw new FHIRException("No matches found for rule '"+name+"'. Reference found in "+map.getUrl());
1678    source.setUserData(kn, res);
1679    return res;
1680  }
1681
1682  private List<Variables> processSource(String ruleId, TransformContext context, Variables vars, StructureMapGroupRuleSourceComponent src, String pathForErrors, String indent) throws FHIRException {
1683    List<Base> items;
1684    if (src.getContext().equals("@search")) {
1685      ExpressionNode expr = (ExpressionNode) src.getUserData(MAP_SEARCH_EXPRESSION);
1686      if (expr == null) {
1687        expr = fpe.parse(src.getElement());
1688        src.setUserData(MAP_SEARCH_EXPRESSION, expr);
1689      }
1690      String search = fpe.evaluateToString(vars, null, null, new StringType(), expr); // string is a holder of nothing to ensure that variables are processed correctly 
1691      items = services.performSearch(context.appInfo, search);
1692    } else {
1693      items = new ArrayList<Base>();
1694      Base b = vars.get(VariableMode.INPUT, src.getContext());
1695      if (b == null)
1696        throw new FHIRException("Unknown input variable "+src.getContext()+" in "+pathForErrors+" rule "+ruleId+" (vars = "+vars.summary()+")");
1697
1698      if (!src.hasElement()) 
1699        items.add(b);
1700      else { 
1701        getChildrenByName(b, src.getElement(), items);
1702        if (items.size() == 0 && src.hasDefaultValue())
1703          items.add(src.getDefaultValue());
1704      }
1705    }
1706    
1707                if (src.hasType()) {
1708            List<Base> remove = new ArrayList<Base>();
1709            for (Base item : items) {
1710              if (item != null && !isType(item, src.getType())) {
1711                remove.add(item);
1712              }
1713            }
1714            items.removeAll(remove);
1715                }
1716
1717    if (src.hasCondition()) {
1718      ExpressionNode expr = (ExpressionNode) src.getUserData(MAP_WHERE_EXPRESSION);
1719      if (expr == null) {
1720        expr = fpe.parse(src.getCondition());
1721        //        fpe.check(context.appInfo, ??, ??, expr)
1722        src.setUserData(MAP_WHERE_EXPRESSION, expr);
1723      }
1724      List<Base> remove = new ArrayList<Base>();
1725      for (Base item : items) {
1726        if (!fpe.evaluateToBoolean(vars, null, null, item, expr)) {
1727          log(indent+"  condition ["+src.getCondition()+"] for "+item.toString()+" : false");
1728          remove.add(item);
1729        } else
1730          log(indent+"  condition ["+src.getCondition()+"] for "+item.toString()+" : true");
1731      }
1732      items.removeAll(remove);
1733    }
1734
1735    if (src.hasCheck()) {
1736      ExpressionNode expr = (ExpressionNode) src.getUserData(MAP_WHERE_CHECK);
1737      if (expr == null) {
1738        expr = fpe.parse(src.getCheck());
1739        //        fpe.check(context.appInfo, ??, ??, expr)
1740        src.setUserData(MAP_WHERE_CHECK, expr);
1741      }
1742      List<Base> remove = new ArrayList<Base>();
1743      for (Base item : items) {
1744        if (!fpe.evaluateToBoolean(vars, null, null, item, expr))
1745          throw new FHIRException("Rule \""+ruleId+"\": Check condition failed");
1746      }
1747    } 
1748
1749    if (src.hasLogMessage()) {
1750      ExpressionNode expr = (ExpressionNode) src.getUserData(MAP_WHERE_LOG);
1751      if (expr == null) {
1752        expr = fpe.parse(src.getLogMessage());
1753        //        fpe.check(context.appInfo, ??, ??, expr)
1754        src.setUserData(MAP_WHERE_LOG, expr);
1755      }
1756      CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder();
1757      for (Base item : items) 
1758        b.appendIfNotNull(fpe.evaluateToString(vars, null, null, item, expr));
1759      if (b.length() > 0)
1760        services.log(b.toString());
1761    } 
1762
1763                
1764                if (src.hasListMode() && !items.isEmpty()) {
1765                  switch (src.getListMode()) {
1766                  case FIRST:
1767                    Base bt = items.get(0);
1768        items.clear();
1769        items.add(bt);
1770                    break;
1771                  case NOTFIRST: 
1772        if (items.size() > 0)
1773          items.remove(0);
1774        break;
1775                  case LAST:
1776        bt = items.get(items.size()-1);
1777        items.clear();
1778        items.add(bt);
1779        break;
1780                  case NOTLAST: 
1781        if (items.size() > 0)
1782          items.remove(items.size()-1);
1783        break;
1784                  case ONLYONE:
1785                    if (items.size() > 1)
1786          throw new FHIRException("Rule \""+ruleId+"\": Check condition failed: the collection has more than one item");
1787        break;
1788      case NULL:
1789                  }
1790                }
1791                List<Variables> result = new ArrayList<Variables>();
1792                for (Base r : items) {
1793                        Variables v = vars.copy();
1794                        if (src.hasVariable())
1795                                v.add(VariableMode.INPUT, src.getVariable(), r);
1796                        result.add(v); 
1797                }
1798                return result;
1799        }
1800
1801
1802        private boolean isType(Base item, String type) {
1803    if (type.equals(item.fhirType()))
1804      return true;
1805    return false;
1806  }
1807
1808  private void processTarget(String ruleId, TransformContext context, Variables vars, StructureMap map, StructureMapGroupComponent group, StructureMapGroupRuleTargetComponent tgt, String srcVar, boolean atRoot, Variables sharedVars) throws FHIRException {
1809          Base dest = null;
1810          if (tgt.hasContext()) {
1811                dest = vars.get(VariableMode.OUTPUT, tgt.getContext());
1812                if (dest == null)
1813                  throw new FHIRException("Rule \""+ruleId+"\": target context not known: "+tgt.getContext());
1814                if (!tgt.hasElement())
1815                  throw new FHIRException("Rule \""+ruleId+"\": Not supported yet");
1816          }
1817          Base v = null;
1818          if (tgt.hasTransform()) {
1819            v = runTransform(ruleId, context, map, group, tgt, vars, dest, tgt.getElement(), srcVar, atRoot);
1820            if (v != null && dest != null)
1821              v = dest.setProperty(tgt.getElement().hashCode(), tgt.getElement(), v); // reset v because some implementations may have to rewrite v when setting the value
1822          } else if (dest != null) { 
1823                if (tgt.hasListMode(StructureMapTargetListMode.SHARE)) {
1824                        v = sharedVars.get(VariableMode.SHARED, tgt.getListRuleId());
1825                        if (v == null) {
1826                                v = dest.makeProperty(tgt.getElement().hashCode(), tgt.getElement());
1827                                sharedVars.add(VariableMode.SHARED, tgt.getListRuleId(), v);                            
1828                        }
1829                } else {
1830                        v = dest.makeProperty(tgt.getElement().hashCode(), tgt.getElement());
1831                }
1832          }
1833          if (tgt.hasVariable() && v != null)
1834            vars.add(VariableMode.OUTPUT, tgt.getVariable(), v);
1835        }
1836
1837        private Base runTransform(String ruleId, TransformContext context, StructureMap map, StructureMapGroupComponent group, StructureMapGroupRuleTargetComponent tgt, Variables vars, Base dest, String element, String srcVar, boolean root) throws FHIRException {
1838          try {
1839            switch (tgt.getTransform()) {
1840            case CREATE :
1841              String tn;
1842              if (tgt.getParameter().isEmpty()) {
1843                // we have to work out the type. First, we see if there is a single type for the target. If there is, we use that
1844                String[] types = dest.getTypesForProperty(element.hashCode(), element);
1845                if (types.length == 1 && !"*".equals(types[0]) && !types[0].equals("Resource"))
1846                  tn = types[0];
1847                else if (srcVar != null) {
1848                  tn = determineTypeFromSourceType(map, group, vars.get(VariableMode.INPUT, srcVar), types);
1849                } else
1850                  throw new Error("Cannot determine type implicitly because there is no single input variable");
1851              } else {
1852                tn = getParamStringNoNull(vars, tgt.getParameter().get(0), tgt.toString());
1853                // ok, now we resolve the type name against the import statements 
1854                for (StructureMapStructureComponent uses : map.getStructure()) {
1855                  if (uses.getMode() == StructureMapModelMode.TARGET && uses.hasAlias() && tn.equals(uses.getAlias())) {
1856                    tn = uses.getUrl();
1857                    break;
1858                  }
1859                }
1860              }
1861              Base res = services != null ? services.createType(context.getAppInfo(), tn) : ResourceFactory.createResourceOrType(tn);
1862              if (res.isResource() && !res.fhirType().equals("Parameters")) {
1863//              res.setIdBase(tgt.getParameter().size() > 1 ? getParamString(vars, tgt.getParameter().get(0)) : UUID.randomUUID().toString().toLowerCase());
1864                if (services != null) 
1865                  res = services.createResource(context.getAppInfo(), res, root);
1866              }
1867              if (tgt.hasUserData("profile"))
1868                res.setUserData("profile", tgt.getUserData("profile"));
1869              return res;
1870            case COPY : 
1871              return getParam(vars, tgt.getParameter().get(0));
1872            case EVALUATE :
1873              ExpressionNode expr = (ExpressionNode) tgt.getUserData(MAP_EXPRESSION);
1874              if (expr == null) {
1875                expr = fpe.parse(getParamStringNoNull(vars, tgt.getParameter().get(0), tgt.toString()));
1876                tgt.setUserData(MAP_WHERE_EXPRESSION, expr);
1877              }
1878              List<Base> v = fpe.evaluate(vars, null, null, tgt.getParameter().size() == 2 ? getParam(vars, tgt.getParameter().get(0)) : new BooleanType(false), expr);
1879              if (v.size() == 0)
1880                return null;
1881              else if (v.size() != 1)
1882                throw new FHIRException("Rule \""+ruleId+"\": Evaluation of "+expr.toString()+" returned "+Integer.toString(v.size())+" objects");
1883              else
1884                return v.get(0);
1885
1886            case TRUNCATE : 
1887              String src = getParamString(vars, tgt.getParameter().get(0));
1888              String len = getParamStringNoNull(vars, tgt.getParameter().get(1), tgt.toString());
1889              if (Utilities.isInteger(len)) {
1890                int l = Integer.parseInt(len);
1891                if (src.length() > l)
1892                  src = src.substring(0, l);
1893              }
1894              return new StringType(src);
1895            case ESCAPE : 
1896              throw new Error("Rule \""+ruleId+"\": Transform "+tgt.getTransform().toCode()+" not supported yet");
1897            case CAST :
1898        src = getParamString(vars, tgt.getParameter().get(0));
1899        if (tgt.getParameter().size() == 1)
1900          throw new FHIRException("Implicit type parameters on cast not yet supported");
1901        String t = getParamString(vars, tgt.getParameter().get(1));
1902        if (t.equals("string"))
1903          return new StringType(src);
1904        else
1905          throw new FHIRException("cast to "+t+" not yet supported");
1906            case APPEND : 
1907        StringBuilder sb = new StringBuilder(getParamString(vars, tgt.getParameter().get(0)));
1908        for (int i = 1; i < tgt.getParameter().size(); i++)
1909          sb.append(getParamString(vars, tgt.getParameter().get(i)));
1910        return new StringType(sb.toString());
1911            case TRANSLATE : 
1912              return translate(context, map, vars, tgt.getParameter());
1913            case REFERENCE :
1914              Base b = getParam(vars, tgt.getParameter().get(0));
1915              if (b == null)
1916                throw new FHIRException("Rule \""+ruleId+"\": Unable to find parameter "+((IdType) tgt.getParameter().get(0).getValue()).asStringValue());
1917              if (!b.isResource())
1918                throw new FHIRException("Rule \""+ruleId+"\": Transform engine cannot point at an element of type "+b.fhirType());
1919              else {
1920                String id = b.getIdBase();
1921                if (id == null) {
1922                  id = UUID.randomUUID().toString().toLowerCase();
1923                  b.setIdBase(id);
1924                }
1925          return new StringType(b.fhirType()+"/"+id);
1926              }
1927            case DATEOP :
1928              throw new Error("Rule \""+ruleId+"\": Transform "+tgt.getTransform().toCode()+" not supported yet");
1929            case UUID :
1930              return new IdType(UUID.randomUUID().toString());
1931            case POINTER :
1932              b = getParam(vars, tgt.getParameter().get(0));
1933              if (b instanceof Resource)
1934                return new UriType("urn:uuid:"+((Resource) b).getId());
1935              else
1936                throw new FHIRException("Rule \""+ruleId+"\": Transform engine cannot point at an element of type "+b.fhirType());
1937            case CC:
1938              CodeableConcept cc = new CodeableConcept();
1939              cc.addCoding(buildCoding(getParamStringNoNull(vars, tgt.getParameter().get(0), tgt.toString()), getParamStringNoNull(vars, tgt.getParameter().get(1), tgt.toString())));
1940              return cc;
1941            case C: 
1942              Coding c = buildCoding(getParamStringNoNull(vars, tgt.getParameter().get(0), tgt.toString()), getParamStringNoNull(vars, tgt.getParameter().get(1), tgt.toString()));
1943              return c;
1944            default:
1945              throw new Error("Rule \""+ruleId+"\": Transform Unknown: "+tgt.getTransform().toCode());
1946            }
1947          } catch (Exception e) {
1948            throw new FHIRException("Exception executing transform "+tgt.toString()+" on Rule \""+ruleId+"\": "+e.getMessage(), e);
1949          }
1950        }
1951
1952
1953  private Coding buildCoding(String uri, String code) throws FHIRException {
1954          // if we can get this as a valueSet, we will
1955          String system = null;
1956          String display = null;
1957          ValueSet vs = Utilities.noString(uri) ? null : worker.fetchResourceWithException(ValueSet.class, uri);
1958          if (vs != null) {
1959            ValueSetExpansionOutcome vse = worker.expandVS(vs, true, false);
1960            if (vse.getError() != null)
1961              throw new FHIRException(vse.getError());
1962            CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder();
1963            for (ValueSetExpansionContainsComponent t : vse.getValueset().getExpansion().getContains()) {
1964              if (t.hasCode())
1965                b.append(t.getCode());
1966              if (code.equals(t.getCode()) && t.hasSystem()) {
1967                system = t.getSystem();
1968          display = t.getDisplay();
1969                break;
1970              }
1971        if (code.equalsIgnoreCase(t.getDisplay()) && t.hasSystem()) {
1972          system = t.getSystem();
1973          display = t.getDisplay();
1974          break;
1975        }
1976            }
1977            if (system == null)
1978              throw new FHIRException("The code '"+code+"' is not in the value set '"+uri+"' (valid codes: "+b.toString()+"; also checked displays)");
1979          } else
1980            system = uri;
1981          ValidationResult vr = worker.validateCode(terminologyServiceOptions, system, code, null);
1982          if (vr != null && vr.getDisplay() != null)
1983            display = vr.getDisplay();
1984   return new Coding().setSystem(system).setCode(code).setDisplay(display);
1985  }
1986
1987
1988  private String getParamStringNoNull(Variables vars, StructureMapGroupRuleTargetParameterComponent parameter, String message) throws FHIRException {
1989    Base b = getParam(vars, parameter);
1990    if (b == null)
1991      throw new FHIRException("Unable to find a value for "+parameter.toString()+". Context: "+message);
1992    if (!b.hasPrimitiveValue())
1993      throw new FHIRException("Found a value for "+parameter.toString()+", but it has a type of "+b.fhirType()+" and cannot be treated as a string. Context: "+message);
1994    return b.primitiveValue();
1995  }
1996
1997  private String getParamString(Variables vars, StructureMapGroupRuleTargetParameterComponent parameter) throws DefinitionException {
1998                Base b = getParam(vars, parameter);
1999                if (b == null || !b.hasPrimitiveValue())
2000                        return null;
2001                return b.primitiveValue();
2002        }
2003
2004
2005        private Base getParam(Variables vars, StructureMapGroupRuleTargetParameterComponent parameter) throws DefinitionException {
2006                DataType p = parameter.getValue();
2007                if (!(p instanceof IdType))
2008                        return p;
2009                else { 
2010                        String n = ((IdType) p).asStringValue();
2011      Base b = vars.get(VariableMode.INPUT, n);
2012                        if (b == null)
2013                                b = vars.get(VariableMode.OUTPUT, n);
2014                        if (b == null)
2015        throw new DefinitionException("Variable "+n+" not found ("+vars.summary()+")");
2016                        return b;
2017                }
2018        }
2019
2020
2021        private Base translate(TransformContext context, StructureMap map, Variables vars, List<StructureMapGroupRuleTargetParameterComponent> parameter) throws FHIRException {
2022                Base src = getParam(vars, parameter.get(0));
2023                String id = getParamString(vars, parameter.get(1));
2024                String fld = parameter.size() > 2 ? getParamString(vars, parameter.get(2)) : null;
2025                return translate(context, map, src, id, fld);
2026        }
2027
2028        private class SourceElementComponentWrapper {
2029          private ConceptMapGroupComponent group;
2030    private SourceElementComponent comp;
2031    public SourceElementComponentWrapper(ConceptMapGroupComponent group, SourceElementComponent comp) {
2032      super();
2033      this.group = group;
2034      this.comp = comp;
2035    }
2036        }
2037        public Base translate(TransformContext context, StructureMap map, Base source, String conceptMapUrl, String fieldToReturn) throws FHIRException {
2038                Coding src = new Coding();
2039                if (source.isPrimitive()) {
2040                        src.setCode(source.primitiveValue());
2041                } else if ("Coding".equals(source.fhirType())) {
2042                        Base[] b = source.getProperty("system".hashCode(), "system", true);
2043                        if (b.length == 1)
2044                                src.setSystem(b[0].primitiveValue());
2045                        b = source.getProperty("code".hashCode(), "code", true);
2046                        if (b.length == 1)
2047                                src.setCode(b[0].primitiveValue());
2048                } else if ("CE".equals(source.fhirType())) {
2049                        Base[] b = source.getProperty("codeSystem".hashCode(), "codeSystem", true);
2050                        if (b.length == 1)
2051                                src.setSystem(b[0].primitiveValue());
2052                        b = source.getProperty("code".hashCode(), "code", true);
2053                        if (b.length == 1)
2054                                src.setCode(b[0].primitiveValue());
2055                } else
2056                        throw new FHIRException("Unable to translate source "+source.fhirType());
2057
2058                String su = conceptMapUrl;
2059                if (conceptMapUrl.equals("http://hl7.org/fhir/ConceptMap/special-oid2uri")) {
2060                        String uri = worker.oid2Uri(src.getCode());
2061                        if (uri == null)
2062                                uri = "urn:oid:"+src.getCode();
2063                        if ("uri".equals(fieldToReturn))
2064                                return new UriType(uri);
2065                        else
2066                                throw new FHIRException("Error in return code");
2067                } else {
2068                        ConceptMap cmap = null;
2069                        if (conceptMapUrl.startsWith("#")) {
2070                                for (Resource r : map.getContained()) {
2071                                        if (r instanceof ConceptMap && ((ConceptMap) r).getId().equals(conceptMapUrl.substring(1))) {
2072                                                cmap = (ConceptMap) r;
2073                                                su = map.getUrl()+"#"+conceptMapUrl;
2074                                        }
2075                                }
2076                                if (cmap == null)
2077                      throw new FHIRException("Unable to translate - cannot find map "+conceptMapUrl);
2078                        } else {
2079                          if (conceptMapUrl.contains("#")) {
2080                            String[] p = conceptMapUrl.split("\\#");
2081                            StructureMap mapU = worker.fetchResource(StructureMap.class, p[0]);  
2082                for (Resource r : mapU.getContained()) {
2083                  if (r instanceof ConceptMap && ((ConceptMap) r).getId().equals(p[1])) {
2084                    cmap = (ConceptMap) r;
2085                    su = conceptMapUrl;
2086                  }
2087                }
2088                          }
2089                          if (cmap == null)
2090                                  cmap = worker.fetchResource(ConceptMap.class, conceptMapUrl);
2091                        }
2092                        Coding outcome = null;
2093                        boolean done = false;
2094                        String message = null;
2095                        if (cmap == null) {
2096                                if (services == null) 
2097                                        message = "No map found for "+conceptMapUrl;
2098                                else {
2099                                        outcome = services.translate(context.appInfo, src, conceptMapUrl);
2100                                        done = true;
2101                                }
2102                        } else {
2103                          List<SourceElementComponentWrapper> list = new ArrayList<SourceElementComponentWrapper>();
2104                          for (ConceptMapGroupComponent g : cmap.getGroup()) {
2105                            for (SourceElementComponent e : g.getElement()) {
2106                                                if (!src.hasSystem() && src.getCode().equals(e.getCode())) 
2107                                list.add(new SourceElementComponentWrapper(g, e));
2108                              else if (src.hasSystem() && src.getSystem().equals(g.getSource()) && src.getCode().equals(e.getCode()))
2109                                list.add(new SourceElementComponentWrapper(g, e));
2110                            }
2111                                }
2112                                if (list.size() == 0)
2113                                        done = true;
2114                                else if (list.get(0).comp.getTarget().size() == 0)
2115                                        message = "Concept map "+su+" found no translation for "+src.getCode();
2116                                else {
2117                                        for (TargetElementComponent tgt : list.get(0).comp.getTarget()) {
2118                                                if (tgt.getRelationship() == null || EnumSet.of( ConceptMapRelationship.RELATEDTO , ConceptMapRelationship.EQUIVALENT, ConceptMapRelationship.BROADER).contains(tgt.getRelationship())) {
2119                                                        if (done) {
2120                                                                message = "Concept map "+su+" found multiple matches for "+src.getCode();
2121                                                                done = false;
2122                                                        } else {
2123                                                                done = true;
2124                                                                outcome = new Coding().setCode(tgt.getCode()).setSystem(list.get(0).group.getTarget());
2125                                                        }
2126                                                }
2127                                        }
2128                                        if (!done)
2129                                                message = "Concept map "+su+" found no usable translation for "+src.getCode();
2130                                }
2131                        }
2132                        if (!done) 
2133                                throw new FHIRException(message);
2134                        if (outcome == null)
2135                                return null;
2136                        if ("code".equals(fieldToReturn))
2137                                return new CodeType(outcome.getCode());
2138                        else
2139                                return outcome; 
2140                }
2141        }
2142
2143
2144        public class PropertyWithType {
2145    private String path;
2146    private Property baseProperty;
2147    private Property profileProperty;
2148          private TypeDetails types;
2149    public PropertyWithType(String path, Property baseProperty, Property profileProperty, TypeDetails types) {
2150      super();
2151      this.baseProperty = baseProperty;
2152      this.profileProperty = profileProperty;
2153      this.path = path;
2154      this.types = types;
2155    }
2156
2157    public TypeDetails getTypes() {
2158      return types;
2159    }
2160    public String getPath() {
2161      return path;
2162    }
2163
2164    public Property getBaseProperty() {
2165      return baseProperty;
2166    }
2167
2168    public void setBaseProperty(Property baseProperty) {
2169      this.baseProperty = baseProperty;
2170    }
2171
2172    public Property getProfileProperty() {
2173      return profileProperty;
2174    }
2175
2176    public void setProfileProperty(Property profileProperty) {
2177      this.profileProperty = profileProperty;
2178    }
2179
2180    public String summary() {
2181      return path;
2182    }
2183    
2184        }
2185        
2186        public class VariableForProfiling {
2187            private VariableMode mode;
2188            private String name;
2189            private PropertyWithType property;
2190            
2191            public VariableForProfiling(VariableMode mode, String name, PropertyWithType property) {
2192              super();
2193              this.mode = mode;
2194              this.name = name;
2195              this.property = property;
2196            }
2197            public VariableMode getMode() {
2198              return mode;
2199            }
2200            public String getName() {
2201              return name;
2202            }
2203      public PropertyWithType getProperty() {
2204        return property;
2205      }
2206      public String summary() {
2207        return name+": "+property.summary();
2208      }      
2209          }
2210
2211  public class VariablesForProfiling {
2212    private List<VariableForProfiling> list = new ArrayList<VariableForProfiling>();
2213    private boolean optional;
2214    private boolean repeating;
2215
2216    public VariablesForProfiling(boolean optional, boolean repeating) {
2217      this.optional = optional;
2218      this.repeating = repeating;
2219    }
2220
2221    public void add(VariableMode mode, String name, String path, Property property, TypeDetails types) {
2222      add(mode, name, new PropertyWithType(path, property, null, types));
2223    }
2224    
2225    public void add(VariableMode mode, String name, String path, Property baseProperty, Property profileProperty, TypeDetails types) {
2226      add(mode, name, new PropertyWithType(path, baseProperty, profileProperty, types));
2227    }
2228    
2229    public void add(VariableMode mode, String name, PropertyWithType property) {
2230      VariableForProfiling vv = null;
2231      for (VariableForProfiling v : list) 
2232        if ((v.mode == mode) && v.getName().equals(name))
2233          vv = v;
2234      if (vv != null)
2235        list.remove(vv);
2236      list.add(new VariableForProfiling(mode, name, property));
2237    }
2238
2239    public VariablesForProfiling copy(boolean optional, boolean repeating) {
2240      VariablesForProfiling result = new VariablesForProfiling(optional, repeating);
2241      result.list.addAll(list);
2242      return result;
2243    }
2244
2245    public VariablesForProfiling copy() {
2246      VariablesForProfiling result = new VariablesForProfiling(optional, repeating);
2247      result.list.addAll(list);
2248      return result;
2249    }
2250
2251    public VariableForProfiling get(VariableMode mode, String name) {
2252      if (mode == null) {
2253        for (VariableForProfiling v : list) 
2254          if ((v.mode == VariableMode.OUTPUT) && v.getName().equals(name))
2255            return v;
2256        for (VariableForProfiling v : list) 
2257          if ((v.mode == VariableMode.INPUT) && v.getName().equals(name))
2258            return v;
2259      }
2260      for (VariableForProfiling v : list) 
2261        if ((v.mode == mode) && v.getName().equals(name))
2262          return v;
2263      return null;
2264    }
2265
2266    public String summary() {
2267      CommaSeparatedStringBuilder s = new CommaSeparatedStringBuilder();
2268      CommaSeparatedStringBuilder t = new CommaSeparatedStringBuilder();
2269      for (VariableForProfiling v : list)
2270        if (v.mode == VariableMode.INPUT)
2271          s.append(v.summary());
2272        else
2273          t.append(v.summary());
2274      return "source variables ["+s.toString()+"], target variables ["+t.toString()+"]";
2275    }
2276  }
2277
2278  public class StructureMapAnalysis {
2279    private List<StructureDefinition> profiles = new ArrayList<StructureDefinition>();
2280    private XhtmlNode summary;
2281    public List<StructureDefinition> getProfiles() {
2282      return profiles;
2283    }
2284    public XhtmlNode getSummary() {
2285      return summary;
2286    }
2287    
2288  }
2289
2290        /**
2291         * Given a structure map, return a set of analyses on it. 
2292         * 
2293         * Returned:
2294         *   - a list or profiles for what it will create. First profile is the target
2295         *   - a table with a summary (in xhtml) for easy human undertanding of the mapping
2296         *   
2297         * 
2298         * @param appInfo
2299         * @param map
2300         * @return
2301         * @throws Exception
2302         */
2303  public StructureMapAnalysis analyse(Object appInfo, StructureMap map) throws FHIRException {
2304    ids.clear();
2305    StructureMapAnalysis result = new StructureMapAnalysis(); 
2306    TransformContext context = new TransformContext(appInfo);
2307    VariablesForProfiling vars = new VariablesForProfiling(false, false);
2308    StructureMapGroupComponent start = map.getGroup().get(0);
2309    for (StructureMapGroupInputComponent t : start.getInput()) {
2310      PropertyWithType ti = resolveType(map, t.getType(), t.getMode());
2311      if (t.getMode() == StructureMapInputMode.SOURCE)
2312       vars.add(VariableMode.INPUT, t.getName(), ti);
2313      else 
2314        vars.add(VariableMode.OUTPUT, t.getName(), createProfile(map, result.profiles, ti, start.getName(), start));
2315    }
2316
2317    result.summary = new XhtmlNode(NodeType.Element, "table").setAttribute("class", "grid");
2318    XhtmlNode tr = result.summary.addTag("tr");
2319    tr.addTag("td").addTag("b").addText("Source");
2320    tr.addTag("td").addTag("b").addText("Target");
2321    
2322    log("Start Profiling Transform "+map.getUrl());
2323    analyseGroup("", context, map, vars, start, result);
2324    ProfileUtilities pu = new ProfileUtilities(worker, null, pkp);
2325    for (StructureDefinition sd : result.getProfiles())
2326      pu.cleanUpDifferential(sd);
2327    return result;
2328  }
2329
2330
2331  private void analyseGroup(String indent, TransformContext context, StructureMap map, VariablesForProfiling vars, StructureMapGroupComponent group, StructureMapAnalysis result) throws FHIRException {
2332    log(indent+"Analyse Group : "+group.getName());
2333    // todo: extends
2334    // todo: check inputs
2335    XhtmlNode tr = result.summary.addTag("tr").setAttribute("class", "diff-title");
2336    XhtmlNode xs = tr.addTag("td");
2337    XhtmlNode xt = tr.addTag("td");
2338    for (StructureMapGroupInputComponent inp : group.getInput()) {
2339      if (inp.getMode() == StructureMapInputMode.SOURCE) 
2340        noteInput(vars, inp, VariableMode.INPUT, xs);
2341      if (inp.getMode() == StructureMapInputMode.TARGET) 
2342        noteInput(vars, inp, VariableMode.OUTPUT, xt);
2343    }
2344    for (StructureMapGroupRuleComponent r : group.getRule()) {
2345      analyseRule(indent+"  ", context, map, vars, group, r, result);
2346    }    
2347  }
2348
2349
2350  private void noteInput(VariablesForProfiling vars, StructureMapGroupInputComponent inp, VariableMode mode, XhtmlNode xs) {
2351    VariableForProfiling v = vars.get(mode, inp.getName());
2352    if (v != null)
2353      xs.addText("Input: "+v.property.getPath());
2354  }
2355
2356  private void analyseRule(String indent, TransformContext context, StructureMap map, VariablesForProfiling vars, StructureMapGroupComponent group, StructureMapGroupRuleComponent rule, StructureMapAnalysis result) throws FHIRException {
2357    log(indent+"Analyse rule : "+rule.getName());
2358    XhtmlNode tr = result.summary.addTag("tr");
2359    XhtmlNode xs = tr.addTag("td");
2360    XhtmlNode xt = tr.addTag("td");
2361
2362    VariablesForProfiling srcVars = vars.copy();
2363    if (rule.getSource().size() != 1)
2364      throw new FHIRException("Rule \""+rule.getName()+"\": not handled yet");
2365    VariablesForProfiling source = analyseSource(rule.getName(), context, srcVars, rule.getSourceFirstRep(), xs);
2366
2367    TargetWriter tw = new TargetWriter();
2368      for (StructureMapGroupRuleTargetComponent t : rule.getTarget()) {
2369      analyseTarget(rule.getName(), context, source, map, t, rule.getSourceFirstRep().getVariable(), tw, result.profiles, rule.getName());
2370      }
2371    tw.commit(xt);
2372
2373          for (StructureMapGroupRuleComponent childrule : rule.getRule()) {
2374      analyseRule(indent+"  ", context, map, source, group, childrule, result);
2375          }
2376//    for (StructureMapGroupRuleDependentComponent dependent : rule.getDependent()) {
2377//      executeDependency(indent+"  ", context, map, v, group, dependent); // do we need group here?
2378//    }
2379          }
2380
2381  public class StringPair {
2382    private String var;
2383    private String desc;
2384    public StringPair(String var, String desc) {
2385      super();
2386      this.var = var;
2387      this.desc = desc;
2388        }
2389    public String getVar() {
2390      return var;
2391      }
2392    public String getDesc() {
2393      return desc;
2394    }
2395  }
2396  public class TargetWriter {
2397    private Map<String, String> newResources = new HashMap<String, String>();
2398    private List<StringPair> assignments = new ArrayList<StringPair>();
2399    private List<StringPair> keyProps = new ArrayList<StringPair>();
2400    private CommaSeparatedStringBuilder txt = new CommaSeparatedStringBuilder();
2401
2402    public void newResource(String var, String name) {
2403      newResources.put(var, name);
2404      txt.append("new "+name);
2405    }
2406
2407    public void valueAssignment(String context, String desc) {
2408      assignments.add(new StringPair(context, desc));      
2409      txt.append(desc);
2410        }
2411
2412    public void keyAssignment(String context, String desc) {
2413      keyProps.add(new StringPair(context, desc));      
2414      txt.append(desc);
2415    }
2416    public void commit(XhtmlNode xt) {
2417      if (newResources.size() == 1 && assignments.size() == 1 && newResources.containsKey(assignments.get(0).getVar()) && keyProps.size() == 1 && newResources.containsKey(keyProps.get(0).getVar()) ) {
2418        xt.addText("new "+assignments.get(0).desc+" ("+keyProps.get(0).desc.substring(keyProps.get(0).desc.indexOf(".")+1)+")");
2419      } else if (newResources.size() == 1 && assignments.size() == 1 && newResources.containsKey(assignments.get(0).getVar()) && keyProps.size() == 0) {
2420        xt.addText("new "+assignments.get(0).desc);
2421      } else {
2422        xt.addText(txt.toString());        
2423    }
2424    }
2425  }
2426
2427  private VariablesForProfiling analyseSource(String ruleId, TransformContext context, VariablesForProfiling vars, StructureMapGroupRuleSourceComponent src, XhtmlNode td) throws FHIRException {
2428    VariableForProfiling var = vars.get(VariableMode.INPUT, src.getContext());
2429    if (var == null)
2430      throw new FHIRException("Rule \""+ruleId+"\": Unknown input variable "+src.getContext());
2431    PropertyWithType prop = var.getProperty();
2432
2433    boolean optional = false;
2434    boolean repeating = false;
2435
2436    if (src.hasCondition()) {
2437      optional = true;
2438    }
2439
2440    if (src.hasElement()) {
2441      Property element = prop.getBaseProperty().getChild(prop.types.getType(), src.getElement());
2442      if (element == null)
2443        throw new FHIRException("Rule \""+ruleId+"\": Unknown element name "+src.getElement());
2444      if (element.getDefinition().getMin() == 0)
2445        optional = true;
2446      if (element.getDefinition().getMax().equals("*"))
2447        repeating = true;
2448      VariablesForProfiling result = vars.copy(optional, repeating);
2449      TypeDetails type = new TypeDetails(CollectionStatus.SINGLETON);
2450      for (TypeRefComponent tr : element.getDefinition().getType()) {
2451        if (!tr.hasCode())
2452          throw new Error("Rule \""+ruleId+"\": Element has no type");
2453        ProfiledType pt = new ProfiledType(tr.getWorkingCode());
2454        if (tr.hasProfile())
2455          pt.addProfiles(tr.getProfile());
2456        if (element.getDefinition().hasBinding())
2457          pt.addBinding(element.getDefinition().getBinding());
2458        type.addType(pt);
2459    } 
2460      td.addText(prop.getPath()+"."+src.getElement()); 
2461      if (src.hasVariable())
2462        result.add(VariableMode.INPUT, src.getVariable(), new PropertyWithType(prop.getPath()+"."+src.getElement(), element, null, type));
2463    return result;
2464    } else {
2465      td.addText(prop.getPath()); // ditto!
2466      return vars.copy(optional, repeating);
2467    }
2468  }
2469
2470
2471  private void analyseTarget(String ruleId, TransformContext context, VariablesForProfiling vars, StructureMap map, StructureMapGroupRuleTargetComponent tgt, String tv, TargetWriter tw, List<StructureDefinition> profiles, String sliceName) throws FHIRException {
2472    VariableForProfiling var = null;
2473    if (tgt.hasContext()) {
2474      var = vars.get(VariableMode.OUTPUT, tgt.getContext());
2475      if (var == null)
2476        throw new FHIRException("Rule \""+ruleId+"\": target context not known: "+tgt.getContext());
2477      if (!tgt.hasElement())
2478        throw new FHIRException("Rule \""+ruleId+"\": Not supported yet");
2479    }
2480
2481    
2482    TypeDetails type = null;
2483    if (tgt.hasTransform()) {
2484      type = analyseTransform(context, map, tgt, var, vars);
2485        // profiling: dest.setProperty(tgt.getElement().hashCode(), tgt.getElement(), v);
2486    } else {
2487      Property vp = var.property.baseProperty.getChild(tgt.getElement(),  tgt.getElement());
2488      if (vp == null)
2489        throw new FHIRException("Unknown Property "+tgt.getElement()+" on "+var.property.path);
2490      
2491      type = new TypeDetails(CollectionStatus.SINGLETON, vp.getType(tgt.getElement()));
2492    }
2493
2494    if (tgt.getTransform() == StructureMapTransform.CREATE) {
2495      String s = getParamString(vars, tgt.getParameter().get(0));
2496      if (worker.getResourceNames().contains(s))
2497        tw.newResource(tgt.getVariable(), s);
2498    } else { 
2499      boolean mapsSrc = false;
2500      for (StructureMapGroupRuleTargetParameterComponent p : tgt.getParameter()) {
2501        DataType pr = p.getValue();
2502        if (pr instanceof IdType && ((IdType) pr).asStringValue().equals(tv)) 
2503          mapsSrc = true;
2504      }
2505      if (mapsSrc) { 
2506        if (var == null)
2507          throw new Error("Rule \""+ruleId+"\": Attempt to assign with no context");
2508        tw.valueAssignment(tgt.getContext(), var.property.getPath()+"."+tgt.getElement()+getTransformSuffix(tgt.getTransform()));
2509      } else if (tgt.hasContext()) {
2510        if (isSignificantElement(var.property, tgt.getElement())) {
2511          String td = describeTransform(tgt);
2512          if (td != null)
2513            tw.keyAssignment(tgt.getContext(), var.property.getPath()+"."+tgt.getElement()+" = "+td);
2514        }
2515      }
2516    }
2517    DataType fixed = generateFixedValue(tgt);
2518    
2519    PropertyWithType prop = updateProfile(var, tgt.getElement(), type, map, profiles, sliceName, fixed, tgt);
2520    if (tgt.hasVariable())
2521      if (tgt.hasElement())
2522        vars.add(VariableMode.OUTPUT, tgt.getVariable(), prop); 
2523      else
2524        vars.add(VariableMode.OUTPUT, tgt.getVariable(), prop); 
2525  }
2526  
2527  private DataType generateFixedValue(StructureMapGroupRuleTargetComponent tgt) {
2528    if (!allParametersFixed(tgt))
2529      return null;
2530    if (!tgt.hasTransform())
2531      return null;
2532    switch (tgt.getTransform()) {
2533    case COPY: return tgt.getParameter().get(0).getValue(); 
2534    case TRUNCATE: return null; 
2535    //case ESCAPE: 
2536    //case CAST: 
2537    //case APPEND: 
2538    case TRANSLATE: return null; 
2539  //case DATEOP, 
2540  //case UUID, 
2541  //case POINTER, 
2542  //case EVALUATE, 
2543    case CC: 
2544      CodeableConcept cc = new CodeableConcept();
2545      cc.addCoding(buildCoding(tgt.getParameter().get(0).getValue(), tgt.getParameter().get(1).getValue()));
2546      return cc;
2547    case C: 
2548      return buildCoding(tgt.getParameter().get(0).getValue(), tgt.getParameter().get(1).getValue());
2549    case QTY: return null; 
2550  //case ID, 
2551  //case CP, 
2552    default:
2553      return null;
2554    }
2555  }
2556
2557  @SuppressWarnings("rawtypes")
2558  private Coding buildCoding(DataType value1, DataType value2) {
2559    return new Coding().setSystem(((PrimitiveType) value1).asStringValue()).setCode(((PrimitiveType) value2).asStringValue()) ;
2560  }
2561
2562  private boolean allParametersFixed(StructureMapGroupRuleTargetComponent tgt) {
2563    for (StructureMapGroupRuleTargetParameterComponent p : tgt.getParameter()) {
2564      DataType pr = p.getValue();
2565      if (pr instanceof IdType)
2566        return false;
2567    }
2568    return true;
2569  }
2570
2571  private String describeTransform(StructureMapGroupRuleTargetComponent tgt) throws FHIRException {
2572    switch (tgt.getTransform()) {
2573    case COPY: return null; 
2574    case TRUNCATE: return null; 
2575    //case ESCAPE: 
2576    //case CAST: 
2577    //case APPEND: 
2578    case TRANSLATE: return null; 
2579  //case DATEOP, 
2580  //case UUID, 
2581  //case POINTER, 
2582  //case EVALUATE, 
2583    case CC: return describeTransformCCorC(tgt); 
2584    case C: return describeTransformCCorC(tgt); 
2585    case QTY: return null; 
2586  //case ID, 
2587  //case CP, 
2588    default:
2589      return null;
2590    }
2591  }
2592
2593  @SuppressWarnings("rawtypes")
2594  private String describeTransformCCorC(StructureMapGroupRuleTargetComponent tgt) throws FHIRException {
2595    if (tgt.getParameter().size() < 2)
2596      return null;
2597    DataType p1 = tgt.getParameter().get(0).getValue();
2598    DataType p2 = tgt.getParameter().get(1).getValue();
2599    if (p1 instanceof IdType || p2 instanceof IdType)
2600      return null;
2601    if (!(p1 instanceof PrimitiveType) || !(p2 instanceof PrimitiveType))
2602      return null;
2603    String uri = ((PrimitiveType) p1).asStringValue();
2604    String code = ((PrimitiveType) p2).asStringValue();
2605    if (Utilities.noString(uri))
2606      throw new FHIRException("Describe Transform, but the uri is blank");
2607    if (Utilities.noString(code))
2608      throw new FHIRException("Describe Transform, but the code is blank");
2609    Coding c = buildCoding(uri, code);
2610    return NarrativeGenerator.describeSystem(c.getSystem())+"#"+c.getCode()+(c.hasDisplay() ? "("+c.getDisplay()+")" : "");
2611  }
2612
2613
2614  private boolean isSignificantElement(PropertyWithType property, String element) {
2615    if ("Observation".equals(property.getPath()))
2616      return "code".equals(element);
2617    else if ("Bundle".equals(property.getPath()))
2618      return "type".equals(element);
2619    else
2620      return false;
2621  }
2622
2623  private String getTransformSuffix(StructureMapTransform transform) {
2624    switch (transform) {
2625    case COPY: return ""; 
2626    case TRUNCATE: return " (truncated)"; 
2627    //case ESCAPE: 
2628    //case CAST: 
2629    //case APPEND: 
2630    case TRANSLATE: return " (translated)"; 
2631  //case DATEOP, 
2632  //case UUID, 
2633  //case POINTER, 
2634  //case EVALUATE, 
2635    case CC: return " (--> CodeableConcept)"; 
2636    case C: return " (--> Coding)"; 
2637    case QTY: return " (--> Quantity)"; 
2638  //case ID, 
2639  //case CP, 
2640    default:
2641      return " {??)";
2642    }
2643  }
2644
2645  private PropertyWithType updateProfile(VariableForProfiling var, String element, TypeDetails type, StructureMap map, List<StructureDefinition> profiles, String sliceName, DataType fixed, StructureMapGroupRuleTargetComponent tgt) throws FHIRException {
2646    if (var == null) {
2647      assert (Utilities.noString(element));
2648      // 1. start the new structure definition
2649      StructureDefinition sdn = worker.fetchResource(StructureDefinition.class, type.getType());
2650      if (sdn == null)
2651        throw new FHIRException("Unable to find definition for "+type.getType());
2652      ElementDefinition edn = sdn.getSnapshot().getElementFirstRep();
2653      PropertyWithType pn = createProfile(map, profiles, new PropertyWithType(sdn.getId(), new Property(worker, edn, sdn), null, type), sliceName, tgt);
2654
2655//      // 2. hook it into the base bundle
2656//      if (type.getType().startsWith("http://hl7.org/fhir/StructureDefinition/") && worker.getResourceNames().contains(type.getType().substring(40))) {
2657//        StructureDefinition sd = var.getProperty().profileProperty.getStructure();
2658//        ElementDefinition ed = sd.getDifferential().addElement();
2659//        ed.setPath("Bundle.entry");
2660//        ed.setName(sliceName);
2661//        ed.setMax("1"); // well, it is for now...
2662//        ed = sd.getDifferential().addElement();
2663//        ed.setPath("Bundle.entry.fullUrl");
2664//        ed.setMin(1);
2665//        ed = sd.getDifferential().addElement();
2666//        ed.setPath("Bundle.entry.resource");
2667//        ed.setMin(1);
2668//        ed.addType().setCode(pn.getProfileProperty().getStructure().getType()).setProfile(pn.getProfileProperty().getStructure().getUrl());
2669//      }
2670      return pn; 
2671    } else {
2672      assert (!Utilities.noString(element));
2673      Property pvb = var.getProperty().getBaseProperty();
2674      Property pvd = var.getProperty().getProfileProperty();
2675      Property pc = pvb.getChild(element, var.property.types);
2676      if (pc == null)
2677        throw new DefinitionException("Unable to find a definition for "+pvb.getDefinition().getPath()+"."+element);
2678      
2679      // the profile structure definition (derived)
2680      StructureDefinition sd = var.getProperty().profileProperty.getStructure();
2681      ElementDefinition ednew = sd.getDifferential().addElement();
2682      ednew.setPath(var.getProperty().profileProperty.getDefinition().getPath()+"."+pc.getName());
2683      ednew.setUserData("slice-name", sliceName);
2684      ednew.setFixed(fixed);
2685      for (ProfiledType pt : type.getProfiledTypes()) {
2686        if (pt.hasBindings())
2687          ednew.setBinding(pt.getBindings().get(0));
2688        if (pt.getUri().startsWith("http://hl7.org/fhir/StructureDefinition/")) {
2689          String t = pt.getUri().substring(40);
2690          t = checkType(t, pc, pt.getProfiles());
2691          if (t != null) {
2692            if (pt.hasProfiles()) {
2693              for (String p : pt.getProfiles())
2694                if (t.equals("Reference"))
2695                  ednew.getType(t).addTargetProfile(p);
2696                else
2697                  ednew.getType(t).addProfile(p);
2698            } else 
2699            ednew.getType(t);
2700      }
2701        }
2702      }
2703      
2704      return new PropertyWithType(var.property.path+"."+element, pc, new Property(worker, ednew, sd), type);
2705    }
2706  }
2707  
2708
2709
2710  private String checkType(String t, Property pvb, List<String> profiles) throws FHIRException {
2711    if (pvb.getDefinition().getType().size() == 1 && isCompatibleType(t, pvb.getDefinition().getType().get(0).getWorkingCode()) && profilesMatch(profiles, pvb.getDefinition().getType().get(0).getProfile())) 
2712      return null;
2713    for (TypeRefComponent tr : pvb.getDefinition().getType()) {
2714      if (isCompatibleType(t, tr.getWorkingCode()))
2715        return tr.getWorkingCode(); // note what is returned - the base type, not the inferred mapping type
2716    }
2717    throw new FHIRException("The type "+t+" is not compatible with the allowed types for "+pvb.getDefinition().getPath());
2718  }
2719
2720  private boolean profilesMatch(List<String> profiles, List<CanonicalType> profile) {
2721    return profiles == null || profiles.size() == 0 || profile.size() == 0 || (profiles.size() == 1 && profiles.get(0).equals(profile.get(0).getValue()));
2722  }
2723
2724  private boolean isCompatibleType(String t, String code) {
2725    if (t.equals(code))
2726      return true;
2727    if (t.equals("string")) {
2728      StructureDefinition sd = worker.fetchTypeDefinition(code);
2729      if (sd != null && sd.getBaseDefinition().equals("http://hl7.org/fhir/StructureDefinition/string"))
2730        return true;
2731    }
2732    return false;
2733  }
2734
2735  private TypeDetails analyseTransform(TransformContext context, StructureMap map, StructureMapGroupRuleTargetComponent tgt, VariableForProfiling var, VariablesForProfiling vars) throws FHIRException {
2736    switch (tgt.getTransform()) {
2737    case CREATE :
2738      String p = getParamString(vars, tgt.getParameter().get(0));
2739      return new TypeDetails(CollectionStatus.SINGLETON, p);
2740    case COPY : 
2741      return getParam(vars, tgt.getParameter().get(0));
2742    case EVALUATE :
2743      ExpressionNode expr = (ExpressionNode) tgt.getUserData(MAP_EXPRESSION);
2744      if (expr == null) {
2745        expr = fpe.parse(getParamString(vars, tgt.getParameter().get(tgt.getParameter().size()-1)));
2746        tgt.setUserData(MAP_WHERE_EXPRESSION, expr);
2747      }
2748      return fpe.check(vars, null, expr);
2749
2750////case TRUNCATE : 
2751////  String src = getParamString(vars, tgt.getParameter().get(0));
2752////  String len = getParamString(vars, tgt.getParameter().get(1));
2753////  if (Utilities.isInteger(len)) {
2754////    int l = Integer.parseInt(len);
2755////    if (src.length() > l)
2756////      src = src.substring(0, l);
2757////  }
2758////  return new StringType(src);
2759////case ESCAPE : 
2760////  throw new Error("Transform "+tgt.getTransform().toCode()+" not supported yet");
2761////case CAST :
2762////  throw new Error("Transform "+tgt.getTransform().toCode()+" not supported yet");
2763////case APPEND : 
2764////  throw new Error("Transform "+tgt.getTransform().toCode()+" not supported yet");
2765    case TRANSLATE : 
2766      return new TypeDetails(CollectionStatus.SINGLETON, "CodeableConcept");
2767   case CC:
2768     ProfiledType res = new ProfiledType("CodeableConcept");
2769     if (tgt.getParameter().size() >= 2  && isParamId(vars, tgt.getParameter().get(1))) {
2770       TypeDetails td = vars.get(null, getParamId(vars, tgt.getParameter().get(1))).property.types;
2771       if (td != null && td.hasBinding())
2772         // todo: do we need to check that there's no implicit translation her? I don't think we do...
2773         res.addBinding(td.getBinding());
2774     }
2775     return new TypeDetails(CollectionStatus.SINGLETON, res);
2776   case C:
2777     return new TypeDetails(CollectionStatus.SINGLETON, "Coding");
2778   case QTY:
2779     return new TypeDetails(CollectionStatus.SINGLETON, "Quantity");
2780   case REFERENCE :
2781      VariableForProfiling vrs = vars.get(VariableMode.OUTPUT, getParamId(vars, tgt.getParameterFirstRep()));
2782      if (vrs == null)
2783        throw new FHIRException("Unable to resolve variable \""+getParamId(vars, tgt.getParameterFirstRep())+"\"");
2784      String profile = vrs.property.getProfileProperty().getStructure().getUrl();
2785     TypeDetails td = new TypeDetails(CollectionStatus.SINGLETON);
2786     td.addType("Reference", profile);
2787     return td;  
2788////case DATEOP :
2789////  throw new Error("Transform "+tgt.getTransform().toCode()+" not supported yet");
2790////case UUID :
2791////  return new IdType(UUID.randomUUID().toString());
2792////case POINTER :
2793////  Base b = getParam(vars, tgt.getParameter().get(0));
2794////  if (b instanceof Resource)
2795////    return new UriType("urn:uuid:"+((Resource) b).getId());
2796////  else
2797////    throw new FHIRException("Transform engine cannot point at an element of type "+b.fhirType());
2798    default:
2799      throw new Error("Transform Unknown or not handled yet: "+tgt.getTransform().toCode());
2800    }
2801  }
2802  private String getParamString(VariablesForProfiling vars, StructureMapGroupRuleTargetParameterComponent parameter) {
2803    DataType p = parameter.getValue();
2804    if (p == null || p instanceof IdType)
2805      return null;
2806    if (!p.hasPrimitiveValue())
2807      return null;
2808    return p.primitiveValue();
2809  }
2810
2811  private String getParamId(VariablesForProfiling vars, StructureMapGroupRuleTargetParameterComponent parameter) {
2812    DataType p = parameter.getValue();
2813    if (p == null || !(p instanceof IdType))
2814      return null;
2815    return p.primitiveValue();
2816  }
2817
2818  private boolean isParamId(VariablesForProfiling vars, StructureMapGroupRuleTargetParameterComponent parameter) {
2819    DataType p = parameter.getValue();
2820    if (p == null || !(p instanceof IdType))
2821      return false;
2822    return vars.get(null, p.primitiveValue()) != null;
2823  }
2824
2825  private TypeDetails getParam(VariablesForProfiling vars, StructureMapGroupRuleTargetParameterComponent parameter) throws DefinitionException {
2826    DataType p = parameter.getValue();
2827    if (!(p instanceof IdType))
2828      return new TypeDetails(CollectionStatus.SINGLETON, ProfileUtilities.sdNs(p.fhirType(), worker.getOverrideVersionNs()));
2829    else { 
2830      String n = ((IdType) p).asStringValue();
2831      VariableForProfiling b = vars.get(VariableMode.INPUT, n);
2832      if (b == null)
2833        b = vars.get(VariableMode.OUTPUT, n);
2834      if (b == null)
2835        throw new DefinitionException("Variable "+n+" not found ("+vars.summary()+")");
2836      return b.getProperty().getTypes();
2837    }
2838  }
2839
2840  private PropertyWithType createProfile(StructureMap map, List<StructureDefinition> profiles, PropertyWithType prop, String sliceName, Base ctxt) throws FHIRException {
2841    if (prop.getBaseProperty().getDefinition().getPath().contains(".")) 
2842      throw new DefinitionException("Unable to process entry point");
2843
2844    String type = prop.getBaseProperty().getDefinition().getPath();
2845    String suffix = "";
2846    if (ids.containsKey(type)) {
2847      int id = ids.get(type);
2848      id++;
2849      ids.put(type, id);
2850      suffix = "-"+Integer.toString(id);
2851    } else
2852      ids.put(type, 0);
2853    
2854    StructureDefinition profile = new StructureDefinition();
2855    profiles.add(profile);
2856    profile.setDerivation(TypeDerivationRule.CONSTRAINT);
2857    profile.setType(type);
2858    profile.setBaseDefinition(prop.getBaseProperty().getStructure().getUrl());
2859    profile.setName("Profile for "+profile.getType()+" for "+sliceName);
2860    profile.setUrl(map.getUrl().replace("StructureMap", "StructureDefinition")+"-"+profile.getType()+suffix);
2861    ctxt.setUserData("profile", profile.getUrl()); // then we can easily assign this profile url for validation later when we actually transform
2862    profile.setId(map.getId()+"-"+profile.getType()+suffix);
2863    profile.setStatus(map.getStatus());
2864    profile.setExperimental(map.getExperimental());
2865    profile.setDescription("Generated automatically from the mapping by the Java Reference Implementation");
2866    for (ContactDetail c : map.getContact()) {
2867      ContactDetail p = profile.addContact();
2868      p.setName(c.getName());
2869      for (ContactPoint cc : c.getTelecom()) 
2870        p.addTelecom(cc);
2871    }
2872    profile.setDate(map.getDate());
2873    profile.setCopyright(map.getCopyright());
2874    profile.setFhirVersion(FHIRVersion.fromCode(Constants.VERSION));
2875    profile.setKind(prop.getBaseProperty().getStructure().getKind());
2876    profile.setAbstract(false);
2877    ElementDefinition ed = profile.getDifferential().addElement();
2878    ed.setPath(profile.getType());
2879    prop.profileProperty = new Property(worker, ed, profile);
2880    return prop;
2881  }
2882
2883  private PropertyWithType resolveType(StructureMap map, String type, StructureMapInputMode mode) throws FHIRException {
2884    for (StructureMapStructureComponent imp : map.getStructure()) {
2885      if ((imp.getMode() == StructureMapModelMode.SOURCE && mode == StructureMapInputMode.SOURCE) || 
2886          (imp.getMode() == StructureMapModelMode.TARGET && mode == StructureMapInputMode.TARGET)) {
2887        StructureDefinition sd = worker.fetchResource(StructureDefinition.class, imp.getUrl());
2888        if (sd == null)
2889          throw new FHIRException("Import "+imp.getUrl()+" cannot be resolved");
2890        if (sd.getId().equals(type)) {
2891          return new PropertyWithType(sd.getType(), new Property(worker, sd.getSnapshot().getElement().get(0), sd), null, new TypeDetails(CollectionStatus.SINGLETON, sd.getUrl()));
2892        }
2893      }
2894    }
2895    throw new FHIRException("Unable to find structure definition for "+type+" in imports");
2896  }
2897
2898
2899  public StructureMap generateMapFromMappings(StructureDefinition sd) throws IOException, FHIRException {
2900    String id = getLogicalMappingId(sd);
2901    if (id == null) 
2902        return null;
2903    String prefix = ToolingExtensions.readStringExtension(sd,  ToolingExtensions.EXT_MAPPING_PREFIX);
2904    String suffix = ToolingExtensions.readStringExtension(sd,  ToolingExtensions.EXT_MAPPING_SUFFIX);
2905    if (prefix == null || suffix == null)
2906      return null;
2907    // we build this by text. Any element that has a mapping, we put it's mappings inside it....
2908    StringBuilder b = new StringBuilder();
2909    b.append(prefix);
2910
2911    ElementDefinition root = sd.getSnapshot().getElementFirstRep();
2912    String m = getMapping(root, id);
2913    if (m != null)
2914      b.append(m+"\r\n");
2915    addChildMappings(b, id, "", sd, root, false);
2916    b.append("\r\n");
2917    b.append(suffix);
2918    b.append("\r\n");
2919    StructureMap map = parse(b.toString(), sd.getUrl());
2920    map.setId(tail(map.getUrl()));
2921    if (!map.hasStatus())
2922      map.setStatus(PublicationStatus.DRAFT);
2923    map.getText().setStatus(NarrativeStatus.GENERATED);
2924    map.getText().setDiv(new XhtmlNode(NodeType.Element, "div"));
2925    map.getText().getDiv().addTag("pre").addText(render(map));
2926    return map;
2927  }
2928
2929
2930  private String tail(String url) {
2931    return url.substring(url.lastIndexOf("/")+1);
2932  }
2933
2934
2935  private void addChildMappings(StringBuilder b, String id, String indent, StructureDefinition sd, ElementDefinition ed, boolean inner) throws DefinitionException {
2936    boolean first = true;
2937    List<ElementDefinition> children = ProfileUtilities.getChildMap(sd, ed);
2938    for (ElementDefinition child : children) {
2939      if (first && inner) {
2940        b.append(" then {\r\n");
2941        first = false;
2942      }
2943      String map = getMapping(child, id);
2944      if (map != null) {
2945        b.append(indent+"  "+child.getPath()+": "+map);
2946        addChildMappings(b, id, indent+"  ", sd, child, true);
2947        b.append("\r\n");
2948      }
2949    }
2950    if (!first && inner)
2951      b.append(indent+"}");
2952    
2953  }
2954
2955
2956  private String getMapping(ElementDefinition ed, String id) {
2957    for (ElementDefinitionMappingComponent map : ed.getMapping())
2958      if (id.equals(map.getIdentity()))
2959        return map.getMap();
2960    return null;
2961  }
2962
2963
2964  private String getLogicalMappingId(StructureDefinition sd) {
2965    String id = null;
2966    for (StructureDefinitionMappingComponent map : sd.getMapping()) {
2967      if ("http://hl7.org/fhir/logical".equals(map.getUri()))
2968        return map.getIdentity();
2969    }
2970    return null;
2971  }
2972
2973  public ValidationOptions getTerminologyServiceOptions() {
2974    return terminologyServiceOptions;
2975  }
2976
2977  public void setTerminologyServiceOptions(ValidationOptions terminologyServiceOptions) {
2978    this.terminologyServiceOptions = terminologyServiceOptions;
2979  }
2980        
2981}