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