ComponentCache & ComponentCassandraDao removal
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / components / impl / ResourceBusinessLogic.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
23 package org.openecomp.sdc.be.components.impl;
24
25
26 import static java.util.stream.Collectors.joining;
27 import static java.util.stream.Collectors.toList;
28 import static java.util.stream.Collectors.toMap;
29 import static java.util.stream.Collectors.toSet;
30 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
31 import static org.apache.commons.collections.MapUtils.isEmpty;
32 import static org.apache.commons.collections.MapUtils.isNotEmpty;
33 import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaStringElement;
34 import static org.openecomp.sdc.be.components.impl.ImportUtils.getPropertyJsonStringValue;
35 import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN;
36
37 import java.util.ArrayList;
38 import java.util.Collection;
39 import java.util.EnumMap;
40 import java.util.HashMap;
41 import java.util.HashSet;
42 import java.util.Iterator;
43 import java.util.List;
44 import java.util.ListIterator;
45 import java.util.Map;
46 import java.util.Map.Entry;
47 import java.util.Optional;
48 import java.util.Set;
49 import java.util.function.Function;
50 import java.util.regex.Pattern;
51
52 import fj.data.Either;
53 import org.apache.commons.codec.binary.Base64;
54 import org.apache.commons.collections.CollectionUtils;
55 import org.apache.commons.collections.MapUtils;
56 import org.apache.commons.collections4.ListUtils;
57 import org.apache.commons.lang.StringUtils;
58 import org.apache.commons.lang3.tuple.ImmutablePair;
59 import org.openecomp.sdc.be.components.csar.CsarArtifactsAndGroupsBusinessLogic;
60 import org.openecomp.sdc.be.components.csar.CsarBusinessLogic;
61 import org.openecomp.sdc.be.components.csar.CsarInfo;
62 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
63 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationInfo;
64 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
65 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
66 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
67 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
68 import org.openecomp.sdc.be.components.impl.utils.CINodeFilterUtils;
69 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
70 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
71 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
72 import org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic;
73 import org.openecomp.sdc.be.components.merge.utils.MergeInstanceUtils;
74 import org.openecomp.sdc.be.config.BeEcompErrorManager;
75 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
76 import org.openecomp.sdc.be.config.ConfigurationManager;
77 import org.openecomp.sdc.be.dao.api.ActionStatus;
78 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
79 import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
80 import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils;
81 import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
82 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
83 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
84 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
85 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
86 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
87 import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum;
88 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
89 import org.openecomp.sdc.be.datatypes.enums.CreatedFrom;
90 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
91 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
92 import org.openecomp.sdc.be.impl.ComponentsUtils;
93 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
94 import org.openecomp.sdc.be.info.NodeTypeInfoToUpdateArtifacts;
95 import org.openecomp.sdc.be.model.ArtifactDefinition;
96 import org.openecomp.sdc.be.model.CapabilityDefinition;
97 import org.openecomp.sdc.be.model.CapabilityRequirementRelationship;
98 import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
99 import org.openecomp.sdc.be.model.Component;
100 import org.openecomp.sdc.be.model.ComponentInstance;
101 import org.openecomp.sdc.be.model.ComponentInstanceInput;
102 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
103 import org.openecomp.sdc.be.model.ComponentParametersView;
104 import org.openecomp.sdc.be.model.DataTypeDefinition;
105 import org.openecomp.sdc.be.model.GroupDefinition;
106 import org.openecomp.sdc.be.model.InputDefinition;
107 import org.openecomp.sdc.be.model.InterfaceDefinition;
108 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
109 import org.openecomp.sdc.be.model.LifecycleStateEnum;
110 import org.openecomp.sdc.be.model.NodeTypeInfo;
111 import org.openecomp.sdc.be.model.Operation;
112 import org.openecomp.sdc.be.model.ParsedToscaYamlInfo;
113 import org.openecomp.sdc.be.model.PropertyDefinition;
114 import org.openecomp.sdc.be.model.RelationshipImpl;
115 import org.openecomp.sdc.be.model.RelationshipInfo;
116 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
117 import org.openecomp.sdc.be.model.RequirementDefinition;
118 import org.openecomp.sdc.be.model.Resource;
119 import org.openecomp.sdc.be.model.UploadCapInfo;
120 import org.openecomp.sdc.be.model.UploadComponentInstanceInfo;
121 import org.openecomp.sdc.be.model.UploadInfo;
122 import org.openecomp.sdc.be.model.UploadNodeFilterInfo;
123 import org.openecomp.sdc.be.model.UploadPropInfo;
124 import org.openecomp.sdc.be.model.UploadReqInfo;
125 import org.openecomp.sdc.be.model.UploadResourceInfo;
126 import org.openecomp.sdc.be.model.User;
127 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
128 import org.openecomp.sdc.be.model.category.CategoryDefinition;
129 import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
130 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
131 import org.openecomp.sdc.be.model.operations.StorageException;
132 import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation;
133 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
134 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
135 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
136 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
137 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
138 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
139 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
140 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
141 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
142 import org.openecomp.sdc.be.tosca.CsarUtils;
143 import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo;
144 import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
145 import org.openecomp.sdc.be.user.IUserBusinessLogic;
146 import org.openecomp.sdc.be.user.UserBusinessLogic;
147 import org.openecomp.sdc.be.utils.CommonBeUtils;
148 import org.openecomp.sdc.be.utils.TypeUtils;
149 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
150 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
151 import org.openecomp.sdc.common.api.Constants;
152 import org.openecomp.sdc.common.datastructure.Wrapper;
153 import org.openecomp.sdc.common.kpi.api.ASDCKpiApi;
154 import org.openecomp.sdc.common.log.wrappers.Logger;
155 import org.openecomp.sdc.common.util.GeneralUtility;
156 import org.openecomp.sdc.common.util.ValidationUtils;
157 import org.openecomp.sdc.exception.ResponseFormat;
158 import org.springframework.beans.factory.annotation.Autowired;
159 import org.springframework.web.context.WebApplicationContext;
160 import org.yaml.snakeyaml.DumperOptions;
161 import org.yaml.snakeyaml.Yaml;
162
163 import javax.servlet.ServletContext;
164
165 @org.springframework.stereotype.Component("resourceBusinessLogic")
166 public class ResourceBusinessLogic extends ComponentBusinessLogic {
167
168     private static final String DELETE_RESOURCE = "Delete Resource";
169     private static final String IN_RESOURCE = "  in resource {} ";
170     private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
171     public static final String INITIAL_VERSION = "0.1";
172     private static final Logger log = Logger.getLogger(ResourceBusinessLogic.class);
173     private static final String CERTIFICATION_ON_IMPORT = "certification on import";
174     private static final String CREATE_RESOURCE = "Create Resource";
175     private static final String VALIDATE_DERIVED_BEFORE_UPDATE = "validate derived before update";
176     private static final String CATEGORY_IS_EMPTY = "Resource category is empty";
177     private static final String CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES = "Create Resource - validateCapabilityTypesCreate";
178     private static final String COMPONENT_INSTANCE_WITH_NAME = "component instance with name ";
179     private static final String COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE = "component instance with name {}  in resource {} ";
180
181
182     @Autowired
183     private ICapabilityTypeOperation capabilityTypeOperation = null;
184
185     @Autowired
186     private IInterfaceLifecycleOperation interfaceTypeOperation = null;
187
188     @Autowired
189     private LifecycleBusinessLogic lifecycleBusinessLogic;
190
191     @Autowired
192     private ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
193
194     @Autowired
195     private ResourceImportManager resourceImportManager;
196
197     @Autowired
198     private InputsBusinessLogic inputsBusinessLogic;
199
200     @Autowired
201     private CompositionBusinessLogic compositionBusinessLogic;
202
203     @Autowired
204     private ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic;
205
206     @Autowired
207     private CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic;
208
209     @Autowired
210     private MergeInstanceUtils mergeInstanceUtils;
211
212     @Autowired
213     private UiComponentDataConverter uiComponentDataConverter;
214
215     @Autowired
216     private CsarBusinessLogic csarBusinessLogic;
217
218     /**
219      * Default constructor
220      */
221     public ResourceBusinessLogic() {
222         log.debug("ResourceBusinessLogic started");
223     }
224
225     public LifecycleBusinessLogic getLifecycleBusinessLogic() {
226         return lifecycleBusinessLogic;
227     }
228
229     public void setLifecycleManager(LifecycleBusinessLogic lifecycleBusinessLogic) {
230         this.lifecycleBusinessLogic = lifecycleBusinessLogic;
231     }
232
233     public IElementOperation getElementDao() {
234         return elementDao;
235     }
236
237     public void setElementDao(IElementOperation elementDao) {
238         this.elementDao = elementDao;
239     }
240
241     public IUserBusinessLogic getUserAdmin() {
242         return this.userAdmin;
243     }
244
245     public void setUserAdmin(UserBusinessLogic userAdmin) {
246         this.userAdmin = userAdmin;
247     }
248
249     public ComponentsUtils getComponentsUtils() {
250         return this.componentsUtils;
251     }
252
253     public void setComponentsUtils(ComponentsUtils componentsUtils) {
254         this.componentsUtils = componentsUtils;
255     }
256
257     public ArtifactsBusinessLogic getArtifactsManager() {
258         return artifactsBusinessLogic;
259     }
260
261     public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) {
262         this.artifactsBusinessLogic = artifactsManager;
263     }
264
265     public ApplicationDataTypeCache getApplicationDataTypeCache() {
266         return applicationDataTypeCache;
267     }
268
269     public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) {
270         this.applicationDataTypeCache = applicationDataTypeCache;
271     }
272
273     public void setInterfaceTypeOperation(IInterfaceLifecycleOperation interfaceTypeOperation) {
274         this.interfaceTypeOperation = interfaceTypeOperation;
275     }
276
277     /**
278      * the method returns a list of all the resources that are certified, the
279      * returned resources are only abstract or only none abstract according to
280      * the given param
281      *
282      * @param getAbstract
283      * @param userId      TODO
284      * @return
285      */
286     public List<Resource> getAllCertifiedResources(boolean getAbstract,
287                                                    HighestFilterEnum highestFilter, String userId) {
288         User user = validateUserExists(userId, "get All Certified Resources", false);
289         Boolean isHighest = null;
290         switch (highestFilter) {
291             case ALL:
292                 break;
293             case HIGHEST_ONLY:
294                 isHighest = true;
295                 break;
296             case NON_HIGHEST_ONLY:
297                 isHighest = false;
298                 break;
299             default:
300                 break;
301         }
302         Either<List<Resource>, StorageOperationStatus> getResponse = toscaOperationFacade
303                 .getAllCertifiedResources(getAbstract, isHighest);
304
305         if (getResponse.isRight()) {
306             throw new StorageException(getResponse.right().value());
307         }
308
309         return getResponse.left().value();
310     }
311
312     public Either<Map<String, Boolean>, ResponseFormat> validateResourceNameExists(String resourceName,
313                                                                                    ResourceTypeEnum resourceTypeEnum, String userId) {
314
315         validateUserExists(userId, "validate Resource Name Exists", false);
316
317         Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
318                 .validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE);
319         // DE242223
320         janusGraphDao.commit();
321
322         if (dataModelResponse.isLeft()) {
323             Map<String, Boolean> result = new HashMap<>();
324             result.put("isValid", dataModelResponse.left().value());
325             log.debug("validation was successfully performed.");
326             return Either.left(result);
327         }
328
329         ResponseFormat responseFormat = componentsUtils
330                 .getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
331
332         return Either.right(responseFormat);
333     }
334
335     public Resource createResource(Resource resource, AuditingActionEnum auditingAction,
336                                    User user, Map<String, byte[]> csarUIPayload, String payloadName) {
337         validateResourceBeforeCreate(resource, user, false);
338         String csarUUID = payloadName == null ? resource.getCsarUUID() : payloadName;
339         if (StringUtils.isNotEmpty(csarUUID)) {
340             csarBusinessLogic.validateCsarBeforeCreate(resource, auditingAction, user, csarUUID);
341             log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID);
342             return createResourceFromCsar(resource, user, csarUIPayload, csarUUID);
343         }
344
345         return createResourceByDao(resource, user, auditingAction, false, false);
346     }
347
348     public Resource validateAndUpdateResourceFromCsar(Resource resource, User user,
349                                                       Map<String, byte[]> csarUIPayload, String payloadName, String resourceUniqueId) {
350         String csarUUID = payloadName;
351         String csarVersion = null;
352         Resource updatedResource = null;
353         if (payloadName == null) {
354             csarUUID = resource.getCsarUUID();
355             csarVersion = resource.getCsarVersion();
356         }
357         if (csarUUID != null && !csarUUID.isEmpty()) {
358             Resource oldResource = getResourceByUniqueId(resourceUniqueId);
359             validateCsarUuidMatching(oldResource, resource, csarUUID, resourceUniqueId, user);
360             validateCsarIsNotAlreadyUsed(oldResource, resource, csarUUID, user);
361             if (oldResource != null && ValidationUtils.hasBeenCertified(oldResource.getVersion())) {
362                 overrideImmutableMetadata(oldResource, resource);
363             }
364             validateResourceBeforeCreate(resource, user, false);
365             String oldCsarVersion = oldResource.getCsarVersion();
366             log.debug("CsarUUID is {} - going to update resource with UniqueId {} from CSAR", csarUUID,
367                     resourceUniqueId);
368             // (on boarding flow): If the update includes same csarUUID and
369             // same csarVersion as already in the VF - no need to import the
370             // csar (do only metadata changes if there are).
371             if (csarVersion != null && oldCsarVersion != null && oldCsarVersion.equals(csarVersion)) {
372                 updatedResource = updateResourceMetadata(resourceUniqueId, resource, oldResource, user,
373                         false);
374             } else {
375                 updatedResource = updateResourceFromCsar(oldResource, resource, user,
376                         AuditingActionEnum.UPDATE_RESOURCE_METADATA, false, csarUIPayload, csarUUID);
377             }
378         } else {
379             log.debug("Failed to update resource {}, csarUUID or payload name is missing", resource.getSystemName());
380             ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CSAR_UUID,
381                     resource.getName());
382             componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.CREATE_RESOURCE);
383             throw new ByActionStatusComponentException(ActionStatus.MISSING_CSAR_UUID, resource.getName());
384         }
385         return updatedResource;
386     }
387
388     private void validateCsarIsNotAlreadyUsed(Resource oldResource,
389                                               Resource resource, String csarUUID, User user) {
390         // (on boarding flow): If the update includes a csarUUID: verify this
391         // csarUUID is not in use by another VF, If it is - use same error as
392         // above:
393         // "Error: The VSP with UUID %1 was already imported for VF %2. Please
394         // select another or update the existing VF." %1 - csarUUID, %2 - VF
395         // name
396         Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = toscaOperationFacade
397                 .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUUID, resource.getSystemName());
398         if (resourceLinkedToCsarRes.isRight()) {
399             if (!StorageOperationStatus.NOT_FOUND.equals(resourceLinkedToCsarRes.right().value())) {
400                 log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID,
401                         resource.getSystemName());
402                 throw new StorageException(resourceLinkedToCsarRes.right().value());
403             }
404         } else if (!resourceLinkedToCsarRes.left().value().getUniqueId().equals(oldResource.getUniqueId())
405                 && !resourceLinkedToCsarRes.left().value().getName().equals(oldResource.getName())) {
406             ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID,
407                     resourceLinkedToCsarRes.left().value().getName());
408             componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
409             throw new ByActionStatusComponentException(ActionStatus.VSP_ALREADY_EXISTS, csarUUID,
410                     resourceLinkedToCsarRes.left().value().getName());
411         }
412     }
413
414     private void validateCsarUuidMatching(Resource resource,
415                                           Resource oldResource, String csarUUID, String resourceUniqueId, User user) {
416         // (on boarding flow): If the update includes csarUUID which is
417         // different from the csarUUID of the VF - fail with
418         // error: "Error: Resource %1 cannot be updated using since it is linked
419         // to a different VSP" %1 - VF name
420         String oldCsarUUID = oldResource.getCsarUUID();
421         if (oldCsarUUID != null && !oldCsarUUID.isEmpty() && !csarUUID.equals(oldCsarUUID)) {
422             log.debug(
423                     "Failed to update resource with UniqueId {} using Csar {}, since the resource is linked to a different VSP {}",
424                     resourceUniqueId, csarUUID, oldCsarUUID);
425             ResponseFormat errorResponse = componentsUtils.getResponseFormat(
426                     ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
427             componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
428             throw new ByActionStatusComponentException(ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
429         }
430     }
431
432     private Resource getResourceByUniqueId(String resourceUniqueId) {
433         Either<Resource, StorageOperationStatus> oldResourceRes = toscaOperationFacade.getToscaFullElement(resourceUniqueId);
434         if (oldResourceRes.isRight()) {
435             log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId,
436                     oldResourceRes.right().value());
437             throw new StorageException(oldResourceRes.right().value());
438         }
439         return oldResourceRes.left().value();
440     }
441
442     private void overrideImmutableMetadata(Resource oldRresource, Resource resource) {
443         resource.setName(oldRresource.getName());
444         resource.setIcon(oldRresource.getIcon());
445         resource.setTags(oldRresource.getTags());
446         resource.setCategories(oldRresource.getCategories());
447         resource.setDerivedFrom(oldRresource.getDerivedFrom());
448     }
449
450     private Resource updateResourceFromCsar(Resource oldResource, Resource newResource,
451                                             User user, AuditingActionEnum updateResource, boolean inTransaction,
452                                             Map<String, byte[]> csarUIPayload, String csarUUID) {
453         Resource updatedResource = null;
454         validateLifecycleState(oldResource, user);
455         String lockedResourceId = oldResource.getUniqueId();
456         List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
457         CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(newResource, oldResource, user, csarUIPayload, csarUUID);
458         Either<Boolean, ResponseFormat> lockResult = lockComponent(lockedResourceId, oldResource,
459                 "update Resource From Csar");
460         if (lockResult.isRight()) {
461             throw new ByResponseFormatComponentException(lockResult.right().value());
462         }
463
464         Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
465
466         Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
467                 nodeTypesInfo, csarInfo, oldResource);
468         if (findNodeTypesArtifactsToHandleRes.isRight()) {
469             log.debug("failed to find node types for update with artifacts during import csar {}. ",
470                     csarInfo.getCsarUUID());
471             throw new ByResponseFormatComponentException(findNodeTypesArtifactsToHandleRes.right().value());
472         }
473         Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes
474                 .left().value();
475         try {
476             updatedResource = updateResourceFromYaml(oldResource, newResource, updateResource, createdArtifacts, csarInfo.getMainTemplateName(),
477                     csarInfo.getMainTemplateContent(), csarInfo, nodeTypesInfo, nodeTypesArtifactsToHandle, null, false);
478
479             connectUiRelations(oldResource, updatedResource);
480
481         } catch (ComponentException|StorageException e){
482             rollback(inTransaction, newResource, createdArtifacts, null);
483             throw e;
484         }
485         finally {
486             janusGraphDao.commit();
487             log.debug("unlock resource {}", lockedResourceId);
488             graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
489         }
490         return updatedResource;
491
492     }
493
494     private void validateLifecycleState(Resource oldResource, User user) {
495         if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.equals(oldResource.getLifecycleState()) &&
496                 !oldResource.getLastUpdaterUserId().equals(user.getUserId())) {
497             log.debug("#validateLifecycleState - Current user is not last updater, last updater userId: {}, current user userId: {}",
498                     oldResource.getLastUpdaterUserId(), user.getUserId());
499             throw new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION);
500         }
501     }
502
503     private Either<Resource, ResponseFormat> connectUiRelations(Resource oldResource, Resource newResource) {
504         Either<Resource, ResponseFormat> result;
505
506         List<RequirementCapabilityRelDef> updatedUiRelations = mergeInstanceUtils.updateUiRelationsInResource(oldResource, newResource);
507
508         StorageOperationStatus status = toscaOperationFacade.associateResourceInstances(newResource.getUniqueId(), updatedUiRelations);
509         if (status == StorageOperationStatus.OK) {
510             newResource.getComponentInstancesRelations().addAll(updatedUiRelations);
511             result = Either.left(newResource);
512         } else {
513             result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status), newResource));
514         }
515
516         return result;
517     }
518
519     private Resource updateResourceFromYaml(Resource oldRresource, Resource newRresource,
520                                             AuditingActionEnum actionEnum, List<ArtifactDefinition> createdArtifacts,
521                                             String yamlFileName, String yamlFileContent, CsarInfo csarInfo, Map<String, NodeTypeInfo> nodeTypesInfo,
522                                             Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
523                                             String nodeName, boolean isNested) {
524         boolean inTransaction = true;
525         boolean shouldLock = false;
526         Resource preparedResource = null;
527         ParsedToscaYamlInfo uploadComponentInstanceInfoMap = null;
528         try {
529             uploadComponentInstanceInfoMap = csarBusinessLogic.getParsedToscaYamlInfo(yamlFileContent, yamlFileName, nodeTypesInfo, csarInfo, nodeName);
530             Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.getInstances();
531             if (MapUtils.isEmpty(instances) && newRresource.getResourceType() != ResourceTypeEnum.PNF) {
532                 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlFileName);
533             }
534             preparedResource = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(),
535                     inTransaction, shouldLock, isNested).left;
536             log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent);
537             handleResourceGenericType(preparedResource);
538             handleNodeTypes(yamlFileName, preparedResource, yamlFileContent,
539                     shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo, csarInfo, nodeName);
540             preparedResource = createInputsOnResource(preparedResource,  uploadComponentInstanceInfoMap.getInputs());
541             preparedResource = createResourceInstances(yamlFileName, preparedResource, instances, csarInfo.getCreatedNodes());
542             preparedResource = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, instances);
543         } catch (ByResponseFormatComponentException e) {
544             ResponseFormat responseFormat = e.getResponseFormat();
545             log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat);
546             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum);
547             throw e;
548         } catch (ByActionStatusComponentException e) {
549             ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
550             log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat);
551             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum);
552             throw e;
553         } catch (StorageException e){
554             ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
555             log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat);
556             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum);
557             throw e;
558         }
559         Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
560                 .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.getGroups(),
561                         preparedResource.getSystemName());
562         if (validateUpdateVfGroupNamesRes.isRight()) {
563
564             throw new ByResponseFormatComponentException(validateUpdateVfGroupNamesRes.right().value());
565         }
566         // add groups to resource
567         Map<String, GroupDefinition> groups;
568
569         if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
570             groups = validateUpdateVfGroupNamesRes.left().value();
571         } else {
572             groups = uploadComponentInstanceInfoMap.getGroups();
573         }
574         handleGroupsProperties(preparedResource, groups);
575         preparedResource =  updateGroupsOnResource(preparedResource, groups);
576         NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
577                 nodeTypesArtifactsToHandle);
578
579         Either<Resource, ResponseFormat> updateArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.UPDATE, createdArtifacts, yamlFileName,
580                 csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
581         if (updateArtifactsEither.isRight()) {
582             log.debug("failed to update artifacts {}", updateArtifactsEither.right().value());
583             throw new ByResponseFormatComponentException(updateArtifactsEither.right().value());
584         }
585         preparedResource = getResourceWithGroups(updateArtifactsEither.left().value().getUniqueId());
586
587         ActionStatus mergingPropsAndInputsStatus = resourceDataMergeBusinessLogic.mergeResourceEntities(oldRresource, preparedResource);
588         if (mergingPropsAndInputsStatus != ActionStatus.OK) {
589             ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus,
590                     preparedResource);
591             throw new ByResponseFormatComponentException(responseFormat);
592         }
593         compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier().getUserId());
594         return preparedResource;
595     }
596
597     private Either<Resource, ResponseFormat> createOrUpdateArtifacts(ArtifactOperationEnum operation, List<ArtifactDefinition> createdArtifacts,
598                                                                      String yamlFileName, CsarInfo csarInfo, Resource preparedResource,
599                                                                      NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts, boolean inTransaction, boolean shouldLock) {
600
601         String nodeName = nodeTypeInfoToUpdateArtifacts.getNodeName();
602         Resource resource = preparedResource;
603
604         Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts
605                 .getNodeTypesArtifactsToHandle();
606         if (preparedResource.getResourceType() == ResourceTypeEnum.CVFC) {
607             if (nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null && !nodeTypesArtifactsToHandle.get(nodeName).isEmpty()) {
608                 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes =
609                         handleNodeTypeArtifacts(preparedResource, nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(), inTransaction, true);
610                 if (handleNodeTypeArtifactsRes.isRight()) {
611                     return Either.right(handleNodeTypeArtifactsRes.right().value());
612                 }
613             }
614         } else {
615             Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource, csarInfo, createdArtifacts,
616                     artifactsBusinessLogic.new ArtifactOperationInfo(false, false, operation), shouldLock, inTransaction);
617             log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
618             if (createdCsarArtifactsEither.isRight()) {
619                 return createdCsarArtifactsEither;
620
621             }
622             resource = createdCsarArtifactsEither.left().value();
623         }
624         return Either.left(resource);
625     }
626
627     private Resource handleResourceGenericType(Resource resource) {
628         Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
629         if (resource.shouldGenerateInputs()) {
630             generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
631         }
632         return genericResource;
633     }
634
635     private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(
636             Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Resource oldResource) {
637
638         Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
639         Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes
640                 = Either.left(nodeTypesArtifactsToHandle);
641
642         try {
643             Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csarInfo.getCsar());
644             Map<String, ImmutablePair<String, String>> extractedVfcToscaNames =
645                     extractVfcToscaNames(nodeTypesInfo, oldResource.getName(), csarInfo);
646             log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ",
647                     oldResource.getName(), csarInfo.getCsarUUID());
648             extractedVfcToscaNames.forEach((namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo, nodeTypesArtifactsToHandle, oldResource,
649                     extractedVfcsArtifacts,
650                     namespace, vfcToscaNames));
651         } catch (Exception e) {
652             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
653             nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
654             log.debug("Exception occured when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e);
655         }
656         return nodeTypesArtifactsToHandleRes;
657     }
658
659     private void findAddNodeTypeArtifactsToHandle(CsarInfo csarInfo, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
660                                                   Resource resource, Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts, String namespace, ImmutablePair<String, String> vfcToscaNames){
661
662         EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
663         log.debug("Going to fetch node type with tosca name {}. ", vfcToscaNames.getLeft());
664         Resource curNodeType = findVfcResource(csarInfo, resource, vfcToscaNames.getLeft(), vfcToscaNames.getRight(), null);
665         if (!isEmpty(extractedVfcsArtifacts)) {
666             List<ArtifactDefinition> currArtifacts = new ArrayList<>();
667             if (extractedVfcsArtifacts.containsKey(namespace)) {
668                 handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(namespace));
669             }
670             curNodeTypeArtifactsToHandle = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
671         } else if (curNodeType != null) {
672             // delete all artifacts if have not received artifacts from
673             // csar
674             curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
675             List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
676             // delete all informational artifacts
677             artifactsToDelete.addAll(curNodeType.getArtifacts().values().stream()
678                     .filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
679                     .collect(toList()));
680             // delete all deployment artifacts
681             artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values());
682             if (!artifactsToDelete.isEmpty()) {
683                 curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
684             }
685         }
686         if (isNotEmpty(curNodeTypeArtifactsToHandle)) {
687             nodeTypesArtifactsToHandle.put(namespace, curNodeTypeArtifactsToHandle);
688         }
689     }
690
691     private Resource findVfcResource(CsarInfo csarInfo, Resource resource, String currVfcToscaName, String previousVfcToscaName, StorageOperationStatus status) {
692         if (status != null && status != StorageOperationStatus.NOT_FOUND) {
693             log.debug("Error occured during fetching node type with tosca name {}, error: {}", currVfcToscaName, status);
694             ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
695             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.CREATE_RESOURCE);
696             throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
697         } else if (StringUtils.isNotEmpty(currVfcToscaName)) {
698             return (Resource)toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName)
699                     .left()
700                     .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st));
701         }
702         return null;
703     }
704
705     private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> findNodeTypeArtifactsToHandle(
706             Resource curNodeType, List<ArtifactDefinition> extractedArtifacts) {
707
708         EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
709         try {
710             List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
711             List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
712             List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
713             processExistingNodeTypeArtifacts(extractedArtifacts, artifactsToUpload, artifactsToUpdate, artifactsToDelete,
714                     collectExistingArtifacts(curNodeType));
715             nodeTypeArtifactsToHandle = putFoundArtifacts(artifactsToUpload, artifactsToUpdate, artifactsToDelete);
716         } catch (Exception e) {
717             log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
718             throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
719         }
720         return nodeTypeArtifactsToHandle;
721     }
722
723     private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> putFoundArtifacts(List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete) {
724         EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
725         if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
726             nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
727             if (!artifactsToUpload.isEmpty()) {
728                 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
729             }
730             if (!artifactsToUpdate.isEmpty()) {
731                 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
732             }
733             if (!artifactsToDelete.isEmpty()) {
734                 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
735             }
736         }
737         return nodeTypeArtifactsToHandle;
738     }
739
740     private void processExistingNodeTypeArtifacts(List<ArtifactDefinition> extractedArtifacts, List<ArtifactDefinition> artifactsToUpload,
741                                                   List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete,
742                                                   Map<String, ArtifactDefinition> existingArtifacts) {
743         if (!existingArtifacts.isEmpty()) {
744             extractedArtifacts.stream().forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a));
745             artifactsToDelete.addAll(existingArtifacts.values());
746         }
747     }
748
749     private void processNodeTypeArtifact(List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate, Map<String, ArtifactDefinition> existingArtifacts, ArtifactDefinition currNewArtifact) {
750         Optional<ArtifactDefinition> foundArtifact = existingArtifacts.values()
751                 .stream()
752                 .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName()))
753                 .findFirst();
754         if (foundArtifact.isPresent()) {
755             if (foundArtifact.get().getArtifactType().equals(currNewArtifact.getArtifactType())) {
756                 updateFoundArtifact(artifactsToUpdate, currNewArtifact, foundArtifact.get());
757                 existingArtifacts.remove(foundArtifact.get().getArtifactLabel());
758                 artifactsToUpload.remove(currNewArtifact);
759             } else {
760                 log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
761                 throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
762                         currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(),
763                         foundArtifact.get().getArtifactType());
764             }
765         }
766     }
767
768     private void updateFoundArtifact(List<ArtifactDefinition> artifactsToUpdate, ArtifactDefinition currNewArtifact, ArtifactDefinition foundArtifact) {
769         if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
770             foundArtifact.setPayload(currNewArtifact.getPayloadData());
771             foundArtifact.setPayloadData(
772                     Base64.encodeBase64String(currNewArtifact.getPayloadData()));
773             foundArtifact.setArtifactChecksum(GeneralUtility
774                     .calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
775             artifactsToUpdate.add(foundArtifact);
776         }
777     }
778
779     private Map<String, ArtifactDefinition> collectExistingArtifacts(Resource curNodeType) {
780         Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>();
781         if (curNodeType == null) {
782             return existingArtifacts;
783         }
784         if (MapUtils.isNotEmpty(curNodeType.getDeploymentArtifacts())) {
785             existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
786         }
787         if (MapUtils.isNotEmpty(curNodeType.getArtifacts())) {
788             existingArtifacts
789                     .putAll(curNodeType.getArtifacts().entrySet()
790                             .stream()
791                             .filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
792                             .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
793         }
794         return existingArtifacts;
795     }
796
797     /**
798      * Changes resource life cycle state to checked out
799      *
800      * @param resource
801      * @param user
802      * @param inTransaction
803      * @return
804      */
805     private Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) {
806         Either<Resource, ResponseFormat> checkoutResourceRes;
807         try {
808             if (!resource.getComponentMetadataDefinition().getMetadataDataDefinition().getState()
809                     .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
810                 log.debug(
811                         "************* Going to change life cycle state of resource {} to not certified checked out. ",
812                         resource.getName());
813                 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(
814                         resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
815                         new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
816                                 LifecycleChanceActionEnum.CREATE_FROM_CSAR),
817                         inTransaction, true);
818                 if (checkoutRes.isRight()) {
819                     log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ",
820                             resource.getComponentType().getNodeType(), resource.getUniqueId(),
821                             checkoutRes.right().value().getStatus());
822                     checkoutResourceRes = Either.right(checkoutRes.right().value());
823                 } else {
824                     checkoutResourceRes = Either.left((Resource) checkoutRes.left().value());
825                 }
826             } else {
827                 checkoutResourceRes = Either.left(resource);
828             }
829         } catch (Exception e) {
830             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
831             checkoutResourceRes = Either.right(responseFormat);
832             log.debug("Exception occured when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(),
833                     e);
834         }
835         return checkoutResourceRes;
836     }
837
838     /**
839      * Handles Artifacts of NodeType
840      *
841      * @param nodeTypeResource
842      * @param nodeTypeArtifactsToHandle
843      * @param user
844      * @param inTransaction
845      * @return
846      */
847     public Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource,
848                                                                                     Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
849                                                                                     List<ArtifactDefinition> createdArtifacts, User user, boolean inTransaction, boolean ignoreLifecycleState) {
850         Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRequestRes;
851         Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null;
852         Either<Resource, ResponseFormat> changeStateResponse;
853         try {
854             changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction);
855             if (changeStateResponse.isRight()) {
856                 return Either.right(changeStateResponse.right().value());
857             }
858             nodeTypeResource = changeStateResponse.left().value();
859
860             List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>();
861             log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName());
862             for (Entry<ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle
863                     .entrySet()) {
864                 ArtifactOperationEnum curOperation = curOperationEntry.getKey();
865                 List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue();
866                 if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) {
867                     log.debug("************* Going to {} artifact to vfc {}", curOperation.name(),
868                             nodeTypeResource.getName());
869                     handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic
870                             .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user,
871                                     createdArtifacts, artifactsBusinessLogic.new ArtifactOperationInfo(false,
872                                             ignoreLifecycleState, curOperation),
873                                     false, inTransaction);
874                     if (handleNodeTypeArtifactsRequestRes.isRight()) {
875                         handleNodeTypeArtifactsRes = Either.right(handleNodeTypeArtifactsRequestRes.right().value());
876                         break;
877                     }
878                     if (ArtifactOperationEnum.isCreateOrLink(curOperation)) {
879                         createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value());
880                     }
881                     handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value());
882                 }
883             }
884             if (handleNodeTypeArtifactsRes == null) {
885                 handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts);
886             }
887         } catch (Exception e) {
888             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
889             handleNodeTypeArtifactsRes = Either.right(responseFormat);
890             log.debug("Exception occured when handleVfcArtifacts, error is:{}", e.getMessage(), e);
891         }
892         return handleNodeTypeArtifactsRes;
893     }
894
895     private Map<String, ImmutablePair<String, String>> extractVfcToscaNames(Map<String, NodeTypeInfo> nodeTypesInfo,
896                                                                             String vfResourceName, CsarInfo csarInfo) {
897         Map<String, ImmutablePair<String, String>> vfcToscaNames = new HashMap<>();
898
899         Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo);
900         if (!nodes.isEmpty()) {
901             Iterator<Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator();
902             while (nodesNameEntry.hasNext()) {
903                 Entry<String, Object> nodeType = nodesNameEntry.next();
904                 ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName(
905                         ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey());
906                 vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
907             }
908         }
909         for (NodeTypeInfo cvfc : nodeTypesInfo.values()) {
910             vfcToscaNames.put(cvfc.getType(),
911                     buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), vfResourceName, cvfc.getType()));
912         }
913         return vfcToscaNames;
914     }
915
916     private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
917         Map<String, Object> nodes = new HashMap<>();
918         for (NodeTypeInfo nodeTypeInfo : nodeTypesInfo.values()) {
919             extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate());
920         }
921         extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate());
922         return nodes;
923     }
924
925     private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) {
926         Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils
927                 .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
928         if (eitherNodeTypes.isLeft()) {
929             nodes.putAll(eitherNodeTypes.left().value());
930         }
931     }
932
933     public Resource createResourceFromCsar(Resource resource, User user,
934                                            Map<String, byte[]> csarUIPayload, String csarUUID) {
935         log.trace("************* created successfully from YAML, resource TOSCA ");
936
937         CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(resource, null, user, csarUIPayload, csarUUID);
938
939         Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
940         Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
941                 nodeTypesInfo, csarInfo, resource);
942         if (findNodeTypesArtifactsToHandleRes.isRight()) {
943             log.debug("failed to find node types for update with artifacts during import csar {}. ",
944                     csarInfo.getCsarUUID());
945             throw new ByResponseFormatComponentException(findNodeTypesArtifactsToHandleRes.right().value());
946         }
947         Resource vfResource = createResourceFromYaml(resource, csarInfo.getMainTemplateContent(), csarInfo.getMainTemplateName(),
948                 nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left().value(), true, false,
949                 null);
950         log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}",
951                 vfResource.getToscaResourceName());
952         return vfResource;
953     }
954
955     private Resource validateResourceBeforeCreate(Resource resource, User user, boolean inTransaction) {
956         log.trace("validating resource before create");
957         user.copyData(validateUser(user, CREATE_RESOURCE, resource, AuditingActionEnum.CREATE_RESOURCE, false));
958         // validate user role
959         validateUserRole(user, resource, new ArrayList<>(), AuditingActionEnum.CREATE_RESOURCE, null);
960         // VF / PNF "derivedFrom" should be null (or ignored)
961         if (ModelConverter.isAtomicComponent(resource)) {
962             validateDerivedFromNotEmpty(user, resource, AuditingActionEnum.CREATE_RESOURCE);
963         }
964         return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction, null);
965
966     }
967
968     // resource, yamlFileContents, yamlFileName, nodeTypesInfo,csarInfo,
969     // nodeTypesArtifactsToCreate, true, false, null
970     private Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml,
971                                             String yamlName, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
972                                             Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
973                                             boolean shouldLock, boolean inTransaction, String nodeName) {
974
975         List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
976         Resource createdResource;
977         try{
978             ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic.getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName);
979             if (MapUtils.isEmpty(parsedToscaYamlInfo.getInstances()) && resource.getResourceType() != ResourceTypeEnum.PNF) {
980                 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
981             }
982             log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", resource.getName());
983             createdResource = createResourceAndRIsFromYaml(yamlName, resource,
984                     parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml,
985                     nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
986             log.debug("#createResourceFromYaml - The resource {} has been created ", resource.getName());
987         } catch (ByActionStatusComponentException e) {
988             ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
989             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
990             throw e;
991         } catch (ByResponseFormatComponentException e) {
992             ResponseFormat responseFormat = e.getResponseFormat();
993             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
994             throw e;
995         } catch (StorageException e){
996             ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
997             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
998             throw e;
999         }
1000         return createdResource;
1001
1002     }
1003
1004     public Map<String, Resource> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, Map<String, Object> mappedToscaTemplate, boolean needLock,
1005                                                                       Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1006                                                                       List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
1007                                                                       CsarInfo csarInfo) {
1008
1009         Either<String, ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate,
1010                 TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
1011         if (toscaVersion.isRight()) {
1012             throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE);
1013         }
1014         Map<String, Object> mapToConvert = new HashMap<>();
1015         mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left().value());
1016         Map<String, Object> nodeTypes = getNodeTypesFromTemplate(mappedToscaTemplate);
1017         createNodeTypes(yamlName, resource, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, mapToConvert, nodeTypes);
1018         return csarInfo.getCreatedNodes();
1019     }
1020
1021     private Map<String,Object> getNodeTypesFromTemplate(Map<String, Object> mappedToscaTemplate) {
1022         return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES)
1023                 .left().orValue(HashMap::new);
1024     }
1025
1026     private void createNodeTypes(String yamlName, Resource resource, boolean needLock, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Map<String, Object> mapToConvert, Map<String, Object> nodeTypes) {
1027         Iterator<Entry<String, Object>> nodesNameValueIter = nodeTypes.entrySet().iterator();
1028         Resource vfcCreated = null;
1029         while (nodesNameValueIter.hasNext()) {
1030             Entry<String, Object> nodeType = nodesNameValueIter.next();
1031             Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null
1032                     || nodeTypesArtifactsToHandle.isEmpty() ? null
1033                     : nodeTypesArtifactsToHandle.get(nodeType.getKey());
1034
1035             if (nodeTypesInfo.containsKey(nodeType.getKey())) {
1036                 log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
1037                 vfcCreated = handleNestedVfc(resource,
1038                         nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
1039                         nodeType.getKey());
1040                 log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
1041             } else if (csarInfo.getCreatedNodesToscaResourceNames() != null
1042                     && !csarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())) {
1043                 log.trace("************* Going to create node {}", nodeType.getKey());
1044                 ImmutablePair<Resource, ActionStatus> resourceCreated = createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert,
1045                         resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true,
1046                         csarInfo, true);
1047                 log.debug("************* Finished to create node {}", nodeType.getKey());
1048
1049                 vfcCreated = resourceCreated.getLeft();
1050                 csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(),
1051                         vfcCreated.getToscaResourceName());
1052             }
1053             if (vfcCreated != null) {
1054                 csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated);
1055             }
1056             mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName());
1057         }
1058     }
1059
1060     private Resource handleNestedVfc(Resource resource, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1061                                      List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1062                                      String nodeName) {
1063
1064         String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
1065         Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
1066
1067         log.debug("************* Going to create node types from yaml {}", yamlName);
1068         createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false,
1069                 nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo);
1070         log.debug("************* Finished to create node types from yaml {}", yamlName);
1071
1072         if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
1073             log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
1074             resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
1075                     csarInfo, nodeName, yamlName);
1076         }
1077         return resource;
1078     }
1079
1080     private Resource handleComplexVfc(Resource resource, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1081                                       List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1082                                       String nodeName, String yamlName) {
1083
1084         Resource oldComplexVfc = null;
1085         Resource newComplexVfc = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo);
1086         Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade
1087                 .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
1088         if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
1089             oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
1090                     buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(),
1091                             nodeName).getRight());
1092         }
1093         if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
1094             log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ",
1095                     newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value());
1096             throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
1097         } else if (oldComplexVfcRes.isLeft()) {
1098             log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
1099             Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(
1100                     oldComplexVfcRes.left().value(), newComplexVfc,
1101                     ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
1102             if (eitherValidation.isLeft()) {
1103                 oldComplexVfc = oldComplexVfcRes.left().value();
1104             }
1105         }
1106         newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName,
1107                 oldComplexVfc, newComplexVfc);
1108         csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
1109         LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(
1110                 CERTIFICATION_ON_IMPORT, LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1111         log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
1112         Either<Resource, ResponseFormat> result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false,
1113                 true);
1114         if (result.isRight()) {
1115             log.debug("Failed to certify complex VFC resource {}. ", newComplexVfc.getName());
1116         }
1117         csarInfo.getCreatedNodes().put(nodeName, result.left().value());
1118         csarInfo.removeNodeFromQueue();
1119         return result.left().value();
1120     }
1121
1122     private Resource handleComplexVfc(Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1123                                       List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1124                                       String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) {
1125
1126         Resource handleComplexVfcRes;
1127         Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName).getMappedToscaTemplate();
1128         String yamlContent = new String(csarInfo.getCsar().get(yamlName));
1129         Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet().stream()
1130                 .collect(toMap(Entry::getKey, e -> e.getValue().getUnmarkedCopy()));
1131         CsarInfo.markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
1132         if (oldComplexVfc == null) {
1133             handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo,
1134                     csarInfo, nodesArtifactsToHandle, false, true, nodeName);
1135         } else {
1136             handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc,
1137                     AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, yamlContent, yamlName, csarInfo,
1138                     newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true);
1139         }
1140         return handleComplexVfcRes;
1141     }
1142
1143     private Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName,
1144                                           Map<String, NodeTypeInfo> nodesInfo) {
1145
1146         Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo);
1147         log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
1148         csarInfo.addNodeToQueue(nodeName);
1149         return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(),
1150                 AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
1151     }
1152
1153     private String getNodeTypeActualName(String fullName) {
1154         String nameWithouNamespacePrefix = fullName
1155                 .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1156         String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1157         String resourceType = findTypes[0];
1158         return nameWithouNamespacePrefix.substring(resourceType.length());
1159     }
1160
1161     private ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(
1162             String yamlName, Entry<String, Object> nodeNameValue, User user, Map<String, Object> mapToConvert,
1163             Resource resourceVf, boolean needLock,
1164             Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1165             List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
1166             boolean isNested) {
1167
1168         UploadResourceInfo resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
1169
1170         String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert,
1171                 resourceMetaData.getResourceType(), csarInfo);
1172         user = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
1173         return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock,
1174                 nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo,
1175                 nodeNameValue.getKey(), isNested);
1176     }
1177
1178     private String buildNodeTypeYaml(Entry<String, Object> nodeNameValue, Map<String, Object> mapToConvert,
1179                                      String nodeResourceType, CsarInfo csarInfo) {
1180         // We need to create a Yaml from each node_types in order to create
1181         // resource from each node type using import normative flow.
1182         DumperOptions options = new DumperOptions();
1183         options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
1184         Yaml yaml = new Yaml(options);
1185
1186         Map<String, Object> node = new HashMap<>();
1187         node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey())
1188                 .getLeft(), nodeNameValue.getValue());
1189         mapToConvert.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
1190
1191         return yaml.dumpAsMap(mapToConvert);
1192     }
1193
1194     public Either<Boolean, ResponseFormat> validateResourceCreationFromNodeType(Resource resource, User creator) {
1195         validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
1196         return Either.left(true);
1197     }
1198
1199     public ImmutablePair<Resource, ActionStatus> createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock,
1200                                                                             Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1201                                                                             List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
1202                                                                             String nodeName, boolean isNested) {
1203
1204         LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1205                 LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1206         Function<Resource, Either<Boolean, ResponseFormat>> validator = resource -> validateResourceCreationFromNodeType(resource, creator);
1207         return resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator,
1208                 lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle,
1209                 nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested)
1210                 .left().on(this::failOnCertification);
1211     }
1212
1213     private ImmutablePair<Resource,ActionStatus> failOnCertification(ResponseFormat error) {
1214         throw new ByResponseFormatComponentException(error);
1215     }
1216
1217     private UploadResourceInfo fillResourceMetadata(String yamlName, Resource resourceVf,
1218                                                     String nodeName, User user) {
1219         UploadResourceInfo resourceMetaData = new UploadResourceInfo();
1220
1221         // validate nodetype name prefix
1222         if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
1223             log.debug("invalid nodeName:{} does not start with {}.", nodeName,
1224                     Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
1225             throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
1226                     yamlName, resourceMetaData.getName(), nodeName);
1227         }
1228
1229         String actualName = this.getNodeTypeActualName(nodeName);
1230         String namePrefix = nodeName.replace(actualName, "");
1231         String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1232
1233         // if we import from csar, the node_type name can be
1234         // org.openecomp.resource.abstract.node_name - in this case we always
1235         // create a vfc
1236         if (resourceType.equals(Constants.ABSTRACT)) {
1237             resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
1238         }
1239         // validating type
1240         if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
1241             log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(),
1242                     ResourceTypeEnum.values());
1243             throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
1244                     yamlName, resourceMetaData.getName(), nodeName);
1245         }
1246
1247         // Setting name
1248         resourceMetaData.setName(resourceVf.getSystemName() + actualName);
1249
1250         // Setting type from name
1251         String type = resourceType.toUpperCase();
1252         resourceMetaData.setResourceType(type);
1253
1254         resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
1255         resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1256         resourceMetaData.setContactId(user.getUserId());
1257         resourceMetaData.setVendorName(resourceVf.getVendorName());
1258         resourceMetaData.setVendorRelease(resourceVf.getVendorRelease());
1259
1260         // Setting tag
1261         List<String> tags = new ArrayList<>();
1262         tags.add(resourceMetaData.getName());
1263         resourceMetaData.setTags(tags);
1264
1265         // Setting category
1266         CategoryDefinition category = new CategoryDefinition();
1267         category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1268         SubCategoryDefinition subCategory = new SubCategoryDefinition();
1269         subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1270         category.addSubCategory(subCategory);
1271         List<CategoryDefinition> categories = new ArrayList<>();
1272         categories.add(category);
1273         resourceMetaData.setCategories(categories);
1274
1275         return resourceMetaData;
1276     }
1277
1278     private Resource buildComplexVfcMetadata(Resource resourceVf, CsarInfo csarInfo, String nodeName,
1279                                              Map<String, NodeTypeInfo> nodesInfo) {
1280         Resource cvfc = new Resource();
1281         NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
1282         cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
1283         cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
1284         cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
1285         cvfc.setResourceType(ResourceTypeEnum.CVFC);
1286         cvfc.setAbstract(true);
1287         cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
1288         cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION);
1289         cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1290         cvfc.setContactId(csarInfo.getModifier().getUserId());
1291         cvfc.setCreatorUserId(csarInfo.getModifier().getUserId());
1292         cvfc.setVendorName(resourceVf.getVendorName());
1293         cvfc.setVendorRelease(resourceVf.getVendorRelease());
1294         cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
1295         cvfc.setToscaResourceName(
1296                 buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName)
1297                         .getLeft());
1298         cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
1299
1300         List<String> tags = new ArrayList<>();
1301         tags.add(cvfc.getName());
1302         cvfc.setTags(tags);
1303
1304         CategoryDefinition category = new CategoryDefinition();
1305         category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1306         SubCategoryDefinition subCategory = new SubCategoryDefinition();
1307         subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1308         category.addSubCategory(subCategory);
1309         List<CategoryDefinition> categories = new ArrayList<>();
1310         categories.add(category);
1311         cvfc.setCategories(categories);
1312
1313         cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
1314         cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
1315         cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
1316
1317         return cvfc;
1318     }
1319
1320     private String buildCvfcName(String resourceVfName, String nodeName) {
1321         String nameWithouNamespacePrefix = nodeName
1322                 .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1323         String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1324         String resourceType = findTypes[0];
1325         String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1);
1326         return addCvfcSuffixToResourceName(resourceName);
1327     }
1328
1329     private Resource createResourceAndRIsFromYaml(String yamlName, Resource resource,
1330                                                   ParsedToscaYamlInfo parsedToscaYamlInfo, AuditingActionEnum actionEnum, boolean isNormative,
1331                                                   List<ArtifactDefinition> createdArtifacts, String topologyTemplateYaml,
1332                                                   Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1333                                                   Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1334                                                   boolean shouldLock, boolean inTransaction, String nodeName) {
1335
1336         List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
1337
1338         if (shouldLock) {
1339             Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
1340                     CREATE_RESOURCE);
1341             if (lockResult.isRight()) {
1342                 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1343                 throw new ByResponseFormatComponentException(lockResult.right().value());
1344             }
1345             log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
1346         }
1347         try {
1348             log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
1349             Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
1350             resource = createResourceTransaction(resource,
1351                     csarInfo.getModifier(), isNormative);
1352             log.trace("************* createResourceFromYaml after full create resource {}", yamlName);
1353             log.trace("************* Going to add inputs from yaml {}", yamlName);
1354             if (resource.shouldGenerateInputs())
1355                 generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
1356
1357             Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
1358             resource = createInputsOnResource(resource, inputs);
1359             log.trace("************* Finish to add inputs from yaml {}", yamlName);
1360
1361             Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo
1362                     .getInstances();
1363             log.trace("************* Going to create nodes, RI's and Relations  from yaml {}", yamlName);
1364
1365             resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap,
1366                     topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
1367                     nodeTypesArtifactsToCreate, nodeName);
1368             log.trace("************* Finished to create nodes, RI and Relation  from yaml {}", yamlName);
1369             // validate update vf module group names
1370             Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
1371                     .validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName());
1372             if (validateUpdateVfGroupNamesRes.isRight()) {
1373                 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1374                 throw new ByResponseFormatComponentException(validateUpdateVfGroupNamesRes.right().value());
1375             }
1376             // add groups to resource
1377             Map<String, GroupDefinition> groups;
1378             log.trace("************* Going to add groups from yaml {}", yamlName);
1379
1380             if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
1381                 groups = validateUpdateVfGroupNamesRes.left().value();
1382             } else {
1383                 groups = parsedToscaYamlInfo.getGroups();
1384             }
1385
1386             Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource,
1387                     groups);
1388             if (createGroupsOnResource.isRight()) {
1389                 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1390                 throw new ByResponseFormatComponentException(createGroupsOnResource.right().value());
1391             }
1392             resource = createGroupsOnResource.left().value();
1393             log.trace("************* Finished to add groups from yaml {}", yamlName);
1394
1395             log.trace("************* Going to add artifacts from yaml {}", yamlName);
1396
1397             NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
1398                     nodeTypesArtifactsToCreate);
1399
1400             Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.CREATE, createdArtifacts, yamlName,
1401                     csarInfo, resource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
1402             if (createArtifactsEither.isRight()) {
1403                 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1404                 throw new ByResponseFormatComponentException(createArtifactsEither.right().value());
1405             }
1406
1407             resource = getResourceWithGroups(createArtifactsEither.left().value().getUniqueId());
1408
1409             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
1410             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum);
1411             ASDCKpiApi.countCreatedResourcesKPI();
1412             return resource;
1413
1414         } catch(ComponentException|StorageException e) {
1415             rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1416             throw e;
1417         } finally {
1418             if (!inTransaction) {
1419                 janusGraphDao.commit();
1420             }
1421             if (shouldLock) {
1422                 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
1423                         NodeTypeEnum.Resource);
1424             }
1425         }
1426     }
1427
1428     private void rollback(boolean inTransaction, Resource resource, List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
1429         if(!inTransaction) {
1430             janusGraphDao.rollback();
1431         }
1432         if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) {
1433             createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
1434             log.debug("Found {} newly created artifacts to deleted, the component name: {}",createdArtifacts.size(), resource.getName());
1435         }
1436     }
1437
1438     private Resource getResourceWithGroups(String resourceId) {
1439
1440         ComponentParametersView filter = new ComponentParametersView();
1441         filter.setIgnoreGroups(false);
1442         Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter);
1443         if (updatedResource.isRight()) {
1444             rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resourceId);
1445         }
1446         return updatedResource.left().value();
1447     }
1448
1449     private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource,
1450                                                                     Map<String, GroupDefinition> groups) {
1451         if (groups != null && !groups.isEmpty()) {
1452             List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(
1453                     groups, resource);
1454             handleGroupsProperties(resource, groups);
1455             fillGroupsFinalFields(groupsAsList);
1456             Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource,
1457                     groupsAsList, true);
1458             if (createGroups.isRight()) {
1459                 return Either.right(createGroups.right().value());
1460             }
1461         } else {
1462             return Either.left(resource);
1463         }
1464         Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
1465                 .getToscaElement(resource.getUniqueId());
1466         if (updatedResource.isRight()) {
1467             ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
1468                     componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
1469             return Either.right(responseFormat);
1470         }
1471         return Either.left(updatedResource.left().value());
1472     }
1473
1474     private void handleGroupsProperties(Resource resource, Map<String, GroupDefinition> groups) {
1475         List<InputDefinition> inputs = resource.getInputs();
1476         if (MapUtils.isNotEmpty(groups)) {
1477             groups.values()
1478                     .stream()
1479                     .filter(g -> isNotEmpty(g.getProperties()))
1480                     .flatMap(g -> g.getProperties().stream())
1481                     .forEach(p -> handleGetInputs(p, inputs));
1482         }
1483     }
1484
1485     private void handleGetInputs(PropertyDataDefinition property, List<InputDefinition> inputs) {
1486         if (isNotEmpty(property.getGetInputValues())) {
1487             if (inputs == null || inputs.isEmpty()) {
1488                 log.debug("Failed to add property {} to group. Inputs list is empty ", property);
1489                 rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
1490                         .stream()
1491                         .map(GetInputValueDataDefinition::getInputName)
1492                         .collect(toList()).toString());
1493             }
1494             ListIterator<GetInputValueDataDefinition> getInputValuesIter = property.getGetInputValues().listIterator();
1495             while (getInputValuesIter.hasNext()) {
1496                 GetInputValueDataDefinition getInput = getInputValuesIter.next();
1497                 InputDefinition input = findInputByName(inputs, getInput);
1498                 getInput.setInputId(input.getUniqueId());
1499                 if (getInput.getGetInputIndex() != null) {
1500                     GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
1501                     input = findInputByName(inputs, getInputIndex);
1502                     getInputIndex.setInputId(input.getUniqueId());
1503                     getInputValuesIter.add(getInputIndex);
1504                 }
1505             }
1506         }
1507     }
1508
1509     private InputDefinition findInputByName(List<InputDefinition> inputs, GetInputValueDataDefinition getInput) {
1510         Optional<InputDefinition> inputOpt = inputs.stream()
1511                 .filter(p -> p.getName().equals(getInput.getInputName()))
1512                 .findFirst();
1513         if (!inputOpt.isPresent()) {
1514             log.debug("#findInputByName - Failed to find the input {} ", getInput.getInputName());
1515             rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, getInput.getInputName());
1516         }
1517         return inputOpt.get();
1518     }
1519
1520     private void fillGroupsFinalFields(List<GroupDefinition> groupsAsList) {
1521         groupsAsList.forEach(groupDefinition -> {
1522             groupDefinition.setInvariantName(groupDefinition.getName());
1523             groupDefinition.setCreatedFrom(CreatedFrom.CSAR);
1524         });
1525     }
1526
1527     private Resource updateGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
1528         if (isEmpty(groups)) {
1529             return resource;
1530         } else {
1531             updateOrCreateGroups(resource, groups);
1532         }
1533         Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
1534                 .getToscaElement(resource.getUniqueId());
1535         if (updatedResource.isRight()) {
1536             throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatByResource(
1537                     componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
1538         }
1539         return updatedResource.left().value();
1540     }
1541
1542     private void updateOrCreateGroups(Resource resource, Map<String, GroupDefinition> groups) {
1543         List<GroupDefinition> groupsFromResource = resource.getGroups();
1544         List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
1545         List<GroupDefinition> groupsToUpdate = new ArrayList<>();
1546         List<GroupDefinition> groupsToDelete = new ArrayList<>();
1547         List<GroupDefinition> groupsToCreate = new ArrayList<>();
1548         if (isNotEmpty(groupsFromResource)) {
1549             addGroupsToCreateOrUpdate(groupsFromResource, groupsAsList, groupsToUpdate, groupsToCreate);
1550             addGroupsToDelete(groupsFromResource, groupsAsList, groupsToDelete);
1551         } else {
1552             groupsToCreate.addAll(groupsAsList);
1553         }
1554         if (isNotEmpty(groupsToCreate)) {
1555             fillGroupsFinalFields(groupsToCreate);
1556             if (isNotEmpty(groupsFromResource)) {
1557                 groupBusinessLogic.addGroups(resource,
1558                         groupsToCreate, true)
1559                         .left()
1560                         .on(this::throwComponentException);
1561             } else {
1562                 groupBusinessLogic.createGroups(resource,
1563                         groupsToCreate, true)
1564                         .left()
1565                         .on(this::throwComponentException);
1566             }
1567         }
1568         if (isNotEmpty(groupsToDelete)) {
1569             groupBusinessLogic.deleteGroups(resource, groupsToDelete)
1570                     .left()
1571                     .on(this::throwComponentException);
1572         }
1573         if (isNotEmpty(groupsToUpdate)) {
1574             groupBusinessLogic.updateGroups(resource, groupsToUpdate, true)
1575                     .left()
1576                     .on(this::throwComponentException);
1577         }
1578     }
1579
1580     private void addGroupsToDelete(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList, List<GroupDefinition> groupsToDelete) {
1581         for (GroupDefinition group : groupsFromResource) {
1582             Optional<GroupDefinition> op = groupsAsList.stream()
1583                     .filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny();
1584             if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) {
1585                 groupsToDelete.add(group);
1586             }
1587         }
1588     }
1589
1590     private void addGroupsToCreateOrUpdate(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList, List<GroupDefinition> groupsToUpdate, List<GroupDefinition> groupsToCreate) {
1591         for (GroupDefinition group : groupsAsList) {
1592             Optional<GroupDefinition> op = groupsFromResource.stream()
1593                     .filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName())).findAny();
1594             if (op.isPresent()) {
1595                 GroupDefinition groupToUpdate = op.get();
1596                 groupToUpdate.setMembers(group.getMembers());
1597                 groupToUpdate.setCapabilities(group.getCapabilities());
1598                 groupToUpdate.setProperties(group.getProperties());
1599                 groupsToUpdate.add(groupToUpdate);
1600             } else {
1601                 groupsToCreate.add(group);
1602             }
1603         }
1604     }
1605
1606     private Resource createInputsOnResource(Resource resource, Map<String, InputDefinition> inputs) {
1607         List<InputDefinition> resourceProperties = resource.getInputs();
1608         if (MapUtils.isNotEmpty(inputs)|| isNotEmpty(resourceProperties)) {
1609
1610             Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs,
1611                     resource);
1612             if (createInputs.isRight()) {
1613                 throw new ByResponseFormatComponentException(createInputs.right().value());
1614             }
1615         } else {
1616             return resource;
1617         }
1618         Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
1619                 .getToscaElement(resource.getUniqueId());
1620         if (updatedResource.isRight()) {
1621             throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatByResource(
1622                     componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
1623         }
1624         return updatedResource.left().value();
1625     }
1626
1627     private List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, Resource component) {
1628
1629         List<GroupDefinition> result = new ArrayList<>();
1630         List<ComponentInstance> componentInstances = component.getComponentInstances();
1631
1632         if (groups != null) {
1633             Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups);
1634             if (validateCyclicGroupsDependencies.isRight()) {
1635                 throw new ByResponseFormatComponentException(validateCyclicGroupsDependencies.right().value());
1636             }
1637             for (Entry<String, GroupDefinition> entry : groups.entrySet()) {
1638                 String groupName = entry.getKey();
1639                 GroupDefinition groupDefinition = entry.getValue();
1640                 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
1641                 updatedGroupDefinition.setMembers(null);
1642                 Map<String, String> members = groupDefinition.getMembers();
1643                 if (members != null) {
1644                     updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members);
1645                 }
1646                 result.add(updatedGroupDefinition);
1647             }
1648         }
1649         return result;
1650     }
1651
1652     private void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition, Resource component, List<ComponentInstance> componentInstances, String groupName, Map<String, String> members) {
1653         Set<String> compInstancesNames = members.keySet();
1654
1655         if (CollectionUtils.isEmpty(componentInstances)) {
1656             String membersAstString = compInstancesNames.stream().collect(joining(","));
1657             log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.",
1658                     membersAstString, groupName, component.getNormalizedName());
1659             throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(
1660                     ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
1661                     component.getNormalizedName(), getComponentTypeForResponse(component)));
1662         }
1663         // Find all component instances with the member names
1664         Map<String, String> memberNames = componentInstances.stream()
1665                 .collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
1666         memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> "")));
1667         Map<String, String> relevantInstances = memberNames.entrySet().stream()
1668                 .filter(n -> compInstancesNames.contains(n.getKey()))
1669                 .collect(toMap(Entry::getKey, Entry::getValue));
1670
1671         if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
1672
1673             List<String> foundMembers = new ArrayList<>();
1674             if (relevantInstances != null) {
1675                 foundMembers = relevantInstances.keySet().stream().collect(toList());
1676             }
1677             compInstancesNames.removeAll(foundMembers);
1678             String membersAstString = compInstancesNames.stream().collect(joining(","));
1679             log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString,
1680                     groupName, component.getNormalizedName());
1681             throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(
1682                     ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
1683                     component.getNormalizedName(), getComponentTypeForResponse(component)));
1684         }
1685         updatedGroupDefinition.setMembers(relevantInstances);
1686     }
1687
1688     /**
1689      * This Method validates that there is no cyclic group dependencies. meaning
1690      * group A as member in group B which is member in group A
1691      *
1692      * @param allGroups
1693      * @return
1694      */
1695     private Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) {
1696
1697         Either<Boolean, ResponseFormat> result = Either.left(true);
1698         try {
1699             Iterator<Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet().iterator();
1700             while (allGroupsItr.hasNext() && result.isLeft()) {
1701                 Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next();
1702                 // Fetches a group member A
1703                 String groupAName = groupAEntry.getKey();
1704                 // Finds all group members in group A
1705                 Set<String> allGroupAMembersNames = new HashSet<>();
1706                 fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames);
1707                 // If A is a group member of itself found cyclic dependency
1708                 if (allGroupAMembersNames.contains(groupAName)) {
1709                     ResponseFormat responseFormat = componentsUtils
1710                             .getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
1711                     result = Either.right(responseFormat);
1712                 }
1713             }
1714         } catch (Exception e) {
1715             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1716             result = Either.right(responseFormat);
1717             log.debug("Exception occured when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e);
1718         }
1719         return result;
1720     }
1721
1722     /**
1723      * This Method fills recursively the set groupMembers with all the members
1724      * of the given group which are also of type group.
1725      *
1726      * @param groupName
1727      * @param allGroups
1728      * @param allGroupMembers
1729      * @return
1730      */
1731     private void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups,
1732                                                 Set<String> allGroupMembers) {
1733
1734         // Found Cyclic dependency
1735         if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) {
1736             return;
1737         }
1738         GroupDefinition groupDefinition = allGroups.get(groupName);
1739         // All Members Of Current Group Resource Instances & Other Groups
1740         Set<String> currGroupMembers = groupDefinition.getMembers().keySet();
1741         // Filtered Members Of Current Group containing only members which
1742         // are groups
1743         List<String> currGroupFilteredMembers = currGroupMembers.stream().
1744                 // Keep Only Elements of type group and not Resource Instances
1745                         filter(allGroups::containsKey).
1746                 // Add Filtered Elements to main Set
1747                         peek(allGroupMembers::add).
1748                 // Collect results
1749                         collect(toList());
1750
1751         // Recursively call the method for all the filtered group members
1752         for (String innerGroupName : currGroupFilteredMembers) {
1753             fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers);
1754         }
1755
1756     }
1757
1758     private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups,
1759                                                                Set<String> allGroupMembers) {
1760
1761         boolean stop = false;
1762         // In Case Not Group Stop
1763         if (!allGroups.containsKey(groupName)) {
1764             stop = true;
1765         }
1766         // In Case Group Has no members stop
1767         if (!stop) {
1768             GroupDefinition groupDefinition = allGroups.get(groupName);
1769             stop = isEmpty(groupDefinition.getMembers());
1770
1771         }
1772         // In Case all group members already contained stop
1773         if (!stop) {
1774             final Set<String> allMembers = allGroups.get(groupName).getMembers().keySet();
1775             Set<String> membersOfTypeGroup = allMembers.stream().
1776                     // Filter In Only Group members
1777                             filter(allGroups::containsKey).
1778                     // Collect
1779                             collect(toSet());
1780             stop = allGroupMembers.containsAll(membersOfTypeGroup);
1781         }
1782         return stop;
1783     }
1784
1785     private Resource createRIAndRelationsFromYaml(String yamlName, Resource resource,
1786                                                   Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap,
1787                                                   String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1788                                                   Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1789                                                   Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1790                                                   String nodeName) {
1791
1792         log.debug("************* Going to create all nodes {}", yamlName);
1793         handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts,
1794                 nodeTypesInfo, csarInfo, nodeName);
1795         log.debug("************* Finished to create all nodes {}", yamlName);
1796         log.debug("************* Going to create all resource instances {}", yamlName);
1797         resource = createResourceInstances(yamlName, resource,
1798                 uploadComponentInstanceInfoMap, csarInfo.getCreatedNodes());
1799         log.debug("************* Finished to create all resource instances {}", yamlName);
1800         log.debug("************* Going to create all relations {}", yamlName);
1801         resource = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap);
1802         log.debug("************* Finished to create all relations {}", yamlName);
1803         log.debug("************* Going to create positions {}", yamlName);
1804         compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier().getUserId());
1805         log.debug("************* Finished to set positions {}", yamlName);
1806         return resource;
1807     }
1808
1809     private void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts,
1810                                                     List<ArtifactDefinition> artifactsToAdd) {
1811         List<String> vfcArtifactNames = vfcArtifacts.stream().map(ArtifactDataDefinition::getArtifactName)
1812                 .collect(toList());
1813         artifactsToAdd.stream().forEach(a -> {
1814             if (!vfcArtifactNames.contains(a.getArtifactName())) {
1815                 vfcArtifacts.add(a);
1816             } else {
1817                 log.debug("Can't upload two artifact with the same name {}. ", a.getArtifactName());
1818             }
1819         });
1820
1821     }
1822
1823     @SuppressWarnings("unchecked")
1824     private void handleNodeTypes(String yamlName, Resource resource,
1825                                  String topologyTemplateYaml, boolean needLock,
1826                                  Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1827                                  List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
1828                                  CsarInfo csarInfo, String nodeName) {
1829         try{
1830             for (Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
1831                 if (nodeTypeEntry.getValue().isNested()) {
1832
1833                     handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts,
1834                             nodeTypesInfo, csarInfo, nodeTypeEntry.getKey());
1835                     log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
1836                 }
1837             }
1838             Map<String, Object> mappedToscaTemplate = null;
1839             if (StringUtils.isNotEmpty(nodeName) && isNotEmpty(nodeTypesInfo)
1840                     && nodeTypesInfo.containsKey(nodeName)) {
1841                 mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
1842             }
1843             if (isEmpty(mappedToscaTemplate)) {
1844                 mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
1845             }
1846             createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle,
1847                     nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
1848         } catch(ByActionStatusComponentException e){
1849             ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
1850             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
1851             throw e;
1852         } catch(ByResponseFormatComponentException e){
1853             ResponseFormat responseFormat = e.getResponseFormat();
1854             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
1855             throw e;
1856         } catch (StorageException e){
1857             ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
1858             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
1859             throw e;
1860         }
1861     }
1862
1863     private Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo,
1864                                                                    List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock,
1865                                                                    boolean inTransaction) {
1866
1867         if (csarInfo.getCsar() != null) {
1868             String vendorLicenseModelId = null;
1869             String vfLicenseModelId = null;
1870
1871             if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE) {
1872                 Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts();
1873                 if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
1874                     for (Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
1875                         if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) {
1876                             vendorLicenseModelId = artifactEntry.getValue().getUniqueId();
1877                         }
1878                         if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) {
1879                             vfLicenseModelId = artifactEntry.getValue().getUniqueId();
1880                         }
1881                     }
1882                 }
1883
1884             }
1885             // Specific Behavior for license artifacts
1886             createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
1887                     CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL,
1888                     ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
1889                     Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME,
1890                     Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, true, shouldLock,
1891                     inTransaction);
1892             createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
1893                     CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
1894                     ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL,
1895                     Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId,
1896                     artifactOperation, null, true, shouldLock, inTransaction);
1897
1898             Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource,
1899                     createdArtifacts, shouldLock, inTransaction, artifactOperation);
1900             if (eitherCreateResult.isRight()) {
1901                 return Either.right(eitherCreateResult.right().value());
1902             }
1903             Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade
1904                     .getToscaElement(resource.getUniqueId());
1905             if (eitherGerResource.isRight()) {
1906                 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
1907                         componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
1908
1909                 return Either.right(responseFormat);
1910
1911             }
1912             resource = eitherGerResource.left().value();
1913
1914             Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils.getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
1915
1916             if (artifacsMetaCsarStatus.isLeft()) {
1917                 String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
1918                 String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
1919                 Either<Resource, ResponseFormat> createArtifactsFromCsar;
1920                 if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
1921                     createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
1922                 } else {
1923                     createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
1924                 }
1925
1926                 if (createArtifactsFromCsar.isRight()) {
1927                     log.debug("Couldn't create artifacts from artifacts.meta");
1928                     return Either.right(createArtifactsFromCsar.right().value());
1929                 }
1930
1931                 return Either.left(createArtifactsFromCsar.left().value());
1932             } else {
1933
1934                 return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(resource, csarInfo, shouldLock, inTransaction);
1935
1936             }
1937         }
1938         return Either.left(resource);
1939     }
1940
1941
1942     private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, CsarInfo csarInfo,
1943                                                                                 String artifactPath, String artifactFileName, String artifactType, ArtifactGroupTypeEnum artifactGroupType,
1944                                                                                 String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId,
1945                                                                                 ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, boolean isFromCsar, boolean shouldLock,
1946                                                                                 boolean inTransaction) {
1947         byte[] artifactFileBytes = null;
1948
1949         if (csarInfo.getCsar().containsKey(artifactPath)) {
1950             artifactFileBytes = csarInfo.getCsar().get(artifactPath);
1951         }
1952         Either<Boolean, ResponseFormat> result = Either.left(true);
1953         if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE || operation.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE) {
1954             if (isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) {
1955                 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource,
1956                         shouldLock, inTransaction);
1957                 if (handleDelete.isRight()) {
1958                     result = Either.right(handleDelete.right().value());
1959                 }
1960                 return result;
1961             }
1962
1963
1964             if (StringUtils.isEmpty(artifactId) && artifactFileBytes != null) {
1965                 operation = artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
1966                         ArtifactOperationEnum.CREATE);
1967             }
1968
1969         }
1970         if (artifactFileBytes != null) {
1971             Map<String, Object> vendorLicenseModelJson = ArtifactUtils.buildJsonForUpdateArtifact(artifactId, artifactFileName,
1972                     artifactType, artifactGroupType, artifactLabel, artifactDisplayName, artifactDescription,
1973                     artifactFileBytes, null, isFromCsar);
1974             Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic.createOrUpdateCsarArtifactFromJson(
1975                     resource, csarInfo.getModifier(), vendorLicenseModelJson, operation);
1976             addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
1977             if (eitherNonMetaArtifacts.isRight()) {
1978                 BeEcompErrorManager.getInstance()
1979                         .logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: "
1980                                         + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(),
1981                                 ErrorSeverity.WARNING);
1982                 return Either.right(eitherNonMetaArtifacts.right().value());
1983             }
1984         }
1985         return result;
1986     }
1987
1988     private boolean isArtifactDeletionRequired(String artifactId, byte[] artifactFileBytes, boolean isFromCsar) {
1989         return !StringUtils.isEmpty(artifactId) && artifactFileBytes == null && isFromCsar;
1990     }
1991
1992
1993     private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation,
1994                                                              List<ArtifactDefinition> createdArtifacts,
1995                                                              Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
1996         if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && createdArtifacts != null
1997                 && eitherNonMetaArtifacts.isLeft()) {
1998             Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left().value();
1999             if (eitherResult.isLeft()) {
2000                 createdArtifacts.add(eitherResult.left().value());
2001             }
2002         }
2003     }
2004
2005
2006     private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource,
2007                                                                             List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
2008                                                                             ArtifactOperationInfo artifactOperation) {
2009
2010         Either<Resource, ResponseFormat> resStatus = null;
2011         Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
2012
2013         try {
2014             Either<List<NonMetaArtifactInfo>, String> artifactPathAndNameList = getValidArtifactNames(csarInfo, collectedWarningMessages);
2015             if (artifactPathAndNameList.isRight()) {
2016                 return Either.right(getComponentsUtils().getResponseFormatByArtifactId(
2017                         ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right().value()));
2018             }
2019             EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
2020
2021             if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
2022                 vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
2023                 vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left().value());
2024             } else {
2025                 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(
2026                         resource, artifactPathAndNameList.left().value(), csarInfo.getModifier());
2027
2028                 if (findVfCsarArtifactsToHandleRes.isRight()) {
2029                     resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value());
2030                 }
2031                 if (resStatus == null) {
2032                     vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left().value();
2033                 }
2034             }
2035             if (resStatus == null && vfCsarArtifactsToHandle != null) {
2036                 resStatus = processCsarArtifacts(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, resStatus, vfCsarArtifactsToHandle);
2037             }
2038             if (resStatus == null) {
2039                 resStatus = Either.left(resource);
2040             }
2041         } catch (Exception e) {
2042             resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2043             log.debug("Exception occured in createNonMetaArtifacts, message:{}", e.getMessage(), e);
2044         } finally {
2045             CsarUtils.handleWarningMessages(collectedWarningMessages);
2046         }
2047         return resStatus;
2048     }
2049
2050     private Either<Resource, ResponseFormat> processCsarArtifacts(CsarInfo csarInfo, Resource resource, List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction, Either<Resource, ResponseFormat> resStatus, EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle) {
2051         for (Entry<ArtifactOperationEnum, List<NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle
2052                 .entrySet()) {
2053
2054             Optional<ResponseFormat> optionalCreateInDBError =
2055                     // Stream of artifacts to be created
2056                     currArtifactOperationPair.getValue().stream()
2057                             // create each artifact
2058                             .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(),
2059                                     e.getArtifactName(), e.getArtifactType().getType(),
2060                                     e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
2061                                     CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(),
2062                                     artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
2063                                             currArtifactOperationPair.getKey()),
2064                                     createdArtifacts, e.isFromCsar(), shouldLock, inTransaction))
2065                             // filter in only error
2066                             .filter(Either::isRight).
2067                             // Convert the error from either to
2068                             // ResponseFormat
2069                                     map(e -> e.right().value()).
2070                             // Check if an error occurred
2071                                     findAny();
2072             // Error found on artifact Creation
2073             if (optionalCreateInDBError.isPresent()) {
2074                 resStatus = Either.right(optionalCreateInDBError.get());
2075                 break;
2076             }
2077         }
2078         return resStatus;
2079     }
2080
2081     private Either<List<NonMetaArtifactInfo>, String> getValidArtifactNames(CsarInfo csarInfo, Map<String, Set<List<String>>> collectedWarningMessages) {
2082         List<NonMetaArtifactInfo> artifactPathAndNameList =
2083                 // Stream of file paths contained in csar
2084                 csarInfo.getCsar().entrySet().stream()
2085                         // Filter in only VF artifact path location
2086                         .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey())
2087                                 .matches())
2088                         // Validate and add warnings
2089                         .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(),
2090                                 collectedWarningMessages))
2091                         // Filter in Non Warnings
2092                         .filter(Either::isLeft)
2093                         // Convert from Either to NonMetaArtifactInfo
2094                         .map(e -> e.left().value())
2095                         // collect to List
2096                         .collect(toList());
2097         Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
2098         for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
2099             if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) {
2100                 return Either.right(nonMetaArtifactInfo.getArtifactName());
2101             }
2102         }
2103         return Either.left(artifactPathAndNameList);
2104     }
2105
2106     private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(
2107             Resource resource, List<NonMetaArtifactInfo> artifactPathAndNameList, User user) {
2108
2109         List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
2110         // collect all Deployment and Informational artifacts of VF
2111         if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts().isEmpty()) {
2112             existingArtifacts.addAll(resource.getDeploymentArtifacts().values());
2113         }
2114         if (resource.getArtifacts() != null && !resource.getArtifacts().isEmpty()) {
2115             existingArtifacts.addAll(resource.getArtifacts().values());
2116         }
2117         existingArtifacts = existingArtifacts.stream()
2118                 // filter MANDATORY artifacts, LICENSE artifacts and artifacts
2119                 // was created from HEAT.meta
2120                 .filter(this::isNonMetaArtifact).collect(toList());
2121
2122         List<String> artifactsToIgnore = new ArrayList<>();
2123         // collect IDs of Artifacts of VF which belongs to any group
2124         if (resource.getGroups() != null) {
2125             resource.getGroups().stream().forEach(g -> {
2126                 if (g.getArtifacts() != null && !g.getArtifacts().isEmpty()) {
2127                     artifactsToIgnore.addAll(g.getArtifacts());
2128                 }
2129             });
2130         }
2131         existingArtifacts = existingArtifacts.stream()
2132                 // filter artifacts which belongs to any group
2133                 .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(toList());
2134         return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user);
2135     }
2136
2137     private boolean isNonMetaArtifact(ArtifactDefinition artifact) {
2138         boolean result = true;
2139         if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) {
2140             result = false;
2141         }
2142         return result;
2143     }
2144
2145     private boolean isValidArtifactType(ArtifactDefinition artifact) {
2146         boolean result = true;
2147         if (artifact.getArtifactType() == null
2148                 || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE
2149                 || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) {
2150             result = false;
2151         }
2152         return result;
2153     }
2154
2155     private Resource createResourceInstancesRelations(User user, String yamlName, Resource resource,
2156                                                       Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2157         log.debug("#createResourceInstancesRelations - Going to create relations ");
2158         List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
2159         if (((isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)) &&
2160                 resource.getResourceType() != ResourceTypeEnum.PNF)) { // PNF can have no resource instances
2161             log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ", resource.getUniqueId(), yamlName);
2162             BeEcompErrorManager.getInstance().logInternalDataError("createResourceInstancesRelations", "No instances found in a resource or nn yaml template. ", ErrorSeverity.ERROR);
2163             throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName));
2164         }
2165         Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
2166         Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
2167         Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
2168         Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
2169         Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
2170         Map<String, List<PropertyDefinition>> instAttributes = new HashMap<>();
2171         Map<String, Resource> originCompMap = new HashMap<>();
2172         List<RequirementCapabilityRelDef> relations = new ArrayList<>();
2173         Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
2174
2175         log.debug("#createResourceInstancesRelations - Before get all datatypes. ");
2176         Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll();
2177         if (allDataTypes.isRight()) {
2178             JanusGraphOperationStatus status = allDataTypes.right().value();
2179             BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance",
2180                     "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
2181             throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
2182                     DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)), yamlName));
2183
2184         }
2185         Resource finalResource = resource;
2186         uploadResInstancesMap
2187                 .values()
2188                 .forEach(i ->processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes,
2189                         instProperties, instCapabilities, instRequirements, instDeploymentArtifacts,
2190                         instArtifacts, instAttributes, originCompMap, instInputs, i));
2191
2192         associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties);
2193         associateComponentInstanceInputsToComponent(yamlName, resource, instInputs);
2194         associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts);
2195         associateArtifactsToInstances(yamlName, resource, instArtifacts);
2196         associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements);
2197         associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes);
2198
2199         resource = getResourceAfterCreateRelations(resource);
2200
2201         addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations);
2202         associateResourceInstances(yamlName, resource, relations);
2203         handleSubstitutionMappings(resource, uploadResInstancesMap);
2204         log.debug("************* in create relations, getResource start");
2205         Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
2206         log.debug("************* in create relations, getResource end");
2207         if (eitherGetResource.isRight()) {
2208             throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatByResource(
2209                     componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource));
2210         }
2211         return eitherGetResource.left().value();
2212     }
2213
2214     private Resource getResourceAfterCreateRelations(Resource resource) {
2215         ComponentParametersView parametersView = getComponentFilterAfterCreateRelations();
2216         Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
2217                 .getToscaElement(resource.getUniqueId(), parametersView);
2218
2219         if (eitherGetResource.isRight()) {
2220             throwComponentExceptionByResource(eitherGetResource.right().value(),resource);
2221         }
2222         return eitherGetResource.left().value();
2223     }
2224
2225     private void associateResourceInstances(String yamlName, Resource resource, List<RequirementCapabilityRelDef> relations) {
2226         StorageOperationStatus addArtToInst;
2227         addArtToInst = toscaOperationFacade.associateResourceInstances(resource.getUniqueId(), relations);
2228         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2229             log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(),
2230                     addArtToInst);
2231             throw new ByResponseFormatComponentException(componentsUtils
2232                     .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2233         }
2234     }
2235
2236     private ComponentParametersView getComponentFilterAfterCreateRelations() {
2237         ComponentParametersView parametersView = new ComponentParametersView();
2238         parametersView.disableAll();
2239         parametersView.setIgnoreComponentInstances(false);
2240         parametersView.setIgnoreComponentInstancesProperties(false);
2241         parametersView.setIgnoreCapabilities(false);
2242         parametersView.setIgnoreRequirements(false);
2243         parametersView.setIgnoreGroups(false);
2244         return parametersView;
2245     }
2246
2247     private void associateInstAttributeToComponentToInstances(String yamlName, Resource resource, Map<String, List<PropertyDefinition>> instAttributes) {
2248         StorageOperationStatus addArtToInst;
2249         addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes,
2250                 resource.getUniqueId());
2251         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2252             log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
2253                     addArtToInst);
2254             throw new ByResponseFormatComponentException(componentsUtils
2255                     .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2256         }
2257     }
2258
2259     private void associateOrAddCalculatedCapReq(String yamlName, Resource resource, Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
2260         StorageOperationStatus addArtToInst;
2261         addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements,
2262                 resource.getUniqueId());
2263         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2264             log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(),
2265                     addArtToInst);
2266             throw new ByResponseFormatComponentException(componentsUtils
2267                     .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2268         }
2269     }
2270
2271     private void associateArtifactsToInstances(String yamlName, Resource resource, Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
2272         StorageOperationStatus addArtToInst;
2273
2274         addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource.getUniqueId());
2275         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2276             log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2277             throw new ByResponseFormatComponentException(componentsUtils
2278                     .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2279         }
2280     }
2281
2282     private void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource, Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
2283         StorageOperationStatus addArtToInst = toscaOperationFacade
2284                 .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource.getUniqueId(), user);
2285         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2286             log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2287             throw new ByResponseFormatComponentException(componentsUtils
2288                     .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2289         }
2290     }
2291
2292     private void associateComponentInstanceInputsToComponent(String yamlName, Resource resource, Map<String, List<ComponentInstanceInput>> instInputs) {
2293         if (MapUtils.isNotEmpty(instInputs)) {
2294             Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
2295                     .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
2296             if (addInputToInst.isRight()) {
2297                 log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(),
2298                         addInputToInst.right().value());
2299                 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(
2300                         componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
2301             }
2302         }
2303     }
2304
2305     private void associateComponentInstancePropertiesToComponent(String yamlName, Resource resource, Map<String, List<ComponentInstanceProperty>> instProperties) {
2306         Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
2307                 .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
2308         if (addPropToInst.isRight()) {
2309             log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(),
2310                     addPropToInst.right().value());
2311             throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(
2312                     componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
2313         }
2314     }
2315
2316     private void handleSubstitutionMappings(Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2317         if (resource.getResourceType() == ResourceTypeEnum.CVFC) {
2318             Either<Resource, StorageOperationStatus> getResourceRes = toscaOperationFacade.getToscaFullElement(resource.getUniqueId());
2319             if (getResourceRes.isRight()) {
2320                 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
2321                         componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
2322                 throw new ByResponseFormatComponentException(responseFormat);
2323             }
2324             getResourceRes = updateCalculatedCapReqWithSubstitutionMappings(getResourceRes.left().value(),
2325                     uploadResInstancesMap);
2326             if (getResourceRes.isRight()) {
2327                 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
2328                         componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
2329                 throw new ByResponseFormatComponentException(responseFormat);
2330             }
2331         }
2332     }
2333
2334     private void addRelationsToRI(String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) {
2335         for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
2336             UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
2337             ComponentInstance currentCompInstance = null;
2338             for (ComponentInstance compInstance : componentInstancesList) {
2339
2340                 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
2341                     currentCompInstance = compInstance;
2342                     break;
2343                 }
2344
2345             }
2346             if (currentCompInstance == null) {
2347                 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
2348                         resource.getUniqueId());
2349                 BeEcompErrorManager.getInstance().logInternalDataError(
2350                         COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
2351                         resource.getUniqueId(), ErrorSeverity.ERROR);
2352                 ResponseFormat responseFormat = componentsUtils
2353                         .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2354                 throw new ByResponseFormatComponentException(responseFormat);
2355             }
2356
2357             ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
2358             if (addRelationToRiRes.getStatus() != 200) {
2359                 throw new ByResponseFormatComponentException(addRelationToRiRes);
2360             }
2361         }
2362     }
2363
2364     private void processComponentInstance(String yamlName, Resource resource, List<ComponentInstance> componentInstancesList, Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes, Map<String, List<ComponentInstanceProperty>> instProperties, Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements, Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts, Map<String, Map<String, ArtifactDefinition>> instArtifacts, Map<String, List<PropertyDefinition>> instAttributes, Map<String, Resource> originCompMap, Map<String, List<ComponentInstanceInput>> instInputs, UploadComponentInstanceInfo uploadComponentInstanceInfo) {
2365         Optional<ComponentInstance> currentCompInstanceOpt = componentInstancesList.stream()
2366                 .filter(i->i.getName().equals(uploadComponentInstanceInfo.getName()))
2367                 .findFirst();
2368         if (!currentCompInstanceOpt.isPresent()) {
2369             log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
2370                     resource.getUniqueId());
2371             BeEcompErrorManager.getInstance().logInternalDataError(
2372                     COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
2373                     resource.getUniqueId(), ErrorSeverity.ERROR);
2374             ResponseFormat responseFormat = componentsUtils
2375                     .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2376             throw new ByResponseFormatComponentException(responseFormat);
2377         }
2378         ComponentInstance currentCompInstance = currentCompInstanceOpt.get();
2379         String resourceInstanceId = currentCompInstance.getUniqueId();
2380         Resource originResource = getOriginResource(yamlName, originCompMap, currentCompInstance);
2381         if (isNotEmpty(originResource.getRequirements())) {
2382             instRequirements.put(currentCompInstance, originResource.getRequirements());
2383         }
2384         if (isNotEmpty(originResource.getCapabilities())) {
2385             processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo,
2386                     currentCompInstance, originResource);
2387         }
2388         if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty()) {
2389             instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
2390         }
2391         if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty()) {
2392             instArtifacts.put(resourceInstanceId, originResource.getArtifacts());
2393         }
2394         if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty()) {
2395             instAttributes.put(resourceInstanceId, originResource.getAttributes());
2396         }
2397         if (originResource.getResourceType() != ResourceTypeEnum.CVFC) {
2398             ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource,
2399                     originResource, currentCompInstance, instProperties, allDataTypes.left().value());
2400             if (addPropertiesValueToRiRes.getStatus() != 200) {
2401                 throw new ByResponseFormatComponentException(addPropertiesValueToRiRes);
2402             }
2403         } else {
2404             addInputsValuesToRi(uploadComponentInstanceInfo, resource,
2405                     originResource, currentCompInstance, instInputs, allDataTypes.left().value());
2406         }
2407     }
2408
2409     private Resource getOriginResource(String yamlName, Map<String, Resource> originCompMap, ComponentInstance currentCompInstance) {
2410         Resource originResource;
2411         if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
2412             Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade
2413                     .getToscaFullElement(currentCompInstance.getComponentUid());
2414             if (getOriginResourceRes.isRight()) {
2415                 log.debug("failed to fetch resource with uniqueId {} and tosca component name {} status is {}",
2416                         currentCompInstance.getComponentUid(), currentCompInstance.getToscaComponentName(),
2417                         getOriginResourceRes);
2418                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
2419                         componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName);
2420                 throw new ByResponseFormatComponentException(responseFormat);
2421             }
2422             originResource = getOriginResourceRes.left().value();
2423             originCompMap.put(originResource.getUniqueId(), originResource);
2424         } else {
2425             originResource = originCompMap.get(currentCompInstance.getComponentUid());
2426         }
2427         return originResource;
2428     }
2429
2430     private void processComponentInstanceCapabilities(Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes, Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance, Resource originResource) {
2431         Map<String, List<CapabilityDefinition>> originCapabilities;
2432         if (isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) {
2433             originCapabilities = new HashMap<>();
2434             Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>();
2435             originResource.getCapabilities().forEach((k,v) ->  addCapabilities(originCapabilities, k, v));
2436             uploadComponentInstanceInfo.getCapabilities().values().forEach(l-> addCapabilitiesProperties(newPropertiesMap, l));
2437             updateCapabilityPropertiesValues(allDataTypes, originCapabilities, newPropertiesMap);
2438         } else {
2439             originCapabilities = originResource.getCapabilities();
2440         }
2441         instCapabilties.put(currentCompInstance, originCapabilities);
2442     }
2443
2444     private void updateCapabilityPropertiesValues(Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes, Map<String, List<CapabilityDefinition>> originCapabilities, Map<String, Map<String, UploadPropInfo>> newPropertiesMap) {
2445         originCapabilities.values().stream()
2446                 .flatMap(Collection::stream)
2447                 .filter(c -> newPropertiesMap.containsKey(c.getName()))
2448                 .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()), allDataTypes.left().value()));
2449     }
2450
2451     private void addCapabilitiesProperties(Map<String, Map<String, UploadPropInfo>> newPropertiesMap, List<UploadCapInfo> capabilities) {
2452         for (UploadCapInfo capability : capabilities) {
2453             if (isNotEmpty(capability.getProperties())) {
2454                 newPropertiesMap.put(capability.getName(), capability.getProperties().stream()
2455                         .collect(toMap(UploadInfo::getName, p -> p)));
2456             }
2457         }
2458     }
2459
2460     private void addCapabilities(Map<String, List<CapabilityDefinition>> originCapabilities, String type, List<CapabilityDefinition> capabilities) {
2461         List<CapabilityDefinition> list = capabilities.stream().map(CapabilityDefinition::new)
2462                 .collect(toList());
2463         originCapabilities.put(type, list);
2464     }
2465
2466     private void updatePropertyValues(List<ComponentInstanceProperty> properties, Map<String, UploadPropInfo> newProperties,
2467                                       Map<String, DataTypeDefinition> allDataTypes) {
2468         properties.forEach(p->updatePropertyValue(p, newProperties.get(p.getName()), allDataTypes));
2469     }
2470
2471     private String updatePropertyValue(ComponentInstanceProperty property, UploadPropInfo propertyInfo,
2472                                        Map<String, DataTypeDefinition> allDataTypes) {
2473         String value = null;
2474         List<GetInputValueDataDefinition> getInputs = null;
2475         boolean isValidate = true;
2476         if (null != propertyInfo && propertyInfo.getValue() != null) {
2477             getInputs = propertyInfo.getGet_input();
2478             isValidate = getInputs == null || getInputs.isEmpty();
2479             if (isValidate) {
2480                 value = getPropertyJsonStringValue(propertyInfo.getValue(), property.getType());
2481             } else {
2482                 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2483                         TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
2484             }
2485         }
2486         property.setValue(value);
2487         return validatePropValueBeforeCreate(property, value, isValidate, null, allDataTypes);
2488     }
2489
2490     private Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource,
2491                                                                                                     Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2492         Either<Resource, StorageOperationStatus> updateRes = null;
2493         Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>();
2494         Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>();
2495         StorageOperationStatus status = toscaOperationFacade
2496                 .deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId());
2497         if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2498             log.debug(
2499                     "Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}",
2500                     resource.getUniqueId(), status);
2501             updateRes = Either.right(status);
2502         }
2503         if (updateRes == null) {
2504             fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap,
2505                     updatedInstCapabilities, updatedInstRequirements);
2506             status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements,
2507                     resource.getUniqueId());
2508             if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2509                 log.debug(
2510                         "Failed to associate capabilities and requirementss of resource {}, updated according to a substitution mapping. Status is {}",
2511                         resource.getUniqueId(), status);
2512                 updateRes = Either.right(status);
2513             }
2514         }
2515         if (updateRes == null) {
2516             updateRes = Either.left(resource);
2517         }
2518         return updateRes;
2519     }
2520
2521     private void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances,
2522                                                          Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2523                                                          Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities,
2524                                                          Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) {
2525
2526         componentInstances.stream().forEach(i -> {
2527             fillUpdatedInstCapabilities(updatedInstCapabilities, i,
2528                     uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate());
2529             fillUpdatedInstRequirements(updatedInstRequirements, i,
2530                     uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate());
2531         });
2532     }
2533
2534     private void fillUpdatedInstRequirements(
2535             Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements,
2536             ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
2537         Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
2538         Set<String> updatedReqNames = new HashSet<>();
2539         if (isNotEmpty(requirementsNamesToUpdate)) {
2540             for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements().entrySet()) {
2541                 updatedRequirements.put(requirements.getKey(),
2542                         requirements.getValue().stream()
2543                                 .filter(r -> requirementsNamesToUpdate.containsKey(r.getName())
2544                                         && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
2545                                 .map(r -> {
2546                                     r.setParentName(r.getName());
2547                                     r.setName(requirementsNamesToUpdate.get(r.getName()));
2548                                     updatedReqNames.add(r.getName());
2549                                     return r;
2550                                 }).collect(toList()));
2551             }
2552         }
2553         if (isNotEmpty(updatedRequirements)) {
2554             updatedInstRequirements.put(instance, updatedRequirements);
2555         }
2556     }
2557
2558     private void fillUpdatedInstCapabilities(
2559             Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties,
2560             ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
2561         Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
2562         Set<String> updatedCapNames = new HashSet<>();
2563         if (isNotEmpty(capabilitiesNamesToUpdate)) {
2564             for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities().entrySet()) {
2565                 updatedCapabilities.put(requirements.getKey(),
2566                         requirements.getValue().stream()
2567                                 .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName())
2568                                         && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
2569                                 .map(c -> {
2570                                     c.setParentName(c.getName());
2571                                     c.setName(capabilitiesNamesToUpdate.get(c.getName()));
2572                                     updatedCapNames.add(c.getName());
2573                                     return c;
2574                                 }).collect(toList()));
2575             }
2576         }
2577         if (isNotEmpty(updatedCapabilities)) {
2578             updatedInstCapabilties.put(instance, updatedCapabilities);
2579         }
2580     }
2581
2582     private ResponseFormat addRelationToRI(String yamlName, Resource resource,
2583                                            UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
2584         List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
2585
2586         ComponentInstance currentCompInstance = null;
2587
2588         for (ComponentInstance compInstance : componentInstancesList) {
2589
2590             if (compInstance.getName().equals(nodesInfoValue.getName())) {
2591                 currentCompInstance = compInstance;
2592                 break;
2593             }
2594
2595         }
2596
2597         if (currentCompInstance == null) {
2598             log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(),
2599                     resource.getUniqueId());
2600             BeEcompErrorManager.getInstance().logInternalDataError(
2601                     COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE,
2602                     resource.getUniqueId(), ErrorSeverity.ERROR);
2603             return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE,
2604                     yamlName);
2605         }
2606         String resourceInstanceId = currentCompInstance.getUniqueId();
2607
2608         Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
2609
2610         if (regMap != null) {
2611             Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
2612
2613             while (nodesRegValue.hasNext()) {
2614                 Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
2615
2616                 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
2617                 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
2618                     log.debug("Going to create  relation {}", uploadRegInfo.getName());
2619                     String regName = uploadRegInfo.getName();
2620                     RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
2621                     regCapRelDef.setFromNode(resourceInstanceId);
2622                     log.debug("try to find available requirement {} ", regName);
2623                     Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName,
2624                             yamlName, nodesInfoValue, currentCompInstance,
2625                             uploadRegInfo.getCapabilityName());
2626                     if (eitherReqStatus.isRight()) {
2627                         log.debug("failed to find available requirement {} status is {}", regName,
2628                                 eitherReqStatus.right().value());
2629                         return eitherReqStatus.right().value();
2630                     }
2631
2632                     RequirementDefinition validReq = eitherReqStatus.left().value();
2633                     List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef
2634                             .getRelationships();
2635                     if (reqAndRelationshipPairList == null) {
2636                         reqAndRelationshipPairList = new ArrayList<>();
2637                     }
2638                     RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
2639                     reqAndRelationshipPair.setRequirement(regName);
2640                     reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
2641                     reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
2642                     RelationshipImpl relationship = new RelationshipImpl();
2643                     relationship.setType(validReq.getCapability());
2644                     reqAndRelationshipPair.setRelationships(relationship);
2645
2646                     ComponentInstance currentCapCompInstance = null;
2647                     for (ComponentInstance compInstance : componentInstancesList) {
2648                         if (compInstance.getName().equals(uploadRegInfo.getNode())) {
2649                             currentCapCompInstance = compInstance;
2650                             break;
2651                         }
2652                     }
2653
2654                     if (currentCapCompInstance == null) {
2655                         log.debug("The component instance  with name {} not found on resource {} ",
2656                                 uploadRegInfo.getNode(), resource.getUniqueId());
2657                         BeEcompErrorManager.getInstance().logInternalDataError(
2658                                 COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE,
2659                                 resource.getUniqueId(), ErrorSeverity.ERROR);
2660                         return componentsUtils
2661                                 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2662                     }
2663                     regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
2664                     log.debug("try to find aviable Capability  req name is {} ", validReq.getName());
2665                     CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq,
2666                             currentCapCompInstance, uploadRegInfo);
2667                     reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
2668                     reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
2669                     reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
2670                     if (aviableCapForRel == null) {
2671                         log.debug("aviable capability was not found. req name is {} component instance is {}",
2672                                 validReq.getName(), currentCapCompInstance.getUniqueId());
2673                         BeEcompErrorManager.getInstance().logInternalDataError(
2674                                 "aviable capability was not found. req name is " + validReq.getName()
2675                                         + " component instance is " + currentCapCompInstance.getUniqueId(),
2676                                 resource.getUniqueId(), ErrorSeverity.ERROR);
2677                         return componentsUtils
2678                                 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2679                     }
2680                     CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
2681                     capReqRel.setRelation(reqAndRelationshipPair);
2682                     reqAndRelationshipPairList.add(capReqRel);
2683                     regCapRelDef.setRelationships(reqAndRelationshipPairList);
2684                     relations.add(regCapRelDef);
2685                 }
2686             }
2687         } else if (resource.getResourceType() != ResourceTypeEnum.CVFC) {
2688             return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
2689         }
2690         return componentsUtils.getResponseFormat(ActionStatus.OK);
2691     }
2692
2693     private void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
2694                                      Resource resource, Resource originResource, ComponentInstance currentCompInstance,
2695                                      Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) {
2696         Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
2697         if (MapUtils.isNotEmpty(propMap)) {
2698             Map<String, InputDefinition> currPropertiesMap = new HashMap<>();
2699             List<ComponentInstanceInput> instPropList = new ArrayList<>();
2700
2701             if (CollectionUtils.isEmpty( originResource.getInputs())) {
2702                 log.debug("failed to find properties ");
2703                 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND));
2704             }
2705             originResource.getInputs().forEach(p->addInput(currPropertiesMap, p));
2706             for (List<UploadPropInfo> propertyList : propMap.values()) {
2707                 processProperty(resource, currentCompInstance, allDataTypes, currPropertiesMap, instPropList, propertyList);
2708             }
2709             currPropertiesMap.values().forEach(p->instPropList.add(new ComponentInstanceInput(p)));
2710             instInputs.put(currentCompInstance.getUniqueId(), instPropList);
2711         }
2712     }
2713
2714     private void processProperty(Resource resource, ComponentInstance currentCompInstance, Map<String, DataTypeDefinition> allDataTypes, Map<String, InputDefinition> currPropertiesMap, List<ComponentInstanceInput> instPropList, List<UploadPropInfo> propertyList) {
2715         UploadPropInfo propertyInfo = propertyList.get(0);
2716         String propName = propertyInfo.getName();
2717         if (!currPropertiesMap.containsKey(propName)) {
2718             log.debug("failed to find property {} ", propName);
2719             throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
2720                     propName));
2721         }
2722         InputDefinition curPropertyDef = currPropertiesMap.get(propName);
2723         ComponentInstanceInput property = null;
2724
2725         String value = null;
2726         List<GetInputValueDataDefinition> getInputs = null;
2727         boolean isValidate = true;
2728         if (propertyInfo.getValue() != null) {
2729             getInputs = propertyInfo.getGet_input();
2730             isValidate = getInputs == null || getInputs.isEmpty();
2731             if (isValidate) {
2732                 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2733                         curPropertyDef.getType());
2734             } else {
2735                 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2736                         TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
2737             }
2738         }
2739         String innerType = null;
2740         property = new ComponentInstanceInput(curPropertyDef, value, null);
2741
2742         String validPropertyVAlue = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes);
2743
2744         property.setValue(validPropertyVAlue);
2745
2746         if (isNotEmpty(getInputs)) {
2747             List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
2748             for (GetInputValueDataDefinition getInput : getInputs) {
2749                 List<InputDefinition> inputs = resource.getInputs();
2750                 if (CollectionUtils.isEmpty(inputs)) {
2751                     log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ",
2752                             property, currentCompInstance.getUniqueId());
2753                     throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2754                 }
2755
2756                 Optional<InputDefinition> optional = inputs.stream()
2757                         .filter(p -> p.getName().equals(getInput.getInputName())).findAny();
2758                 if (!optional.isPresent()) {
2759                     log.debug("Failed to find input {} ", getInput.getInputName());
2760                     // @@TODO error message
2761                     throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2762                 }
2763                 InputDefinition input = optional.get();
2764                 getInput.setInputId(input.getUniqueId());
2765                 getInputValues.add(getInput);
2766
2767                 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
2768                 processGetInput(getInputValues, inputs, getInputIndex);
2769             }
2770             property.setGetInputValues(getInputValues);
2771         }
2772         instPropList.add(property);
2773         // delete overriden property
2774         currPropertiesMap.remove(property.getName());
2775     }
2776
2777     private void processGetInput(List<GetInputValueDataDefinition> getInputValues, List<InputDefinition> inputs, GetInputValueDataDefinition getInputIndex) {
2778         Optional<InputDefinition> optional;
2779         if (getInputIndex != null) {
2780             optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName()))
2781                     .findAny();
2782             if (!optional.isPresent()) {
2783                 log.debug("Failed to find input {} ", getInputIndex.getInputName());
2784                 // @@TODO error message
2785                 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2786             }
2787             InputDefinition inputIndex = optional.get();
2788             getInputIndex.setInputId(inputIndex.getUniqueId());
2789             getInputValues.add(getInputIndex);
2790         }
2791     }
2792
2793     private void addInput(Map<String, InputDefinition> currPropertiesMap, InputDefinition prop) {
2794         String propName = prop.getName();
2795         if (!currPropertiesMap.containsKey(propName)) {
2796             currPropertiesMap.put(propName, prop);
2797         }
2798     }
2799
2800     private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
2801                                                  Resource resource, Resource originResource, ComponentInstance currentCompInstance,
2802                                                  Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) {
2803
2804         Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
2805         Map<String, PropertyDefinition> currPropertiesMap = new HashMap<>();
2806
2807         List<PropertyDefinition> listFromMap = originResource.getProperties();
2808         if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) {
2809             log.debug("failed to find properties ");
2810             return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
2811         }
2812         if (listFromMap == null || listFromMap.isEmpty()) {
2813             return componentsUtils.getResponseFormat(ActionStatus.OK);
2814         }
2815         for (PropertyDefinition prop : listFromMap) {
2816             String propName = prop.getName();
2817             if (!currPropertiesMap.containsKey(propName)) {
2818                 currPropertiesMap.put(propName, prop);
2819             }
2820         }
2821         List<ComponentInstanceProperty> instPropList = new ArrayList<>();
2822         if (propMap != null && propMap.size() > 0) {
2823             for (List<UploadPropInfo> propertyList : propMap.values()) {
2824
2825                 UploadPropInfo propertyInfo = propertyList.get(0);
2826                 String propName = propertyInfo.getName();
2827                 if (!currPropertiesMap.containsKey(propName)) {
2828                     log.debug("failed to find property {} ", propName);
2829                     return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
2830                             propName);
2831                 }
2832                 PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
2833                 ComponentInstanceProperty property = null;
2834
2835                 String value = null;
2836                 List<GetInputValueDataDefinition> getInputs = null;
2837                 boolean isValidate = true;
2838                 if (propertyInfo.getValue() != null) {
2839                     getInputs = propertyInfo.getGet_input();
2840                     isValidate = getInputs == null || getInputs.isEmpty();
2841                     if (isValidate) {
2842                         value = getPropertyJsonStringValue(propertyInfo.getValue(),
2843                                 curPropertyDef.getType());
2844                     } else {
2845                         value = getPropertyJsonStringValue(propertyInfo.getValue(),
2846                                 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
2847                     }
2848                 }
2849                 String innerType = null;
2850                 property = new ComponentInstanceProperty(curPropertyDef, value, null);
2851
2852                 String validatePropValue = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes);
2853                 property.setValue(validatePropValue);
2854
2855                 if (getInputs != null && !getInputs.isEmpty()) {
2856                     List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
2857                     for (GetInputValueDataDefinition getInput : getInputs) {
2858                         List<InputDefinition> inputs = resource.getInputs();
2859                         if (inputs == null || inputs.isEmpty()) {
2860                             log.debug("Failed to add property {} to instance. Inputs list is empty ", property);
2861                             rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
2862                                     .stream()
2863                                     .map(GetInputValueDataDefinition::getInputName)
2864                                     .collect(toList()).toString());
2865                         }
2866                         InputDefinition input = findInputByName(inputs, getInput);
2867                         getInput.setInputId(input.getUniqueId());
2868                         getInputValues.add(getInput);
2869
2870                         GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
2871                         if (getInputIndex != null) {
2872                             input = findInputByName(inputs, getInputIndex);
2873                             getInputIndex.setInputId(input.getUniqueId());
2874                             getInputValues.add(getInputIndex);
2875
2876                         }
2877
2878                     }
2879                     property.setGetInputValues(getInputValues);
2880                 }
2881                 instPropList.add(property);
2882                 // delete overriden property
2883                 currPropertiesMap.remove(property.getName());
2884             }
2885         }
2886         // add rest of properties
2887         if (!currPropertiesMap.isEmpty()) {
2888             for (PropertyDefinition value : currPropertiesMap.values()) {
2889                 instPropList.add(new ComponentInstanceProperty(value));
2890             }
2891         }
2892         instProperties.put(currentCompInstance.getUniqueId(), instPropList);
2893         return componentsUtils.getResponseFormat(ActionStatus.OK);
2894     }
2895
2896     // US740820 Relate RIs according to capability name
2897     private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq,
2898                                                                      ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
2899         if (null == uploadReqInfo.getCapabilityName()
2900                 || validReq.getCapability().equals(uploadReqInfo.getCapabilityName())) {// get
2901             // by
2902             // capability
2903             // type
2904             return findAvailableCapability(validReq, currentCapCompInstance);
2905         }
2906         return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo);
2907     }
2908
2909     private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq,
2910                                                          ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
2911         CapabilityDefinition cap = null;
2912         Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
2913         if (!capMap.containsKey(validReq.getCapability())) {
2914             return null;
2915         }
2916         Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability()).stream()
2917                 .filter(p -> p.getName().equals(uploadReqInfo.getCapabilityName())).findAny();
2918         if (!capByName.isPresent()) {
2919             return null;
2920         }
2921         cap = capByName.get();
2922
2923         if (isBoundedByOccurrences(cap)) {
2924             String leftOccurrences = cap.getLeftOccurrences();
2925             int left = Integer.parseInt(leftOccurrences);
2926             if (left > 0) {
2927                 --left;
2928                 cap.setLeftOccurrences(String.valueOf(left));
2929
2930             }
2931
2932         }
2933         return cap;
2934     }
2935
2936     private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance instance) {
2937         Map<String, List<CapabilityDefinition>> capMap = instance.getCapabilities();
2938         if (capMap.containsKey(validReq.getCapability())) {
2939             List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
2940
2941             for (CapabilityDefinition cap : capList) {
2942                 if (isBoundedByOccurrences(cap)) {
2943                     String leftOccurrences = cap.getLeftOccurrences() != null ?
2944                             cap.getLeftOccurrences() : cap.getMaxOccurrences();
2945                     int left = Integer.parseInt(leftOccurrences);
2946                     if (left > 0) {
2947                         --left;
2948                         cap.setLeftOccurrences(String.valueOf(left));
2949                         return cap;
2950                     }
2951                 } else {
2952                     return cap;
2953                 }
2954             }
2955         }
2956         return null;
2957     }
2958
2959     private boolean isBoundedByOccurrences(CapabilityDefinition cap) {
2960         return cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES);
2961     }
2962
2963     private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName,
2964                                                                                 UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance,
2965                                                                                 String capName) {
2966         Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
2967         List<RequirementDefinition> list = comInstRegDefMap.get(capName);
2968         RequirementDefinition validRegDef = null;
2969         if (list == null) {
2970             for (Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
2971                 for (RequirementDefinition reqDef : entry.getValue()) {
2972                     if (reqDef.getName().equals(regName)) {
2973                         if (reqDef.getMaxOccurrences() != null
2974                                 && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
2975                             String leftOccurrences = reqDef.getLeftOccurrences();
2976                             if (leftOccurrences == null) {
2977                                 leftOccurrences = reqDef.getMaxOccurrences();
2978                             }
2979                             int left = Integer.parseInt(leftOccurrences);
2980                             if (left > 0) {
2981                                 --left;
2982                                 reqDef.setLeftOccurrences(String.valueOf(left));
2983                                 validRegDef = reqDef;
2984                                 break;
2985                             } else {
2986                                 continue;
2987                             }
2988                         } else {
2989                             validRegDef = reqDef;
2990                             break;
2991                         }
2992
2993                     }
2994                 }
2995                 if (validRegDef != null) {
2996                     break;
2997                 }
2998             }
2999         } else {
3000             for (RequirementDefinition reqDef : list) {
3001                 if (reqDef.getName().equals(regName)) {
3002                     if (reqDef.getMaxOccurrences() != null
3003                             && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
3004                         String leftOccurrences = reqDef.getLeftOccurrences();
3005                         if (leftOccurrences == null) {
3006                             leftOccurrences = reqDef.getMaxOccurrences();
3007                         }
3008                         int left = Integer.parseInt(leftOccurrences);
3009                         if (left > 0) {
3010                             --left;
3011                             reqDef.setLeftOccurrences(String.valueOf(left));
3012                             validRegDef = reqDef;
3013                             break;
3014                         } else {
3015                             continue;
3016                         }
3017                     } else {
3018                         validRegDef = reqDef;
3019                         break;
3020                     }
3021                 }
3022             }
3023         }
3024         if (validRegDef == null) {
3025             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
3026                     yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3027             return Either.right(responseFormat);
3028         }
3029         return Either.left(validRegDef);
3030     }
3031
3032     private Resource createResourceInstances(String yamlName, Resource resource,
3033                                              Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
3034                                              Map<String, Resource> nodeNamespaceMap) {
3035
3036         Either<Resource, ResponseFormat> eitherResource = null;
3037         log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
3038         if (isEmpty(uploadResInstancesMap) && resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
3039             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
3040             throw new ByResponseFormatComponentException(responseFormat);
3041         }
3042         Map<String, Resource> existingNodeTypeMap = new HashMap<>();
3043         if (MapUtils.isNotEmpty(nodeNamespaceMap)) {
3044             nodeNamespaceMap.forEach((k, v) -> existingNodeTypeMap.put(v.getToscaResourceName(), v));
3045         }
3046         Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
3047         uploadResInstancesMap
3048                 .values()
3049                 .forEach(i->createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap, existingNodeTypeMap, resourcesInstancesMap));
3050
3051         if (isNotEmpty(resourcesInstancesMap)) {
3052             StorageOperationStatus status = toscaOperationFacade.associateComponentInstancesToComponent(resource,
3053                     resourcesInstancesMap, false);
3054             if (status != null && status != StorageOperationStatus.OK) {
3055                 log.debug("Failed to add component instances to container component {}", resource.getName());
3056                 ResponseFormat responseFormat = componentsUtils
3057                         .getResponseFormat(componentsUtils.convertFromStorageResponse(status));
3058                 eitherResource = Either.right(responseFormat);
3059                 throw new ByResponseFormatComponentException(eitherResource.right().value());
3060             }
3061         }
3062         log.debug("*************Going to get resource {}", resource.getUniqueId());
3063         Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
3064                 .getToscaElement(resource.getUniqueId(), getComponentWithInstancesFilter());
3065         log.debug("*************finished to get resource {}", resource.getUniqueId());
3066         if (eitherGetResource.isRight()) {
3067             ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
3068                     componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
3069             throw new ByResponseFormatComponentException(responseFormat);
3070         }
3071         if (CollectionUtils.isEmpty(eitherGetResource.left().value().getComponentInstances()) &&
3072                 resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
3073             log.debug("Error when create resource instance from csar. ComponentInstances list empty");
3074             BeEcompErrorManager.getInstance().logBeDaoSystemError(
3075                     "Error when create resource instance from csar. ComponentInstances list empty");
3076             throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
3077         }
3078         return eitherGetResource.left().value();
3079     }
3080
3081     private void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName,
3082                                               Resource resource, Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingnodeTypeMap, Map<ComponentInstance, Resource> resourcesInstancesMap) {
3083         Either<Resource, ResponseFormat> eitherResource;
3084         log.debug("*************Going to create  resource instances {}", yamlName);
3085         // updating type if the type is node type name - we need to take the
3086         // updated name
3087         log.debug("*************Going to create  resource instances {}", uploadComponentInstanceInfo.getName());
3088         if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
3089             uploadComponentInstanceInfo
3090                     .setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
3091         }
3092         Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo,
3093                 existingnodeTypeMap);
3094
3095         ComponentInstance componentInstance = new ComponentInstance();
3096         componentInstance.setComponentUid(refResource.getUniqueId());
3097
3098         Collection<String> directives = uploadComponentInstanceInfo.getDirectives();
3099         if(directives != null && !directives.isEmpty()) {
3100             componentInstance.setDirectives(new ArrayList<>(directives));
3101         }
3102         UploadNodeFilterInfo uploadNodeFilterInfo = uploadComponentInstanceInfo.getUploadNodeFilterInfo();
3103         if (uploadNodeFilterInfo != null){
3104             componentInstance.setNodeFilter(new CINodeFilterUtils().getNodeFilterDataDefinition(uploadNodeFilterInfo,
3105                     componentInstance.getUniqueId()));
3106         }
3107
3108         ComponentTypeEnum containerComponentType = resource.getComponentType();
3109         NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
3110         if (containerNodeType.equals(NodeTypeEnum.Resource)
3111                 && isNotEmpty(uploadComponentInstanceInfo.getCapabilities())
3112                 && isNotEmpty(refResource.getCapabilities())) {
3113             setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
3114             Map<String, List<CapabilityDefinition>> validComponentInstanceCapabilities = getValidComponentInstanceCapabilities(
3115                     refResource.getUniqueId(), refResource.getCapabilities(),
3116                     uploadComponentInstanceInfo.getCapabilities());
3117             componentInstance.setCapabilities(validComponentInstanceCapabilities);
3118         }
3119         if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
3120             log.debug(
3121                     "createResourceInstances - not found lates version for resource instance with name {} and type ",
3122                     uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3123             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
3124                     yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3125             throw new ByResponseFormatComponentException(responseFormat);
3126         }
3127         Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
3128         componentInstance.setName(uploadComponentInstanceInfo.getName());
3129         componentInstance.setIcon(origResource.getIcon());
3130         resourcesInstancesMap.put(componentInstance, origResource);
3131     }
3132
3133     private ComponentParametersView getComponentWithInstancesFilter() {
3134         ComponentParametersView parametersView = new ComponentParametersView();
3135         parametersView.disableAll();
3136         parametersView.setIgnoreComponentInstances(false);
3137         parametersView.setIgnoreInputs(false);
3138         // inputs are read when creating
3139         // property values on instances
3140         parametersView.setIgnoreUsers(false);
3141         return parametersView;
3142     }
3143
3144     private void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities,
3145                                          Map<String, List<UploadCapInfo>> uploadedCapabilities) {
3146         for (Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()) {
3147             if (originCapabilities.containsKey(currEntry.getKey())) {
3148                 currEntry.getValue().stream().forEach(cap -> cap.setType(currEntry.getKey()));
3149             }
3150         }
3151         for (Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()) {
3152             capabilities.getValue().stream().forEach(cap -> {
3153                 if (uploadedCapabilities.containsKey(cap.getName())) {
3154                     uploadedCapabilities.get(cap.getName()).stream().forEach(c -> {
3155                         c.setName(cap.getName());
3156                         c.setType(cap.getType());
3157                     });
3158                 }
3159             });
3160         }
3161
3162     }
3163
3164     private Resource validateResourceInstanceBeforeCreate(String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo,
3165                                                           Map<String, Resource> nodeNamespaceMap) {
3166
3167         log.debug("validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type before create",
3168                 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3169         Resource refResource;
3170         if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
3171             refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType());
3172         } else {
3173             Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade
3174                     .getLatestCertifiedNodeTypeByToscaResourceName(uploadComponentInstanceInfo.getType());
3175             if (findResourceEither.isRight()) {
3176                 log.debug(
3177                         "validateResourceInstanceBeforeCreate - not found lates version for resource instance with name {} and type ",
3178                         uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3179                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
3180                         componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
3181                 throw new ByResponseFormatComponentException(responseFormat);
3182             }
3183             refResource = findResourceEither.left().value();
3184             nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
3185         }
3186         String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState();
3187         if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
3188             log.debug(
3189                     "validateResourceInstanceBeforeCreate - component instance of component {} can not be created because the component is in an illegal state {}.",
3190                     refResource.getName(), componentState);
3191             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE,
3192                     refResource.getComponentType().getValue(), refResource.getName(), componentState);
3193             throw new ByResponseFormatComponentException(responseFormat);
3194         }
3195
3196         if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) {
3197             log.debug("validateResourceInstanceBeforeCreate -  ref resource type is  ", refResource.getResourceType());
3198             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
3199                     yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3200             throw new ByResponseFormatComponentException(responseFormat);
3201         }
3202         return refResource;
3203     }
3204
3205
3206     public Either<Resource, ResponseFormat> propagateStateToCertified(User user, Resource resource,
3207                                                                       LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock,
3208                                                                       boolean forceCertificationAllowed) {
3209
3210         Either<Resource, ResponseFormat> result = null;
3211         try {
3212             if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed
3213                     && lifecycleBusinessLogic.isFirstCertification(resource.getVersion())) {
3214                 result = nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
3215                 if (result.isRight()) {
3216                     return result;
3217                 }
3218                 resource = result.left().value();
3219             }
3220             if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
3221                 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherPopulated = populateToscaArtifacts(
3222                         resource, user, false, inTransaction, needLock);
3223                 result = eitherPopulated.isLeft() ? Either.left(resource)
3224                         : Either.right(eitherPopulated.right().value());
3225                 return result;
3226             }
3227             return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
3228         } catch (Exception e) {
3229             log.debug("The exception has occurred upon certification of resource {}. ", resource.getName(), e);
3230             return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
3231         } finally {
3232             if (result == null || result.isRight()) {
3233                 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
3234                 if (!inTransaction) {
3235                     janusGraphDao.rollback();
3236                 }
3237             } else if (!inTransaction) {
3238                 janusGraphDao.commit();
3239             }
3240         }
3241     }
3242
3243     private Either<Resource, ResponseFormat> nodeFullCertification(String uniqueId, User user,
3244                                                                    LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
3245         return lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY,
3246                 lifecycleChangeInfo, inTransaction, needLock);
3247     }
3248
3249     private Either<Resource, ResponseFormat> nodeForceCertification(Resource resource, User user,
3250                                                                     LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
3251         return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction,
3252                 needLock);
3253     }
3254
3255     public ImmutablePair<Resource, ActionStatus> createOrUpdateResourceByImport(
3256             Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock,
3257             CsarInfo csarInfo, String nodeName, boolean isNested) {
3258
3259         ImmutablePair<Resource, ActionStatus> result = null;
3260         // check if resource already exists (search by tosca name = type)
3261         boolean isNestedResource = isNestedResourceUpdate(csarInfo, nodeName);
3262         Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade
3263                 .getLatestByToscaResourceName(resource.getToscaResourceName());
3264
3265         if (latestByToscaName.isLeft()) {
3266             Resource foundResource = latestByToscaName.left().value();
3267             // we don't allow updating names of top level types
3268             if (!isNestedResource &&
3269                     !StringUtils.equals(resource.getName(), foundResource.getName())) {
3270                 BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import",
3271                         ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
3272                 log.debug("resource already exist new name={} old name={} same type={}", resource.getName(),
3273                         foundResource.getName(), resource.getToscaResourceName());
3274                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
3275                 componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
3276                 throwComponentException(responseFormat);
3277             }
3278             result = updateExistingResourceByImport(resource, foundResource, user, isNormative, needLock, isNested);
3279         } else if (isNotFound(latestByToscaName)) {
3280             if (isNestedResource) {
3281                 result = createOrUpdateNestedResource(resource, user, isNormative, isInTransaction, needLock, csarInfo, isNested, nodeName);
3282             } else {
3283                 result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3284             }
3285         } else {
3286             StorageOperationStatus status = latestByToscaName.right().value();
3287             log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
3288             ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
3289                     componentsUtils.convertFromStorageResponse(latestByToscaName.right().value()), resource);
3290             componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
3291             throwComponentException(responseFormat);
3292         }
3293         return result;
3294     }
3295
3296     private boolean isNestedResourceUpdate(CsarInfo csarInfo, String nodeName) {
3297         return csarInfo != null && csarInfo.isUpdate() && nodeName != null;
3298     }
3299
3300     private ImmutablePair<Resource, ActionStatus> createOrUpdateNestedResource(Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock, CsarInfo csarInfo, boolean isNested, String nodeName) {
3301         Either<Component, StorageOperationStatus> latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(buildNestedToscaResourceName(
3302                 resource.getResourceType().name(), csarInfo.getVfResourceName(), nodeName).getRight());
3303         if (latestByToscaName.isLeft()) {
3304             Resource nestedResource = (Resource) latestByToscaName.left().value();
3305             log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
3306             Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(nestedResource, resource,
3307                     ValidationUtils.hasBeenCertified(nestedResource.getVersion()));
3308             if (eitherValidation.isRight()) {
3309                 return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3310             }
3311             return updateExistingResourceByImport(resource, nestedResource, user, isNormative, needLock, isNested);
3312         } else {
3313             return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3314         }
3315     }
3316
3317     private boolean isNotFound(Either<Resource, StorageOperationStatus> getResourceEither) {
3318         return getResourceEither.isRight() && getResourceEither.right().value() == StorageOperationStatus.NOT_FOUND;
3319     }
3320
3321     private ImmutablePair<Resource, ActionStatus> createResourceByImport(Resource resource,
3322                                                                          User user, boolean isNormative, boolean isInTransaction, CsarInfo csarInfo) {
3323         log.debug("resource with name {} does not exist. create new resource", resource.getName());
3324         validateResourceBeforeCreate(resource, user,
3325                 AuditingActionEnum.IMPORT_RESOURCE, isInTransaction, csarInfo);
3326         Resource createdResource = createResourceByDao(resource, user,
3327                 AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction);
3328         ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createdResource,
3329                 ActionStatus.CREATED);
3330         ASDCKpiApi.countImportResourcesKPI();
3331         return resourcePair;
3332     }
3333
3334     public boolean isResourceExist(String resourceName) {
3335         Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resourceName);
3336         return latestByName.isLeft();
3337     }
3338
3339     private ImmutablePair<Resource, ActionStatus> updateExistingResourceByImport(
3340             Resource newResource, Resource oldResource, User user, boolean inTransaction, boolean needLock,
3341             boolean isNested) {
3342         String lockedResourceId = oldResource.getUniqueId();
3343         log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId,
3344                 oldResource.getVersion(), oldResource.getLifecycleState());
3345         ImmutablePair<Resource, ActionStatus> resourcePair = null;
3346         try {
3347             lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import");
3348             oldResource = prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false);
3349             mergeOldResourceMetadataWithNew(oldResource, newResource);
3350
3351             validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested);
3352             validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), newResource, AuditingActionEnum.IMPORT_RESOURCE, inTransaction);
3353             // contact info normalization
3354             newResource.setContactId(newResource.getContactId().toLowerCase());
3355             // non-updatable fields
3356             newResource.setCreatorUserId(user.getUserId());
3357             newResource.setCreatorFullName(user.getFullName());
3358             newResource.setLastUpdaterUserId(user.getUserId());
3359             newResource.setLastUpdaterFullName(user.getFullName());
3360             newResource.setUniqueId(oldResource.getUniqueId());
3361             newResource.setVersion(oldResource.getVersion());
3362             newResource.setInvariantUUID(oldResource.getInvariantUUID());
3363             newResource.setLifecycleState(oldResource.getLifecycleState());
3364             newResource.setUUID(oldResource.getUUID());
3365             newResource.setNormalizedName(oldResource.getNormalizedName());
3366             newResource.setSystemName(oldResource.getSystemName());
3367             if (oldResource.getCsarUUID() != null) {
3368                 newResource.setCsarUUID(oldResource.getCsarUUID());
3369             }
3370             if (oldResource.getImportedToscaChecksum() != null) {
3371                 newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
3372             }
3373             newResource.setAbstract(oldResource.isAbstract());
3374
3375             if (newResource.getDerivedFrom() == null || newResource.getDerivedFrom().isEmpty()) {
3376                 newResource.setDerivedFrom(oldResource.getDerivedFrom());
3377             }
3378             if (newResource.getDerivedFromGenericType() == null || newResource.getDerivedFromGenericType().isEmpty()) {
3379                 newResource.setDerivedFromGenericType(oldResource.getDerivedFromGenericType());
3380             }
3381             if (newResource.getDerivedFromGenericVersion() == null || newResource.getDerivedFromGenericVersion().isEmpty()) {
3382                 newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion());
3383             }
3384             // add for new)
3385             // created without tosca artifacts - add the placeholders
3386             if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts().isEmpty()) {
3387                 setToscaArtifactsPlaceHolders(newResource, user);
3388             }
3389
3390             if (newResource.getInterfaces() == null || newResource.getInterfaces().isEmpty()) {
3391                 newResource.setInterfaces(oldResource.getInterfaces());
3392             }
3393
3394             if (CollectionUtils.isEmpty(newResource.getProperties())) {
3395                 newResource.setProperties(oldResource.getProperties());
3396             }
3397
3398             Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade
3399                     .overrideComponent(newResource, oldResource);
3400
3401             if (overrideResource.isRight()) {
3402                 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
3403                         componentsUtils.convertFromStorageResponse(overrideResource.right().value()), newResource);
3404                 componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE);
3405
3406                 throwComponentException(responseFormat);
3407             }
3408
3409             log.debug("Resource updated successfully!!!");
3410             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3411             componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
3412                     ResourceVersionInfo.newBuilder()
3413                             .state(oldResource.getLifecycleState()
3414                                     .name())
3415                             .version(oldResource.getVersion())
3416                             .build());
3417
3418             resourcePair = new ImmutablePair<>(overrideResource.left().value(),
3419                     ActionStatus.OK);
3420             return resourcePair;
3421         } finally {
3422             if (resourcePair == null) {
3423                 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
3424                 janusGraphDao.rollback();
3425             } else if (!inTransaction) {
3426                 janusGraphDao.commit();
3427             }
3428             if (needLock) {
3429                 log.debug("unlock resource {}", lockedResourceId);
3430                 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
3431             }
3432         }
3433
3434     }
3435
3436     /**
3437      * Merge old resource with new. Keep old category and vendor name without
3438      * change
3439      *
3440      * @param oldResource
3441      * @param newResource
3442      */
3443     private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
3444
3445         // keep old category and vendor name without change
3446         // merge the rest of the resource metadata
3447         if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
3448             newResource.setTags(oldResource.getTags());
3449         }
3450
3451         if (newResource.getDescription() == null) {
3452             newResource.setDescription(oldResource.getDescription());
3453         }
3454
3455         if (newResource.getVendorRelease() == null) {
3456             newResource.setVendorRelease(oldResource.getVendorRelease());
3457         }
3458
3459         if (newResource.getResourceVendorModelNumber() == null) {
3460             newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber());
3461         }
3462
3463         if (newResource.getContactId() == null) {
3464             newResource.setContactId(oldResource.getContactId());
3465         }
3466
3467         newResource.setCategories(oldResource.getCategories());
3468         if (newResource.getVendorName() == null) {
3469             newResource.setVendorName(oldResource.getVendorName());
3470         }
3471     }
3472
3473     private Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user,
3474                                               boolean inTransaction, boolean needLock) {
3475
3476         if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) {
3477             // checkout
3478             return lifecycleBusinessLogic.changeState(
3479                     oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
3480                     new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock)
3481                     .left()
3482                     .on(response -> failOnChangeState(response, user, oldResource, newResource));
3483         }
3484         return oldResource;
3485     }
3486
3487     private Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) {
3488         log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(),
3489                 response.getFormattedMessage());
3490         componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
3491                 ResourceVersionInfo.newBuilder()
3492                         .state(oldResource.getLifecycleState().name())
3493                         .version(oldResource.getVersion())
3494                         .build());
3495         throw new ByResponseFormatComponentException(response);
3496     }
3497
3498     public Resource validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction, CsarInfo csarInfo) {
3499
3500         validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
3501         validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
3502         validateLifecycleTypesCreate(user, resource, actionEnum);
3503         validateResourceType(user, resource, actionEnum);
3504         resource.setCreatorUserId(user.getUserId());
3505         resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
3506         resource.setContactId(resource.getContactId().toLowerCase());
3507         if (StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) {
3508             String resourceSystemName;
3509             if (csarInfo != null && StringUtils.isNotEmpty(csarInfo.getVfResourceName())) {
3510                 resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName());
3511             } else {
3512                 resourceSystemName = resource.getSystemName();
3513             }
3514             resource.setToscaResourceName(CommonBeUtils
3515                     .generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
3516         }
3517
3518         // Generate invariant UUID - must be here and not in operation since it
3519         // should stay constant during clone
3520         // TODO
3521         String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
3522         resource.setInvariantUUID(invariantUUID);
3523
3524         return resource;
3525     }
3526
3527     private Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource,
3528                                                                  AuditingActionEnum actionEnum) {
3529         Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
3530         if (resource.getResourceType() == null) {
3531             log.debug("Invalid resource type for resource");
3532             ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3533             eitherResult = Either.right(errorResponse);
3534             componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
3535         }
3536         return eitherResult;
3537     }
3538
3539     private Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource,
3540                                                                          AuditingActionEnum actionEnum) {
3541         Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
3542         if (resource.getInterfaces() != null && resource.getInterfaces().size() > 0) {
3543             log.debug("validate interface lifecycle Types Exist");
3544             Iterator<InterfaceDefinition> intItr = resource.getInterfaces().values().iterator();
3545             while (intItr.hasNext() && eitherResult.isLeft()) {
3546                 InterfaceDefinition interfaceDefinition = intItr.next();
3547                 String intType = interfaceDefinition.getUniqueId();
3548                 Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation
3549                         .getInterface(intType);
3550                 if (eitherCapTypeFound.isRight()) {
3551                     if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
3552                         BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
3553                                 "Create Resource - validateLifecycleTypesCreate", "Interface", intType);
3554                         log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB",
3555                                 intType, resource.getName());
3556                         BeEcompErrorManager.getInstance()
3557                                 .logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
3558                         log.debug("request to data model failed with error: {}",
3559                                 eitherCapTypeFound.right().value().name());
3560                     }
3561
3562                     ResponseFormat errorResponse = componentsUtils
3563                             .getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
3564                     eitherResult = Either.right(errorResponse);
3565                     componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
3566                 }
3567
3568             }
3569         }
3570         return eitherResult;
3571     }
3572
3573     private Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user,
3574                                                                           ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
3575                                                                           boolean inTransaction) {
3576
3577         Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
3578         if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) {
3579             log.debug("validate capability Types Exist - capabilities section");
3580
3581             for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities().entrySet()) {
3582
3583                 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum,
3584                         eitherResult, typeEntry, inTransaction);
3585                 if (eitherResult.isRight()) {
3586                     return Either.right(eitherResult.right().value());
3587                 }
3588             }
3589         }
3590
3591         if (resource.getRequirements() != null && resource.getRequirements().size() > 0) {
3592             log.debug("validate capability Types Exist - requirements section");
3593             for (String type : resource.getRequirements().keySet()) {
3594                 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource,
3595                         resource.getRequirements().get(type), actionEnum, eitherResult, type, inTransaction);
3596                 if (eitherResult.isRight()) {
3597                     return Either.right(eitherResult.right().value());
3598                 }
3599             }
3600         }
3601
3602         return eitherResult;
3603     }
3604
3605     // @param typeObject- the object to which the validation is done
3606     private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
3607                                                                          ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List<?> validationObjects,
3608                                                                          AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type,
3609                                                                          boolean inTransaction) {
3610         Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
3611                 .getCapabilityType(type, inTransaction);
3612         if (eitherCapTypeFound.isRight()) {
3613             if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
3614                 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
3615                         CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", type);
3616                 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type,
3617                         resource.getName());
3618                 BeEcompErrorManager.getInstance()
3619                         .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
3620             }
3621             log.debug("Trying to get capability type {} failed with error: {}", type,
3622                     eitherCapTypeFound.right().value().name());
3623             ResponseFormat errorResponse = null;
3624             if (type != null) {
3625                 errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
3626             } else {
3627                 errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE,
3628                         validationObjects);
3629             }
3630             eitherResult = Either.right(errorResponse);
3631             componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
3632         }
3633         return eitherResult;
3634     }
3635
3636     private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
3637                                                                          ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
3638                                                                          Either<Boolean, ResponseFormat> eitherResult, Entry<String, List<CapabilityDefinition>> typeEntry,
3639                                                                          boolean inTransaction) {
3640         Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
3641                 .getCapabilityType(typeEntry.getKey(), inTransaction);
3642         if (eitherCapTypeFound.isRight()) {
3643             if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
3644                 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
3645                         CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", typeEntry.getKey());
3646                 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB",
3647                         typeEntry.getKey(), resource.getName());
3648                 BeEcompErrorManager.getInstance()
3649                         .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
3650             }
3651             log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(),
3652                     eitherCapTypeFound.right().value().name());
3653             ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE,
3654                     typeEntry.getKey());
3655             eitherResult = Either.right(errorResponse);
3656             componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
3657         }
3658         CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
3659         if (capabilityTypeDefinition.getProperties() != null) {
3660             for (CapabilityDefinition capDef : typeEntry.getValue()) {
3661                 List<ComponentInstanceProperty> properties = capDef.getProperties();
3662                 if (properties == null || properties.isEmpty()) {
3663                     properties = new ArrayList<>();
3664                     for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
3665                         ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
3666                         properties.add(newProp);
3667                     }
3668                 } else {
3669                     for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
3670                         PropertyDefinition porpFromDef = prop.getValue();
3671                         List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
3672                         for (ComponentInstanceProperty cip : properties) {
3673                             if (!cip.getName().equals(porpFromDef.getName())) {
3674                                 ComponentInstanceProperty newProp = new ComponentInstanceProperty(porpFromDef);
3675                                 propsToAdd.add(newProp);
3676                             }
3677                         }
3678                         if (!propsToAdd.isEmpty()) {
3679                             properties.addAll(propsToAdd);
3680                         }
3681                     }
3682                 }
3683                 capDef.setProperties(properties);
3684             }
3685         }
3686         return eitherResult;
3687     }
3688
3689     public Resource createResourceByDao(Resource resource, User user,
3690                                         AuditingActionEnum actionEnum, boolean isNormative, boolean inTransaction) {
3691         // create resource
3692
3693         // lock new resource name in order to avoid creation resource with same
3694         // name
3695         Resource createdResource = null;
3696         if (!inTransaction) {
3697             Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
3698                     CREATE_RESOURCE);
3699             if (lockResult.isRight()) {
3700                 ResponseFormat responseFormat = lockResult.right().value();
3701                 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
3702                 throw new ByResponseFormatComponentException(responseFormat);
3703             }
3704
3705             log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
3706         }
3707         try {
3708             if (resource.deriveFromGeneric()) {
3709                 handleResourceGenericType(resource);
3710             }
3711            createdResource = createResourceTransaction(resource, user, isNormative
3712            );
3713             componentsUtils.auditResource(componentsUtils.getResponseFormat(ActionStatus.CREATED), user,
3714                     createdResource, actionEnum);
3715             ASDCKpiApi.countCreatedResourcesKPI();
3716         } catch(ByActionStatusComponentException e) {
3717             ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
3718             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
3719             throw e;
3720         } catch(ByResponseFormatComponentException e) {
3721             ResponseFormat responseFormat = e.getResponseFormat();
3722             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
3723             throw e;
3724         } catch (StorageException e){
3725             ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
3726             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
3727             throw e;
3728         }
3729         finally {
3730             if (!inTransaction) {
3731                 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
3732                         NodeTypeEnum.Resource);
3733             }
3734         }
3735         return createdResource;
3736     }
3737
3738     private Resource createResourceTransaction(Resource resource, User user,
3739                                                boolean isNormative) {
3740         // validate resource name uniqueness
3741         log.debug("validate resource name");
3742         Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(
3743                 resource.getName(), resource.getResourceType(), resource.getComponentType());
3744         if (eitherValidation.isRight()) {
3745             log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(),
3746                     eitherValidation.right().value());
3747             ResponseFormat errorResponse = componentsUtils
3748                     .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
3749             throw new ByResponseFormatComponentException(errorResponse);
3750         }
3751         if (eitherValidation.left().value()) {
3752             log.debug("resource with name: {}, already exists", resource.getName());
3753             ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
3754                     ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
3755             throw new ByResponseFormatComponentException(errorResponse);
3756         }
3757
3758         log.debug("send resource {} to dao for create", resource.getName());
3759
3760         createArtifactsPlaceHolderData(resource, user);
3761         // enrich object
3762         if (!isNormative) {
3763             log.debug("enrich resource with creator, version and state");
3764             resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
3765             resource.setVersion(INITIAL_VERSION);
3766             resource.setHighestVersion(true);
3767             if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC) {
3768                 resource.setAbstract(false);
3769             }
3770         }
3771         return toscaOperationFacade.createToscaComponent(resource)
3772                 .left()
3773                 .on(r->throwComponentExceptionByResource(r, resource));
3774     }
3775
3776     private Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) {
3777         ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
3778                 componentsUtils.convertFromStorageResponse(status), resource);
3779         throw new ByResponseFormatComponentException(responseFormat);
3780     }
3781
3782     private void createArtifactsPlaceHolderData(Resource resource, User user) {
3783         // create mandatory artifacts
3784
3785         // TODO it must be removed after that artifact uniqueId creation will be
3786         // moved to ArtifactOperation
3787
3788         setInformationalArtifactsPlaceHolder(resource, user);
3789         setDeploymentArtifactsPlaceHolder(resource, user);
3790         setToscaArtifactsPlaceHolders(resource, user);
3791     }
3792
3793     @SuppressWarnings("unchecked")
3794     @Override
3795     public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
3796         Resource resource = (Resource) component;
3797         Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
3798         if (artifactMap == null) {
3799             artifactMap = new HashMap<>();
3800         }
3801         Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
3802                 .getConfiguration().getDeploymentResourceArtifacts();
3803         if (deploymentResourceArtifacts != null) {
3804             Map<String, ArtifactDefinition> finalArtifactMap = artifactMap;
3805             deploymentResourceArtifacts.forEach((k, v)->processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k,v));
3806         }
3807         resource.setDeploymentArtifacts(artifactMap);
3808     }
3809
3810     private void processDeploymentResourceArtifacts(User user, Resource resource, Map<String, ArtifactDefinition> artifactMap, String k, Object v) {
3811         boolean shouldCreateArtifact = true;
3812         Map<String, Object> artifactDetails = (Map<String, Object>) v;
3813         Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
3814         if (object != null) {
3815             List<String> artifactTypes = (List<String>) object;
3816             if (!artifactTypes.contains(resource.getResourceType().name())) {
3817                 shouldCreateArtifact = false;
3818                 return;
3819             }
3820         } else {
3821             log.info("resource types for artifact placeholder {} were not defined. default is all resources",
3822                     k);
3823         }
3824         if (shouldCreateArtifact) {
3825             if (artifactsBusinessLogic != null) {
3826                 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
3827                         resource.getUniqueId(), k, (Map<String, Object>) v,
3828                         user, ArtifactGroupTypeEnum.DEPLOYMENT);
3829                 if (artifactDefinition != null
3830                         && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
3831                     artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
3832                 }
3833             }
3834         }
3835     }
3836
3837     @SuppressWarnings("unchecked")
3838     private void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
3839         Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
3840         if (artifactMap == null) {
3841             artifactMap = new HashMap<>();
3842         }
3843         String resourceUniqueId = resource.getUniqueId();
3844         List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration()
3845                 .getExcludeResourceCategory();
3846         List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration()
3847                 .getExcludeResourceType();
3848         Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager()
3849                 .getConfiguration().getInformationalResourceArtifacts();
3850         List<CategoryDefinition> categories = resource.getCategories();
3851         boolean isCreateArtifact = true;
3852         if (exludeResourceCategory != null) {
3853             String category = categories.get(0).getName();
3854             isCreateArtifact = exludeResourceCategory.stream().noneMatch(e->e.equalsIgnoreCase(category));
3855         }
3856         if (isCreateArtifact && exludeResourceType != null) {
3857             String resourceType = resource.getResourceType().name();
3858             isCreateArtifact = exludeResourceType.stream().noneMatch(e->e.equalsIgnoreCase(resourceType));
3859         }
3860         if (informationalResourceArtifacts != null && isCreateArtifact) {
3861             Set<String> keys = informationalResourceArtifacts.keySet();
3862             for (String informationalResourceArtifactName : keys) {
3863                 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts
3864                         .get(informationalResourceArtifactName);
3865                 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
3866                         resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
3867                         ArtifactGroupTypeEnum.INFORMATIONAL);
3868                 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
3869
3870             }
3871         }
3872         resource.setArtifacts(artifactMap);
3873     }
3874
3875     /**
3876      * deleteResource
3877      *
3878      * @param resourceId
3879      * @param user
3880      * @return
3881      */
3882     public ResponseFormat deleteResource(String resourceId, User user) {
3883         ResponseFormat responseFormat;
3884         validateUserExists(user, DELETE_RESOURCE, false);
3885
3886         Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId);
3887         if (resourceStatus.isRight()) {
3888             log.debug("failed to get resource {}", resourceId);
3889             return componentsUtils
3890                     .getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), "");
3891         }
3892
3893         Resource resource = resourceStatus.left().value();
3894
3895         StorageOperationStatus result = StorageOperationStatus.OK;
3896         Either<Boolean, ResponseFormat> lockResult = lockComponent(resourceId, resource, "Mark resource to delete");
3897         if (lockResult.isRight()) {
3898             return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3899         }
3900
3901         try {
3902
3903             result = markComponentToDelete(resource);
3904             if (result.equals(StorageOperationStatus.OK)) {
3905                 responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
3906             } else {
3907                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
3908                 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
3909             }
3910             return responseFormat;
3911
3912         } finally {
3913             if (result == null || !result.equals(StorageOperationStatus.OK)) {
3914                 janusGraphDao.rollback();
3915             } else {
3916                 janusGraphDao.commit();
3917             }
3918             graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
3919         }
3920
3921     }
3922
3923     public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) {
3924         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
3925         validateUserExists(user, DELETE_RESOURCE, false);
3926         Resource resource = null;
3927         StorageOperationStatus result = StorageOperationStatus.OK;
3928         try {
3929
3930             Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade
3931                     .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version);
3932             if (resourceStatus.isRight()) {
3933                 log.debug("failed to get resource {} version {}", resourceName, version);
3934                 return componentsUtils.getResponseFormatByResource(
3935                         componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), resourceName);
3936             }
3937
3938             resource = resourceStatus.left().value();
3939
3940         } finally {
3941             if (result == null || !result.equals(StorageOperationStatus.OK)) {
3942                 janusGraphDao.rollback();
3943                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
3944                 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resourceName);
3945             } else {
3946                 janusGraphDao.commit();
3947             }
3948         }
3949         if (resource != null) {
3950             Either<Boolean, ResponseFormat> lockResult = lockComponent(resource.getUniqueId(), resource,
3951                     DELETE_RESOURCE);
3952             if (lockResult.isRight()) {
3953                 result = StorageOperationStatus.GENERAL_ERROR;
3954                 return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3955             }
3956             try {
3957                 result = markComponentToDelete(resource);
3958                 if (!result.equals(StorageOperationStatus.OK)) {
3959                     ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
3960                     responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
3961                     return responseFormat;
3962                 }
3963
3964             } finally {
3965                 if (result == null || !result.equals(StorageOperationStatus.OK)) {
3966                     janusGraphDao.rollback();
3967                 } else {
3968                     janusGraphDao.commit();
3969                 }
3970                 graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource);
3971             }
3972         }
3973         return responseFormat;
3974     }
3975
3976     public Either<Resource, ResponseFormat> getResource(String resourceId, User user) {
3977
3978         if (user != null) {
3979             validateUserExists(user, CREATE_RESOURCE, false);
3980         }
3981
3982         Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId);
3983         if (storageStatus.isRight()) {
3984             log.debug("failed to get resource by id {}", resourceId);
3985             return Either.right(componentsUtils.getResponseFormatByResource(
3986                     componentsUtils.convertFromStorageResponse(storageStatus.right().value()), resourceId));
3987         }
3988         if (!(storageStatus.left().value() instanceof Resource)) {
3989             return Either.right(componentsUtils.getResponseFormatByResource(
3990                     componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId));
3991         }
3992         return Either.left(storageStatus.left().value());
3993
3994     }
3995
3996     public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion,
3997                                                                         String userId) {
3998
3999         validateUserExists(userId, "get Resource By Name And Version", false);
4000
4001         Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade
4002                 .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion);
4003         if (getResource.isRight()) {
4004             log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion);
4005             return Either.right(componentsUtils.getResponseFormatByResource(
4006                     componentsUtils.convertFromStorageResponse(getResource.right().value()), resourceName));
4007         }
4008         return Either.left(getResource.left().value());
4009     }
4010
4011     /**
4012      * updateResourceMetadata
4013      *
4014      * @param user               - modifier data (userId)
4015      * @param inTransaction      TODO
4016      * @param resourceIdToUpdate - the resource identifier
4017      * @param newResource
4018      * @return Either<Resource ,   responseFormat>
4019      */
4020     public Resource updateResourceMetadata(String resourceIdToUpdate, Resource newResource,
4021                                            Resource currentResource, User user, boolean inTransaction) {
4022
4023         validateUserExists(user.getUserId(), "update Resource Metadata", false);
4024
4025         log.debug("Get resource with id {}", resourceIdToUpdate);
4026         boolean needToUnlock = false;
4027         boolean rollbackNeeded = true;
4028
4029         try {
4030             if (currentResource == null) {
4031                 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade
4032                         .getToscaElement(resourceIdToUpdate);
4033                 if (storageStatus.isRight()) {
4034                     throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatByResource(
4035                             componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
4036                 }
4037
4038                 currentResource = storageStatus.left().value();
4039             }
4040             // verify that resource is checked-out and the user is the last
4041             // updater
4042             if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) {
4043                 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
4044             }
4045
4046             // lock resource
4047             StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate,
4048                     NodeTypeEnum.Resource);
4049             if (!lockResult.equals(StorageOperationStatus.OK)) {
4050                 BeEcompErrorManager.getInstance().logBeFailedLockObjectError("Upload Artifact - lock ",
4051                         NodeTypeEnum.Resource.getName(), resourceIdToUpdate);
4052                 log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult);
4053                 ResponseFormat responseFormat = componentsUtils
4054                         .getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
4055                 throw new ByResponseFormatComponentException(responseFormat);
4056             }
4057
4058             needToUnlock = true;
4059
4060             // critical section starts here
4061             // convert json to object
4062
4063             // Update and updated resource must have a non-empty "derivedFrom"
4064             // list
4065             // This code is not called from import resources, because of root
4066             // VF "derivedFrom" should be null (or ignored)
4067             if (ModelConverter.isAtomicComponent(currentResource)) {
4068                 validateDerivedFromNotEmpty(null, newResource, null);
4069                 validateDerivedFromNotEmpty(null, currentResource, null);
4070             } else {
4071                 newResource.setDerivedFrom(null);
4072             }
4073
4074             Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource,
4075                     user, currentResource, false, true);
4076             if (dataModelResponse.isRight()) {
4077                 log.debug("failed to update resource metadata!!!");
4078                 rollbackNeeded = true;
4079                 throw new ByResponseFormatComponentException(dataModelResponse.right().value());
4080             }
4081
4082             log.debug("Resource metadata updated successfully!!!");
4083             rollbackNeeded = false;
4084             return dataModelResponse.left().value();
4085
4086         } catch (ComponentException|StorageException e){
4087             rollback(inTransaction, newResource, null, null);
4088             throw e;
4089         }
4090         finally {
4091             if (!inTransaction) {
4092                 janusGraphDao.commit();
4093             }
4094             if (needToUnlock) {
4095                 graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
4096             }
4097         }
4098     }
4099
4100     private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource,
4101                                                                     User user, Resource currentResource, boolean shouldLock, boolean inTransaction) {
4102         updateVfModuleGroupsNames(currentResource, newResource);
4103         validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction, false);
4104         // Setting last updater and uniqueId
4105         newResource.setContactId(newResource.getContactId().toLowerCase());
4106         newResource.setLastUpdaterUserId(user.getUserId());
4107         newResource.setUniqueId(resourceIdToUpdate);
4108         // Cannot set highest version through UI
4109         newResource.setHighestVersion(currentResource.isHighestVersion());
4110         newResource.setCreationDate(currentResource.getCreationDate());
4111
4112         Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource,
4113                 newResource, user.getUserId(), inTransaction);
4114
4115         if (processUpdateOfDerivedFrom.isRight()) {
4116             log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate);
4117             return Either.right(processUpdateOfDerivedFrom.right().value());
4118         }
4119
4120         log.debug("send resource {} to dao for update", newResource.getUniqueId());
4121         if (isNotEmpty(newResource.getGroups())) {
4122             for (GroupDefinition group : newResource.getGroups()) {
4123                 if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) {
4124                     groupBusinessLogic.validateAndUpdateGroupMetadata(
4125                             newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId(),
4126                             user, newResource.getComponentType(), group, true, false);
4127                 }
4128             }
4129         }
4130         Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade
4131                 .updateToscaElement(newResource);
4132
4133         if (dataModelResponse.isRight()) {
4134             ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
4135                     componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), newResource);
4136             return Either.right(responseFormat);
4137         } else if (dataModelResponse.left().value() == null) {
4138             log.debug("No response from updateResource");
4139             return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4140         }
4141         return Either.left(dataModelResponse.left().value());
4142     }
4143
4144
4145     private void updateVfModuleGroupsNames(Resource currentResource, Resource newResource) {
4146         if(currentResource.getGroups() != null && !currentResource.getName().equals(newResource.getName())){
4147             List<GroupDefinition> updatedGroups = currentResource.getGroups()
4148                     .stream()
4149                     .map(group -> getUpdatedGroup(group, currentResource.getName(), newResource.getName()))
4150                     .collect(toList());
4151             newResource.setGroups(updatedGroups);
4152         }
4153     }
4154
4155     private GroupDefinition getUpdatedGroup(GroupDefinition currGroup, String replacePattern, String with) {
4156         GroupDefinition updatedGroup = new GroupDefinition(currGroup);
4157         if(updatedGroup.isSamePrefix(replacePattern) && updatedGroup.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)){
4158             String prefix = updatedGroup.getName().substring(0, replacePattern.length());
4159             String newGroupName = updatedGroup.getName().replaceFirst(prefix, with);
4160             updatedGroup.setName(newGroupName);
4161         }
4162         return updatedGroup;
4163     }
4164     /**
4165      * validateResourceFieldsBeforeCreate
4166      *
4167      * @param user - modifier data (userId)
4168      * @return Either<Boolean   ,       ErrorResponse>
4169      */
4170     private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, Resource resource,
4171                                                                                AuditingActionEnum actionEnum, boolean inTransaction) {
4172         validateComponentFieldsBeforeCreate(user, resource, actionEnum);
4173         // validate category
4174         log.debug("validate category");
4175         validateCategory(user, resource, actionEnum, inTransaction);
4176         // validate vendor name & release & model number
4177         log.debug("validate vendor name");
4178         validateVendorName(user, resource, actionEnum);
4179         log.debug("validate vendor release");
4180         validateVendorReleaseName(user, resource, actionEnum);
4181         log.debug("validate resource vendor model number");
4182         validateResourceVendorModelNumber(user, resource, actionEnum);
4183         // validate cost
4184         log.debug("validate cost");
4185         validateCost(resource);
4186         // validate licenseType
4187         log.debug("validate licenseType");
4188         validateLicenseType(user, resource, actionEnum);
4189         // validate template (derived from)
4190         log.debug("validate derived from");
4191         if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
4192             resource.setDerivedFrom(null);
4193         }
4194         validateDerivedFromExist(user, resource, actionEnum);
4195         // warn about non-updatable fields
4196         checkComponentFieldsForOverrideAttempt(resource);
4197         String currentCreatorFullName = resource.getCreatorFullName();
4198         if (currentCreatorFullName != null) {
4199             log.debug("Resource Creator fullname is automatically set and cannot be updated");
4200         }
4201
4202         String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
4203         if (currentLastUpdaterFullName != null) {
4204             log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
4205         }
4206
4207         Long currentLastUpdateDate = resource.getLastUpdateDate();
4208         if (currentLastUpdateDate != null) {
4209             log.debug("Resource last update date is automatically set and cannot be updated");
4210         }
4211
4212         Boolean currentAbstract = resource.isAbstract();
4213         if (currentAbstract != null) {
4214             log.debug("Resource abstract is automatically set and cannot be updated");
4215         }
4216
4217         return Either.left(true);
4218     }
4219
4220     /**
4221      * validateResourceFieldsBeforeUpdate
4222      *
4223      * @param currentResource - Resource object to validate
4224      * @param isNested
4225      */
4226     private void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource,
4227                                                     boolean inTransaction, boolean isNested) {
4228         validateFields(currentResource, updateInfoResource, inTransaction, isNested);
4229         warnNonEditableFields(currentResource, updateInfoResource);
4230     }
4231
4232     private void warnNonEditableFields(Resource currentResource, Resource updateInfoResource) {
4233         String currentResourceVersion = currentResource.getVersion();
4234         String updatedResourceVersion = updateInfoResource.getVersion();
4235
4236         if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) {
4237             log.debug("Resource version is automatically set and cannot be updated");
4238         }
4239
4240         String currentCreatorUserId = currentResource.getCreatorUserId();
4241         String updatedCreatorUserId = updateInfoResource.getCreatorUserId();
4242
4243         if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) {
4244             log.debug("Resource Creator UserId is automatically set and cannot be updated");
4245         }
4246
4247         String currentCreatorFullName = currentResource.getCreatorFullName();
4248         String updatedCreatorFullName = updateInfoResource.getCreatorFullName();
4249
4250         if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) {
4251             log.debug("Resource Creator fullname is automatically set and cannot be updated");
4252         }
4253
4254         String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId();
4255         String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId();
4256
4257         if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) {
4258             log.debug("Resource LastUpdater userId is automatically set and cannot be updated");
4259         }
4260
4261         String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName();
4262         String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName();
4263
4264         if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) {
4265             log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
4266         }
4267
4268         Long currentCreationDate = currentResource.getCreationDate();
4269         Long updatedCreationDate = updateInfoResource.getCreationDate();
4270
4271         if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) {
4272             log.debug("Resource Creation date is automatically set and cannot be updated");
4273         }
4274
4275         Long currentLastUpdateDate = currentResource.getLastUpdateDate();
4276         Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate();
4277
4278         if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) {
4279             log.debug("Resource last update date is automatically set and cannot be updated");
4280         }
4281
4282         LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState();
4283         LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState();
4284
4285         if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) {
4286             log.debug("Resource lifecycle state date is automatically set and cannot be updated");
4287         }
4288
4289         Boolean currentAbstract = currentResource.isAbstract();
4290         Boolean updatedAbstract = updateInfoResource.isAbstract();
4291
4292         if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) {
4293             log.debug("Resource abstract is automatically set and cannot be updated");
4294         }
4295
4296         Boolean currentHighestVersion = currentResource.isHighestVersion();
4297         Boolean updatedHighestVersion = updateInfoResource.isHighestVersion();
4298
4299         if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) {
4300             log.debug("Resource highest version is automatically set and cannot be updated");
4301         }
4302
4303         String currentUuid = currentResource.getUUID();
4304         String updatedUuid = updateInfoResource.getUUID();
4305
4306         if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) {
4307             log.debug("Resource UUID is automatically set and cannot be updated");
4308         }
4309
4310         ResourceTypeEnum currentResourceType = currentResource.getResourceType();
4311         ResourceTypeEnum updatedResourceType = updateInfoResource.getResourceType();
4312
4313         if ((updatedResourceType != null) && (!updatedResourceType.equals(currentResourceType))) {
4314             log.debug("Resource Type  cannot be updated");
4315
4316         }
4317         updateInfoResource.setResourceType(currentResource.getResourceType());
4318
4319         String currentInvariantUuid = currentResource.getInvariantUUID();
4320         String updatedInvariantUuid = updateInfoResource.getInvariantUUID();
4321
4322         if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
4323             log.debug("Resource invariant UUID is automatically set and cannot be updated");
4324             updateInfoResource.setInvariantUUID(currentInvariantUuid);
4325         }
4326     }
4327
4328     private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) {
4329         boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
4330         log.debug("validate resource name before update");
4331         validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested);
4332         log.debug("validate description before update");
4333         validateDescriptionAndCleanup(null, updateInfoResource, null);
4334         log.debug("validate icon before update");
4335         validateIcon(currentResource, updateInfoResource, hasBeenCertified);
4336         log.debug("validate tags before update");
4337         validateTagsListAndRemoveDuplicates(null, updateInfoResource, null);
4338         log.debug("validate vendor name before update");
4339         validateVendorName(null, updateInfoResource, null);
4340         log.debug("validate resource vendor model number before update");
4341         validateResourceVendorModelNumber(currentResource, updateInfoResource);
4342         log.debug("validate vendor release before update");
4343         validateVendorReleaseName(null, updateInfoResource, null);
4344         log.debug("validate contact info before update");
4345         validateContactId(null, updateInfoResource, null);
4346         log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
4347         validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified);
4348         log.debug("validate category before update");
4349         validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction);
4350     }
4351
4352
4353     private boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) {
4354         String resourceNameUpdated = updateInfoResource.getName();
4355         String resourceNameCurrent = currentResource.getName();
4356         if (resourceNameCurrent.equals(resourceNameUpdated)) {
4357             return true;
4358         }
4359         // In case of CVFC type we should support the case of old VF with CVFC
4360         // instances that were created without the "Cvfc" suffix
4361         return currentResource.getResourceType().equals(ResourceTypeEnum.CVFC) &&
4362                 resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent));
4363     }
4364
4365     private String addCvfcSuffixToResourceName(String resourceName) {
4366         return resourceName + "Cvfc";
4367     }
4368
4369     private void validateResourceName(Resource currentResource, Resource updateInfoResource,
4370                                       boolean hasBeenCertified, boolean isNested) {
4371         String resourceNameUpdated = updateInfoResource.getName();
4372         if (!isResourceNameEquals(currentResource, updateInfoResource)) {
4373             if (isNested || !hasBeenCertified) {
4374                 validateComponentName(null, updateInfoResource, null);
4375                 validateResourceNameUniqueness(updateInfoResource);
4376                 currentResource.setName(resourceNameUpdated);
4377                 currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
4378                 currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
4379
4380             } else {
4381                 log.info("Resource name: {}, cannot be updated once the resource has been certified once.",
4382                         resourceNameUpdated);
4383                 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
4384             }
4385         }
4386     }
4387
4388     private void validateIcon(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
4389         String iconUpdated = updateInfoResource.getIcon();
4390         String iconCurrent = currentResource.getIcon();
4391         if (!iconCurrent.equals(iconUpdated)) {
4392             if (!hasBeenCertified) {
4393                 validateIcon(null, updateInfoResource, null);
4394             } else {
4395                 log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated);
4396                 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
4397             }
4398         }
4399     }
4400
4401     private void validateResourceVendorModelNumber(Resource currentResource, Resource updateInfoResource) {
4402         String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber();
4403         String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber();
4404         if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) {
4405             validateResourceVendorModelNumber(null, updateInfoResource, null);
4406         }
4407     }
4408
4409     private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource,
4410                                                              boolean hasBeenCertified, boolean inTransaction) {
4411         validateCategory(null, updateInfoResource, null, inTransaction);
4412         if (hasBeenCertified) {
4413             CategoryDefinition currentCategory = currentResource.getCategories().get(0);
4414             SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories().get(0);
4415             CategoryDefinition updateCategory = updateInfoResource.getCategories().get(0);
4416             SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories().get(0);
4417             if (!currentCategory.getName().equals(updateCategory.getName())
4418                     || !currentSubCategory.getName().equals(updtaeSubCategory.getName())) {
4419                 log.info("Category {} cannot be updated once the resource has been certified once.",
4420                         currentResource.getCategories());
4421                 ResponseFormat errorResponse = componentsUtils
4422                         .getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
4423                 return Either.right(errorResponse);
4424             }
4425         }
4426         return Either.left(true);
4427     }
4428
4429     private Either<Boolean, ResponseFormat> validateDerivedFromDuringUpdate(Resource currentResource,
4430                                                                             Resource updateInfoResource, boolean hasBeenCertified) {
4431
4432         List<String> currentDerivedFrom = currentResource.getDerivedFrom();
4433         List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
4434         if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
4435                 || updatedDerivedFrom.isEmpty()) {
4436             log.trace("Update normative types");
4437             return Either.left(true);
4438         }
4439
4440         String derivedFromCurrent = currentDerivedFrom.get(0);
4441         String derivedFromUpdated = updatedDerivedFrom.get(0);
4442
4443         if (!derivedFromCurrent.equals(derivedFromUpdated)) {
4444             if (!hasBeenCertified) {
4445                 validateDerivedFromExist(null, updateInfoResource, null);
4446             } else {
4447                 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
4448                         currentResource, updateInfoResource, null);
4449
4450                 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
4451                     log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
4452                     return validateDerivedFromExtending;
4453                 }
4454             }
4455         } else {
4456             // For derived from, we must know whether it was actually changed,
4457             // otherwise we must do no action.
4458             // Due to changes it inflicts on data model (remove artifacts,
4459             // properties...), it's not like a flat field which can be
4460             // overwritten if not changed.
4461             // So we must indicate that derived from is not changed
4462             updateInfoResource.setDerivedFrom(null);
4463         }
4464         return Either.left(true);
4465     }
4466
4467     private Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource,
4468                                                                                   Resource updateInfoResource, boolean hasBeenCertified) {
4469
4470         List<String> currentDerivedFrom = currentResource.getDerivedFrom();
4471         List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
4472         if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
4473                 || updatedDerivedFrom.isEmpty()) {
4474             log.trace("Update normative types");
4475             return Either.left(true);
4476         }
4477
4478         String derivedFromCurrent = currentDerivedFrom.get(0);
4479         String derivedFromUpdated = updatedDerivedFrom.get(0);
4480
4481         if (!derivedFromCurrent.equals(derivedFromUpdated)) {
4482             if (!hasBeenCertified) {
4483                 validateDerivedFromExist(null, updateInfoResource, null);
4484             } else {
4485                 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
4486                         currentResource, updateInfoResource, null);
4487
4488                 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
4489                     log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
4490                     return validateDerivedFromExtending;
4491                 }
4492             }
4493         }
4494         return Either.left(true);
4495     }
4496
4497     private void validateDerivedFromExist(User user, Resource resource,  AuditingActionEnum actionEnum) {
4498         if (resource.getDerivedFrom() == null || resource.getDerivedFrom().isEmpty()) {
4499             return;
4500         }
4501         String templateName = resource.getDerivedFrom().get(0);
4502         Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
4503                 .validateToscaResourceNameExists(templateName);
4504         if (dataModelResponse.isRight()) {
4505             StorageOperationStatus storageStatus = dataModelResponse.right().value();
4506             BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist");
4507             log.debug("request to data model failed with error: {}", storageStatus);
4508             ResponseFormat responseFormat = componentsUtils
4509                     .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
4510             log.trace("audit before sending response");
4511             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4512             throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus));
4513         } else if (!dataModelResponse.left().value()) {
4514             log.info("resource template with name: {}, does not exists", templateName);
4515             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
4516             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4517             throw new ByActionStatusComponentException(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
4518         }
4519     }
4520
4521     // Tal G for extending inheritance US815447
4522     private Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource,
4523                                                                          Resource updateInfoResource, AuditingActionEnum actionEnum) {
4524         String currentTemplateName = currentResource.getDerivedFrom().get(0);
4525         String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0);
4526
4527         Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
4528                 .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName);
4529         if (dataModelResponse.isRight()) {
4530             StorageOperationStatus storageStatus = dataModelResponse.right().value();
4531             BeEcompErrorManager.getInstance()
4532                     .logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
4533             ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
4534                     componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
4535             log.trace("audit before sending response");
4536             componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
4537             return Either.right(responseFormat);
4538         }
4539
4540         if (!dataModelResponse.left().value()) {
4541             log.info("resource template with name {} does not inherit as original {}", updatedTemplateName,
4542                     currentTemplateName);
4543             ResponseFormat responseFormat = componentsUtils
4544                     .getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
4545             componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
4546
4547             return Either.right(responseFormat);
4548
4549         }
4550         return Either.left(true);
4551     }
4552
4553     public void validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
4554         log.debug("validate resource derivedFrom field");
4555         if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty())
4556                 || (resource.getDerivedFrom().get(0)) == null || (resource.getDerivedFrom().get(0).trim().isEmpty())) {
4557             log.info("derived from (template) field is missing for the resource");
4558             ResponseFormat responseFormat = componentsUtils
4559                     .getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
4560             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4561
4562             throw new ByActionStatusComponentException(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
4563         }
4564     }
4565
4566     private void validateResourceNameUniqueness(Resource resource) {
4567
4568         Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade
4569                 .validateComponentNameExists(resource.getName(), resource.getResourceType(),
4570                         resource.getComponentType());
4571         if (resourceOperationResponse.isLeft() && resourceOperationResponse.left().value()) {
4572             log.debug("resource with name: {}, already exists", resource.getName());
4573             throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(),
4574                     resource.getName());
4575         } else if(resourceOperationResponse.isRight()){
4576             log.debug("error while validateResourceNameExists for resource: {}", resource.getName());
4577             throw new StorageException(resourceOperationResponse.right().value());
4578         }
4579     }
4580
4581
4582     private void validateCategory(User user, Resource resource,
4583                                   AuditingActionEnum actionEnum, boolean inTransaction) {
4584
4585         List<CategoryDefinition> categories = resource.getCategories();
4586         if (CollectionUtils.isEmpty(categories)) {
4587             log.debug(CATEGORY_IS_EMPTY);
4588             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
4589                     ComponentTypeEnum.RESOURCE.getValue());
4590             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4591             throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
4592                     ComponentTypeEnum.RESOURCE.getValue());
4593         }
4594         if (categories.size() > 1) {
4595             log.debug("Must be only one category for resource");
4596             throw new ByActionStatusComponentException(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.RESOURCE.getValue());
4597         }
4598         CategoryDefinition category = categories.get(0);
4599         List<SubCategoryDefinition> subcategories = category.getSubcategories();
4600         if (CollectionUtils.isEmpty(subcategories)) {
4601             log.debug("Missinig subcategory for resource");
4602             throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
4603         }
4604         if (subcategories.size() > 1) {
4605             log.debug("Must be only one sub category for resource");
4606             throw new ByActionStatusComponentException(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
4607         }
4608
4609         SubCategoryDefinition subcategory = subcategories.get(0);
4610
4611         if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
4612             log.debug(CATEGORY_IS_EMPTY);
4613             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
4614                     ComponentTypeEnum.RESOURCE.getValue());
4615             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4616             throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
4617                     ComponentTypeEnum.RESOURCE.getValue());
4618         }
4619         if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
4620             log.debug(CATEGORY_IS_EMPTY);
4621             ResponseFormat responseFormat = componentsUtils.getResponseFormat(
4622                     ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
4623             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4624             throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
4625         }
4626
4627         validateCategoryListed(category, subcategory, user, resource, actionEnum, inTransaction);
4628     }
4629
4630     private void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory,
4631                                         User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
4632         ResponseFormat responseFormat;
4633         if (category != null && subcategory != null) {
4634             log.debug("validating resource category {} against valid categories list", category);
4635             Either<List<CategoryDefinition>, ActionStatus> categories = elementDao
4636                     .getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
4637             if (categories.isRight()) {
4638                 log.debug("failed to retrieve resource categories from JanusGraph");
4639                 responseFormat = componentsUtils.getResponseFormat(categories.right().value());
4640                 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4641                 throw new ByActionStatusComponentException(categories.right().value());
4642             }
4643             List<CategoryDefinition> categoryList = categories.left().value();
4644             Optional<CategoryDefinition> foundCategory = categoryList.stream()
4645                     .filter(cat -> cat.getName().equals(category.getName()))
4646                     .findFirst();
4647             if(!foundCategory.isPresent()){
4648                 log.debug("Category {} is not part of resource category group. Resource category valid values are {}",
4649                         category, categoryList);
4650                 failOnInvalidCategory(user, resource, actionEnum);
4651             }
4652             Optional<SubCategoryDefinition> foundSubcategory = foundCategory.get()
4653                     .getSubcategories()
4654                     .stream()
4655                     .filter(subcat -> subcat.getName().equals(subcategory.getName()))
4656                     .findFirst();
4657             if(!foundSubcategory.isPresent()){
4658                 log.debug("SubCategory {} is not part of resource category group. Resource subcategory valid values are {}",
4659                         subcategory, foundCategory.get().getSubcategories());
4660                 failOnInvalidCategory(user, resource, actionEnum);
4661             }
4662         }
4663     }
4664
4665     private void failOnInvalidCategory(User user, Resource resource, AuditingActionEnum actionEnum) {
4666         ResponseFormat responseFormat;
4667         responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY,
4668                 ComponentTypeEnum.RESOURCE.getValue());
4669         componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4670         throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY,
4671                 ComponentTypeEnum.RESOURCE.getValue());
4672     }
4673
4674     public void validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) {
4675         String vendorRelease = resource.getVendorRelease();
4676         log.debug("validate vendor relese name");
4677         if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) {
4678             log.info("vendor relese name is missing.");
4679             ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
4680             componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4681             throw new ByActionStatusComponentException(ActionStatus.MISSING_VENDOR_RELEASE);
4682         }
4683
4684         validateVendorReleaseName(vendorRelease, user, resource, actionEnum);
4685     }
4686
4687     public void validateVendorReleaseName(String vendorRelease, User user, Resource resource, AuditingActionEnum actionEnum) {
4688         if (vendorRelease != null) {
4689             if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
4690                 log.info("vendor release exceds limit.");
4691                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
4692                         ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
4693                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4694                 throw new ByActionStatusComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
4695             }
4696
4697             if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
4698                 log.info("vendor release  is not valid.");
4699                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
4700                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4701                 throw new ByActionStatusComponentException(ActionStatus.INVALID_VENDOR_RELEASE);
4702             }
4703         }
4704     }
4705
4706     private void validateVendorName(User user, Resource resource,
4707                                     AuditingActionEnum actionEnum) {
4708         String vendorName = resource.getVendorName();
4709         if (!ValidationUtils.validateStringNotEmpty(vendorName)) {
4710             log.info("vendor name is missing.");
4711             ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME);
4712             componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4713             throw new ByActionStatusComponentException(ActionStatus.MISSING_VENDOR_NAME);
4714         }
4715         validateVendorName(vendorName, user, resource, actionEnum);
4716     }
4717
4718     private void validateVendorName(String vendorName, User user, Resource resource,
4719                                     AuditingActionEnum actionEnum) {
4720         if (vendorName != null) {
4721             if (!ValidationUtils.validateVendorNameLength(vendorName)) {
4722                 log.info("vendor name exceds limit.");
4723                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
4724                         "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
4725                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4726                 throw new ByActionStatusComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
4727                         "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
4728             }
4729
4730             if (!ValidationUtils.validateVendorName(vendorName)) {
4731                 log.info("vendor name  is not valid.");
4732                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
4733                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4734                 throw new ByActionStatusComponentException(ActionStatus.INVALID_VENDOR_NAME);
4735             }
4736         }
4737     }
4738
4739     private void validateResourceVendorModelNumber(User user, Resource resource, AuditingActionEnum actionEnum) {
4740         String resourceVendorModelNumber = resource.getResourceVendorModelNumber();
4741         if (StringUtils.isNotEmpty(resourceVendorModelNumber)) {
4742             if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
4743                 log.info("resource vendor model number exceeds limit.");
4744                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
4745                         ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
4746                         "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
4747                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4748                 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
4749                         "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
4750             }
4751             // resource vendor model number is currently validated as vendor
4752             // name
4753             if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) {
4754                 log.info("resource vendor model number  is not valid.");
4755                 ResponseFormat errorResponse = componentsUtils
4756                         .getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
4757                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4758                 throw new ByActionStatusComponentException(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
4759             }
4760         }
4761     }
4762
4763
4764     private void validateCost(Resource resource) {
4765         String cost = resource.getCost();
4766         if (cost != null) {
4767             if (!ValidationUtils.validateCost(cost)) {
4768                 log.debug("resource cost is invalid.");
4769                 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
4770             }
4771         }
4772     }
4773
4774     private void validateLicenseType(User user, Resource resource,
4775                                      AuditingActionEnum actionEnum) {
4776         log.debug("validate licenseType");
4777         String licenseType = resource.getLicenseType();
4778         if (licenseType != null) {
4779             List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration()
4780                     .getLicenseTypes();
4781             if (!licenseTypes.contains(licenseType)) {
4782                 log.debug("License type {} isn't configured", licenseType);
4783                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
4784                 if (actionEnum != null) {
4785                     // In update case, no audit is required
4786                     componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4787                 }
4788                 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
4789             }
4790         }
4791     }
4792
4793     private Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom(Resource currentResource,
4794                                                                        Resource updatedResource, String userId, boolean inTransaction) {
4795         Either<Operation, ResponseFormat> deleteArtifactByInterface;
4796         if (updatedResource.getDerivedFrom() != null) {
4797             log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId());
4798             log.debug("1. Removing interface artifacts from graph");
4799             // Remove all interface artifacts of resource
4800             String resourceId = updatedResource.getUniqueId();
4801             Map<String, InterfaceDefinition> interfaces = currentResource.getInterfaces();
4802
4803             if (interfaces != null) {
4804                 Collection<InterfaceDefinition> values = interfaces.values();
4805                 for (InterfaceDefinition interfaceDefinition : values) {
4806                     String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition);
4807
4808                     log.trace("Starting interface artifacts removal for interface type {}", interfaceType);
4809                     Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
4810                     if (operations != null) {
4811                         for (Entry<String, Operation> operationEntry : operations.entrySet()) {
4812                             Operation operation = operationEntry.getValue();
4813                             ArtifactDefinition implementation = operation.getImplementationArtifact();
4814                             if (implementation != null) {
4815                                 String uniqueId = implementation.getUniqueId();
4816                                 log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}",
4817                                         uniqueId, operationEntry.getKey(), interfaceType);
4818                                 // only thing that transacts and locks here
4819                                 deleteArtifactByInterface = artifactsBusinessLogic.deleteArtifactByInterface(resourceId,
4820                                         userId, uniqueId,
4821                                         true);
4822                                 if (deleteArtifactByInterface.isRight()) {
4823                                     log.debug("Couldn't remove artifact definition with id {}", uniqueId);
4824                                     if (!inTransaction) {
4825                                         janusGraphDao.rollback();
4826                                     }
4827                                     return Either.right(deleteArtifactByInterface.right().value());
4828                                 }
4829                             } else {
4830                                 log.trace("No implementation found for operation {} - nothing to delete",
4831                                         operationEntry.getKey());
4832                             }
4833                         }
4834                     } else {
4835                         log.trace("No operations found for interface type {}", interfaceType);
4836                     }
4837                 }
4838             }
4839             log.debug("2. Removing properties");
4840             Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = propertyOperation
4841                     .deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId);
4842
4843             if (findPropertiesOfNode.isRight()
4844                     && !findPropertiesOfNode.right().value().equals(StorageOperationStatus.OK)) {
4845                 log.debug("Failed to remove all properties of resource");
4846                 if (!inTransaction) {
4847                     janusGraphDao.rollback();
4848                 }
4849                 return Either.right(componentsUtils.getResponseFormat(
4850                         componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right().value())));
4851             }
4852
4853         } else {
4854             log.debug("Derived from wasn't changed during update");
4855         }
4856
4857         if (inTransaction) {
4858             return Either.left(true);
4859         }
4860         janusGraphDao.commit();
4861         return Either.left(true);
4862
4863     }
4864
4865     /**** Auditing *******************/
4866
4867     protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) {
4868         WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
4869                 .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
4870
4871         WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
4872
4873         return webApplicationContext.getBean(class1);
4874     }
4875
4876     public ICapabilityTypeOperation getCapabilityTypeOperation() {
4877         return capabilityTypeOperation;
4878     }
4879
4880     public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) {
4881         this.capabilityTypeOperation = capabilityTypeOperation;
4882     }
4883
4884     public Either<Boolean, ResponseFormat> validatePropertiesDefaultValues(Resource resource) {
4885         log.debug("validate resource properties default values");
4886         Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4887         List<PropertyDefinition> properties = resource.getProperties();
4888         if (properties != null) {
4889             eitherResult = iterateOverProperties(properties);
4890         }
4891         return eitherResult;
4892     }
4893
4894     public Either<Boolean, ResponseFormat> iterateOverProperties(List<PropertyDefinition> properties){
4895         Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4896         String type = null;
4897         String innerType = null;
4898         for (PropertyDefinition property : properties) {
4899             if (!propertyOperation.isPropertyTypeValid(property)) {
4900                 log.info("Invalid type for property {}", property);
4901                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
4902                         ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
4903                 eitherResult = Either.right(responseFormat);
4904                 break;
4905             }
4906
4907             Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(
4908                     applicationDataTypeCache);
4909             if (allDataTypes.isRight()) {
4910                 return Either.right(allDataTypes.right().value());
4911             }
4912
4913             type = property.getType();
4914
4915             if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
4916                 ResponseFormat responseFormat = validateMapOrListPropertyType(property, innerType, allDataTypes.left().value());
4917                 if(responseFormat != null) {
4918                     break;
4919                 }
4920             }
4921             eitherResult = validateDefaultPropertyValue(property, allDataTypes.left().value(), type, innerType);
4922         }
4923         return eitherResult;
4924     }
4925
4926     private Either<Boolean,ResponseFormat> validateDefaultPropertyValue(PropertyDefinition property, Map<String, DataTypeDefinition> allDataTypes, String type, String innerType) {
4927         if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes)) {
4928             log.info("Invalid default value for property {}", property);
4929             ResponseFormat responseFormat;
4930             if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
4931                 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE,
4932                         property.getName(), type, innerType, property.getDefaultValue());
4933             } else {
4934                 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE,
4935                         property.getName(), type, property.getDefaultValue());
4936             }
4937             return Either.right(responseFormat);
4938
4939         }
4940         return Either.left(true);
4941     }
4942
4943     private ResponseFormat validateMapOrListPropertyType(PropertyDefinition property, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
4944         ResponseFormat responseFormat = null;
4945         ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation
4946                 .isPropertyInnerTypeValid(property, allDataTypes);
4947         innerType = propertyInnerTypeValid.getLeft();
4948         if (!propertyInnerTypeValid.getRight().booleanValue()) {
4949             log.info("Invalid inner type for property {}", property);
4950             responseFormat = componentsUtils.getResponseFormat(
4951                     ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
4952         }
4953         return responseFormat;
4954     }
4955
4956     @Override
4957     public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
4958         return deleteMarkedComponents(ComponentTypeEnum.RESOURCE);
4959     }
4960
4961     @Override
4962     public ComponentInstanceBusinessLogic getComponentInstanceBL() {
4963         return componentInstanceBusinessLogic;
4964     }
4965
4966     private String getComponentTypeForResponse(Component component) {
4967         String componentTypeForResponse = "SERVICE";
4968         if (component instanceof Resource) {
4969             componentTypeForResponse = ((Resource) component).getResourceType().name();
4970         }
4971         return componentTypeForResponse;
4972     }
4973
4974     public Either<Resource, ResponseFormat> getLatestResourceFromCsarUuid(String csarUuid, User user) {
4975         // validate user
4976         if (user != null) {
4977             validateUserExists(user, "Get resource from csar UUID",
4978                     false);
4979         }
4980         // get resource from csar uuid
4981         Either<Resource, StorageOperationStatus> either = toscaOperationFacade
4982                 .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, "");
4983         if (either.isRight()) {
4984             ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND,
4985                     csarUuid);
4986             return Either.right(resp);
4987         }
4988
4989         return Either.left(either.left().value());
4990     }
4991
4992     @Override
4993     public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(
4994             String componentId, String userId) {
4995         return null;
4996     }
4997
4998     private Map<String, List<CapabilityDefinition>> getValidComponentInstanceCapabilities(
4999             String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities,
5000             Map<String, List<UploadCapInfo>> uploadedCapabilities) {
5001
5002         Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
5003         uploadedCapabilities.forEach((k,v)->addValidComponentInstanceCapabilities(k,v,resourceId,defaultCapabilities,validCapabilitiesMap));
5004         return validCapabilitiesMap;
5005     }
5006
5007     private void addValidComponentInstanceCapabilities(String key, List<UploadCapInfo> capabilities, String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities, Map<String, List<CapabilityDefinition>> validCapabilitiesMap){
5008         String capabilityType = capabilities.get(0).getType();
5009         if (defaultCapabilities.containsKey(capabilityType)) {
5010             CapabilityDefinition defaultCapability = getCapability(resourceId, defaultCapabilities, capabilityType);
5011             validateCapabilityProperties(capabilities, resourceId, defaultCapability);
5012             List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
5013             validCapabilityList.add(defaultCapability);
5014             validCapabilitiesMap.put(key, validCapabilityList);
5015         } else {
5016             throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType));
5017         }
5018     }
5019
5020     private void validateCapabilityProperties(List<UploadCapInfo> capabilities, String resourceId, CapabilityDefinition defaultCapability) {
5021         if (CollectionUtils.isEmpty(defaultCapability.getProperties())
5022                 && isNotEmpty(capabilities.get(0).getProperties())) {
5023             log.debug("Failed to validate capability {} of component {}. Property list is empty. ",
5024                     defaultCapability.getName(), resourceId);
5025             log.debug(
5026                     "Failed to update capability property values. Property list of fetched capability {} is empty. ",
5027                     defaultCapability.getName());
5028             throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, resourceId));
5029         } else if (isNotEmpty(capabilities.get(0).getProperties())) {
5030             validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, capabilities.get(0));
5031         }
5032     }
5033
5034     private CapabilityDefinition getCapability(String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities, String capabilityType) {
5035         CapabilityDefinition defaultCapability;
5036         if (isNotEmpty(defaultCapabilities.get(capabilityType).get(0).getProperties())) {
5037             defaultCapability = defaultCapabilities.get(capabilityType).get(0);
5038         } else {
5039             Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade
5040                     .getToscaFullElement(resourceId);
5041             if (getFullComponentRes.isRight()) {
5042                 log.debug("Failed to get full component {}. Status is {}. ", resourceId,
5043                         getFullComponentRes.right().value());
5044                 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND,
5045                         resourceId));
5046             }
5047             defaultCapability = getFullComponentRes.left().value().getCapabilities().get(capabilityType).get(0);
5048         }
5049         return defaultCapability;
5050     }
5051
5052     private void validateUniquenessUpdateUploadedComponentInstanceCapability(
5053             CapabilityDefinition defaultCapability, UploadCapInfo uploadedCapability) {
5054         List<ComponentInstanceProperty> validProperties = new ArrayList<>();
5055         Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties().stream()
5056                 .collect(toMap(PropertyDefinition::getName, Function.identity()));
5057         List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
5058         for (UploadPropInfo property : uploadedProperties) {
5059             String propertyName = property.getName().toLowerCase();
5060             String propertyType = property.getType();
5061             ComponentInstanceProperty validProperty;
5062             if (defaultProperties.containsKey(propertyName) && propertTypeEqualsTo(defaultProperties, propertyName, propertyType)) {
5063                 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS,
5064                         propertyName));
5065             }
5066             validProperty = new ComponentInstanceProperty();
5067             validProperty.setName(propertyName);
5068             if (property.getValue() != null) {
5069                 validProperty.setValue(property.getValue().toString());
5070             }
5071             validProperty.setDescription(property.getDescription());
5072             validProperty.setPassword(property.isPassword());
5073             validProperties.add(validProperty);
5074         }
5075         defaultCapability.setProperties(validProperties);
5076     }
5077
5078     private boolean propertTypeEqualsTo(Map<String, PropertyDefinition> defaultProperties, String propertyName, String propertyType) {
5079         return propertyType != null && !defaultProperties.get(propertyName).getType().equals(propertyType);
5080     }
5081
5082     private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(
5083             List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle,
5084             Resource resource, User user) {
5085
5086         EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(
5087                 ArtifactOperationEnum.class);
5088         Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
5089         Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either
5090                 .left(nodeTypeArtifactsToHandle);
5091         try {
5092             // add all found Csar artifacts to list to upload
5093             List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
5094             List<NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
5095             List<NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
5096             for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
5097                 ArtifactDefinition foundArtifact;
5098
5099                 if (!existingArtifactsToHandle.isEmpty()) {
5100                     foundArtifact = existingArtifactsToHandle.stream()
5101                             .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst()
5102                             .orElse(null);
5103                     if (foundArtifact != null) {
5104                         if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()) == currNewArtifact
5105                                 .getArtifactType()) {
5106                             if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
5107                                 currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
5108                                 // if current artifact already exists, but has
5109                                 // different content, add him to the list to
5110                                 // update
5111                                 artifactsToUpdate.add(currNewArtifact);
5112                             }
5113                             // remove found artifact from the list of existing
5114                             // artifacts to handle, because it was already
5115                             // handled
5116                             existingArtifactsToHandle.remove(foundArtifact);
5117                             // and remove found artifact from the list to
5118                             // upload, because it should either be updated or be
5119                             // ignored
5120                             artifactsToUpload.remove(currNewArtifact);
5121                         } else {
5122                             log.debug("Can't upload two artifact with the same name {}.",
5123                                     currNewArtifact.getArtifactName());
5124                             ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(
5125                                     ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
5126                                     currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType().name(),
5127                                     foundArtifact.getArtifactType());
5128                             AuditingActionEnum auditingAction = artifactsBusinessLogic
5129                                     .detectAuditingType(artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
5130                                             ArtifactOperationEnum.CREATE), foundArtifact.getArtifactChecksum());
5131                             artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(),
5132                                     user, null, null, foundArtifact.getUniqueId(), responseFormat,
5133                                     resource.getComponentType(), null);
5134                             responseWrapper.setInnerElement(responseFormat);
5135                             break;
5136                         }
5137                     }
5138                 }
5139             }
5140             if (responseWrapper.isEmpty()) {
5141                 for (ArtifactDefinition currArtifact : existingArtifactsToHandle) {
5142                     if (currArtifact.getIsFromCsar()) {
5143                         artifactsToDelete.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
5144                     } else {
5145                         artifactsToUpdate.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
5146
5147                     }
5148                 }
5149             }
5150             if (responseWrapper.isEmpty()) {
5151                 if (!artifactsToUpload.isEmpty()) {
5152                     nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
5153                 }
5154                 if (!artifactsToUpdate.isEmpty()) {
5155                     nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
5156                 }
5157                 if (!artifactsToDelete.isEmpty()) {
5158                     nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
5159                 }
5160             }
5161             if (!responseWrapper.isEmpty()) {
5162                 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
5163             }
5164         } catch (Exception e) {
5165             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5166             responseWrapper.setInnerElement(responseFormat);
5167             log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
5168             nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
5169         }
5170         return nodeTypeArtifactsToHandleRes;
5171     }
5172
5173     ImmutablePair<String, String> buildNestedToscaResourceName(String nodeResourceType, String vfResourceName,
5174                                                                String nodeTypeFullName) {
5175         String actualType;
5176         String actualVfName;
5177         if (ResourceTypeEnum.CVFC.name().equals(nodeResourceType)) {
5178             actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name();
5179             actualType = ResourceTypeEnum.VFC.name();
5180         } else {
5181             actualVfName = vfResourceName;
5182             actualType = nodeResourceType;
5183         }
5184         String nameWithouNamespacePrefix;
5185         try {
5186             StringBuilder toscaResourceName = new StringBuilder(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
5187             if (!nodeTypeFullName.contains(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)){
5188                nameWithouNamespacePrefix = nodeTypeFullName;
5189             } else {
5190                 nameWithouNamespacePrefix = nodeTypeFullName
5191                     .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
5192             }
5193             String[] findTypes = nameWithouNamespacePrefix.split("\\.");
5194             String resourceType = findTypes[0];
5195             String actualName = nameWithouNamespacePrefix.substring(resourceType.length());
5196
5197             if (actualName.startsWith(Constants.ABSTRACT)) {
5198                 toscaResourceName.append(resourceType.toLowerCase()).append('.')
5199                         .append(ValidationUtils.convertToSystemName(actualVfName));
5200             } else {
5201                 toscaResourceName.append(actualType.toLowerCase()).append('.')
5202                         .append(ValidationUtils.convertToSystemName(actualVfName)).append('.').append(Constants.ABSTRACT);
5203             }
5204             StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName);
5205             return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
5206                     previousToscaResourceName
5207                             .append(actualName.substring(actualName.split("\\.")[1].length() + 1).toLowerCase())
5208                             .toString());
5209         } catch (Exception e) {
5210             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
5211             log.debug("Exception occured when buildNestedToscaResourceName, error is:{}", e.getMessage(), e);
5212             throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfResourceName);
5213         }
5214     }
5215
5216     @Override
5217         public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId,
5218                                                                                                                                                                                                    List<String> dataParamsToReturn) {
5219
5220                 ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
5221                 Either<Resource, StorageOperationStatus> resourceResultEither =
5222                                 toscaOperationFacade.getToscaElement(resourceId,
5223                                                 paramsToRetuen);
5224
5225                 if (resourceResultEither.isRight()) {
5226                         if (resourceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
5227                                 log.debug("Failed to found resource with id {} ", resourceId);
5228                                 Either
5229                                                 .right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
5230                         }
5231
5232                         log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn);
5233                         return Either.right(componentsUtils.getResponseFormatByResource(
5234                                         componentsUtils.convertFromStorageResponse(resourceResultEither.right().value()), ""));
5235                 }
5236
5237                 Resource resource = resourceResultEither.left().value();
5238                 if (dataParamsToReturn.contains(ComponentFieldsEnum.INPUTS.getValue())) {
5239                         ListUtils.emptyIfNull(resource.getInputs())
5240                                         .forEach(input -> input.setConstraints(setInputConstraint(input)));
5241                 }
5242
5243                 UiComponentDataTransfer dataTransfer = uiComponentDataConverter.getUiDataTransferFromResourceByParams(resource,
5244                                 dataParamsToReturn);
5245                 return Either.left(dataTransfer);
5246         }
5247
5248     @Override
5249     public Either<Component, ActionStatus> shouldUpgradeToLatestDerived(Component clonedComponent) {
5250         Resource resource = (Resource) clonedComponent;
5251         if (ModelConverter.isAtomicComponent(resource.getResourceType())) {
5252             Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived = toscaOperationFacade
5253                     .shouldUpgradeToLatestDerived(resource);
5254             if (shouldUpgradeToLatestDerived.isRight()) {
5255                 return Either.right(
5256                         componentsUtils.convertFromStorageResponse(shouldUpgradeToLatestDerived.right().value()));
5257             }
5258             return Either.left(shouldUpgradeToLatestDerived.left().value());
5259         } else {
5260             return super.shouldUpgradeToLatestDerived(clonedComponent);
5261         }
5262     }
5263 }