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