001package org.hl7.fhir.utilities.json.model;
002
003import java.text.ParseException;
004import java.text.SimpleDateFormat;
005import java.time.Instant;
006import java.time.OffsetDateTime;
007import java.util.ArrayList;
008import java.util.Date;
009import java.util.HashMap;
010import java.util.HashSet;
011import java.util.List;
012import java.util.Map;
013import java.util.Set;
014
015import org.hl7.fhir.utilities.CommaSeparatedStringBuilder;
016import org.hl7.fhir.utilities.Utilities;
017import org.hl7.fhir.utilities.json.JsonException;
018
019
020public class JsonObject extends JsonElement {
021  
022  private List<JsonProperty> properties = new ArrayList<>();
023  private Map<String, JsonProperty> propMap = new HashMap<>();
024  private boolean extraComma; // json5 support
025  
026  public JsonElementType type() {
027    return JsonElementType.OBJECT;
028  }
029
030  public JsonObject add(String name, JsonElement value) throws JsonException {
031    check(name != null, "Json Property Name is null");
032    check(value != null, "Json Property Value is null");
033    if (get(name) != null) {
034      check(false, "Name '"+name+"' already exists (value = "+get(name).toString()+")");
035    }
036    JsonProperty p = new JsonProperty(name, value);
037    properties.add(p);
038    propMap.put(name, p);
039    return this;
040  }
041  
042  public JsonObject add(int index, String name, JsonElement value) throws JsonException {
043    check(name != null, "Json Property Name is null");
044    check(value != null, "Json Property Value is null");
045    if (get(name) != null) {
046      check(false, "Name '"+name+"' already exists (value = "+get(name).toString()+")");
047    }
048    JsonProperty p = new JsonProperty(name, value);
049    properties.add(index, p);
050    propMap.put(name, p);
051    return this;
052  }
053
054  public JsonObject addIfNotNull(String name, JsonElement value) throws JsonException {
055    if (value != null) {
056      check(name != null, "Name is null");
057      if (get(name) != null) {
058        check(false, "Name '"+name+"' already exists (value = "+get(name).toString()+")");
059      }
060      JsonProperty p = new JsonProperty(name, value);
061      properties.add(p);
062      propMap.put(name, p);
063    }
064    return this;
065  }
066
067  
068  // this is used by the parser which can allow duplicates = true (for the validator). You should not otherwise use it
069  public JsonObject addForParser(String name, JsonElement value, boolean noComma, boolean nameUnquoted, boolean valueUnquoted) throws JsonException {
070    check(name != null, "Name is null");
071    check(value != null, "Value is null");
072    JsonProperty p = new JsonProperty(name, value);
073    p.setNoComma(noComma);
074    p.setUnquotedName(nameUnquoted);
075    p.setUnquotedValue(valueUnquoted);
076    properties.add(p);
077    propMap.put(name, p); // last duplicate wins
078    return this;
079  }
080
081  public JsonObject add(String name, String value) throws JsonException {
082    check(name != null, "Name is null");
083    return add(name, value == null ? new JsonNull() : new JsonString(value));
084  }
085
086  public JsonObject add(String name, List<String> values) throws JsonException {
087    check(name != null, "Name is null");
088    JsonArray arr = new JsonArray();
089    add(name, arr);
090    for (String v : values) {
091      arr.add(v);
092    }
093    return this;
094  }
095
096  public JsonObject addIfNotNull(String name, String value) throws JsonException {
097    check(name != null, "Name is null");
098    if (value == null) { 
099      return this;
100    } else {
101      return add(name, value == null ? new JsonNull() : new JsonString(value));
102    }
103  }
104
105  public JsonObject add(String name, boolean value) throws JsonException {
106    check(name != null, "Name is null");
107    return add(name, new JsonBoolean(value));
108  }
109
110  public JsonObject add(String name, int value) throws JsonException {
111    check(name != null, "Name is null");
112    return add(name, new JsonNumber(value));
113  }
114
115
116  public JsonObject add(String name, long value) throws JsonException {
117    check(name != null, "Name is null");
118    return add(name, new JsonNumber(value));
119  }
120
121  
122  public JsonObject set(String name, JsonElement value) throws JsonException {
123    check(name != null, "Name is null");
124    check(value != null, "Value is null");
125    JsonProperty p = propMap.get(name);
126    if (p != null) {
127      p.setValue(value);
128      return this;
129    } else {
130      return add(name, value);
131    }
132  }
133
134  public JsonObject set(String name, Instant value) throws JsonException {
135    String v = value == null ? null : value.toString();
136    return set(name, v);
137  }
138    
139
140  public JsonObject set(String name, String value) throws JsonException {
141    check(name != null, "Name is null");
142    JsonProperty p = propMap.get(name);
143    if (p != null) {
144      p.setValue(value == null ? new JsonNull() : new JsonString(value));
145      return this;
146    } else {
147      return add(name, value == null ? new JsonNull() : new JsonString(value));
148    }
149  }
150
151  public JsonObject set(String name, boolean value) throws JsonException {
152    check(name != null, "Name is null");
153    JsonProperty p = propMap.get(name);
154    if (p != null) {
155      p.setValue(new JsonBoolean(value));
156      return this;
157    } else {
158      return add(name, new JsonBoolean(value));
159    }
160  }
161
162  public JsonObject set(String name, int value) throws JsonException {
163    check(name != null, "Name is null");
164    JsonProperty p = propMap.get(name);
165    if (p != null) {
166      p.setValue(new JsonNumber(value));
167      return this;
168    } else {
169      return add(name, new JsonNumber(value));
170    }
171  }
172
173  public JsonObject set(String name, long value) throws JsonException {
174    check(name != null, "Name is null");
175    JsonProperty p = propMap.get(name);
176    if (p != null) {
177      p.setValue(new JsonNumber(value));
178      return this;
179    } else {
180      return add(name, new JsonNumber(value));
181    }
182  }
183
184  public JsonElement get(String name) {
185    if (propMap.containsKey(name)) {
186      return propMap.get(name).getValue();
187    } else {
188      return null;
189    }
190  }
191
192  public boolean has(String name) {
193    return propMap.containsKey(name);
194  }
195
196  public boolean has(String... names) {
197    for (String n : names) {
198      if (propMap.containsKey(n)) {
199        return true;
200      }
201    }
202    return false;
203  }
204
205  public void remove(String name) {
206    if (propMap.containsKey(name)) {
207      propMap.remove(name);
208      properties.removeIf((JsonProperty item) -> name.equals(item.getName()));
209    }
210  }
211  
212  public List<JsonProperty> getProperties() {
213    return properties;
214  }
215
216  public List<String> getNames() {
217    return Utilities.sorted(propMap.keySet());
218  }
219
220  public String str(String name) {
221    if (hasPrimitive(name)) {
222      return get(name).asJsonPrimitive().getValue();
223    } else {
224      return null;
225    }
226  }
227
228  public boolean hasObject(String name) {
229    return propMap.containsKey(name) && propMap.get(name).getValue().type() == JsonElementType.OBJECT;
230  }
231
232  public boolean hasArray(String name) {
233    return propMap.containsKey(name) && propMap.get(name).getValue().type() == JsonElementType.ARRAY;
234  }
235
236  public boolean hasPrimitive(String name) {
237    return propMap.containsKey(name) && propMap.get(name).getValue() instanceof JsonPrimitive;
238  }
239
240  public boolean hasString(String name) {
241    return propMap.containsKey(name) && propMap.get(name).getValue().type() == JsonElementType.STRING;
242  }
243
244  public boolean hasNumber(String name) {
245    return propMap.containsKey(name) && propMap.get(name).getValue().type() == JsonElementType.NUMBER;
246  }
247
248  public boolean hasBoolean(String name) {
249    return propMap.containsKey(name) && propMap.get(name).getValue().type() == JsonElementType.BOOLEAN;
250  }
251
252  public boolean hasNull(String name) {
253    return propMap.containsKey(name) && propMap.get(name).getValue().type() == JsonElementType.NULL;
254  }
255
256
257  public JsonObject getJsonObject(String name) {
258    return hasObject(name) ?  (JsonObject) get(name) : null;
259  }
260
261  public JsonString getJsonString(String name) {
262    return hasString(name) ? (JsonString) get(name) : null;
263  }
264
265  public JsonBoolean getJsonBoolean(String name) {
266    return hasBoolean(name) ? (JsonBoolean) get(name) : null;
267  }
268  
269  public JsonNumber getJsonNumber(String name) {
270    return hasNumber(name) ? (JsonNumber) get(name) : null;
271  }
272  
273  public JsonNull getJsonNull(String name) {
274    return hasNull(name) ?(JsonNull) get(name) : null;
275  }
276  
277  public JsonArray getJsonArray(String name) {
278    return hasArray(name) ? (JsonArray) get(name) : null;
279  }
280
281  public Integer asInteger(String name) {
282    if (hasNumber(name)) {
283      return ((JsonNumber) get(name)).getInteger();
284    }
285    if (hasPrimitive(name)) {
286      String s = asString(name);
287      if (Utilities.isInteger(s)) {
288        return Integer.parseInt(s);
289      }
290    }
291    return null;
292  }
293  
294  public Double asDouble(String name) {
295    if (hasNumber(name)) {
296      return ((JsonNumber) get(name)).getDouble();
297    }
298    if (hasPrimitive(name)) {
299      String s = asString(name);
300      if (Utilities.isDecimal(s, false)) {
301        return Double.parseDouble(s);
302      }
303    }
304    return null;
305  }
306
307
308  public String asString(String name) {
309    return hasPrimitive(name) ? ((JsonPrimitive) get(name)).getValue() : null;
310  }
311
312  public String asString(String... names) {
313    for (String n : names) {
314      if (hasPrimitive(n)) {
315        return asString(n);
316      }
317    }
318    return null;
319  }
320
321  public boolean asBoolean(String name) {
322    if (hasBoolean(name)) {
323      return ((JsonBoolean) get(name)).isValue();
324    }
325    if (hasPrimitive(name)) {
326      String s = asString(name);
327      if ("true".equals(s)) {
328        return true;
329      }
330      if ("false".equals(s)) {
331        return false;
332      }
333    }
334    return false;
335  }
336
337  public Instant asDate(String name) {
338    String source = asString(name);
339    if (Utilities.noString(source)) {
340      return null;
341    } else {
342      OffsetDateTime odt = OffsetDateTime.parse(source);
343      return odt.toInstant();
344    }
345  }
346  
347  public Instant asInstant(String name) throws ParseException {
348    String source = asString(name);
349    if (Utilities.noString(source) || "null".equals(source)) {
350      return null;
351    } else if (source.length() <= 10) {
352      Date d = new SimpleDateFormat("yyyy-mm-dd").parse(source);
353      return d.toInstant();
354    } else {
355      OffsetDateTime odt = OffsetDateTime.parse(source);
356      return odt.toInstant();
357    }
358  }
359  
360  public JsonObject forceObject(String name) throws JsonException {
361    if (has(name) && !hasObject(name)) {
362      remove(name);
363    }
364    if (!has(name)) {
365      add(name, new JsonObject());
366    }
367    return getJsonObject(name);
368  }
369
370  public JsonArray forceArray(String name) throws JsonException {
371    if (has(name) && !hasArray(name)) {
372      remove(name);
373    }
374    if (!has(name)) {
375      add(name, new JsonArray());
376    }
377    return getJsonArray(name);
378  }
379  
380  public JsonArray forceArray(int index, String name) throws JsonException {
381    if (has(name) && !hasArray(name)) {
382      remove(name);
383    }
384    if (!has(name)) {
385      add(index, name, new JsonArray());
386    }
387    return getJsonArray(name);
388  }
389
390  public List<JsonObject> getJsonObjects(String name) {
391    List<JsonObject> res = new ArrayList<>();
392    if (hasArray(name)) {
393      res.addAll(getJsonArray(name).asJsonObjects());
394    } else if (hasObject(name)) {
395      res.add(getJsonObject(name));
396    } 
397    return res;
398  }
399  
400  public List<String> getStrings(String name) {
401    List<String> res = new ArrayList<>();
402    if (hasArray(name)) {
403      res.addAll(getJsonArray(name).asStrings());
404    } else if (hasPrimitive(name)) {
405      res.add(asString(name));
406    } 
407    return res;
408  }
409  
410  public JsonObject deepCopy() {
411    return (JsonObject) make().copy(this);
412  }
413
414  @Override
415  protected JsonElement copy(JsonElement other) {
416    JsonObject o = (JsonObject) other;
417    for (JsonProperty p : o.getProperties()) {
418      add(p.getName(), p.getValue().deepCopy());
419    }
420    return this;
421  }
422  
423  @Override
424  protected JsonElement make() {
425    return new JsonObject();
426  }
427  
428  public JsonObject findByStringProp(String arrName, String prop, String value) {
429    for (JsonObject obj : getJsonObjects(arrName)) {
430      if (obj.has(prop) && value.equals(obj.asString(prop))) 
431        return obj;
432    }
433    return null;
434  }
435  
436  public void merge(JsonObject source) {
437    for (JsonProperty pp : source.getProperties()) {
438      if (has(pp.getName())) {
439        JsonElement te = get(pp.getName());
440        if (te.isJsonObject() && pp.getValue().isJsonObject()) {
441          ((JsonObject) te).merge((JsonObject) pp.getValue());
442        } else {
443          set(pp.getName(), pp.getValue());
444        }
445      } else {
446        add(pp.getName(), pp.getValue());
447      }
448    }
449  }
450
451
452  @Override
453  public String toString() {
454    StringBuilder b = new StringBuilder();
455    b.append("{ ");
456    boolean first = true;
457    for (JsonProperty p : properties) {
458      if (first) first = false; else b.append(", ");
459      b.append(p.toString());
460    }
461    b.append(" }");
462    return b.toString();
463  }
464
465  public boolean isExtraComma() {
466    return extraComma;
467  }
468
469  public void setExtraComma(boolean extraComma) {
470    this.extraComma = extraComma;
471  }
472  
473  public void clear() {
474    properties.clear();
475    propMap.clear();
476  }
477
478  public boolean isJsonString(String name) {
479    return has(name) && get(name).type() == JsonElementType.STRING;
480  }
481  
482  public boolean isJsonBoolean(String name) {
483    return has(name) && get(name).type() == JsonElementType.BOOLEAN;
484  }
485
486  public String compareTo(JsonObject j2) {
487    String path = "$";
488    CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder();
489    compare(path, b, this, j2);
490    return b.length() == 0 ? null : b.toString();
491  }
492
493  private void compare(String path, CommaSeparatedStringBuilder b, JsonObject j1, JsonObject j2) {
494    for (JsonProperty p : j1.getProperties()) {
495      String np = path+"."+p.getName();
496      JsonElement p2 = j2.get(p.getName());
497      if (p2 == null) {
498        b.append("Missing at "+np);
499      } else if (p.getValue().type() != p2.type()) {
500        b.append("Wrong type at "+np+": "+p2.type().toName()+" instead of "+p.getValue().type().toName());        
501      } else if (p2.isJsonPrimitive()) {
502        String s2 = p2.asString();
503        String s1 = p.getValue().asString();
504        if (!s2.equals(s1)) {
505          b.append("Value Mismatch at "+np+": '"+s2+"' instead of '"+s1+"'");                  
506        }
507      } else if (p2.isJsonArray()) {
508        compare(np, b, p.getValue().asJsonArray(), p2.asJsonArray());
509      } else {
510        compare(np, b, p.getValue().asJsonObject(), p2.asJsonObject());        
511      }
512    }
513    for (JsonProperty p : j2.getProperties()) {
514      String np = path+"."+p.getName();
515      if (!j1.has(p.getName())) {
516        b.append("Unexpected "+p.getValue().type().toName()+" at "+np);        
517      }
518    }
519  }
520  
521  private void compare(String path, CommaSeparatedStringBuilder b, JsonArray j1, JsonArray j2) {
522    for (int i = 0; i < Integer.min(j1.size(), j2.size()); i++) {
523      String np = path+"["+i+"]";
524      JsonElement i1 = j1.get(i);
525      JsonElement i2 = j2.get(i);
526      if (i1.type() != i2.type()) {
527        b.append("Wrong type at "+np+": "+i2.type().toName()+" instead of "+i1.type().toName());        
528      } else if (i2.isJsonPrimitive()) {
529        if (!i2.toString().equals(i1.asString())) {
530          b.append("Value Mismatch at "+np+": '"+i1.toString()+"' instead of '"+i1.toString()+"'");                  
531        }
532      } else if (i2.isJsonArray()) {
533        compare(np, b, i1.asJsonArray(), i2.asJsonArray());
534      } else {
535        compare(np, b, i1.asJsonObject(), i2.asJsonObject());        
536      }
537    }
538    if (j1.size() > j2.size()) {
539      b.append("Missing Element "+j2.size()+" at "+path);  
540    } else if (j1.size() < j2.size()) {
541      b.append("Unexpected Element "+j1.size()+" at "+path);  
542    }
543  }
544}