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 addNull(String name) throws JsonException {
087    check(name != null, "Name is null");
088    return add(name, new JsonNull());
089  }
090
091  public JsonObject add(String name, List<String> values) throws JsonException {
092    check(name != null, "Name is null");
093    JsonArray arr = new JsonArray();
094    add(name, arr);
095    for (String v : values) {
096      arr.add(v);
097    }
098    return this;
099  }
100
101  public JsonObject addIfNotNull(String name, String value) throws JsonException {
102    check(name != null, "Name is null");
103    if (value == null) { 
104      return this;
105    } else {
106      return add(name, value == null ? new JsonNull() : new JsonString(value));
107    }
108  }
109
110  public JsonObject add(String name, boolean value) throws JsonException {
111    check(name != null, "Name is null");
112    return add(name, new JsonBoolean(value));
113  }
114
115  public JsonObject add(String name, int value) throws JsonException {
116    check(name != null, "Name is null");
117    return add(name, new JsonNumber(value));
118  }
119
120
121  public JsonObject add(String name, long value) throws JsonException {
122    check(name != null, "Name is null");
123    return add(name, new JsonNumber(value));
124  }
125
126  
127  public JsonObject set(String name, JsonElement value) throws JsonException {
128    check(name != null, "Name is null");
129    check(value != null, "Value is null");
130    JsonProperty p = propMap.get(name);
131    if (p != null) {
132      p.setValue(value);
133      return this;
134    } else {
135      return add(name, value);
136    }
137  }
138
139  public JsonObject set(String name, Instant value) throws JsonException {
140    String v = value == null ? null : value.toString();
141    return set(name, v);
142  }
143    
144
145  public JsonObject set(String name, String value) throws JsonException {
146    check(name != null, "Name is null");
147    JsonProperty p = propMap.get(name);
148    if (p != null) {
149      p.setValue(value == null ? new JsonNull() : new JsonString(value));
150      return this;
151    } else {
152      return add(name, value == null ? new JsonNull() : new JsonString(value));
153    }
154  }
155
156  public JsonObject set(String name, boolean value) throws JsonException {
157    check(name != null, "Name is null");
158    JsonProperty p = propMap.get(name);
159    if (p != null) {
160      p.setValue(new JsonBoolean(value));
161      return this;
162    } else {
163      return add(name, new JsonBoolean(value));
164    }
165  }
166
167  public JsonObject set(String name, int value) throws JsonException {
168    check(name != null, "Name is null");
169    JsonProperty p = propMap.get(name);
170    if (p != null) {
171      p.setValue(new JsonNumber(value));
172      return this;
173    } else {
174      return add(name, new JsonNumber(value));
175    }
176  }
177
178  public JsonObject set(String name, long value) throws JsonException {
179    check(name != null, "Name is null");
180    JsonProperty p = propMap.get(name);
181    if (p != null) {
182      p.setValue(new JsonNumber(value));
183      return this;
184    } else {
185      return add(name, new JsonNumber(value));
186    }
187  }
188
189  public JsonElement get(String name) {
190    if (propMap.containsKey(name)) {
191      return propMap.get(name).getValue();
192    } else {
193      return null;
194    }
195  }
196
197  public boolean has(String name) {
198    return propMap.containsKey(name);
199  }
200
201  public boolean has(String... names) {
202    for (String n : names) {
203      if (propMap.containsKey(n)) {
204        return true;
205      }
206    }
207    return false;
208  }
209
210  public void remove(String name) {
211    if (propMap.containsKey(name)) {
212      propMap.remove(name);
213      properties.removeIf((JsonProperty item) -> name.equals(item.getName()));
214    }
215  }
216  
217  public List<JsonProperty> getProperties() {
218    return properties;
219  }
220
221  public List<String> getNames() {
222    return Utilities.sorted(propMap.keySet());
223  }
224
225  public String str(String name) {
226    if (hasPrimitive(name)) {
227      return get(name).asJsonPrimitive().getValue();
228    } else {
229      return null;
230    }
231  }
232
233  public boolean hasObject(String name) {
234    return propMap.containsKey(name) && propMap.get(name).getValue().type() == JsonElementType.OBJECT;
235  }
236
237  public boolean hasArray(String name) {
238    return propMap.containsKey(name) && propMap.get(name).getValue().type() == JsonElementType.ARRAY;
239  }
240
241  public boolean hasPrimitive(String name) {
242    return propMap.containsKey(name) && propMap.get(name).getValue() instanceof JsonPrimitive;
243  }
244
245  public boolean hasString(String name) {
246    return propMap.containsKey(name) && propMap.get(name).getValue().type() == JsonElementType.STRING;
247  }
248
249  public boolean hasNumber(String name) {
250    return propMap.containsKey(name) && propMap.get(name).getValue().type() == JsonElementType.NUMBER;
251  }
252
253  public boolean hasBoolean(String name) {
254    return propMap.containsKey(name) && propMap.get(name).getValue().type() == JsonElementType.BOOLEAN;
255  }
256
257  public boolean hasNull(String name) {
258    return propMap.containsKey(name) && propMap.get(name).getValue().type() == JsonElementType.NULL;
259  }
260
261
262  public JsonObject getJsonObject(String name) {
263    return hasObject(name) ?  (JsonObject) get(name) : null;
264  }
265
266  public JsonString getJsonString(String name) {
267    return hasString(name) ? (JsonString) get(name) : null;
268  }
269
270  public JsonBoolean getJsonBoolean(String name) {
271    return hasBoolean(name) ? (JsonBoolean) get(name) : null;
272  }
273  
274  public JsonNumber getJsonNumber(String name) {
275    return hasNumber(name) ? (JsonNumber) get(name) : null;
276  }
277  
278  public JsonNull getJsonNull(String name) {
279    return hasNull(name) ?(JsonNull) get(name) : null;
280  }
281  
282  public JsonArray getJsonArray(String name) {
283    return hasArray(name) ? (JsonArray) get(name) : null;
284  }
285
286  public Integer asInteger(String name) {
287    if (hasNumber(name)) {
288      return ((JsonNumber) get(name)).getInteger();
289    }
290    if (hasPrimitive(name)) {
291      String s = asString(name);
292      if (Utilities.isInteger(s)) {
293        return Integer.parseInt(s);
294      }
295    }
296    return null;
297  }
298
299  public Long asLong(String name) {
300    if (hasNumber(name)) {
301      return ((JsonNumber) get(name)).getLong();
302    }
303    if (hasPrimitive(name)) {
304      String s = asString(name);
305      if (Utilities.isLong(s)) {
306        return Long.parseLong(s);
307      }
308    }
309    return null;
310  }
311
312  public Double asDouble(String name) {
313    if (hasNumber(name)) {
314      return ((JsonNumber) get(name)).getDouble();
315    }
316    if (hasPrimitive(name)) {
317      String s = asString(name);
318      if (Utilities.isDecimal(s, false)) {
319        return Double.parseDouble(s);
320      }
321    }
322    return null;
323  }
324
325
326  public String asString(String name) {
327    return hasPrimitive(name) ? ((JsonPrimitive) get(name)).getValue() : null;
328  }
329
330  public String asString(String... names) {
331    for (String n : names) {
332      if (hasPrimitive(n)) {
333        return asString(n);
334      }
335    }
336    return null;
337  }
338
339  public boolean asBoolean(String name) {
340    if (hasBoolean(name)) {
341      return ((JsonBoolean) get(name)).isValue();
342    }
343    if (hasPrimitive(name)) {
344      String s = asString(name);
345      if ("true".equals(s)) {
346        return true;
347      }
348      if ("false".equals(s)) {
349        return false;
350      }
351    }
352    return false;
353  }
354
355  public Instant asDate(String name) {
356    String source = asString(name);
357    if (Utilities.noString(source)) {
358      return null;
359    } else {
360      OffsetDateTime odt = OffsetDateTime.parse(source);
361      return odt.toInstant();
362    }
363  }
364  
365  public Instant asInstant(String name) throws ParseException {
366    String source = asString(name);
367    if (Utilities.noString(source) || "null".equals(source)) {
368      return null;
369    } else if (source.length() <= 10) {
370      Date d = new SimpleDateFormat("yyyy-mm-dd").parse(source);
371      return d.toInstant();
372    } else {
373      OffsetDateTime odt = OffsetDateTime.parse(source);
374      return odt.toInstant();
375    }
376  }
377  
378  public JsonObject forceObject(String name) throws JsonException {
379    if (has(name) && !hasObject(name)) {
380      remove(name);
381    }
382    if (!has(name)) {
383      add(name, new JsonObject());
384    }
385    return getJsonObject(name);
386  }
387
388  public JsonArray forceArray(String name) throws JsonException {
389    if (has(name) && !hasArray(name)) {
390      remove(name);
391    }
392    if (!has(name)) {
393      add(name, new JsonArray());
394    }
395    return getJsonArray(name);
396  }
397  
398  public JsonArray forceArray(int index, String name) throws JsonException {
399    if (has(name) && !hasArray(name)) {
400      remove(name);
401    }
402    if (!has(name)) {
403      add(index, name, new JsonArray());
404    }
405    return getJsonArray(name);
406  }
407
408  public List<JsonObject> getJsonObjects(String name) {
409    List<JsonObject> res = new ArrayList<>();
410    if (hasArray(name)) {
411      res.addAll(getJsonArray(name).asJsonObjects());
412    } else if (hasObject(name)) {
413      res.add(getJsonObject(name));
414    } 
415    return res;
416  }
417  
418  public List<String> getStrings(String name) {
419    List<String> res = new ArrayList<>();
420    if (hasArray(name)) {
421      res.addAll(getJsonArray(name).asStrings());
422    } else if (hasPrimitive(name)) {
423      res.add(asString(name));
424    } 
425    return res;
426  }
427  
428  public JsonObject deepCopy() {
429    return (JsonObject) make().copy(this);
430  }
431
432  @Override
433  protected JsonElement copy(JsonElement other) {
434    JsonObject o = (JsonObject) other;
435    for (JsonProperty p : o.getProperties()) {
436      add(p.getName(), p.getValue().deepCopy());
437    }
438    return this;
439  }
440  
441  @Override
442  protected JsonElement make() {
443    return new JsonObject();
444  }
445  
446  public JsonObject findByStringProp(String arrName, String prop, String value) {
447    for (JsonObject obj : getJsonObjects(arrName)) {
448      if (obj.has(prop) && value.equals(obj.asString(prop))) 
449        return obj;
450    }
451    return null;
452  }
453  
454  public void merge(JsonObject source) {
455    for (JsonProperty pp : source.getProperties()) {
456      if (has(pp.getName())) {
457        JsonElement te = get(pp.getName());
458        if (te.isJsonObject() && pp.getValue().isJsonObject()) {
459          ((JsonObject) te).merge((JsonObject) pp.getValue());
460        } else {
461          set(pp.getName(), pp.getValue());
462        }
463      } else {
464        add(pp.getName(), pp.getValue());
465      }
466    }
467  }
468
469
470  @Override
471  public String toString() {
472    StringBuilder b = new StringBuilder();
473    b.append("{ ");
474    boolean first = true;
475    for (JsonProperty p : properties) {
476      if (first) first = false; else b.append(", ");
477      b.append(p.toString());
478    }
479    b.append(" }");
480    return b.toString();
481  }
482
483  public boolean isExtraComma() {
484    return extraComma;
485  }
486
487  public void setExtraComma(boolean extraComma) {
488    this.extraComma = extraComma;
489  }
490  
491  public void clear() {
492    properties.clear();
493    propMap.clear();
494  }
495
496  public boolean isJsonString(String name) {
497    return has(name) && get(name).type() == JsonElementType.STRING;
498  }
499  
500  public boolean isJsonBoolean(String name) {
501    return has(name) && get(name).type() == JsonElementType.BOOLEAN;
502  }
503
504  public boolean isJsonNumber(String name) {
505    return has(name) && get(name).type() == JsonElementType.NUMBER;
506  }
507  
508  public String compareTo(JsonObject j2) {
509    String path = "$";
510    CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder();
511    compare(path, b, this, j2);
512    return b.length() == 0 ? null : b.toString();
513  }
514
515  private void compare(String path, CommaSeparatedStringBuilder b, JsonObject j1, JsonObject j2) {
516    for (JsonProperty p : j1.getProperties()) {
517      String np = path+"."+p.getName();
518      JsonElement p2 = j2.get(p.getName());
519      if (p2 == null) {
520        b.append("Missing at "+np);
521      } else if (p.getValue().type() != p2.type()) {
522        b.append("Wrong type at "+np+": "+p2.type().toName()+" instead of "+p.getValue().type().toName());        
523      } else if (p2.isJsonPrimitive()) {
524        String s2 = p2.asString();
525        String s1 = p.getValue().asString();
526        if (!s2.equals(s1)) {
527          b.append("Value Mismatch at "+np+": '"+s2+"' instead of '"+s1+"'");                  
528        }
529      } else if (p2.isJsonArray()) {
530        compare(np, b, p.getValue().asJsonArray(), p2.asJsonArray());
531      } else {
532        compare(np, b, p.getValue().asJsonObject(), p2.asJsonObject());        
533      }
534    }
535    for (JsonProperty p : j2.getProperties()) {
536      String np = path+"."+p.getName();
537      if (!j1.has(p.getName())) {
538        b.append("Unexpected "+p.getValue().type().toName()+" at "+np);        
539      }
540    }
541  }
542  
543  private void compare(String path, CommaSeparatedStringBuilder b, JsonArray j1, JsonArray j2) {
544    for (int i = 0; i < Integer.min(j1.size(), j2.size()); i++) {
545      String np = path+"["+i+"]";
546      JsonElement i1 = j1.get(i);
547      JsonElement i2 = j2.get(i);
548      if (i1.type() != i2.type()) {
549        b.append("Wrong type at "+np+": "+i2.type().toName()+" instead of "+i1.type().toName());        
550      } else if (i2.isJsonPrimitive()) {
551        if (!i2.toString().equals(i1.asString())) {
552          b.append("Value Mismatch at "+np+": '"+i1.toString()+"' instead of '"+i1.toString()+"'");                  
553        }
554      } else if (i2.isJsonArray()) {
555        compare(np, b, i1.asJsonArray(), i2.asJsonArray());
556      } else {
557        compare(np, b, i1.asJsonObject(), i2.asJsonObject());        
558      }
559    }
560    if (j1.size() > j2.size()) {
561      b.append("Missing Element "+j2.size()+" at "+path);  
562    } else if (j1.size() < j2.size()) {
563      b.append("Unexpected Element "+j1.size()+" at "+path);  
564    }
565  }
566}