Implement 'Update Service by importing Tosca Template'-story
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / components / impl / ResourceImportManager.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  * Modifications copyright (c) 2019 Nokia
20  * ================================================================================
21  */
22 package org.openecomp.sdc.be.components.impl;
23
24 import static org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaElementOperation.createDataType;
25 import static org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaElementOperation.createDataTypeDefinitionWithName;
26
27 import fj.data.Either;
28 import java.util.ArrayList;
29 import java.util.Arrays;
30 import java.util.Collections;
31 import java.util.Comparator;
32 import java.util.EnumMap;
33 import java.util.HashMap;
34 import java.util.HashSet;
35 import java.util.Iterator;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.Map.Entry;
39 import java.util.Optional;
40 import java.util.Set;
41 import java.util.function.Function;
42 import java.util.regex.Pattern;
43 import java.util.stream.Collectors;
44 import javax.servlet.ServletContext;
45 import org.apache.commons.codec.binary.Base64;
46 import org.apache.commons.collections4.CollectionUtils;
47 import org.apache.commons.collections4.MapUtils;
48 import org.apache.commons.lang3.StringUtils;
49 import org.apache.commons.lang3.tuple.ImmutablePair;
50 import org.openecomp.sdc.be.auditing.api.AuditEventFactory;
51 import org.openecomp.sdc.be.auditing.impl.AuditingManager;
52 import org.openecomp.sdc.be.auditing.impl.resourceadmin.AuditImportResourceAdminEventFactory;
53 import org.openecomp.sdc.be.components.csar.CsarInfo;
54 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
55 import org.openecomp.sdc.be.components.impl.ImportUtils.Constants;
56 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
57 import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaElementTypeEnum;
58 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
59 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
60 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
61 import org.openecomp.sdc.be.config.BeEcompErrorManager;
62 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
63 import org.openecomp.sdc.be.dao.api.ActionStatus;
64 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphDao;
65 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
66 import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
67 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
68 import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
69 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
70 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
71 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
72 import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
73 import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
74 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
75 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
76 import org.openecomp.sdc.be.impl.ComponentsUtils;
77 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
78 import org.openecomp.sdc.be.model.ArtifactDefinition;
79 import org.openecomp.sdc.be.model.AttributeDefinition;
80 import org.openecomp.sdc.be.model.CapabilityDefinition;
81 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
82 import org.openecomp.sdc.be.model.DataTypeDefinition;
83 import org.openecomp.sdc.be.model.DefaultUploadResourceInfo;
84 import org.openecomp.sdc.be.model.InterfaceDefinition;
85 import org.openecomp.sdc.be.model.LifecycleStateEnum;
86 import org.openecomp.sdc.be.model.NodeTypesMetadataList;
87 import org.openecomp.sdc.be.model.NullNodeTypeMetadata;
88 import org.openecomp.sdc.be.model.PropertyDefinition;
89 import org.openecomp.sdc.be.model.RequirementDefinition;
90 import org.openecomp.sdc.be.model.Resource;
91 import org.openecomp.sdc.be.model.UploadResourceInfo;
92 import org.openecomp.sdc.be.model.User;
93 import org.openecomp.sdc.be.model.category.CategoryDefinition;
94 import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
95 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
96 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
97 import org.openecomp.sdc.be.model.mapper.NodeTypeMetadataMapper;
98 import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
99 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
100 import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation;
101 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
102 import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
103 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
104 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
105 import org.openecomp.sdc.be.utils.TypeUtils;
106 import org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum;
107 import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
108 import org.openecomp.sdc.common.log.wrappers.Logger;
109 import org.openecomp.sdc.common.util.ThreadLocalsHolder;
110 import org.openecomp.sdc.common.util.ValidationUtils;
111 import org.openecomp.sdc.exception.ResponseFormat;
112 import org.springframework.beans.factory.annotation.Autowired;
113 import org.springframework.web.context.WebApplicationContext;
114 import org.yaml.snakeyaml.Yaml;
115
116 @org.springframework.stereotype.Component("resourceImportManager")
117 public class ResourceImportManager {
118
119     static final Pattern PROPERTY_NAME_PATTERN_IGNORE_LENGTH = Pattern.compile("['\\w\\s\\-\\:]+");
120     private static final Logger log = Logger.getLogger(ResourceImportManager.class);
121     private final InterfaceDefinitionHandler interfaceDefinitionHandler;
122     private final ComponentsUtils componentsUtils;
123     private final CapabilityTypeOperation capabilityTypeOperation;
124     private final JanusGraphDao janusGraphDao;
125     private ServletContext servletContext;
126     private AuditingManager auditingManager;
127     private ResourceBusinessLogic resourceBusinessLogic;
128     @Autowired
129     private ServiceBusinessLogic serviceBusinessLogic;
130     private IGraphLockOperation graphLockOperation;
131     private ToscaOperationFacade toscaOperationFacade;
132     private ResponseFormatManager responseFormatManager;
133
134     @Autowired
135     public ResourceImportManager(final ComponentsUtils componentsUtils, final CapabilityTypeOperation capabilityTypeOperation,
136                                  final InterfaceDefinitionHandler interfaceDefinitionHandler, final JanusGraphDao janusGraphDao) {
137         this.componentsUtils = componentsUtils;
138         this.capabilityTypeOperation = capabilityTypeOperation;
139         this.interfaceDefinitionHandler = interfaceDefinitionHandler;
140         this.janusGraphDao = janusGraphDao;
141     }
142
143     public ServiceBusinessLogic getServiceBusinessLogic() {
144         return serviceBusinessLogic;
145     }
146
147     public void setServiceBusinessLogic(ServiceBusinessLogic serviceBusinessLogic) {
148         this.serviceBusinessLogic = serviceBusinessLogic;
149     }
150
151     @Autowired
152     public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) {
153         this.toscaOperationFacade = toscaOperationFacade;
154     }
155
156     public ImmutablePair<Resource, ActionStatus> importNormativeResource(final String resourceYml, final UploadResourceInfo resourceMetaData,
157                                                                          final User creator, final boolean createNewVersion, final boolean needLock,
158                                                                          final boolean isInTransaction) {
159         LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction();
160         lifecycleChangeInfo.setUserRemarks("certification on import");
161         Function<Resource, Boolean> validator = resource -> resourceBusinessLogic.validatePropertiesDefaultValues(resource);
162         return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, createNewVersion,
163             needLock, null, null, false, null, null, false);
164     }
165
166     public void importAllNormativeResource(final String resourcesYaml, final NodeTypesMetadataList nodeTypesMetadataList, final User user,
167                                            final boolean createNewVersion, final boolean needLock) {
168         final Map<String, Object> nodeTypesYamlMap;
169         try {
170             nodeTypesYamlMap = new Yaml().load(resourcesYaml);
171         } catch (final Exception e) {
172             log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, ResourceImportManager.class.getName(), "Could not parse node types YAML", e);
173             throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TYPES_YAML);
174         }
175         if (!nodeTypesYamlMap.containsKey(ToscaTagNamesEnum.NODE_TYPES.getElementName())) {
176             return;
177         }
178         final Map<String, Object> nodeTypesMap = (Map<String, Object>) nodeTypesYamlMap.get(ToscaTagNamesEnum.NODE_TYPES.getElementName());
179         importAllNormativeResource(nodeTypesMap, nodeTypesMetadataList, user, "", createNewVersion,needLock);
180     }
181
182     public void importAllNormativeResource(final  Map<String, Object> nodeTypesMap, final NodeTypesMetadataList nodeTypesMetadataList,
183                                            final User user, String model, final boolean createNewVersion, final boolean needLock) {
184         try {
185             nodeTypesMetadataList.getNodeMetadataList().forEach(nodeTypeMetadata -> {
186                 final String nodeTypeToscaName = nodeTypeMetadata.getToscaName();
187                 final Map<String, Object> nodeTypeMap = (Map<String, Object>) nodeTypesMap.get(nodeTypeToscaName);
188                 if (nodeTypeMap == null) {
189                     log.warn(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, ResourceImportManager.class.getName(),
190                         "Could not find given node type '{}'. The node will not be created.", nodeTypeToscaName);
191                 } else {
192                     final Map<String, Map<String, Map<String, Object>>> nodeTypeDefinitionMap =
193                         Map.of(ToscaTagNamesEnum.NODE_TYPES.getElementName(),
194                             Map.of(nodeTypeToscaName, nodeTypeMap)
195                         );
196                     final String nodeTypeYaml = new Yaml().dump(nodeTypeDefinitionMap);
197                     UploadResourceInfo uploadResourceInfo = NodeTypeMetadataMapper.mapTo(nodeTypeMetadata);
198                     if (uploadResourceInfo instanceof DefaultUploadResourceInfo) {
199                         uploadResourceInfo.setModel(model);
200                         uploadResourceInfo.setContactId(user.getUserId());
201                     }
202                     importNormativeResource(nodeTypeYaml, uploadResourceInfo, user, createNewVersion, needLock, true);
203                 }
204             });
205             janusGraphDao.commit();
206         } catch (final Exception e) {
207             janusGraphDao.rollback();
208             throw e;
209         }
210     }
211
212     public ImmutablePair<Resource, ActionStatus> importCertifiedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator,
213                                                                          Function<Resource, Boolean> validationFunction,
214                                                                          LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean isInTransaction,
215                                                                          boolean createNewVersion, boolean needLock,
216                                                                          Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
217                                                                          List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
218                                                                          boolean forceCertificationAllowed, CsarInfo csarInfo, String nodeName,
219                                                                          boolean isNested) {
220         Resource resource = new Resource();
221         ImmutablePair<Resource, ActionStatus> responsePair = new ImmutablePair<>(resource, ActionStatus.CREATED);
222         Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> response = Either.left(responsePair);
223         String latestCertifiedResourceId = null;
224         try {
225             boolean shouldBeCertified = nodeTypeArtifactsToHandle == null || nodeTypeArtifactsToHandle.isEmpty();
226             setConstantMetaData(resource, shouldBeCertified);
227             setResourceMetaData(resource, resourceYml, resourceMetaData);
228             populateResourceFromYaml(resourceYml, resource);
229             validationFunction.apply(resource);
230             resource.getComponentMetadataDefinition().getMetadataDataDefinition().setNormative(resourceMetaData.isNormative());
231             checkResourceExists(createNewVersion, csarInfo, resource);
232             resource = resourceBusinessLogic
233                 .createOrUpdateResourceByImport(resource, creator, true, isInTransaction, needLock, csarInfo, nodeName, isNested).left;
234             Resource changeStateResponse;
235             if (nodeTypeArtifactsToHandle != null && !nodeTypeArtifactsToHandle.isEmpty()) {
236                 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = resourceBusinessLogic
237                     .handleNodeTypeArtifacts(resource, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, creator, isInTransaction, false);
238                 if (handleNodeTypeArtifactsRes.isRight()) {
239                     //TODO: should be used more correct action
240                     throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
241                 }
242             }
243             latestCertifiedResourceId = getLatestCertifiedResourceId(resource);
244             changeStateResponse = resourceBusinessLogic
245                 .propagateStateToCertified(creator, resource, lifecycleChangeInfo, isInTransaction, needLock, forceCertificationAllowed);
246             responsePair = new ImmutablePair<>(changeStateResponse, response.left().value().right);
247         } catch (RuntimeException e) {
248             handleImportResourceException(resourceMetaData, creator, true, e);
249         } finally {
250             if (latestCertifiedResourceId != null && needLock) {
251                 log.debug("unlock resource {}", latestCertifiedResourceId);
252                 graphLockOperation.unlockComponent(latestCertifiedResourceId, NodeTypeEnum.Resource);
253             }
254         }
255         return responsePair;
256     }
257
258     private void checkResourceExists(final boolean isCreate, final CsarInfo csarInfo, final Resource resource) {
259         if (isCreate) {
260             checkResourceExistsOnCreate(resource, csarInfo);
261         } else {
262             checkResourceExistsOnUpdate(resource);
263         }
264     }
265
266     private void checkResourceExistsOnCreate(final Resource resource, final CsarInfo csarInfo) {
267         if (isCsarPresent(csarInfo)) {
268             return;
269         }
270         final Either<Resource, StorageOperationStatus> resourceEither =
271             toscaOperationFacade.getComponentByNameAndVendorRelease(resource.getComponentType(), resource.getName(),
272                 resource.getVendorRelease(), JsonParseFlagEnum.ParseAll, resource.getModel());
273         if (resourceEither.isLeft() && toscaOperationFacade.isNodeAssociatedToModel(resource.getModel(), resource)) {
274             if (resource.getModel() == null) {
275                 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_WITH_VENDOR_RELEASE_ALREADY_EXISTS,
276                     resource.getName(), resource.getVendorRelease());
277             }
278             throw new ByActionStatusComponentException(ActionStatus.COMPONENT_WITH_VENDOR_RELEASE_ALREADY_EXISTS_IN_MODEL,
279                 resource.getName(), resource.getVendorRelease(), resource.getModel());
280         }
281     }
282
283     private void checkResourceExistsOnUpdate(final Resource resource) {
284         final String model = resource.getModel();
285         final Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resource.getName(), model);
286         if (latestByName.isLeft() && toscaOperationFacade.isNodeAssociatedToModel(model, resource)) {
287             if (model == null) {
288                 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
289                     resource.getResourceType().name(), resource.getName());
290             }
291             throw new ByActionStatusComponentException(ActionStatus.COMPONENT_WITH_MODEL_ALREADY_EXIST, resource.getName(), model);
292         }
293     }
294
295     private boolean isCsarPresent(final CsarInfo csarInfo) {
296         return csarInfo != null && StringUtils.isNotEmpty(csarInfo.getCsarUUID());
297     }
298
299     private String getLatestCertifiedResourceId(Resource resource) {
300         Map<String, String> allVersions = resource.getAllVersions();
301         Double latestCertifiedVersion = 0.0;
302         if (allVersions != null) {
303             for (String version : allVersions.keySet()) {
304                 Double dVersion = Double.valueOf(version);
305                 if ((dVersion > latestCertifiedVersion) && (version.endsWith(".0"))) {
306                     latestCertifiedVersion = dVersion;
307                 }
308             }
309             return allVersions.get(String.valueOf(latestCertifiedVersion));
310         } else {
311             return null;
312         }
313     }
314
315     public void populateResourceMetadata(UploadResourceInfo resourceMetaData, Resource resource) {
316         if (resource != null && resourceMetaData != null) {
317             resource.setDescription(resourceMetaData.getDescription());
318             resource.setTags(resourceMetaData.getTags());
319             resource.setCategories(resourceMetaData.getCategories());
320             resource.setContactId(resourceMetaData.getContactId());
321             resource.setName(resourceMetaData.getName());
322             resource.setIcon(resourceMetaData.getResourceIconPath());
323             resource.setResourceVendorModelNumber(resourceMetaData.getResourceVendorModelNumber());
324             resource.setResourceType(ResourceTypeEnum.valueOf(resourceMetaData.getResourceType()));
325             resource.setTenant(resourceMetaData.getTenant());
326             if (resourceMetaData.getVendorName() != null) {
327                 resource.setVendorName(resourceMetaData.getVendorName());
328             }
329             if (resourceMetaData.getVendorRelease() != null) {
330                 resource.setVendorRelease(resourceMetaData.getVendorRelease());
331             }
332             if (resourceMetaData.getModel() != null) {
333                 resource.setModel(resourceMetaData.getModel());
334             }
335         }
336     }
337
338     public ImmutablePair<Resource, ActionStatus> importUserDefinedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator,
339                                                                            boolean isInTransaction) {
340         Resource resource = new Resource();
341         ImmutablePair<Resource, ActionStatus> responsePair = new ImmutablePair<>(resource, ActionStatus.CREATED);
342         try {
343             setMetaDataFromJson(resourceMetaData, resource);
344             populateResourceFromYaml(resourceYml, resource);
345             // currently import VF isn't supported. In future will be supported import VF only with CSAR file!!
346             if (ResourceTypeEnum.VF == resource.getResourceType()) {
347                 log.debug("Now import VF isn't supported. It will be supported in future with CSAR file only");
348                 throw new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION);
349             }
350             resourceBusinessLogic.validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
351             resourceBusinessLogic.validatePropertiesDefaultValues(resource);
352             responsePair = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, false, isInTransaction, true, null, null, false);
353         } catch (RuntimeException e) {
354             handleImportResourceException(resourceMetaData, creator, false, e);
355         }
356         return responsePair;
357     }
358
359     private void populateResourceFromYaml(final String resourceYml, Resource resource) {
360         @SuppressWarnings("unchecked") Object ymlObj = new Yaml().load(resourceYml);
361         if (ymlObj instanceof Map) {
362             final Either<Resource, StorageOperationStatus> existingResource = getExistingResource(resource);
363             final Map<String, Object> toscaJsonAll = (Map<String, Object>) ymlObj;
364             Map<String, Object> toscaJson = toscaJsonAll;
365             if (toscaJsonAll.containsKey(ToscaTagNamesEnum.NODE_TYPES.getElementName()) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
366                 toscaJson = new HashMap<>();
367                 toscaJson.put(ToscaTagNamesEnum.NODE_TYPES.getElementName(), toscaJsonAll.get(ToscaTagNamesEnum.NODE_TYPES.getElementName()));
368             }
369             final List<Object> foundElements = new ArrayList<>();
370             final Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils
371                 .findToscaElements(toscaJsonAll, ToscaTagNamesEnum.DATA_TYPES.getElementName(), ToscaElementTypeEnum.MAP, foundElements);
372             if (toscaElements.isLeft()) {
373                 final Map<String, Object> toscaAttributes = (Map<String, Object>) foundElements.get(0);
374                 if (MapUtils.isNotEmpty(toscaAttributes)) {
375                     resource.setDataTypes(extractDataTypeFromJson(resourceBusinessLogic, toscaAttributes, resource.getModel()));
376                 }
377             }
378             final Resource parentResource = setDerivedFrom(toscaJson, resource);
379             if (StringUtils.isEmpty(resource.getToscaResourceName())) {
380                 setToscaResourceName(toscaJson, resource);
381             }
382             setCapabilities(toscaJson, resource, parentResource);
383             setProperties(toscaJson, resource, existingResource);
384             setAttributes(toscaJson, resource);
385             setRequirements(toscaJson, resource, parentResource);
386             setInterfaceLifecycle(toscaJson, resource, existingResource);
387         } else {
388             throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
389         }
390     }
391
392     private Either<Resource, StorageOperationStatus> getExistingResource(final Resource resource) {
393         final Either<List<GraphVertex>, JanusGraphOperationStatus> byCriteria = janusGraphDao.getByCriteria(
394             getVertexTypeEnum(resource.getResourceType()), propertiesToMatch(resource), propertiesToNotMatch(),
395             JsonParseFlagEnum.ParseAll, resource.getModel(), false);
396         if (byCriteria.isLeft() && CollectionUtils.isNotEmpty(byCriteria.left().value())) {
397             final List<GraphVertex> graphVertexList = byCriteria.left().value();
398             if (graphVertexList.size() == 1) {
399                 return toscaOperationFacade.getToscaElement(graphVertexList.get(0).getUniqueId());
400             } else {
401                 final Optional<GraphVertex> vertex = graphVertexList.stream()
402                     .max(Comparator.comparing(graphVertex -> (String) graphVertex.getMetadataProperties().get(GraphPropertyEnum.VERSION)));
403                 if (vertex.isPresent()) {
404                     return toscaOperationFacade.getToscaElement(vertex.get().getUniqueId());
405                 }
406             }
407         }
408         return Either.right(StorageOperationStatus.NOT_FOUND);
409     }
410
411     private VertexTypeEnum getVertexTypeEnum(final ResourceTypeEnum resourceType) {
412         return ModelConverter.isAtomicComponent(resourceType) ? VertexTypeEnum.NODE_TYPE : VertexTypeEnum.TOPOLOGY_TEMPLATE;
413     }
414
415     private Map<GraphPropertyEnum, Object> propertiesToMatch(final Resource resource) {
416         final Map<GraphPropertyEnum, Object> graphProperties = new EnumMap<>(GraphPropertyEnum.class);
417         graphProperties.put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normaliseComponentName(resource.getName()));
418         graphProperties.put(GraphPropertyEnum.COMPONENT_TYPE, resource.getComponentType().name());
419         graphProperties.put(GraphPropertyEnum.RESOURCE_TYPE, resource.getResourceType().name());
420         graphProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
421         return graphProperties;
422     }
423
424     private Map<GraphPropertyEnum, Object> propertiesToNotMatch() {
425         final Map<GraphPropertyEnum, Object> graphProperties = new EnumMap<>(GraphPropertyEnum.class);
426         graphProperties.put(GraphPropertyEnum.IS_DELETED, true);
427         graphProperties.put(GraphPropertyEnum.IS_ARCHIVED, true);
428         return graphProperties;
429     }
430
431     private void setToscaResourceName(Map<String, Object> toscaJson, Resource resource) {
432         resource.setToscaResourceName(getToscaResourceName(toscaJson));
433     }
434
435     private String getToscaResourceName(Map<String, Object> toscaJson) {
436         Either<Map<String, Object>, ResultStatusEnum> toscaElement = ImportUtils
437                 .findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.NODE_TYPES);
438         if (toscaElement.isLeft() && toscaElement.left().value().size() == 1) {
439             String toscaResourceName = toscaElement.left().value().keySet().iterator().next();
440             return toscaResourceName;
441         }
442         return null;
443     }
444
445     private void setInterfaceLifecycle(Map<String, Object> toscaJson, Resource resource, Either<Resource, StorageOperationStatus> existingResource) {
446         final Either<Map<String, Object>, ResultStatusEnum> toscaInterfaces = ImportUtils
447             .findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.INTERFACES);
448         final Map<String, InterfaceDefinition> moduleInterfaces = new HashMap<>();
449         final Map<String, Object> map;
450         if (toscaInterfaces.isLeft()) {
451             map = toscaInterfaces.left().value();
452             for (final Entry<String, Object> interfaceNameValue : map.entrySet()) {
453                 final Either<InterfaceDefinition, ResultStatusEnum> eitherInterface = createModuleInterface(interfaceNameValue.getValue(),
454                     resource.getModel());
455                 if (eitherInterface.isRight()) {
456                     log.info("error when creating interface:{}, for resource:{}", interfaceNameValue.getKey(), resource.getName());
457                 } else {
458                     final InterfaceDefinition interfaceDefinition = eitherInterface.left().value();
459                     moduleInterfaces.put(interfaceDefinition.getType(), interfaceDefinition);
460                 }
461             }
462         } else {
463             map = Collections.emptyMap();
464         }
465         if (existingResource.isLeft()) {
466             final Map<String, InterfaceDefinition> userCreatedInterfaceDefinitions =
467                 existingResource.left().value().getInterfaces().entrySet().stream()
468                     .filter(i -> i.getValue().isUserCreated())
469                     .filter(i -> !map.containsKey(i.getValue().getType()))
470                     .collect(Collectors.toMap(Entry::getKey, Entry::getValue));
471             if (MapUtils.isNotEmpty(userCreatedInterfaceDefinitions)) {
472                 moduleInterfaces.putAll(userCreatedInterfaceDefinitions);
473             }
474         }
475
476         if (MapUtils.isNotEmpty(moduleInterfaces)) {
477             resource.setInterfaces(moduleInterfaces);
478         }
479     }
480
481     private Either<InterfaceDefinition, ResultStatusEnum> createModuleInterface(final Object interfaceJson, final String model) {
482         try {
483             if (interfaceJson instanceof String) {
484                 final InterfaceDefinition interfaceDefinition = new InterfaceDefinition();
485                 interfaceDefinition.setType((String) interfaceJson);
486                 return Either.left(interfaceDefinition);
487             }
488             if (interfaceJson instanceof Map) {
489                 final Map<String, Object> interfaceJsonMap = (Map<String, Object>) interfaceJson;
490                 final InterfaceDefinition interfaceDefinition = interfaceDefinitionHandler.create(interfaceJsonMap, model);
491                 return Either.left(interfaceDefinition);
492             }
493             return Either.right(ResultStatusEnum.GENERAL_ERROR);
494         } catch (final Exception e) {
495             BeEcompErrorManager.getInstance().logBeSystemError("Import Resource- create interface");
496             log.debug("error when creating interface, message:{}", e.getMessage(), e);
497             return Either.right(ResultStatusEnum.GENERAL_ERROR);
498         }
499     }
500
501     private void setRequirements(Map<String, Object> toscaJson, Resource resource,
502                                  Resource parentResource) {// Note that parentResource can be null
503         Either<List<Object>, ResultStatusEnum> toscaRequirements = ImportUtils
504             .findFirstToscaListElement(toscaJson, ToscaTagNamesEnum.REQUIREMENTS);
505         if (toscaRequirements.isLeft()) {
506             List<Object> jsonRequirements = toscaRequirements.left().value();
507             Map<String, List<RequirementDefinition>> moduleRequirements = new HashMap<>();
508             // Checking for name duplication
509             Set<String> reqNames = new HashSet<>();
510             // Getting flattened list of capabilities of parent node - cap name to cap type
511             Map<String, String> reqName2TypeMap = getReqName2Type(parentResource);
512             for (Object jsonRequirementObj : jsonRequirements) {
513                 // Requirement
514                 Map<String, Object> requirementJsonWrapper = (Map<String, Object>) jsonRequirementObj;
515                 String requirementName = requirementJsonWrapper.keySet().iterator().next();
516                 String reqNameLowerCase = requirementName.toLowerCase();
517                 if (reqNames.contains(reqNameLowerCase)) {
518                     log.debug("More than one requirement with same name {} (case-insensitive) in imported TOSCA file is invalid", reqNameLowerCase);
519                     throw new ByActionStatusComponentException(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "requirement", reqNameLowerCase);
520                 }
521                 reqNames.add(reqNameLowerCase);
522                 RequirementDefinition requirementDef = createRequirementFromImportFile(requirementJsonWrapper.get(requirementName));
523                 requirementDef.setName(requirementName);
524                 if (moduleRequirements.containsKey(requirementDef.getCapability())) {
525                     moduleRequirements.get(requirementDef.getCapability()).add(requirementDef);
526                 } else {
527                     List<RequirementDefinition> list = new ArrayList<>();
528                     list.add(requirementDef);
529                     moduleRequirements.put(requirementDef.getCapability(), list);
530                 }
531                 // Validating against req/cap of "derived from" node
532                 Boolean validateVsParentCap = validateCapNameVsDerived(reqName2TypeMap, requirementDef.getCapability(), requirementDef.getName());
533                 if (!validateVsParentCap) {
534                     String parentResourceName = parentResource != null ? parentResource.getName() : "";
535                     log.debug("Requirement with name {} already exists in parent {}", requirementDef.getName(), parentResourceName);
536                     throw new ByActionStatusComponentException(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "requirement",
537                         requirementDef.getName().toLowerCase(), parentResourceName);
538                 }
539             }
540             if (moduleRequirements.size() > 0) {
541                 resource.setRequirements(moduleRequirements);
542             }
543         }
544     }
545
546     private RequirementDefinition createRequirementFromImportFile(Object requirementJson) {
547         RequirementDefinition requirement = new RequirementDefinition();
548         if (requirementJson instanceof String) {
549             String requirementJsonString = (String) requirementJson;
550             requirement.setCapability(requirementJsonString);
551         } else if (requirementJson instanceof Map) {
552             Map<String, Object> requirementJsonMap = (Map<String, Object>) requirementJson;
553             if (requirementJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITY.getElementName())) {
554                 requirement.setCapability((String) requirementJsonMap.get(ToscaTagNamesEnum.CAPABILITY.getElementName()));
555             }
556             if (requirementJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) {
557                 requirement.setNode((String) requirementJsonMap.get(ToscaTagNamesEnum.NODE.getElementName()));
558             }
559             if (requirementJsonMap.containsKey(ToscaTagNamesEnum.RELATIONSHIP.getElementName())) {
560                 requirement.setRelationship((String) requirementJsonMap.get(ToscaTagNamesEnum.RELATIONSHIP.getElementName()));
561             }
562             if (requirementJsonMap.containsKey(ToscaTagNamesEnum.OCCURRENCES.getElementName())) {
563                 List<Object> occurrencesList = (List) requirementJsonMap.get(ToscaTagNamesEnum.OCCURRENCES.getElementName());
564                 validateOccurrences(occurrencesList);
565                 requirement.setMinOccurrences(occurrencesList.get(0).toString());
566                 requirement.setMaxOccurrences(occurrencesList.get(1).toString());
567             }
568         } else {
569             throw new ByActionStatusComponentException(ActionStatus.INVALID_YAML);
570         }
571         return requirement;
572     }
573
574     private void setProperties(final Map<String, Object> toscaJson, final Resource resource,
575                                final Either<Resource, StorageOperationStatus> existingResource) {
576         final Map<String, Object> reducedToscaJson = new HashMap<>(toscaJson);
577         ImportUtils.removeElementFromJsonMap(reducedToscaJson, "capabilities");
578         final Either<Map<String, PropertyDefinition>, ResultStatusEnum> properties = ImportUtils.getProperties(reducedToscaJson);
579         if (properties.isLeft()) {
580             final Map<String, PropertyDefinition> propertyDefinitionMap = properties.left().value();
581             if (MapUtils.isNotEmpty(propertyDefinitionMap)) {
582                 final List<PropertyDefinition> propertiesList = new ArrayList<>();
583                 for (final Entry<String, PropertyDefinition> entry : propertyDefinitionMap.entrySet()) {
584                     addPropertyToList(resource.getName(), propertiesList, entry);
585                 }
586                 if (existingResource.isLeft()) {
587                     if ( CollectionUtils.isNotEmpty(existingResource.left().value().getProperties())) {
588                         final List<PropertyDefinition> userCreatedResourceProperties =
589                             existingResource.left().value().getProperties().stream()
590                                 .filter(PropertyDataDefinition::isUserCreated)
591                                 .filter(propertyDefinition -> !propertyDefinitionMap.containsKey(propertyDefinition.getName()))
592                                 .collect(Collectors.toList());
593                         if (CollectionUtils.isNotEmpty(userCreatedResourceProperties)) {
594                             propertiesList.addAll(userCreatedResourceProperties);
595                         }
596                     }
597                 }
598
599                 resource.setProperties(propertiesList);
600             }
601         } else if (properties.right().value() != ResultStatusEnum.ELEMENT_NOT_FOUND) {
602             throw new ByActionStatusComponentException(
603                 componentsUtils.convertFromResultStatusEnum(properties.right().value(), JsonPresentationFields.PROPERTY));
604         }
605     }
606
607     private void addPropertyToList(final String resourceName,
608                                    final List<PropertyDefinition> propertiesList,
609                                    final Entry<String, PropertyDefinition> entry) {
610         final String propertyName = entry.getKey();
611         if (!PROPERTY_NAME_PATTERN_IGNORE_LENGTH.matcher(propertyName).matches()) {
612             log.debug("The property with invalid name {} occured upon import resource {}. ", propertyName, resourceName);
613             throw new ByActionStatusComponentException(
614                 componentsUtils.convertFromResultStatusEnum(ResultStatusEnum.INVALID_PROPERTY_NAME, JsonPresentationFields.PROPERTY));
615         }
616         final PropertyDefinition propertyDefinition = entry.getValue();
617         propertyDefinition.setName(propertyName);
618         propertiesList.add(propertyDefinition);
619     }
620
621     private void setAttributes(final Map<String, Object> originalToscaJsonMap, final Resource resource) {
622         final Map<String, Object> toscaJsonMap = new HashMap<>(originalToscaJsonMap);
623         ImportUtils.removeElementFromJsonMap(toscaJsonMap, "capabilities");
624         final Either<Map<String, AttributeDefinition>, ResultStatusEnum> getAttributeEither = ImportUtils.getAttributes(toscaJsonMap);
625         if (getAttributeEither.isRight()) {
626             final ResultStatusEnum resultStatus = getAttributeEither.right().value();
627             if (resultStatus == ResultStatusEnum.ELEMENT_NOT_FOUND) {
628                 return;
629             }
630             throw new ByActionStatusComponentException(componentsUtils.convertFromResultStatusEnum(resultStatus, JsonPresentationFields.ATTRIBUTES));
631         }
632         final List<AttributeDefinition> attributeDefinitionList = new ArrayList<>();
633         final Map<String, AttributeDefinition> attributeMap = getAttributeEither.left().value();
634         if (MapUtils.isEmpty(attributeMap)) {
635             return;
636         }
637         for (final Entry<String, AttributeDefinition> entry : attributeMap.entrySet()) {
638             final String name = entry.getKey();
639             if (!PROPERTY_NAME_PATTERN_IGNORE_LENGTH.matcher(name).matches()) {
640                 log.debug("Detected attribute with invalid name '{}' during resource '{}' import. ", name, resource.getName());
641                 throw new ByActionStatusComponentException(
642                     componentsUtils.convertFromResultStatusEnum(ResultStatusEnum.INVALID_ATTRIBUTE_NAME, JsonPresentationFields.ATTRIBUTES));
643             }
644             final AttributeDefinition attributeDefinition = entry.getValue();
645             attributeDefinition.setName(name);
646             if (attributeDefinition.getEntry_schema() != null && attributeDefinition.getEntry_schema().getType() != null) {
647                 attributeDefinition.setSchema(new SchemaDefinition());
648                 attributeDefinition.getSchema().setProperty(new PropertyDataDefinition());
649                 attributeDefinition.getSchema().getProperty().setType(entry.getValue().getEntry_schema().getType());
650             }
651             attributeDefinitionList.add(attributeDefinition);
652         }
653         resource.setAttributes(attributeDefinitionList);
654     }
655
656     private Resource setDerivedFrom(Map<String, Object> toscaJson, Resource resource) {
657         Either<String, ResultStatusEnum> toscaDerivedFromElement = ImportUtils
658             .findFirstToscaStringElement(toscaJson, ToscaTagNamesEnum.DERIVED_FROM);
659         Resource derivedFromResource = null;
660         if (toscaDerivedFromElement.isLeft()) {
661             String derivedFrom = toscaDerivedFromElement.left().value();
662             log.debug("Derived from TOSCA name is {}", derivedFrom);
663             resource.setDerivedFrom(Arrays.asList(new String[]{derivedFrom}));
664             Either<Resource, StorageOperationStatus> latestByToscaResourceName = toscaOperationFacade.getLatestByToscaResourceName(derivedFrom,
665                 resource.getModel());
666             if (latestByToscaResourceName.isRight()) {
667                 StorageOperationStatus operationStatus = latestByToscaResourceName.right().value();
668                 if (operationStatus == StorageOperationStatus.NOT_FOUND) {
669                     operationStatus = StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND;
670                 }
671                 log.debug("Error when fetching parent resource {}, error: {}", derivedFrom, operationStatus);
672                 ActionStatus convertFromStorageResponse = componentsUtils.convertFromStorageResponse(operationStatus);
673                 BeEcompErrorManager.getInstance().logBeComponentMissingError("Import TOSCA YAML", "resource", derivedFrom);
674                 throw new ByActionStatusComponentException(convertFromStorageResponse, derivedFrom);
675             }
676             derivedFromResource = latestByToscaResourceName.left().value();
677         }
678         return derivedFromResource;
679     }
680
681     private void setCapabilities(Map<String, Object> toscaJson, Resource resource,
682                                  Resource parentResource) {// Note that parentResource can be null
683         Either<Map<String, Object>, ResultStatusEnum> toscaCapabilities = ImportUtils
684             .findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.CAPABILITIES);
685         if (toscaCapabilities.isLeft()) {
686             Map<String, Object> jsonCapabilities = toscaCapabilities.left().value();
687             Map<String, List<CapabilityDefinition>> moduleCapabilities = new HashMap<>();
688             Iterator<Entry<String, Object>> capabilitiesNameValue = jsonCapabilities.entrySet().iterator();
689             Set<String> capNames = new HashSet<>();
690             // Getting flattened list of capabilities of parent node - cap name
691
692             // to cap type
693             Map<String, String> capName2TypeMap = getCapName2Type(parentResource);
694             while (capabilitiesNameValue.hasNext()) {
695                 Entry<String, Object> capabilityNameValue = capabilitiesNameValue.next();
696                 // Validating that no req/cap duplicates exist in imported YAML
697                 String capNameLowerCase = capabilityNameValue.getKey().toLowerCase();
698                 if (capNames.contains(capNameLowerCase)) {
699                     log.debug("More than one capability with same name {} (case-insensitive) in imported TOSCA file is invalid", capNameLowerCase);
700                     throw new ByActionStatusComponentException(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "capability", capNameLowerCase);
701                 }
702                 capNames.add(capNameLowerCase);
703                 CapabilityDefinition capabilityDef = createCapabilityFromImportFile(capabilityNameValue.getValue());
704                 capabilityDef.setName(capabilityNameValue.getKey());
705                 if (moduleCapabilities.containsKey(capabilityDef.getType())) {
706                     moduleCapabilities.get(capabilityDef.getType()).add(capabilityDef);
707                 } else {
708                     List<CapabilityDefinition> list = new ArrayList<>();
709                     list.add(capabilityDef);
710                     moduleCapabilities.put(capabilityDef.getType(), list);
711                 }
712                 // Validating against req/cap of "derived from" node
713                 Boolean validateVsParentCap = validateCapNameVsDerived(capName2TypeMap, capabilityDef.getType(), capabilityDef.getName());
714                 if (!validateVsParentCap) {
715                     // Here parentResource is for sure not null, so it's
716
717                     // null-safe
718
719                     // Check added to avoid sonar warning
720                     String parentResourceName = parentResource != null ? parentResource.getName() : "";
721                     log.debug("Capability with name {} already exists in parent {}", capabilityDef.getName(), parentResourceName);
722                     throw new ByActionStatusComponentException(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "capability",
723                         capabilityDef.getName().toLowerCase(), parentResourceName);
724                 }
725             }
726             if (moduleCapabilities.size() > 0) {
727                 resource.setCapabilities(moduleCapabilities);
728             }
729         }
730     }
731
732     private Map<String, String> getCapName2Type(Resource parentResource) {
733         Map<String, String> capName2type = new HashMap<>();
734         if (parentResource != null) {
735             Map<String, List<CapabilityDefinition>> capabilities = parentResource.getCapabilities();
736             if (capabilities != null) {
737                 for (List<CapabilityDefinition> capDefinitions : capabilities.values()) {
738                     for (CapabilityDefinition capDefinition : capDefinitions) {
739                         String nameLowerCase = capDefinition.getName().toLowerCase();
740                         if (capName2type.get(nameLowerCase) != null) {
741                             String parentResourceName = parentResource.getName();
742                             log.debug("Resource with name {} has more than one capability with name {}, ignoring case", parentResourceName,
743                                 nameLowerCase);
744                             BeEcompErrorManager.getInstance().logInternalDataError("Import resource",
745                                 "Parent resource " + parentResourceName + " of imported resource has one or more capabilities with name "
746                                     + nameLowerCase, ErrorSeverity.ERROR);
747                             throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
748                         }
749                         capName2type.put(nameLowerCase, capDefinition.getType());
750                     }
751                 }
752             }
753         }
754         return capName2type;
755     }
756
757     private Map<String, String> getReqName2Type(Resource parentResource) {
758         Map<String, String> reqName2type = new HashMap<>();
759         if (parentResource != null) {
760             Map<String, List<RequirementDefinition>> requirements = parentResource.getRequirements();
761             if (requirements != null) {
762                 for (List<RequirementDefinition> reqDefinitions : requirements.values()) {
763                     for (RequirementDefinition reqDefinition : reqDefinitions) {
764                         String nameLowerCase = reqDefinition.getName().toLowerCase();
765                         if (reqName2type.get(nameLowerCase) != null) {
766                             String parentResourceName = parentResource.getName();
767                             log.debug("Resource with name {} has more than one requirement with name {}, ignoring case", parentResourceName,
768                                 nameLowerCase);
769                             BeEcompErrorManager.getInstance().logInternalDataError("Import resource",
770                                 "Parent resource " + parentResourceName + " of imported resource has one or more requirements with name "
771                                     + nameLowerCase, ErrorSeverity.ERROR);
772                             throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
773                         }
774                         reqName2type.put(nameLowerCase, reqDefinition.getCapability());
775                     }
776                 }
777             }
778         }
779         return reqName2type;
780     }
781
782     private Boolean validateCapNameVsDerived(Map<String, String> parentCapName2Type, String childCapabilityType, String reqCapName) {
783         String capNameLowerCase = reqCapName.toLowerCase();
784         log.trace("Validating capability {} vs parent resource", capNameLowerCase);
785         String parentCapType = parentCapName2Type.get(capNameLowerCase);
786         if (parentCapType != null) {
787             if (childCapabilityType.equals(parentCapType)) {
788                 log.debug("Capability with name {} is of same type {} for imported resource and its parent - this is OK", capNameLowerCase,
789                     childCapabilityType);
790                 return true;
791             }
792             Either<Boolean, StorageOperationStatus> capabilityTypeDerivedFrom = capabilityTypeOperation
793                 .isCapabilityTypeDerivedFrom(childCapabilityType, parentCapType);
794             if (capabilityTypeDerivedFrom.isRight()) {
795                 log.debug("Couldn't check whether imported resource capability derives from its parent's capability");
796                 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(capabilityTypeDerivedFrom.right().value()));
797             }
798             return capabilityTypeDerivedFrom.left().value();
799         }
800         return true;
801     }
802
803     private CapabilityDefinition createCapabilityFromImportFile(Object capabilityJson) {
804         CapabilityDefinition capabilityDefinition = new CapabilityDefinition();
805         if (capabilityJson instanceof String) {
806             String capabilityJsonString = (String) capabilityJson;
807             capabilityDefinition.setType(capabilityJsonString);
808         } else if (capabilityJson instanceof Map) {
809             Map<String, Object> capabilityJsonMap = (Map<String, Object>) capabilityJson;
810             // Type
811             if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
812                 capabilityDefinition.setType((String) capabilityJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName()));
813             }
814             // ValidSourceTypes
815             if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())) {
816                 capabilityDefinition
817                     .setValidSourceTypes((List<String>) capabilityJsonMap.get(ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName()));
818             }
819             // ValidSourceTypes
820             if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
821                 capabilityDefinition.setDescription((String) capabilityJsonMap.get(ToscaTagNamesEnum.DESCRIPTION.getElementName()));
822             }
823             if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.OCCURRENCES.getElementName())) {
824                 List<Object> occurrencesList = (List) capabilityJsonMap.get(ToscaTagNamesEnum.OCCURRENCES.getElementName());
825                 validateOccurrences(occurrencesList);
826                 capabilityDefinition.setMinOccurrences(occurrencesList.get(0).toString());
827                 capabilityDefinition.setMaxOccurrences(occurrencesList.get(1).toString());
828             }
829             if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
830                 Either<Map<String, PropertyDefinition>, ResultStatusEnum> propertiesRes = ImportUtils.getProperties(capabilityJsonMap);
831                 if (propertiesRes.isRight()) {
832                     throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND);
833                 } else {
834                     propertiesRes.left().value().entrySet().stream().forEach(e -> e.getValue().setName(e.getKey().toLowerCase()));
835                     List<ComponentInstanceProperty> capabilityProperties = propertiesRes.left().value().values().stream()
836                         .map(p -> new ComponentInstanceProperty(p, p.getDefaultValue(), null)).collect(Collectors.toList());
837                     capabilityDefinition.setProperties(capabilityProperties);
838                 }
839             }
840         } else if (!(capabilityJson instanceof List)) {
841             throw new ByActionStatusComponentException(ActionStatus.INVALID_YAML);
842         }
843         return capabilityDefinition;
844     }
845
846     private void handleImportResourceException(UploadResourceInfo resourceMetaData, User user, boolean isNormative, RuntimeException e) {
847         ResponseFormat responseFormat;
848         ComponentException newException;
849         if (e instanceof ComponentException) {
850             ComponentException componentException = (ComponentException) e;
851             responseFormat = componentException.getResponseFormat();
852             if (responseFormat == null) {
853                 responseFormat = getResponseFormatManager().getResponseFormat(componentException.getActionStatus(), componentException.getParams());
854             }
855             newException = componentException;
856         } else {
857             responseFormat = getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR);
858             newException = new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
859         }
860         String payloadName = (resourceMetaData != null) ? resourceMetaData.getPayloadName() : "";
861         BeEcompErrorManager.getInstance().logBeSystemError("Import Resource " + payloadName);
862         log.debug("Error when importing resource from payload:{} Exception text: {}", payloadName, e.getMessage(), e);
863         auditErrorImport(resourceMetaData, user, responseFormat, isNormative);
864         throw newException;
865     }
866
867     private void auditErrorImport(UploadResourceInfo resourceMetaData, User user, ResponseFormat errorResponseWrapper, boolean isNormative) {
868         String version, lifeCycleState;
869         if (isNormative) {
870             version = TypeUtils.getFirstCertifiedVersionVersion();
871             lifeCycleState = LifecycleStateEnum.CERTIFIED.name();
872         } else {
873             version = "";
874             lifeCycleState = LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name();
875         }
876         String message = "";
877         if (errorResponseWrapper.getMessageId() != null) {
878             message = errorResponseWrapper.getMessageId() + ": ";
879         }
880         message += errorResponseWrapper.getFormattedMessage();
881         AuditEventFactory factory = new AuditImportResourceAdminEventFactory(
882             CommonAuditData.newBuilder().status(errorResponseWrapper.getStatus()).description(message).requestId(ThreadLocalsHolder.getUuid())
883                 .build(), new ResourceCommonInfo(resourceMetaData.getName(), ComponentTypeEnum.RESOURCE.getValue()),
884             ResourceVersionInfo.newBuilder().state(lifeCycleState).version(version).build(),
885             ResourceVersionInfo.newBuilder().state("").version("").build(), "", user, "");
886         getAuditingManager().auditEvent(factory);
887     }
888
889     private void setResourceMetaData(Resource resource, String resourceYml, UploadResourceInfo resourceMetaData) {
890         Map<String, Object> ymlObj = new Yaml().load(resourceYml);
891         String toscaName = getToscaResourceName(ymlObj);
892         final Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade
893             .getLatestByToscaResourceName(toscaName, resourceMetaData.getModel());
894         if (latestByToscaName.isLeft() && resourceMetaData instanceof DefaultUploadResourceInfo) {
895             setMetaDataFromLatestResource(resource, latestByToscaName.left().value());
896         } else {
897             setMetaDataFromJson(resourceMetaData, resource);
898         }
899     }
900
901     private void setMetaDataFromJson(final UploadResourceInfo resourceMetaData, final Resource resource) {
902         this.populateResourceMetadata(resourceMetaData, resource);
903         resource.setCreatorUserId(resourceMetaData.getContactId());
904         final String payloadData = resourceMetaData.getPayloadData();
905         if (payloadData != null) {
906             resource.setToscaVersion(getToscaVersion(payloadData));
907         }
908         final List<CategoryDefinition> categories = resourceMetaData.getCategories();
909         calculateResourceIsAbstract(resource, categories);
910     }
911
912     private void setMetaDataFromLatestResource(Resource resource, Resource latestResource) {
913         if (resource != null && latestResource != null) {
914             resource.setCreatorUserId(latestResource.getContactId());
915             resource.setDescription(latestResource.getDescription());
916             resource.setTags(latestResource.getTags());
917             resource.setCategories(latestResource.getCategories());
918             resource.setContactId(latestResource.getContactId());
919             resource.setName(latestResource.getName());
920             resource.setIcon(latestResource.getIcon());
921             resource.setResourceVendorModelNumber(latestResource.getResourceVendorModelNumber());
922             resource.setResourceType(latestResource.getResourceType());
923             if (latestResource.getVendorName() != null) {
924                 resource.setVendorName(latestResource.getVendorName());
925             }
926             if (latestResource.getVendorRelease() != null) {
927                 resource.setVendorRelease(latestResource.getVendorRelease());
928             }
929             if (latestResource.getModel() != null) {
930                 resource.setModel(latestResource.getModel());
931             }
932             if (latestResource.getToscaVersion() != null) {
933                 resource.setToscaVersion(latestResource.getToscaVersion());
934             }
935             final List<CategoryDefinition> categories = latestResource.getCategories();
936             calculateResourceIsAbstract(resource, categories);
937         }
938     }
939
940     private Map<String, Object> decodePayload(final String payloadData) {
941         final String decodedPayload = new String(Base64.decodeBase64(payloadData));
942         return (Map<String, Object>) new Yaml().load(decodedPayload);
943     }
944
945     private String getToscaVersion(final String payloadData) {
946         final Map<String, Object> mappedToscaTemplate = decodePayload(payloadData);
947         final Either<String, ResultStatusEnum> findFirstToscaStringElement = ImportUtils
948             .findFirstToscaStringElement(mappedToscaTemplate, ToscaTagNamesEnum.TOSCA_VERSION);
949         if (findFirstToscaStringElement.isLeft()) {
950             return findFirstToscaStringElement.left().value();
951         } else {
952             return null;
953         }
954     }
955
956     private void calculateResourceIsAbstract(Resource resource, List<CategoryDefinition> categories) {
957         if (categories != null && !categories.isEmpty()) {
958             CategoryDefinition categoryDef = categories.get(0);
959             resource.setAbstract(false);
960             if (categoryDef != null && categoryDef.getName() != null && categoryDef.getName().equals(Constants.ABSTRACT_CATEGORY_NAME)) {
961                 SubCategoryDefinition subCategoryDef = categoryDef.getSubcategories().get(0);
962                 if (subCategoryDef != null && subCategoryDef.getName().equals(Constants.ABSTRACT_SUBCATEGORY)) {
963                     resource.setAbstract(true);
964                 }
965             }
966         }
967     }
968
969     private void setConstantMetaData(Resource resource, boolean shouldBeCertified) {
970         String version;
971         LifecycleStateEnum state;
972         if (shouldBeCertified) {
973             version = TypeUtils.getFirstCertifiedVersionVersion();
974             state = ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE;
975         } else {
976             version = ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION;
977             state = ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT;
978         }
979         resource.setVersion(version);
980         resource.setLifecycleState(state);
981         resource.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
982         resource.setVendorName(ImportUtils.Constants.VENDOR_NAME);
983         resource.setVendorRelease(ImportUtils.Constants.VENDOR_RELEASE);
984     }
985
986     private void validateOccurrences(List<Object> occurrensesList) {
987         if (!ValidationUtils.validateListNotEmpty(occurrensesList)) {
988             log.debug("Occurrenses list empty");
989             throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES);
990         }
991         if (occurrensesList.size() < 2) {
992             log.debug("Occurrenses list size not 2");
993             throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES);
994         }
995         Object minObj = occurrensesList.get(0);
996         Object maxObj = occurrensesList.get(1);
997         Integer minOccurrences;
998         Integer maxOccurrences;
999         if (minObj instanceof Integer) {
1000             minOccurrences = (Integer) minObj;
1001         } else {
1002             log.debug("Invalid occurrenses format. low_bound occurrense must be Integer {}", minObj);
1003             throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES);
1004         }
1005         if (minOccurrences < 0) {
1006             log.debug("Invalid occurrenses format.low_bound occurrense negative {}", minOccurrences);
1007             throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES);
1008         }
1009         if (maxObj instanceof String) {
1010             if (!"UNBOUNDED".equals(maxObj)) {
1011                 log.debug("Invalid occurrenses format. Max occurrence is {}", maxObj);
1012                 throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES);
1013             }
1014         } else {
1015             if (maxObj instanceof Integer) {
1016                 maxOccurrences = (Integer) maxObj;
1017             } else {
1018                 log.debug("Invalid occurrenses format.  Max occurrence is {}", maxObj);
1019                 throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES);
1020             }
1021             if (maxOccurrences < 0 || maxOccurrences < minOccurrences) {
1022                 log.debug("Invalid occurrenses format.  min occurrence is {}, Max occurrence is {}", minOccurrences, maxOccurrences);
1023                 throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES);
1024             }
1025         }
1026     }
1027
1028     public synchronized void init(ServletContext servletContext) {
1029         if (this.servletContext == null) {
1030             this.servletContext = servletContext;
1031             responseFormatManager = ResponseFormatManager.getInstance();
1032             resourceBusinessLogic = getResourceBL(servletContext);
1033         }
1034     }
1035
1036     public boolean isResourceExist(String resourceName) {
1037         return resourceBusinessLogic.isResourceExist(resourceName);
1038     }
1039
1040     private ResourceBusinessLogic getResourceBL(ServletContext context) {
1041         WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
1042             .getAttribute(org.openecomp.sdc.common.api.Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
1043         WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
1044         return webApplicationContext.getBean(ResourceBusinessLogic.class);
1045     }
1046
1047     public ServletContext getServletContext() {
1048         return servletContext;
1049     }
1050
1051     public void setServletContext(ServletContext servletContext) {
1052         this.servletContext = servletContext;
1053     }
1054
1055     public AuditingManager getAuditingManager() {
1056         return auditingManager;
1057     }
1058
1059     @Autowired
1060     public void setAuditingManager(AuditingManager auditingManager) {
1061         this.auditingManager = auditingManager;
1062     }
1063
1064     public ResponseFormatManager getResponseFormatManager() {
1065         return responseFormatManager;
1066     }
1067
1068     public void setResponseFormatManager(ResponseFormatManager responseFormatManager) {
1069         this.responseFormatManager = responseFormatManager;
1070     }
1071
1072     public ResourceBusinessLogic getResourceBusinessLogic() {
1073         return resourceBusinessLogic;
1074     }
1075
1076     @Autowired
1077     public void setResourceBusinessLogic(ResourceBusinessLogic resourceBusinessLogic) {
1078         this.resourceBusinessLogic = resourceBusinessLogic;
1079     }
1080
1081     public IGraphLockOperation getGraphLockOperation() {
1082         return graphLockOperation;
1083     }
1084
1085     @Autowired
1086     public void setGraphLockOperation(IGraphLockOperation graphLockOperation) {
1087         this.graphLockOperation = graphLockOperation;
1088     }
1089
1090     private List<DataTypeDefinition> extractDataTypeFromJson(final ResourceBusinessLogic resourceBusinessLogic,
1091                                                              final Map<String, Object> foundElements,
1092                                                              final String model) {
1093         final List<DataTypeDefinition> dataTypeDefinitionList = new ArrayList<>();
1094         if (MapUtils.isNotEmpty(foundElements)) {
1095             final Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> dataTypeCacheAll =
1096                 resourceBusinessLogic.applicationDataTypeCache.getAll(model);
1097             if (dataTypeCacheAll.isLeft()) {
1098                 for (final Entry<String, Object> attributeNameValue : foundElements.entrySet()) {
1099                     final Object value = attributeNameValue.getValue();
1100                     if (value instanceof Map) {
1101                         final DataTypeDefinition dataTypeDefinition = createDataTypeDefinitionWithName(attributeNameValue);
1102                         final DataTypeDefinition dataTypeDefinitionParent = dataTypeCacheAll.left().value()
1103                             .get(dataTypeDefinition.getDerivedFromName());
1104                         dataTypeDefinition.setDerivedFrom(dataTypeDefinitionParent);
1105                         dataTypeDefinitionList.add(dataTypeDefinition);
1106                     } else {
1107                         dataTypeDefinitionList.add(createDataType(String.valueOf(value)));
1108                     }
1109                 }
1110             }
1111         }
1112         return dataTypeDefinitionList;
1113     }
1114 }