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