upgrade to new JSON parser

This commit is contained in:
Grahame Grieve 2022-11-24 17:57:46 -03:00
parent b2e2c68f7e
commit 80f275ff18
49 changed files with 815 additions and 550 deletions

View File

@ -16,8 +16,10 @@ import org.hl7.fhir.utilities.SimpleHTTPClient;
import org.hl7.fhir.utilities.SimpleHTTPClient.HTTPResult; import org.hl7.fhir.utilities.SimpleHTTPClient.HTTPResult;
import org.hl7.fhir.utilities.TextFile; import org.hl7.fhir.utilities.TextFile;
import org.hl7.fhir.utilities.Utilities; import org.hl7.fhir.utilities.Utilities;
import org.hl7.fhir.utilities.json.JsonTrackingParser; import org.hl7.fhir.utilities.json.model.JsonArray;
import org.hl7.fhir.utilities.json.JsonUtilities; import org.hl7.fhir.utilities.json.model.JsonElement;
import org.hl7.fhir.utilities.json.model.JsonObject;
import org.hl7.fhir.utilities.json.parser.JsonParser;
import org.hl7.fhir.utilities.npm.FilesystemPackageCacheManager; import org.hl7.fhir.utilities.npm.FilesystemPackageCacheManager;
import org.hl7.fhir.utilities.npm.NpmPackage; import org.hl7.fhir.utilities.npm.NpmPackage;
import org.hl7.fhir.utilities.npm.PackageClient; import org.hl7.fhir.utilities.npm.PackageClient;
@ -28,10 +30,6 @@ import org.w3c.dom.Document;
import org.w3c.dom.Element; import org.w3c.dom.Element;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
public class PackageVisitor { public class PackageVisitor {
public interface IPackageVisitorProcessor { public interface IPackageVisitorProcessor {
@ -140,11 +138,11 @@ public class PackageVisitor {
} }
i++; i++;
} }
JsonObject json = JsonTrackingParser.fetchJson("https://raw.githubusercontent.com/FHIR/ig-registry/master/fhir-ig-list.json"); JsonObject json = JsonParser.parseObjectFromUrl("https://raw.githubusercontent.com/FHIR/ig-registry/master/fhir-ig-list.json");
i = 0; i = 0;
List<JsonObject> objects = JsonUtilities.objects(json, "guides"); List<JsonObject> objects = json.getJsonObjects("guides");
for (JsonObject o : objects) { for (JsonObject o : objects) {
String pid = JsonUtilities.str(o, "npm-name"); String pid = o.asString("npm-name");
if (pid != null && !cpidSet.contains(pid)) { if (pid != null && !cpidSet.contains(pid)) {
cpidSet.add(pid); cpidSet.add(pid);
List<String> vList = listVersions(pid); List<String> vList = listVersions(pid);
@ -195,11 +193,10 @@ public class PackageVisitor {
private Map<String, String> getAllCIPackages() throws IOException { private Map<String, String> getAllCIPackages() throws IOException {
Map<String, String> res = new HashMap<>(); Map<String, String> res = new HashMap<>();
if (current) { if (current) {
JsonArray json = JsonTrackingParser.fetchJsonArray("https://build.fhir.org/ig/qas.json"); JsonArray json = (JsonArray) JsonParser.parseFromUrl("https://build.fhir.org/ig/qas.json");
for (JsonElement j : json) { for (JsonObject o : json.asJsonObjects()) {
JsonObject o = (JsonObject) j; String url = o.asString("repo");
String url = JsonUtilities.str(o, "repo"); res.put(url, o.asString("package-id"));
res.put(url, JsonUtilities.str(o, "package-id"));
} }
} }
return res; return res;
@ -220,13 +217,13 @@ public class PackageVisitor {
for (PackageInfo i : pc.search(null, null, null, false)) { for (PackageInfo i : pc.search(null, null, null, false)) {
list.add(i.getId()); list.add(i.getId());
} }
JsonObject json = JsonTrackingParser.fetchJson("https://raw.githubusercontent.com/FHIR/ig-registry/master/fhir-ig-list.json"); JsonObject json = JsonParser.parseObjectFromUrl("https://raw.githubusercontent.com/FHIR/ig-registry/master/fhir-ig-list.json");
for (JsonObject ig : JsonUtilities.objects(json, "guides")) { for (JsonObject ig : json.getJsonObjects("guides")) {
list.add(JsonUtilities.str(ig, "npm-name")); list.add(ig.asString("npm-name"));
} }
json = JsonTrackingParser.fetchJson("https://raw.githubusercontent.com/FHIR/ig-registry/master/package-feeds.json"); json = JsonParser.parseObjectFromUrl("https://raw.githubusercontent.com/FHIR/ig-registry/master/package-feeds.json");
for (JsonObject feed : JsonUtilities.objects(json, "feeds")) { for (JsonObject feed : json.getJsonObjects("feeds")) {
processFeed(list, JsonUtilities.str(feed, "url")); processFeed(list, feed.asString("url"));
} }
return list; return list;

View File

@ -7,10 +7,10 @@ import java.io.IOException;
import org.hl7.fhir.exceptions.FHIRFormatError; import org.hl7.fhir.exceptions.FHIRFormatError;
import org.hl7.fhir.utilities.Utilities; import org.hl7.fhir.utilities.Utilities;
import org.hl7.fhir.utilities.json.JsonTrackingParser; import org.hl7.fhir.utilities.json.model.JsonObject;
import org.hl7.fhir.utilities.json.parser.JsonParser;
import org.hl7.fhir.utilities.npm.NpmPackage; import org.hl7.fhir.utilities.npm.NpmPackage;
import com.google.gson.JsonObject;
public class CorePackageTools { public class CorePackageTools {
@ -33,7 +33,7 @@ public class CorePackageTools {
private void buildXml(String json, String xml, String version) throws FHIRFormatError, IOException { private void buildXml(String json, String xml, String version) throws FHIRFormatError, IOException {
for (File f : new File(Utilities.path(json, "package")).listFiles()) { for (File f : new File(Utilities.path(json, "package")).listFiles()) {
if (f.getName().endsWith(".json")) { if (f.getName().endsWith(".json")) {
JsonObject j = new JsonTrackingParser().parseJson(f); JsonObject j = JsonParser.parseObject(f);
if (j.has("resourceType")) { if (j.has("resourceType")) {
if ("1.4".equals(version)) { if ("1.4".equals(version)) {
String n = f.getName(); String n = f.getName();

View File

@ -10,9 +10,8 @@ import java.util.Set;
import org.hl7.fhir.convertors.factory.VersionConvertorFactory_40_50; import org.hl7.fhir.convertors.factory.VersionConvertorFactory_40_50;
import org.hl7.fhir.exceptions.FHIRFormatError; import org.hl7.fhir.exceptions.FHIRFormatError;
import org.hl7.fhir.utilities.TextFile; import org.hl7.fhir.utilities.TextFile;
import org.hl7.fhir.utilities.json.JsonTrackingParser; import org.hl7.fhir.utilities.json.model.JsonObject;
import org.hl7.fhir.utilities.json.parser.JsonParser;
import com.google.gson.JsonObject;
public class ExamplesPackageBuilder { public class ExamplesPackageBuilder {
@ -25,10 +24,10 @@ public class ExamplesPackageBuilder {
Set<String> set = new HashSet<>(); Set<String> set = new HashSet<>();
for (File f : new File(source).listFiles()) { for (File f : new File(source).listFiles()) {
if (f.getName().endsWith(".json")) { if (f.getName().endsWith(".json")) {
JsonObject obj = JsonTrackingParser.parseJson(new FileInputStream(f)); JsonObject obj = JsonParser.parseObject(new FileInputStream(f));
if (obj.has("resourceType") && obj.has("id")) { if (obj.has("resourceType") && obj.has("id")) {
String type = obj.get("resourceType").getAsString(); String type = obj.asString("resourceType");
String id = obj.get("id").getAsString(); String id = obj.asString("id");
byte[] content = TextFile.fileToBytes(f); byte[] content = TextFile.fileToBytes(f);
if (type.equals("ConceptMap")) { if (type.equals("ConceptMap")) {
System.out.println("convert "+f.getName()); System.out.println("convert "+f.getName());

View File

@ -28,10 +28,9 @@ import org.hl7.fhir.r4.utils.ToolingExtensions;
import org.hl7.fhir.utilities.SimpleHTTPClient; import org.hl7.fhir.utilities.SimpleHTTPClient;
import org.hl7.fhir.utilities.SimpleHTTPClient.HTTPResult; import org.hl7.fhir.utilities.SimpleHTTPClient.HTTPResult;
import org.hl7.fhir.utilities.Utilities; import org.hl7.fhir.utilities.Utilities;
import org.hl7.fhir.utilities.json.JsonTrackingParser; import org.hl7.fhir.utilities.json.model.JsonElement;
import org.hl7.fhir.utilities.json.model.JsonObject;
import com.google.gson.JsonElement; import org.hl7.fhir.utilities.json.parser.JsonParser;
import com.google.gson.JsonObject;
public class ICD11Generator { public class ICD11Generator {
@ -42,12 +41,12 @@ public class ICD11Generator {
private void execute(String base, String dest) throws IOException { private void execute(String base, String dest) throws IOException {
CodeSystem cs = makeMMSCodeSystem(); CodeSystem cs = makeMMSCodeSystem();
JsonObject version = fetchJson(Utilities.pathURL(base, "/icd/release/11/mms")); JsonObject version = fetchJson(Utilities.pathURL(base, "/icd/release/11/mms"));
String[] p = version.get("latestRelease").getAsString().split("\\/"); String[] p = version.asString("latestRelease").split("\\/");
cs.setVersion(p[6]); cs.setVersion(p[6]);
JsonObject root = fetchJson(url(base, version.get("latestRelease").getAsString())); JsonObject root = fetchJson(url(base, version.asString("latestRelease")));
cs.setDateElement(new DateTimeType(root.get("releaseDate").getAsString())); cs.setDateElement(new DateTimeType(root.asString("releaseDate")));
for (JsonElement child : root.getAsJsonArray("child")) { for (JsonElement child : root.getJsonArray("child")) {
processMMSEntity(cs, base, child.getAsString(), cs.addConcept(), dest); processMMSEntity(cs, base, child.asString(), cs.addConcept(), dest);
System.out.println(); System.out.println();
} }
new XmlParser(XmlVersion.V1_1).setOutputStyle(OutputStyle.PRETTY).compose(new FileOutputStream(Utilities.path(dest, "icd-11-mms.xml")), cs); new XmlParser(XmlVersion.V1_1).setOutputStyle(OutputStyle.PRETTY).compose(new FileOutputStream(Utilities.path(dest, "icd-11-mms.xml")), cs);
@ -55,12 +54,12 @@ public class ICD11Generator {
cs = makeEntityCodeSystem(); cs = makeEntityCodeSystem();
root = fetchJson(Utilities.pathURL(base, "/icd/entity")); root = fetchJson(Utilities.pathURL(base, "/icd/entity"));
cs.setVersion(root.get("releaseId").getAsString()); cs.setVersion(root.asString("releaseId"));
cs.setDateElement(new DateTimeType(root.get("releaseDate").getAsString())); cs.setDateElement(new DateTimeType(root.asString("releaseDate")));
cs.setTitle(readString(root, "title")); cs.setTitle(readString(root, "title"));
Set<String> ids = new HashSet<>(); Set<String> ids = new HashSet<>();
for (JsonElement child : root.getAsJsonArray("child")) { for (JsonElement child : root.getJsonArray("child")) {
processEntity(cs, ids, base, tail(child.getAsString()), dest); processEntity(cs, ids, base, tail(child.asString()), dest);
System.out.println(); System.out.println();
} }
new XmlParser(XmlVersion.V1_1).setOutputStyle(OutputStyle.PRETTY).compose(new FileOutputStream(Utilities.path(dest, "icd-11-foundation.xml")), cs); new XmlParser(XmlVersion.V1_1).setOutputStyle(OutputStyle.PRETTY).compose(new FileOutputStream(Utilities.path(dest, "icd-11-foundation.xml")), cs);
@ -80,34 +79,34 @@ public class ICD11Generator {
cc.setDefinition(d); cc.setDefinition(d);
} }
if (entity.has("inclusion")) { if (entity.has("inclusion")) {
for (JsonElement child : entity.getAsJsonArray("inclusion")) { for (JsonElement child : entity.getJsonArray("inclusion")) {
JsonObject co = (JsonObject) child; JsonObject co = (JsonObject) child;
String v = readString(co, "label"); String v = readString(co, "label");
if (v != null) { if (v != null) {
if (co.has("foundationReference")) { if (co.has("foundationReference")) {
cc.addProperty().setValue(new Coding().setSystem("http://id.who.int/icd11/foundation").setCode(tail(co.get("foundationReference").getAsString())).setDisplay(v)).setCode("inclusion"); cc.addProperty().setValue(new Coding().setSystem("http://id.who.int/icd11/foundation").setCode(tail(co.asString("foundationReference"))).setDisplay(v)).setCode("inclusion");
} }
} }
} }
} }
if (entity.has("exclusion")) { if (entity.has("exclusion")) {
for (JsonElement child : entity.getAsJsonArray("exclusion")) { for (JsonElement child : entity.getJsonArray("exclusion")) {
JsonObject co = (JsonObject) child; JsonObject co = (JsonObject) child;
String v = readString(co, "label"); String v = readString(co, "label");
if (v != null) { if (v != null) {
if (co.has("foundationReference")) { if (co.has("foundationReference")) {
cc.addProperty().setValue(new Coding().setSystem("http://id.who.int/icd11/foundation").setCode(tail(co.get("foundationReference").getAsString())).setDisplay(v)).setCode("exclusion"); cc.addProperty().setValue(new Coding().setSystem("http://id.who.int/icd11/foundation").setCode(tail(co.asString("foundationReference"))).setDisplay(v)).setCode("exclusion");
} }
} }
} }
} }
if (entity.has("narrowerTerm")) { if (entity.has("narrowerTerm")) {
for (JsonElement child : entity.getAsJsonArray("narrowerTerm")) { for (JsonElement child : entity.getJsonArray("narrowerTerm")) {
JsonObject co = (JsonObject) child; JsonObject co = (JsonObject) child;
String v = readString(co, "label"); String v = readString(co, "label");
if (v != null) { if (v != null) {
if (co.has("narrowerTerm")) { if (co.has("narrowerTerm")) {
cc.addProperty().setValue(new Coding().setSystem("http://id.who.int/icd11/foundation").setCode(tail(co.get("foundationReference").getAsString())).setDisplay(v)).setCode("narrowerTerm"); cc.addProperty().setValue(new Coding().setSystem("http://id.who.int/icd11/foundation").setCode(tail(co.asString("foundationReference"))).setDisplay(v)).setCode("narrowerTerm");
} }
} }
} }
@ -115,22 +114,22 @@ public class ICD11Generator {
addDesignation(readString(entity, "longDefinition"), cc, "http://id.who.int/icd11/mms/designation", "longDefinition"); addDesignation(readString(entity, "longDefinition"), cc, "http://id.who.int/icd11/mms/designation", "longDefinition");
addDesignation(readString(entity, "fullySpecifiedName"), cc, "http://snomed.info/sct", "900000000000003001"); addDesignation(readString(entity, "fullySpecifiedName"), cc, "http://snomed.info/sct", "900000000000003001");
if (entity.has("synonym")) { if (entity.has("synonym")) {
for (JsonElement j : entity.getAsJsonArray("synonym")) { for (JsonElement j : entity.getJsonArray("synonym")) {
String v = readString((JsonObject) j, "label"); String v = readString((JsonObject) j, "label");
if (v != null && !v.equals(cc.getDisplay())) { if (v != null && !v.equals(cc.getDisplay())) {
addDesignation(v, cc, "http://id.who.int/icd11/mms/designation", "synonym"); addDesignation(v, cc, "http://id.who.int/icd11/mms/designation", "synonym");
} }
} }
} }
for (JsonElement j : entity.getAsJsonArray("parent")) { for (JsonElement j : entity.getJsonArray("parent")) {
String v = j.getAsString(); String v = j.asString();
if (!"http://id.who.int/icd/entity".equals(v)) { if (!"http://id.who.int/icd/entity".equals(v)) {
cc.addProperty().setValue(new CodeType(tail(v))).setCode("narrowerTerm"); cc.addProperty().setValue(new CodeType(tail(v))).setCode("narrowerTerm");
} }
} }
if (entity.has("child")) { if (entity.has("child")) {
for (JsonElement j : entity.getAsJsonArray("child")) { for (JsonElement j : entity.getJsonArray("child")) {
String v = j.getAsString(); String v = j.asString();
cc.addProperty().setValue(new CodeType(tail(v))).setCode("child"); cc.addProperty().setValue(new CodeType(tail(v))).setCode("child");
processEntity(cs, ids, base, tail(v), dest); processEntity(cs, ids, base, tail(v), dest);
} }
@ -180,16 +179,16 @@ public class ICD11Generator {
System.out.print("."); System.out.print(".");
JsonObject entity = fetchJson(url(base, ref)); JsonObject entity = fetchJson(url(base, ref));
cc.setId(tail(ref)); cc.setId(tail(ref));
if (entity.has("code") && !Utilities.noString(entity.get("code").getAsString())) { if (entity.has("code") && !Utilities.noString(entity.asString("code"))) {
cc.setCode(entity.get("code").getAsString()); cc.setCode(entity.asString("code"));
} else if (entity.has("blockId") && !Utilities.noString(entity.get("blockId").getAsString())) { } else if (entity.has("blockId") && !Utilities.noString(entity.asString("blockId"))) {
cc.setCode(entity.get("blockId").getAsString()); cc.setCode(entity.asString("blockId"));
} else { } else {
cc.setCode(cc.getId()); cc.setCode(cc.getId());
cc.addProperty().setCode("abstract").setValue(new BooleanType(true)); cc.addProperty().setCode("abstract").setValue(new BooleanType(true));
} }
if (entity.has("classKind") && !Utilities.noString(entity.get("classKind").getAsString()) && !"category".equals(entity.get("classKind").getAsString())) { if (entity.has("classKind") && !Utilities.noString(entity.asString("classKind")) && !"category".equals(entity.asString("classKind"))) {
cc.addProperty().setCode("kind").setValue(new CodeType(entity.get("classKind").getAsString())); cc.addProperty().setCode("kind").setValue(new CodeType(entity.asString("classKind")));
} }
cc.setDisplay(readString(entity, "title")); cc.setDisplay(readString(entity, "title"));
StringBuilder defn = new StringBuilder(); StringBuilder defn = new StringBuilder();
@ -203,7 +202,7 @@ public class ICD11Generator {
if (entity.has("inclusion")) { if (entity.has("inclusion")) {
defn.append(". Includes: "); defn.append(". Includes: ");
boolean first = true; boolean first = true;
for (JsonElement child : entity.getAsJsonArray("inclusion")) { for (JsonElement child : entity.getJsonArray("inclusion")) {
if (first) first = false; if (first) first = false;
else defn.append(", "); else defn.append(", ");
defn.append(readString((JsonObject) child, "label")); defn.append(readString((JsonObject) child, "label"));
@ -212,7 +211,7 @@ public class ICD11Generator {
if (entity.has("exclusion")) { if (entity.has("exclusion")) {
defn.append(". Excludes: "); defn.append(". Excludes: ");
boolean first = true; boolean first = true;
for (JsonElement child : entity.getAsJsonArray("exclusion")) { for (JsonElement child : entity.getJsonArray("exclusion")) {
if (first) first = false; if (first) first = false;
else defn.append(", "); else defn.append(", ");
JsonObject co = (JsonObject) child; JsonObject co = (JsonObject) child;
@ -220,7 +219,7 @@ public class ICD11Generator {
if (v != null) { if (v != null) {
defn.append(v); defn.append(v);
if (co.has("linearizationReference")) { if (co.has("linearizationReference")) {
cc.addProperty().setValue(new Coding().setSystem("http://id.who.int/icd11/mms").setCode(tail(co.get("linearizationReference").getAsString())).setDisplay(v)).setCode("exclusion"); cc.addProperty().setValue(new Coding().setSystem("http://id.who.int/icd11/mms").setCode(tail(co.asString("linearizationReference"))).setDisplay(v)).setCode("exclusion");
} }
} }
} }
@ -231,33 +230,33 @@ public class ICD11Generator {
addProperty(readString(entity, "codingNote"), cc, "codingNote"); addProperty(readString(entity, "codingNote"), cc, "codingNote");
if (entity.has("indexTerm")) { if (entity.has("indexTerm")) {
// CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder("; "); // CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder("; ");
// for (JsonElement child : entity.getAsJsonArray("indexTerm")) { // for (JsonElement child : entity.getJsonArray("indexTerm")) {
// processIndexTerm(cc, b, (JsonObject) child); // processIndexTerm(cc, b, (JsonObject) child);
// } // }
// if (b.length() > 0) { // if (b.length() > 0) {
// cc.addProperty().setCode("terms").setValue(new StringType(b.toString())); // cc.addProperty().setCode("terms").setValue(new StringType(b.toString()));
// } // }
for (JsonElement child : entity.getAsJsonArray("indexTerm")) { for (JsonElement child : entity.getJsonArray("indexTerm")) {
processIndexTerm(cc, (JsonObject) child); processIndexTerm(cc, (JsonObject) child);
} }
} }
if (entity.has("postcoordinationScale")) { if (entity.has("postcoordinationScale")) {
for (JsonElement child : entity.getAsJsonArray("postcoordinationScale")) { for (JsonElement child : entity.getJsonArray("postcoordinationScale")) {
JsonObject o = (JsonObject) child; JsonObject o = (JsonObject) child;
String name = tail(o.get("axisName").getAsString()); String name = tail(o.asString("axisName"));
ConceptPropertyComponent prop = cc.addProperty(); ConceptPropertyComponent prop = cc.addProperty();
prop.setCode("postcoordinationScale"); prop.setCode("postcoordinationScale");
prop.setValue(new CodeType(name)); prop.setValue(new CodeType(name));
ToolingExtensions.addBooleanExtension(prop, "http://id.who.int/icd11/extensions/required", o.get("requiredPostcoordination").getAsBoolean()); ToolingExtensions.addBooleanExtension(prop, "http://id.who.int/icd11/extensions/required", o.asBoolean("requiredPostcoordination"));
ToolingExtensions.addBooleanExtension(prop, "http://id.who.int/icd11/extensions/repeats", o.get("allowMultipleValues").getAsBoolean()); ToolingExtensions.addBooleanExtension(prop, "http://id.who.int/icd11/extensions/repeats", o.asBoolean("allowMultipleValues"));
if (o.has("scaleEntity")) { if (o.has("scaleEntity")) {
ToolingExtensions.addUriExtension(prop, "http://id.who.int/icd11/extensions/valueSet", buildValueSet(cs, cc.getCode(), name, o, dest)); ToolingExtensions.addUriExtension(prop, "http://id.who.int/icd11/extensions/valueSet", buildValueSet(cs, cc.getCode(), name, o, dest));
} }
} }
} }
if (entity.has("child")) { if (entity.has("child")) {
for (JsonElement child : entity.getAsJsonArray("child")) { for (JsonElement child : entity.getJsonArray("child")) {
processMMSEntity(cs, base, child.getAsString(), cc.addConcept(), dest); processMMSEntity(cs, base, child.asString(), cc.addConcept(), dest);
} }
} }
} }
@ -279,8 +278,8 @@ public class ICD11Generator {
vs.setStatus(cs.getStatus()); vs.setStatus(cs.getStatus());
ConceptSetComponent inc = vs.getCompose().addInclude(); ConceptSetComponent inc = vs.getCompose().addInclude();
inc.setSystem(cs.getUrl()); inc.setSystem(cs.getUrl());
for (JsonElement e : o.getAsJsonArray("scaleEntity")) { for (JsonElement e : o.getJsonArray("scaleEntity")) {
inc.addFilter().setProperty("concept").setOp(FilterOperator.ISA).setValue(tail(e.getAsString())); inc.addFilter().setProperty("concept").setOp(FilterOperator.ISA).setValue(tail(e.asString()));
} }
new XmlParser(XmlVersion.V1_1).setOutputStyle(OutputStyle.PRETTY).compose(new FileOutputStream(Utilities.path(dest, "vs-" + id + ".xml")), vs); new XmlParser(XmlVersion.V1_1).setOutputStyle(OutputStyle.PRETTY).compose(new FileOutputStream(Utilities.path(dest, "vs-" + id + ".xml")), vs);
return url; return url;
@ -328,12 +327,12 @@ public class ICD11Generator {
} }
private String readString(JsonObject obj, String name) { private String readString(JsonObject obj, String name) {
JsonObject p = obj.getAsJsonObject(name); JsonObject p = obj.getJsonObject(name);
if (p == null) { if (p == null) {
return null; return null;
} }
if (p.has("@value")) { if (p.has("@value")) {
return p.get("@value").getAsString(); return p.get("@value").asString();
} }
return null; return null;
} }
@ -400,7 +399,7 @@ public class ICD11Generator {
http.addHeader("Accept-Language", "en"); http.addHeader("Accept-Language", "en");
HTTPResult res = http.get(source, "application/json"); HTTPResult res = http.get(source, "application/json");
res.checkThrowException(); res.checkThrowException();
return JsonTrackingParser.parseJson(res.getContent()); return JsonParser.parseObject(res.getContent());
} }

View File

@ -1,11 +1,12 @@
package org.hl7.fhir.convertors.misc; package org.hl7.fhir.convertors.misc;
import java.io.File; import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import org.hl7.fhir.utilities.json.JsonTrackingParser; import org.hl7.fhir.utilities.json.model.JsonObject;
import org.hl7.fhir.utilities.json.parser.JsonParser;
import com.google.gson.JsonObject;
public class JsonProcessor { public class JsonProcessor {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
@ -13,9 +14,9 @@ public class JsonProcessor {
} }
private void process(String source) throws IOException { private void process(String source) throws IOException {
JsonObject json = JsonTrackingParser.parseJsonFile(source); JsonObject json = JsonParser.parseObjectFromFile(source);
process(json); process(json);
JsonTrackingParser.write(json, new File(source), true); JsonParser.compose(json, new FileOutputStream(source), true);
} }
@ -178,11 +179,11 @@ public class JsonProcessor {
} }
private void process(JsonObject json, String name) { private void process(JsonObject json, String name) {
JsonObject j = json.getAsJsonObject(name); JsonObject j = json.getJsonObject(name);
if (j == null) { if (j == null) {
System.out.println("Can't find "+name); System.out.println("Can't find "+name);
} else { } else {
j.addProperty("modifier", true); j.add("modifier", true);
} }
} }

View File

@ -29,13 +29,12 @@ import org.hl7.fhir.convertors.factory.VersionConvertorFactory_30_50;
import org.hl7.fhir.convertors.factory.VersionConvertorFactory_40_50; import org.hl7.fhir.convertors.factory.VersionConvertorFactory_40_50;
import org.hl7.fhir.utilities.TextFile; import org.hl7.fhir.utilities.TextFile;
import org.hl7.fhir.utilities.VersionUtilities; import org.hl7.fhir.utilities.VersionUtilities;
import org.hl7.fhir.utilities.json.JsonTrackingParser; import org.hl7.fhir.utilities.json.model.JsonArray;
import org.hl7.fhir.utilities.json.JsonUtilities; import org.hl7.fhir.utilities.json.model.JsonObject;
import org.hl7.fhir.utilities.json.parser.JsonParser;
import org.hl7.fhir.utilities.npm.NpmPackageIndexBuilder; import org.hl7.fhir.utilities.npm.NpmPackageIndexBuilder;
import com.google.common.base.Charsets; import com.google.common.base.Charsets;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
public class NpmPackageVersionConverter { public class NpmPackageVersionConverter {
@ -105,7 +104,7 @@ public class NpmPackageVersionConverter {
if (!e.getKey().equals("package/package.json")) { if (!e.getKey().equals("package/package.json")) {
byte[] cnv = e.getValue(); byte[] cnv = e.getValue();
try { try {
JsonObject json = JsonTrackingParser.parseJson(e.getValue()); JsonObject json = JsonParser.parseObject(e.getValue());
if (json.has("resourceType")) { if (json.has("resourceType")) {
cnv = convertResource(e.getKey(), e.getValue()); cnv = convertResource(e.getKey(), e.getValue());
} }
@ -174,11 +173,11 @@ public class NpmPackageVersionConverter {
} }
private byte[] convertPackage(byte[] cnt) throws IOException { private byte[] convertPackage(byte[] cnt) throws IOException {
JsonObject json = JsonTrackingParser.parseJson(cnt); JsonObject json = JsonParser.parseObject(cnt);
currentVersion = json.getAsJsonArray("fhirVersions").get(0).getAsString(); currentVersion = json.getJsonArray("fhirVersions").get(0).asString();
String name = JsonUtilities.str(json, "name"); String name = json.asString("name");
json.remove("name"); json.remove("name");
json.addProperty("name", name + "." + vCode); json.add("name", name + "." + vCode);
json.remove("fhirVersions"); json.remove("fhirVersions");
json.remove("dependencies"); json.remove("dependencies");
JsonArray fv = new JsonArray(); JsonArray fv = new JsonArray();
@ -186,8 +185,8 @@ public class NpmPackageVersionConverter {
fv.add(version); fv.add(version);
JsonObject dep = new JsonObject(); JsonObject dep = new JsonObject();
json.add("dependencies", dep); json.add("dependencies", dep);
dep.addProperty(VersionUtilities.packageForVersion(version), version); dep.add(VersionUtilities.packageForVersion(version), version);
return JsonTrackingParser.write(json).getBytes(Charsets.UTF_8); return JsonParser.composeBytes(json);
} }
private byte[] convertResource(String n, byte[] cnt) { private byte[] convertResource(String n, byte[] cnt) {

View File

@ -7,7 +7,8 @@ import java.util.List;
import org.hl7.fhir.utilities.TextFile; import org.hl7.fhir.utilities.TextFile;
import org.hl7.fhir.utilities.Utilities; import org.hl7.fhir.utilities.Utilities;
import org.hl7.fhir.utilities.json.JsonTrackingParser; import org.hl7.fhir.utilities.json.model.JsonObject;
import org.hl7.fhir.utilities.json.parser.JsonParser;
/* /*
Copyright (c) 2011+, HL7, Inc. Copyright (c) 2011+, HL7, Inc.
@ -38,11 +39,6 @@ import org.hl7.fhir.utilities.json.JsonTrackingParser;
*/ */
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
public class PackageMaintainer { public class PackageMaintainer {
@ -96,11 +92,10 @@ public class PackageMaintainer {
if (f.isDirectory()) if (f.isDirectory())
strip(f); strip(f);
else if (f.getName().endsWith(".json")) { else if (f.getName().endsWith(".json")) {
JsonObject json = JsonTrackingParser.parseJson(f); JsonObject json = JsonParser.parseObject(f);
if (json.has("resourceType") && json.has("text")) { if (json.has("resourceType") && json.has("text")) {
json.remove("text"); json.remove("text");
Gson gson = new GsonBuilder().create(); String src = JsonParser.compose(json);
String src = gson.toJson(json);
TextFile.stringToFile(src, f.getAbsolutePath()); TextFile.stringToFile(src, f.getAbsolutePath());
} }
} }

View File

@ -5,12 +5,10 @@ import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.util.Map.Entry; import java.util.Map.Entry;
import org.hl7.fhir.utilities.json.model.JsonObject;
import org.hl7.fhir.utilities.json.model.JsonProperty;
import org.hl7.fhir.utilities.npm.NpmPackage; import org.hl7.fhir.utilities.npm.NpmPackage;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
public class XMLPackageConvertor { public class XMLPackageConvertor {
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
@ -26,13 +24,13 @@ public class XMLPackageConvertor {
System.out.println("Package " + f.getAbsolutePath()); System.out.println("Package " + f.getAbsolutePath());
NpmPackage p = NpmPackage.fromPackage(new FileInputStream(f)); NpmPackage p = NpmPackage.fromPackage(new FileInputStream(f));
if (p.getNpm().has("dependencies")) { if (p.getNpm().has("dependencies")) {
JsonObject dep = p.getNpm().getAsJsonObject("dependencies"); JsonObject dep = p.getNpm().getJsonObject("dependencies");
if (dep.entrySet().isEmpty()) { if (dep.getProperties().isEmpty()) {
System.out.println(" Dependencies: none"); System.out.println(" Dependencies: none");
} else { } else {
System.out.println(" Dependencies:"); System.out.println(" Dependencies:");
for (Entry<String, JsonElement> e : dep.entrySet()) { for (JsonProperty e : dep.getProperties()) {
System.out.println(" " + e.getKey() + ": " + e.getValue().getAsString()); System.out.println(" " + e.getName() + ": " + e.getValue().toString());
} }
} }
} else { } else {

View File

@ -17,13 +17,12 @@ import org.hl7.fhir.convertors.factory.VersionConvertorFactory_40_50;
import org.hl7.fhir.convertors.misc.xver.CorePackageVersionConvertor.BaseConvertor; import org.hl7.fhir.convertors.misc.xver.CorePackageVersionConvertor.BaseConvertor;
import org.hl7.fhir.utilities.Utilities; import org.hl7.fhir.utilities.Utilities;
import org.hl7.fhir.utilities.VersionUtilities; import org.hl7.fhir.utilities.VersionUtilities;
import org.hl7.fhir.utilities.json.JsonTrackingParser; import org.hl7.fhir.utilities.json.model.JsonArray;
import org.hl7.fhir.utilities.json.JsonUtilities; import org.hl7.fhir.utilities.json.model.JsonObject;
import org.hl7.fhir.utilities.json.parser.JsonParser;
import org.hl7.fhir.utilities.npm.NpmPackage; import org.hl7.fhir.utilities.npm.NpmPackage;
import org.hl7.fhir.utilities.npm.NpmPackage.NpmPackageFolder; import org.hl7.fhir.utilities.npm.NpmPackage.NpmPackageFolder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
public class CorePackageVersionConvertor { public class CorePackageVersionConvertor {
@ -582,13 +581,13 @@ public class CorePackageVersionConvertor {
} }
private byte[] convertPackage(byte[] cnt, String version) throws IOException { private byte[] convertPackage(byte[] cnt, String version) throws IOException {
JsonObject json = JsonTrackingParser.parseJson(cnt); JsonObject json = JsonParser.parseObject(cnt);
json.remove("fhir-version-list"); json.remove("fhir-version-list");
JsonArray vl = new JsonArray(); JsonArray vl = new JsonArray();
json.add("fhirVersions", vl); json.add("fhirVersions", vl);
vl.add(version); vl.add(version);
json.addProperty("name", JsonUtilities.str(json, "name")+".as."+VersionUtilities.getNameForVersion(version).toLowerCase()); json.add("name", json.asString("name")+".as."+VersionUtilities.getNameForVersion(version).toLowerCase());
json.addProperty("title", JsonUtilities.str(json, "title")+" (as Version "+VersionUtilities.getNameForVersion(version).toLowerCase()+")"); json.add("title", json.asString("title")+" (as Version "+VersionUtilities.getNameForVersion(version).toLowerCase()+")");
return JsonTrackingParser.write(json).getBytes(StandardCharsets.UTF_8); return JsonParser.composeBytes(json);
} }
} }

View File

@ -156,7 +156,7 @@ public class SimpleWorkerContext extends BaseWorkerContext implements IWorkerCon
public static SimpleWorkerContext fromPackage(NpmPackage pi, IContextResourceLoader loader) throws FileNotFoundException, IOException, FHIRException { public static SimpleWorkerContext fromPackage(NpmPackage pi, IContextResourceLoader loader) throws FileNotFoundException, IOException, FHIRException {
SimpleWorkerContext res = new SimpleWorkerContext(); SimpleWorkerContext res = new SimpleWorkerContext();
res.setAllowLoadingDuplicates(true); res.setAllowLoadingDuplicates(true);
res.version = pi.getNpm().get("version").getAsString(); res.version = pi.getNpm().asString("version");
res.loadFromPackage(pi, loader); res.loadFromPackage(pi, loader);
return res; return res;
} }

View File

@ -163,7 +163,7 @@ public class SimpleWorkerContext extends BaseWorkerContext implements IWorkerCon
public static SimpleWorkerContext fromPackage(NpmPackage pi, IContextResourceLoader loader) throws FileNotFoundException, IOException, FHIRException { public static SimpleWorkerContext fromPackage(NpmPackage pi, IContextResourceLoader loader) throws FileNotFoundException, IOException, FHIRException {
SimpleWorkerContext res = new SimpleWorkerContext(); SimpleWorkerContext res = new SimpleWorkerContext();
res.setAllowLoadingDuplicates(true); res.setAllowLoadingDuplicates(true);
res.version = pi.getNpm().get("version").getAsString(); res.version = pi.getNpm().asString("version");
res.loadFromPackage(pi, loader); res.loadFromPackage(pi, loader);
return res; return res;
} }

View File

@ -216,7 +216,7 @@ public class SimpleWorkerContext extends BaseWorkerContext implements IWorkerCon
public static SimpleWorkerContext fromPackage(NpmPackage pi, IContextResourceLoader loader) throws FileNotFoundException, IOException, FHIRException { public static SimpleWorkerContext fromPackage(NpmPackage pi, IContextResourceLoader loader) throws FileNotFoundException, IOException, FHIRException {
SimpleWorkerContext res = new SimpleWorkerContext(); SimpleWorkerContext res = new SimpleWorkerContext();
res.setAllowLoadingDuplicates(true); res.setAllowLoadingDuplicates(true);
res.version = pi.getNpm().get("version").getAsString(); res.version = pi.getNpm().asString("version");
res.loadFromPackage(pi, loader); res.loadFromPackage(pi, loader);
res.finishLoading(); res.finishLoading();
return res; return res;

View File

@ -250,7 +250,7 @@ public class SimpleWorkerContext extends BaseWorkerContext implements IWorkerCon
public SimpleWorkerContext fromPackage(NpmPackage pi, IContextResourceLoader loader) throws IOException, FHIRException { public SimpleWorkerContext fromPackage(NpmPackage pi, IContextResourceLoader loader) throws IOException, FHIRException {
SimpleWorkerContext context = getSimpleWorkerContextInstance(); SimpleWorkerContext context = getSimpleWorkerContextInstance();
context.setAllowLoadingDuplicates(allowLoadingDuplicates); context.setAllowLoadingDuplicates(allowLoadingDuplicates);
context.version = pi.getNpm().get("version").getAsString(); context.version = pi.getNpm().asString("version");
context.loadFromPackage(pi, loader); context.loadFromPackage(pi, loader);
context.finishLoading(); context.finishLoading();
return build(context); return build(context);

View File

@ -62,16 +62,14 @@ import org.hl7.fhir.r5.model.ImplementationGuide.ImplementationGuideDependsOnCom
import org.hl7.fhir.utilities.CommaSeparatedStringBuilder; import org.hl7.fhir.utilities.CommaSeparatedStringBuilder;
import org.hl7.fhir.utilities.TextFile; import org.hl7.fhir.utilities.TextFile;
import org.hl7.fhir.utilities.Utilities; import org.hl7.fhir.utilities.Utilities;
import org.hl7.fhir.utilities.json.model.JsonArray;
import org.hl7.fhir.utilities.json.model.JsonObject;
import org.hl7.fhir.utilities.json.model.JsonString;
import org.hl7.fhir.utilities.json.parser.JsonParser;
import org.hl7.fhir.utilities.npm.NpmPackageIndexBuilder; import org.hl7.fhir.utilities.npm.NpmPackageIndexBuilder;
import org.hl7.fhir.utilities.npm.ToolsVersion; import org.hl7.fhir.utilities.npm.ToolsVersion;
import org.hl7.fhir.utilities.npm.PackageGenerator.PackageType; import org.hl7.fhir.utilities.npm.PackageGenerator.PackageType;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
public class NPMPackageGenerator { public class NPMPackageGenerator {
public enum Category { public enum Category {
@ -118,13 +116,13 @@ public class NPMPackageGenerator {
public static NPMPackageGenerator subset(NPMPackageGenerator master, String destFile, String id, String name, Date date, boolean notForPublication) throws FHIRException, IOException { public static NPMPackageGenerator subset(NPMPackageGenerator master, String destFile, String id, String name, Date date, boolean notForPublication) throws FHIRException, IOException {
JsonObject p = master.packageJ.deepCopy(); JsonObject p = master.packageJ.deepCopy();
p.remove("name"); p.remove("name");
p.addProperty("name", id); p.add("name", id);
p.remove("type"); p.remove("type");
p.addProperty("type", PackageType.CONFORMANCE.getCode()); p.add("type", PackageType.CONFORMANCE.getCode());
p.remove("title"); p.remove("title");
p.addProperty("title", name); p.add("title", name);
if (notForPublication) { if (notForPublication) {
p.addProperty("notForPublication", true); p.add("notForPublication", true);
} }
return new NPMPackageGenerator(destFile, p, date, notForPublication); return new NPMPackageGenerator(destFile, p, date, notForPublication);
@ -142,17 +140,16 @@ public class NPMPackageGenerator {
String dt = new SimpleDateFormat("yyyyMMddHHmmss").format(date); String dt = new SimpleDateFormat("yyyyMMddHHmmss").format(date);
packageJ = npm; packageJ = npm;
packageManifest = new JsonObject(); packageManifest = new JsonObject();
packageManifest.addProperty("version", npm.get("version").getAsString()); packageManifest.set("version", npm.asString("version"));
packageManifest.addProperty("date", dt); packageManifest.set("date", dt);
if (notForPublication) { if (notForPublication) {
packageManifest.addProperty("notForPublication", true); packageManifest.add("notForPublication", true);
} }
npm.addProperty("date", dt); npm.set("date", dt);
packageManifest.addProperty("name", npm.get("name").getAsString()); packageManifest.set("name", npm.asString("name"));
this.destFile = destFile; this.destFile = destFile;
start(); start();
Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = JsonParser.compose(npm, true);
String json = gson.toJson(npm);
try { try {
addFile(Category.RESOURCE, "package.json", json.getBytes("UTF-8")); addFile(Category.RESOURCE, "package.json", json.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
@ -183,31 +180,31 @@ public class NPMPackageGenerator {
} }
JsonObject npm = new JsonObject(); JsonObject npm = new JsonObject();
npm.addProperty("name", ig.getPackageId()); npm.add("name", ig.getPackageId());
npm.addProperty("version", ig.getVersion()); npm.add("version", ig.getVersion());
igVersion = ig.getVersion(); igVersion = ig.getVersion();
npm.addProperty("tools-version", ToolsVersion.TOOLS_VERSION); npm.add("tools-version", ToolsVersion.TOOLS_VERSION);
npm.addProperty("type", kind.getCode()); npm.add("type", kind.getCode());
npm.addProperty("date", dt); npm.add("date", dt);
if (ig.hasLicense()) { if (ig.hasLicense()) {
npm.addProperty("license", ig.getLicense().toCode()); npm.add("license", ig.getLicense().toCode());
} }
npm.addProperty("canonical", canonical); npm.add("canonical", canonical);
if (notForPublication) { if (notForPublication) {
npm.addProperty("notForPublication", true); npm.add("notForPublication", true);
} }
npm.addProperty("url", web); npm.add("url", web);
if (ig.hasTitle()) { if (ig.hasTitle()) {
npm.addProperty("title", ig.getTitle()); npm.add("title", ig.getTitle());
} }
if (ig.hasDescription()) { if (ig.hasDescription()) {
npm.addProperty("description", ig.getDescription()+ " (built "+dtHuman+timezone()+")"); npm.add("description", ig.getDescription()+ " (built "+dtHuman+timezone()+")");
} }
JsonArray vl = new JsonArray(); JsonArray vl = new JsonArray();
npm.add("fhirVersions", vl); npm.add("fhirVersions", vl);
for (String v : fhirVersion) { for (String v : fhirVersion) {
vl.add(new JsonPrimitive(v)); vl.add(new JsonString(v));
} }
if (kind != PackageType.CORE) { if (kind != PackageType.CORE) {
@ -216,15 +213,15 @@ public class NPMPackageGenerator {
for (String v : fhirVersion) { for (String v : fhirVersion) {
String vp = packageForVersion(v); String vp = packageForVersion(v);
if (vp != null ) { if (vp != null ) {
dep.addProperty(vp, v); dep.add(vp, v);
} }
} }
for (ImplementationGuideDependsOnComponent d : ig.getDependsOn()) { for (ImplementationGuideDependsOnComponent d : ig.getDependsOn()) {
dep.addProperty(d.getPackageId(), d.getVersion()); dep.add(d.getPackageId(), d.getVersion());
} }
} }
if (ig.hasPublisher()) { if (ig.hasPublisher()) {
npm.addProperty("author", ig.getPublisher()); npm.add("author", ig.getPublisher());
} }
JsonArray m = new JsonArray(); JsonArray m = new JsonArray();
for (ContactDetail t : ig.getContact()) { for (ContactDetail t : ig.getContact()) {
@ -233,23 +230,22 @@ public class NPMPackageGenerator {
if (t.hasName() & (email != null || url != null)) { if (t.hasName() & (email != null || url != null)) {
JsonObject md = new JsonObject(); JsonObject md = new JsonObject();
m.add(md); m.add(md);
md.addProperty("name", t.getName()); md.add("name", t.getName());
if (email != null) if (email != null)
md.addProperty("email", email); md.add("email", email);
if (url != null) if (url != null)
md.addProperty("url", url); md.add("url", url);
} }
} }
if (m.size() > 0) if (m.size() > 0)
npm.add("maintainers", m); npm.add("maintainers", m);
if (ig.getManifest().hasRendering()) if (ig.getManifest().hasRendering())
npm.addProperty("homepage", ig.getManifest().getRendering()); npm.add("homepage", ig.getManifest().getRendering());
JsonObject dir = new JsonObject(); JsonObject dir = new JsonObject();
npm.add("directories", dir); npm.add("directories", dir);
dir.addProperty("lib", "package"); dir.add("lib", "package");
dir.addProperty("example", "example"); dir.add("example", "example");
Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = JsonParser.compose(npm, true);
String json = gson.toJson(npm);
try { try {
addFile(Category.RESOURCE, "package.json", json.getBytes("UTF-8")); addFile(Category.RESOURCE, "package.json", json.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
@ -257,14 +253,14 @@ public class NPMPackageGenerator {
packageJ = npm; packageJ = npm;
packageManifest = new JsonObject(); packageManifest = new JsonObject();
packageManifest.addProperty("version", ig.getVersion()); packageManifest.add("version", ig.getVersion());
JsonArray fv = new JsonArray(); JsonArray fv = new JsonArray();
for (String v : fhirVersion) { for (String v : fhirVersion) {
fv.add(v); fv.add(v);
} }
packageManifest.add("fhirVersion", fv); packageManifest.add("fhirVersion", fv);
packageManifest.addProperty("date", dt); packageManifest.add("date", dt);
packageManifest.addProperty("name", ig.getPackageId()); packageManifest.add("name", ig.getPackageId());
} }
@ -380,8 +376,7 @@ public class NPMPackageGenerator {
OutputStream.close(); OutputStream.close();
TextFile.bytesToFile(OutputStream.toByteArray(), destFile); TextFile.bytesToFile(OutputStream.toByteArray(), destFile);
// also, for cache management on current builds, generate a little manifest // also, for cache management on current builds, generate a little manifest
Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = JsonParser.compose(packageManifest, true);
String json = gson.toJson(packageManifest);
TextFile.stringToFile(json, Utilities.changeFileExt(destFile, ".manifest.json"), false); TextFile.stringToFile(json, Utilities.changeFileExt(destFile, ".manifest.json"), false);
} }

View File

@ -62,9 +62,9 @@ public class XVerExtensionManager {
} }
} }
JsonObject root = lists.get(v); JsonObject root = lists.get(v);
JsonObject path = root.getObject(e); JsonObject path = root.getJsonObject(e);
if (path == null) { if (path == null) {
path = root.getObject(e+"[x]"); path = root.getJsonObject(e+"[x]");
} }
if (path == null) { if (path == null) {
return XVerExtensionStatus.Unknown; return XVerExtensionStatus.Unknown;
@ -85,9 +85,9 @@ public class XVerExtensionManager {
String verTarget = VersionUtilities.getMajMin(context.getVersion()); String verTarget = VersionUtilities.getMajMin(context.getVersion());
String e = url.substring(54); String e = url.substring(54);
JsonObject root = lists.get(verSource); JsonObject root = lists.get(verSource);
JsonObject path = root.getObject(e); JsonObject path = root.getJsonObject(e);
if (path == null) { if (path == null) {
path = root.getObject(e+"[x]"); path = root.getJsonObject(e+"[x]");
} }
StructureDefinition sd = new StructureDefinition(); StructureDefinition sd = new StructureDefinition();
@ -116,9 +116,9 @@ public class XVerExtensionManager {
populateTypes(path, val, verSource, verTarget); populateTypes(path, val, verSource, verTarget);
} else if (path.has("elements")) { } else if (path.has("elements")) {
for (JsonElement i : path.forceArray("elements").getItems()) { for (JsonElement i : path.forceArray("elements").getItems()) {
JsonObject elt = root.getObject(e+"."+i.toString()); JsonObject elt = root.getJsonObject(e+"."+i.asString());
if (elt != null) { if (elt != null) {
String s = i.toString().replace("[x]", ""); String s = i.asString().replace("[x]", "");
sd.getDifferential().addElement().setPath("Extension.extension").setSliceName(s); sd.getDifferential().addElement().setPath("Extension.extension").setSliceName(s);
sd.getDifferential().addElement().setPath("Extension.extension.extension").setMax("0"); sd.getDifferential().addElement().setPath("Extension.extension.extension").setMax("0");
sd.getDifferential().addElement().setPath("Extension.extension.url").setFixed(new UriType(s)); sd.getDifferential().addElement().setPath("Extension.extension.url").setFixed(new UriType(s));
@ -144,7 +144,7 @@ public class XVerExtensionManager {
public void populateTypes(JsonObject path, ElementDefinition val, String verSource, String verTarget) { public void populateTypes(JsonObject path, ElementDefinition val, String verSource, String verTarget) {
for (JsonElement i : path.forceArray("types").getItems()) { for (JsonElement i : path.forceArray("types").getItems()) {
String s = i.toString(); String s = i.asString();
if (!s.startsWith("!")) { if (!s.startsWith("!")) {
if (s.contains("(")) { if (s.contains("(")) {
String t = s.substring(0, s.indexOf("(")); String t = s.substring(0, s.indexOf("("));

View File

@ -1,12 +1,13 @@
package org.hl7.fhir.utilities.json.model; package org.hl7.fhir.utilities.json.model;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; import java.util.List;
import org.hl7.fhir.utilities.json.JsonException; import org.hl7.fhir.utilities.json.JsonException;
public class JsonArray extends JsonElement { public class JsonArray extends JsonElement implements Iterable<JsonElement> {
private List<JsonElement> items = new ArrayList<>(); private List<JsonElement> items = new ArrayList<>();
private List<Boolean> noCommas; // validator use private List<Boolean> noCommas; // validator use
private List<Boolean> unQuoted; // validator use private List<Boolean> unQuoted; // validator use
@ -15,7 +16,7 @@ public class JsonArray extends JsonElement {
List<String> list = new ArrayList<>(); List<String> list = new ArrayList<>();
for (JsonElement n : items) { for (JsonElement n : items) {
if (n instanceof JsonPrimitive) { if (n instanceof JsonPrimitive) {
list.add(n.toString()); list.add(n.asJsonPrimitive().getValue());
} }
} }
return list; return list;
@ -25,7 +26,7 @@ public class JsonArray extends JsonElement {
return items; return items;
} }
public List<JsonObject> asObjects() { public List<JsonObject> asJsonObjects() {
List<JsonObject> list = new ArrayList<>(); List<JsonObject> list = new ArrayList<>();
for (JsonElement n : items) { for (JsonElement n : items) {
if (n instanceof JsonObject) { if (n instanceof JsonObject) {
@ -79,11 +80,50 @@ public class JsonArray extends JsonElement {
public JsonObject findByStringProp(JsonArray arr, String prop, String value) { public JsonObject findByStringProp(JsonArray arr, String prop, String value) {
for (JsonObject obj : asObjects()) { for (JsonObject obj : asJsonObjects()) {
if (obj.has(prop) && value.equals(obj.getString(prop))) if (obj.has(prop) && value.equals(obj.asString(prop)))
return obj; return obj;
} }
return null; return null;
} }
public Iterator<JsonElement> iterator() {
return items.iterator();
}
public JsonElement get(int i) {
return items.get(i);
}
public JsonArray deepCopy() {
return (JsonArray) make().copy(this);
}
@Override
protected JsonElement copy(JsonElement other) {
JsonArray o = (JsonArray) other;
for (JsonElement p : o.getItems()) {
add(p.deepCopy());
}
return this;
}
@Override
protected JsonElement make() {
return new JsonArray();
}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
b.append("[ ");
boolean first = true;
for (JsonElement p : items) {
if (first) first = false; else b.append(", ");
b.append(p.toString());
}
b.append(" ]");
return b.toString();
}
} }

View File

@ -8,6 +8,9 @@ public class JsonBoolean extends JsonPrimitive {
this.value = value; this.value = value;
} }
private JsonBoolean() {
}
public JsonElementType elementType() { public JsonElementType elementType() {
return JsonElementType.BOOLEAN; return JsonElementType.BOOLEAN;
} }
@ -20,6 +23,7 @@ public class JsonBoolean extends JsonPrimitive {
this.value = value; this.value = value;
} }
@Override
public String getValue() { public String getValue() {
return value ? "true" : "false"; return value ? "true" : "false";
} }
@ -28,4 +32,15 @@ public class JsonBoolean extends JsonPrimitive {
public String toString() { public String toString() {
return getValue(); return getValue();
} }
@Override
protected JsonElement copy(JsonElement other) {
value = ((JsonBoolean) other).value;
return this;
}
@Override
protected JsonElement make() {
return new JsonBoolean();
}
} }

View File

@ -1,5 +0,0 @@
package org.hl7.fhir.utilities.json.model;
public class JsonComment {
}

View File

@ -45,4 +45,71 @@ public abstract class JsonElement {
public boolean hasComments() { public boolean hasComments() {
return comments != null && !comments.isEmpty(); return comments != null && !comments.isEmpty();
} }
public JsonElement deepCopy() {
return make().copy(this);
}
protected abstract JsonElement copy(JsonElement jsonElement);
protected abstract JsonElement make();
public boolean isJsonObject() {
return elementType() == JsonElementType.OBJECT;
}
public boolean isJsonArray() {
return elementType() == JsonElementType.ARRAY;
}
public boolean isJsonPrimitive() {
return isJsonBoolean() || isJsonString() || isJsonNull() || isJsonNumber();
}
public boolean isJsonBoolean() {
return elementType() == JsonElementType.BOOLEAN;
}
public boolean isJsonString() {
return elementType() == JsonElementType.STRING;
}
public boolean isJsonNumber() {
return elementType() == JsonElementType.NUMBER;
}
public boolean isJsonNull() {
return elementType() == JsonElementType.NULL;
}
public JsonObject asJsonObject() {
return isJsonObject() ? (JsonObject) this : null;
}
public JsonArray asJsonArray() {
return isJsonArray() ? (JsonArray) this : null;
}
public JsonPrimitive asJsonPrimitive() {
return isJsonPrimitive() ? (JsonPrimitive) this : null;
}
public JsonBoolean asJsonBoolean() {
return isJsonBoolean() ? (JsonBoolean) this : null;
}
public JsonString asJsonString() {
return isJsonString() ? (JsonString) this : null;
}
public JsonNumber asJsonNumber() {
return isJsonNumber() ? (JsonNumber) this : null;
}
public JsonNull asJsonNull() {
return isJsonNull() ? (JsonNull) this : null;
}
public String asString() {
return isJsonPrimitive() ? ((JsonPrimitive) this).getValue() : null;
}
} }

View File

@ -6,7 +6,7 @@ public class JsonNull extends JsonPrimitive {
return JsonElementType.NULL; return JsonElementType.NULL;
} }
@Override
public String getValue() { public String getValue() {
return "null"; return "null";
} }
@ -15,4 +15,14 @@ public class JsonNull extends JsonPrimitive {
public String toString() { public String toString() {
return getValue(); return getValue();
} }
@Override
protected JsonElement copy(JsonElement other) {
return this;
}
@Override
protected JsonElement make() {
return new JsonNull();
}
} }

View File

@ -10,10 +10,18 @@ public class JsonNumber extends JsonPrimitive {
this.value = value; this.value = value;
} }
public JsonNumber(int value) {
this.value = Integer.toString(value);
}
private JsonNumber() {
}
public JsonElementType elementType() { public JsonElementType elementType() {
return JsonElementType.NUMBER; return JsonElementType.NUMBER;
} }
@Override
public String getValue() { public String getValue() {
return value; return value;
} }
@ -30,4 +38,15 @@ public class JsonNumber extends JsonPrimitive {
return null; return null;
} }
} }
@Override
protected JsonElement copy(JsonElement other) {
value = ((JsonNumber) other).value;
return this;
}
@Override
protected JsonElement make() {
return new JsonNumber();
}
} }

View File

@ -1,9 +1,12 @@
package org.hl7.fhir.utilities.json.model; package org.hl7.fhir.utilities.json.model;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry;
import org.hl7.fhir.utilities.Utilities; import org.hl7.fhir.utilities.Utilities;
import org.hl7.fhir.utilities.json.JsonException; import org.hl7.fhir.utilities.json.JsonException;
@ -19,8 +22,8 @@ public class JsonObject extends JsonElement {
} }
public JsonObject add(String name, JsonElement value) throws JsonException { public JsonObject add(String name, JsonElement value) throws JsonException {
check(name != null, "Numm is null"); check(name != null, "Name is null");
check(value != null, "Numm is null"); check(value != null, "Value is null");
check(get(name) == null, "Name '"+name+"' already exists"); check(get(name) == null, "Name '"+name+"' already exists");
JsonProperty p = new JsonProperty(name, value); JsonProperty p = new JsonProperty(name, value);
properties.add(p); properties.add(p);
@ -30,8 +33,8 @@ public class JsonObject extends JsonElement {
// this is used by the parser which can allow duplicates = true (for the validator). You should not otherwise use it // this is used by the parser which can allow duplicates = true (for the validator). You should not otherwise use it
public JsonObject addForParser(String name, JsonElement value, boolean noComma, boolean nameUnquoted, boolean valueUnquoted) throws JsonException { public JsonObject addForParser(String name, JsonElement value, boolean noComma, boolean nameUnquoted, boolean valueUnquoted) throws JsonException {
check(name != null, "Numm is null"); check(name != null, "Name is null");
check(value != null, "Numm is null"); check(value != null, "Value is null");
JsonProperty p = new JsonProperty(name, value); JsonProperty p = new JsonProperty(name, value);
p.setNoComma(noComma); p.setNoComma(noComma);
p.setUnquotedName(nameUnquoted); p.setUnquotedName(nameUnquoted);
@ -42,13 +45,64 @@ public class JsonObject extends JsonElement {
} }
public JsonObject add(String name, String value) throws JsonException { public JsonObject add(String name, String value) throws JsonException {
check(name != null, "Name is null");
return add(name, new JsonString(value)); return add(name, new JsonString(value));
} }
public JsonObject add(String name, boolean value) throws JsonException { public JsonObject add(String name, boolean value) throws JsonException {
check(name != null, "Name is null");
return add(name, new JsonBoolean(value)); return add(name, new JsonBoolean(value));
} }
public JsonObject add(String name, int value) throws JsonException {
check(name != null, "Name is null");
return add(name, new JsonNumber(value));
}
public JsonObject set(String name, JsonElement value) throws JsonException {
check(name != null, "Name is null");
check(value != null, "Value is null");
JsonProperty p = propMap.get(name);
if (p != null) {
p.setValue(value);
return this;
} else {
return add(name, value);
}
}
public JsonObject set(String name, String value) throws JsonException {
check(name != null, "Name is null");
JsonProperty p = propMap.get(name);
if (p != null) {
p.setValue(new JsonString(value));
return this;
} else {
return add(name, new JsonString(value));
}
}
public JsonObject set(String name, boolean value) throws JsonException {
check(name != null, "Name is null");
JsonProperty p = propMap.get(name);
if (p != null) {
p.setValue(new JsonBoolean(value));
return this;
} else {
return add(name, new JsonBoolean(value));
}
}
public JsonObject set(String name, int value) throws JsonException {
check(name != null, "Name is null");
JsonProperty p = propMap.get(name);
if (p != null) {
p.setValue(new JsonNumber(value));
return this;
} else {
return add(name, new JsonNumber(value));
}
}
public JsonElement get(String name) { public JsonElement get(String name) {
if (propMap.containsKey(name)) { if (propMap.containsKey(name)) {
@ -62,7 +116,7 @@ public class JsonObject extends JsonElement {
return propMap.containsKey(name); return propMap.containsKey(name);
} }
public void drop(String name) { public void remove(String name) {
if (propMap.containsKey(name)) { if (propMap.containsKey(name)) {
propMap.remove(name); propMap.remove(name);
properties.removeIf((JsonProperty item) -> name.equals(item.getName())); properties.removeIf((JsonProperty item) -> name.equals(item.getName()));
@ -74,8 +128,8 @@ public class JsonObject extends JsonElement {
} }
public String str(String name) { public String str(String name) {
if (has(name)) { if (hasPrimitive(name)) {
return get(name).toString(); return get(name).asJsonPrimitive().getValue();
} else { } else {
return null; return null;
} }
@ -110,27 +164,27 @@ public class JsonObject extends JsonElement {
} }
public JsonObject getObject(String name) { public JsonObject getJsonObject(String name) {
return hasObject(name) ? (JsonObject) get(name) : null; return hasObject(name) ? (JsonObject) get(name) : null;
} }
public JsonString getString(String name) { public JsonString getJsonString(String name) {
return hasString(name) ? (JsonString) get(name) : null; return hasString(name) ? (JsonString) get(name) : null;
} }
public JsonBoolean getBoolean(String name) { public JsonBoolean getJsonBoolean(String name) {
return hasBoolean(name) ? (JsonBoolean) get(name) : null; return hasBoolean(name) ? (JsonBoolean) get(name) : null;
} }
public JsonNumber getNumber(String name) { public JsonNumber getJsonNumber(String name) {
return hasNumber(name) ? (JsonNumber) get(name) : null; return hasNumber(name) ? (JsonNumber) get(name) : null;
} }
public JsonNull getNull(String name) { public JsonNull getJsonNull(String name) {
return hasNull(name) ?(JsonNull) get(name) : null; return hasNull(name) ?(JsonNull) get(name) : null;
} }
public JsonArray getArray(String name) { public JsonArray getJsonArray(String name) {
return hasArray(name) ? (JsonArray) get(name) : null; return hasArray(name) ? (JsonArray) get(name) : null;
} }
@ -148,7 +202,16 @@ public class JsonObject extends JsonElement {
} }
public String asString(String name) { public String asString(String name) {
return hasPrimitive(name) ? ((JsonPrimitive) get(name)).toString() : null; return hasPrimitive(name) ? ((JsonPrimitive) get(name)).getValue() : null;
}
public String asString(String... names) {
for (String n : names) {
if (hasPrimitive(n)) {
return asString(n);
}
}
return null;
} }
public boolean asBoolean(String name) { public boolean asBoolean(String name) {
@ -167,25 +230,101 @@ public class JsonObject extends JsonElement {
return false; return false;
} }
public Instant asDate(String name) {
String source = asString(name);
if (Utilities.noString(source)) {
return null;
} else {
OffsetDateTime odt = OffsetDateTime.parse(source);
return odt.toInstant();
}
}
public JsonObject forceObject(String name) throws JsonException { public JsonObject forceObject(String name) throws JsonException {
if (has(name) && !hasObject(name)) { if (has(name) && !hasObject(name)) {
drop(name); remove(name);
} }
if (!has(name)) { if (!has(name)) {
add(name, new JsonObject()); add(name, new JsonObject());
} }
return getObject(name); return getJsonObject(name);
} }
public JsonArray forceArray(String name) throws JsonException { public JsonArray forceArray(String name) throws JsonException {
if (has(name) && !hasArray(name)) { if (has(name) && !hasArray(name)) {
drop(name); remove(name);
} }
if (!has(name)) { if (!has(name)) {
add(name, new JsonArray()); add(name, new JsonArray());
} }
return getArray(name); return getJsonArray(name);
}
public List<JsonObject> getJsonObjects(String name) {
List<JsonObject> res = new ArrayList<>();
if (hasArray(name)) {
res.addAll(getJsonArray(name).asJsonObjects());
} else if (hasObject(name)) {
res.add(getJsonObject(name));
}
return res;
}
public List<String> getStrings(String name) {
List<String> res = new ArrayList<>();
if (hasArray(name)) {
res.addAll(getJsonArray(name).asStrings());
} else if (hasPrimitive(name)) {
res.add(asString(name));
}
return res;
}
public JsonObject deepCopy() {
return (JsonObject) make().copy(this);
}
@Override
protected JsonElement copy(JsonElement other) {
JsonObject o = (JsonObject) other;
for (JsonProperty p : o.getProperties()) {
add(p.getName(), p.getValue().deepCopy());
}
return this;
}
@Override
protected JsonElement make() {
return new JsonObject();
}
public void merge(JsonObject source) {
for (JsonProperty pp : source.getProperties()) {
if (has(pp.getName())) {
JsonElement te = get(pp.getName());
if (te.isJsonObject() && pp.getValue().isJsonObject()) {
((JsonObject) te).merge((JsonObject) pp.getValue());
} else {
set(pp.getName(), pp.getValue());
}
} else {
add(pp.getName(), pp.getValue());
}
}
} }
@Override
public String toString() {
StringBuilder b = new StringBuilder();
b.append("{ ");
boolean first = true;
for (JsonProperty p : properties) {
if (first) first = false; else b.append(", ");
b.append(p.toString());
}
b.append(" }");
return b.toString();
}
} }

View File

@ -2,4 +2,9 @@ package org.hl7.fhir.utilities.json.model;
public abstract class JsonPrimitive extends JsonElement { public abstract class JsonPrimitive extends JsonElement {
public abstract String getValue();
public String toJson() {
return getValue();
}
} }

View File

@ -50,4 +50,9 @@ public class JsonProperty {
this.unquotedValue = unquotedValue; this.unquotedValue = unquotedValue;
} }
@Override
public String toString() {
return "\""+name+"\" : "+value.toString();
}
} }

View File

@ -1,5 +1,7 @@
package org.hl7.fhir.utilities.json.model; package org.hl7.fhir.utilities.json.model;
import org.hl7.fhir.utilities.Utilities;
public class JsonString extends JsonPrimitive { public class JsonString extends JsonPrimitive {
private String value; private String value;
@ -8,10 +10,14 @@ public class JsonString extends JsonPrimitive {
this.value = value; this.value = value;
} }
private JsonString() {
}
public JsonElementType elementType() { public JsonElementType elementType() {
return JsonElementType.STRING; return JsonElementType.STRING;
} }
@Override
public String getValue() { public String getValue() {
return value; return value;
} }
@ -22,7 +28,23 @@ public class JsonString extends JsonPrimitive {
@Override @Override
public String toString() { public String toString() {
return value; throw new Error("This should not be called");
// return "\""+ Utilities.escapeJson(value)+"\"";
} }
@Override
public String toJson() {
return "\""+ Utilities.escapeJson(value)+"\"";
}
@Override
protected JsonElement copy(JsonElement other) {
value = ((JsonString) other).value;
return this;
}
@Override
protected JsonElement make() {
return new JsonString();
}
} }

View File

@ -220,8 +220,11 @@ public class JsonParser {
lexer.next(); lexer.next();
lexer.getStates().push(new State("", true)); lexer.getStates().push(new State("", true));
} }
else else if (lexer.getType() != null) {
throw lexer.error("Unexpected content at start of JSON: "+lexer.getType().toString()); throw lexer.error("Unexpected content at start of JSON: "+lexer.getType().toString());
} else {
throw lexer.error("Unexpected content at start of JSON");
}
if (lexer.getType() != TokenType.Close) { if (lexer.getType() != TokenType.Close) {
parseProperty(); parseProperty();
@ -568,7 +571,7 @@ public class JsonParser {
int length = 0; int length = 0;
for (JsonElement i : arr.getItems()) { for (JsonElement i : arr.getItems()) {
if (i instanceof JsonPrimitive) { if (i instanceof JsonPrimitive) {
length = length + i.toString().length(); length = length + ((JsonPrimitive)i).toJson().length();
} }
if (i.elementType() == JsonElementType.ARRAY || i.elementType() == JsonElementType.OBJECT if (i.elementType() == JsonElementType.ARRAY || i.elementType() == JsonElementType.OBJECT
|| i.hasComments()) { // 20 is a somewhat arbitrary cut off || i.hasComments()) { // 20 is a somewhat arbitrary cut off

View File

@ -32,8 +32,10 @@ import org.hl7.fhir.utilities.SimpleHTTPClient.HTTPResult;
import org.hl7.fhir.utilities.TextFile; import org.hl7.fhir.utilities.TextFile;
import org.hl7.fhir.utilities.Utilities; import org.hl7.fhir.utilities.Utilities;
import org.hl7.fhir.utilities.VersionUtilities; import org.hl7.fhir.utilities.VersionUtilities;
import org.hl7.fhir.utilities.json.JsonTrackingParser; import org.hl7.fhir.utilities.json.model.JsonArray;
import org.hl7.fhir.utilities.json.JsonUtilities; import org.hl7.fhir.utilities.json.model.JsonElement;
import org.hl7.fhir.utilities.json.model.JsonObject;
import org.hl7.fhir.utilities.json.parser.JsonParser;
import org.hl7.fhir.utilities.npm.NpmPackage.NpmPackageFolder; import org.hl7.fhir.utilities.npm.NpmPackage.NpmPackageFolder;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -67,12 +69,6 @@ import org.slf4j.LoggerFactory;
*/ */
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
/** /**
* This is a package cache manager implementation that uses a local disk cache * This is a package cache manager implementation that uses a local disk cache
* *
@ -420,18 +416,18 @@ public class FilesystemPackageCacheManager extends BasePackageCacheManager imple
log(" done."); log(" done.");
} }
pck = loadPackageInfo(packRoot); pck = loadPackageInfo(packRoot);
if (!id.equals(JsonUtilities.str(npm.getNpm(), "name")) || !v.equals(JsonUtilities.str(npm.getNpm(), "version"))) { if (!id.equals(npm.getNpm().asString("name")) || !v.equals(npm.getNpm().asString("version"))) {
if (!id.equals(JsonUtilities.str(npm.getNpm(), "name"))) { if (!id.equals(npm.getNpm().asString("name"))) {
npm.getNpm().addProperty("original-name", JsonUtilities.str(npm.getNpm(), "name")); npm.getNpm().add("original-name", npm.getNpm().asString("name"));
npm.getNpm().remove("name"); npm.getNpm().remove("name");
npm.getNpm().addProperty("name", id); npm.getNpm().add("name", id);
} }
if (!v.equals(JsonUtilities.str(npm.getNpm(), "version"))) { if (!v.equals(npm.getNpm().asString("version"))) {
npm.getNpm().addProperty("original-version", JsonUtilities.str(npm.getNpm(), "version")); npm.getNpm().add("original-version", npm.getNpm().asString("version"));
npm.getNpm().remove("version"); npm.getNpm().remove("version");
npm.getNpm().addProperty("version", v); npm.getNpm().add("version", v);
} }
TextFile.stringToFile(new GsonBuilder().setPrettyPrinting().create().toJson(npm.getNpm()), Utilities.path(cacheFolder, id + "#" + v, "package", "package.json"), false); TextFile.stringToFile(JsonParser.compose(npm.getNpm(), true), Utilities.path(cacheFolder, id + "#" + v, "package", "package.json"), false);
} }
} catch (Exception e) { } catch (Exception e) {
try { try {
@ -570,10 +566,9 @@ public class FilesystemPackageCacheManager extends BasePackageCacheManager imple
private String getPackageUrlFromBuildList(String packageId) throws IOException { private String getPackageUrlFromBuildList(String packageId) throws IOException {
checkBuildLoaded(); checkBuildLoaded();
for (JsonElement n : buildInfo) { for (JsonObject o : buildInfo.asJsonObjects()) {
JsonObject o = (JsonObject) n; if (packageId.equals(o.asString("package-id"))) {
if (packageId.equals(JsonUtilities.str(o, "package-id"))) { return o.asString("url");
return JsonUtilities.str(o, "url");
} }
} }
return null; return null;
@ -583,8 +578,8 @@ public class FilesystemPackageCacheManager extends BasePackageCacheManager imple
checkBuildLoaded(); checkBuildLoaded();
for (JsonElement n : buildInfo) { for (JsonElement n : buildInfo) {
JsonObject o = (JsonObject) n; JsonObject o = (JsonObject) n;
if (!specList.containsKey(JsonUtilities.str(o, "package-id"))) { if (!specList.containsKey(o.asString("package-id"))) {
specList.put(JsonUtilities.str(o, "package-id"), JsonUtilities.str(o, "url")); specList.put(o.asString("package-id"), o.asString("url"));
} }
} }
} }
@ -609,9 +604,9 @@ public class FilesystemPackageCacheManager extends BasePackageCacheManager imple
try { try {
for (String pf : listPackages()) { for (String pf : listPackages()) {
if (new File(Utilities.path(cacheFolder, pf, "package", "package.json")).exists()) { if (new File(Utilities.path(cacheFolder, pf, "package", "package.json")).exists()) {
JsonObject npm = JsonTrackingParser.parseJsonFile(Utilities.path(cacheFolder, pf, "package", "package.json")); JsonObject npm = JsonParser.parseObjectFromFile(Utilities.path(cacheFolder, pf, "package", "package.json"));
if (canonicalUrl.equals(JsonUtilities.str(npm, "canonical"))) { if (canonicalUrl.equals(npm.asString("canonical"))) {
return JsonUtilities.str(npm, "name"); return npm.asString("name");
} }
} }
} }
@ -630,14 +625,14 @@ public class FilesystemPackageCacheManager extends BasePackageCacheManager imple
if (buildInfo != null) { if (buildInfo != null) {
for (JsonElement n : buildInfo) { for (JsonElement n : buildInfo) {
JsonObject o = (JsonObject) n; JsonObject o = (JsonObject) n;
if (canonical.equals(JsonUtilities.str(o, "url"))) { if (canonical.equals(o.asString("url"))) {
return JsonUtilities.str(o, "package-id"); return o.asString("package-id");
} }
} }
for (JsonElement n : buildInfo) { for (JsonElement n : buildInfo) {
JsonObject o = (JsonObject) n; JsonObject o = (JsonObject) n;
if (JsonUtilities.str(o, "url").startsWith(canonical + "/ImplementationGuide/")) { if (o.asString("url").startsWith(canonical + "/ImplementationGuide/")) {
return JsonUtilities.str(o, "package-id"); return o.asString("package-id");
} }
} }
} }
@ -649,8 +644,8 @@ public class FilesystemPackageCacheManager extends BasePackageCacheManager imple
// special case: current versions roll over, and we have to check their currency // special case: current versions roll over, and we have to check their currency
try { try {
String url = ciList.get(id); String url = ciList.get(id);
JsonObject json = JsonTrackingParser.fetchJson(Utilities.pathURL(url, "package.manifest.json")); JsonObject json = JsonParser.parseObjectFromUrl(Utilities.pathURL(url, "package.manifest.json"));
String currDate = JsonUtilities.str(json, "date"); String currDate = json.asString("date");
String packDate = p.date(); String packDate = p.date();
if (!currDate.equals(packDate)) { if (!currDate.equals(packDate)) {
return null; // nup, we need a new copy return null; // nup, we need a new copy
@ -678,17 +673,17 @@ public class FilesystemPackageCacheManager extends BasePackageCacheManager imple
HTTPResult res = http.get("https://build.fhir.org/ig/qas.json?nocache=" + System.currentTimeMillis()); HTTPResult res = http.get("https://build.fhir.org/ig/qas.json?nocache=" + System.currentTimeMillis());
res.checkThrowException(); res.checkThrowException();
buildInfo = (JsonArray) new com.google.gson.JsonParser().parse(TextFile.bytesToString(res.getContent())); buildInfo = (JsonArray) JsonParser.parse(TextFile.bytesToString(res.getContent()));
List<BuildRecord> builds = new ArrayList<>(); List<BuildRecord> builds = new ArrayList<>();
for (JsonElement n : buildInfo) { for (JsonElement n : buildInfo) {
JsonObject o = (JsonObject) n; JsonObject o = (JsonObject) n;
if (o.has("url") && o.has("package-id") && o.get("package-id").getAsString().contains(".")) { if (o.has("url") && o.has("package-id") && o.asString("package-id").contains(".")) {
String u = o.get("url").getAsString(); String u = o.asString("url");
if (u.contains("/ImplementationGuide/")) if (u.contains("/ImplementationGuide/"))
u = u.substring(0, u.indexOf("/ImplementationGuide/")); u = u.substring(0, u.indexOf("/ImplementationGuide/"));
builds.add(new BuildRecord(u, o.get("package-id").getAsString(), getRepo(o.get("repo").getAsString()), readDate(o.get("date").getAsString()))); builds.add(new BuildRecord(u, o.asString("package-id"), getRepo(o.asString("repo")), readDate(o.asString("date"))));
} }
} }
Collections.sort(builds, new BuildRecordSorter()); Collections.sort(builds, new BuildRecordSorter());
@ -735,7 +730,7 @@ public class FilesystemPackageCacheManager extends BasePackageCacheManager imple
String aurl = pu; String aurl = pu;
JsonObject json; JsonObject json;
try { try {
json = JsonTrackingParser.fetchJson(pu); json = JsonParser.parseObjectFromUrl(pu);
} catch (Exception e) { } catch (Exception e) {
String pv = Utilities.pathURL(url, v, "package.tgz"); String pv = Utilities.pathURL(url, v, "package.tgz");
try { try {
@ -746,13 +741,12 @@ public class FilesystemPackageCacheManager extends BasePackageCacheManager imple
throw new FHIRException("Error fetching package directly (" + pv + "), or fetching package list for " + id + " from " + pu + ": " + e1.getMessage(), e1); throw new FHIRException("Error fetching package directly (" + pv + "), or fetching package list for " + id + " from " + pu + ": " + e1.getMessage(), e1);
} }
} }
if (!id.equals(JsonUtilities.str(json, "package-id"))) if (!id.equals(json.asString("package-id")))
throw new FHIRException("Package ids do not match in " + pu + ": " + id + " vs " + JsonUtilities.str(json, "package-id")); throw new FHIRException("Package ids do not match in " + pu + ": " + id + " vs " + json.asString("package-id"));
for (JsonElement e : json.getAsJsonArray("list")) { for (JsonObject vo : json.getJsonObjects("list")) {
JsonObject vo = (JsonObject) e; if (v.equals(vo.asString("version"))) {
if (v.equals(JsonUtilities.str(vo, "version"))) { aurl = Utilities.pathURL(vo.asString("path"), "package.tgz");
aurl = Utilities.pathURL(JsonUtilities.str(vo, "path"), "package.tgz"); String u = Utilities.pathURL(vo.asString("path"), "package.tgz");
String u = Utilities.pathURL(JsonUtilities.str(vo, "path"), "package.tgz");
return new InputStreamWithSrc(fetchFromUrlSpecific(u, true), u, v); return new InputStreamWithSrc(fetchFromUrlSpecific(u, true), u, v);
} }
} }
@ -776,13 +770,12 @@ public class FilesystemPackageCacheManager extends BasePackageCacheManager imple
throw new FHIRException("Unable to resolve package id " + id); throw new FHIRException("Unable to resolve package id " + id);
} }
String pu = Utilities.pathURL(url, "package-list.json"); String pu = Utilities.pathURL(url, "package-list.json");
JsonObject json = JsonTrackingParser.fetchJson(pu); JsonObject json = JsonParser.parseObjectFromUrl(pu);
if (!id.equals(JsonUtilities.str(json, "package-id"))) if (!id.equals(json.asString("package-id")))
throw new FHIRException("Package ids do not match in " + pu + ": " + id + " vs " + JsonUtilities.str(json, "package-id")); throw new FHIRException("Package ids do not match in " + pu + ": " + id + " vs " + json.asString("package-id"));
for (JsonElement e : json.getAsJsonArray("list")) { for (JsonObject vo : json.getJsonObjects("list")) {
JsonObject vo = (JsonObject) e; if (vo.asBoolean("current")) {
if (JsonUtilities.bool(vo, "current")) { return vo.asString("version");
return JsonUtilities.str(vo, "version");
} }
} }

View File

@ -66,15 +66,13 @@ import org.hl7.fhir.utilities.SimpleHTTPClient;
import org.hl7.fhir.utilities.SimpleHTTPClient.HTTPResult; import org.hl7.fhir.utilities.SimpleHTTPClient.HTTPResult;
import org.hl7.fhir.utilities.TextFile; import org.hl7.fhir.utilities.TextFile;
import org.hl7.fhir.utilities.Utilities; import org.hl7.fhir.utilities.Utilities;
import org.hl7.fhir.utilities.json.JsonTrackingParser; import org.hl7.fhir.utilities.json.model.JsonArray;
import org.hl7.fhir.utilities.json.JsonUtilities; import org.hl7.fhir.utilities.json.model.JsonElement;
import org.hl7.fhir.utilities.json.model.JsonObject;
import org.hl7.fhir.utilities.json.model.JsonProperty;
import org.hl7.fhir.utilities.json.parser.JsonParser;
import org.hl7.fhir.utilities.npm.PackageGenerator.PackageType; import org.hl7.fhir.utilities.npm.PackageGenerator.PackageType;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
/** /**
* info and loader for a package * info and loader for a package
* *
@ -111,13 +109,13 @@ public class NpmPackage {
public PackageResourceInformation(String root, JsonObject fi) throws IOException { public PackageResourceInformation(String root, JsonObject fi) throws IOException {
super(); super();
id = JsonUtilities.str(fi, "id"); id = fi.asString("id");
resourceType = JsonUtilities.str(fi, "resourceType"); resourceType = fi.asString("resourceType");
url = JsonUtilities.str(fi, "url"); url = fi.asString("url");
version = JsonUtilities.str(fi, "version"); version = fi.asString("version");
filename = Utilities.path(root, JsonUtilities.str(fi, "filename")); filename = Utilities.path(root, fi.asString("filename"));
supplements = JsonUtilities.str(fi, "supplements"); supplements = fi.asString("supplements");
stype = JsonUtilities.str(fi, "type"); stype = fi.asString("type");
} }
public String getId() { public String getId() {
return id; return id;
@ -146,8 +144,8 @@ public class NpmPackage {
@Override @Override
public int compare(JsonObject o0, JsonObject o1) { public int compare(JsonObject o0, JsonObject o1) {
String v0 = JsonUtilities.str(o0, "version"); String v0 = o0.asString("version");
String v1 = JsonUtilities.str(o1, "version"); String v1 = o1.asString("version");
return v0.compareTo(v1); return v0.compareTo(v1);
} }
} }
@ -181,14 +179,13 @@ public class NpmPackage {
} }
public boolean readIndex(JsonObject index) { public boolean readIndex(JsonObject index) {
if (!index.has("index-version") || (index.get("index-version").getAsInt() != 1)) { if (!index.has("index-version") || (index.asInteger("index-version") != 1)) {
return false; return false;
} }
this.index = index; this.index = index;
for (JsonElement e : index.getAsJsonArray("files")) { for (JsonObject file : index.getJsonObjects("files")) {
JsonObject file = (JsonObject) e; String type = file.asString("resourceType");
String type = JsonUtilities.str(file, "resourceType"); String name = file.asString("filename");
String name = JsonUtilities.str(file, "filename");
if (!types.containsKey(type)) if (!types.containsKey(type))
types.put(type, new ArrayList<>()); types.put(type, new ArrayList<>());
types.get(type).add(name); types.get(type).add(name);
@ -301,7 +298,7 @@ public class NpmPackage {
} }
public void loadFiles(String path, File source, String... exemptions) throws FileNotFoundException, IOException { public void loadFiles(String path, File source, String... exemptions) throws FileNotFoundException, IOException {
this.npm = (JsonObject) new com.google.gson.JsonParser().parse(TextFile.fileToString(Utilities.path(path, "package", "package.json"))); this.npm = JsonParser.parseObject(TextFile.fileToString(Utilities.path(path, "package", "package.json")));
this.path = path; this.path = path;
File dir = new File(path); File dir = new File(path);
@ -318,7 +315,7 @@ public class NpmPackage {
File ij = new File(Utilities.path(f.getAbsolutePath(), ".index.json")); File ij = new File(Utilities.path(f.getAbsolutePath(), ".index.json"));
if (ij.exists()) { if (ij.exists()) {
try { try {
if (!folder.readIndex(JsonTrackingParser.parseJson(ij))) { if (!folder.readIndex(JsonParser.parseObject(ij))) {
indexFolder(folder.getName(), folder); indexFolder(folder.getName(), folder);
} }
} catch (Exception e) { } catch (Exception e) {
@ -353,7 +350,7 @@ public class NpmPackage {
File ij = new File(Utilities.path(f.getAbsolutePath(), ".index.json")); File ij = new File(Utilities.path(f.getAbsolutePath(), ".index.json"));
if (ij.exists()) { if (ij.exists()) {
try { try {
if (!folder.readIndex(JsonTrackingParser.parseJson(ij))) { if (!folder.readIndex(JsonParser.parseObject(ij))) {
indexFolder(folder.getName(), folder); indexFolder(folder.getName(), folder);
} }
} catch (Exception e) { } catch (Exception e) {
@ -374,7 +371,7 @@ public class NpmPackage {
if (!res.folders.get("package").hasFile("package.json") && defType != null) { if (!res.folders.get("package").hasFile("package.json") && defType != null) {
TextFile.stringToFile("{ \"type\" : \""+defType.getCode()+"\"}", Utilities.path(res.folders.get("package").folder.getAbsolutePath(), "package.json")); TextFile.stringToFile("{ \"type\" : \""+defType.getCode()+"\"}", Utilities.path(res.folders.get("package").folder.getAbsolutePath(), "package.json"));
} }
res.npm = (JsonObject) new com.google.gson.JsonParser().parse(new String(res.folders.get("package").fetchFile("package.json"))); res.npm = JsonParser.parseObject(new String(res.folders.get("package").fetchFile("package.json")));
return res; return res;
} }
@ -439,7 +436,7 @@ public class NpmPackage {
} }
} }
try { try {
npm = JsonTrackingParser.parseJson(folders.get("package").fetchFile("package.json")); npm = JsonParser.parseObject(folders.get("package").fetchFile("package.json"));
} catch (Exception e) { } catch (Exception e) {
throw new IOException("Error parsing "+(desc == null ? "" : desc+"#")+"package/package.json: "+e.getMessage(), e); throw new IOException("Error parsing "+(desc == null ? "" : desc+"#")+"package/package.json: "+e.getMessage(), e);
} }
@ -482,7 +479,7 @@ public class NpmPackage {
} }
String json = indexer.build(); String json = indexer.build();
try { try {
folder.readIndex(JsonTrackingParser.parseJson(json)); folder.readIndex(JsonParser.parseObject(json));
if (folder.folder != null) { if (folder.folder != null) {
TextFile.stringToFile(json, Utilities.path(folder.folder.getAbsolutePath(), ".index.json")); TextFile.stringToFile(json, Utilities.path(folder.folder.getAbsolutePath(), ".index.json"));
} }
@ -520,7 +517,7 @@ public class NpmPackage {
} }
zip.close(); zip.close();
try { try {
res.npm = JsonTrackingParser.parseJson(res.folders.get("package").fetchFile("package.json")); res.npm = JsonParser.parseObject(res.folders.get("package").fetchFile("package.json"));
} catch (Exception e) { } catch (Exception e) {
throw new IOException("Error parsing "+(desc == null ? "" : desc+"#")+"package/package.json: "+e.getMessage(), e); throw new IOException("Error parsing "+(desc == null ? "" : desc+"#")+"package/package.json: "+e.getMessage(), e);
} }
@ -561,9 +558,8 @@ public class NpmPackage {
List<PackageResourceInformation> res = new ArrayList<PackageResourceInformation>(); List<PackageResourceInformation> res = new ArrayList<PackageResourceInformation>();
for (NpmPackageFolder folder : folders.values()) { for (NpmPackageFolder folder : folders.values()) {
if (folder.index != null) { if (folder.index != null) {
for (JsonElement e : folder.index.getAsJsonArray("files")) { for (JsonObject fi : folder.index.getJsonObjects("files")) {
JsonObject fi = e.getAsJsonObject(); if (Utilities.existsInList(fi.asString("resourceType"), types)) {
if (Utilities.existsInList(JsonUtilities.str(fi, "resourceType"), types)) {
res.add(new PackageResourceInformation(folder.folder == null ? "@"+folder.getName() : folder.folder.getAbsolutePath(), fi)); res.add(new PackageResourceInformation(folder.folder == null ? "@"+folder.getName() : folder.folder.getAbsolutePath(), fi));
} }
} }
@ -634,21 +630,20 @@ public class NpmPackage {
public InputStream loadByCanonicalVersion(String folder, String canonical, String version) throws IOException { public InputStream loadByCanonicalVersion(String folder, String canonical, String version) throws IOException {
NpmPackageFolder f = folders.get(folder); NpmPackageFolder f = folders.get(folder);
List<JsonObject> matches = new ArrayList<>(); List<JsonObject> matches = new ArrayList<>();
for (JsonElement e : f.index.getAsJsonArray("files")) { for (JsonObject file : f.index.getJsonObjects("files")) {
JsonObject file = (JsonObject) e; if (canonical.equals(file.asString("url"))) {
if (canonical.equals(JsonUtilities.str(file, "url"))) { if (version != null && version.equals(file.asString("version"))) {
if (version != null && version.equals(JsonUtilities.str(file, "version"))) { return load("package", file.asString("filename"));
return load("package", JsonUtilities.str(file, "filename"));
} else if (version == null) { } else if (version == null) {
matches.add(file); matches.add(file);
} }
} }
if (matches.size() > 0) { if (matches.size() > 0) {
if (matches.size() == 1) { if (matches.size() == 1) {
return load("package", JsonUtilities.str(matches.get(0), "filename")); return load("package", matches.get(0).asString("filename"));
} else { } else {
Collections.sort(matches, new IndexVersionSorter()); Collections.sort(matches, new IndexVersionSorter());
return load("package", JsonUtilities.str(matches.get(matches.size()-1), "filename")); return load("package", matches.get(matches.size()-1).asString("filename"));
} }
} }
} }
@ -708,7 +703,7 @@ public class NpmPackage {
* @return * @return
*/ */
public String name() { public String name() {
return JsonUtilities.str(npm, "name"); return npm.asString("name");
} }
/** /**
@ -716,15 +711,15 @@ public class NpmPackage {
* @return * @return
*/ */
public String id() { public String id() {
return JsonUtilities.str(npm, "name"); return npm.asString("name");
} }
public String date() { public String date() {
return JsonUtilities.str(npm, "date"); return npm.asString("date");
} }
public String canonical() { public String canonical() {
return JsonUtilities.str(npm, "canonical"); return npm.asString("canonical");
} }
/** /**
@ -732,7 +727,7 @@ public class NpmPackage {
* @return * @return
*/ */
public String version() { public String version() {
return JsonUtilities.str(npm, "version"); return npm.asString("version");
} }
/** /**
@ -740,28 +735,28 @@ public class NpmPackage {
* @return * @return
*/ */
public String fhirVersion() { public String fhirVersion() {
if ("hl7.fhir.core".equals(JsonUtilities.str(npm, "name"))) if ("hl7.fhir.core".equals(npm.asString("name")))
return JsonUtilities.str(npm, "version"); return npm.asString("version");
else if (JsonUtilities.str(npm, "name").startsWith("hl7.fhir.r2.") || JsonUtilities.str(npm, "name").startsWith("hl7.fhir.r2b.") || JsonUtilities.str(npm, "name").startsWith("hl7.fhir.r3.") || else if (npm.asString("name").startsWith("hl7.fhir.r2.") || npm.asString("name").startsWith("hl7.fhir.r2b.") || npm.asString("name").startsWith("hl7.fhir.r3.") ||
JsonUtilities.str(npm, "name").startsWith("hl7.fhir.r4.") || JsonUtilities.str(npm, "name").startsWith("hl7.fhir.r4b.") || JsonUtilities.str(npm, "name").startsWith("hl7.fhir.r5.")) npm.asString("name").startsWith("hl7.fhir.r4.") || npm.asString("name").startsWith("hl7.fhir.r4b.") || npm.asString("name").startsWith("hl7.fhir.r5."))
return JsonUtilities.str(npm, "version"); return npm.asString("version");
else { else {
JsonObject dep = null; JsonObject dep = null;
if (npm.has("dependencies") && npm.get("dependencies").isJsonObject()) { if (npm.hasObject("dependencies")) {
dep = npm.getAsJsonObject("dependencies"); dep = npm.getJsonObject("dependencies");
if (dep != null) { if (dep != null) {
for (Entry<String, JsonElement> e : dep.entrySet()) { for (JsonProperty e : dep.getProperties()) {
if (Utilities.existsInList(e.getKey(), "hl7.fhir.r2.core", "hl7.fhir.r2b.core", "hl7.fhir.r3.core", "hl7.fhir.r4.core")) if (Utilities.existsInList(e.getName(), "hl7.fhir.r2.core", "hl7.fhir.r2b.core", "hl7.fhir.r3.core", "hl7.fhir.r4.core"))
return e.getValue().getAsString(); return e.getValue().asString();
if (Utilities.existsInList(e.getKey(), "hl7.fhir.core")) // while all packages are updated if (Utilities.existsInList(e.getName(), "hl7.fhir.core")) // while all packages are updated
return e.getValue().getAsString(); return e.getValue().asString();
} }
} }
} }
if (npm.has("fhirVersions")) { if (npm.hasArray("fhirVersions")) {
JsonElement e = npm.get("fhirVersions"); JsonArray e = npm.getJsonArray("fhirVersions");
if (e.isJsonArray() && e.getAsJsonArray().size() > 0) { if (e.size() > 0) {
return npm.getAsJsonArray("fhirVersions").get(0).getAsString(); return e.getItems().get(0).asString();
} }
} }
if (dep != null) { if (dep != null) {
@ -789,11 +784,11 @@ public class NpmPackage {
} }
public String type() { public String type() {
return JsonUtilities.str(npm, "type"); return npm.asString("type");
} }
public String description() { public String description() {
return JsonUtilities.str(npm, "description"); return npm.asString("description");
} }
public String getPath() { public String getPath() {
@ -803,32 +798,32 @@ public class NpmPackage {
public List<String> dependencies() { public List<String> dependencies() {
List<String> res = new ArrayList<>(); List<String> res = new ArrayList<>();
if (npm.has("dependencies")) { if (npm.has("dependencies")) {
for (Entry<String, JsonElement> e : npm.getAsJsonObject("dependencies").entrySet()) { for (JsonProperty e : npm.getJsonObject("dependencies").getProperties()) {
res.add(e.getKey()+"#"+e.getValue().getAsString()); res.add(e.getName()+"#"+e.getValue().asString());
} }
} }
return res; return res;
} }
public String homepage() { public String homepage() {
return JsonUtilities.str(npm, "homepage"); return npm.asString("homepage");
} }
public String url() { public String url() {
return JsonUtilities.str(npm, "url"); return npm.asString("url");
} }
public String title() { public String title() {
return JsonUtilities.str(npm, "title"); return npm.asString("title");
} }
public String toolsVersion() { public String toolsVersion() {
return JsonUtilities.str(npm, "tools-version"); return npm.asString("tools-version");
} }
public String license() { public String license() {
return JsonUtilities.str(npm, "license"); return npm.asString("license");
} }
// /** // /**
@ -841,20 +836,20 @@ public class NpmPackage {
// } // }
public String getWebLocation() { public String getWebLocation() {
if (npm.has("url") && npm.get("url").isJsonPrimitive()) { if (npm.hasPrimitive("url")) {
return PackageHacker.fixPackageUrl(npm.get("url").getAsString()); return PackageHacker.fixPackageUrl(npm.asString("url"));
} else { } else {
return JsonUtilities.str(npm, "canonical"); return npm.asString("canonical");
} }
} }
public InputStream loadResource(String type, String id) throws IOException { public InputStream loadResource(String type, String id) throws IOException {
NpmPackageFolder f = folders.get("package"); NpmPackageFolder f = folders.get("package");
JsonArray files = f.index.getAsJsonArray("files"); JsonArray files = f.index.getJsonArray("files");
for (JsonElement e : files) { for (JsonElement e : files.getItems()) {
JsonObject i = (JsonObject) e; JsonObject i = (JsonObject) e;
if (type.equals(JsonUtilities.str(i, "resourceType")) && id.equals(JsonUtilities.str(i, "id"))) { if (type.equals(i.asString("resourceType")) && id.equals(i.asString("id"))) {
return load("package", JsonUtilities.str(i, "filename")); return load("package", i.asString("filename"));
} }
} }
return null; return null;
@ -866,11 +861,11 @@ public class NpmPackage {
f = folders.get("package/example"); f = folders.get("package/example");
} }
if (f != null) { if (f != null) {
JsonArray files = f.index.getAsJsonArray("files"); JsonArray files = f.index.getJsonArray("files");
for (JsonElement e : files) { for (JsonElement e : files.getItems()) {
JsonObject i = (JsonObject) e; JsonObject i = (JsonObject) e;
if (type.equals(JsonUtilities.str(i, "resourceType")) && id.equals(JsonUtilities.str(i, "id"))) { if (type.equals(i.asString("resourceType")) && id.equals(i.asString("id"))) {
return load("example", JsonUtilities.str(i, "filename")); return load("example", i.asString("filename"));
} }
} }
} }
@ -909,7 +904,7 @@ public class NpmPackage {
byte[] cnt = indexer.build().getBytes(StandardCharsets.UTF_8); byte[] cnt = indexer.build().getBytes(StandardCharsets.UTF_8);
TextFile.bytesToFile(cnt, Utilities.path(dir.getAbsolutePath(), n, ".index.json")); TextFile.bytesToFile(cnt, Utilities.path(dir.getAbsolutePath(), n, ".index.json"));
} }
byte[] cnt = TextFile.stringToBytes(new GsonBuilder().setPrettyPrinting().create().toJson(npm), false); byte[] cnt = TextFile.stringToBytes(JsonParser.compose(npm, true), false);
TextFile.bytesToFile(cnt, Utilities.path(dir.getAbsolutePath(), "package", "package.json")); TextFile.bytesToFile(cnt, Utilities.path(dir.getAbsolutePath(), "package", "package.json"));
} }
@ -955,7 +950,7 @@ public class NpmPackage {
tar.write(cnt); tar.write(cnt);
tar.closeArchiveEntry(); tar.closeArchiveEntry();
} }
byte[] cnt = TextFile.stringToBytes(new GsonBuilder().setPrettyPrinting().create().toJson(npm), false); byte[] cnt = TextFile.stringToBytes(JsonParser.compose(npm, true), false);
TarArchiveEntry entry = new TarArchiveEntry("package/package.json"); TarArchiveEntry entry = new TarArchiveEntry("package/package.json");
entry.setSize(cnt.length); entry.setSize(cnt.length);
tar.putArchiveEntry(entry); tar.putArchiveEntry(entry);
@ -981,13 +976,13 @@ public class NpmPackage {
public String fhirVersionList() { public String fhirVersionList() {
if (npm.has("fhirVersions")) { if (npm.has("fhirVersions")) {
CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder(); CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder();
if (npm.get("fhirVersions").isJsonArray()) { if (npm.hasArray("fhirVersions")) {
for (JsonElement n : npm.getAsJsonArray("fhirVersions")) { for (String n : npm.getJsonArray("fhirVersions").asStrings()) {
b.append(n.getAsString()); b.append(n);
} }
} }
if (npm.get("fhirVersions").isJsonPrimitive()) { if (npm.hasPrimitive("fhirVersions")) {
b.append(npm.get("fhirVersions").getAsString()); b.append(npm.asString("fhirVersions"));
} }
return b.toString(); return b.toString();
} else } else
@ -997,8 +992,8 @@ public class NpmPackage {
public String dependencySummary() { public String dependencySummary() {
if (npm.has("dependencies")) { if (npm.has("dependencies")) {
CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder(); CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder();
for (Entry<String, JsonElement> e : npm.getAsJsonObject("dependencies").entrySet()) { for (JsonProperty e : npm.getJsonObject("dependencies").getProperties()) {
b.append(e.getKey()+"#"+e.getValue().getAsString()); b.append(e.getName()+"#"+e.getValue().asString());
} }
return b.toString(); return b.toString();
} else } else
@ -1080,7 +1075,7 @@ public class NpmPackage {
folder.types.get(type).add(name); folder.types.get(type).add(name);
if ("package".equals(folderName) && "package.json".equals(name)) { if ("package".equals(folderName) && "package.json".equals(name)) {
try { try {
npm = JsonTrackingParser.parseJson(cnt); npm = JsonParser.parseObject(cnt);
} catch (IOException e) { } catch (IOException e) {
} }
} }
@ -1118,11 +1113,11 @@ public class NpmPackage {
} }
public boolean isCore() { public boolean isCore() {
return Utilities.existsInList(JsonUtilities.str(npm, "type"), "fhir.core", "Core"); return Utilities.existsInList(npm.asString("type"), "fhir.core", "Core");
} }
public boolean isTx() { public boolean isTx() {
return JsonUtilities.str(npm, "name").startsWith("hl7.terminology"); return npm.asString("name").startsWith("hl7.terminology");
} }
public boolean hasCanonical(String url) { public boolean hasCanonical(String url) {
@ -1133,10 +1128,9 @@ public class NpmPackage {
String v = url.contains("|") ? url.substring(url.indexOf("|")+1) : null; String v = url.contains("|") ? url.substring(url.indexOf("|")+1) : null;
NpmPackageFolder folder = folders.get("package"); NpmPackageFolder folder = folders.get("package");
if (folder != null) { if (folder != null) {
for (JsonElement e : folder.index.getAsJsonArray("files")) { for (JsonObject o : folder.index.getJsonObjects("files")) {
JsonObject o = (JsonObject) e; if (u.equals(o.asString("url"))) {
if (u.equals(JsonUtilities.str(o, "url"))) { if (v == null || v.equals(o.asString("version"))) {
if (v == null || v.equals(JsonUtilities.str(o, "version"))) {
return true; return true;
} }
} }
@ -1154,7 +1148,7 @@ public class NpmPackage {
if (Utilities.existsInList(name(), "fhir.test.data.r2", "fhir.test.data.r3", "fhir.test.data.r4", "fhir.tx.support.r2", "fhir.tx.support.r3", "fhir.tx.support.r4", "us.nlm.vsac")) { if (Utilities.existsInList(name(), "fhir.test.data.r2", "fhir.test.data.r3", "fhir.test.data.r4", "fhir.tx.support.r2", "fhir.tx.support.r3", "fhir.tx.support.r4", "us.nlm.vsac")) {
return true; return true;
} }
if (JsonUtilities.bool(npm, "lazy-load")) { if (npm.asBoolean("lazy-load")) {
return true; return true;
} }
if (!hasFile("other", "spec.internals")) { if (!hasFile("other", "spec.internals")) {
@ -1164,7 +1158,7 @@ public class NpmPackage {
} }
public boolean isNotForPublication() { public boolean isNotForPublication() {
return JsonUtilities.bool(npm, "notForPublication"); return npm.asBoolean("notForPublication");
} }
public InputStream load(PackageResourceInformation p) throws FileNotFoundException { public InputStream load(PackageResourceInformation p) throws FileNotFoundException {

View File

@ -6,11 +6,9 @@ import java.io.IOException;
import org.hl7.fhir.exceptions.FHIRException; import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.utilities.TextFile; import org.hl7.fhir.utilities.TextFile;
import org.hl7.fhir.utilities.Utilities; import org.hl7.fhir.utilities.Utilities;
import org.hl7.fhir.utilities.json.JsonTrackingParser; import org.hl7.fhir.utilities.json.model.JsonArray;
import org.hl7.fhir.utilities.json.model.JsonObject;
import com.google.gson.GsonBuilder; import org.hl7.fhir.utilities.json.parser.JsonParser;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
/** /**
* This class builds the .index.json for a package * This class builds the .index.json for a package
@ -25,7 +23,7 @@ public class NpmPackageIndexBuilder {
public void start() { public void start() {
index = new JsonObject(); index = new JsonObject();
index.addProperty("index-version", 1); index.add("index-version", 1);
files = new JsonArray(); files = new JsonArray();
index.add("files", files); index.add("files", files);
} }
@ -33,30 +31,30 @@ public class NpmPackageIndexBuilder {
public boolean seeFile(String name, byte[] content) { public boolean seeFile(String name, byte[] content) {
if (name.endsWith(".json")) { if (name.endsWith(".json")) {
try { try {
JsonObject json = JsonTrackingParser.parseJson(content); JsonObject json = JsonParser.parseObject(content);
if (json.has("resourceType")) { if (json.has("resourceType")) {
// ok we treat it as a resource // ok we treat it as a resource
JsonObject fi = new JsonObject(); JsonObject fi = new JsonObject();
files.add(fi); files.add(fi);
fi.addProperty("filename", name); fi.add("filename", name);
fi.addProperty("resourceType", json.get("resourceType").getAsString()); fi.add("resourceType", json.asString("resourceType"));
if (json.has("id") && json.get("id").isJsonPrimitive()) { if (json.hasPrimitive("id")) {
fi.addProperty("id", json.get("id").getAsString()); fi.add("id", json.asString("id"));
} }
if (json.has("url") && json.get("url").isJsonPrimitive()) { if (json.hasPrimitive("url")) {
fi.addProperty("url", json.get("url").getAsString()); fi.add("url", json.asString("url"));
} }
if (json.has("version") && json.get("version").isJsonPrimitive()) { if (json.hasPrimitive("version")) {
fi.addProperty("version", json.get("version").getAsString()); fi.add("version", json.asString("version"));
} }
if (json.has("kind") && json.get("kind").isJsonPrimitive()) { if (json.hasPrimitive("kind")) {
fi.addProperty("kind", json.get("kind").getAsString()); fi.add("kind", json.asString("kind"));
} }
if (json.has("type") && json.get("type").isJsonPrimitive()) { if (json.hasPrimitive("type")) {
fi.addProperty("type", json.get("type").getAsString()); fi.add("type", json.asString("type"));
} }
if (json.has("supplements") && json.get("supplements").isJsonPrimitive()) { if (json.hasPrimitive("supplements")) {
fi.addProperty("supplements", json.get("supplements").getAsString()); fi.add("supplements", json.asString("supplements"));
} }
} }
} catch (Exception e) { } catch (Exception e) {
@ -70,7 +68,7 @@ public class NpmPackageIndexBuilder {
} }
public String build() { public String build() {
String res = new GsonBuilder().setPrettyPrinting().create().toJson(index); String res = JsonParser.compose(index, true);
index = null; index = null;
files = null; files = null;
return res; return res;

View File

@ -17,12 +17,10 @@ import org.hl7.fhir.utilities.SimpleHTTPClient.HTTPResult;
import org.hl7.fhir.utilities.TextFile; import org.hl7.fhir.utilities.TextFile;
import org.hl7.fhir.utilities.Utilities; import org.hl7.fhir.utilities.Utilities;
import org.hl7.fhir.utilities.VersionUtilities; import org.hl7.fhir.utilities.VersionUtilities;
import org.hl7.fhir.utilities.json.JsonTrackingParser; import org.hl7.fhir.utilities.json.model.JsonArray;
import org.hl7.fhir.utilities.json.JsonUtilities; import org.hl7.fhir.utilities.json.model.JsonObject;
import org.hl7.fhir.utilities.json.model.JsonProperty;
import com.google.gson.JsonArray; import org.hl7.fhir.utilities.json.parser.JsonParser;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
public class PackageClient { public class PackageClient {
@ -81,21 +79,21 @@ public class PackageClient {
JsonObject json; JsonObject json;
try { try {
json = fetchJson(Utilities.pathURL(address, id)); json = fetchJson(Utilities.pathURL(address, id));
JsonObject versions = json.getAsJsonObject("versions"); JsonObject versions = json.getJsonObject("versions");
boolean hasDates = true; boolean hasDates = true;
if (versions != null) { if (versions != null) {
for (String v : versions.keySet()) { for (JsonProperty v : versions.getProperties()) {
JsonObject obj = versions.getAsJsonObject(v); JsonObject obj = versions.getJsonObject(v.getName());
Instant d = obj.has("date") ? JsonUtilities.parseDate(obj, "date") : null; Instant d = obj.hasString("date") ? obj.asDate("date") : null;
if (d == null) { if (d == null) {
hasDates = false; hasDates = false;
} }
res.add(new PackageInfo(JsonUtilities.str(obj, "Name", "name"), res.add(new PackageInfo(obj.asString("Name", "name"),
JsonUtilities.str(obj, "Version", "version"), obj.asString("Version", "version"),
JsonUtilities.str(obj, "FhirVersion", "fhirVersion"), obj.asString("FhirVersion", "fhirVersion"),
JsonUtilities.str(obj, "Description", "description"), obj.asString("Description", "description"),
JsonUtilities.str(obj, "url"), obj.asString("url"),
JsonUtilities.str(obj, "canonical"), obj.asString("canonical"),
address, d)); address, d));
} }
} }
@ -127,18 +125,17 @@ public class PackageClient {
try { try {
JsonArray json = fetchJsonArray(Utilities.pathURL(address, "catalog?")+params.toString()); JsonArray json = fetchJsonArray(Utilities.pathURL(address, "catalog?")+params.toString());
boolean hasDates = true; boolean hasDates = true;
for (JsonElement e : json) { for (JsonObject obj : json.asJsonObjects()) {
JsonObject obj = (JsonObject) e; Instant d = obj.has("date") ? obj.asDate("date") : null;
Instant d = obj.has("date") ? JsonUtilities.parseDate(obj, "date") : null;
if (d == null) { if (d == null) {
hasDates = false; hasDates = false;
} }
res.add(new PackageInfo(JsonUtilities.str(obj, "Name", "name"), res.add(new PackageInfo(obj.asString("Name", "name"),
JsonUtilities.str(obj, "Version", "version"), obj.asString("Version", "version"),
JsonUtilities.str(obj, "FhirVersion", "fhirVersion"), obj.asString("FhirVersion", "fhirVersion"),
JsonUtilities.str(obj, "Description", "description"), obj.asString("Description", "description"),
JsonUtilities.str(obj, "url"), obj.asString("url"),
JsonUtilities.str(obj, "canonical"), obj.asString("canonical"),
address, d)); address, d));
} }
if (hasDates) { if (hasDates) {
@ -165,13 +162,13 @@ public class PackageClient {
private JsonObject fetchJson(String source) throws IOException { private JsonObject fetchJson(String source) throws IOException {
String src = TextFile.streamToString(fetchUrl(source, "application/json")); String src = TextFile.streamToString(fetchUrl(source, "application/json"));
//System.out.println(src); //System.out.println(src);
return (JsonObject) new com.google.gson.JsonParser().parse(src); return JsonParser.parseObject(src);
} }
private JsonArray fetchJsonArray(String source) throws IOException { private JsonArray fetchJsonArray(String source) throws IOException {
String src = TextFile.streamToString(fetchUrl(source, "application/json")); String src = TextFile.streamToString(fetchUrl(source, "application/json"));
//System.out.println(src); //System.out.println(src);
return (JsonArray) new com.google.gson.JsonParser().parse(src); return (JsonArray) JsonParser.parse(src);
} }
public String url(String id, String v) { public String url(String id, String v) {
@ -209,11 +206,11 @@ public class PackageClient {
} }
protected PackageInfo getPackageInfoFromJSON(JsonObject o, String name, String canonical, String fhirVersion) { protected PackageInfo getPackageInfoFromJSON(JsonObject o, String name, String canonical, String fhirVersion) {
String id = JsonUtilities.str(o, "npm-name"); String id = o.asString("npm-name");
String pname = JsonUtilities.str(o, "name"); String pname = o.asString("name");
String pcanonical = JsonUtilities.str(o, "canonical"); String pcanonical = o.asString("canonical");
String description = JsonUtilities.str(o, "description"); String description = o.asString("description");
Instant d = o.has("date") ? JsonUtilities.parseDate(o, "date") : null; Instant d = o.has("date") ? o.asDate("date") : null;
boolean ok = true; boolean ok = true;
if (ok && !Utilities.noString(name)) { if (ok && !Utilities.noString(name)) {
ok = (pname != null && pname.contains(name)) || (description != null && description.contains(name)) || (id != null && id.contains(name)); ok = (pname != null && pname.contains(name)) || (description != null && description.contains(name)) || (id != null && id.contains(name));
@ -227,15 +224,15 @@ public class PackageClient {
if (ok) { if (ok) {
// if we can find something... // if we can find something...
for (JsonObject e : JsonUtilities.objects(o, "editions")) { for (JsonObject e : o.getJsonObjects("editions")) {
if (fhirVersion == null || fhirVersion.equals(JsonUtilities.str(e, "fhir-version"))) { if (fhirVersion == null || fhirVersion.equals(e.asString("fhir-version"))) {
String v = JsonUtilities.str(e, "ig-version"); String v = e.asString("ig-version");
if (version == null || VersionUtilities.isThisOrLater(version, v)) { if (version == null || VersionUtilities.isThisOrLater(version, v)) {
version = v; version = v;
fVersion = e.getAsJsonArray("fhir-version").get(0).getAsString(); fVersion = e.getJsonArray("fhir-version").get(0).asString();
url = JsonUtilities.str(e, "url"); url = e.asString("url");
String npmPackage = JsonUtilities.str(e, "package"); String npmPackage = e.asString("package");
if (npmPackage != null && id == null) { if (npmPackage != null && id == null) {
id = npmPackage.substring(0, npmPackage.indexOf("#")); id = npmPackage.substring(0, npmPackage.indexOf("#"));
} }
@ -248,8 +245,8 @@ public class PackageClient {
public List<PackageInfo> listFromRegistry(String name, String canonical, String fhirVersion) throws IOException { public List<PackageInfo> listFromRegistry(String name, String canonical, String fhirVersion) throws IOException {
List<PackageInfo> result = new ArrayList<>(); List<PackageInfo> result = new ArrayList<>();
JsonObject packages = JsonTrackingParser.fetchJson("https://raw.githubusercontent.com/FHIR/ig-registry/master/fhir-ig-list.json?nocache=" + System.currentTimeMillis()); JsonObject packages = JsonParser.parseObjectFromUrl("https://raw.githubusercontent.com/FHIR/ig-registry/master/fhir-ig-list.json?nocache=" + System.currentTimeMillis());
for (JsonObject o : JsonUtilities.objects(packages, "guides")) { for (JsonObject o : packages.getJsonObjects("guides")) {
if (o.has("canonical")) { if (o.has("canonical")) {
final PackageInfo packageInfo = getPackageInfoFromJSON(o, name, canonical, fhirVersion); final PackageInfo packageInfo = getPackageInfoFromJSON(o, name, canonical, fhirVersion);
if (packageInfo.getVersion() != null) { if (packageInfo.getVersion() != null) {
@ -265,9 +262,8 @@ public class PackageClient {
params.append("dependency="+id.replace("#", "|")); params.append("dependency="+id.replace("#", "|"));
try { try {
JsonArray json = fetchJsonArray(Utilities.pathURL(address, "catalog?")+params.toString()); JsonArray json = fetchJsonArray(Utilities.pathURL(address, "catalog?")+params.toString());
for (JsonElement e : json) { for (JsonObject obj : json.asJsonObjects()) {
JsonObject obj = (JsonObject) e; list.add(obj.asString("Name", "name"));
list.add(JsonUtilities.str(obj, "Name", "name"));
} }
} catch (IOException e1) { } catch (IOException e1) {
} }

View File

@ -39,14 +39,9 @@ import java.util.List;
import org.hl7.fhir.utilities.TextFile; import org.hl7.fhir.utilities.TextFile;
import org.hl7.fhir.utilities.Utilities; import org.hl7.fhir.utilities.Utilities;
import org.hl7.fhir.utilities.json.model.JsonArray;
import com.google.gson.Gson; import org.hl7.fhir.utilities.json.model.JsonObject;
import com.google.gson.GsonBuilder; import org.hl7.fhir.utilities.json.parser.JsonParser;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSyntaxException;
public class PackageGenerator { public class PackageGenerator {
@ -94,11 +89,10 @@ public class PackageGenerator {
object = new JsonObject(); object = new JsonObject();
} }
public PackageGenerator(OutputStream stream, InputStream template) throws JsonSyntaxException, IOException { public PackageGenerator(OutputStream stream, InputStream template) throws IOException {
super(); super();
this.stream = stream; this.stream = stream;
JsonParser parser = new com.google.gson.JsonParser(); object = JsonParser.parseObject(TextFile.streamToString(template));
object = parser.parse(TextFile.streamToString(template)).getAsJsonObject();
} }
@ -107,8 +101,7 @@ public class PackageGenerator {
} }
public void commit() throws IOException { public void commit() throws IOException {
Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = JsonParser.compose(object, true);
String json = gson.toJson(object);
OutputStreamWriter sw = new OutputStreamWriter(stream, "UTF-8"); OutputStreamWriter sw = new OutputStreamWriter(stream, "UTF-8");
sw.write('\ufeff'); // Unicode BOM, translates to UTF-8 with the configured outputstreamwriter sw.write('\ufeff'); // Unicode BOM, translates to UTF-8 with the configured outputstreamwriter
sw.write(json); sw.write(json);
@ -118,17 +111,17 @@ public class PackageGenerator {
public PackageGenerator name(String value) { public PackageGenerator name(String value) {
// NOTE: I removed a prefix of "@fhir/" here. What was this for? -JA // NOTE: I removed a prefix of "@fhir/" here. What was this for? -JA
object.addProperty("name", value); object.add("name", value);
return this; return this;
} }
public PackageGenerator version(String value) { public PackageGenerator version(String value) {
object.addProperty("version", value); object.add("version", value);
return this; return this;
} }
public PackageGenerator toolsVersion(int value) { public PackageGenerator toolsVersion(int value) {
object.addProperty("tools-version", value); object.add("tools-version", value);
return this; return this;
} }
@ -142,44 +135,44 @@ public class PackageGenerator {
} }
public PackageGenerator description(String value) { public PackageGenerator description(String value) {
object.addProperty("description", value); object.add("description", value);
return this; return this;
} }
public PackageGenerator license(String value) { public PackageGenerator license(String value) {
object.addProperty("license", value); object.add("license", value);
return this; return this;
} }
public PackageGenerator homepage(String value) { public PackageGenerator homepage(String value) {
object.addProperty("homepage", value); object.add("homepage", value);
return this; return this;
} }
public PackageGenerator bugs(String value) { public PackageGenerator bugs(String value) {
object.addProperty("bugs", value); object.add("bugs", value);
return this; return this;
} }
public PackageGenerator author(String name, String email, String url) { public PackageGenerator author(String name, String email, String url) {
JsonObject person = new JsonObject(); JsonObject person = new JsonObject();
person.addProperty("name", name); person.add("name", name);
if (!Utilities.noString(email)) if (!Utilities.noString(email))
person.addProperty("email", email); person.add("email", email);
if (!Utilities.noString(url)) if (!Utilities.noString(url))
person.addProperty("url", url); person.add("url", url);
object.add("author", person); object.add("author", person);
return this; return this;
} }
public PackageGenerator contributor(String name, String email, String url) { public PackageGenerator contributor(String name, String email, String url) {
JsonObject person = new JsonObject(); JsonObject person = new JsonObject();
person.addProperty("name", name); person.add("name", name);
if (!Utilities.noString(email)) if (!Utilities.noString(email))
person.addProperty("email", email); person.add("email", email);
if (!Utilities.noString(url)) if (!Utilities.noString(url))
person.addProperty("url", url); person.add("url", url);
JsonArray c = object.getAsJsonArray("contributors"); JsonArray c = object.getJsonArray("contributors");
if (c == null) { if (c == null) {
c = new JsonArray(); c = new JsonArray();
object.add("contributors", c); object.add("contributors", c);
@ -189,27 +182,23 @@ public class PackageGenerator {
} }
public PackageGenerator dependency(String name, String version) { public PackageGenerator dependency(String name, String version) {
JsonObject dep = object.getAsJsonObject("dependencies"); JsonObject dep = object.getJsonObject("dependencies");
if (dep == null) { if (dep == null) {
dep = new JsonObject(); dep = new JsonObject();
object.add("dependencies", dep); object.add("dependencies", dep);
} }
dep.addProperty(name, version); dep.add(name, version);
return this; return this;
} }
public PackageGenerator file(String name) { public PackageGenerator file(String name) {
JsonArray files = object.getAsJsonArray("files"); JsonArray files = object.forceArray("files");
if (files == null) { files.add(name);
files = new JsonArray();
object.add("files", files);
}
files.add(new JsonPrimitive(name));
return this; return this;
} }
public PackageGenerator kind(PackageType kind) { public PackageGenerator kind(PackageType kind) {
object.addProperty("type", kind.getCode()); object.add("type", kind.getCode());
return this; return this;
} }

View File

@ -12,10 +12,11 @@ import java.util.Map;
import org.hl7.fhir.utilities.TextFile; import org.hl7.fhir.utilities.TextFile;
import org.hl7.fhir.utilities.Utilities; import org.hl7.fhir.utilities.Utilities;
import org.hl7.fhir.utilities.json.model.JsonArray;
import org.hl7.fhir.utilities.json.model.JsonObject;
import org.hl7.fhir.utilities.json.parser.JsonParser;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
/** /**
* intenral use only - set the file name to edit in main(), and fill out the edit routine * intenral use only - set the file name to edit in main(), and fill out the edit routine
@ -74,14 +75,14 @@ public class PackageHacker {
} }
private String nice(JsonObject json) { private String nice(JsonObject json) {
return new GsonBuilder().setPrettyPrinting().create().toJson(json); return JsonParser.compose(json, true);
} }
private void change(JsonObject npm) throws FileNotFoundException, IOException { private void change(JsonObject npm) throws FileNotFoundException, IOException {
// fixVersions(npm); // fixVersions(npm);
// npm.remove("notForPublication"); // npm.remove("notForPublication");
npm.remove("url"); npm.remove("url");
npm.addProperty("url", "https://hl7chile.cl/fhir/ig/CoreCL/1.7.0"); npm.add("url", "https://hl7chile.cl/fhir/ig/CoreCL/1.7.0");
// npm.remove("name"); // npm.remove("name");
// npm.addProperty("name", "hl7.fhir.uv.smart-app-launch"); // npm.addProperty("name", "hl7.fhir.uv.smart-app-launch");
// npm.remove("canonical"); // npm.remove("canonical");
@ -128,7 +129,7 @@ public class PackageHacker {
private void setProperty(JsonObject npm, String name, String value) { private void setProperty(JsonObject npm, String name, String value) {
npm.remove("homepage"); npm.remove("homepage");
npm.addProperty("homepage", "http://hl7.org/fhir"); npm.add("homepage", "http://hl7.org/fhir");
} }
private void fixNames(Map<String, byte[]> content) { private void fixNames(Map<String, byte[]> content) {

View File

@ -9,10 +9,9 @@ import java.util.Set;
import org.hl7.fhir.utilities.TextFile; import org.hl7.fhir.utilities.TextFile;
import org.hl7.fhir.utilities.Utilities; import org.hl7.fhir.utilities.Utilities;
import org.hl7.fhir.utilities.json.JsonTrackingParser; import org.hl7.fhir.utilities.json.model.JsonObject;
import org.hl7.fhir.utilities.json.JsonUtilities; import org.hl7.fhir.utilities.json.parser.JsonParser;
import com.google.gson.JsonObject;
public class PackageScanner { public class PackageScanner {
@ -63,7 +62,7 @@ public class PackageScanner {
} catch (Exception e) { } catch (Exception e) {
fv = "--"; fv = "--";
} }
output.add(pck.name()+"\t"+pck.version()+"\t"+pck.canonical()+"\t"+fv+'\t'+pck.fhirVersionList()+'\t'+JsonUtilities.str(json, "kind")+'\t'+JsonUtilities.str(json, "type")+'\t'+JsonTrackingParser.writeDense(json)); } catch (Exception e) { output.add(pck.name()+"\t"+pck.version()+"\t"+pck.canonical()+"\t"+fv+'\t'+pck.fhirVersionList()+'\t'+json.asString("kind")+'\t'+json.asString("type")+'\t'+JsonParser.compose(json)); } catch (Exception e) {
System.out.println("Error acessing "+pi.getId()+"#"+piv.getVersion()+": "+e.getMessage()); System.out.println("Error acessing "+pi.getId()+"#"+piv.getVersion()+": "+e.getMessage());
e.printStackTrace(); e.printStackTrace();
} }

View File

@ -1,13 +1,13 @@
package org.hl7.fhir.utilities.npm; package org.hl7.fhir.utilities.npm;
import java.io.File; import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import org.hl7.fhir.utilities.Utilities; import org.hl7.fhir.utilities.Utilities;
import org.hl7.fhir.utilities.json.JsonTrackingParser; import org.hl7.fhir.utilities.json.model.JsonObject;
import org.hl7.fhir.utilities.json.JsonUtilities; import org.hl7.fhir.utilities.json.parser.JsonParser;
import com.google.gson.JsonObject;
public class ResourceRenamer { public class ResourceRenamer {
@ -24,13 +24,13 @@ public class ResourceRenamer {
} }
private void unbundle(File f) throws IOException { private void unbundle(File f) throws IOException {
JsonObject j = JsonTrackingParser.parseJson(f); JsonObject j = JsonParser.parseObject(f);
for (JsonObject e : JsonUtilities.objects(j, "entry")) { for (JsonObject e : j.getJsonObjects("entry")) {
JsonObject r = e.getAsJsonObject("resource"); JsonObject r = e.getJsonObject("resource");
String rt = r.get("resourceType").getAsString(); String rt = r.asString("resourceType");
String id = r.get("id").getAsString(); String id = r.asString("id");
String nn = Utilities.path(Utilities.getDirectoryForFile(f.getAbsolutePath()), rt+"-"+id+".json"); String nn = Utilities.path(Utilities.getDirectoryForFile(f.getAbsolutePath()), rt+"-"+id+".json");
JsonTrackingParser.write(r, new File(nn), true); JsonParser.compose(r, new FileOutputStream(nn), true);
} }
} }
@ -39,9 +39,9 @@ public class ResourceRenamer {
for (File f : dir.listFiles()) { for (File f : dir.listFiles()) {
if (f.getName().endsWith(".json")) { if (f.getName().endsWith(".json")) {
try { try {
JsonObject j = JsonTrackingParser.parseJson(f); JsonObject j = JsonParser.parseObject(f);
String rt = j.get("resourceType").getAsString(); String rt = j.asString("resourceType");
String id = j.get("id").getAsString(); String id = j.asString("id");
String nn = Utilities.path(Utilities.getDirectoryForFile(f.getAbsolutePath()), rt+"-"+id+".json"); String nn = Utilities.path(Utilities.getDirectoryForFile(f.getAbsolutePath()), rt+"-"+id+".json");
File nf = new File(nn); File nf = new File(nn);
if (!nn.equals(f.getAbsolutePath())) { if (!nn.equals(f.getAbsolutePath())) {

View File

@ -1,6 +1,12 @@
package org.hl7.fhir.utilities; package org.hl7.fhir.utilities;
import ca.uhn.fhir.model.api.TemporalPrecisionEnum; import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.stream.Stream;
import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Disabled;
@ -8,12 +14,7 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.MethodSource;
import java.util.Date; import ca.uhn.fhir.model.api.TemporalPrecisionEnum;
import java.util.Locale;
import java.util.TimeZone;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class DateTimeUtilTests { public class DateTimeUtilTests {

View File

@ -1,18 +1,19 @@
package org.hl7.fhir.utilities; package org.hl7.fhir.utilities;
import org.junit.jupiter.params.ParameterizedTest; import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException; import java.io.IOException;
import java.time.Duration; import java.time.Duration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.stream.Stream; import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals; import javax.xml.parsers.ParserConfigurationException;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.xml.sax.SAXException;
public class DurationUtilTest { public class DurationUtilTest {

View File

@ -1,6 +1,8 @@
package org.hl7.fhir.utilities; package org.hl7.fhir.utilities;
import org.junit.jupiter.api.Test; import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
@ -8,9 +10,7 @@ import java.io.PrintStream;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import static org.hamcrest.CoreMatchers.containsString; import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
public class FileFormatTest { public class FileFormatTest {
@Test @Test

View File

@ -1,11 +1,10 @@
package org.hl7.fhir.utilities; package org.hl7.fhir.utilities;
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test;
public class SimpleHTTPClientTest { public class SimpleHTTPClientTest {
@Test @Test

View File

@ -1,9 +1,6 @@
package org.hl7.fhir.utilities; package org.hl7.fhir.utilities;
import org.apache.commons.lang3.SystemUtils; import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@ -11,7 +8,10 @@ import java.nio.file.Paths;
import java.text.MessageFormat; import java.text.MessageFormat;
import java.util.Random; import java.util.Random;
import static org.junit.jupiter.api.Assertions.*; import org.apache.commons.lang3.SystemUtils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class UtilitiesTest { class UtilitiesTest {

View File

@ -1,8 +1,9 @@
package org.hl7.fhir.utilities; package org.hl7.fhir.utilities;
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test;
public class VersionUtilitiesTest { public class VersionUtilitiesTest {

View File

@ -1,10 +1,8 @@
package org.hl7.fhir.utilities.i18n; package org.hl7.fhir.utilities.i18n;
import com.ibm.icu.text.PluralRules; import static org.hamcrest.CoreMatchers.containsString;
import org.junit.jupiter.api.Assertions; import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.jupiter.api.Disabled; import static org.junit.jupiter.api.Assertions.assertFalse;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
@ -12,12 +10,13 @@ import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.text.MessageFormat; import java.text.MessageFormat;
import java.util.*; import java.util.Arrays;
import java.util.Locale;
import java.util.ResourceBundle;
import static org.hamcrest.CoreMatchers.containsString; import org.junit.jupiter.api.Assertions;
import static org.hamcrest.MatcherAssert.assertThat; import org.junit.jupiter.api.DisplayName;
import static org.junit.jupiter.api.Assertions.assertFalse; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
class I18nBaseTest { class I18nBaseTest {

View File

@ -1,14 +1,15 @@
package org.hl7.fhir.utilities.i18n; package org.hl7.fhir.utilities.i18n;
import com.ibm.icu.text.PluralRules; import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashSet; import java.util.HashSet;
import java.util.Locale; import java.util.Locale;
import java.util.Set; import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test;
import com.ibm.icu.text.PluralRules;
public class ICU4JTests { public class ICU4JTests {

View File

@ -26,7 +26,7 @@ public class JsonParserTests {
public void testComments2() throws IOException, JsonException { public void testComments2() throws IOException, JsonException {
JsonObject obj = JsonParser.parseObject("{\n // some comment \n \"n1\" : \"v1\"\n}\n", true); JsonObject obj = JsonParser.parseObject("{\n // some comment \n \"n1\" : \"v1\"\n}\n", true);
Assertions.assertEquals(0, obj.getComments().size()); Assertions.assertEquals(0, obj.getComments().size());
JsonString c = obj.getString("n1"); JsonString c = obj.getJsonString("n1");
Assertions.assertEquals(1, c.getComments().size()); Assertions.assertEquals(1, c.getComments().size());
Assertions.assertEquals("some comment", c.getComments().get(0)); Assertions.assertEquals("some comment", c.getComments().get(0));
Assertions.assertEquals("{\"n1\":\"v1\"}", JsonParser.compose(obj, false)); Assertions.assertEquals("{\"n1\":\"v1\"}", JsonParser.compose(obj, false));
@ -38,7 +38,7 @@ public class JsonParserTests {
JsonObject obj = JsonParser.parseObject("// some comment\n{\n \"n1\" : \"v1\"\n}\n", true); JsonObject obj = JsonParser.parseObject("// some comment\n{\n \"n1\" : \"v1\"\n}\n", true);
Assertions.assertEquals(1, obj.getComments().size()); Assertions.assertEquals(1, obj.getComments().size());
Assertions.assertEquals("some comment", obj.getComments().get(0)); Assertions.assertEquals("some comment", obj.getComments().get(0));
JsonString c = obj.getString("n1"); JsonString c = obj.getJsonString("n1");
Assertions.assertEquals(0, c.getComments().size()); Assertions.assertEquals(0, c.getComments().size());
Assertions.assertEquals("{\"n1\":\"v1\"}", JsonParser.compose(obj, false)); Assertions.assertEquals("{\"n1\":\"v1\"}", JsonParser.compose(obj, false));
Assertions.assertEquals("// some comment\n{\n \"n1\" : \"v1\"\n}\n", JsonParser.compose(obj, true)); Assertions.assertEquals("// some comment\n{\n \"n1\" : \"v1\"\n}\n", JsonParser.compose(obj, true));

View File

@ -1,20 +1,16 @@
package org.hl7.fhir.utilities.npm; package org.hl7.fhir.utilities.npm;
import com.google.gson.Gson;
import com.google.gson.JsonObject; import static org.junit.jupiter.api.Assertions.assertEquals;
import java.net.URISyntaxException;
import org.hl7.fhir.utilities.json.model.JsonObject;
import org.hl7.fhir.utilities.json.parser.JsonParser;
import org.hl7.fhir.utilities.tests.ResourceLoaderTests; import org.hl7.fhir.utilities.tests.ResourceLoaderTests;
import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class PackageClientTest implements ResourceLoaderTests { public class PackageClientTest implements ResourceLoaderTests {
PackageClient packageClient = new PackageClient(PackageClient.PRIMARY_SERVER); PackageClient packageClient = new PackageClient(PackageClient.PRIMARY_SERVER);
@ -32,7 +28,7 @@ public class PackageClientTest implements ResourceLoaderTests {
@Test @Test
@DisplayName("test getting package from JSON works") @DisplayName("test getting package from JSON works")
public void getPackageInfoFromJSONTest() throws java.io.IOException, URISyntaxException { public void getPackageInfoFromJSONTest() throws java.io.IOException, URISyntaxException {
final JsonObject jsonObject = new Gson().fromJson(new InputStreamReader(getResourceAsInputStream("npm","PackageClient-baseTestCase.json")), JsonObject.class); final JsonObject jsonObject = JsonParser.parseObject(getResourceAsInputStream("npm","PackageClient-baseTestCase.json"));
final PackageInfo packageInfo = packageClient.getPackageInfoFromJSON(jsonObject, null, null, null); final PackageInfo packageInfo = packageClient.getPackageInfoFromJSON(jsonObject, null, null, null);
assertExpectedFields(packageInfo); assertExpectedFields(packageInfo);
@ -41,7 +37,7 @@ public class PackageClientTest implements ResourceLoaderTests {
@Test @Test
@DisplayName("test getting package from JSON works") @DisplayName("test getting package from JSON works")
public void getPackageInfoWithIdFromJSONTest() throws java.io.IOException { public void getPackageInfoWithIdFromJSONTest() throws java.io.IOException {
final JsonObject jsonObject = new Gson().fromJson(new InputStreamReader(getResourceAsInputStream("npm", "PackageClient-testCaseWithId.json")), JsonObject.class); final JsonObject jsonObject = JsonParser.parseObject(getResourceAsInputStream("npm", "PackageClient-testCaseWithId.json"));
final PackageInfo packageInfo = packageClient.getPackageInfoFromJSON(jsonObject, null, null, null); final PackageInfo packageInfo = packageClient.getPackageInfoFromJSON(jsonObject, null, null, null);
assertExpectedFields(packageInfo); assertExpectedFields(packageInfo);

View File

@ -1,14 +1,14 @@
package org.hl7.fhir.utilities.tests; package org.hl7.fhir.utilities.tests;
import java.io.IOException;
import java.util.List;
import org.hl7.fhir.utilities.npm.CachingPackageClient; import org.hl7.fhir.utilities.npm.CachingPackageClient;
import org.hl7.fhir.utilities.npm.CommonPackages; import org.hl7.fhir.utilities.npm.CommonPackages;
import org.hl7.fhir.utilities.npm.PackageInfo; import org.hl7.fhir.utilities.npm.PackageInfo;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.List;
public class CachingPackageClientTests { public class CachingPackageClientTests {
private static final String SERVER1 = "http://packages.fhir.org"; private static final String SERVER1 = "http://packages.fhir.org";

View File

@ -1,5 +1,9 @@
package org.hl7.fhir.utilities.tests; package org.hl7.fhir.utilities.tests;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.hl7.fhir.utilities.Utilities; import org.hl7.fhir.utilities.Utilities;
import org.hl7.fhir.utilities.npm.CommonPackages; import org.hl7.fhir.utilities.npm.CommonPackages;
import org.hl7.fhir.utilities.npm.FilesystemPackageCacheManager; import org.hl7.fhir.utilities.npm.FilesystemPackageCacheManager;
@ -8,10 +12,6 @@ import org.hl7.fhir.utilities.npm.ToolsVersion;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
import java.util.List;
public class PackageCacheTests { public class PackageCacheTests {
@Test @Test

View File

@ -1,17 +1,12 @@
package org.hl7.fhir.utilities.tests; package org.hl7.fhir.utilities.tests;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerException;
import org.apache.commons.io.IOUtils;
import org.hl7.fhir.exceptions.FHIRException; import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.utilities.xls.XLSXmlNormaliser; import org.hl7.fhir.utilities.xls.XLSXmlNormaliser;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;

View File

@ -1,5 +1,9 @@
package org.hl7.fhir.utilities.tests; package org.hl7.fhir.utilities.tests;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import org.hl7.fhir.exceptions.FHIRException; import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.exceptions.FHIRFormatError; import org.hl7.fhir.exceptions.FHIRFormatError;
import org.hl7.fhir.utilities.xhtml.XhtmlNode; import org.hl7.fhir.utilities.xhtml.XhtmlNode;
@ -9,10 +13,6 @@ import org.junit.jupiter.api.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class XhtmlNodeTest { public class XhtmlNodeTest {
private static final Logger ourLog = LoggerFactory.getLogger(XhtmlNodeTest.class); private static final Logger ourLog = LoggerFactory.getLogger(XhtmlNodeTest.class);

View File

@ -1,13 +1,13 @@
package org.hl7.fhir.utilities.tests.execution; package org.hl7.fhir.utilities.tests.execution;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Arrays;
import org.hl7.fhir.utilities.tests.execution.junit4.JUnit4TestExecutor; import org.hl7.fhir.utilities.tests.execution.junit4.JUnit4TestExecutor;
import org.hl7.fhir.utilities.tests.execution.junit5.JUnit5ModuleTestExecutor; import org.hl7.fhir.utilities.tests.execution.junit5.JUnit5ModuleTestExecutor;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ModuleTestExecutorTests { public class ModuleTestExecutorTests {
@Test @Test