Search in sources :

Example 6 with IgLoader

use of org.hl7.fhir.validation.IgLoader in project org.hl7.fhir.core by hapifhir.

the class ValidationService method scanForVersions.

public VersionSourceInformation scanForVersions(CliContext cliContext) throws Exception {
    VersionSourceInformation versions = new VersionSourceInformation();
    IgLoader igLoader = new IgLoader(new FilesystemPackageCacheManager(true, ToolsVersion.TOOLS_VERSION), new SimpleWorkerContext.SimpleWorkerContextBuilder().fromNothing(), null);
    for (String src : cliContext.getIgs()) {
        igLoader.scanForIgVersion(src, cliContext.isRecursive(), versions);
    }
    igLoader.scanForVersions(cliContext.getSources(), versions);
    return versions;
}
Also used : IgLoader(org.hl7.fhir.validation.IgLoader) FilesystemPackageCacheManager(org.hl7.fhir.utilities.npm.FilesystemPackageCacheManager) VersionSourceInformation(org.hl7.fhir.validation.cli.utils.VersionSourceInformation)

Example 7 with IgLoader

use of org.hl7.fhir.validation.IgLoader in project org.hl7.fhir.core by hapifhir.

the class ValidationService method initializeValidator.

public String initializeValidator(CliContext cliContext, String definitions, TimeTracker tt, String sessionId) throws Exception {
    tt.milestone();
    if (!sessionCache.sessionExists(sessionId)) {
        if (sessionId != null) {
            System.out.println("No such cached session exists for session id " + sessionId + ", re-instantiating validator.");
        }
        System.out.print("  Load FHIR v" + cliContext.getSv() + " from " + definitions);
        ValidationEngine validator = new ValidationEngine.ValidationEngineBuilder().withVersion(cliContext.getSv()).withTimeTracker(tt).withUserAgent("fhir/validator").fromSource(definitions);
        sessionId = sessionCache.cacheSession(validator);
        FhirPublication ver = FhirPublication.fromCode(cliContext.getSv());
        IgLoader igLoader = new IgLoader(validator.getPcm(), validator.getContext(), validator.getVersion(), validator.isDebug());
        System.out.println(" - " + validator.getContext().countAllCaches() + " resources (" + tt.milestone() + ")");
        igLoader.loadIg(validator.getIgs(), validator.getBinaries(), "hl7.terminology", false);
        System.out.print("  Terminology server " + cliContext.getTxServer());
        String txver = validator.setTerminologyServer(cliContext.getTxServer(), cliContext.getTxLog(), ver);
        System.out.println(" - Version " + txver + " (" + tt.milestone() + ")");
        validator.setDebug(cliContext.isDoDebug());
        validator.getContext().setLogger(new SystemOutLoggingService(cliContext.isDoDebug()));
        for (String src : cliContext.getIgs()) {
            igLoader.loadIg(validator.getIgs(), validator.getBinaries(), src, cliContext.isRecursive());
        }
        System.out.print("  Get set... ");
        validator.setQuestionnaireMode(cliContext.getQuestionnaireMode());
        validator.setLevel(cliContext.getLevel());
        validator.setDoNative(cliContext.isDoNative());
        validator.setHintAboutNonMustSupport(cliContext.isHintAboutNonMustSupport());
        for (String s : cliContext.getExtensions()) {
            if ("*".equals(s)) {
                validator.setAnyExtensionsAllowed(true);
            } else {
                validator.getExtensionDomains().add(s);
            }
        }
        validator.setLanguage(cliContext.getLang());
        validator.setLocale(cliContext.getLocale());
        validator.setSnomedExtension(cliContext.getSnomedCTCode());
        validator.setAssumeValidRestReferences(cliContext.isAssumeValidRestReferences());
        validator.setShowMessagesFromReferences(cliContext.isShowMessagesFromReferences());
        validator.setNoExtensibleBindingMessages(cliContext.isNoExtensibleBindingMessages());
        validator.setNoUnicodeBiDiControlChars(cliContext.isNoUnicodeBiDiControlChars());
        validator.setNoInvariantChecks(cliContext.isNoInvariants());
        validator.setWantInvariantInMessage(cliContext.isWantInvariantsInMessages());
        validator.setSecurityChecks(cliContext.isSecurityChecks());
        validator.setCrumbTrails(cliContext.isCrumbTrails());
        validator.setShowTimes(cliContext.isShowTimes());
        validator.setAllowExampleUrls(cliContext.isAllowExampleUrls());
        StandAloneValidatorFetcher fetcher = new StandAloneValidatorFetcher(validator.getPcm(), validator.getContext(), validator);
        validator.setFetcher(fetcher);
        validator.getContext().setLocator(fetcher);
        validator.getBundleValidationRules().addAll(cliContext.getBundleValidationRules());
        TerminologyCache.setNoCaching(cliContext.isNoInternalCaching());
        // generate any missing snapshots
        validator.prepare();
        System.out.println(" go (" + tt.milestone() + ")");
    } else {
        System.out.println("Cached session exists for session id " + sessionId + ", returning stored validator session id.");
    }
    return sessionId;
}
Also used : IgLoader(org.hl7.fhir.validation.IgLoader) FhirPublication(org.hl7.fhir.utilities.FhirPublication) SystemOutLoggingService(org.hl7.fhir.r5.context.SystemOutLoggingService) ValidationEngine(org.hl7.fhir.validation.ValidationEngine)

Example 8 with IgLoader

use of org.hl7.fhir.validation.IgLoader in project org.hl7.fhir.core by hapifhir.

the class LoadIgTests method testLoad.

@Test
public void testLoad() {
    String id = "hl7.fhir.r4.core";
    String version = "4.0.1";
    int DO_TIMES = 10;
    try {
        final String fhirSpecVersion = "4.0";
        final String definitions = VersionUtilities.packageForVersion(fhirSpecVersion) + "#" + VersionUtilities.getCurrentVersion(fhirSpecVersion);
        ValidationEngine hl7Validator = new ValidationEngine.ValidationEngineBuilder().fromSource(definitions);
        hl7Validator.setDoNative(false);
        hl7Validator.setAnyExtensionsAllowed(true);
        hl7Validator.prepare();
        IgLoader igLoader = new IgLoader(hl7Validator.getPcm(), hl7Validator.getContext(), hl7Validator.getVersion(), true);
        // yes the choice of R5 is deliberate here - it's the same content as R4.
        byte[] b = TextFile.streamToBytes(TestingUtilities.loadTestResourceStream("r5", "snapshot-generation", "t34-expected.xml"));
        for (int i = 0; i < DO_TIMES; i++) {
            System.gc();
            for (int j = 0; j < 100; j++) {
                igLoader.loadResourceByVersion("4.0.1", b, "resource.xml");
            }
            System.out.print("loading: allocated memory " + getUsedMemoryAsMbs() + " MB, ");
            System.out.print("free memory " + getFreeMemoryAsMbs() + " MB, ");
            System.out.println("max memory " + getTotalMemoryAsMbs() + " MB");
            // The method under test:
            igLoader.loadIg(hl7Validator.getIgs(), hl7Validator.getBinaries(), id + (version != null ? "#" + version : ""), true);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
// loadResourceByVersion
}
Also used : IgLoader(org.hl7.fhir.validation.IgLoader) ValidationEngine(org.hl7.fhir.validation.ValidationEngine) Test(org.junit.Test)

Example 9 with IgLoader

use of org.hl7.fhir.validation.IgLoader in project org.hl7.fhir.core by hapifhir.

the class ValidationEngineTests method test301USCore.

@Test
public void test301USCore() throws Exception {
    if (!TestUtilities.silent)
        System.out.println("Test301USCore: Validate patient300.xml against US-Core");
    ValidationEngine ve = TestUtilities.getValidationEngine("hl7.fhir.r3.core#3.0.2", DEF_TX, FhirPublication.STU3, "3.0.2");
    CacheVerificationLogger logger = new CacheVerificationLogger();
    ve.getContext().getTxClient().setLogger(logger);
    IgLoader igLoader = new IgLoader(ve.getPcm(), ve.getContext(), ve.getVersion(), true);
    if (!TestUtilities.silent)
        System.out.println("  .. load USCore");
    igLoader.loadIg(ve.getIgs(), ve.getBinaries(), "hl7.fhir.us.core#1.0.1", false);
    List<String> profiles = new ArrayList<>();
    profiles.add("http://hl7.org/fhir/us/core/StructureDefinition/us-core-patient");
    OperationOutcome op = ve.validate(FhirFormat.XML, TestingUtilities.loadTestResourceStream("validator", "patient301.xml"), profiles);
    if (!TestUtilities.silent)
        for (OperationOutcomeIssueComponent issue : op.getIssue()) System.out.println("  - " + issue.getDetails().getText());
    int e = errors(op);
    int w = warnings(op);
    int h = hints(op);
    Assertions.assertEquals(1, e);
    Assertions.assertEquals(0, w);
    Assertions.assertEquals(0, h);
    assertTrue(logger.verifyHasNoRequests(), "Unexpected request to TX server");
    if (!TestUtilities.silent)
        System.out.println("  .. done: " + Integer.toString(e) + " errors, " + Integer.toString(w) + " warnings, " + Integer.toString(h) + " information messages");
}
Also used : IgLoader(org.hl7.fhir.validation.IgLoader) OperationOutcomeIssueComponent(org.hl7.fhir.r5.model.OperationOutcome.OperationOutcomeIssueComponent) CacheVerificationLogger(org.hl7.fhir.utilities.tests.CacheVerificationLogger) OperationOutcome(org.hl7.fhir.r5.model.OperationOutcome) ArrayList(java.util.ArrayList) ValidationEngine(org.hl7.fhir.validation.ValidationEngine) Test(org.junit.jupiter.api.Test)

Example 10 with IgLoader

use of org.hl7.fhir.validation.IgLoader in project org.hl7.fhir.core by hapifhir.

the class IgLoader method loadIg.

/**
 * @param igs
 * @param binaries
 * @param src Source of the IG
 *
 * @param recursive
 * @throws IOException
 * @throws FHIRException
 *
 * @see IgLoader#loadIgSource(String, boolean, boolean) loadIgSource for detailed description of the src parameter
 */
public void loadIg(List<ImplementationGuide> igs, Map<String, byte[]> binaries, String src, boolean recursive) throws IOException, FHIRException {
    final String explicitFhirVersion;
    final String srcPackage;
    if (src.startsWith("[") && src.indexOf(']', 1) > 1) {
        explicitFhirVersion = src.substring(1, src.indexOf(']', 1));
        srcPackage = src.substring(src.indexOf(']', 1) + 1);
        if (!VersionUtilities.isSupportedVersion(explicitFhirVersion)) {
            throw new FHIRException("Unsupported FHIR Version: " + explicitFhirVersion + " valid versions are " + VersionUtilities.listSupportedVersions());
        }
    } else {
        explicitFhirVersion = null;
        srcPackage = src;
    }
    NpmPackage npm = srcPackage.matches(FilesystemPackageCacheManager.PACKAGE_VERSION_REGEX_OPT) && !new File(srcPackage).exists() ? getPackageCacheManager().loadPackage(srcPackage, null) : null;
    if (npm != null) {
        for (String s : npm.dependencies()) {
            if (!getContext().getLoadedPackages().contains(s)) {
                if (!VersionUtilities.isCorePackage(s)) {
                    loadIg(igs, binaries, s, false);
                }
            }
        }
        System.out.print("  Load " + srcPackage);
        if (!srcPackage.contains("#")) {
            System.out.print("#" + npm.version());
        }
        int count = getContext().loadFromPackage(npm, ValidatorUtils.loaderForVersion(npm.fhirVersion()));
        System.out.println(" - " + count + " resources (" + getContext().clock().milestone() + ")");
    } else {
        System.out.print("  Load " + srcPackage);
        String canonical = null;
        int count = 0;
        Map<String, byte[]> source = loadIgSource(srcPackage, recursive, true);
        String version = Constants.VERSION;
        if (getVersion() != null) {
            version = getVersion();
        }
        if (source.containsKey("version.info")) {
            version = readInfoVersion(source.get("version.info"));
        }
        if (explicitFhirVersion != null) {
            version = explicitFhirVersion;
        }
        for (Map.Entry<String, byte[]> t : source.entrySet()) {
            String fn = t.getKey();
            if (!exemptFile(fn)) {
                Resource r = loadFileWithErrorChecking(version, t, fn);
                if (r != null) {
                    count++;
                    getContext().cacheResource(r);
                    if (r instanceof ImplementationGuide) {
                        canonical = ((ImplementationGuide) r).getUrl();
                        igs.add((ImplementationGuide) r);
                        if (canonical.contains("/ImplementationGuide/")) {
                            Resource r2 = r.copy();
                            ((ImplementationGuide) r2).setUrl(canonical.substring(0, canonical.indexOf("/ImplementationGuide/")));
                            getContext().cacheResource(r2);
                        }
                    }
                }
            }
        }
        if (canonical != null) {
            ValidatorUtils.grabNatives(binaries, source, canonical);
        }
        System.out.println(" - " + count + " resources (" + getContext().clock().milestone() + ")");
    }
}
Also used : ImplementationGuide(org.hl7.fhir.r5.model.ImplementationGuide) NpmPackage(org.hl7.fhir.utilities.npm.NpmPackage) Resource(org.hl7.fhir.r5.model.Resource) FHIRException(org.hl7.fhir.exceptions.FHIRException) IniFile(org.hl7.fhir.utilities.IniFile) TextFile(org.hl7.fhir.utilities.TextFile) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

IgLoader (org.hl7.fhir.validation.IgLoader)6 FHIRException (org.hl7.fhir.exceptions.FHIRException)5 ValidationEngine (org.hl7.fhir.validation.ValidationEngine)4 ImplementationGuide (org.hl7.fhir.r5.model.ImplementationGuide)3 Test (org.junit.Test)3 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 DefinitionException (org.hl7.fhir.exceptions.DefinitionException)2 NpmPackage (org.hl7.fhir.utilities.npm.NpmPackage)2 CacheVerificationLogger (org.hl7.fhir.utilities.tests.CacheVerificationLogger)2 Test (org.junit.jupiter.api.Test)2 JsonElement (com.google.gson.JsonElement)1 JsonObject (com.google.gson.JsonObject)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 FileNotFoundException (java.io.FileNotFoundException)1 InputStream (java.io.InputStream)1 MalformedURLException (java.net.MalformedURLException)1 URISyntaxException (java.net.URISyntaxException)1