use of org.hl7.fhir.r4b.formats.JsonParser in project kindling by HL7.
the class PageProcessor method r2Json.
private String r2Json(ValueSet vs) throws Exception {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
IParser json = new JsonParser().setOutputStyle(OutputStyle.PRETTY);
json.setSuppressXhtml("Snipped for Brevity");
json.compose(bytes, vs);
return new String(bytes.toByteArray());
}
use of org.hl7.fhir.r4b.formats.JsonParser in project kindling by HL7.
the class BindingsParser method loadValueSet.
private ValueSet loadValueSet(String ref, String committee) throws Exception {
String folder = new File(filename).getParent();
String srcName;
IParser p;
if (new File(Utilities.path(folder, ref + ".xml")).exists()) {
p = new XmlParser();
srcName = Utilities.path(folder, ref + ".xml");
} else if (new File(Utilities.path(folder, ref + ".json")).exists()) {
p = new JsonParser();
srcName = Utilities.path(folder, ref + ".json");
} else
throw new Exception("Unable to find source for " + ref + " in " + filename + " (" + Utilities.path(folder, ref + ".xml/json)"));
FileInputStream input = new FileInputStream(srcName);
try {
ValueSet result = ValueSetUtilities.makeShareable((ValueSet) p.parse(input));
result.setId(ref.substring(9));
if (!result.hasExperimental())
result.setExperimental(false);
// if (!result.hasUrl())
result.setUrl("http://hl7.org/fhir/ValueSet/" + ref.substring(9));
if (!result.hasVersion() || result.getUrl().startsWith("http://hl7.org/fhir"))
result.setVersion(version);
if (!Utilities.noString(committee)) {
if (!result.hasExtension(ToolingExtensions.EXT_WORKGROUP)) {
result.addExtension().setUrl(ToolingExtensions.EXT_WORKGROUP).setValue(new CodeType(committee));
} else {
String ec = ToolingExtensions.readStringExtension(result, ToolingExtensions.EXT_WORKGROUP);
if (!ec.equals(committee))
System.out.println("ValueSet " + result.getUrl() + " WG mismatch 1: is " + ec + ", want to set to " + committee);
}
}
result.setUserData("filename", "valueset-" + ref.substring(9));
result.setUserData("path", "valueset-" + ref.substring(9) + ".html");
new CodeSystemConvertor(codeSystems).convert(p, result, srcName, packageInfo);
return result;
} finally {
IOUtils.closeQuietly(input);
}
}
use of org.hl7.fhir.r4b.formats.JsonParser in project kindling by HL7.
the class Publisher method buildLoincExample.
private String buildLoincExample(String filename) throws FileNotFoundException, Exception {
LoincToDEConvertor conv = new LoincToDEConvertor();
conv.setDefinitions(Utilities.path(page.getFolders().srcDir, "loinc", "loincS.xml"));
conv.process();
IParser xml = new XmlParser().setOutputStyle(OutputStyle.PRETTY);
FileOutputStream s = new FileOutputStream(Utilities.path(page.getFolders().dstDir, filename + ".xml"));
xml.compose(s, conv.getBundle());
s.close();
IParser json = new JsonParser().setOutputStyle(OutputStyle.PRETTY);
s = new FileOutputStream(Utilities.path(page.getFolders().dstDir, filename + ".json"));
json.compose(s, conv.getBundle());
s.close();
return "Loinc Narrative";
}
use of org.hl7.fhir.r4b.formats.JsonParser in project kindling by HL7.
the class Publisher method produceTypeProfile.
private void produceTypeProfile(TypeDefn type) throws Exception {
// ProfileDefn p = new ProfileDefn();
// p.putMetadata("id", type.getName());
// p.putMetadata("name", "Basic StructureDefinition for " + type.getName());
// p.putMetadata("author.name", "FHIR Specification");
// p.putMetadata("author.ref", "http://hl7.org/fhir");
// p.putMetadata("description", "Basic StructureDefinition for " + type.getName() + " for validation support");
// p.putMetadata("status", "draft");
// p.putMetadata("date", new SimpleDateFormat("yyyy-MM-dd", new Locale("en", "US")).format(new Date()));
// p.getElements().add(type);
// ProfileGenerator pgen = new ProfileGenerator(page.getDefinitions());
// String fn = "type-" + type.getName() + ".profile.xml";
// StructureDefinition rp = pgen.generate(p, "type-" + type.getName() + ".profile", "<div>Type definition for " + type.getName() + " from <a href=\"http://hl7.org/fhir/datatypes.html#" + type.getName()
// + "\">FHIR Specification</a></div>");
String fn = type.getName().toLowerCase() + ".profile.xml";
StructureDefinition rp = type.getProfile();
FileOutputStream s = new FileOutputStream(page.getFolders().dstDir + fn);
new XmlParser().setOutputStyle(OutputStyle.PRETTY).compose(s, rp);
s.close();
s = new FileOutputStream(page.getFolders().dstDir + Utilities.changeFileExt(fn, ".canonical.xml"));
new XmlParser().setOutputStyle(OutputStyle.CANONICAL).compose(s, rp);
s.close();
s = new FileOutputStream(page.getFolders().dstDir + Utilities.changeFileExt(fn, ".json"));
new JsonParser().setOutputStyle(OutputStyle.PRETTY).compose(s, rp);
s.close();
s = new FileOutputStream(page.getFolders().dstDir + Utilities.changeFileExt(fn, ".canonical.json"));
new JsonParser().setOutputStyle(OutputStyle.CANONICAL).compose(s, rp);
s.close();
Utilities.copyFile(new CSFile(page.getFolders().dstDir + fn), new CSFile(Utilities.path(page.getFolders().dstDir, "examples", fn)));
addToResourceFeed(rp, page.getTypeBundle(), fn);
// saveAsPureHtml(rp, new FileOutputStream(page.getFolders().dstDir+ "html"
// + File.separator + "datatypes.html"));
cloneToXhtml(type.getName().toLowerCase() + ".profile", "StructureDefinition for " + type.getName(), false, "profile-instance:type:" + type.getName(), "Type", null, wg("mnm"));
jsonToXhtml(type.getName().toLowerCase() + ".profile", "StructureDefinition for " + type.getName(), resource2Json(rp), "profile-instance:type:" + type.getName(), "Type", null, wg("mnm"));
ttlToXhtml(type.getName().toLowerCase() + ".profile", "StructureDefinition for " + type.getName(), resource2Ttl(rp), "profile-instance:type:" + type.getName(), "Type", null, wg("mnm"));
String shex = new ShExGenerator(page.getWorkerContext()).generate(HTMLLinkPolicy.NONE, rp);
TextFile.stringToFile(shex, Utilities.changeFileExt(page.getFolders().dstDir + fn, ".shex"));
shexToXhtml(type.getName().toLowerCase(), "ShEx statement for " + type.getName(), shex, "profile-instance:type:" + type.getName(), "Type", null, wg("mnm"));
}
use of org.hl7.fhir.r4b.formats.JsonParser in project cqf-ruler by DBCG.
the class CdsHooksServlet method doPost.
@Override
@SuppressWarnings("deprecation")
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
logger.info(request.getRequestURI());
try {
// validate that we are dealing with JSON
if (request.getContentType() == null || !request.getContentType().startsWith("application/json")) {
throw new ServletException(String.format("Invalid content type %s. Please use application/json.", request.getContentType()));
}
String baseUrl = this.myAppProperties.getServer_address();
String service = request.getPathInfo().replace("/", "");
JsonParser parser = new JsonParser();
JsonObject requestJson = parser.parse(request.getReader()).getAsJsonObject();
logger.info(requestJson.toString());
Request cdsHooksRequest = new Request(service, requestJson, JsonHelper.getObjectRequired(getService(service), "prefetch"));
Hook hook = HookFactory.createHook(cdsHooksRequest);
String hookName = hook.getRequest().getHook();
logger.info("cds-hooks hook: {}", hookName);
logger.info("cds-hooks hook instance: {}", hook.getRequest().getHookInstance());
logger.info("cds-hooks maxCodesPerQuery: {}", this.getProviderConfiguration().getMaxCodesPerQuery());
logger.info("cds-hooks expandValueSets: {}", this.getProviderConfiguration().getExpandValueSets());
logger.info("cds-hooks searchStyle: {}", this.getProviderConfiguration().getSearchStyle());
logger.info("cds-hooks prefetch maxUriLength: {}", this.getProviderConfiguration().getMaxUriLength());
logger.info("cds-hooks local server address: {}", baseUrl);
logger.info("cds-hooks fhir server address: {}", hook.getRequest().getFhirServerUrl());
logger.info("cds-hooks cql_logging_enabled: {}", this.getProviderConfiguration().getCqlLoggingEnabled());
PlanDefinition planDefinition = read(Ids.newId(PlanDefinition.class, hook.getRequest().getServiceName()));
AtomicBoolean planDefinitionHookMatchesRequestHook = new AtomicBoolean(false);
planDefinition.getAction().forEach(action -> {
action.getTriggerDefinition().forEach(triggerDefn -> {
if (hookName.equals(triggerDefn.getEventName())) {
planDefinitionHookMatchesRequestHook.set(true);
return;
}
});
if (planDefinitionHookMatchesRequestHook.get()) {
return;
}
});
if (!planDefinitionHookMatchesRequestHook.get()) {
throw new ServletException("ERROR: Request hook does not match the service called.");
}
// No tenant information available, so create local system request
RequestDetails requestDetails = new SystemRequestDetails();
LibraryLoader libraryLoader = libraryLoaderFactory.create(Lists.newArrayList(jpaLibraryContentProviderFactory.create(requestDetails)));
Reference reference = planDefinition.getLibrary().get(0);
Library library = read(reference.getReferenceElement());
org.cqframework.cql.elm.execution.Library elm = libraryLoader.load(new VersionedIdentifier().withId(library.getName()).withVersion(library.getVersion()));
Context context = new Context(elm);
context.setDebugMap(this.getDebugMap());
// provider case
// No tenant information available for cds-hooks
TerminologyProvider serverTerminologyProvider = myJpaTerminologyProviderFactory.create(requestDetails);
// TODO make sure tooling handles remote
context.registerDataProvider("http://hl7.org/fhir", fhirRetrieveProviderFactory.create(requestDetails, serverTerminologyProvider));
context.registerTerminologyProvider(serverTerminologyProvider);
context.registerLibraryLoader(libraryLoader);
context.setContextValue("Patient", hook.getRequest().getContext().getPatientId().replace("Patient/", ""));
context.setExpressionCaching(true);
EvaluationContext<PlanDefinition> evaluationContext = new Stu3EvaluationContext(hook, FhirContext.forCached(FhirVersionEnum.DSTU3).newRestfulGenericClient(baseUrl), context, elm, planDefinition, this.getProviderConfiguration(), this.modelResolver);
this.setAccessControlHeaders(response);
response.setHeader("Content-Type", ContentType.APPLICATION_JSON.getMimeType());
Stu3HookEvaluator evaluator = new Stu3HookEvaluator(this.modelResolver);
String jsonResponse = toJsonResponse(evaluator.evaluate(evaluationContext));
logger.info(jsonResponse);
response.getWriter().println(jsonResponse);
} catch (BaseServerResponseException e) {
this.setAccessControlHeaders(response);
// This will be overwritten with the correct status code downstream if needed.
response.setStatus(500);
response.getWriter().println("ERROR: Exception connecting to remote server.");
this.printMessageAndCause(e, response);
this.handleServerResponseException(e, response);
this.printStackTrack(e, response);
logger.error(e.toString());
} catch (DataProviderException e) {
this.setAccessControlHeaders(response);
// This will be overwritten with the correct status code downstream if needed.
response.setStatus(500);
response.getWriter().println("ERROR: Exception in DataProvider.");
this.printMessageAndCause(e, response);
if (e.getCause() != null && (e.getCause() instanceof BaseServerResponseException)) {
this.handleServerResponseException((BaseServerResponseException) e.getCause(), response);
}
this.printStackTrack(e, response);
logger.error(e.toString());
} catch (CqlException e) {
this.setAccessControlHeaders(response);
// This will be overwritten with the correct status code downstream if needed.
response.setStatus(500);
response.getWriter().println("ERROR: Exception in CQL Execution.");
this.printMessageAndCause(e, response);
if (e.getCause() != null && (e.getCause() instanceof BaseServerResponseException)) {
this.handleServerResponseException((BaseServerResponseException) e.getCause(), response);
}
this.printStackTrack(e, response);
logger.error(e.toString());
} catch (Exception e) {
logger.error(e.toString());
throw new ServletException("ERROR: Exception in cds-hooks processing.", e);
}
}
Aggregations