001package org.hl7.fhir.utilities.json.model; 002 003import java.util.ArrayList; 004import java.util.List; 005 006import org.hl7.fhir.utilities.json.JsonException; 007 008public abstract class JsonElement { 009 010 private List<JsonComment> comments; 011 private JsonLocationData start; 012 private JsonLocationData end; 013 014 public abstract JsonElementType type(); 015 016 public List<JsonComment> getComments() { 017 if (comments == null ) { 018 comments = new ArrayList<>(); 019 } 020 return comments; 021 } 022 023 public JsonLocationData getStart() { 024 return start; 025 } 026 027 public void setStart(JsonLocationData start) { 028 this.start = start; 029 } 030 031 public JsonLocationData getEnd() { 032 return end; 033 } 034 035 public void setEnd(JsonLocationData end) { 036 this.end = end; 037 } 038 039 protected void check(boolean test, String msg) throws JsonException { 040 if (!test) { 041 throw new JsonException(msg); 042 } 043 } 044 045 public boolean hasComments() { 046 return comments != null && !comments.isEmpty(); 047 } 048 049 public JsonElement deepCopy() { 050 return make().copy(this); 051 } 052 053 protected abstract JsonElement copy(JsonElement jsonElement); 054 protected abstract JsonElement make(); 055 056 public boolean isJsonObject() { 057 return type() == JsonElementType.OBJECT; 058 } 059 060 public boolean isJsonArray() { 061 return type() == JsonElementType.ARRAY; 062 } 063 064 public boolean isJsonPrimitive() { 065 return isJsonBoolean() || isJsonString() || isJsonNull() || isJsonNumber(); 066 } 067 068 public boolean isJsonBoolean() { 069 return type() == JsonElementType.BOOLEAN; 070 } 071 072 public boolean isJsonString() { 073 return type() == JsonElementType.STRING; 074 } 075 076 public boolean isJsonNumber() { 077 return type() == JsonElementType.NUMBER; 078 } 079 080 public boolean isJsonNull() { 081 return type() == JsonElementType.NULL; 082 } 083 084 public JsonObject asJsonObject() { 085 return isJsonObject() ? (JsonObject) this : null; 086 } 087 088 public JsonArray asJsonArray() { 089 return isJsonArray() ? (JsonArray) this : null; 090 } 091 092 public JsonPrimitive asJsonPrimitive() { 093 return isJsonPrimitive() ? (JsonPrimitive) this : null; 094 } 095 096 public JsonBoolean asJsonBoolean() { 097 return isJsonBoolean() ? (JsonBoolean) this : null; 098 } 099 100 public JsonString asJsonString() { 101 return isJsonString() ? (JsonString) this : null; 102 } 103 104 public JsonNumber asJsonNumber() { 105 return isJsonNumber() ? (JsonNumber) this : null; 106 } 107 108 public JsonNull asJsonNull() { 109 return isJsonNull() ? (JsonNull) this : null; 110 } 111 112 public String asString() { 113 return isJsonPrimitive() ? ((JsonPrimitive) this).getValue() : null; 114 } 115}