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