aboutsummaryrefslogtreecommitdiffstats
path: root/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/MapConverter.java
blob: 3be610ec535209d76b84fd77c4d73d8cf5e5c611 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
/*-
 * ============LICENSE_START=======================================================
 * SDC
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * 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.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.openecomp.sdc.be.model.tosca.converters;

import com.google.common.base.Strings;
import com.google.gson.*;
import fj.data.Either;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
import org.openecomp.sdc.be.model.tosca.validators.DataTypeValidatorConverter;
import org.openecomp.sdc.be.model.tosca.validators.ListValidator;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.GsonFactory;
import org.openecomp.sdc.common.util.JsonUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class MapConverter implements PropertyValueConverter {

    private static MapConverter mapConverter = new MapConverter();
    private static Gson gson = GsonFactory.getGson();
    private static final Logger log = Logger.getLogger(ListValidator.class.getName());

    DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance();

    private static JsonParser jsonParser = new JsonParser();

    public static MapConverter getInstance() {
        return mapConverter;
    }

    public String convert(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {

        Either<String, Boolean> convertWithErrorResult = this.convertWithErrorResult(value, innerType, dataTypes);
        if (convertWithErrorResult.isRight()) {
            return null;
        }

        return convertWithErrorResult.left().value();
    }

    public Either<String, Boolean> convertWithErrorResult(String value, String innerType,
            Map<String, DataTypeDefinition> dataTypes) {

        if (Strings.isNullOrEmpty(value) || innerType == null) {
            return Either.left(value);
        }

        PropertyValueConverter innerConverter;
        PropertyValueConverter keyConverter = ToscaPropertyType.STRING.getConverter();
        ToscaPropertyType innerToscaType = ToscaPropertyType.isValidType(innerType);

        if (innerToscaType != null) {
            switch (innerToscaType) {
            case STRING:
                innerConverter = ToscaPropertyType.STRING.getConverter();
                break;
            case INTEGER:
                innerConverter = ToscaPropertyType.INTEGER.getConverter();
                break;
            case FLOAT:
                innerConverter = ToscaPropertyType.FLOAT.getConverter();
                break;
            case BOOLEAN:
                innerConverter = ToscaPropertyType.BOOLEAN.getConverter();
                break;
            case JSON:
                innerConverter = ToscaPropertyType.JSON.getConverter();
                break;
            default:
                log.debug("inner Tosca Type is unknown");
                return Either.left(value);
            }

        } else {

            log.debug("inner Tosca Type {} ia a complex data type.", innerType);

            return convertComplexInnerType(value, innerType, keyConverter,
                    dataTypes);

        }

        try {
            Map<String, String> newMap = new HashMap<>();

            JsonElement jsonObject = jsonParser.parse(value);
            JsonObject asJsonObject = jsonObject.getAsJsonObject();
            Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet();
            for (Entry<String, JsonElement> entry : entrySet) {
                String key = entry.getKey();
                JsonElement jsonValue = entry.getValue();

                key = keyConverter.convert(entry.getKey(), null, dataTypes);

                String element = JsonUtils.toString(jsonValue);

                String val = innerConverter.convert(element, null, dataTypes);
                newMap.put(key, val);
            }

            String objVal;
            switch (innerToscaType) {
            case STRING:
                value = gson.toJson(newMap);
                break;
            case INTEGER:
                String key = null;
                Map<String, Integer> intMap = new HashMap<>();
                for (Map.Entry<String, String> entry : newMap.entrySet()) {
                    objVal = entry.getValue();
                    key = entry.getKey();
                    if (objVal != null) {
                        intMap.put(key, Integer.valueOf(objVal.toString()));
                    } else {
                        intMap.put(key, null);
                    }

                }
                value = gson.toJson(intMap);
                break;
            case FLOAT:
                value = "{";
                for (Map.Entry<String, String> entry : newMap.entrySet()) {
                    objVal = entry.getValue();
                    if (objVal == null) {
                        objVal = "null";
                    }
                    key = entry.getKey();
                    value += "\"" + key + "\":" + objVal.toString() + ",";
                }
                value = value.substring(0, value.length() - 1);
                value += "}";
                break;
            case BOOLEAN:
                Map<String, Boolean> boolMap = new HashMap<>();
                for (Map.Entry<String, String> entry : newMap.entrySet()) {
                    objVal = entry.getValue();
                    key = entry.getKey();
                    if (objVal != null) {
                        boolMap.put(key, Boolean.valueOf(objVal.toString()));
                    } else {
                        boolMap.put(key, null);
                    }
                }
                value = gson.toJson(boolMap);
                break;
            default:
                value = gson.toJson(newMap);
                log.debug("inner Tosca Type unknown : {}", innerToscaType);
            }
        } catch (JsonParseException e) {
            log.debug("Failed to parse json : {}", value, e);
            BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Map Converter");
            return Either.right(false);
        }

        return Either.left(value);

    }

    /**
     * convert the json value of map when the inner type is a complex data type
     *
     * @param value
     * @param innerType
     * @param keyConverter
     * @param allDataTypes
     * @return
     */
    private Either<String, Boolean> convertComplexInnerType(String value, String innerType,
            PropertyValueConverter keyConverter, Map<String, DataTypeDefinition> allDataTypes) {

        DataTypeDefinition dataTypeDefinition = allDataTypes.get(innerType);
        if (dataTypeDefinition == null) {
            log.debug("Cannot find data type {}", innerType);
            return Either.right(false);
        }

        Map<String, JsonElement> newMap = new HashMap<>();

        try {

            JsonElement jsonObject = jsonParser.parse(value);
            JsonObject asJsonObject = jsonObject.getAsJsonObject();
            Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet();
            for (Entry<String, JsonElement> entry : entrySet) {
                String currentKey = keyConverter.convert(entry.getKey(), null, allDataTypes);

                JsonElement currentValue = entry.getValue();

                if (currentValue != null) {

                    String element = JsonUtils.toString(currentValue);

                    ImmutablePair<JsonElement, Boolean> validateAndUpdate = dataTypeValidatorConverter
                            .validateAndUpdate(element, dataTypeDefinition, allDataTypes);
                    if (!validateAndUpdate.right.booleanValue()) {
                        log.debug("Cannot parse value {} from type {} of key {}",currentValue,innerType,currentKey);
                        return Either.right(false);
                    }
                    JsonElement newValue = validateAndUpdate.left;
                    newMap.put(currentKey, newValue);
                } else {
                    newMap.put(currentKey, null);
                }
            }

        } catch (Exception e) {
            log.debug("Cannot parse value {} of map from inner type {}", value, innerType);
            return Either.right(false);
        }

        value = gson.toJson(newMap);
        return Either.left(value);
    }

}