Reformat catalog-model
[sdc.git] / catalog-model / src / main / java / org / openecomp / sdc / be / model / tosca / converters / ListConverter.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 package org.openecomp.sdc.be.model.tosca.converters;
21
22 import com.google.gson.Gson;
23 import com.google.gson.JsonArray;
24 import com.google.gson.JsonElement;
25 import com.google.gson.JsonParseException;
26 import com.google.gson.JsonParser;
27 import fj.data.Either;
28 import java.math.BigInteger;
29 import java.util.ArrayList;
30 import java.util.List;
31 import java.util.Map;
32 import org.apache.commons.lang3.tuple.ImmutablePair;
33 import org.openecomp.sdc.be.config.BeEcompErrorManager;
34 import org.openecomp.sdc.be.model.DataTypeDefinition;
35 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
36 import org.openecomp.sdc.be.model.tosca.validators.DataTypeValidatorConverter;
37 import org.openecomp.sdc.be.model.tosca.validators.ListValidator;
38 import org.openecomp.sdc.common.log.wrappers.Logger;
39 import org.openecomp.sdc.common.util.GsonFactory;
40 import org.openecomp.sdc.common.util.JsonUtils;
41
42 public class ListConverter implements PropertyValueConverter {
43
44     private static final Logger log = Logger.getLogger(ListValidator.class.getName());
45     private static ListConverter listConverter = new ListConverter();
46     private static Gson gson = GsonFactory.getGson();
47     private static JsonParser jsonParser = new JsonParser();
48     DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance();
49
50     public static ListConverter getInstance() {
51         return listConverter;
52     }
53
54     @Override
55     public String convert(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
56         Either<String, Boolean> convertWithErrorResult = this.convertWithErrorResult(value, innerType, dataTypes);
57         if (convertWithErrorResult.isRight()) {
58             return null;
59         }
60         return convertWithErrorResult.left().value();
61     }
62
63     public Either<String, Boolean> convertWithErrorResult(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
64         if (value == null || innerType == null) {
65             return Either.left(value);
66         }
67         PropertyValueConverter innerConverter;
68         ToscaPropertyType innerToscaType = ToscaPropertyType.isValidType(innerType);
69         if (innerToscaType != null) {
70             PropertyValueConverter innerConverter1;
71             switch (innerToscaType) {
72                 case STRING:
73                     innerConverter1 = ToscaPropertyType.STRING.getConverter();
74                     break;
75                 case INTEGER:
76                     innerConverter1 = ToscaPropertyType.INTEGER.getConverter();
77                     break;
78                 case FLOAT:
79                     innerConverter1 = ToscaPropertyType.FLOAT.getConverter();
80                     break;
81                 case BOOLEAN:
82                     innerConverter1 = ToscaPropertyType.BOOLEAN.getConverter();
83                     break;
84                 case JSON:
85                     innerConverter1 = ToscaPropertyType.JSON.getConverter();
86                     break;
87                 default:
88                     log.debug("inner Tosca Type is unknown");
89                     return Either.left(value);
90             }
91             innerConverter = innerConverter1;
92         } else {
93             log.debug("inner Tosca Type {} ia a complex data type.", innerType);
94             return convertComplexInnerType(value, innerType, dataTypes);
95         }
96         try {
97             ArrayList<String> newList = new ArrayList<>();
98             JsonArray jo = (JsonArray) jsonParser.parse(value);
99             if (ToscaPropertyType.JSON == innerToscaType) {
100                 return Either.left(value);
101             }
102             int size = jo.size();
103             for (int i = 0; i < size; i++) {
104                 JsonElement currentValue = jo.get(i);
105                 String element = JsonUtils.toString(currentValue);
106                 if (element == null || element.isEmpty()) {
107                     continue;
108                 }
109                 element = innerConverter.convert(element, null, dataTypes);
110                 newList.add(element);
111             }
112             switch (innerToscaType) {
113                 case STRING:
114                     value = gson.toJson(newList);
115                     break;
116                 case INTEGER:
117                     List<BigInteger> intList = new ArrayList<>();
118                     for (String str : newList) {
119                         int base = 10;
120                         if (str.contains("0x")) {
121                             str = str.replaceFirst("0x", "");
122                             base = 16;
123                         }
124                         if (str.contains("0o")) {
125                             str = str.replaceFirst("0o", "");
126                             base = 8;
127                         }
128                         intList.add(new BigInteger(str, base));
129                     }
130                     value = gson.toJson(intList);
131                     break;
132                 case FLOAT:
133                     value = "[";
134                     for (String str : newList) {
135                         value += str + ",";
136                     }
137                     value = value.substring(0, value.length() - 1);
138                     value += "]";
139                     break;
140                 case BOOLEAN:
141                     List<Boolean> boolList = new ArrayList<>();
142                     for (String str : newList) {
143                         boolList.add(Boolean.valueOf(str));
144                     }
145                     value = gson.toJson(boolList);
146                     break;
147                 default:
148                     value = gson.toJson(newList);
149                     log.debug("inner Tosca Type unknown : {}", innerToscaType);
150             }
151         } catch (JsonParseException e) {
152             log.debug("Failed to parse json : {}", value, e);
153             BeEcompErrorManager.getInstance().logBeInvalidJsonInput("List Converter");
154             return Either.right(false);
155         }
156         return Either.left(value);
157     }
158
159     private Either<String, Boolean> convertComplexInnerType(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
160         DataTypeDefinition dataTypeDefinition = allDataTypes.get(innerType);
161         if (dataTypeDefinition == null) {
162             log.debug("Cannot find data type {}", innerType);
163             return Either.right(false);
164         }
165         List<JsonElement> newList = new ArrayList<>();
166         try {
167             JsonArray jo = (JsonArray) jsonParser.parse(value);
168             int size = jo.size();
169             for (int i = 0; i < size; i++) {
170                 JsonElement currentValue = jo.get(i);
171                 if (currentValue != null) {
172                     String element = JsonUtils.toString(currentValue);
173                     ImmutablePair<JsonElement, Boolean> validateAndUpdate = dataTypeValidatorConverter
174                         .validateAndUpdate(element, dataTypeDefinition, allDataTypes);
175                     if (!validateAndUpdate.right.booleanValue()) {
176                         log.debug("Cannot parse value {} from type {} in list position {}", currentValue, innerType, i);
177                         return Either.right(false);
178                     }
179                     JsonElement newValue = validateAndUpdate.left;
180                     newList.add(newValue);
181                 }
182             }
183         } catch (Exception e) {
184             log.debug("Failed to parse the value {} of list parameter.", value);
185             return Either.right(false);
186         }
187         value = gson.toJson(newList);
188         return Either.left(value);
189     }
190 }