[SDC-29] Amdocs OnBoard 1707 initial commit.
[sdc.git] / openecomp-be / lib / openecomp-core-lib / openecomp-utilities-lib / src / main / java / org / openecomp / core / utilities / json / JsonSchemaDataGenerator.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.core.utilities.json;
22
23 import org.json.JSONException;
24 import org.json.JSONObject;
25 import org.openecomp.sdc.logging.api.Logger;
26 import org.openecomp.sdc.logging.api.LoggerFactory;
27
28 import java.util.HashMap;
29 import java.util.Map;
30
31 public class JsonSchemaDataGenerator {
32
33   private static final String ROOT = "root";
34   private static final Logger logger =
35       (Logger) LoggerFactory.getLogger(JsonSchemaDataGenerator.class);
36   boolean includeDefaults = true;
37   private JSONObject root;
38   private Map<String, Object> referencesData;
39
40   /**
41    * Instantiates a new Json schema data generator.
42    *
43    * @param jsonSchema the json schema
44    */
45   public JsonSchemaDataGenerator(String jsonSchema) {
46     if (jsonSchema == null) {
47       throw new IllegalArgumentException("Input string jsonSchema can not be null");
48     }
49     root = new JSONObject(jsonSchema);
50   }
51
52   public void setIncludeDefaults(boolean includeDefaults) {
53     this.includeDefaults = includeDefaults;
54   }
55
56   /**
57    * Generates json data that conform to the schema according to turned on flags.
58    *
59    * @return json that conform to the schema
60    */
61   public String generateData() {
62     referencesData = new HashMap<>();
63     JSONObject data = new JSONObject();
64
65     generateData(ROOT, root,
66         data);
67     // "root" is dummy name to represent the top level object
68     // (which, as apposed to inner objects, doesn't have a name in the schema)
69     return data.has(ROOT) ? data.get(ROOT).toString() : data.toString();
70   }
71
72   private void generateData(String propertyName, JSONObject property, JSONObject propertyData) {
73     if (property.has(JsonSchemaKeyword.TYPE)) {
74       String propertyType = property.getString(JsonSchemaKeyword.TYPE);
75       if (JsonSchemaKeyword.OBJECT.equals(propertyType)) {
76         generateObjectData(propertyName, property, propertyData);
77       } else {
78         generatePrimitiveData(propertyType, propertyName, property, propertyData);
79       }
80     } else if (property.has(JsonSchemaKeyword.REF)) {
81       generateReferenceData(propertyName, property.getString(JsonSchemaKeyword.REF), propertyData);
82     }
83   }
84
85   private void generateObjectData(String propertyName, JSONObject property,
86                                   JSONObject propertyData) {
87     JSONObject subProperties = property.getJSONObject(JsonSchemaKeyword.PROPERTIES);
88
89     JSONObject subPropertiesData = new JSONObject();
90     for (String subPropertyName : subProperties.keySet()) {
91       generateData(subPropertyName, subProperties.getJSONObject(subPropertyName),
92           subPropertiesData);
93     }
94
95     if (subPropertiesData.length() > 0) {
96       propertyData.put(propertyName, subPropertiesData);
97     }
98   }
99
100   private void generateReferenceData(String propertyName, String referencePath,
101                                      JSONObject propertyData) {
102     if (referencesData.containsKey(referencePath)) {
103       Object referenceData = referencesData.get(referencePath);
104       if (referenceData != null) {
105         propertyData.put(propertyName, referenceData);
106       }
107     } else {
108       generateData(propertyName, resolveReference(referencePath), propertyData);
109       referencesData.put(referencePath, propertyData.opt(propertyName));
110     }
111   }
112
113   private JSONObject resolveReference(String referencePath) {
114     String[] keys = referencePath.replaceFirst("#/", "").split("/");
115
116     JSONObject reference = root;
117     for (String key : keys) {
118       reference = reference.getJSONObject(key);
119     }
120     return reference;
121   }
122
123   private void generatePrimitiveData(String propertyType, String propertyName, JSONObject property,
124                                      JSONObject propertyData) {
125     if (includeDefaults) {
126       populateWithDefaultValue(propertyType, propertyName, property, propertyData);
127     }
128   }
129
130   private void populateWithDefaultValue(String propertyType, String propertyName,
131                                         JSONObject property, JSONObject propertyData) {
132     if (!property.has(JsonSchemaKeyword.DEFAULT)) {
133       return;
134     }
135     try {
136       switch (propertyType) {
137         case JsonSchemaKeyword.ARRAY:
138           propertyData.put(propertyName, property.getJSONArray(JsonSchemaKeyword.DEFAULT));
139           break;
140         case JsonSchemaKeyword.BOOLEAN:
141           propertyData.put(propertyName, property.getBoolean(JsonSchemaKeyword.DEFAULT));
142           break;
143         case JsonSchemaKeyword.INTEGER:
144           propertyData.put(propertyName, property.getInt(JsonSchemaKeyword.DEFAULT));
145           break;
146         case JsonSchemaKeyword.NUMBER:
147           propertyData.put(propertyName, property.getDouble(JsonSchemaKeyword.DEFAULT));
148           break;
149         case JsonSchemaKeyword.STRING:
150           propertyData.put(propertyName, property.getString(JsonSchemaKeyword.DEFAULT));
151           break;
152         default:
153           break;
154       }
155     } catch (JSONException exception) {
156       Object defaultValue = property.get(JsonSchemaKeyword.DEFAULT);
157       logger.error(String.format(
158           "Invalid schema: '%s' property type is '%s' but it has a default value which is not: %s.",
159           propertyName, propertyType, defaultValue), exception);
160       throw exception;
161     }
162   }
163
164   private static class JsonSchemaKeyword {
165     private static final String DEFAULT = "default";
166     private static final String TYPE = "type";
167     private static final String PROPERTIES = "properties";
168     private static final String ARRAY = "array";
169     private static final String BOOLEAN = "boolean";
170     private static final String INTEGER = "integer";
171     private static final String NUMBER = "number";
172     private static final String STRING = "string";
173     private static final String OBJECT = "object";
174     private static final String REF = "$ref";
175   }
176 }