Fix bugs in attribute outputs page
[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 ToscaSchemaDefinition convert(final EntrySchema entrySchema) {
101         if (entrySchema == null) {
102             return null;
103         }
104         final ToscaSchemaDefinition toscaSchemaDefinition = new ToscaSchemaDefinition();
105         toscaSchemaDefinition.setType(entrySchema.getType());
106         toscaSchemaDefinition.setDescription(entrySchema.getDescription());
107         return toscaSchemaDefinition;
108     }
109
110     private Object convertToToscaObject(final AttributeDefinition attributeDefinition,
111                                         String value,
112                                         final boolean preserveEmptyValue) {
113         final String name = attributeDefinition.getName();
114         final String attributeType = attributeDefinition.getType();
115         final EntrySchema schemaDefinition = attributeDefinition.getEntry_schema();
116
117         final String innerType = schemaDefinition == null ? attributeType : schemaDefinition.getType();
118         LOGGER.trace("Converting attribute '{}' of type '{}', value '{}', innerType '{}'", name, attributeType, value, innerType);
119         if (StringUtils.isEmpty(value)) {
120             value = getTypeDefaultValue(attributeType);
121             if (StringUtils.isEmpty(value)) {
122                 return null;
123             }
124         }
125         try {
126             boolean isScalar = true;
127             ToscaPropertyType predefinedType = ToscaPropertyType.isValidType(attributeType);
128             if (predefinedType == null) {
129                 //not predefined, search in existing data types
130                 final DataTypeDefinition dataTypeDefinition = dataTypes.get(attributeType);
131                 predefinedType = toscaMapValueConverter.isScalarType(dataTypeDefinition);
132                 if (predefinedType == null) {
133                     isScalar = false;
134                 }
135             } else {
136                 isScalar = ToscaPropertyType.getTypeIfScalar(predefinedType.getType()) != null;
137             }
138             final JsonElement valueAsJson = parseToJson(value);
139             if (isValueGetAttribute(valueAsJson)) {
140                 return ToscaMapValueConverter.getInstance().handleComplexJsonValue(valueAsJson.getAsJsonObject());
141             }
142             //if it has a converter
143             if (predefinedType != null && predefinedType.getValueConverter() != null) {
144                 LOGGER.trace("It's well defined type. convert it");
145                 return predefinedType.getValueConverter().convertToToscaValue(value, innerType, dataTypes);
146             }
147             //no converter but scalar
148             if (isScalar) {
149                 return toscaMapValueConverter.handleComplexJsonValue(valueAsJson);
150             }
151             //if it is a data type
152             return toscaMapValueConverter.convertDataTypeToToscaObject(innerType, dataTypes, null, false, valueAsJson,
153                 preserveEmptyValue, false);
154         } catch (final JsonParseException e) {
155             final String errorMsg = "Failed to parse json value";
156             LOGGER.error(EcompLoggerErrorCode.SCHEMA_ERROR, "Attribute Converter", errorMsg, e);
157             return null;
158         } catch (final Exception e) {
159             final String errorMsg = "Unexpected error occurred while converting attribute value to TOSCA";
160             LOGGER.error(EcompLoggerErrorCode.UNKNOWN_ERROR, "Attribute Converter", errorMsg, e);
161             return null;
162         }
163     }
164
165     private JsonElement parseToJson(final String value) {
166         final StringReader reader = new StringReader(value);
167         final JsonReader jsonReader = new JsonReader(reader);
168         jsonReader.setLenient(true);
169         return new JsonParser().parse(jsonReader);
170     }
171
172     private boolean isValueGetAttribute(final JsonElement valueAsJson) {
173         if (!valueAsJson.isJsonObject()) {
174             return false;
175         }
176         final JsonObject jsonObj = valueAsJson.getAsJsonObject();
177         return jsonObj.entrySet().size() == 1 && jsonObj.has(ToscaFunctions.GET_ATTRIBUTE.getFunctionName());
178     }
179
180     private String getTypeDefaultValue(final String attributeType) {
181         return DataTypePropertyConverter.getInstance().getDataTypePropertiesDefaultValuesRec(attributeType, dataTypes);
182     }
183
184     public void convertAndAddValue(final Map<String, Object> attribs,
185                                    final AttributeDefinition attribute) {
186         final Object convertedValue = convertToToscaObject(attribute, attribute.getValue(), false);
187         if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue) && !attribute.isGetOutputAttribute()) {
188             attribs.put(attribute.getName(), convertedValue);
189         }
190     }
191
192 }