1 package org.openecomp.core.utilities.deserializers;
3 import com.google.gson.JsonArray;
4 import com.google.gson.JsonDeserializationContext;
5 import com.google.gson.JsonDeserializer;
6 import com.google.gson.JsonElement;
7 import com.google.gson.JsonObject;
8 import com.google.gson.JsonParseException;
9 import com.google.gson.JsonPrimitive;
10 import org.onap.sdc.tosca.datatypes.model.RequirementDefinition;
12 import java.lang.reflect.Type;
13 import java.util.Objects;
14 import java.util.Optional;
16 public class RequirementDefinitionDeserializer implements JsonDeserializer<RequirementDefinition> {
18 private static final String CAPABILITY = "capability";
19 private static final String NODE = "node";
20 private static final String RELATIONSHIP = "relationship";
21 private static final String OCCURRENCES = "occurrences";
24 public RequirementDefinition deserialize(JsonElement jsonElement, Type type,
25 JsonDeserializationContext jsonDeserializationContext)
26 throws JsonParseException {
28 JsonObject jsonObject = jsonElement.getAsJsonObject();
30 RequirementDefinition requirementDefinition = new RequirementDefinition();
31 setRequirementValues(jsonObject, requirementDefinition);
33 Optional<Object[]> occurrences = handleOccurrences(jsonObject);
34 occurrences.ifPresent(requirementDefinition::setOccurrences);
36 return requirementDefinition;
40 private void setRequirementValues(JsonObject jsonObject,
41 RequirementDefinition requirementDefinition) {
43 JsonElement capabilityElement = jsonObject.get(CAPABILITY);
44 if (!Objects.isNull(capabilityElement)) {
45 requirementDefinition.setCapability(capabilityElement.getAsString());
48 JsonElement nodeElement = jsonObject.get(NODE);
49 if (!Objects.isNull(nodeElement)) {
50 requirementDefinition.setNode(nodeElement.getAsString());
53 JsonElement relationshipElement = jsonObject.get(RELATIONSHIP);
54 if (!Objects.isNull(relationshipElement)) {
55 requirementDefinition.setRelationship(relationshipElement.getAsString());
59 private Optional<Object[]> handleOccurrences(JsonObject jsonObject) {
61 JsonElement occurrencesElement = jsonObject.get(OCCURRENCES);
63 if(Objects.isNull(occurrencesElement)){
64 return Optional.empty();
67 JsonArray occurrences = occurrencesElement.getAsJsonArray();
68 Object[] fixedOccurrences = new Object[occurrences.size()];
70 for (int i = 0; i < occurrences.size(); i++) {
71 JsonElement currElement = occurrences.get(i);
73 // values inside occurrences array can be either String or Integer
74 if (currElement.isJsonPrimitive()) {
75 JsonPrimitive jsonPrimitive = currElement.getAsJsonPrimitive();
77 if (jsonPrimitive.isNumber()) {
78 fixedOccurrences[i] = jsonPrimitive.getAsNumber().intValue();
80 fixedOccurrences[i] = jsonPrimitive.getAsString();
85 return Optional.of(fixedOccurrences);