Reformat catalog-be
[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 package org.openecomp.sdc.be.tosca;
20
21 import com.google.gson.JsonElement;
22 import com.google.gson.JsonObject;
23 import com.google.gson.JsonParseException;
24 import com.google.gson.JsonParser;
25 import com.google.gson.stream.JsonReader;
26 import java.io.StringReader;
27 import java.util.Map;
28 import org.apache.commons.lang3.StringUtils;
29 import org.onap.sdc.tosca.datatypes.model.EntrySchema;
30 import org.openecomp.sdc.be.model.AttributeDefinition;
31 import org.openecomp.sdc.be.model.DataTypeDefinition;
32 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
33 import org.openecomp.sdc.be.model.tosca.converters.DataTypePropertyConverter;
34 import org.openecomp.sdc.be.model.tosca.converters.ToscaMapValueConverter;
35 import org.openecomp.sdc.be.tosca.exception.ToscaConversionException;
36 import org.openecomp.sdc.be.tosca.model.ToscaAttribute;
37 import org.openecomp.sdc.be.tosca.model.ToscaSchemaDefinition;
38 import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
39 import org.openecomp.sdc.common.log.wrappers.Logger;
40 import org.openecomp.sdc.tosca.datatypes.ToscaFunctions;
41 import org.springframework.beans.factory.config.BeanDefinition;
42 import org.springframework.context.annotation.Scope;
43 import org.springframework.stereotype.Component;
44
45 /**
46  * Handles conversions between attribute objects.
47  */
48 @Component
49 @Scope(BeanDefinition.SCOPE_PROTOTYPE)
50 public class AttributeConverter {
51
52     private static final Logger LOGGER = Logger.getLogger(AttributeConverter.class);
53     private final Map<String, DataTypeDefinition> dataTypes;
54     private final ToscaMapValueConverter toscaMapValueConverter;
55
56     /**
57      * Creates an {@link AttributeConverter} with all the required data types.
58      *
59      * @param dataTypes all the data types required for the conversion
60      */
61     public AttributeConverter(final Map<String, DataTypeDefinition> dataTypes) {
62         this.dataTypes = dataTypes;
63         toscaMapValueConverter = ToscaMapValueConverter.getInstance();
64     }
65
66     /**
67      * Converts an {@link AttributeDefinition} to a {@link ToscaAttribute}.
68      *
69      * @param attributeDefinition the attribute definition to be converted
70      * @return the {@link ToscaAttribute} instance based on the the given {@link AttributeDefinition} instance
71      */
72     public ToscaAttribute convert(final AttributeDefinition attributeDefinition) throws ToscaConversionException {
73         final ToscaAttribute toscaAttribute = new ToscaAttribute();
74         LOGGER.trace("Converting attribute '{}' from type '{}' with default value '{}'", attributeDefinition.getName(), attributeDefinition.getType(),
75             attributeDefinition.getDefaultValue());
76         toscaAttribute.setEntrySchema(convert(attributeDefinition.getEntry_schema()));
77         toscaAttribute.setType(attributeDefinition.getType());
78         toscaAttribute.setDescription(attributeDefinition.getDescription());
79         toscaAttribute.setStatus(attributeDefinition.getStatus());
80         final Object defaultValue = convertToToscaObject(attributeDefinition.getName(), attributeDefinition.getType(),
81             attributeDefinition.getDefaultValue(), attributeDefinition.getEntry_schema(), false);
82         if (defaultValue != null) {
83             toscaAttribute.setDefault(defaultValue);
84         }
85         final Object value = convertToToscaObject(attributeDefinition.getName(), attributeDefinition.getType(), attributeDefinition.getValue(),
86             attributeDefinition.getEntry_schema(), false);
87         if (value != null) {
88             toscaAttribute.setValue(value);
89         }
90         return toscaAttribute;
91     }
92
93     private ToscaSchemaDefinition convert(final EntrySchema entrySchema) {
94         if (entrySchema == null) {
95             return null;
96         }
97         final ToscaSchemaDefinition toscaSchemaDefinition = new ToscaSchemaDefinition();
98         toscaSchemaDefinition.setType(entrySchema.getType());
99         toscaSchemaDefinition.setDescription(entrySchema.getDescription());
100         return toscaSchemaDefinition;
101     }
102
103     private Object convertToToscaObject(final String name, final String attributeType, String value, final EntrySchema schemaDefinition,
104                                         final boolean preserveEmptyValue) throws ToscaConversionException {
105         final String innerType = schemaDefinition == null ? attributeType : schemaDefinition.getType();
106         LOGGER.trace("Converting attribute '{}' of type '{}', value '{}', innerType '{}'", name, attributeType, value, innerType);
107         if (StringUtils.isEmpty(value)) {
108             value = getTypeDefaultValue(attributeType);
109             if (StringUtils.isEmpty(value)) {
110                 return null;
111             }
112         }
113         try {
114             boolean isScalar = true;
115             ToscaPropertyType predefinedType = ToscaPropertyType.isValidType(attributeType);
116             if (predefinedType == null) {
117                 //not predefined, search in existing data types
118                 final DataTypeDefinition dataTypeDefinition = dataTypes.get(attributeType);
119                 predefinedType = toscaMapValueConverter.isScalarType(dataTypeDefinition);
120                 if (predefinedType == null) {
121                     isScalar = false;
122                 }
123             } else {
124                 isScalar = ToscaPropertyType.getTypeIfScalar(predefinedType.getType()) != null;
125             }
126             final JsonElement valueAsJson = parseToJson(value);
127             if (isValueGetAttribute(valueAsJson)) {
128                 return ToscaMapValueConverter.getInstance().handleComplexJsonValue(valueAsJson.getAsJsonObject());
129             }
130             //if it has a converter
131             if (predefinedType != null && predefinedType.getValueConverter() != null) {
132                 LOGGER.trace("It's well defined type. convert it");
133                 return predefinedType.getValueConverter().convertToToscaValue(value, innerType, dataTypes);
134             }
135             //no converter but scalar
136             if (isScalar) {
137                 return toscaMapValueConverter.handleComplexJsonValue(valueAsJson);
138             }
139             //if it is a data type
140             return toscaMapValueConverter.convertDataTypeToToscaObject(innerType, dataTypes, null, false, valueAsJson, preserveEmptyValue);
141         } catch (final JsonParseException e) {
142             final String errorMsg = "Failed to parse json value";
143             LOGGER.error(EcompLoggerErrorCode.SCHEMA_ERROR, "Attribute Converter", errorMsg, e);
144             throw new ToscaConversionException(errorMsg, e);
145         } catch (final Exception e) {
146             final String errorMsg = "Unexpected error occurred while converting attribute value to TOSCA";
147             LOGGER.error(EcompLoggerErrorCode.UNKNOWN_ERROR, "Attribute Converter", errorMsg, e);
148             throw new ToscaConversionException(errorMsg, e);
149         }
150     }
151
152     private JsonElement parseToJson(final String value) {
153         final StringReader reader = new StringReader(value);
154         final JsonReader jsonReader = new JsonReader(reader);
155         jsonReader.setLenient(true);
156         return new JsonParser().parse(jsonReader);
157     }
158
159     private boolean isValueGetAttribute(final JsonElement valueAsJson) {
160         if (!valueAsJson.isJsonObject()) {
161             return false;
162         }
163         final JsonObject jsonObj = valueAsJson.getAsJsonObject();
164         return jsonObj.entrySet().size() == 1 && jsonObj.has(ToscaFunctions.GET_ATTRIBUTE.getFunctionName());
165     }
166
167     private String getTypeDefaultValue(final String attributeType) {
168         return DataTypePropertyConverter.getInstance().getDataTypePropertiesDefaultValuesRec(attributeType, dataTypes);
169     }
170 }