Improve test coverage
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / tosca / AttributeConverter.java
1 /*
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021 Nordix Foundation
4  *  ================================================================================
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *  Unless required by applicable law or agreed to in writing, software
11  *  distributed under the License is distributed on an "AS IS" BASIS,
12  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *  See the License for the specific language governing permissions and
14  *  limitations under the License.
15  *
16  *  SPDX-License-Identifier: Apache-2.0
17  *  ============LICENSE_END=========================================================
18  */
19
20 package org.openecomp.sdc.be.tosca;
21
22 import com.google.gson.JsonElement;
23 import com.google.gson.JsonObject;
24 import com.google.gson.JsonParseException;
25 import com.google.gson.JsonParser;
26 import com.google.gson.stream.JsonReader;
27 import java.io.StringReader;
28 import java.util.Map;
29 import org.apache.commons.lang3.StringUtils;
30 import org.onap.sdc.tosca.datatypes.model.EntrySchema;
31 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
32 import org.openecomp.sdc.be.model.AttributeDefinition;
33 import org.openecomp.sdc.be.model.DataTypeDefinition;
34 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
35 import org.openecomp.sdc.be.model.tosca.converters.DataTypePropertyConverter;
36 import org.openecomp.sdc.be.model.tosca.converters.ToscaMapValueConverter;
37 import org.openecomp.sdc.be.model.tosca.converters.ToscaValueBaseConverter;
38 import org.openecomp.sdc.be.tosca.model.ToscaAttribute;
39 import org.openecomp.sdc.be.tosca.model.ToscaSchemaDefinition;
40 import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
41 import org.openecomp.sdc.common.log.wrappers.Logger;
42 import org.openecomp.sdc.tosca.datatypes.ToscaFunctions;
43 import org.springframework.beans.factory.config.BeanDefinition;
44 import org.springframework.context.annotation.Scope;
45 import org.springframework.stereotype.Component;
46
47 /**
48  * Handles conversions between attribute objects.
49  */
50 @Component
51 @Scope(BeanDefinition.SCOPE_PROTOTYPE)
52 public class AttributeConverter {
53
54     private static final Logger LOGGER = Logger.getLogger(AttributeConverter.class);
55     private final Map<String, DataTypeDefinition> dataTypes;
56     private final ToscaMapValueConverter toscaMapValueConverter;
57
58     /**
59      * Creates an {@link AttributeConverter} with all the required data types.
60      *
61      * @param dataTypes all the data types required for the conversion
62      */
63     public AttributeConverter(final Map<String, DataTypeDefinition> dataTypes) {
64         this.dataTypes = dataTypes;
65         toscaMapValueConverter = ToscaMapValueConverter.getInstance();
66     }
67
68     /**
69      * Converts an {@link AttributeDefinition} to a {@link ToscaAttribute}.
70      *
71      * @param attributeDefinition the attribute definition to be converted
72      * @return the {@link ToscaAttribute} instance based on the the given {@link AttributeDefinition} instance
73      */
74     public ToscaAttribute convert(final AttributeDefinition attributeDefinition) {
75         final ToscaAttribute toscaAttribute = new ToscaAttribute();
76         LOGGER.trace("Converting attribute '{}' from type '{}' with default value '{}'", attributeDefinition.getName(), attributeDefinition.getType(),
77             attributeDefinition.getDefaultValue());
78         SchemaDefinition schema = attributeDefinition.getSchema();
79         if (schema != null && schema.getProperty() != null && schema.getProperty().getType() != null
80             && StringUtils.isNotEmpty(schema.getProperty().getType())) {
81             final ToscaSchemaDefinition toscaSchemaDefinition = new ToscaSchemaDefinition();
82             toscaSchemaDefinition.setType(schema.getProperty().getType());
83             toscaSchemaDefinition.setDescription(schema.getProperty().getDescription());
84             toscaAttribute.setEntrySchema(toscaSchemaDefinition);
85         }
86         toscaAttribute.setType(attributeDefinition.getType());
87         toscaAttribute.setDescription(attributeDefinition.getDescription());
88         toscaAttribute.setStatus(attributeDefinition.getStatus());
89         final Object defaultValue = convertToToscaObject(attributeDefinition, attributeDefinition.getDefaultValue(), false);
90         if (defaultValue != null) {
91             toscaAttribute.setDefault(defaultValue);
92         }
93         final Object value = convertToToscaObject(attributeDefinition, attributeDefinition.getValue(), false);
94         if (value != null) {
95             toscaAttribute.setValue(value);
96         }
97         return toscaAttribute;
98     }
99
100     private Object convertToToscaObject(final AttributeDefinition attributeDefinition,
101                                         String value,
102                                         final boolean preserveEmptyValue) {
103         final String name = attributeDefinition.getName();
104         final String attributeType = attributeDefinition.getType();
105         final EntrySchema schemaDefinition = attributeDefinition.getEntry_schema();
106
107         final String innerType = schemaDefinition == null ? attributeType : schemaDefinition.getType();
108         LOGGER.trace("Converting attribute '{}' of type '{}', value '{}', innerType '{}'", name, attributeType, value, innerType);
109         if (StringUtils.isEmpty(value)) {
110             value = getTypeDefaultValue(attributeType);
111             if (StringUtils.isEmpty(value)) {
112                 return null;
113             }
114         }
115         try {
116             boolean isScalar = true;
117             ToscaPropertyType predefinedType = ToscaPropertyType.isValidType(attributeType);
118             if (predefinedType == null) {
119                 //not predefined, search in existing data types
120                 final DataTypeDefinition dataTypeDefinition = dataTypes.get(attributeType);
121                 predefinedType = toscaMapValueConverter.isScalarType(dataTypeDefinition);
122                 if (predefinedType == null) {
123                     isScalar = false;
124                 }
125             } else {
126                 isScalar = ToscaPropertyType.getTypeIfScalar(predefinedType.getType()) != null;
127             }
128             final JsonElement valueAsJson = parseToJson(value);
129             if (isValueGetAttribute(valueAsJson)) {
130                 return ToscaMapValueConverter.getInstance().handleComplexJsonValue(valueAsJson.getAsJsonObject());
131             }
132             //if it has a converter
133             if (predefinedType != null && predefinedType.getValueConverter() != null) {
134                 LOGGER.trace("It's well defined type. convert it");
135                 return predefinedType.getValueConverter().convertToToscaValue(value, innerType, dataTypes);
136             }
137             //no converter but scalar
138             if (isScalar) {
139                 return toscaMapValueConverter.handleComplexJsonValue(valueAsJson);
140             }
141             //if it is a data type
142             return toscaMapValueConverter.convertDataTypeToToscaObject(innerType, dataTypes, null, false, valueAsJson,
143                 preserveEmptyValue, false);
144         } catch (final JsonParseException e) {
145             final String errorMsg = "Failed to parse json value";
146             LOGGER.error(EcompLoggerErrorCode.SCHEMA_ERROR, "Attribute Converter", errorMsg, e);
147             return null;
148         } catch (final Exception e) {
149             final String errorMsg = "Unexpected error occurred while converting attribute value to TOSCA";
150             LOGGER.error(EcompLoggerErrorCode.UNKNOWN_ERROR, "Attribute Converter", errorMsg, e);
151             return null;
152         }
153     }
154
155     private JsonElement parseToJson(final String value) {
156         final StringReader reader = new StringReader(value);
157         final JsonReader jsonReader = new JsonReader(reader);
158         jsonReader.setLenient(true);
159         return new JsonParser().parse(jsonReader);
160     }
161
162     private boolean isValueGetAttribute(final JsonElement valueAsJson) {
163         if (!valueAsJson.isJsonObject()) {
164             return false;
165         }
166         final JsonObject jsonObj = valueAsJson.getAsJsonObject();
167         return jsonObj.entrySet().size() == 1 && jsonObj.has(ToscaFunctions.GET_ATTRIBUTE.getFunctionName());
168     }
169
170     private String getTypeDefaultValue(final String attributeType) {
171         return DataTypePropertyConverter.getInstance().getDataTypePropertiesDefaultValuesRec(attributeType, dataTypes);
172     }
173
174     public void convertAndAddValue(final Map<String, Object> attribs,
175                                    final AttributeDefinition attribute) {
176         final Object convertedValue = convertToToscaObject(attribute, attribute.getValue(), false);
177         if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue) && !attribute.isGetOutputAttribute()) {
178             attribs.put(attribute.getName(), convertedValue);
179         }
180     }
181
182 }