001package org.hl7.fhir.r5.context;
002
003/*-
004 * #%L
005 * org.hl7.fhir.r5
006 * %%
007 * Copyright (C) 2014 - 2019 Health Level 7
008 * %%
009 * Licensed under the Apache License, Version 2.0 (the "License");
010 * you may not use this file except in compliance with the License.
011 * You may obtain a copy of the License at
012 * 
013 *      http://www.apache.org/licenses/LICENSE-2.0
014 * 
015 * Unless required by applicable law or agreed to in writing, software
016 * distributed under the License is distributed on an "AS IS" BASIS,
017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
018 * See the License for the specific language governing permissions and
019 * limitations under the License.
020 * #L%
021 */
022
023
024import java.io.ByteArrayInputStream;
025import java.io.File;
026import java.io.FileInputStream;
027import java.io.FileNotFoundException;
028import java.io.FileOutputStream;
029import java.io.IOException;
030import java.io.InputStream;
031import java.net.URISyntaxException;
032import java.util.ArrayList;
033import java.util.Arrays;
034import java.util.Collections;
035import java.util.HashMap;
036import java.util.HashSet;
037import java.util.List;
038import java.util.Map;
039import java.util.Set;
040import java.util.zip.ZipEntry;
041import java.util.zip.ZipInputStream;
042
043import org.apache.commons.io.IOUtils;
044import org.hl7.fhir.exceptions.DefinitionException;
045import org.hl7.fhir.exceptions.FHIRException;
046import org.hl7.fhir.exceptions.FHIRFormatError;
047import org.hl7.fhir.r5.conformance.ProfileUtilities;
048import org.hl7.fhir.r5.conformance.ProfileUtilities.ProfileKnowledgeProvider;
049import org.hl7.fhir.r5.context.IWorkerContext.ILoggingService.LogCategory;
050import org.hl7.fhir.r5.context.SimpleWorkerContext.ILoadFilter;
051import org.hl7.fhir.r5.formats.IParser;
052import org.hl7.fhir.r5.formats.JsonParser;
053import org.hl7.fhir.r5.formats.ParserType;
054import org.hl7.fhir.r5.formats.XmlParser;
055import org.hl7.fhir.r5.formats.IParser.OutputStyle;
056import org.hl7.fhir.r5.model.Bundle;
057import org.hl7.fhir.r5.model.Bundle.BundleEntryComponent;
058import org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionBindingComponent;
059import org.hl7.fhir.r5.model.ImplementationGuide;
060import org.hl7.fhir.r5.model.CanonicalResource;
061import org.hl7.fhir.r5.model.Questionnaire;
062import org.hl7.fhir.r5.model.Resource;
063import org.hl7.fhir.r5.model.ResourceType;
064import org.hl7.fhir.r5.model.StructureDefinition;
065import org.hl7.fhir.r5.model.StructureDefinition.StructureDefinitionKind;
066import org.hl7.fhir.r5.model.StructureDefinition.TypeDerivationRule;
067import org.hl7.fhir.r5.model.StructureMap;
068import org.hl7.fhir.r5.model.StructureMap.StructureMapModelMode;
069import org.hl7.fhir.r5.model.StructureMap.StructureMapStructureComponent;
070import org.hl7.fhir.r5.terminologies.TerminologyClient;
071import org.hl7.fhir.r5.utils.INarrativeGenerator;
072import org.hl7.fhir.r5.utils.IResourceValidator;
073import org.hl7.fhir.r5.utils.NarrativeGenerator;
074import org.hl7.fhir.utilities.CSFileInputStream;
075import org.hl7.fhir.utilities.TextFile;
076import org.hl7.fhir.utilities.Utilities;
077import org.hl7.fhir.utilities.cache.NpmPackage;
078import org.hl7.fhir.utilities.validation.ValidationMessage;
079import org.hl7.fhir.utilities.validation.ValidationMessage.IssueType;
080import org.hl7.fhir.utilities.validation.ValidationMessage.Source;
081
082import ca.uhn.fhir.fluentpath.IFluentPath;
083import ca.uhn.fhir.parser.DataFormatException;
084
085/*
086 * This is a stand alone implementation of worker context for use inside a tool.
087 * It loads from the validation package (validation-min.xml.zip), and has a 
088 * very light client to connect to an open unauthenticated terminology service
089 */
090
091public class SimpleWorkerContext extends BaseWorkerContext implements IWorkerContext, ProfileKnowledgeProvider {
092
093  public interface ILoadFilter {
094
095    boolean isOkToLoad(Resource resource);
096
097  }
098
099  public interface IContextResourceLoader {
100    Bundle loadBundle(InputStream stream, boolean isJson) throws FHIRException, IOException;
101
102    String[] getTypes();
103  }
104
105  public interface IValidatorFactory {
106    IResourceValidator makeValidator(IWorkerContext ctxts) throws FHIRException;
107  }
108
109        private Questionnaire questionnaire;
110  private String version;
111  private String revision;
112  private String date;
113  private IValidatorFactory validatorFactory;
114  private boolean ignoreProfileErrors;
115  private boolean progress;
116  
117  public SimpleWorkerContext() throws FileNotFoundException, IOException, FHIRException {
118    super();
119  }
120  
121  public SimpleWorkerContext(SimpleWorkerContext other) throws FileNotFoundException, IOException, FHIRException {
122    super();
123    copy(other);
124  }
125  
126  protected void copy(SimpleWorkerContext other) {
127    super.copy(other);
128    questionnaire = other.questionnaire;
129    binaries.putAll(other.binaries);
130    version = other.version;
131    revision = other.revision;
132    date = other.date;
133    validatorFactory = other.validatorFactory;
134  }
135
136  // -- Initializations
137        /**
138         * Load the working context from the validation pack
139         * 
140         * @param path
141         *           filename of the validation pack
142         * @return
143         * @throws IOException 
144         * @throws FileNotFoundException 
145         * @throws FHIRException 
146         * @throws Exception
147         */
148  public static SimpleWorkerContext fromPack(String path) throws FileNotFoundException, IOException, FHIRException {
149    SimpleWorkerContext res = new SimpleWorkerContext();
150    res.loadFromPack(path, null);
151    return res;
152  }
153
154  public static SimpleWorkerContext fromPackage(NpmPackage pi, boolean allowDuplicates) throws FileNotFoundException, IOException, FHIRException {
155    return fromPackage(pi, allowDuplicates, null);
156  }
157  public static SimpleWorkerContext fromPackage(NpmPackage pi, boolean allowDuplicates, ILoadFilter filter) throws FileNotFoundException, IOException, FHIRException {
158    SimpleWorkerContext res = new SimpleWorkerContext();
159    res.setAllowLoadingDuplicates(allowDuplicates);
160    res.loadFromPackage(pi, null, filter);
161    return res;
162  }
163
164  public static SimpleWorkerContext fromPackage(NpmPackage pi) throws FileNotFoundException, IOException, FHIRException {
165    SimpleWorkerContext res = new SimpleWorkerContext();
166    res.loadFromPackage(pi, null);
167    return res;
168  }
169
170  public static SimpleWorkerContext fromPackage(NpmPackage pi, IContextResourceLoader loader) throws FileNotFoundException, IOException, FHIRException {
171    return fromPackage(pi, loader, null);  
172  }
173  
174  public static SimpleWorkerContext fromPackage(NpmPackage pi, IContextResourceLoader loader, ILoadFilter filter) throws FileNotFoundException, IOException, FHIRException {
175    SimpleWorkerContext res = new SimpleWorkerContext();
176    res.setAllowLoadingDuplicates(true);
177    res.version = pi.getNpm().get("version").getAsString();
178    res.loadFromPackage(pi, loader, filter);
179    return res;
180  }
181
182  public static SimpleWorkerContext fromPack(String path, boolean allowDuplicates) throws FileNotFoundException, IOException, FHIRException {
183    SimpleWorkerContext res = new SimpleWorkerContext();
184    res.setAllowLoadingDuplicates(allowDuplicates);
185    res.loadFromPack(path, null);
186    return res;
187  }
188
189  public static SimpleWorkerContext fromPack(String path, IContextResourceLoader loader) throws FileNotFoundException, IOException, FHIRException {
190    SimpleWorkerContext res = new SimpleWorkerContext();
191    res.loadFromPack(path, loader);
192    return res;
193  }
194
195        public static SimpleWorkerContext fromClassPath() throws IOException, FHIRException {
196                SimpleWorkerContext res = new SimpleWorkerContext();
197                res.loadFromStream(SimpleWorkerContext.class.getResourceAsStream("validation.json.zip"), null);
198                return res;
199        }
200
201         public static SimpleWorkerContext fromClassPath(String name) throws IOException, FHIRException {
202           InputStream s = SimpleWorkerContext.class.getResourceAsStream("/"+name);
203            SimpleWorkerContext res = new SimpleWorkerContext();
204           res.loadFromStream(s, null);
205            return res;
206          }
207
208        public static SimpleWorkerContext fromDefinitions(Map<String, byte[]> source) throws IOException, FHIRException {
209                SimpleWorkerContext res = new SimpleWorkerContext();
210                for (String name : source.keySet()) {
211                  res.loadDefinitionItem(name, new ByteArrayInputStream(source.get(name)), null, null);
212                }
213                return res;
214        }
215
216  public static SimpleWorkerContext fromDefinitions(Map<String, byte[]> source, IContextResourceLoader loader) throws FileNotFoundException, IOException, FHIRException  {
217    SimpleWorkerContext res = new SimpleWorkerContext();
218    for (String name : source.keySet()) { 
219      try {
220        res.loadDefinitionItem(name, new ByteArrayInputStream(source.get(name)), loader, null);
221      } catch (Exception e) {
222        System.out.println("Error loading "+name+": "+e.getMessage());
223        throw new FHIRException("Error loading "+name+": "+e.getMessage(), e);
224      }
225    }
226    return res;
227  }
228
229  private void loadDefinitionItem(String name, InputStream stream, IContextResourceLoader loader, ILoadFilter filter) throws IOException, FHIRException {
230    if (name.endsWith(".xml"))
231      loadFromFile(stream, name, loader, filter);
232    else if (name.endsWith(".json"))
233      loadFromFileJson(stream, name, loader, filter);
234    else if (name.equals("version.info"))
235      readVersionInfo(stream);
236    else
237      loadBytes(name, stream);
238  }
239
240  public String connectToTSServer(TerminologyClient client, String log) {
241    try {
242      tlog("Connect to "+client.getAddress());
243      txClient = client;
244      if (log != null && log.endsWith(".txt")) {
245        txLog = new TextClientLogger(log);
246      } else {
247        txLog = new HTMLClientLogger(log);
248      }
249      txClient.setLogger(txLog);
250      return txClient.getCapabilitiesStatementQuick().getSoftware().getVersion();
251    } catch (Exception e) {
252      throw new FHIRException("Unable to connect to terminology server. Use parameter '-tx n/a' tun run without using terminology services to validate LOINC, SNOMED, ICD-X etc. Error = "+e.getMessage(), e);
253    }
254  }
255
256  public void loadFromFile(InputStream stream, String name, IContextResourceLoader loader) throws IOException, FHIRException {
257    loadFromFile(stream, name, null);
258  }
259  
260        public void loadFromFile(InputStream stream, String name, IContextResourceLoader loader, ILoadFilter filter) throws IOException, FHIRException {
261                Resource f;
262                try {
263                  if (loader != null)
264                    f = loader.loadBundle(stream, false);
265                  else {
266                    XmlParser xml = new XmlParser();
267                    f = xml.parse(stream);
268                  }
269    } catch (DataFormatException e1) {
270      throw new org.hl7.fhir.exceptions.FHIRFormatError("Error parsing "+name+":" +e1.getMessage(), e1);
271    } catch (Exception e1) {
272                        throw new org.hl7.fhir.exceptions.FHIRFormatError("Error parsing "+name+":" +e1.getMessage(), e1);
273                }
274                if (f instanceof Bundle) {
275                  Bundle bnd = (Bundle) f;
276                  for (BundleEntryComponent e : bnd.getEntry()) {
277                    if (e.getFullUrl() == null) {
278                      logger.logDebugMessage(LogCategory.CONTEXT, "unidentified resource in " + name+" (no fullUrl)");
279                    }
280              if (filter == null || filter.isOkToLoad(e.getResource())) {
281                      cacheResource(e.getResource());
282              }
283                  }
284                } else if (f instanceof CanonicalResource) {
285                  if (filter == null || filter.isOkToLoad(f)) {
286                    cacheResource(f);
287                  }
288                }
289        }
290
291  private void loadFromFileJson(InputStream stream, String name, IContextResourceLoader loader, ILoadFilter filter) throws IOException, FHIRException {
292    Bundle f = null;
293    try {
294      if (loader != null)
295        f = loader.loadBundle(stream, true);
296      else {
297        JsonParser json = new JsonParser();
298        Resource r = json.parse(stream);
299        if (r instanceof Bundle)
300          f = (Bundle) r;
301        else if (filter == null || filter.isOkToLoad(f)) {
302          cacheResource(r);
303        }
304      }
305    } catch (FHIRFormatError e1) {
306      throw new org.hl7.fhir.exceptions.FHIRFormatError(e1.getMessage(), e1);
307    }
308    if (f != null)
309      for (BundleEntryComponent e : f.getEntry()) {
310        if (filter == null || filter.isOkToLoad(e.getResource())) {
311          cacheResource(e.getResource());
312        }
313    }
314  }
315
316        private void loadFromPack(String path, IContextResourceLoader loader) throws FileNotFoundException, IOException, FHIRException {
317                loadFromStream(new CSFileInputStream(path), loader);
318        }
319  
320  public void loadFromPackage(NpmPackage pi, IContextResourceLoader loader, ILoadFilter filter) throws IOException  {
321    if (progress) {
322      System.out.println("Load Package "+pi.name()+"#"+pi.version());
323    }
324    for (String s : pi.listResources(loader.getTypes())) {
325       try {
326        loadDefinitionItem(s, pi.load("package", s), loader, filter);
327      } catch (FHIRException | IOException e) {
328        throw new FHIRException("Error reading "+s+" from package "+pi.name()+"#"+pi.version()+": "+e.getMessage(), e);
329      }
330    }
331    for (String s : pi.list("other")) {
332      binaries.put(s, TextFile.streamToBytes(pi.load("other", s)));
333    }
334    if (version == null) {
335      version = pi.version();
336    }
337  }
338
339        public void loadFromPackage(NpmPackage pi, IContextResourceLoader loader, String... types) throws FileNotFoundException, IOException, FHIRException {
340          if (progress) {
341            System.out.println("Load Package "+pi.name()+"#"+pi.version());
342          }
343          if (types.length == 0)
344            types = new String[] { "StructureDefinition", "ValueSet", "CodeSystem", "SearchParameter", "OperationDefinition", "Questionnaire","ConceptMap","StructureMap", "NamingSystem"};
345          for (String s : pi.listResources(types)) {
346       loadDefinitionItem(s, pi.load("package", s), loader, null);
347          }
348          for (String s : pi.list("other")) {
349            binaries.put(s, TextFile.streamToBytes(pi.load("other", s)));
350          }
351          if (version == null) {
352            version = pi.version();
353          }
354        }
355
356  public void loadFromFile(String file, IContextResourceLoader loader) throws IOException, FHIRException {
357    loadDefinitionItem(file, new CSFileInputStream(file), loader, null);
358  }
359  
360        private void loadFromStream(InputStream stream, IContextResourceLoader loader) throws IOException, FHIRException {
361                ZipInputStream zip = new ZipInputStream(stream);
362                ZipEntry ze;
363                while ((ze = zip.getNextEntry()) != null) {
364      loadDefinitionItem(ze.getName(), zip, loader, null);
365                        zip.closeEntry();
366                }
367                zip.close();
368        }
369
370  private void readVersionInfo(InputStream stream) throws IOException, DefinitionException {
371    byte[] bytes = IOUtils.toByteArray(stream);
372    binaries.put("version.info", bytes);
373
374    String[] vi = new String(bytes).split("\\r?\\n");
375    for (String s : vi) {
376      if (s.startsWith("version=")) {
377        if (version == null)
378        version = s.substring(8);
379        else if (!version.equals(s.substring(8))) 
380          throw new DefinitionException("Version mismatch. The context has version "+version+" loaded, and the new content being loaded is version "+s.substring(8));
381      }
382      if (s.startsWith("revision="))
383        revision = s.substring(9);
384      if (s.startsWith("date="))
385        date = s.substring(5);
386    }
387  }
388
389        private void loadBytes(String name, InputStream stream) throws IOException {
390    byte[] bytes = IOUtils.toByteArray(stream);
391          binaries.put(name, bytes);
392  }
393
394        @Override
395        public IParser getParser(ParserType type) {
396                switch (type) {
397                case JSON: return newJsonParser();
398                case XML: return newXmlParser();
399                default:
400                        throw new Error("Parser Type "+type.toString()+" not supported");
401                }
402        }
403
404        @Override
405        public IParser getParser(String type) {
406                if (type.equalsIgnoreCase("JSON"))
407                        return new JsonParser();
408                if (type.equalsIgnoreCase("XML"))
409                        return new XmlParser();
410                throw new Error("Parser Type "+type.toString()+" not supported");
411        }
412
413        @Override
414        public IParser newJsonParser() {
415                return new JsonParser();
416        }
417        @Override
418        public IParser newXmlParser() {
419                return new XmlParser();
420        }
421
422        @Override
423        public INarrativeGenerator getNarrativeGenerator(String prefix, String basePath) {
424                return new NarrativeGenerator(prefix, basePath, this);
425        }
426
427        @Override
428        public IResourceValidator newValidator() throws FHIRException {
429          if (validatorFactory == null)
430            throw new Error("No validator configured");
431          return validatorFactory.makeValidator(this);
432        }
433
434
435
436
437  @Override
438  public List<String> getResourceNames() {
439    List<String> result = new ArrayList<String>();
440    for (StructureDefinition sd : listStructures()) {
441      if (sd.getKind() == StructureDefinitionKind.RESOURCE && sd.getDerivation() == TypeDerivationRule.SPECIALIZATION)
442        result.add(sd.getName());
443    }
444    Collections.sort(result);
445    return result;
446  }
447
448  @Override
449  public List<String> getTypeNames() {
450    List<String> result = new ArrayList<String>();
451    for (StructureDefinition sd : listStructures()) {
452      if (sd.getKind() != StructureDefinitionKind.LOGICAL && sd.getDerivation() == TypeDerivationRule.SPECIALIZATION)
453        result.add(sd.getName());
454    }
455    Collections.sort(result);
456    return result;
457  }
458
459  @Override
460  public String getAbbreviation(String name) {
461    return "xxx";
462  }
463
464  @Override
465  public boolean isDatatype(String typeSimple) {
466    // TODO Auto-generated method stub
467    return false;
468  }
469
470  @Override
471  public boolean isResource(String t) {
472    StructureDefinition sd;
473    try {
474      sd = fetchResource(StructureDefinition.class, "http://hl7.org/fhir/StructureDefinition/"+t);
475    } catch (Exception e) {
476      return false;
477    }
478    if (sd == null)
479      return false;
480    if (sd.getDerivation() == TypeDerivationRule.CONSTRAINT)
481      return false;
482    return sd.getKind() == StructureDefinitionKind.RESOURCE;
483  }
484
485  @Override
486  public boolean hasLinkFor(String typeSimple) {
487    return false;
488  }
489
490  @Override
491  public String getLinkFor(String corePath, String typeSimple) {
492    return null;
493  }
494
495  @Override
496  public BindingResolution resolveBinding(StructureDefinition profile, ElementDefinitionBindingComponent binding, String path) {
497    return null;
498  }
499
500  @Override
501  public BindingResolution resolveBinding(StructureDefinition profile, String url, String path) {
502    return null;
503  }
504
505  @Override
506  public String getLinkForProfile(StructureDefinition profile, String url) {
507    return null;
508  }
509
510  public Questionnaire getQuestionnaire() {
511    return questionnaire;
512  }
513
514  public void setQuestionnaire(Questionnaire questionnaire) {
515    this.questionnaire = questionnaire;
516  }
517
518  @Override
519  public List<StructureDefinition> allStructures() {
520    List<StructureDefinition> result = new ArrayList<StructureDefinition>();
521    Set<StructureDefinition> set = new HashSet<StructureDefinition>();
522    for (StructureDefinition sd : listStructures()) {
523      if (!set.contains(sd)) {
524        try {
525          generateSnapshot(sd);
526          // new XmlParser().setOutputStyle(OutputStyle.PRETTY).compose(new FileOutputStream(Utilities.path("[tmp]", "snapshot", tail(sd.getUrl())+".xml")), sd);
527        } catch (Exception e) {
528          System.out.println("Unable to generate snapshot for "+tail(sd.getUrl()) +" from "+tail(sd.getBaseDefinition())+" because "+e.getMessage());
529          if (true) {
530            e.printStackTrace();
531          }
532        }
533        result.add(sd);
534        set.add(sd);
535      }
536    }
537    return result;
538  }
539
540  private String tail(String url) {
541    if (Utilities.noString(url)) {
542      return "noname";
543    }
544    if (url.contains("/")) {
545      return url.substring(url.lastIndexOf("/")+1);
546    }
547    return url;
548  }
549
550  public void loadBinariesFromFolder(String folder) throws FileNotFoundException, Exception {
551    for (String n : new File(folder).list()) {
552      loadBytes(n, new FileInputStream(Utilities.path(folder, n)));
553    }
554  }
555  
556  public void loadBinariesFromFolder(NpmPackage pi) throws FileNotFoundException, Exception {
557    for (String n : pi.list("other")) {
558      loadBytes(n, pi.load("other", n));
559    }
560  }
561  
562  public void loadFromFolder(String folder) throws FileNotFoundException, Exception {
563    for (String n : new File(folder).list()) {
564      if (n.endsWith(".json")) 
565        loadFromFile(Utilities.path(folder, n), new JsonParser());
566      else if (n.endsWith(".xml")) 
567        loadFromFile(Utilities.path(folder, n), new XmlParser());
568    }
569  }
570  
571  private void loadFromFile(String filename, IParser p) throws FileNotFoundException, Exception {
572        Resource r; 
573        try {
574                r = p.parse(new FileInputStream(filename));
575      if (r.getResourceType() == ResourceType.Bundle) {
576        for (BundleEntryComponent e : ((Bundle) r).getEntry()) {
577          cacheResource(e.getResource());
578        }
579     } else {
580       cacheResource(r);
581     }
582        } catch (Exception e) {
583        return;
584    }
585  }
586
587  @Override
588  public boolean prependLinks() {
589    return false;
590  }
591
592  @Override
593  public boolean hasCache() {
594    return false;
595  }
596
597  @Override
598  public String getVersion() {
599    return version;
600  }
601
602  
603  public List<StructureMap> findTransformsforSource(String url) {
604    List<StructureMap> res = new ArrayList<StructureMap>();
605    for (StructureMap map : listTransforms()) {
606      boolean match = false;
607      boolean ok = true;
608      for (StructureMapStructureComponent t : map.getStructure()) {
609        if (t.getMode() == StructureMapModelMode.SOURCE) {
610          match = match || t.getUrl().equals(url);
611          ok = ok && t.getUrl().equals(url);
612        }
613      }
614      if (match && ok)
615        res.add(map);
616    }
617    return res;
618  }
619
620  public IValidatorFactory getValidatorFactory() {
621    return validatorFactory;
622  }
623
624  public void setValidatorFactory(IValidatorFactory validatorFactory) {
625    this.validatorFactory = validatorFactory;
626  }
627
628  @Override
629  public <T extends Resource> T fetchResource(Class<T> class_, String uri) {
630    T r = super.fetchResource(class_, uri);
631    if (r instanceof StructureDefinition) {
632      StructureDefinition p = (StructureDefinition)r;
633      try {
634        generateSnapshot(p);
635      } catch (Exception e) {
636        // not sure what to do in this case?
637        System.out.println("Unable to generate snapshot for "+uri+": "+e.getMessage());
638      }
639    }
640    return r;
641  }
642  
643  @Override
644  public void generateSnapshot(StructureDefinition p) throws DefinitionException, FHIRException {
645    generateSnapshot(p, false);
646  }
647  
648  @Override
649  public void generateSnapshot(StructureDefinition p, boolean logical) throws DefinitionException, FHIRException {
650    if (!p.hasSnapshot() && (logical || p.getKind() != StructureDefinitionKind.LOGICAL)) {
651      if (!p.hasBaseDefinition())
652        throw new DefinitionException("Profile "+p.getName()+" ("+p.getUrl()+") has no base and no snapshot");
653      StructureDefinition sd = fetchResource(StructureDefinition.class, p.getBaseDefinition());
654      if (sd == null && "http://hl7.org/fhir/StructureDefinition/Base".equals(p.getBaseDefinition())) {
655        sd = ProfileUtilities.makeBaseDefinition(p.getFhirVersion());
656      }
657      if (sd == null) {
658        throw new DefinitionException("Profile "+p.getName()+" ("+p.getUrl()+") base "+p.getBaseDefinition()+" could not be resolved");
659      }
660      List<ValidationMessage> msgs = new ArrayList<ValidationMessage>();
661      List<String> errors = new ArrayList<String>();
662      ProfileUtilities pu = new ProfileUtilities(this, msgs, this);
663      pu.setThrowException(false);
664      if (sd.getDerivation() == TypeDerivationRule.CONSTRAINT) {
665        pu.sortDifferential(sd, p, p.getUrl(), errors);
666      }
667      pu.setDebug(false);
668      for (String err : errors)
669        msgs.add(new ValidationMessage(Source.ProfileValidator, IssueType.EXCEPTION, p.getUserString("path"), "Error sorting Differential: "+err, ValidationMessage.IssueSeverity.ERROR));
670      pu.generateSnapshot(sd, p, p.getUrl(), Utilities.extractBaseUrl(sd.getUserString("path")), p.getName());
671      for (ValidationMessage msg : msgs) {
672        if ((!ignoreProfileErrors && msg.getLevel() == ValidationMessage.IssueSeverity.ERROR) || msg.getLevel() == ValidationMessage.IssueSeverity.FATAL)
673          throw new DefinitionException("Profile "+p.getName()+" ("+p.getUrl()+"). Error generating snapshot: "+msg.getMessage());
674      }
675      if (!p.hasSnapshot())
676        throw new FHIRException("Profile "+p.getName()+" ("+p.getUrl()+"). Error generating snapshot");
677      pu = null;
678    }
679  }
680
681  public boolean isIgnoreProfileErrors() {
682    return ignoreProfileErrors;
683  }
684
685  public void setIgnoreProfileErrors(boolean ignoreProfileErrors) {
686    this.ignoreProfileErrors = ignoreProfileErrors;
687  }
688
689  public String listMapUrls() {
690    return Utilities.listCanonicalUrls(transforms.keys());
691  }
692
693  public boolean isProgress() {
694    return progress;
695  }
696
697  public void setProgress(boolean progress) {
698    this.progress = progress;
699  }
700
701
702
703
704}