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