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