Implement Attributes/Outputs BE (part 2)
[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.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.model.ToscaAttribute;
36 import org.openecomp.sdc.common.log.wrappers.Logger;
37 import org.openecomp.sdc.tosca.datatypes.ToscaFunctions;
38 import org.springframework.beans.factory.config.BeanDefinition;
39 import org.springframework.context.annotation.Scope;
40 import org.springframework.stereotype.Component;
41
42 /**
43  * Handles conversions between attribute objects.
44  */
45 @Component
46 @Scope(BeanDefinition.SCOPE_PROTOTYPE)
47 public class AttributeConverter {
48
49     private static final Logger LOGGER = Logger.getLogger(AttributeConverter.class);
50     private final Map<String, DataTypeDefinition> dataTypes;
51     private final ToscaMapValueConverter toscaMapValueConverter;
52
53     /**
54      * Creates an {@link AttributeConverter} with all the required data types.
55      *
56      * @param dataTypes all the data types required for the conversion
57      */
58     public AttributeConverter(final Map<String, DataTypeDefinition> dataTypes) {
59         this.dataTypes = dataTypes;
60         toscaMapValueConverter = ToscaMapValueConverter.getInstance();
61     }
62
63     /**
64      * Converts and {@link AttributeDefinition} to a {@link ToscaAttribute}.
65      *
66      * @param attributeDefinition the attribute definition to be converted
67      * @return the {@link ToscaAttribute} instance based on the the given {@link AttributeDefinition} instance
68      */
69     public ToscaAttribute convert(final AttributeDefinition attributeDefinition) {
70         final ToscaAttribute toscaAttribute = new ToscaAttribute();
71         LOGGER.trace("Converting attribute '{}' from type '{}' with default value '{}'",
72             attributeDefinition.getName(), attributeDefinition.getType(), attributeDefinition.getDefaultValue());
73         toscaAttribute.setType(attributeDefinition.getType());
74         toscaAttribute.setDescription(attributeDefinition.getDescription());
75         toscaAttribute.setStatus(attributeDefinition.getStatus());
76         final Object defaultValue = convertToToscaObject(attributeDefinition.getName(), attributeDefinition.getType(),
77             attributeDefinition.getDefaultValue(), attributeDefinition.getEntry_schema(), false);
78         if (defaultValue != null) {
79             toscaAttribute.setDefault(defaultValue);
80         }
81         final Object value = convertToToscaObject(attributeDefinition.getName(), attributeDefinition.getType(),
82             attributeDefinition.getValue(), attributeDefinition.getEntry_schema(), false);
83         if (value != null) {
84             toscaAttribute.setValue(value);
85         }
86
87         return toscaAttribute;
88     }
89
90     private Object convertToToscaObject(final String name, final String attributeType, String value,
91                                         final EntrySchema schemaDefinition, final boolean preserveEmptyValue) {
92         final String innerType = schemaDefinition == null ? attributeType : schemaDefinition.getType();
93         LOGGER.trace("Converting attribute '{}' of type '{}', value '{}', innerType '{}'",
94             name, attributeType, value, innerType);
95         if (StringUtils.isEmpty(value)) {
96             value = getTypeDefaultValue(attributeType);
97             if (StringUtils.isEmpty(value)) {
98                 return null;
99             }
100         }
101
102         try {
103             boolean isScalar = true;
104
105             ToscaPropertyType predefinedType = ToscaPropertyType.isValidType(attributeType);
106             if (predefinedType == null) {
107                 //not predefined, search in existing data types
108                 final DataTypeDefinition dataTypeDefinition = dataTypes.get(attributeType);
109                 predefinedType = toscaMapValueConverter.isScalarType(dataTypeDefinition);
110                 if (predefinedType == null) {
111                     isScalar = false;
112                 }
113             } else {
114                 isScalar = ToscaPropertyType.getTypeIfScalar(predefinedType.getType()) != null;
115             }
116             final JsonElement valueAsJson = parseToJson(value);
117             if (valueAsJson.isJsonObject()) {
118                 final JsonObject jsonObj = valueAsJson.getAsJsonObject();
119                 if (jsonObj.entrySet().size() == 1 && jsonObj.has(ToscaFunctions.GET_ATTRIBUTE.getFunctionName())) {
120                     return ToscaMapValueConverter.getInstance().handleComplexJsonValue(valueAsJson);
121                 }
122             }
123             //if it has a converter
124             if (predefinedType != null && predefinedType.getValueConverter() != null) {
125                 LOGGER.trace("It's well defined type. convert it");
126                 return predefinedType.getValueConverter().convertToToscaValue(value, innerType, dataTypes);
127             }
128             //no converter but scalar
129             if (isScalar) {
130                 return toscaMapValueConverter.handleComplexJsonValue(valueAsJson);
131             }
132
133             //if it is a data type
134             return toscaMapValueConverter.convertDataTypeToToscaObject(
135                 innerType, dataTypes, null, false, valueAsJson, preserveEmptyValue);
136
137         } catch (final Exception e) {
138             LOGGER.debug("convertToToscaValue failed to parse json value :", e);
139             return null;
140         }
141
142     }
143
144     private JsonElement parseToJson(final String value) {
145         final StringReader reader = new StringReader(value);
146         final JsonReader jsonReader = new JsonReader(reader);
147         jsonReader.setLenient(true);
148         return new JsonParser().parse(jsonReader);
149     }
150
151     private String getTypeDefaultValue(final String attributeType) {
152         return DataTypePropertyConverter.getInstance().getDataTypePropertiesDefaultValuesRec(attributeType, dataTypes);
153     }
154
155 }