001package org.hl7.fhir.r5.openapi;
002
003/*-
004 * #%L
005 * org.hl7.fhir.r5
006 * %%
007 * Copyright (C) 2014 - 2019 Health Level 7
008 * %%
009 * Licensed under the Apache License, Version 2.0 (the "License");
010 * you may not use this file except in compliance with the License.
011 * You may obtain a copy of the License at
012 * 
013 *      http://www.apache.org/licenses/LICENSE-2.0
014 * 
015 * Unless required by applicable law or agreed to in writing, software
016 * distributed under the License is distributed on an "AS IS" BASIS,
017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
018 * See the License for the specific language governing permissions and
019 * limitations under the License.
020 * #L%
021 */
022
023
024import com.google.gson.JsonArray;
025import com.google.gson.JsonElement;
026import com.google.gson.JsonObject;
027
028public class BaseWriter {
029
030  protected JsonObject object;
031
032  public BaseWriter(JsonObject object) {
033    super();
034    this.object = object;
035  }
036
037  protected JsonObject ensureObject(String name) {
038    JsonObject child = object.getAsJsonObject(name);
039    if (child == null) {
040      child = new JsonObject();
041      object.add(name, child);
042    }
043    return child;
044  }
045  
046  protected JsonObject ensureArrayObject(String arrayName, String propertyName, String value) {
047    JsonArray arr = forceArray(arrayName);
048    for (JsonElement e : arr) {
049      String s = e.getAsJsonObject().get(propertyName).getAsString();
050      if (value.equals(s))
051        return e.getAsJsonObject();
052    }
053    JsonObject e = new JsonObject();
054    arr.add(e);
055    e.addProperty(propertyName, value);
056    return e;
057  }
058
059  protected JsonArray forceArray(String arrayName) {
060    JsonArray arr = object.getAsJsonArray(arrayName);
061    if (arr == null) {
062      arr = new JsonArray();
063      object.add(arrayName, arr);
064    }
065    return arr;
066  }
067  
068  protected JsonObject forceArrayObject(String arrayName) {
069    JsonArray arr = object.getAsJsonArray(arrayName);
070    if (arr == null) {
071      arr = new JsonArray();
072      object.add(arrayName, arr);
073    }
074    JsonObject obj = new JsonObject();
075    arr.add(obj);
076    return obj;
077  }
078  
079
080  protected JsonObject ensureMapObject(String mapName, String value) {
081    JsonObject map = object.getAsJsonObject(mapName);
082    if (map == null) {
083      map = new JsonObject();
084      object.add(mapName, map);
085    }
086    if (map.has(value))
087      return map.getAsJsonObject(value);
088    JsonObject e = new JsonObject();
089    map.add(value, e);
090    return e;
091  }
092  
093
094  protected JsonObject ensureMapObject(String value) {
095    if (object.has(value))
096      return object.getAsJsonObject(value);
097    JsonObject e = new JsonObject();
098    object.add(value, e);
099    return e;
100  }
101  
102}