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.IOException; 029import java.io.InputStream; 030import java.net.URISyntaxException; 031import java.util.ArrayList; 032import java.util.Arrays; 033import java.util.Collections; 034import java.util.HashMap; 035import java.util.HashSet; 036import java.util.List; 037import java.util.Map; 038import java.util.Set; 039import java.util.zip.ZipEntry; 040import java.util.zip.ZipInputStream; 041 042import org.apache.commons.io.IOUtils; 043import org.hl7.fhir.exceptions.DefinitionException; 044import org.hl7.fhir.exceptions.FHIRException; 045import org.hl7.fhir.exceptions.FHIRFormatError; 046import org.hl7.fhir.r5.conformance.ProfileUtilities; 047import org.hl7.fhir.r5.conformance.ProfileUtilities.ProfileKnowledgeProvider; 048import org.hl7.fhir.r5.context.IWorkerContext.ILoggingService.LogCategory; 049import org.hl7.fhir.r5.formats.IParser; 050import org.hl7.fhir.r5.formats.JsonParser; 051import org.hl7.fhir.r5.formats.ParserType; 052import org.hl7.fhir.r5.formats.XmlParser; 053import org.hl7.fhir.r5.model.Bundle; 054import org.hl7.fhir.r5.model.Bundle.BundleEntryComponent; 055import org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionBindingComponent; 056import org.hl7.fhir.r5.model.ImplementationGuide; 057import org.hl7.fhir.r5.model.MetadataResource; 058import org.hl7.fhir.r5.model.Questionnaire; 059import org.hl7.fhir.r5.model.Resource; 060import org.hl7.fhir.r5.model.ResourceType; 061import org.hl7.fhir.r5.model.StructureDefinition; 062import org.hl7.fhir.r5.model.StructureDefinition.StructureDefinitionKind; 063import org.hl7.fhir.r5.model.StructureDefinition.TypeDerivationRule; 064import org.hl7.fhir.r5.model.StructureMap; 065import org.hl7.fhir.r5.model.StructureMap.StructureMapModelMode; 066import org.hl7.fhir.r5.model.StructureMap.StructureMapStructureComponent; 067import org.hl7.fhir.r5.terminologies.TerminologyClient; 068import org.hl7.fhir.r5.utils.INarrativeGenerator; 069import org.hl7.fhir.r5.utils.IResourceValidator; 070import org.hl7.fhir.r5.utils.NarrativeGenerator; 071import org.hl7.fhir.utilities.CSFileInputStream; 072import org.hl7.fhir.utilities.Utilities; 073import org.hl7.fhir.utilities.cache.NpmPackage; 074import org.hl7.fhir.utilities.validation.ValidationMessage; 075import org.hl7.fhir.utilities.validation.ValidationMessage.IssueType; 076import org.hl7.fhir.utilities.validation.ValidationMessage.Source; 077 078import ca.uhn.fhir.parser.DataFormatException; 079 080/* 081 * This is a stand alone implementation of worker context for use inside a tool. 082 * It loads from the validation package (validation-min.xml.zip), and has a 083 * very light client to connect to an open unauthenticated terminology service 084 */ 085 086public class SimpleWorkerContext extends BaseWorkerContext implements IWorkerContext, ProfileKnowledgeProvider { 087 088 public interface IContextResourceLoader { 089 Bundle loadBundle(InputStream stream, boolean isJson) throws FHIRException, IOException; 090 } 091 092 public interface IValidatorFactory { 093 IResourceValidator makeValidator(IWorkerContext ctxts) throws FHIRException; 094 } 095 096 private Questionnaire questionnaire; 097 private Map<String, byte[]> binaries = new HashMap<String, byte[]>(); 098 private String version; 099 private String revision; 100 private String date; 101 private IValidatorFactory validatorFactory; 102 private boolean ignoreProfileErrors; 103 104 public SimpleWorkerContext() throws FileNotFoundException, IOException, FHIRException { 105 super(); 106 } 107 108 public SimpleWorkerContext(SimpleWorkerContext other) throws FileNotFoundException, IOException, FHIRException { 109 super(); 110 copy(other); 111 } 112 113 protected void copy(SimpleWorkerContext other) { 114 super.copy(other); 115 questionnaire = other.questionnaire; 116 binaries.putAll(other.binaries); 117 version = other.version; 118 revision = other.revision; 119 date = other.date; 120 validatorFactory = other.validatorFactory; 121 } 122 123 // -- Initializations 124 /** 125 * Load the working context from the validation pack 126 * 127 * @param path 128 * filename of the validation pack 129 * @return 130 * @throws IOException 131 * @throws FileNotFoundException 132 * @throws FHIRException 133 * @throws Exception 134 */ 135 public static SimpleWorkerContext fromPack(String path) throws FileNotFoundException, IOException, FHIRException { 136 SimpleWorkerContext res = new SimpleWorkerContext(); 137 res.loadFromPack(path, null); 138 return res; 139 } 140 141 public static SimpleWorkerContext fromPackage(NpmPackage pi, boolean allowDuplicates) throws FileNotFoundException, IOException, FHIRException { 142 SimpleWorkerContext res = new SimpleWorkerContext(); 143 res.setAllowLoadingDuplicates(allowDuplicates); 144 res.loadFromPackage(pi, null); 145 return res; 146 } 147 148 public static SimpleWorkerContext fromPackage(NpmPackage pi) throws FileNotFoundException, IOException, FHIRException { 149 SimpleWorkerContext res = new SimpleWorkerContext(); 150 res.loadFromPackage(pi, null); 151 return res; 152 } 153 154 public static SimpleWorkerContext fromPackage(NpmPackage pi, IContextResourceLoader loader) throws FileNotFoundException, IOException, FHIRException { 155 SimpleWorkerContext res = new SimpleWorkerContext(); 156 res.setAllowLoadingDuplicates(true); 157 res.version = pi.getNpm().get("version").getAsString(); 158 res.loadFromPackage(pi, loader); 159 return res; 160 } 161 162 public static SimpleWorkerContext fromPack(String path, boolean allowDuplicates) throws FileNotFoundException, IOException, FHIRException { 163 SimpleWorkerContext res = new SimpleWorkerContext(); 164 res.setAllowLoadingDuplicates(allowDuplicates); 165 res.loadFromPack(path, null); 166 return res; 167 } 168 169 public static SimpleWorkerContext fromPack(String path, IContextResourceLoader loader) throws FileNotFoundException, IOException, FHIRException { 170 SimpleWorkerContext res = new SimpleWorkerContext(); 171 res.loadFromPack(path, loader); 172 return res; 173 } 174 175 public static SimpleWorkerContext fromClassPath() throws IOException, FHIRException { 176 SimpleWorkerContext res = new SimpleWorkerContext(); 177 res.loadFromStream(SimpleWorkerContext.class.getResourceAsStream("validation.json.zip"), null); 178 return res; 179 } 180 181 public static SimpleWorkerContext fromClassPath(String name) throws IOException, FHIRException { 182 InputStream s = SimpleWorkerContext.class.getResourceAsStream("/"+name); 183 SimpleWorkerContext res = new SimpleWorkerContext(); 184 res.loadFromStream(s, null); 185 return res; 186 } 187 188 public static SimpleWorkerContext fromDefinitions(Map<String, byte[]> source) throws IOException, FHIRException { 189 SimpleWorkerContext res = new SimpleWorkerContext(); 190 for (String name : source.keySet()) { 191 res.loadDefinitionItem(name, new ByteArrayInputStream(source.get(name)), null); 192 } 193 return res; 194 } 195 196 public static SimpleWorkerContext fromDefinitions(Map<String, byte[]> source, IContextResourceLoader loader) throws FileNotFoundException, IOException, FHIRException { 197 SimpleWorkerContext res = new SimpleWorkerContext(); 198 for (String name : source.keySet()) { 199 try { 200 res.loadDefinitionItem(name, new ByteArrayInputStream(source.get(name)), loader); 201 } catch (Exception e) { 202 System.out.println("Error loading "+name+": "+e.getMessage()); 203 throw new FHIRException("Error loading "+name+": "+e.getMessage(), e); 204 } 205 } 206 return res; 207 } 208 private void loadDefinitionItem(String name, InputStream stream, IContextResourceLoader loader) throws IOException, FHIRException { 209 if (name.endsWith(".xml")) 210 loadFromFile(stream, name, loader); 211 else if (name.endsWith(".json")) 212 loadFromFileJson(stream, name, loader); 213 else if (name.equals("version.info")) 214 readVersionInfo(stream); 215 else 216 loadBytes(name, stream); 217 } 218 219 220 public String connectToTSServer(TerminologyClient client, String log) { 221 try { 222 tlog("Connect to "+client.getAddress()); 223 txClient = client; 224 txLog = new HTMLClientLogger(log); 225 txClient.setLogger(txLog); 226 return txClient.getCapabilitiesStatementQuick().getSoftware().getVersion(); 227 } catch (Exception e) { 228 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); 229 } 230 } 231 232 public void loadFromFile(InputStream stream, String name, IContextResourceLoader loader) throws IOException, FHIRException { 233 Resource f; 234 try { 235 if (loader != null) 236 f = loader.loadBundle(stream, false); 237 else { 238 XmlParser xml = new XmlParser(); 239 f = xml.parse(stream); 240 } 241 } catch (DataFormatException e1) { 242 throw new org.hl7.fhir.exceptions.FHIRFormatError("Error parsing "+name+":" +e1.getMessage(), e1); 243 } catch (Exception e1) { 244 throw new org.hl7.fhir.exceptions.FHIRFormatError("Error parsing "+name+":" +e1.getMessage(), e1); 245 } 246 if (f instanceof Bundle) { 247 Bundle bnd = (Bundle) f; 248 for (BundleEntryComponent e : bnd.getEntry()) { 249 if (e.getFullUrl() == null) { 250 logger.logDebugMessage(LogCategory.CONTEXT, "unidentified resource in " + name+" (no fullUrl)"); 251 } 252 cacheResource(e.getResource()); 253 } 254 } else if (f instanceof MetadataResource) { 255 MetadataResource m = (MetadataResource) f; 256 cacheResource(m); 257 } 258 } 259 260 private void loadFromFileJson(InputStream stream, String name, IContextResourceLoader loader) throws IOException, FHIRException { 261 Bundle f = null; 262 try { 263 if (loader != null) 264 f = loader.loadBundle(stream, true); 265 else { 266 JsonParser json = new JsonParser(); 267 Resource r = json.parse(stream); 268 if (r instanceof Bundle) 269 f = (Bundle) r; 270 else 271 cacheResource(r); 272 } 273 } catch (FHIRFormatError e1) { 274 throw new org.hl7.fhir.exceptions.FHIRFormatError(e1.getMessage(), e1); 275 } 276 if (f != null) 277 for (BundleEntryComponent e : f.getEntry()) { 278 cacheResource(e.getResource()); 279 } 280 } 281 282 private void loadFromPack(String path, IContextResourceLoader loader) throws FileNotFoundException, IOException, FHIRException { 283 loadFromStream(new CSFileInputStream(path), loader); 284 } 285 286 public void loadFromPackage(NpmPackage pi, IContextResourceLoader loader, String... types) throws FileNotFoundException, IOException, FHIRException { 287 if (types.length == 0) 288 types = new String[] { "StructureDefinition", "ValueSet", "CodeSystem", "SearchParameter", "OperationDefinition", "Questionnaire","ConceptMap","StructureMap", "NamingSystem"}; 289 for (String s : pi.listResources(types)) { 290 loadDefinitionItem(s, pi.load("package", s), loader); 291 } 292 version = pi.version(); 293 } 294 295 public void loadFromFile(String file, IContextResourceLoader loader) throws IOException, FHIRException { 296 loadDefinitionItem(file, new CSFileInputStream(file), loader); 297 } 298 299 private void loadFromStream(InputStream stream, IContextResourceLoader loader) throws IOException, FHIRException { 300 ZipInputStream zip = new ZipInputStream(stream); 301 ZipEntry ze; 302 while ((ze = zip.getNextEntry()) != null) { 303 loadDefinitionItem(ze.getName(), zip, loader); 304 zip.closeEntry(); 305 } 306 zip.close(); 307 } 308 309 private void readVersionInfo(InputStream stream) throws IOException, DefinitionException { 310 byte[] bytes = IOUtils.toByteArray(stream); 311 binaries.put("version.info", bytes); 312 313 String[] vi = new String(bytes).split("\\r?\\n"); 314 for (String s : vi) { 315 if (s.startsWith("version=")) { 316 if (version == null) 317 version = s.substring(8); 318 else if (!version.equals(s.substring(8))) 319 throw new DefinitionException("Version mismatch. The context has version "+version+" loaded, and the new content being loaded is version "+s.substring(8)); 320 } 321 if (s.startsWith("revision=")) 322 revision = s.substring(9); 323 if (s.startsWith("date=")) 324 date = s.substring(5); 325 } 326 } 327 328 private void loadBytes(String name, InputStream stream) throws IOException { 329 byte[] bytes = IOUtils.toByteArray(stream); 330 binaries.put(name, bytes); 331 } 332 333 @Override 334 public IParser getParser(ParserType type) { 335 switch (type) { 336 case JSON: return newJsonParser(); 337 case XML: return newXmlParser(); 338 default: 339 throw new Error("Parser Type "+type.toString()+" not supported"); 340 } 341 } 342 343 @Override 344 public IParser getParser(String type) { 345 if (type.equalsIgnoreCase("JSON")) 346 return new JsonParser(); 347 if (type.equalsIgnoreCase("XML")) 348 return new XmlParser(); 349 throw new Error("Parser Type "+type.toString()+" not supported"); 350 } 351 352 @Override 353 public IParser newJsonParser() { 354 return new JsonParser(); 355 } 356 @Override 357 public IParser newXmlParser() { 358 return new XmlParser(); 359 } 360 361 @Override 362 public INarrativeGenerator getNarrativeGenerator(String prefix, String basePath) { 363 return new NarrativeGenerator(prefix, basePath, this); 364 } 365 366 @Override 367 public IResourceValidator newValidator() throws FHIRException { 368 if (validatorFactory == null) 369 throw new Error("No validator configured"); 370 return validatorFactory.makeValidator(this); 371 } 372 373 374 375 376 @Override 377 public List<String> getResourceNames() { 378 List<String> result = new ArrayList<String>(); 379 for (StructureDefinition sd : listStructures()) { 380 if (sd.getKind() == StructureDefinitionKind.RESOURCE && sd.getDerivation() == TypeDerivationRule.SPECIALIZATION) 381 result.add(sd.getName()); 382 } 383 Collections.sort(result); 384 return result; 385 } 386 387 @Override 388 public List<String> getTypeNames() { 389 List<String> result = new ArrayList<String>(); 390 for (StructureDefinition sd : listStructures()) { 391 if (sd.getKind() != StructureDefinitionKind.LOGICAL && sd.getDerivation() == TypeDerivationRule.SPECIALIZATION) 392 result.add(sd.getName()); 393 } 394 Collections.sort(result); 395 return result; 396 } 397 398 @Override 399 public String getAbbreviation(String name) { 400 return "xxx"; 401 } 402 403 @Override 404 public boolean isDatatype(String typeSimple) { 405 // TODO Auto-generated method stub 406 return false; 407 } 408 409 @Override 410 public boolean isResource(String t) { 411 StructureDefinition sd; 412 try { 413 sd = fetchResource(StructureDefinition.class, "http://hl7.org/fhir/StructureDefinition/"+t); 414 } catch (Exception e) { 415 return false; 416 } 417 if (sd == null) 418 return false; 419 if (sd.getDerivation() == TypeDerivationRule.CONSTRAINT) 420 return false; 421 return sd.getKind() == StructureDefinitionKind.RESOURCE; 422 } 423 424 @Override 425 public boolean hasLinkFor(String typeSimple) { 426 return false; 427 } 428 429 @Override 430 public String getLinkFor(String corePath, String typeSimple) { 431 return null; 432 } 433 434 @Override 435 public BindingResolution resolveBinding(StructureDefinition profile, ElementDefinitionBindingComponent binding, String path) { 436 return null; 437 } 438 439 @Override 440 public BindingResolution resolveBinding(StructureDefinition profile, String url, String path) { 441 return null; 442 } 443 444 @Override 445 public String getLinkForProfile(StructureDefinition profile, String url) { 446 return null; 447 } 448 449 public Questionnaire getQuestionnaire() { 450 return questionnaire; 451 } 452 453 public void setQuestionnaire(Questionnaire questionnaire) { 454 this.questionnaire = questionnaire; 455 } 456 457 @Override 458 public Set<String> typeTails() { 459 return new HashSet<String>(Arrays.asList("Integer","UnsignedInt","PositiveInt","Decimal","DateTime","Date","Time","Instant","String","Uri","Url","Canonical","Oid","Uuid","Id","Boolean","Code","Markdown","Base64Binary","Coding","CodeableConcept","Attachment","Identifier","Quantity","SampledData","Range","Period","Ratio","HumanName","Address","ContactPoint","Timing","Reference","Annotation","Signature","Meta")); 460 } 461 462 @Override 463 public List<StructureDefinition> allStructures() { 464 List<StructureDefinition> result = new ArrayList<StructureDefinition>(); 465 Set<StructureDefinition> set = new HashSet<StructureDefinition>(); 466 for (StructureDefinition sd : listStructures()) { 467 if (!set.contains(sd)) { 468 try { 469 generateSnapshot(sd); 470 } catch (Exception e) { 471 System.out.println("Unable to generate snapshot for "+sd.getUrl()+" because "+e.getMessage()); 472 } 473 result.add(sd); 474 set.add(sd); 475 } 476 } 477 return result; 478 } 479 480 public void loadBinariesFromFolder(String folder) throws FileNotFoundException, Exception { 481 for (String n : new File(folder).list()) { 482 loadBytes(n, new FileInputStream(Utilities.path(folder, n))); 483 } 484 } 485 486 public void loadBinariesFromFolder(NpmPackage pi) throws FileNotFoundException, Exception { 487 for (String n : pi.list("other")) { 488 loadBytes(n, pi.load("other", n)); 489 } 490 } 491 492 public void loadFromFolder(String folder) throws FileNotFoundException, Exception { 493 for (String n : new File(folder).list()) { 494 if (n.endsWith(".json")) 495 loadFromFile(Utilities.path(folder, n), new JsonParser()); 496 else if (n.endsWith(".xml")) 497 loadFromFile(Utilities.path(folder, n), new XmlParser()); 498 } 499 } 500 501 private void loadFromFile(String filename, IParser p) throws FileNotFoundException, Exception { 502 Resource r; 503 try { 504 r = p.parse(new FileInputStream(filename)); 505 if (r.getResourceType() == ResourceType.Bundle) { 506 for (BundleEntryComponent e : ((Bundle) r).getEntry()) { 507 cacheResource(e.getResource()); 508 } 509 } else { 510 cacheResource(r); 511 } 512 } catch (Exception e) { 513 return; 514 } 515 } 516 517 public Map<String, byte[]> getBinaries() { 518 return binaries; 519 } 520 521 @Override 522 public boolean prependLinks() { 523 return false; 524 } 525 526 @Override 527 public boolean hasCache() { 528 return false; 529 } 530 531 @Override 532 public String getVersion() { 533 return version; 534 } 535 536 537 public List<StructureMap> findTransformsforSource(String url) { 538 List<StructureMap> res = new ArrayList<StructureMap>(); 539 for (StructureMap map : listTransforms()) { 540 boolean match = false; 541 boolean ok = true; 542 for (StructureMapStructureComponent t : map.getStructure()) { 543 if (t.getMode() == StructureMapModelMode.SOURCE) { 544 match = match || t.getUrl().equals(url); 545 ok = ok && t.getUrl().equals(url); 546 } 547 } 548 if (match && ok) 549 res.add(map); 550 } 551 return res; 552 } 553 554 public IValidatorFactory getValidatorFactory() { 555 return validatorFactory; 556 } 557 558 public void setValidatorFactory(IValidatorFactory validatorFactory) { 559 this.validatorFactory = validatorFactory; 560 } 561 562 @Override 563 public <T extends Resource> T fetchResource(Class<T> class_, String uri) { 564 T r = super.fetchResource(class_, uri); 565 if (r instanceof StructureDefinition) { 566 StructureDefinition p = (StructureDefinition)r; 567 try { 568 generateSnapshot(p); 569 } catch (Exception e) { 570 // not sure what to do in this case? 571 System.out.println("Unable to generate snapshot for "+uri+": "+e.getMessage()); 572 } 573 } 574 return r; 575 } 576 577 public void generateSnapshot(StructureDefinition p) throws DefinitionException, FHIRException { 578 if (!p.hasSnapshot() && p.getKind() != StructureDefinitionKind.LOGICAL) { 579 if (!p.hasBaseDefinition()) 580 throw new DefinitionException("Profile "+p.getName()+" ("+p.getUrl()+") has no base and no snapshot"); 581 StructureDefinition sd = fetchResource(StructureDefinition.class, p.getBaseDefinition()); 582 if (sd == null) 583 throw new DefinitionException("Profile "+p.getName()+" ("+p.getUrl()+") base "+p.getBaseDefinition()+" could not be resolved"); 584 List<ValidationMessage> msgs = new ArrayList<ValidationMessage>(); 585 List<String> errors = new ArrayList<String>(); 586 ProfileUtilities pu = new ProfileUtilities(this, msgs, this); 587 pu.setThrowException(false); 588 pu.sortDifferential(sd, p, p.getUrl(), errors); 589 for (String err : errors) 590 msgs.add(new ValidationMessage(Source.ProfileValidator, IssueType.EXCEPTION, p.getUserString("path"), "Error sorting Differential: "+err, ValidationMessage.IssueSeverity.ERROR)); 591 pu.generateSnapshot(sd, p, p.getUrl(), Utilities.extractBaseUrl(sd.getUserString("path")), p.getName()); 592 for (ValidationMessage msg : msgs) { 593 if ((!ignoreProfileErrors && msg.getLevel() == ValidationMessage.IssueSeverity.ERROR) || msg.getLevel() == ValidationMessage.IssueSeverity.FATAL) 594 throw new DefinitionException("Profile "+p.getName()+" ("+p.getUrl()+"). Error generating snapshot: "+msg.getMessage()); 595 } 596 if (!p.hasSnapshot()) 597 throw new FHIRException("Profile "+p.getName()+" ("+p.getUrl()+"). Error generating snapshot"); 598 pu = null; 599 } 600 } 601 602 public boolean isIgnoreProfileErrors() { 603 return ignoreProfileErrors; 604 } 605 606 public void setIgnoreProfileErrors(boolean ignoreProfileErrors) { 607 this.ignoreProfileErrors = ignoreProfileErrors; 608 } 609 610 public String listMapUrls() { 611 return Utilities.listCanonicalUrls(transforms.keys()); 612 } 613 614 615 616 617}