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