diff options
Diffstat (limited to 'openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json')
2 files changed, 130 insertions, 156 deletions
diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonSchemaDataGenerator.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonSchemaDataGenerator.java index 2db691a781..fceef8bb51 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonSchemaDataGenerator.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonSchemaDataGenerator.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,160 +17,149 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.utilities.json; +import java.util.HashMap; +import java.util.Map; import org.json.JSONException; import org.json.JSONObject; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; -import java.util.HashMap; -import java.util.Map; - public class JsonSchemaDataGenerator { - private static final String ROOT = "root"; - private static final Logger logger = - LoggerFactory.getLogger(JsonSchemaDataGenerator.class); - boolean includeDefaults = true; - private JSONObject root; - private Map<String, Object> referencesData; - - /** - * Instantiates a new Json schema data generator. - * - * @param jsonSchema the json schema - */ - public JsonSchemaDataGenerator(String jsonSchema) { - if (jsonSchema == null) { - throw new IllegalArgumentException("Input string jsonSchema can not be null"); + private static final String ROOT = "root"; + private static final Logger logger = LoggerFactory.getLogger(JsonSchemaDataGenerator.class); + boolean includeDefaults = true; + private JSONObject root; + private Map<String, Object> referencesData; + + /** + * Instantiates a new Json schema data generator. + * + * @param jsonSchema the json schema + */ + public JsonSchemaDataGenerator(String jsonSchema) { + if (jsonSchema == null) { + throw new IllegalArgumentException("Input string jsonSchema can not be null"); + } + root = new JSONObject(jsonSchema); } - root = new JSONObject(jsonSchema); - } - public void setIncludeDefaults(boolean includeDefaults) { - this.includeDefaults = includeDefaults; - } - - /** - * Generates json data that conform to the schema according to turned on flags. - * - * @return json that conform to the schema - */ - public String generateData() { - referencesData = new HashMap<>(); - JSONObject data = new JSONObject(); - - generateData(ROOT, root, - data); - // "root" is dummy name to represent the top level object - // (which, as apposed to inner objects, doesn't have a name in the schema) - return data.has(ROOT) ? data.get(ROOT).toString() : data.toString(); - } - - private void generateData(String propertyName, JSONObject property, JSONObject propertyData) { - if (property.has(JsonSchemaKeyword.TYPE)) { - String propertyType = property.getString(JsonSchemaKeyword.TYPE); - if (JsonSchemaKeyword.OBJECT.equals(propertyType)) { - generateObjectData(propertyName, property, propertyData); - } else { - generatePrimitiveData(propertyType, propertyName, property, propertyData); - } - } else if (property.has(JsonSchemaKeyword.REF)) { - generateReferenceData(propertyName, property.getString(JsonSchemaKeyword.REF), propertyData); + public void setIncludeDefaults(boolean includeDefaults) { + this.includeDefaults = includeDefaults; } - } - - private void generateObjectData(String propertyName, JSONObject property, - JSONObject propertyData) { - JSONObject subProperties = property.getJSONObject(JsonSchemaKeyword.PROPERTIES); - JSONObject subPropertiesData = new JSONObject(); - for (String subPropertyName : subProperties.keySet()) { - generateData(subPropertyName, subProperties.getJSONObject(subPropertyName), - subPropertiesData); + /** + * Generates json data that conform to the schema according to turned on flags. + * + * @return json that conform to the schema + */ + public String generateData() { + referencesData = new HashMap<>(); + JSONObject data = new JSONObject(); + generateData(ROOT, root, data); + // "root" is dummy name to represent the top level object + + // (which, as apposed to inner objects, doesn't have a name in the schema) + return data.has(ROOT) ? data.get(ROOT).toString() : data.toString(); } - if (subPropertiesData.length() > 0) { - propertyData.put(propertyName, subPropertiesData); + private void generateData(String propertyName, JSONObject property, JSONObject propertyData) { + if (property.has(JsonSchemaKeyword.TYPE)) { + String propertyType = property.getString(JsonSchemaKeyword.TYPE); + if (JsonSchemaKeyword.OBJECT.equals(propertyType)) { + generateObjectData(propertyName, property, propertyData); + } else { + generatePrimitiveData(propertyType, propertyName, property, propertyData); + } + } else if (property.has(JsonSchemaKeyword.REF)) { + generateReferenceData(propertyName, property.getString(JsonSchemaKeyword.REF), propertyData); + } } - } - private void generateReferenceData(String propertyName, String referencePath, - JSONObject propertyData) { - if (referencesData.containsKey(referencePath)) { - Object referenceData = referencesData.get(referencePath); - if (referenceData != null) { - propertyData.put(propertyName, referenceData); - } - } else { - generateData(propertyName, resolveReference(referencePath), propertyData); - referencesData.put(referencePath, propertyData.opt(propertyName)); + private void generateObjectData(String propertyName, JSONObject property, JSONObject propertyData) { + JSONObject subProperties = property.getJSONObject(JsonSchemaKeyword.PROPERTIES); + JSONObject subPropertiesData = new JSONObject(); + for (String subPropertyName : subProperties.keySet()) { + generateData(subPropertyName, subProperties.getJSONObject(subPropertyName), subPropertiesData); + } + if (subPropertiesData.length() > 0) { + propertyData.put(propertyName, subPropertiesData); + } } - } - private JSONObject resolveReference(String referencePath) { - String[] keys = referencePath.replaceFirst("#/", "").split("/"); - - JSONObject reference = root; - for (String key : keys) { - reference = reference.getJSONObject(key); + private void generateReferenceData(String propertyName, String referencePath, JSONObject propertyData) { + if (referencesData.containsKey(referencePath)) { + Object referenceData = referencesData.get(referencePath); + if (referenceData != null) { + propertyData.put(propertyName, referenceData); + } + } else { + generateData(propertyName, resolveReference(referencePath), propertyData); + referencesData.put(referencePath, propertyData.opt(propertyName)); + } } - return reference; - } - private void generatePrimitiveData(String propertyType, String propertyName, JSONObject property, - JSONObject propertyData) { - if (includeDefaults) { - populateWithDefaultValue(propertyType, propertyName, property, propertyData); + private JSONObject resolveReference(String referencePath) { + String[] keys = referencePath.replaceFirst("#/", "").split("/"); + JSONObject reference = root; + for (String key : keys) { + reference = reference.getJSONObject(key); + } + return reference; } - } - private void populateWithDefaultValue(String propertyType, String propertyName, - JSONObject property, JSONObject propertyData) { - if (!property.has(JsonSchemaKeyword.DEFAULT)) { - return; + private void generatePrimitiveData(String propertyType, String propertyName, JSONObject property, JSONObject propertyData) { + if (includeDefaults) { + populateWithDefaultValue(propertyType, propertyName, property, propertyData); + } } - try { - switch (propertyType) { - case JsonSchemaKeyword.ARRAY: - propertyData.put(propertyName, property.getJSONArray(JsonSchemaKeyword.DEFAULT)); - break; - case JsonSchemaKeyword.BOOLEAN: - propertyData.put(propertyName, property.getBoolean(JsonSchemaKeyword.DEFAULT)); - break; - case JsonSchemaKeyword.INTEGER: - propertyData.put(propertyName, property.getInt(JsonSchemaKeyword.DEFAULT)); - break; - case JsonSchemaKeyword.NUMBER: - propertyData.put(propertyName, property.getDouble(JsonSchemaKeyword.DEFAULT)); - break; - case JsonSchemaKeyword.STRING: - propertyData.put(propertyName, property.getString(JsonSchemaKeyword.DEFAULT)); - break; - default: - break; - } - } catch (JSONException exception) { - Object defaultValue = property.get(JsonSchemaKeyword.DEFAULT); - logger.error(String.format( - "Invalid schema: '%s' property type is '%s' but it has a default value which is not: %s.", - propertyName, propertyType, defaultValue), exception); - throw exception; + + private void populateWithDefaultValue(String propertyType, String propertyName, JSONObject property, JSONObject propertyData) { + if (!property.has(JsonSchemaKeyword.DEFAULT)) { + return; + } + try { + switch (propertyType) { + case JsonSchemaKeyword.ARRAY: + propertyData.put(propertyName, property.getJSONArray(JsonSchemaKeyword.DEFAULT)); + break; + case JsonSchemaKeyword.BOOLEAN: + propertyData.put(propertyName, property.getBoolean(JsonSchemaKeyword.DEFAULT)); + break; + case JsonSchemaKeyword.INTEGER: + propertyData.put(propertyName, property.getInt(JsonSchemaKeyword.DEFAULT)); + break; + case JsonSchemaKeyword.NUMBER: + propertyData.put(propertyName, property.getDouble(JsonSchemaKeyword.DEFAULT)); + break; + case JsonSchemaKeyword.STRING: + propertyData.put(propertyName, property.getString(JsonSchemaKeyword.DEFAULT)); + break; + default: + break; + } + } catch (JSONException exception) { + Object defaultValue = property.get(JsonSchemaKeyword.DEFAULT); + logger.error(String + .format("Invalid schema: '%s' property type is '%s' but it has a default value which is not: %s.", propertyName, propertyType, + defaultValue), exception); + throw exception; + } } - } - private static class JsonSchemaKeyword { - private static final String DEFAULT = "default"; - private static final String TYPE = "type"; - private static final String PROPERTIES = "properties"; - private static final String ARRAY = "array"; - private static final String BOOLEAN = "boolean"; - private static final String INTEGER = "integer"; - private static final String NUMBER = "number"; - private static final String STRING = "string"; - private static final String OBJECT = "object"; - private static final String REF = "$ref"; - } + private static class JsonSchemaKeyword { + + private static final String DEFAULT = "default"; + private static final String TYPE = "type"; + private static final String PROPERTIES = "properties"; + private static final String ARRAY = "array"; + private static final String BOOLEAN = "boolean"; + private static final String INTEGER = "integer"; + private static final String NUMBER = "number"; + private static final String STRING = "string"; + private static final String OBJECT = "object"; + private static final String REF = "$ref"; + } } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonUtil.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonUtil.java index b83ad2782d..b148d6457d 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonUtil.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonUtil.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.core.utilities.json; import com.google.gson.Gson; @@ -21,7 +20,6 @@ import com.google.gson.GsonBuilder; import com.google.gson.JsonIOException; import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; - import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; @@ -32,7 +30,6 @@ import java.util.Collections; import java.util.List; import java.util.Set; import java.util.stream.Collectors; - import org.apache.commons.collections4.CollectionUtils; import org.everit.json.schema.EnumSchema; import org.everit.json.schema.Schema; @@ -46,7 +43,6 @@ import org.openecomp.core.utilities.deserializers.RequirementDefinitionDeseriali import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; - /** * The type Json util. */ @@ -58,8 +54,7 @@ public class JsonUtil { static { gsonBuilder = new GsonBuilder(); - gsonBuilder.registerTypeAdapter(RequirementDefinition.class, new - RequirementDefinitionDeserializer()); + gsonBuilder.registerTypeAdapter(RequirementDefinition.class, new RequirementDefinitionDeserializer()); gson = gsonBuilder.create(); } @@ -74,7 +69,6 @@ public class JsonUtil { */ public static String object2Json(Object obj) { return sbObject2Json(obj).toString(); - } /** @@ -125,13 +119,13 @@ public class JsonUtil { return type; } - /** * Is valid json boolean. * * @param json the json * @return the boolean */ + //todo check https://github.com/stleary/JSON-java as replacement for this code public static boolean isValidJson(String json) { try { @@ -152,30 +146,25 @@ public class JsonUtil { public static List<String> validate(String json, String jsonSchema) { List<ValidationException> validationErrors = validateUsingEverit(json, jsonSchema); return validationErrors == null ? null - : validationErrors.stream().map(JsonUtil::mapValidationExceptionToMessage) - .collect(Collectors.toList()); + : validationErrors.stream().map(JsonUtil::mapValidationExceptionToMessage).collect(Collectors.toList()); } private static String mapValidationExceptionToMessage(ValidationException exception) { Object schema = exception.getViolatedSchema(); - if (schema instanceof EnumSchema) { return mapEnumViolationToMessage(exception); } else if (schema instanceof StringSchema) { return mapStringViolationToMessage(exception); } - return exception.getMessage(); } private static String mapEnumViolationToMessage(ValidationException exception) { Set<Object> possibleValues = ((EnumSchema) exception.getViolatedSchema()).getPossibleValues(); - return exception.getMessage().replaceFirst("enum value", possibleValues.size() == 1 - ? String.format("value. %s is the only possible value for this field", - possibleValues.iterator().next()) - : String.format("value. Possible values: %s", CommonMethods - .collectionToCommaSeparatedString( - possibleValues.stream().map(Object::toString).collect(Collectors.toList())))); + return exception.getMessage().replaceFirst("enum value", + possibleValues.size() == 1 ? String.format("value. %s is the only possible value for this field", possibleValues.iterator().next()) + : String.format("value. Possible values: %s", + CommonMethods.collectionToCommaSeparatedString(possibleValues.stream().map(Object::toString).collect(Collectors.toList())))); } private static String mapStringViolationToMessage(ValidationException validationException) { @@ -188,25 +177,21 @@ public class JsonUtil { } private static List<ValidationException> validateUsingEverit(String json, String jsonSchema) { - LOGGER.debug( - String.format("validateUsingEverit start, json=%s, jsonSchema=%s", json, jsonSchema)); + LOGGER.debug(String.format("validateUsingEverit start, json=%s, jsonSchema=%s", json, jsonSchema)); if (json == null || jsonSchema == null) { throw new IllegalArgumentException("Input strings json and jsonSchema can not be null"); } - Schema schemaObj = SchemaLoader.load(new JSONObject(jsonSchema)); try { schemaObj.validate(new JSONObject(json)); } catch (ValidationException ve) { - return CollectionUtils.isEmpty(ve.getCausingExceptions()) ? Collections.singletonList(ve) - : ve.getCausingExceptions(); + return CollectionUtils.isEmpty(ve.getCausingExceptions()) ? Collections.singletonList(ve) : ve.getCausingExceptions(); } return null; } private enum ValidationType { PATTERN("pattern"); - private String keyword; ValidationType(String keyword) { |