8c6e9cb2a2176554040ed22c153f36cdf1499468
[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\\s\\-\\_\\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, InterfaceDefinition> moduleInterfaces = new HashMap<>();
396             for (final Entry<String, Object> interfaceNameValue : toscaInterfaces.left().value().entrySet()) {
397                 final Either<InterfaceDefinition, ResultStatusEnum> eitherInterface = createModuleInterface(interfaceNameValue.getValue(), resource.getModel());
398                 if (eitherInterface.isRight()) {
399                     log.info("error when creating interface:{}, for resource:{}", interfaceNameValue.getKey(), resource.getName());
400                 } else {
401                     final InterfaceDefinition interfaceDefinition = eitherInterface.left().value();
402                     moduleInterfaces.put(interfaceDefinition.getType(), interfaceDefinition);
403                 }
404             }
405             if (!moduleInterfaces.isEmpty()) {
406                 resource.setInterfaces(moduleInterfaces);
407             }
408         }
409     }
410
411     private Either<InterfaceDefinition, ResultStatusEnum> createModuleInterface(final Object interfaceJson, final String model) {
412         try {
413             if (interfaceJson instanceof String) {
414                 final InterfaceDefinition interfaceDefinition = new InterfaceDefinition();
415                 interfaceDefinition.setType((String) interfaceJson);
416                 return Either.left(interfaceDefinition);
417             }
418             if (interfaceJson instanceof Map) {
419                 final Map<String, Object> interfaceJsonMap = (Map<String, Object>) interfaceJson;
420                 final InterfaceDefinition interfaceDefinition = interfaceDefinitionHandler.create(interfaceJsonMap, model);
421                 return Either.left(interfaceDefinition);
422             }
423             return Either.right(ResultStatusEnum.GENERAL_ERROR);
424         } catch (final Exception e) {
425             BeEcompErrorManager.getInstance().logBeSystemError("Import Resource- create interface");
426             log.debug("error when creating interface, message:{}", e.getMessage(), e);
427             return Either.right(ResultStatusEnum.GENERAL_ERROR);
428         }
429     }
430
431     private void setRequirements(Map<String, Object> toscaJson, Resource resource,
432                                  Resource parentResource) {// Note that parentResource can be null
433         Either<List<Object>, ResultStatusEnum> toscaRequirements = ImportUtils
434             .findFirstToscaListElement(toscaJson, ToscaTagNamesEnum.REQUIREMENTS);
435         if (toscaRequirements.isLeft()) {
436             List<Object> jsonRequirements = toscaRequirements.left().value();
437             Map<String, List<RequirementDefinition>> moduleRequirements = new HashMap<>();
438             // Checking for name duplication
439             Set<String> reqNames = new HashSet<>();
440             // Getting flattened list of capabilities of parent node - cap name
441
442             // to cap type
443             Map<String, String> reqName2TypeMap = getReqName2Type(parentResource);
444             for (Object jsonRequirementObj : jsonRequirements) {
445                 // Requirement
446                 Map<String, Object> requirementJsonWrapper = (Map<String, Object>) jsonRequirementObj;
447                 String requirementName = requirementJsonWrapper.keySet().iterator().next();
448                 String reqNameLowerCase = requirementName.toLowerCase();
449                 if (reqNames.contains(reqNameLowerCase)) {
450                     log.debug("More than one requirement with same name {} (case-insensitive) in imported TOSCA file is invalid", reqNameLowerCase);
451                     throw new ByActionStatusComponentException(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "requirement", reqNameLowerCase);
452                 }
453                 reqNames.add(reqNameLowerCase);
454                 RequirementDefinition requirementDef = createRequirementFromImportFile(requirementJsonWrapper.get(requirementName));
455                 requirementDef.setName(requirementName);
456                 if (moduleRequirements.containsKey(requirementDef.getCapability())) {
457                     moduleRequirements.get(requirementDef.getCapability()).add(requirementDef);
458                 } else {
459                     List<RequirementDefinition> list = new ArrayList<>();
460                     list.add(requirementDef);
461                     moduleRequirements.put(requirementDef.getCapability(), list);
462                 }
463                 // Validating against req/cap of "derived from" node
464                 Boolean validateVsParentCap = validateCapNameVsDerived(reqName2TypeMap, requirementDef.getCapability(), requirementDef.getName());
465                 if (!validateVsParentCap) {
466                     String parentResourceName = parentResource != null ? parentResource.getName() : "";
467                     log.debug("Requirement with name {} already exists in parent {}", requirementDef.getName(), parentResourceName);
468                     throw new ByActionStatusComponentException(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "requirement",
469                         requirementDef.getName().toLowerCase(), parentResourceName);
470                 }
471             }
472             if (moduleRequirements.size() > 0) {
473                 resource.setRequirements(moduleRequirements);
474             }
475         }
476     }
477
478     private RequirementDefinition createRequirementFromImportFile(Object requirementJson) {
479         RequirementDefinition requirement = new RequirementDefinition();
480         if (requirementJson instanceof String) {
481             String requirementJsonString = (String) requirementJson;
482             requirement.setCapability(requirementJsonString);
483         } else if (requirementJson instanceof Map) {
484             Map<String, Object> requirementJsonMap = (Map<String, Object>) requirementJson;
485             if (requirementJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITY.getElementName())) {
486                 requirement.setCapability((String) requirementJsonMap.get(ToscaTagNamesEnum.CAPABILITY.getElementName()));
487             }
488             if (requirementJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) {
489                 requirement.setNode((String) requirementJsonMap.get(ToscaTagNamesEnum.NODE.getElementName()));
490             }
491             if (requirementJsonMap.containsKey(ToscaTagNamesEnum.RELATIONSHIP.getElementName())) {
492                 requirement.setRelationship((String) requirementJsonMap.get(ToscaTagNamesEnum.RELATIONSHIP.getElementName()));
493             }
494             if (requirementJsonMap.containsKey(ToscaTagNamesEnum.OCCURRENCES.getElementName())) {
495                 List<Object> occurrencesList = (List) requirementJsonMap.get(ToscaTagNamesEnum.OCCURRENCES.getElementName());
496                 validateOccurrences(occurrencesList);
497                 requirement.setMinOccurrences(occurrencesList.get(0).toString());
498                 requirement.setMaxOccurrences(occurrencesList.get(1).toString());
499             }
500         } else {
501             throw new ByActionStatusComponentException(ActionStatus.INVALID_YAML);
502         }
503         return requirement;
504     }
505
506     private void setProperties(Map<String, Object> toscaJson, Resource resource) {
507         Map<String, Object> reducedToscaJson = new HashMap<>(toscaJson);
508         ImportUtils.removeElementFromJsonMap(reducedToscaJson, "capabilities");
509         Either<Map<String, PropertyDefinition>, ResultStatusEnum> properties = ImportUtils.getProperties(reducedToscaJson);
510         if (properties.isLeft()) {
511             List<PropertyDefinition> propertiesList = new ArrayList<>();
512             Map<String, PropertyDefinition> value = properties.left().value();
513             if (value != null) {
514                 for (Entry<String, PropertyDefinition> entry : value.entrySet()) {
515                     String name = entry.getKey();
516                     if (!PROPERTY_NAME_PATTERN_IGNORE_LENGTH.matcher(name).matches()) {
517                         log.debug("The property with invalid name {} occured upon import resource {}. ", name, resource.getName());
518                         throw new ByActionStatusComponentException(
519                             componentsUtils.convertFromResultStatusEnum(ResultStatusEnum.INVALID_PROPERTY_NAME, JsonPresentationFields.PROPERTY));
520                     }
521                     PropertyDefinition propertyDefinition = entry.getValue();
522                     propertyDefinition.setName(name);
523                     propertiesList.add(propertyDefinition);
524                 }
525             }
526             resource.setProperties(propertiesList);
527         } else if (properties.right().value() != ResultStatusEnum.ELEMENT_NOT_FOUND) {
528             throw new ByActionStatusComponentException(
529                 componentsUtils.convertFromResultStatusEnum(properties.right().value(), JsonPresentationFields.PROPERTY));
530         }
531     }
532
533     private void setAttributes(final Map<String, Object> originalToscaJsonMap, final Resource resource) {
534         final Map<String, Object> toscaJsonMap = new HashMap<>(originalToscaJsonMap);
535         ImportUtils.removeElementFromJsonMap(toscaJsonMap, "capabilities");
536         final Either<Map<String, AttributeDefinition>, ResultStatusEnum> getAttributeEither = ImportUtils.getAttributes(toscaJsonMap);
537         if (getAttributeEither.isRight()) {
538             final ResultStatusEnum resultStatus = getAttributeEither.right().value();
539             if (resultStatus == ResultStatusEnum.ELEMENT_NOT_FOUND) {
540                 return;
541             }
542             throw new ByActionStatusComponentException(componentsUtils.convertFromResultStatusEnum(resultStatus, JsonPresentationFields.ATTRIBUTES));
543         }
544         final List<AttributeDefinition> attributeDefinitionList = new ArrayList<>();
545         final Map<String, AttributeDefinition> attributeMap = getAttributeEither.left().value();
546         if (MapUtils.isEmpty(attributeMap)) {
547             return;
548         }
549         for (final Entry<String, AttributeDefinition> entry : attributeMap.entrySet()) {
550             final String name = entry.getKey();
551             if (!PROPERTY_NAME_PATTERN_IGNORE_LENGTH.matcher(name).matches()) {
552                 log.debug("Detected attribute with invalid name '{}' during resource '{}' import. ", name, resource.getName());
553                 throw new ByActionStatusComponentException(
554                     componentsUtils.convertFromResultStatusEnum(ResultStatusEnum.INVALID_ATTRIBUTE_NAME, JsonPresentationFields.ATTRIBUTES));
555             }
556             final AttributeDefinition attributeDefinition = entry.getValue();
557             attributeDefinition.setName(name);
558             attributeDefinitionList.add(attributeDefinition);
559         }
560         resource.setAttributes(attributeDefinitionList);
561     }
562
563     private Resource setDerivedFrom(Map<String, Object> toscaJson, Resource resource) {
564         Either<String, ResultStatusEnum> toscaDerivedFromElement = ImportUtils
565             .findFirstToscaStringElement(toscaJson, ToscaTagNamesEnum.DERIVED_FROM);
566         Resource derivedFromResource = null;
567         if (toscaDerivedFromElement.isLeft()) {
568             String derivedFrom = toscaDerivedFromElement.left().value();
569             log.debug("Derived from TOSCA name is {}", derivedFrom);
570             resource.setDerivedFrom(Arrays.asList(new String[]{derivedFrom}));
571             Either<Resource, StorageOperationStatus> latestByToscaResourceName = toscaOperationFacade.getLatestByToscaResourceName(derivedFrom, resource.getModel());
572             if (latestByToscaResourceName.isRight()) {
573                 StorageOperationStatus operationStatus = latestByToscaResourceName.right().value();
574                 if (operationStatus == StorageOperationStatus.NOT_FOUND) {
575                     operationStatus = StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND;
576                 }
577                 log.debug("Error when fetching parent resource {}, error: {}", derivedFrom, operationStatus);
578                 ActionStatus convertFromStorageResponse = componentsUtils.convertFromStorageResponse(operationStatus);
579                 BeEcompErrorManager.getInstance().logBeComponentMissingError("Import TOSCA YAML", "resource", derivedFrom);
580                 throw new ByActionStatusComponentException(convertFromStorageResponse, derivedFrom);
581             }
582             derivedFromResource = latestByToscaResourceName.left().value();
583         }
584         return derivedFromResource;
585     }
586
587     private void setCapabilities(Map<String, Object> toscaJson, Resource resource,
588                                  Resource parentResource) {// Note that parentResource can be null
589         Either<Map<String, Object>, ResultStatusEnum> toscaCapabilities = ImportUtils
590             .findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.CAPABILITIES);
591         if (toscaCapabilities.isLeft()) {
592             Map<String, Object> jsonCapabilities = toscaCapabilities.left().value();
593             Map<String, List<CapabilityDefinition>> moduleCapabilities = new HashMap<>();
594             Iterator<Entry<String, Object>> capabilitiesNameValue = jsonCapabilities.entrySet().iterator();
595             Set<String> capNames = new HashSet<>();
596             // Getting flattened list of capabilities of parent node - cap name
597
598             // to cap type
599             Map<String, String> capName2TypeMap = getCapName2Type(parentResource);
600             while (capabilitiesNameValue.hasNext()) {
601                 Entry<String, Object> capabilityNameValue = capabilitiesNameValue.next();
602                 // Validating that no req/cap duplicates exist in imported YAML
603                 String capNameLowerCase = capabilityNameValue.getKey().toLowerCase();
604                 if (capNames.contains(capNameLowerCase)) {
605                     log.debug("More than one capability with same name {} (case-insensitive) in imported TOSCA file is invalid", capNameLowerCase);
606                     throw new ByActionStatusComponentException(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "capability", capNameLowerCase);
607                 }
608                 capNames.add(capNameLowerCase);
609                 CapabilityDefinition capabilityDef = createCapabilityFromImportFile(capabilityNameValue.getValue());
610                 capabilityDef.setName(capabilityNameValue.getKey());
611                 if (moduleCapabilities.containsKey(capabilityDef.getType())) {
612                     moduleCapabilities.get(capabilityDef.getType()).add(capabilityDef);
613                 } else {
614                     List<CapabilityDefinition> list = new ArrayList<>();
615                     list.add(capabilityDef);
616                     moduleCapabilities.put(capabilityDef.getType(), list);
617                 }
618                 // Validating against req/cap of "derived from" node
619                 Boolean validateVsParentCap = validateCapNameVsDerived(capName2TypeMap, capabilityDef.getType(), capabilityDef.getName());
620                 if (!validateVsParentCap) {
621                     // Here parentResource is for sure not null, so it's
622
623                     // null-safe
624
625                     // Check added to avoid sonar warning
626                     String parentResourceName = parentResource != null ? parentResource.getName() : "";
627                     log.debug("Capability with name {} already exists in parent {}", capabilityDef.getName(), parentResourceName);
628                     throw new ByActionStatusComponentException(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "capability",
629                         capabilityDef.getName().toLowerCase(), parentResourceName);
630                 }
631             }
632             if (moduleCapabilities.size() > 0) {
633                 resource.setCapabilities(moduleCapabilities);
634             }
635         }
636     }
637
638     private Map<String, String> getCapName2Type(Resource parentResource) {
639         Map<String, String> capName2type = new HashMap<>();
640         if (parentResource != null) {
641             Map<String, List<CapabilityDefinition>> capabilities = parentResource.getCapabilities();
642             if (capabilities != null) {
643                 for (List<CapabilityDefinition> capDefinitions : capabilities.values()) {
644                     for (CapabilityDefinition capDefinition : capDefinitions) {
645                         String nameLowerCase = capDefinition.getName().toLowerCase();
646                         if (capName2type.get(nameLowerCase) != null) {
647                             String parentResourceName = parentResource.getName();
648                             log.debug("Resource with name {} has more than one capability with name {}, ignoring case", parentResourceName,
649                                 nameLowerCase);
650                             BeEcompErrorManager.getInstance().logInternalDataError("Import resource",
651                                 "Parent resource " + parentResourceName + " of imported resource has one or more capabilities with name "
652                                     + nameLowerCase, ErrorSeverity.ERROR);
653                             throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
654                         }
655                         capName2type.put(nameLowerCase, capDefinition.getType());
656                     }
657                 }
658             }
659         }
660         return capName2type;
661     }
662
663     private Map<String, String> getReqName2Type(Resource parentResource) {
664         Map<String, String> reqName2type = new HashMap<>();
665         if (parentResource != null) {
666             Map<String, List<RequirementDefinition>> requirements = parentResource.getRequirements();
667             if (requirements != null) {
668                 for (List<RequirementDefinition> reqDefinitions : requirements.values()) {
669                     for (RequirementDefinition reqDefinition : reqDefinitions) {
670                         String nameLowerCase = reqDefinition.getName().toLowerCase();
671                         if (reqName2type.get(nameLowerCase) != null) {
672                             String parentResourceName = parentResource.getName();
673                             log.debug("Resource with name {} has more than one requirement with name {}, ignoring case", parentResourceName,
674                                 nameLowerCase);
675                             BeEcompErrorManager.getInstance().logInternalDataError("Import resource",
676                                 "Parent resource " + parentResourceName + " of imported resource has one or more requirements with name "
677                                     + nameLowerCase, ErrorSeverity.ERROR);
678                             throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
679                         }
680                         reqName2type.put(nameLowerCase, reqDefinition.getCapability());
681                     }
682                 }
683             }
684         }
685         return reqName2type;
686     }
687
688     private Boolean validateCapNameVsDerived(Map<String, String> parentCapName2Type, String childCapabilityType, String reqCapName) {
689         String capNameLowerCase = reqCapName.toLowerCase();
690         log.trace("Validating capability {} vs parent resource", capNameLowerCase);
691         String parentCapType = parentCapName2Type.get(capNameLowerCase);
692         if (parentCapType != null) {
693             if (childCapabilityType.equals(parentCapType)) {
694                 log.debug("Capability with name {} is of same type {} for imported resource and its parent - this is OK", capNameLowerCase,
695                     childCapabilityType);
696                 return true;
697             }
698             Either<Boolean, StorageOperationStatus> capabilityTypeDerivedFrom = capabilityTypeOperation
699                 .isCapabilityTypeDerivedFrom(childCapabilityType, parentCapType);
700             if (capabilityTypeDerivedFrom.isRight()) {
701                 log.debug("Couldn't check whether imported resource capability derives from its parent's capability");
702                 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(capabilityTypeDerivedFrom.right().value()));
703             }
704             return capabilityTypeDerivedFrom.left().value();
705         }
706         return true;
707     }
708
709     private CapabilityDefinition createCapabilityFromImportFile(Object capabilityJson) {
710         CapabilityDefinition capabilityDefinition = new CapabilityDefinition();
711         if (capabilityJson instanceof String) {
712             String capabilityJsonString = (String) capabilityJson;
713             capabilityDefinition.setType(capabilityJsonString);
714         } else if (capabilityJson instanceof Map) {
715             Map<String, Object> capabilityJsonMap = (Map<String, Object>) capabilityJson;
716             // Type
717             if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
718                 capabilityDefinition.setType((String) capabilityJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName()));
719             }
720             // ValidSourceTypes
721             if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())) {
722                 capabilityDefinition
723                     .setValidSourceTypes((List<String>) capabilityJsonMap.get(ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName()));
724             }
725             // ValidSourceTypes
726             if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
727                 capabilityDefinition.setDescription((String) capabilityJsonMap.get(ToscaTagNamesEnum.DESCRIPTION.getElementName()));
728             }
729             if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.OCCURRENCES.getElementName())) {
730                 List<Object> occurrencesList = (List) capabilityJsonMap.get(ToscaTagNamesEnum.OCCURRENCES.getElementName());
731                 validateOccurrences(occurrencesList);
732                 capabilityDefinition.setMinOccurrences(occurrencesList.get(0).toString());
733                 capabilityDefinition.setMaxOccurrences(occurrencesList.get(1).toString());
734             }
735             if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
736                 Either<Map<String, PropertyDefinition>, ResultStatusEnum> propertiesRes = ImportUtils.getProperties(capabilityJsonMap);
737                 if (propertiesRes.isRight()) {
738                     throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND);
739                 } else {
740                     propertiesRes.left().value().entrySet().stream().forEach(e -> e.getValue().setName(e.getKey().toLowerCase()));
741                     List<ComponentInstanceProperty> capabilityProperties = propertiesRes.left().value().values().stream()
742                         .map(p -> new ComponentInstanceProperty(p, p.getDefaultValue(), null)).collect(Collectors.toList());
743                     capabilityDefinition.setProperties(capabilityProperties);
744                 }
745             }
746         } else if (!(capabilityJson instanceof List)) {
747             throw new ByActionStatusComponentException(ActionStatus.INVALID_YAML);
748         }
749         return capabilityDefinition;
750     }
751
752     private void handleImportResourceException(UploadResourceInfo resourceMetaData, User user, boolean isNormative, RuntimeException e) {
753         ResponseFormat responseFormat;
754         ComponentException newException;
755         if (e instanceof ComponentException) {
756             ComponentException componentException = (ComponentException) e;
757             responseFormat = componentException.getResponseFormat();
758             if (responseFormat == null) {
759                 responseFormat = getResponseFormatManager().getResponseFormat(componentException.getActionStatus(), componentException.getParams());
760             }
761             newException = componentException;
762         } else {
763             responseFormat = getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR);
764             newException = new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
765         }
766         String payloadName = (resourceMetaData != null) ? resourceMetaData.getPayloadName() : "";
767         BeEcompErrorManager.getInstance().logBeSystemError("Import Resource " + payloadName);
768         log.debug("Error when importing resource from payload:{} Exception text: {}", payloadName, e.getMessage(), e);
769         auditErrorImport(resourceMetaData, user, responseFormat, isNormative);
770         throw newException;
771     }
772
773     private void auditErrorImport(UploadResourceInfo resourceMetaData, User user, ResponseFormat errorResponseWrapper, boolean isNormative) {
774         String version, lifeCycleState;
775         if (isNormative) {
776             version = TypeUtils.getFirstCertifiedVersionVersion();
777             lifeCycleState = LifecycleStateEnum.CERTIFIED.name();
778         } else {
779             version = "";
780             lifeCycleState = LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name();
781         }
782         String message = "";
783         if (errorResponseWrapper.getMessageId() != null) {
784             message = errorResponseWrapper.getMessageId() + ": ";
785         }
786         message += errorResponseWrapper.getFormattedMessage();
787         AuditEventFactory factory = new AuditImportResourceAdminEventFactory(
788             CommonAuditData.newBuilder().status(errorResponseWrapper.getStatus()).description(message).requestId(ThreadLocalsHolder.getUuid())
789                 .build(), new ResourceCommonInfo(resourceMetaData.getName(), ComponentTypeEnum.RESOURCE.getValue()),
790             ResourceVersionInfo.newBuilder().state(lifeCycleState).version(version).build(),
791             ResourceVersionInfo.newBuilder().state("").version("").build(), "", user, "");
792         getAuditingManager().auditEvent(factory);
793     }
794
795     private void setMetaDataFromJson(final UploadResourceInfo resourceMetaData, final Resource resource) {
796         this.populateResourceMetadata(resourceMetaData, resource);
797         resource.setCreatorUserId(resourceMetaData.getContactId());
798         final String payloadData = resourceMetaData.getPayloadData();
799         if (payloadData != null) {
800             resource.setToscaVersion(getToscaVersion(payloadData));
801         }
802         final List<CategoryDefinition> categories = resourceMetaData.getCategories();
803         calculateResourceIsAbstract(resource, categories);
804     }
805
806     private Map<String, Object> decodePayload(final String payloadData) {
807         final String decodedPayload = new String(Base64.decodeBase64(payloadData));
808         return (Map<String, Object>) new Yaml().load(decodedPayload);
809     }
810
811     private String getToscaVersion(final String payloadData) {
812         final Map<String, Object> mappedToscaTemplate = decodePayload(payloadData);
813         final Either<String, ResultStatusEnum> findFirstToscaStringElement = ImportUtils
814             .findFirstToscaStringElement(mappedToscaTemplate, ToscaTagNamesEnum.TOSCA_VERSION);
815         if (findFirstToscaStringElement.isLeft()) {
816             return findFirstToscaStringElement.left().value();
817         } else {
818             return null;
819         }
820     }
821
822     private void calculateResourceIsAbstract(Resource resource, List<CategoryDefinition> categories) {
823         if (categories != null && !categories.isEmpty()) {
824             CategoryDefinition categoryDef = categories.get(0);
825             resource.setAbstract(false);
826             if (categoryDef != null && categoryDef.getName() != null && categoryDef.getName().equals(Constants.ABSTRACT_CATEGORY_NAME)) {
827                 SubCategoryDefinition subCategoryDef = categoryDef.getSubcategories().get(0);
828                 if (subCategoryDef != null && subCategoryDef.getName().equals(Constants.ABSTRACT_SUBCATEGORY)) {
829                     resource.setAbstract(true);
830                 }
831             }
832         }
833     }
834
835     private void setConstantMetaData(Resource resource, boolean shouldBeCertified) {
836         String version;
837         LifecycleStateEnum state;
838         if (shouldBeCertified) {
839             version = TypeUtils.getFirstCertifiedVersionVersion();
840             state = ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE;
841         } else {
842             version = ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION;
843             state = ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT;
844         }
845         resource.setVersion(version);
846         resource.setLifecycleState(state);
847         resource.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
848         resource.setVendorName(ImportUtils.Constants.VENDOR_NAME);
849         resource.setVendorRelease(ImportUtils.Constants.VENDOR_RELEASE);
850     }
851
852     private void validateOccurrences(List<Object> occurrensesList) {
853         if (!ValidationUtils.validateListNotEmpty(occurrensesList)) {
854             log.debug("Occurrenses list empty");
855             throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES);
856         }
857         if (occurrensesList.size() < 2) {
858             log.debug("Occurrenses list size not 2");
859             throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES);
860         }
861         Object minObj = occurrensesList.get(0);
862         Object maxObj = occurrensesList.get(1);
863         Integer minOccurrences;
864         Integer maxOccurrences;
865         if (minObj instanceof Integer) {
866             minOccurrences = (Integer) minObj;
867         } else {
868             log.debug("Invalid occurrenses format. low_bound occurrense must be Integer {}", minObj);
869             throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES);
870         }
871         if (minOccurrences < 0) {
872             log.debug("Invalid occurrenses format.low_bound occurrense negative {}", minOccurrences);
873             throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES);
874         }
875         if (maxObj instanceof String) {
876             if (!"UNBOUNDED".equals(maxObj)) {
877                 log.debug("Invalid occurrenses format. Max occurrence is {}", maxObj);
878                 throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES);
879             }
880         } else {
881             if (maxObj instanceof Integer) {
882                 maxOccurrences = (Integer) maxObj;
883             } else {
884                 log.debug("Invalid occurrenses format.  Max occurrence is {}", maxObj);
885                 throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES);
886             }
887             if (maxOccurrences < 0 || maxOccurrences < minOccurrences) {
888                 log.debug("Invalid occurrenses format.  min occurrence is {}, Max occurrence is {}", minOccurrences, maxOccurrences);
889                 throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES);
890             }
891         }
892     }
893
894     public synchronized void init(ServletContext servletContext) {
895         if (this.servletContext == null) {
896             this.servletContext = servletContext;
897             responseFormatManager = ResponseFormatManager.getInstance();
898             resourceBusinessLogic = getResourceBL(servletContext);
899         }
900     }
901
902     public boolean isResourceExist(String resourceName) {
903         return resourceBusinessLogic.isResourceExist(resourceName);
904     }
905
906     private ResourceBusinessLogic getResourceBL(ServletContext context) {
907         WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
908             .getAttribute(org.openecomp.sdc.common.api.Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
909         WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
910         return webApplicationContext.getBean(ResourceBusinessLogic.class);
911     }
912
913     public ServletContext getServletContext() {
914         return servletContext;
915     }
916
917     public void setServletContext(ServletContext servletContext) {
918         this.servletContext = servletContext;
919     }
920
921     public AuditingManager getAuditingManager() {
922         return auditingManager;
923     }
924
925     @Autowired
926     public void setAuditingManager(AuditingManager auditingManager) {
927         this.auditingManager = auditingManager;
928     }
929
930     public ResponseFormatManager getResponseFormatManager() {
931         return responseFormatManager;
932     }
933
934     public void setResponseFormatManager(ResponseFormatManager responseFormatManager) {
935         this.responseFormatManager = responseFormatManager;
936     }
937
938     public ResourceBusinessLogic getResourceBusinessLogic() {
939         return resourceBusinessLogic;
940     }
941
942     @Autowired
943     public void setResourceBusinessLogic(ResourceBusinessLogic resourceBusinessLogic) {
944         this.resourceBusinessLogic = resourceBusinessLogic;
945     }
946
947     public IGraphLockOperation getGraphLockOperation() {
948         return graphLockOperation;
949     }
950
951     @Autowired
952     public void setGraphLockOperation(IGraphLockOperation graphLockOperation) {
953         this.graphLockOperation = graphLockOperation;
954     }
955
956     private List<DataTypeDefinition> extractDataTypeFromJson(final ResourceBusinessLogic resourceBusinessLogic,
957                                                              final Map<String, Object> foundElements,
958                                                              final String model) {
959         final List<DataTypeDefinition> dataTypeDefinitionList = new ArrayList<>();
960         if (MapUtils.isNotEmpty(foundElements)) {
961             final Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> dataTypeCacheAll =
962                 resourceBusinessLogic.applicationDataTypeCache.getAll(model);
963             if (dataTypeCacheAll.isLeft()) {
964                 for (final Entry<String, Object> attributeNameValue : foundElements.entrySet()) {
965                     final Object value = attributeNameValue.getValue();
966                     if (value instanceof Map) {
967                         final DataTypeDefinition dataTypeDefinition = createDataTypeDefinitionWithName(attributeNameValue);
968                         final DataTypeDefinition dataTypeDefinitionParent = dataTypeCacheAll.left().value()
969                             .get(dataTypeDefinition.getDerivedFromName());
970                         dataTypeDefinition.setDerivedFrom(dataTypeDefinitionParent);
971                         dataTypeDefinitionList.add(dataTypeDefinition);
972                     } else {
973                         dataTypeDefinitionList.add(createDataType(String.valueOf(value)));
974                     }
975                 }
976             }
977         }
978         return dataTypeDefinitionList;
979     }
980 }