1 package org.openecomp.core.utilities.deserializers;
3 import org.onap.sdc.tosca.datatypes.model.RequirementDefinition;
5 import com.google.gson.JsonArray;
6 import com.google.gson.JsonDeserializationContext;
7 import com.google.gson.JsonDeserializer;
8 import com.google.gson.JsonElement;
9 import com.google.gson.JsonObject;
10 import com.google.gson.JsonParseException;
11 import com.google.gson.JsonPrimitive;
12 import org.onap.sdc.tosca.datatypes.model.RequirementDefinition;
14 import java.lang.reflect.Type;
15 import java.util.Objects;
16 import java.util.Optional;
18 public class RequirementDefinitionDeserializer implements JsonDeserializer<RequirementDefinition> {
20 private static final String CAPABILITY = "capability";
21 private static final String NODE = "node";
22 private static final String RELATIONSHIP = "relationship";
23 private static final String OCCURRENCES = "occurrences";
26 public RequirementDefinition deserialize(JsonElement jsonElement, Type type,
27 JsonDeserializationContext jsonDeserializationContext)
28 throws JsonParseException {
30 JsonObject jsonObject = jsonElement.getAsJsonObject();
32 RequirementDefinition requirementDefinition = new RequirementDefinition();
33 setRequirementValues(jsonObject, requirementDefinition);
35 Optional<Object[]> occurrences = handleOccurrences(jsonObject);
36 occurrences.ifPresent(requirementDefinition::setOccurrences);
38 return requirementDefinition;
42 private void setRequirementValues(JsonObject jsonObject,
43 RequirementDefinition requirementDefinition) {
45 JsonElement capabilityElement = jsonObject.get(CAPABILITY);
46 if (!Objects.isNull(capabilityElement)) {
47 requirementDefinition.setCapability(capabilityElement.getAsString());
50 JsonElement nodeElement = jsonObject.get(NODE);
51 if (!Objects.isNull(nodeElement)) {
52 requirementDefinition.setNode(nodeElement.getAsString());
55 JsonElement relationshipElement = jsonObject.get(RELATIONSHIP);
56 if (!Objects.isNull(relationshipElement)) {
57 requirementDefinition.setRelationship(relationshipElement.getAsString());
61 private Optional<Object[]> handleOccurrences(JsonObject jsonObject) {
63 JsonElement occurrencesElement = jsonObject.get(OCCURRENCES);
65 if(Objects.isNull(occurrencesElement)){
66 return Optional.empty();
69 JsonArray occurrences = occurrencesElement.getAsJsonArray();
70 Object[] fixedOccurrences = new Object[occurrences.size()];
72 for (int i = 0; i < occurrences.size(); i++) {
73 JsonElement currElement = occurrences.get(i);
75 // values inside occurrences array can be either String or Integer
76 if (currElement.isJsonPrimitive()) {
77 JsonPrimitive jsonPrimitive = currElement.getAsJsonPrimitive();
79 if (jsonPrimitive.isNumber()) {
80 fixedOccurrences[i] = jsonPrimitive.getAsNumber().intValue();
82 fixedOccurrences[i] = jsonPrimitive.getAsString();
87 return Optional.of(fixedOccurrences);