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