Catalog alignment
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / components / impl / DataTypeImportManager.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.be.components.impl;
22
23 import fj.data.Either;
24 import org.apache.commons.lang3.tuple.ImmutablePair;
25 import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum;
26 import org.openecomp.sdc.be.dao.api.ActionStatus;
27 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
28 import org.openecomp.sdc.be.impl.ComponentsUtils;
29 import org.openecomp.sdc.be.model.DataTypeDefinition;
30 import org.openecomp.sdc.be.model.PropertyDefinition;
31 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
32 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
33 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
34 import org.openecomp.sdc.be.utils.TypeUtils;
35 import org.openecomp.sdc.common.log.wrappers.Logger;
36 import org.openecomp.sdc.exception.ResponseFormat;
37 import org.springframework.stereotype.Component;
38
39 import javax.annotation.Resource;
40 import java.util.ArrayList;
41 import java.util.HashSet;
42 import java.util.List;
43 import java.util.Map;
44 import java.util.Set;
45 import java.util.stream.Collectors;
46
47 @Component("dataTypeImportManager")
48 public class DataTypeImportManager {
49
50     private static final Logger log = Logger.getLogger(DataTypeImportManager.class.getName());
51     @Resource
52     private PropertyOperation propertyOperation;
53     @Resource
54     private ComponentsUtils componentsUtils;
55     @Resource
56     private CommonImportManager commonImportManager;
57
58     public Either<List<ImmutablePair<DataTypeDefinition, Boolean>>, ResponseFormat> createDataTypes(String dataTypeYml) {
59         return commonImportManager.createElementTypes(dataTypeYml, this::createDataTypesFromYml, this::createDataTypesByDao, ElementTypeEnum.DATA_TYPE);
60     }
61
62     private Either<List<DataTypeDefinition>, ActionStatus> createDataTypesFromYml(String dataTypesYml) {
63         return commonImportManager.createElementTypesFromYml(dataTypesYml, this::createDataType);
64     }
65
66     private Either<List<ImmutablePair<DataTypeDefinition, Boolean>>, ResponseFormat> createDataTypesByDao(List<DataTypeDefinition> dataTypesToCreate) {
67
68         return commonImportManager.createElementTypesByDao(dataTypesToCreate, this::validateDataType, dataType -> new ImmutablePair<>(ElementTypeEnum.DATA_TYPE, dataType.getName()),
69                 dataTypeName -> propertyOperation.getDataTypeByNameWithoutDerived(dataTypeName), dataType -> propertyOperation.addDataType(dataType), (newDataType, oldDataType) -> propertyOperation.updateDataType(newDataType, oldDataType));
70     }
71
72     private Either<ActionStatus, ResponseFormat> validateDataType(DataTypeDefinition dataType) {
73
74         String dataTypeName = dataType.getName();
75         List<PropertyDefinition> properties = dataType.getProperties();
76         if (properties == null) {
77             // At least one parameter should be defined either in the properties
78             // section or at one of the parents
79             String derivedDataType = dataType.getDerivedFromName();
80             // If there are no properties, then we can create a data type if it
81             // is an abstract one or it derives from non abstract data type
82             if (derivedDataType == null || derivedDataType.isEmpty()) {
83                 if (!isAbstract(dataType.getName()) && !ToscaPropertyType.isScalarType(dataTypeName)) {
84                     log.debug("Data type {} must have properties unless it derives from non abstract data type", dataType.getName());
85                     ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM, dataType, null);
86                     return Either.right(responseFormat);
87                 }
88             } else {
89                 // if it is not a scalar data type and it derives from abstract
90                 // data type, we should reject the request.
91                 if (!ToscaPropertyType.isScalarType(dataTypeName) && isAbstract(derivedDataType)) {
92                     log.debug("Data type {} which derived from abstract data type must have at least one property", dataType.getName());
93                     ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM, dataType, null);
94                     return Either.right(responseFormat);
95                 }
96             }
97         } else {
98             // properties tag cannot be empty
99             if (properties.isEmpty()) {
100                 ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTIES_CANNOT_BE_EMPTY, dataType, null);
101
102                 return Either.right(responseFormat);
103             }
104
105             // check no duplicates
106             Set<String> collect = properties.stream().map(PropertyDataDefinition::getName).collect(Collectors.toSet());
107             if (collect != null && properties.size() != collect.size()) {
108                 ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_DUPLICATE_PROPERTY, dataType, null);
109
110                 return Either.right(responseFormat);
111             }
112
113             List<String> propertiesWithSameTypeAsDataType = properties.stream().filter(p -> p.getType().equals(dataType.getName())).map(PropertyDataDefinition::getName).collect(Collectors.toList());
114             if (propertiesWithSameTypeAsDataType != null && !propertiesWithSameTypeAsDataType.isEmpty()) {
115                 log.debug("The data type {} contains properties with the type {}", dataType.getName(), dataType.getName());
116                 ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE, dataType, propertiesWithSameTypeAsDataType);
117
118                 return Either.right(responseFormat);
119             }
120         }
121
122         String derivedDataType = dataType.getDerivedFromName();
123         if (derivedDataType != null) {
124             Either<DataTypeDefinition, StorageOperationStatus> derivedDataTypeByName = propertyOperation.getDataTypeByName(derivedDataType, true);
125             if (derivedDataTypeByName.isRight()) {
126                 StorageOperationStatus status = derivedDataTypeByName.right().value();
127                 if (status == StorageOperationStatus.NOT_FOUND) {
128                     ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_DERIVED_IS_MISSING, dataType, null);
129
130                     return Either.right(responseFormat);
131                 } else {
132                     ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.GENERAL_ERROR, dataType, null);
133
134                     return Either.right(responseFormat);
135
136                 }
137             } else {
138
139                 DataTypeDefinition derivedDataTypeDef = derivedDataTypeByName.left().value();
140                 if (properties != null && !properties.isEmpty() && derivedDataTypeDef!=null) {
141
142                     if (isScalarType(derivedDataTypeDef)) {
143                         ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_CANNOT_HAVE_PROPERTIES, dataType, null);
144
145                         return Either.right(responseFormat);
146                     }
147
148                     Set<String> allParentsProps = new HashSet<>();
149                     do {
150                         List<PropertyDefinition> currentParentsProps = derivedDataTypeDef.getProperties();
151                         if (currentParentsProps != null) {
152                             for (PropertyDefinition propertyDefinition : currentParentsProps) {
153                                 allParentsProps.add(propertyDefinition.getName());
154                             }
155                         }
156                         derivedDataTypeDef = derivedDataTypeDef.getDerivedFrom();
157                     } while (derivedDataTypeDef != null);
158
159                     // Check that no property is already defined in one of the
160                     // ancestors
161                     Set<String> alreadyExistPropsCollection = properties.stream().filter(p -> allParentsProps.contains(p.getName())).map(PropertyDataDefinition::getName).collect(Collectors.toSet());
162                     if (alreadyExistPropsCollection != null && !alreadyExistPropsCollection.isEmpty()) {
163                         List<String> duplicateProps = new ArrayList<>();
164                         duplicateProps.addAll(alreadyExistPropsCollection);
165                         ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR, dataType, duplicateProps);
166
167                         return Either.right(responseFormat);
168                     }
169
170                 }
171             }
172         }
173         return Either.left(ActionStatus.OK);
174     }
175
176     private boolean isAbstract(String dataTypeName) {
177
178         ToscaPropertyType isPrimitiveToscaType = ToscaPropertyType.isValidType(dataTypeName);
179
180         return isPrimitiveToscaType != null && isPrimitiveToscaType.isAbstract();
181
182     }
183
184     private boolean isScalarType(DataTypeDefinition dataTypeDef) {
185
186         boolean isScalar = false;
187         DataTypeDefinition dataType = dataTypeDef;
188
189         while (dataType != null) {
190
191             String name = dataType.getName();
192             if (ToscaPropertyType.isScalarType(name)) {
193                 isScalar = true;
194                 break;
195             }
196
197             dataType = dataType.getDerivedFrom();
198         }
199
200         return isScalar;
201     }
202
203     private DataTypeDefinition createDataType(String dataTypeName, Map<String, Object> toscaJson) {
204         DataTypeDefinition dataType = new DataTypeDefinition();
205
206         dataType.setName(dataTypeName);
207
208         if (toscaJson != null) {
209             // Description
210             commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName(), dataType::setDescription);
211             // Derived From
212             commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DERIVED_FROM.getElementName(), dataType::setDerivedFromName);
213             // Properties
214             CommonImportManager.setProperties(toscaJson, dataType::setProperties);
215         }
216         return dataType;
217     }
218
219 }