Search in sources :

Example 1 with IResourceValidator

use of org.hl7.fhir.r5.utils.validation.IResourceValidator in project kindling by HL7.

the class ExampleInspector method fetch.

@Override
public Element fetch(IResourceValidator validator, Object appContext, String url) throws IOException, FHIRException {
    String[] parts = url.split("\\/");
    if (parts.length == 2 && definitions.hasResource(parts[0])) {
        ResourceDefn r = definitions.getResourceByName(parts[0]);
        for (Example e : r.getExamples()) {
            if (e.getElement() == null && e.hasXml()) {
                e.setElement(new org.hl7.fhir.r5.elementmodel.XmlParser(context).parse(e.getXml()));
                if (e.getElement().getProperty().getStructure().getBaseDefinition().contains("MetadataResource")) {
                    String urle = e.getElement().getChildValue("url");
                    String v = e.getElement().getChildValue("url");
                    if (urle != null && urle.startsWith("http://hl7.org/fhir") && !version.toCode().equals(v)) {
                        e.getElement().setChildValue("version", version.toCode());
                    }
                }
            }
            if (e.getElement() != null) {
                if (e.getElement().fhirType().equals("Bundle")) {
                    for (Base b : e.getElement().listChildrenByName("entry")) {
                        if (b.getChildByName("resource").hasValues()) {
                            Element res = (Element) b.getChildByName("resource").getValues().get(0);
                            if (res.fhirType().equals(parts[0]) && parts[1].equals(res.getChildValue("id"))) {
                                return res;
                            }
                        }
                    }
                } else if (e.getElement().fhirType().equals(parts[0]) && e.getId().equals(parts[1])) {
                    return e.getElement();
                }
            }
        }
        try {
            if (parts[0].equals("StructureDefinition"))
                return new ObjectConverter(context).convert(context.fetchResourceWithException(StructureDefinition.class, "http://hl7.org/fhir/" + parts[0] + "/" + parts[1]));
            if (parts[0].equals("OperationDefinition"))
                return new ObjectConverter(context).convert(context.fetchResourceWithException(OperationDefinition.class, "http://hl7.org/fhir/" + parts[0] + "/" + parts[1]));
            if (parts[0].equals("SearchParameter"))
                return new ObjectConverter(context).convert(context.fetchResourceWithException(SearchParameter.class, "http://hl7.org/fhir/" + parts[0] + "/" + parts[1]));
            if (parts[0].equals("ValueSet"))
                return new ObjectConverter(context).convert(context.fetchResourceWithException(ValueSet.class, "http://hl7.org/fhir/" + parts[0] + "/" + parts[1]));
            if (parts[0].equals("CodeSystem"))
                return new ObjectConverter(context).convert(context.fetchResourceWithException(CodeSystem.class, "http://hl7.org/fhir/" + parts[0] + "/" + parts[1]));
        } catch (Exception e) {
            return null;
        }
        return null;
    } else
        return null;
}
Also used : XmlParser(org.hl7.fhir.r5.formats.XmlParser) ObjectConverter(org.hl7.fhir.r5.elementmodel.ObjectConverter) Example(org.hl7.fhir.definitions.model.Example) Element(org.hl7.fhir.r5.elementmodel.Element) ResourceDefn(org.hl7.fhir.definitions.model.ResourceDefn) Base(org.hl7.fhir.r5.model.Base) URISyntaxException(java.net.URISyntaxException) FileNotFoundException(java.io.FileNotFoundException) SAXException(org.xml.sax.SAXException) NotImplementedException(org.apache.commons.lang3.NotImplementedException) DefinitionException(org.hl7.fhir.exceptions.DefinitionException) PathEngineException(org.hl7.fhir.exceptions.PathEngineException) ValidationException(org.everit.json.schema.ValidationException) MalformedURLException(java.net.MalformedURLException) JsonSyntaxException(com.google.gson.JsonSyntaxException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) FHIRException(org.hl7.fhir.exceptions.FHIRException)

Example 2 with IResourceValidator

use of org.hl7.fhir.r5.utils.validation.IResourceValidator in project org.hl7.fhir.core by hapifhir.

the class FFHIRPathHostServices method conformsToProfile.

@Override
public boolean conformsToProfile(Object appContext, Base item, String url) throws FHIRException {
    IResourceValidator val = structureMapUtilities.getWorker().newValidator();
    List<ValidationMessage> valerrors = new ArrayList<ValidationMessage>();
    if (item instanceof Resource) {
        val.validate(appContext, valerrors, (Resource) item, url);
        return noErrorValidationMessages(valerrors);
    }
    if (item instanceof Element) {
        val.validate(appContext, valerrors, null, (Element) item, url);
        return noErrorValidationMessages(valerrors);
    }
    throw new NotImplementedException("Not done yet (FFHIRPathHostServices.conformsToProfile), when item is not element or not resource");
}
Also used : ValidationMessage(org.hl7.fhir.utilities.validation.ValidationMessage) IResourceValidator(org.hl7.fhir.r4b.utils.validation.IResourceValidator) Element(org.hl7.fhir.r4b.elementmodel.Element) NotImplementedException(org.apache.commons.lang3.NotImplementedException) ArrayList(java.util.ArrayList) Resource(org.hl7.fhir.r4b.model.Resource)

Example 3 with IResourceValidator

use of org.hl7.fhir.r5.utils.validation.IResourceValidator in project org.hl7.fhir.core by hapifhir.

the class StandAloneValidatorFetcher method resolveURL.

@Override
public boolean resolveURL(IResourceValidator validator, Object appContext, String path, String url, String type) throws IOException, FHIRException {
    if (!Utilities.isAbsoluteUrl(url)) {
        return false;
    }
    if (url.contains("|")) {
        url = url.substring(0, url.lastIndexOf("|"));
    }
    if (type != null && type.equals("uri") && isMappingUri(url)) {
        return true;
    }
    // if we've got to here, it's a reference to a FHIR URL. We're going to try to resolve it on the fly
    String pid = null;
    String ver = null;
    String base = findBaseUrl(url);
    if (base == null) {
        return !url.startsWith("http://hl7.org/fhir") && !type.equals("canonical");
    }
    // the next operations are expensive. we're going to cache them
    if (urlList.containsKey(url)) {
        return urlList.get(url);
    }
    if (base.equals("http://terminology.hl7.org")) {
        pid = "hl7.terminology";
    } else if (url.startsWith("http://hl7.org/fhir")) {
        pid = pcm.getPackageId(base);
    } else {
        if (pidList.containsKey(base)) {
            pid = pidList.get(base);
        } else {
            pid = pcm.findCanonicalInLocalCache(base);
            pidList.put(base, pid);
        }
    }
    ver = url.contains("|") ? url.substring(url.indexOf("|") + 1) : null;
    if (pid == null && Utilities.startsWithInList(url, "http://hl7.org/fhir", "http://terminology.hl7.org")) {
        urlList.put(url, false);
        return false;
    }
    if (url.startsWith("http://hl7.org/fhir")) {
        // first possibility: it's a reference to a version specific URL http://hl7.org/fhir/X.X/...
        VersionURLInfo vu = VersionUtilities.parseVersionUrl(url);
        if (vu != null) {
            NpmPackage pi = pcm.loadPackage(VersionUtilities.packageForVersion(vu.getVersion()), VersionUtilities.getCurrentVersion(vu.getVersion()));
            boolean res = pi.hasCanonical(vu.getUrl());
            urlList.put(url, res);
            return res;
        }
    }
    // ok maybe it's a reference to a package we know
    if (pid != null) {
        if ("sharedhealth.fhir.ca.common".equals(pid)) {
            // special case - optimise this
            return false;
        }
        NpmPackage pi = null;
        if (pidMap.containsKey(pid + "|" + ver)) {
            pi = pidMap.get(pid + "|" + ver);
        } else if (installer.packageExists(pid, ver)) {
            try {
                installer.loadPackage(pid, ver);
                pi = pcm.loadPackage(pid);
                pidMap.put(pid + "|" + ver, pi);
            } catch (Exception e) {
                pidMap.put(pid + "|" + ver, null);
            }
        } else {
            pidMap.put(pid + "|" + ver, null);
        }
        if (pi != null) {
            context.loadFromPackage(pi, null);
            return pi.hasCanonical(url);
        }
    }
    // we don't bother with urls outside fhir space in the standalone validator - we assume they are valid
    return !url.startsWith("http://hl7.org/fhir") && !type.equals("canonical");
}
Also used : NpmPackage(org.hl7.fhir.utilities.npm.NpmPackage) VersionURLInfo(org.hl7.fhir.utilities.VersionUtilities.VersionURLInfo) URISyntaxException(java.net.URISyntaxException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) FHIRException(org.hl7.fhir.exceptions.FHIRException)

Example 4 with IResourceValidator

use of org.hl7.fhir.r5.utils.validation.IResourceValidator in project org.hl7.fhir.core by hapifhir.

the class R3R4ConversionTests method test.

@SuppressWarnings("deprecation")
@ParameterizedTest(name = "{index}: id {0}")
@MethodSource("data")
public void test(String name, byte[] content) throws Exception {
    checkLoad();
    StructureMapUtilities smu4 = new StructureMapUtilities(contextR4, this);
    StructureMapUtilities smu3 = new StructureMapUtilities(contextR3, this);
    String tn = null;
    workingid = null;
    byte[] cnt = content;
    Exception executionError = null;
    List<ValidationMessage> r4validationErrors = new ArrayList<ValidationMessage>();
    String roundTripError = null;
    try {
        extras = new ArrayList<Resource>();
        // load the example (r3)
        org.hl7.fhir.r4.elementmodel.Element r3 = new org.hl7.fhir.r4.elementmodel.XmlParser(contextR3).parse(new ByteArrayInputStream(content));
        tn = r3.fhirType();
        workingid = r3.getChildValue("id");
        if (SAVING) {
            ByteArrayOutputStream bso = new ByteArrayOutputStream();
            new org.hl7.fhir.r4.elementmodel.JsonParser(contextR3).compose(r3, bso, OutputStyle.PRETTY, null);
            cnt = bso.toByteArray();
            Utilities.createDirectory(Utilities.path(TestingUtilities.home(), "implementations", "r3maps", "test-output"));
            TextFile.bytesToFile(cnt, Utilities.path(TestingUtilities.home(), "implementations", "r3maps", "test-output", tn + "-" + workingid + ".input.json"));
        }
        String mapFile = Utilities.path(TestingUtilities.home(), "implementations", "r3maps", "R3toR4", r3.fhirType() + ".map");
        if (new File(mapFile).exists()) {
            StructureMap sm = smu4.parse(TextFile.fileToString(mapFile), mapFile);
            tn = smu4.getTargetType(sm).getType();
            // convert from r3 to r4
            Resource r4 = ResourceFactory.createResource(tn);
            smu4.transform(contextR4, r3, sm, r4);
            ByteArrayOutputStream bs = new ByteArrayOutputStream();
            new org.hl7.fhir.r4.formats.JsonParser().setOutputStyle(OutputStyle.PRETTY).compose(bs, r4);
            if (SAVING) {
                TextFile.bytesToFile(bs.toByteArray(), Utilities.path(TestingUtilities.home(), "implementations", "r3maps", "test-output", tn + "-" + workingid + ".r4.json"));
                for (Resource r : extras) {
                    bs = new ByteArrayOutputStream();
                    new org.hl7.fhir.r4.formats.JsonParser().setOutputStyle(OutputStyle.PRETTY).compose(bs, r);
                    TextFile.bytesToFile(bs.toByteArray(), Utilities.path(TestingUtilities.home(), "implementations", "r3maps", "test-output", r.fhirType() + "-" + r.getId() + ".r4.json"));
                }
            }
            // validate against R4
            IResourceValidator validator = contextR4.newValidator();
            validator.setNoTerminologyChecks(true);
            validator.setFetcher(this);
            validator.validate(null, r4validationErrors, r4);
            // load the R4 to R3 map
            mapFile = Utilities.path(TestingUtilities.home(), "implementations", "r3maps", "R4toR3", getMapFor(r4.fhirType(), r3.fhirType()) + ".map");
            sm = smu3.parse(TextFile.fileToString(mapFile), mapFile);
            // convert to R3
            StructureDefinition sd = smu3.getTargetType(sm);
            org.hl7.fhir.r4.elementmodel.Element ro3 = Manager.build(contextR3, sd);
            smu3.transform(contextR3, r4, sm, ro3);
            // compare the XML
            bs = new ByteArrayOutputStream();
            new org.hl7.fhir.r4.elementmodel.JsonParser(contextR3).compose(ro3, bs, OutputStyle.PRETTY, null);
            if (SAVING)
                TextFile.bytesToFile(bs.toByteArray(), Utilities.path(TestingUtilities.home(), "implementations", "r3maps", "test-output", tn + "-" + workingid + ".output.json"));
            // check(errors, tn, workingid);
            roundTripError = TestingUtilities.checkJsonSrcIsSame(new String(cnt), new String(bs.toByteArray()), filter != null);
            if (roundTripError != null && roundTripError.equals(rules.getStringProperty(tn + "/" + workingid, "roundtrip")))
                roundTripError = null;
        } else {
            if (loadErrors.containsKey(r3.fhirType() + ".map")) {
                executionError = loadErrors.get(r3.fhirType() + ".map");
            }
        }
    } catch (Exception e) {
        executionError = e;
    }
    if (tn != null && workingid != null)
        updateOutcomes(tn, workingid, executionError, r4validationErrors, roundTripError);
    if (executionError != null)
        throw executionError;
}
Also used : ValidationMessage(org.hl7.fhir.utilities.validation.ValidationMessage) IResourceValidator(org.hl7.fhir.r4.utils.validation.IResourceValidator) ArrayList(java.util.ArrayList) Resource(org.hl7.fhir.r4.model.Resource) MetadataResource(org.hl7.fhir.r4.model.MetadataResource) ByteArrayOutputStream(java.io.ByteArrayOutputStream) StructureMapUtilities(org.hl7.fhir.r4.utils.StructureMapUtilities) FileNotFoundException(java.io.FileNotFoundException) SAXException(org.xml.sax.SAXException) DefinitionException(org.hl7.fhir.exceptions.DefinitionException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) FHIRException(org.hl7.fhir.exceptions.FHIRException) StructureMap(org.hl7.fhir.r4.model.StructureMap) StructureDefinition(org.hl7.fhir.r4.model.StructureDefinition) ByteArrayInputStream(java.io.ByteArrayInputStream) Element(org.hl7.fhir.r4.elementmodel.Element) IniFile(org.hl7.fhir.utilities.IniFile) File(java.io.File) TextFile(org.hl7.fhir.utilities.TextFile) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 5 with IResourceValidator

use of org.hl7.fhir.r5.utils.validation.IResourceValidator in project org.hl7.fhir.core by hapifhir.

the class FFHIRPathHostServices method conformsToProfile.

@Override
public boolean conformsToProfile(Object appContext, Base item, String url) throws FHIRException {
    IResourceValidator val = structureMapUtilities.getWorker().newValidator();
    List<ValidationMessage> valerrors = new ArrayList<ValidationMessage>();
    if (item instanceof Resource) {
        val.validate(appContext, valerrors, (Resource) item, url);
        return noErrorValidationMessages(valerrors);
    }
    if (item instanceof Element) {
        val.validate(appContext, valerrors, null, (Element) item, url);
        return noErrorValidationMessages(valerrors);
    }
    throw new NotImplementedException("Not done yet (FFHIRPathHostServices.conformsToProfile), when item is not element or not resource");
}
Also used : ValidationMessage(org.hl7.fhir.utilities.validation.ValidationMessage) IResourceValidator(org.hl7.fhir.r5.utils.validation.IResourceValidator) Element(org.hl7.fhir.r5.elementmodel.Element) NotImplementedException(org.apache.commons.lang3.NotImplementedException) ArrayList(java.util.ArrayList) Resource(org.hl7.fhir.r5.model.Resource)

Aggregations

ArrayList (java.util.ArrayList)4 NotImplementedException (org.apache.commons.lang3.NotImplementedException)4 FHIRException (org.hl7.fhir.exceptions.FHIRException)4 ValidationMessage (org.hl7.fhir.utilities.validation.ValidationMessage)4 IOException (java.io.IOException)3 FileNotFoundException (java.io.FileNotFoundException)2 MalformedURLException (java.net.MalformedURLException)2 URISyntaxException (java.net.URISyntaxException)2 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)2 DefinitionException (org.hl7.fhir.exceptions.DefinitionException)2 Element (org.hl7.fhir.r5.elementmodel.Element)2 Resource (org.hl7.fhir.r5.model.Resource)2 IResourceValidator (org.hl7.fhir.r5.utils.validation.IResourceValidator)2 HTTPResult (org.hl7.fhir.utilities.SimpleHTTPClient.HTTPResult)2 SAXException (org.xml.sax.SAXException)2 JsonSyntaxException (com.google.gson.JsonSyntaxException)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 File (java.io.File)1 ValidationException (org.everit.json.schema.ValidationException)1