Catalog alignment
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / components / impl / GroupBusinessLogic.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 import fj.data.Either;
26 import org.apache.commons.collections.CollectionUtils;
27 import org.apache.commons.collections.MapUtils;
28 import org.apache.commons.io.FilenameUtils;
29 import org.apache.commons.lang.StringUtils;
30 import org.apache.commons.lang3.math.NumberUtils;
31 import org.apache.commons.lang3.tuple.ImmutablePair;
32 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
33 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
34 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
35 import org.openecomp.sdc.be.components.impl.lock.LockingTransactional;
36 import org.openecomp.sdc.be.components.impl.policy.PolicyTargetsUpdateHandler;
37 import org.openecomp.sdc.be.components.utils.Utils;
38 import org.openecomp.sdc.be.components.validation.AccessValidations;
39 import org.openecomp.sdc.be.components.validation.ComponentValidations;
40 import org.openecomp.sdc.be.config.BeEcompErrorManager;
41 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
42 import org.openecomp.sdc.be.config.ConfigurationManager;
43 import org.openecomp.sdc.be.dao.api.ActionStatus;
44 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
45 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
46 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
47 import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType;
48 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
49 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
50 import org.openecomp.sdc.be.datatypes.enums.CreatedFrom;
51 import org.openecomp.sdc.be.datatypes.enums.PromoteVersionEnum;
52 import org.openecomp.sdc.be.info.ArtifactDefinitionInfo;
53 import org.openecomp.sdc.be.info.ArtifactTemplateInfo;
54 import org.openecomp.sdc.be.info.GroupDefinitionInfo;
55 import org.openecomp.sdc.be.model.ArtifactDefinition;
56 import org.openecomp.sdc.be.model.Component;
57 import org.openecomp.sdc.be.model.ComponentInstance;
58 import org.openecomp.sdc.be.model.ComponentParametersView;
59 import org.openecomp.sdc.be.model.DataTypeDefinition;
60 import org.openecomp.sdc.be.model.GroupDefinition;
61 import org.openecomp.sdc.be.model.GroupInstance;
62 import org.openecomp.sdc.be.model.GroupInstanceProperty;
63 import org.openecomp.sdc.be.model.GroupProperty;
64 import org.openecomp.sdc.be.model.GroupTypeDefinition;
65 import org.openecomp.sdc.be.model.PropertyDefinition;
66 import org.openecomp.sdc.be.model.PropertyDefinition.GroupInstancePropertyValueUpdateBehavior;
67 import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames;
68 import org.openecomp.sdc.be.model.Resource;
69 import org.openecomp.sdc.be.model.User;
70 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
71 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.GroupsOperation;
72 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
73 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.TopologyTemplateOperation;
74 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
75 import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
76 import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
77 import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
78 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
79 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
80 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
81 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
82 import org.openecomp.sdc.common.api.Constants;
83 import org.openecomp.sdc.common.log.elements.LoggerSupportability;
84 import org.openecomp.sdc.common.log.enums.LogLevel;
85 import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions;
86 import org.openecomp.sdc.common.log.enums.StatusCode;
87 import org.openecomp.sdc.common.log.wrappers.Logger;
88 import org.openecomp.sdc.common.util.ValidationUtils;
89 import org.openecomp.sdc.exception.ResponseFormat;
90 import org.springframework.beans.factory.annotation.Autowired;
91
92 import java.util.ArrayList;
93 import java.util.Arrays;
94 import java.util.Collection;
95 import java.util.Collections;
96 import java.util.EnumMap;
97 import java.util.HashMap;
98 import java.util.List;
99 import java.util.Map;
100 import java.util.Map.Entry;
101 import java.util.Optional;
102 import java.util.Set;
103 import java.util.regex.Pattern;
104 import java.util.stream.Collectors;
105
106 import static java.util.stream.Collectors.toList;
107 import static org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter.extractCapabilitiesFromGroups;
108 import static org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter.extractCapabilityPropertiesFromGroups;
109
110 @org.springframework.stereotype.Component("groupBusinessLogic")
111 public class GroupBusinessLogic extends BaseBusinessLogic {
112
113     public static final String GROUP_DELIMITER_REGEX = "\\.\\.";
114
115     public static final String INITIAL_VERSION = "0.0";
116
117     private static final String ADDING_GROUP = "AddingGroup";
118
119     private static final String CREATE_GROUP = "CreateGroup";
120
121     private static final String UPDATE_GROUP = "UpdateGroup";
122
123     private static final String GET_GROUP = "GetGroup";
124
125     private static final String DELETE_GROUP = "DeleteGroup";
126
127     private static final Logger log = Logger.getLogger(GroupBusinessLogic.class);
128
129     public LoggerSupportability loggerSupportability= LoggerSupportability.getLogger(GroupBusinessLogic.class.getName());
130
131     private final AccessValidations accessValidations;
132     private final PolicyTargetsUpdateHandler policyTargetsUpdateHandler;
133
134     @javax.annotation.Resource
135     private final GroupsOperation groupsOperation;
136
137
138     @Autowired
139     public GroupBusinessLogic(IElementOperation elementDao,
140         IGroupOperation groupOperation,
141         IGroupInstanceOperation groupInstanceOperation,
142         IGroupTypeOperation groupTypeOperation,
143         InterfaceOperation interfaceOperation,
144         InterfaceLifecycleOperation interfaceLifecycleTypeOperation, AccessValidations accessValidations,
145         GroupsOperation groupsOperation, PolicyTargetsUpdateHandler policyTargetsUpdateHandler,
146         ArtifactsOperations artifactToscaOperation) {
147         super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
148             interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
149         this.accessValidations = accessValidations;
150         this.groupsOperation = groupsOperation;
151         this.policyTargetsUpdateHandler = policyTargetsUpdateHandler;
152     }
153
154     private String getComponentTypeForResponse(org.openecomp.sdc.be.model.Component component) {
155         String componentTypeForResponse = "SERVICE";
156         if (component instanceof Resource) {
157             componentTypeForResponse = ((Resource) component).getResourceType().name();
158         }
159         return componentTypeForResponse;
160     }
161
162     /**
163      * Verify that the artifact members belongs to the component
164      *
165      * @param component
166      * @param artifacts
167      * @return
168      */
169     private Either<Boolean, ResponseFormat> verifyArtifactsBelongsToComponent(Component component, List<String> artifacts, String context) {
170
171         if (CollectionUtils.isEmpty(artifacts)) {
172             return Either.left(true);
173         }
174
175         Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts();
176         if (MapUtils.isEmpty(deploymentArtifacts)) {
177             BeEcompErrorManager.getInstance().logInvalidInputError(context, "No deployment artifact found under component " + component.getNormalizedName(), ErrorSeverity.INFO);
178             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
179         }
180
181         List<String> currentArtifacts = deploymentArtifacts.values().stream().map(ArtifactDefinition::getUniqueId).collect(toList());
182         log.debug("The deployment artifacts of component {} are {}", component.getNormalizedName(), deploymentArtifacts);
183         if (!currentArtifacts.containsAll(artifacts)) {
184             BeEcompErrorManager.getInstance().logInvalidInputError(context, "Not all artifacts belongs to component " + component.getNormalizedName(), ErrorSeverity.INFO);
185             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
186         }
187
188         return Either.left(true);
189
190     }
191
192     /**
193      * verify that the members are component instances of the component
194      *
195      * @param component
196      * @param groupMembers
197      * @param memberToscaTypes
198      * @return
199      */
200     private Either<Boolean, ResponseFormat> verifyComponentInstancesAreValidMembers(Component component, String groupName, Map<String, String> groupMembers, List<String> memberToscaTypes) {
201
202         if (MapUtils.isEmpty(groupMembers)) {
203             return Either.left(true);
204         }
205
206         if (CollectionUtils.isEmpty(memberToscaTypes)) {
207             return Either.left(true);
208         }
209
210         List<ComponentInstance> componentInstances = component.getComponentInstances();
211         if (CollectionUtils.isNotEmpty(componentInstances)) {
212             Map<String, ComponentInstance> compInstUidToCompInstMap = componentInstances.stream().collect(Collectors.toMap(ComponentInstance::getUniqueId, p -> p));
213
214             Set<String> allCompInstances = compInstUidToCompInstMap.keySet();
215
216             for (Entry<String, String> groupMember : groupMembers.entrySet()) {
217                 String compName = groupMember.getKey();
218                 String compUid = groupMember.getValue();
219
220                 if (!allCompInstances.contains(compUid)) {
221                     /*
222                      * %1 - member name %2 - group name %3 - VF name %4 - component type [VF ]
223                      */
224                     String componentTypeForResponse = getComponentTypeForResponse(component);
225
226                     BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "Not all group members exists under the component", ErrorSeverity.INFO);
227                     return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, compName, groupName, component.getNormalizedName(), componentTypeForResponse));
228                 }
229             }
230         }
231
232         return Either.left(true);
233     }
234
235
236
237     /**
238      * Update GroupDefinition metadata
239      *
240      * @param componentId
241      * @param user
242      * @param componentType
243      * @param updatedGroup
244      * @param inTransaction
245      * @return
246      */
247     public Either<GroupDefinition, ResponseFormat> validateAndUpdateGroupMetadata(String componentId, User user, ComponentTypeEnum componentType, GroupDefinition updatedGroup, boolean inTransaction , boolean shouldLock) {
248
249         Either<GroupDefinition, ResponseFormat> result = null;
250         boolean failed = false;
251         try {
252             // Validate user exist
253             validateUserExists(user.getUserId());
254             // Validate component exist
255             org.openecomp.sdc.be.model.Component component = validateComponentExists(componentId, componentType, null);
256             // validate we can work on component
257             validateCanWorkOnComponent(component, user.getUserId());
258             List<GroupDefinition> currentGroups = component.getGroups();
259             if (CollectionUtils.isEmpty(currentGroups)) {
260                 log.error("Failed to update the metadata of group {} on component {}. The status is {}. ", updatedGroup.getName(), component.getName(), ActionStatus.GROUP_IS_MISSING);
261                 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, updatedGroup.getName(), component.getName(), component.getComponentType().getValue()));
262                 return result;
263             }
264             // Validate groups exists in the component
265             Optional<GroupDefinition> currentGroupOpt = currentGroups.stream().filter(g -> g.getUniqueId().equals(updatedGroup.getUniqueId())).findAny();
266             if (!currentGroupOpt.isPresent()) {
267                 log.error("Failed to update the metadata of group {} on component {}. The status is {}. ", updatedGroup.getName(), component.getName(), ActionStatus.GROUP_IS_MISSING);
268                 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, updatedGroup.getName(), component.getName(), component.getComponentType().getValue()));
269                 return result;
270             }
271             GroupDefinition currentGroup = currentGroupOpt.get();
272             if ( shouldLock ){
273                 lockComponent(componentId, component, "Update GroupDefinition Metadata");
274             }
275             // Validate group type is vfModule
276             if (currentGroup.getType().equals(Constants.GROUP_TOSCA_HEAT)) {
277                 log.error("Failed to update the metadata of group {}. Group type is {} and cannot be updated", currentGroup.getName(), currentGroup.getType());
278                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, updatedGroup.getType());
279                 result = Either.right(responseFormat);
280                 return result;
281             }
282             result = updateGroupMetadata(component, currentGroup, updatedGroup);
283             return result;
284
285         }catch (ComponentException e){
286             failed = true;
287             throw e;
288         }finally {
289             if (!failed) {
290                 janusGraphDao.commit();
291             } else {
292                 janusGraphDao.rollback();
293             }
294             if (shouldLock) {
295                 graphLockOperation.unlockComponent(componentId, componentType.getNodeType());
296             }
297         }
298     }
299
300     private Either<GroupDefinition, ResponseFormat> updateGroupMetadata(Component component, GroupDefinition currentGroup, GroupDefinition updatedGroup) {
301         String currentGroupName = currentGroup.getName();
302         Either<GroupDefinition, ResponseFormat> result = validateAndUpdateGroupMetadata(currentGroup, updatedGroup);
303
304         if (result.isRight()) {
305             log.debug("Failed to validate a metadata of the group {} on component {}. ", updatedGroup.getName(), component.getName());
306         }
307         if (result.isLeft()) {
308             result = updateGroup(component, currentGroup, currentGroupName);
309         }
310         return result;
311     }
312
313     private Either<GroupDefinition, ResponseFormat> updateGroup(Component component, GroupDefinition updatedGroup, String currentGroupName) {
314         Either<GroupDefinition, StorageOperationStatus> handleGroupRes;
315         Either<GroupDefinition, ResponseFormat> result = null;
316         handleGroupRes = groupsOperation.updateGroup(component, updatedGroup);
317         if (handleGroupRes.isRight()) {
318             log.debug("Failed to update a metadata of the group {} on component {}. ", updatedGroup.getName(), component.getName());
319             result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(handleGroupRes.right().value())));
320         }
321         if (result == null) {
322             result = Either.left(updatedGroup);
323         }
324         return result;
325     }
326
327     /**
328      * Validate and update GroupDefinition metadata
329      *
330      * @param currentGroup
331      * @param groupUpdate
332      * @return
333      **/
334     private Either<GroupDefinition, ResponseFormat> validateAndUpdateGroupMetadata(GroupDefinition currentGroup, GroupDefinition groupUpdate) {
335         // Check if to update, and update GroupDefinition name.
336         Either<Boolean, ResponseFormat> response = validateAndUpdateGroupName(currentGroup, groupUpdate);
337         if (response.isRight()) {
338             ResponseFormat errorResponse = response.right().value();
339             return Either.right(errorResponse);
340         }
341
342         // Do not allow to update GroupDefinition version directly.
343         String versionUpdated = groupUpdate.getVersion();
344         String versionCurrent = currentGroup.getVersion();
345         if (versionUpdated != null && !versionCurrent.equals(versionUpdated)) {
346             log.info("update Group: recived request to update version to {} the field is not updatable ignoring.", versionUpdated);
347         }
348
349         return Either.left(currentGroup);
350     }
351
352     /**
353      * Validate and update GroupDefinition name
354      *
355      * @param currentGroup
356      * @param groupUpdate
357      * @return
358      */
359     private Either<Boolean, ResponseFormat> validateAndUpdateGroupName(GroupDefinition currentGroup, GroupDefinition groupUpdate) {
360         String nameUpdated = groupUpdate.getName();
361         String nameCurrent = currentGroup.getName();
362         if (!nameCurrent.equals(nameUpdated)) {
363             Either<Boolean, ResponseFormat> validatNameResponse = validateGroupName(currentGroup.getName(), groupUpdate.getName() ,true);
364             if (validatNameResponse.isRight()) {
365                 ResponseFormat errorRespons = validatNameResponse.right().value();
366                 return Either.right(errorRespons);
367             }
368             currentGroup.setName(groupUpdate.getName());
369         }
370         return Either.left(true);
371     }
372
373     /**
374      * Validate that group name to update is valid (same as current group name except for middle part). For example: Current group name: MyResource..MyDesc..Module-1 Group to update: MyResource..MyDesc2..Module-1 Verify that only the second part
375      * MyDesc was changed.
376      *
377      * @param currentGroupName
378      * @param groupUpdateName
379      * @return
380      */
381     private Either<Boolean, ResponseFormat> validateGroupName(String currentGroupName, String groupUpdateName , boolean isforceNameModification) {
382         try {
383             // Check if the group name is in old format.
384             if (Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(groupUpdateName).matches()) {
385                 log.error("Group name {} is in old format", groupUpdateName);
386                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME, groupUpdateName));
387             }
388
389             // Check that name pats 1 and 3 did not changed (only the second
390             // part can be changed)
391             // But verify before that the current group format is the new one
392             if (!Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(currentGroupName).matches()) {
393                 String[] split1 = currentGroupName.split(GROUP_DELIMITER_REGEX);
394                 String currentResourceName = split1[0];
395                 String currentCounter = split1[2];
396
397                 String[] split2 = groupUpdateName.split(GROUP_DELIMITER_REGEX);
398                 String groupUpdateResourceName = split2[0];
399                 String groupUpdateCounter = split2[2];
400                 if (!isforceNameModification){            //if not forced ,allow name prefix&suffix validation [no changes]
401                     if (!currentResourceName.equals(groupUpdateResourceName)) {
402                         return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME_MODIFICATION, currentResourceName));
403                     }
404
405                     if (!currentCounter.equals(groupUpdateCounter)) {
406                         return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME_MODIFICATION, currentCounter));
407                     }
408                 }
409
410             }
411
412             return Either.left(true);
413         } catch (Exception e) {
414             log.error("Error valiadting group name", e);
415             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
416         }
417     }
418
419
420     /**
421      * associate artifacts to a given group
422      *
423      * @param componentId
424      * @param userId
425      * @param componentType
426      * @param inTransaction
427      * @return
428      */
429     public Either<GroupDefinitionInfo, ResponseFormat> getGroupWithArtifactsById(ComponentTypeEnum componentType, String componentId, String groupId, String userId, boolean inTransaction) {
430
431         Either<GroupDefinitionInfo, ResponseFormat> result = null;
432
433         // Validate user exist
434         validateUserExists(userId);
435         // Validate component exist
436         org.openecomp.sdc.be.model.Component component = null;
437
438         try {
439             ComponentParametersView componentParametersView = new ComponentParametersView();
440             componentParametersView.disableAll();
441             componentParametersView.setIgnoreGroups(false);
442             componentParametersView.setIgnoreArtifacts(false);
443             componentParametersView.setIgnoreUsers(false);
444
445             component = validateComponentExists(componentId, componentType, componentParametersView);
446
447             Either<GroupDefinition, StorageOperationStatus> groupEither = findGroupOnComponent(component, groupId);
448
449             if (groupEither.isRight()) {
450                 log.debug("Failed to find group {} under component {}", groupId, component.getUniqueId());
451                 BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "group  " + groupId + " not found under component " + component.getUniqueId(), ErrorSeverity.INFO);
452                 String componentTypeForResponse = getComponentTypeForResponse(component);
453                 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, groupId, component.getSystemName(), componentTypeForResponse));
454                 return result;
455             }
456             GroupDefinition group = groupEither.left().value();
457
458             List<GroupProperty> props = group.convertToGroupProperties();
459             Boolean isBase = isBaseProp(component, props);
460
461             List<ArtifactDefinitionInfo> artifacts = new ArrayList<>();
462             List<ArtifactDefinition> artifactsFromComponent = new ArrayList<>();
463             List<String> artifactsIds = group.getArtifacts();
464
465             Map<String, ArtifactDefinition> deploymentArtifacts = null;
466             if (MapUtils.isNotEmpty(component.getDeploymentArtifacts())) {
467                 deploymentArtifacts = component.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, a -> a));
468             }
469
470             if (artifactsIds != null && !artifactsIds.isEmpty()) {
471                 for (String id : artifactsIds) {
472                     if (deploymentArtifacts == null || !deploymentArtifacts.containsKey(id)) {
473                         log.debug("Failed to get artifact {} . Status is {} ", id, StorageOperationStatus.NOT_FOUND);
474                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND));
475                         result = Either.right(responseFormat);
476                         return result;
477                     }
478                     artifactsFromComponent.add(deploymentArtifacts.get(id));
479                 }
480                 addArtifactsToList(artifacts, artifactsFromComponent);
481
482             }
483             GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group);
484             resultInfo.setIsBase(isBase);
485             if (!artifacts.isEmpty()) {
486                 resultInfo.setArtifacts(artifacts);
487             }
488             result = Either.left(resultInfo);
489
490             return result;
491
492         } finally {
493             closeTransaction(inTransaction, result);
494         }
495
496     }
497
498     private void addArtifactsToList(List<ArtifactDefinitionInfo> artifacts, List<ArtifactDefinition> artifactsFromComponent) {
499         artifactsFromComponent.forEach(a-> artifacts.add(new ArtifactDefinitionInfo(a)));
500     }
501
502     private Boolean isBaseProp(Component component, List<GroupProperty> props) {
503         Boolean isBase = null;
504         if (CollectionUtils.isNotEmpty(props)) {
505             Optional<GroupProperty> isBasePropOp = props.stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny();
506             if (isBasePropOp.isPresent()) {
507                 GroupProperty propIsBase = isBasePropOp.get();
508                 isBase = Boolean.parseBoolean(propIsBase.getValue());
509
510             } else {
511                 BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO);
512             }
513         }
514         return isBase;
515     }
516
517     private Either<GroupDefinition, StorageOperationStatus> findGroupOnComponent(Component component, String groupId) {
518
519         Either<GroupDefinition, StorageOperationStatus> result = null;
520         if (CollectionUtils.isNotEmpty(component.getGroups())) {
521             Optional<GroupDefinition> foundGroup = component.getGroups().stream().filter(g -> g.getUniqueId().equals(groupId)).findFirst();
522             if (foundGroup.isPresent()) {
523                 result = Either.left(foundGroup.get());
524             }
525         }
526         if (result == null) {
527             result = Either.right(StorageOperationStatus.NOT_FOUND);
528         }
529         return result;
530     }
531
532     public Either<Boolean, ResponseFormat> validateGenerateVfModuleGroupNames(List<ArtifactTemplateInfo> allGroups, String resourceSystemName, int startGroupCounter) {
533         Either<Boolean, ResponseFormat> validateGenerateGroupNamesRes = Either.left(true);
534         Collections.sort(allGroups, ArtifactTemplateInfo::compareByGroupName);
535         for (ArtifactTemplateInfo group : allGroups) {
536             Either<String, ResponseFormat> validateGenerateGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, group.getDescription(), startGroupCounter++);
537             if (validateGenerateGroupNameRes.isRight()) {
538                 validateGenerateGroupNamesRes = Either.right(validateGenerateGroupNameRes.right().value());
539                 break;
540             }
541             group.setGroupName(validateGenerateGroupNameRes.left().value());
542         }
543         return validateGenerateGroupNamesRes;
544     }
545
546     /**
547      * Generate module name from resourceName, description and counter
548      *
549      * @param resourceSystemName
550      * @param description
551      * @param groupCounter
552      * @return
553      */
554     private Either<String, ResponseFormat> validateGenerateVfModuleGroupName(String resourceSystemName, String description, int groupCounter) {
555         Either<String, ResponseFormat> validateGenerateGroupNameRes;
556         if (resourceSystemName != null && description != null && Pattern.compile(Constants.MODULE_DESC_PATTERN).matcher(description).matches()) {
557             final String fileName = description.replaceAll(GROUP_DELIMITER_REGEX, "\\.");
558             validateGenerateGroupNameRes = Either.left(String.format(Constants.MODULE_NAME_FORMAT, resourceSystemName, FilenameUtils.removeExtension(fileName), groupCounter));
559         } else {
560             validateGenerateGroupNameRes = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME));
561         }
562         return validateGenerateGroupNameRes;
563     }
564
565     Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNames(Map<String, GroupDefinition> groups, String resourceSystemName) {
566
567         Map<String, GroupDefinition> updatedNamesGroups = new HashMap<>();
568         Either<Map<String, GroupDefinition>, ResponseFormat> result = Either.left(updatedNamesGroups);
569         for (Entry<String, GroupDefinition> groupEntry : groups.entrySet()) {
570             GroupDefinition curGroup = groupEntry.getValue();
571             String groupType = curGroup.getType();
572             String groupName = groupEntry.getKey();
573             int counter;
574             String description;
575             Either<String, ResponseFormat> newGroupNameRes;
576             if (groupType.equals(Constants.DEFAULT_GROUP_VF_MODULE) && !Pattern.compile(Constants.MODULE_NEW_NAME_PATTERN).matcher(groupName).matches()) {
577
578                 if (Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(groupEntry.getKey()).matches()) {
579                     counter = Integer.parseInt(groupEntry.getKey().split(Constants.MODULE_NAME_DELIMITER)[1]);
580                     description = curGroup.getDescription();
581                 } else {
582                     counter = getNextVfModuleNameCounter(updatedNamesGroups);
583                     description = groupName;
584                 }
585                 newGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, description, counter);
586                 if (newGroupNameRes.isRight()) {
587                     log.debug("Failed to generate new vf module group name. Status is {} ", newGroupNameRes.right().value());
588                     loggerSupportability.log(LogLevel.INFO,LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML.getName(),StatusCode.ERROR.name(),"Failed to generate new vf module group name. Status is: "+newGroupNameRes.right().value());
589                     result = Either.right(newGroupNameRes.right().value());
590                     break;
591                 }
592                 groupName = newGroupNameRes.left().value();
593                 curGroup.setName(groupName);
594             }
595             updatedNamesGroups.put(groupName, curGroup);
596         }
597         return result;
598     }
599
600     public int getNextVfModuleNameCounter(Map<String, GroupDefinition> groups) {
601         int counter = 0;
602         if (groups != null && !groups.isEmpty()) {
603             counter = getNextVfModuleNameCounter(groups.values());
604         }
605         return counter;
606     }
607
608     public int getNextVfModuleNameCounter(Collection<GroupDefinition> groups) {
609         int counter = 0;
610         if (groups != null && !groups.isEmpty()) {
611             List<Integer> counters = groups.stream().filter(group -> Pattern.compile(Constants.MODULE_NEW_NAME_PATTERN).matcher(group.getName()).matches() || Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(group.getName()).matches())
612                     .map(group -> Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1])).collect(toList());
613             counter = (counters == null || counters.isEmpty()) ? 0 : counters.stream().max(Integer::compare).get() + 1;
614         }
615         return counter;
616     }
617
618     public Either<List<GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesOnGraph(List<GroupDefinition> groups, Component component) {
619         List<GroupDefinition> updatedGroups = new ArrayList<>();
620         Either<List<GroupDefinition>, ResponseFormat> result;
621
622         for (GroupDefinition group : groups) {
623             String groupType = group.getType();
624             String oldGroupName = group.getName();
625             String newGroupName;
626             Either<String, ResponseFormat> newGroupNameRes;
627             int counter;
628             if (groupType.equals(Constants.DEFAULT_GROUP_VF_MODULE) && Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(oldGroupName).matches()) {
629                 counter = Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1]);
630                 newGroupNameRes = validateGenerateVfModuleGroupName(component.getSystemName(), group.getDescription(), counter);
631                 if (newGroupNameRes.isRight()) {
632                     log.debug("Failed to generate new vf module group name. Status is {} ", newGroupNameRes.right().value());
633                     result = Either.right(newGroupNameRes.right().value());
634                     break;
635                 }
636                 newGroupName = newGroupNameRes.left().value();
637                 group.setName(newGroupName);
638
639             }
640             updatedGroups.add(group);
641
642         }
643
644         result = Either.left(updatedGroups);
645         return result;
646     }
647
648
649     public Either<GroupDefinitionInfo, ResponseFormat> getGroupInstWithArtifactsById(ComponentTypeEnum componentType, String componentId, String componentInstanceId, String groupInstId, String userId, boolean inTransaction) {
650         Either<GroupDefinitionInfo, ResponseFormat> result = null;
651
652         // Validate user exist
653         validateUserExists(userId);
654         // Validate component exist
655         org.openecomp.sdc.be.model.Component component;
656
657         try {
658             ComponentParametersView componentParametersView = new ComponentParametersView();
659             componentParametersView.disableAll();
660             componentParametersView.setIgnoreUsers(false);
661             componentParametersView.setIgnoreComponentInstances(false);
662             componentParametersView.setIgnoreArtifacts(false);
663
664             component = validateComponentExists(componentId, componentType, componentParametersView);
665             Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> findComponentInstanceAndGroupInstanceRes = findComponentInstanceAndGroupInstanceOnComponent(component, componentInstanceId, groupInstId);
666
667             if (findComponentInstanceAndGroupInstanceRes.isRight()) {
668                 log.debug("Failed to get group {} . Status is {} ", groupInstId, findComponentInstanceAndGroupInstanceRes.right().value());
669                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findComponentInstanceAndGroupInstanceRes.right().value()));
670                 result = Either.right(responseFormat);
671                 return result;
672             }
673
674             GroupInstance group = findComponentInstanceAndGroupInstanceRes.left().value().getRight();
675
676             Boolean isBase = isBaseProperty(component, group);
677
678             List<ArtifactDefinitionInfo> artifacts = new ArrayList<>();
679             List<String> artifactsIds = group.getArtifacts();
680             if (artifactsIds != null && !artifactsIds.isEmpty()) {
681
682                 List<ComponentInstance> instances = component.getComponentInstances();
683                 if (instances != null) {
684                     instances.stream().filter(i -> i.getUniqueId().equals(componentInstanceId))
685                             .findFirst()
686                             .ifPresent(f->getFirstComponentInstance(group, artifacts, artifactsIds, f));
687                 }
688             }
689             GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group);
690             resultInfo.setIsBase(isBase);
691             if (!artifacts.isEmpty()) {
692                 resultInfo.setArtifacts(artifacts);
693             }
694             result = Either.left(resultInfo);
695
696             return result;
697
698         } finally {
699             closeTransaction(inTransaction, result);
700         }
701     }
702
703     private void getFirstComponentInstance(GroupInstance group, List<ArtifactDefinitionInfo> artifacts, List<String> artifactsIds, ComponentInstance ci) {
704         Map<String, ArtifactDefinition> deploymentArtifacts = ci.getDeploymentArtifacts();
705         artifactsIds.forEach(id -> deploymentArtifacts.values().stream()
706                 .filter(a -> a.getUniqueId().equals(id))
707                 .findFirst()
708                 .ifPresent(g -> artifacts.add(new ArtifactDefinitionInfo(g))));
709
710         List<String> instArtifactsIds = group.getGroupInstanceArtifacts();
711         instArtifactsIds.forEach(id -> deploymentArtifacts.values()
712                 .stream()
713                 .filter(a -> a.getUniqueId().equals(id))
714                 .findFirst()
715                 .ifPresent(g -> artifacts.add(new ArtifactDefinitionInfo(g))));
716    }
717
718     private Boolean isBaseProperty(Component component, GroupInstance group) {
719
720         Boolean isBase = null;
721         List<? extends GroupProperty> props = group.convertToGroupInstancesProperties();
722         if (props != null && !props.isEmpty()) {
723             Optional<? extends GroupProperty> isBasePropOp = props.stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny();
724             if (isBasePropOp.isPresent()) {
725                 GroupProperty propIsBase = isBasePropOp.get();
726                 isBase = Boolean.parseBoolean(propIsBase.getValue());
727
728             } else {
729                 BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO);
730             }
731         }
732         return isBase;
733     }
734
735     private void closeTransaction(boolean inTransaction, Either<GroupDefinitionInfo, ResponseFormat> result) {
736         if (!inTransaction) {
737             if (result == null || result.isRight()) {
738                 log.debug("Going to execute rollback on create group.");
739                     janusGraphDao.rollback();
740             } else {
741                 log.debug("Going to execute commit on create group.");
742                     janusGraphDao.commit();
743             }
744         }
745     }
746
747     private Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> findComponentInstanceAndGroupInstanceOnComponent(Component component, String componentInstanceId, String groupInstId) {
748
749         Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> result = null;
750         if (CollectionUtils.isNotEmpty(component.getComponentInstances())) {
751             Optional<GroupInstance> foundGroup;
752             Optional<ComponentInstance> foundComponent = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstanceId)).findFirst();
753             if (foundComponent.isPresent() && CollectionUtils.isNotEmpty(foundComponent.get().getGroupInstances())) {
754                 foundGroup = foundComponent.get().getGroupInstances().stream().filter(gi -> gi.getUniqueId().equals(groupInstId)).findFirst();
755                 if (foundGroup.isPresent()) {
756                     result = Either.left(new ImmutablePair<>(foundComponent.get(), foundGroup.get()));
757                 }
758             }
759         }
760         if (result == null) {
761             result = Either.right(StorageOperationStatus.NOT_FOUND);
762         }
763         return result;
764     }
765
766     private Boolean validateMinMaxAndInitialCountPropertyLogic(Map<PropertyNames, String> newValues, Map<PropertyNames, String> currValues, Map<PropertyNames, String> parentValues) {
767
768         for (Entry<PropertyNames, String> entry : newValues.entrySet()) {
769             PropertyNames currPropertyName = entry.getKey();
770             if (currPropertyName == PropertyNames.MIN_INSTANCES) {
771                 String minValue = parentValues.get(PropertyNames.MIN_INSTANCES);
772                 String maxValue = getMaxValue(newValues, currValues);
773                 validateValueInRange(new ImmutablePair<>(currPropertyName, entry.getValue()), new ImmutablePair<>(PropertyNames.MIN_INSTANCES, minValue),
774                         new ImmutablePair<>(PropertyNames.MAX_INSTANCES, maxValue));
775             } else if (currPropertyName == PropertyNames.INITIAL_COUNT) {
776                 String minValue = newValues.containsKey(PropertyNames.MIN_INSTANCES) ? newValues.get(PropertyNames.MIN_INSTANCES) : currValues.get(PropertyNames.MIN_INSTANCES);
777                 String maxValue = newValues.containsKey(PropertyNames.MAX_INSTANCES) ? newValues.get(PropertyNames.MAX_INSTANCES) : currValues.get(PropertyNames.MAX_INSTANCES);
778                 validateValueInRange(new ImmutablePair<>(currPropertyName, entry.getValue()), new ImmutablePair<>(PropertyNames.MIN_INSTANCES, minValue),
779                         new ImmutablePair<>(PropertyNames.MAX_INSTANCES, maxValue));
780             } else if (currPropertyName == PropertyNames.MAX_INSTANCES) {
781                 String minValue = getMinValue(newValues, currValues);
782                 String maxValue = parentValues.get(PropertyNames.MAX_INSTANCES);
783                 validateValueInRange(new ImmutablePair<>(currPropertyName, entry.getValue()), new ImmutablePair<>(PropertyNames.MIN_INSTANCES, minValue),
784                         new ImmutablePair<>(PropertyNames.MAX_INSTANCES, maxValue));
785             }
786         }
787         return true;
788     }
789
790     private String getMaxValue(Map<PropertyNames, String> newValues, Map<PropertyNames, String> currValues) {
791         return newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MAX_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT);
792     }
793
794     private String getMinValue(Map<PropertyNames, String> newValues, Map<PropertyNames, String> currValues) {
795         return newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MIN_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT);
796     }
797
798     private Boolean validateValueInRange(ImmutablePair<PropertyNames, String> newValue, ImmutablePair<PropertyNames, String> min, ImmutablePair<PropertyNames, String> max) {
799         final String warnMessage = "Failed to validate {} as property value of {}. It must be not higher than {}, and not lower than {}.";
800         int newValueInt = parseIntValue(newValue.getValue(), newValue.getKey());
801         int minInt = parseIntValue(min.getValue(), min.getKey());
802         int maxInt = parseIntValue(max.getValue(), max.getKey());
803         if (newValueInt < 0 || minInt < 0 || maxInt < 0) {
804             throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY);
805         } else if (newValueInt < minInt || newValueInt > maxInt) {
806             log.debug(warnMessage, newValue.getValue(), newValue.getKey().getPropertyName(), min.getValue(), max.getValue());
807             throw new ByActionStatusComponentException(ActionStatus.INVALID_GROUP_MIN_MAX_INSTANCES_PROPERTY_VALUE, newValue.getKey().getPropertyName(),
808                     maxInt == Integer.MAX_VALUE ? Constants.UNBOUNDED : max.getValue(), min.getValue());
809         }
810         return true;
811     }
812
813     private int parseIntValue(String value, PropertyNames propertyName) {
814         int result;
815         if (propertyName == PropertyNames.MAX_INSTANCES) {
816             result = convertIfUnboundMax(value);
817         } else if (NumberUtils.isNumber(value)) {
818             result = Integer.parseInt(value);
819         } else {
820             result = -1;
821         }
822         return result;
823     }
824
825     /**
826      * validates received new property values and updates group instance in case of success
827      *
828      * @param oldGroupInstance
829      * @param newProperties
830      * @return
831      */
832     public Either<GroupInstance, ResponseFormat> validateAndUpdateGroupInstancePropertyValues(String componentId, String instanceId, GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties) {
833
834         Either<GroupInstance, ResponseFormat> actionResult = null;
835         Either<GroupInstance, StorageOperationStatus> updateGroupInstanceResult = null;
836         List<GroupInstanceProperty> validateRes = validateReduceGroupInstancePropertiesBeforeUpdate(oldGroupInstance, newProperties);
837         if (actionResult == null) {
838             List<GroupInstanceProperty> validatedReducedNewProperties = validateRes;
839             updateGroupInstanceResult = groupsOperation.updateGroupInstancePropertyValuesOnGraph(componentId, instanceId, oldGroupInstance, validatedReducedNewProperties);
840             if (updateGroupInstanceResult.isRight()) {
841                 log.debug("Failed to update group instance {} property values. ", oldGroupInstance.getName());
842                 actionResult = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateGroupInstanceResult.right().value())));
843             }
844         }
845         if (actionResult == null) {
846             actionResult = Either.left(updateGroupInstanceResult.left().value());
847         }
848         return actionResult;
849     }
850
851     private List<GroupInstanceProperty> validateReduceGroupInstancePropertiesBeforeUpdate(GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties) {
852
853         Boolean validationRes = null;
854         List<GroupInstanceProperty> actionResult = null;
855         Map<String, GroupInstanceProperty> existingProperties = oldGroupInstance.convertToGroupInstancesProperties().stream().collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p));
856         Map<PropertyNames, String> newPropertyValues = new EnumMap<>(PropertyNames.class);
857         List<GroupInstanceProperty> reducedProperties = new ArrayList<>();
858         String currPropertyName;
859         try {
860             for (GroupInstanceProperty currNewProperty : newProperties) {
861                 currPropertyName = currNewProperty.getName();
862                 validationRes = handleAndAddProperty(reducedProperties, newPropertyValues, currNewProperty, existingProperties.get(currPropertyName));
863             }
864             if (validationRes == null || validationRes) {
865                 Map<PropertyNames, String> existingPropertyValues = new EnumMap<>(PropertyNames.class);
866                 Map<PropertyNames, String> parentPropertyValues = new EnumMap<>(PropertyNames.class);
867                 fillValuesAndParentValuesFromExistingProperties(existingProperties, existingPropertyValues, parentPropertyValues);
868                 validationRes = validateMinMaxAndInitialCountPropertyLogic(newPropertyValues, existingPropertyValues, parentPropertyValues);
869             }
870             if (validationRes) {
871                 actionResult = reducedProperties;
872             }
873         } catch (Exception e) {
874             log.error("Exception occured during validation and reducing group instance properties. The message is {}", e.getMessage(), e);
875             throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
876         }
877         return actionResult;
878     }
879
880     private void fillValuesAndParentValuesFromExistingProperties(Map<String, GroupInstanceProperty> existingProperties, Map<PropertyNames, String> propertyValues, Map<PropertyNames, String> parentPropertyValues) {
881         PropertyNames[] allPropertyNames = PropertyNames.values();
882         for (PropertyNames name : allPropertyNames) {
883             if (isUpdatable(name)) {
884                 propertyValues.put(name, String.valueOf(existingProperties.get(name.getPropertyName()).getValue()));
885                 parentPropertyValues.put(name, String.valueOf(existingProperties.get(name.getPropertyName()).getParentValue()));
886             }
887         }
888     }
889
890     private Boolean handleAndAddProperty(List<GroupInstanceProperty> reducedProperties, Map<PropertyNames, String> newPropertyValues, GroupInstanceProperty currNewProperty, GroupInstanceProperty currExistingProperty) {
891
892         Boolean validationRes = null;
893         String currPropertyName = currNewProperty.getName();
894         PropertyNames propertyName = PropertyNames.findName(currPropertyName);
895         try {
896             if (currExistingProperty == null) {
897                 log.warn("The value of property with the name {} cannot be updated. The property not found on group instance. ", currPropertyName);
898             } else if (isUpdatable(propertyName)) {
899                 validationRes = validateAndUpdatePropertyValue(currNewProperty, currExistingProperty);
900                 addPropertyUpdatedValues(reducedProperties, propertyName, newPropertyValues, currNewProperty, currExistingProperty);
901             } else {
902                 validateImmutableProperty(currExistingProperty, currNewProperty);
903             }
904             if (validationRes == null) {
905                 validationRes = true;
906             }
907         } catch (Exception e) {
908             log.error("Exception occured during handle and adding property. The message is {}", e.getMessage(), e);
909         }
910         return validationRes;
911     }
912
913     private boolean isUpdatable(PropertyNames updatablePropertyName) {
914         return updatablePropertyName != null && updatablePropertyName.getUpdateBehavior().getLevelNumber() >= GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL.getLevelNumber();
915     }
916
917     private void addPropertyUpdatedValues(List<GroupInstanceProperty> reducedProperties, PropertyNames propertyName, Map<PropertyNames, String> newPropertyValues, GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) {
918
919         String newValue = newProperty.getValue();
920         if (!newValue.equals(String.valueOf(existingProperty.getValue()))) {
921             newProperty.setValueUniqueUid(existingProperty.getValueUniqueUid());
922             reducedProperties.add(newProperty);
923         }
924         if (!isEmptyMinInitialCountValue(propertyName, newValue)) {
925             newPropertyValues.put(propertyName, newValue);
926         }
927     }
928
929     private boolean isEmptyMinInitialCountValue(PropertyNames propertyName, String newValue) {
930         boolean result = false;
931         if ((propertyName == PropertyNames.MIN_INSTANCES || propertyName == PropertyNames.INITIAL_COUNT) && !NumberUtils.isNumber(newValue)) {
932             result = true;
933         }
934         return result;
935     }
936
937     private int convertIfUnboundMax(String value) {
938
939         int result;
940         if (!NumberUtils.isNumber(value)) {
941             result = Integer.MAX_VALUE;
942         } else {
943             result = Integer.parseInt(value);
944         }
945         return result;
946     }
947
948     private Boolean validateAndUpdatePropertyValue(GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) {
949
950         String parentValue = existingProperty.getParentValue();
951
952         newProperty.setParentValue(parentValue);
953         if (StringUtils.isEmpty(newProperty.getValue())) {
954             newProperty.setValue(parentValue);
955         }
956         if (StringUtils.isEmpty(existingProperty.getValue())) {
957             existingProperty.setValue(parentValue);
958         }
959         StorageOperationStatus status = groupOperation.validateAndUpdatePropertyValue(newProperty);
960         if (status != StorageOperationStatus.OK) {
961             log.debug("Failed to validate property value {} of property with name {}. Status is {}. ", newProperty.getValue(), newProperty.getName(), status);
962             throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status));
963         }
964         return true;
965     }
966
967     private void validateImmutableProperty(GroupProperty oldProperty, GroupProperty newProperty) {
968         if (oldProperty.getValue() == null && newProperty.getValue() != null || oldProperty.getValue() != null && !oldProperty.getValue().equals(newProperty.getValue())) {
969             log.warn("The value of property with the name {} cannot be updated on service level. Going to ignore new property value {}. ", oldProperty.getName(), newProperty.getValue());
970         }
971     }
972
973     @LockingTransactional
974     public GroupDefinition createGroup(String componentId, ComponentTypeEnum componentTypeEnum, String groupType,
975                                        String userId) {
976
977         Component component = accessValidations.validateUserCanWorkOnComponent(componentId, componentTypeEnum, userId, CREATE_GROUP);
978
979         validateGroupTypePerComponent(groupType, component);
980
981         GroupTypeDefinition groupTypeDefinition = groupTypeOperation.getLatestGroupTypeByType(groupType, false)
982                 .left()
983                 .on(se -> onGroupTypeNotFound(component));
984
985         boolean hasExistingGroups = CollectionUtils.isNotEmpty(component.getGroups());
986         GroupDefinition groupDefinition = new GroupDefinition();
987         groupDefinition.setType(groupType);
988
989         //find next valid counter
990         int nextCounter = 0;
991         if (hasExistingGroups) {
992             nextCounter = getNewGroupCounter(component);
993         }
994         String name = TopologyTemplateOperation.buildSubComponentName(component.getName(), groupType, nextCounter);
995         groupDefinition.setName(name);
996         groupDefinition.setDescription(groupTypeDefinition.getDescription());
997         groupDefinition.setInvariantName(name);
998         groupDefinition.setCreatedFrom(CreatedFrom.UI);
999
1000         //Add default type properties
1001         List<PropertyDefinition> groupTypeProperties = groupTypeDefinition.getProperties();
1002         List<GroupProperty> properties = groupTypeProperties.stream()
1003                 .map(GroupProperty::new)
1004                 .collect(toList());
1005         groupDefinition.convertFromGroupProperties(properties);
1006
1007         groupDefinition.convertCapabilityDefinitions(groupTypeDefinition.getCapabilities());
1008
1009         List<GroupDefinition> gdList;
1010         if (toscaOperationFacade.canAddGroups(componentId)) {
1011             gdList = addGroups(component, Arrays.asList(groupDefinition), false)
1012                     .left()
1013                     .on(this::onFailedGroupDBOperation);
1014         } else {
1015             //createGroups also creates an edge and vertex to store group data
1016             gdList = createGroups(component, Arrays.asList(groupDefinition), false)
1017                     .left()
1018                     .on(this::onFailedGroupDBOperation);
1019         }
1020         return gdList.get(0);
1021     }
1022
1023     private void validateGroupTypePerComponent(String groupType, Component component) {
1024         String specificType = component.getComponentMetadataDefinition().getMetadataDataDefinition().getActualComponentType();
1025         if (!component.isTopologyTemplate()) {
1026             throw new ByActionStatusComponentException(ActionStatus.GROUP_TYPE_ILLEGAL_PER_COMPONENT, groupType,
1027                     specificType);
1028         }
1029         Map<String, Set<String>> excludedGroupTypesMap = ConfigurationManager.getConfigurationManager().getConfiguration()
1030                 .getExcludedGroupTypesMapping();
1031
1032         if (MapUtils.isNotEmpty(excludedGroupTypesMap) && StringUtils.isNotEmpty(specificType)) {
1033             Set<String> excludedGroupTypesPerComponent = excludedGroupTypesMap.get(specificType);
1034             if (excludedGroupTypesPerComponent!=null && excludedGroupTypesPerComponent.contains(groupType)) {
1035                 throw new ByActionStatusComponentException(ActionStatus.GROUP_TYPE_ILLEGAL_PER_COMPONENT, groupType, specificType);
1036             }
1037         }
1038     }
1039
1040     private int getNewGroupCounter(Component component) {
1041         List<String> existingNames = component.getGroups()
1042                 .stream()
1043                 .map(GroupDataDefinition::getInvariantName)
1044                 .collect(toList());
1045         List<String> existingIds = component.getGroups()
1046                 .stream()
1047                 .map(GroupDataDefinition::getUniqueId)
1048                 .collect(toList());
1049         existingIds.addAll(existingNames);
1050
1051         return Utils.getNextCounter(existingIds);
1052     }
1053
1054     @LockingTransactional
1055     public GroupDefinition updateGroup(String componentId, ComponentTypeEnum componentTypeEnum, String groupId,
1056                                        String userId, GroupDefinition updatedGroup) {
1057         Component component = accessValidations.validateUserCanWorkOnComponent(componentId, componentTypeEnum, userId, UPDATE_GROUP);
1058
1059         GroupDefinition existingGroup = findGroupOnComponent(component, groupId)
1060                 .left()
1061                 .on(se -> onGroupNotFoundInComponentError(component, groupId));
1062
1063         String existingGroupName = existingGroup.getName();
1064         String updatedGroupName = updatedGroup.getName();
1065         assertNewNameIsValidAndUnique(existingGroupName, updatedGroupName, component);
1066         existingGroup.setName(updatedGroupName);
1067
1068         return updateGroup(component, existingGroup, existingGroupName)
1069                 .left()
1070                 .on(this::onFailedUpdateGroupDBOperation);
1071     }
1072
1073     private void assertNewNameIsValidAndUnique(String currentGroupName, String updatedGroupName, Component component) {
1074         if (!ValidationUtils.validateResourceInstanceNameLength(updatedGroupName)) {
1075             throw new ByActionStatusComponentException(ActionStatus.EXCEEDS_LIMIT, "Group Name", ValidationUtils.RSI_NAME_MAX_LENGTH.toString());
1076         }
1077         if (!ValidationUtils.validateResourceInstanceName(updatedGroupName)) {
1078             throw new ByActionStatusComponentException(ActionStatus.INVALID_VF_MODULE_NAME, updatedGroupName);
1079         }
1080         if (!ComponentValidations.validateNameIsUniqueInComponent(currentGroupName, updatedGroupName, component)) {
1081             throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, "Group", updatedGroupName);
1082         }
1083     }
1084
1085     @LockingTransactional
1086     public GroupDefinition deleteGroup(String componentId, ComponentTypeEnum componentTypeEnum, String groupId,
1087                                        String userId) {
1088         Component component = accessValidations.validateUserCanWorkOnComponent(componentId, componentTypeEnum, userId, DELETE_GROUP);
1089
1090         GroupDefinition groupDefinition = findGroupOnComponent(component, groupId)
1091                 .left()
1092                 .on(se -> onGroupNotFoundInComponentError(component, groupId));
1093
1094         List<GroupDefinition> gdList = deleteGroups(component, java.util.Arrays.asList(groupDefinition))
1095                 .left()
1096                 .on(this::onFailedGroupDBOperation);
1097
1098         updatePolicyTargetReferencingDeletedGroup(groupId, component);
1099         return gdList.get(0);
1100     }
1101
1102     private List<GroupDefinition> onFailedGroupDBOperation(ResponseFormat responseFormat) {
1103         janusGraphDao.rollback();
1104         throw new ByResponseFormatComponentException(responseFormat);
1105     }
1106
1107     private GroupDefinition onFailedUpdateGroupDBOperation(ResponseFormat responseFormat) {
1108         janusGraphDao.rollback();
1109         throw new ByResponseFormatComponentException(responseFormat);
1110     }
1111
1112     private GroupDefinition onGroupNotFoundInComponentError(Component component, String groupId) {
1113         throw new ByActionStatusComponentException(ActionStatus.GROUP_IS_MISSING, groupId,
1114                 component.getSystemName(), getComponentTypeForResponse(component));
1115     }
1116
1117     private GroupTypeDefinition onGroupTypeNotFound(Component component) {
1118         throw new ByActionStatusComponentException(ActionStatus.GROUP_TYPE_IS_INVALID, component.getSystemName(),
1119                 component.getComponentType().toString());
1120     }
1121
1122     private void updatePolicyTargetReferencingDeletedGroup(String groupId, Component component) {
1123         log.debug("#updatePolicyTargetReferencingDeletedGroup - removing all component {} policy targets referencing group {}", component.getUniqueId(), groupId);
1124         ActionStatus actionStatus = policyTargetsUpdateHandler.removePoliciesTargets(component, groupId, PolicyTargetType.GROUPS);
1125         if (ActionStatus.OK != actionStatus) {
1126             janusGraphDao.rollback();
1127             throw new ByActionStatusComponentException(actionStatus, groupId);
1128         }
1129     }
1130
1131
1132     public Either<List<GroupDefinition>, ResponseFormat> createGroups(Component component, final List<GroupDefinition> groupDefinitions, boolean fromCsar) {
1133
1134         Map<String, GroupDataDefinition> groups = new HashMap<>();
1135         Either<List<GroupDefinition>, ResponseFormat> result = null;
1136         Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult = null;
1137         Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll();
1138         if (allDataTypes.isRight()) {
1139             JanusGraphOperationStatus status = allDataTypes.right().value();
1140             BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR);
1141             return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))));
1142
1143         }
1144
1145         // handle groups and convert to tosca data
1146         if (groupDefinitions != null && !groupDefinitions.isEmpty()) {
1147             for (GroupDefinition groupDefinition : groupDefinitions) {
1148                 Either<GroupDefinition, ResponseFormat> handleGroupRes = handleGroup(component, groupDefinition, allDataTypes.left().value());
1149                 if (handleGroupRes.isRight()) {
1150                     result = Either.right(handleGroupRes.right().value());
1151                     break;
1152                 }
1153                 GroupDefinition handledGroup = handleGroupRes.left().value();
1154                 groups.put(handledGroup.getInvariantName(), new GroupDataDefinition(handledGroup));
1155
1156             }
1157         }
1158         if (result == null) {
1159             createGroupsResult = groupsOperation.createGroups(component, groups);
1160             if (createGroupsResult.isRight()) {
1161                 result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value())));
1162             }
1163         }
1164         if (result == null) {
1165             addCalculatedCapabilitiesWithPropertiesToComponent(component, groupDefinitions, fromCsar);
1166         }
1167         if (result == null) {
1168             result = Either.left(groupDefinitions);
1169         }
1170         component.setGroups(groupDefinitions);
1171         return result;
1172     }
1173
1174     private void updateCalculatedCapabilitiesWithPropertiesOnComponent(Component component, final List<GroupDefinition> groupDefinitions, boolean fromCsar) {
1175         groupDefinitions.forEach(GroupDefinition::updateEmptyCapabilitiesOwnerFields);
1176         StorageOperationStatus status = groupsOperation.updateCalculatedCapabilitiesWithProperties(component.getUniqueId(),
1177                 extractCapabilitiesFromGroups(groupDefinitions), extractCapabilityPropertiesFromGroups(groupDefinitions, fromCsar));
1178         if(status != StorageOperationStatus.OK){
1179             log.error("#updateCalculatedCapabilitiesWithPropertiesOnComponent - failed to update the groups' calculated capabilities with the properties on the component {}. ", component.getUniqueId());
1180             rollbackWithException(componentsUtils.convertFromStorageResponse(status));
1181         }
1182     }
1183
1184     private void addCalculatedCapabilitiesWithPropertiesToComponent(Component component, final List<GroupDefinition> groupDefinitions, boolean fromCsar) {
1185         groupDefinitions.forEach(GroupDefinition::updateEmptyCapabilitiesOwnerFields);
1186         StorageOperationStatus status = groupsOperation.addCalculatedCapabilitiesWithProperties(component.getUniqueId(),
1187                 extractCapabilitiesFromGroups(groupDefinitions), extractCapabilityPropertiesFromGroups(groupDefinitions, fromCsar));
1188         if(status != StorageOperationStatus.OK){
1189             log.error("#addCalculatedCapabilitiesWithPropertiesToComponent - failed to add the groups' calculated capabilities with the properties to the component {}. ", component.getUniqueId());
1190             rollbackWithException(componentsUtils.convertFromStorageResponse(status));
1191         }
1192     }
1193
1194     private void deleteCalculatedCapabilitiesWithPropertiesFromComponent(Component component, final List<GroupDefinition> groupDefinitions) {
1195         StorageOperationStatus status = groupsOperation.deleteCalculatedCapabilitiesWithProperties(component.getUniqueId(), groupDefinitions);
1196         if(status != StorageOperationStatus.OK){
1197             log.error("#deleteCalculatedCapabilitiesWithPropertiesFromComponent - failed to remove the groups' calculated capabilities with the properties from the component {}. ", component.getUniqueId());
1198             rollbackWithException(componentsUtils.convertFromStorageResponse(status));
1199         }
1200     }
1201
1202     public Either<List<GroupDefinition>, ResponseFormat> addGroups(Component component, final List<GroupDefinition> groupDefinitions, boolean fromCsar) {
1203
1204         Either<List<GroupDefinition>, ResponseFormat> result = null;
1205         Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult = null;
1206         List<GroupDataDefinition> groups = new ArrayList<>();
1207
1208         Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll();
1209         if (allDataTypes.isRight()) {
1210             JanusGraphOperationStatus status = allDataTypes.right().value();
1211             BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR);
1212             return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))));
1213
1214         }
1215
1216         // handle groups and convert to tosca data
1217         if (groupDefinitions != null && !groupDefinitions.isEmpty()) {
1218             for (GroupDefinition groupDefinition : groupDefinitions) {
1219                 Either<GroupDefinition, ResponseFormat> handleGroupRes = handleGroup(component, groupDefinition, allDataTypes.left().value());
1220                 if (handleGroupRes.isRight()) {
1221                     result = Either.right(handleGroupRes.right().value());
1222                     break;
1223                 }
1224                 GroupDefinition handledGroup = handleGroupRes.left().value();
1225                 groups.add(new GroupDataDefinition(handledGroup));
1226             }
1227         }
1228         if (result == null) {
1229             createGroupsResult = groupsOperation.addGroups(component, groups);
1230             if (createGroupsResult.isRight()) {
1231                 result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value())));
1232             }
1233             component.addGroups(createGroupsResult.left().value());
1234         }
1235         if (result == null) {
1236             addCalculatedCapabilitiesWithPropertiesToComponent(component, groupDefinitions, fromCsar);
1237         }
1238         if (result == null) {
1239             result = Either.left(groupDefinitions);
1240         }
1241         return result;
1242     }
1243
1244     public Either<List<GroupDefinition>, ResponseFormat> deleteGroups(Component component, List<GroupDefinition> groupDefinitions) {
1245
1246         Either<List<GroupDefinition>, StorageOperationStatus> deleteGroupsResult;
1247
1248         deleteGroupsResult = groupsOperation.deleteGroups(component, groupDefinitions.stream().map(GroupDataDefinition::new).collect(toList()));
1249         if (deleteGroupsResult.isRight()) {
1250             return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteGroupsResult.right().value())));
1251         } else {
1252             deleteCalculatedCapabilitiesWithPropertiesFromComponent(component, groupDefinitions);
1253         }
1254         if (component.getGroups()!=null) {
1255             component.getGroups().removeAll(deleteGroupsResult.left().value());
1256         }
1257         return Either.left(deleteGroupsResult.left().value());
1258     }
1259
1260     /**
1261      * Update specific group version
1262      * @param fromCsar TODO
1263      *
1264      */
1265     public Either<List<GroupDefinition>, ResponseFormat> updateGroups(Component component, List<GroupDefinition> groupDefinitions, boolean fromCsar) {
1266
1267         Either<List<GroupDefinition>, ResponseFormat> result = null;
1268         Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult;
1269
1270         createGroupsResult = groupsOperation.updateGroups(component, groupDefinitions.stream().map(GroupDataDefinition::new).collect(toList()), PromoteVersionEnum.MINOR);
1271         if (createGroupsResult.isRight()) {
1272             result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value())));
1273         }
1274         if (result == null) {
1275             updateCalculatedCapabilitiesWithPropertiesOnComponent(component, groupDefinitions, fromCsar);
1276         }
1277         if (result == null) {
1278             result = Either.left(groupDefinitions);
1279         }
1280         return result;
1281     }
1282
1283     private Either<GroupDefinition, ResponseFormat> handleGroup(Component component, GroupDefinition groupDefinition, Map<String, DataTypeDefinition> allDAtaTypes) {
1284
1285         log.trace("Going to create group {}", groupDefinition);
1286         loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY,component.getComponentMetadataForSupportLog(),StatusCode.STARTED,"Start to create group: {}",groupDefinition.getName()+ " for component " + component.getName());
1287         // 3. verify group not already exist
1288         String groupDefinitionName = groupDefinition.getName();
1289         if (groupExistsInComponent(groupDefinitionName, component)) {
1290             String componentTypeForResponse = getComponentTypeForResponse(component);
1291             return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ALREADY_EXIST, groupDefinitionName, component.getNormalizedName(), componentTypeForResponse));
1292         }
1293         // 4. verify type of group exist
1294         String groupType = groupDefinition.getType();
1295         if (StringUtils.isEmpty(groupType)) {
1296             return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_MISSING_GROUP_TYPE, groupDefinitionName));
1297         }
1298         Either<GroupTypeDefinition, StorageOperationStatus> getGroupType = groupTypeOperation.getLatestGroupTypeByType(groupType, true);
1299         if (getGroupType.isRight()) {
1300             StorageOperationStatus status = getGroupType.right().value();
1301             if (status == StorageOperationStatus.NOT_FOUND) {
1302                 loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY,component.getComponentMetadataForSupportLog(), StatusCode.ERROR,"group {} cannot be found",groupDefinition.getName());
1303                 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "group type " + groupType + " cannot be found", ErrorSeverity.INFO);
1304                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, groupType));
1305             } else {
1306                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1307             }
1308         }
1309         // 6. verify the component instances type are allowed according to
1310         // the member types in the group type
1311         GroupTypeDefinition groupTypeDefinition = getGroupType.left().value();
1312
1313         Either<Boolean, ResponseFormat> areValidMembers = verifyComponentInstancesAreValidMembers(component, groupDefinitionName, groupDefinition.getMembers(), groupTypeDefinition.getMembers());
1314
1315         if (areValidMembers.isRight()) {
1316             ResponseFormat responseFormat = areValidMembers.right().value();
1317             return Either.right(responseFormat);
1318         }
1319         // 7. verify the artifacts belongs to the component
1320         Either<Boolean, ResponseFormat> areValidArtifacts = verifyArtifactsBelongsToComponent(component, groupDefinition.getArtifacts(), CREATE_GROUP);
1321         if (areValidArtifacts.isRight()) {
1322             ResponseFormat responseFormat = areValidArtifacts.right().value();
1323             return Either.right(responseFormat);
1324         }
1325         List<PropertyDefinition> groupTypeProperties = groupTypeDefinition.getProperties();
1326
1327         List<GroupProperty> properties = groupDefinition.convertToGroupProperties();
1328         List<GroupProperty> updatedGroupTypeProperties = new ArrayList<>();
1329         if (CollectionUtils.isNotEmpty(properties)) {
1330             if (CollectionUtils.isEmpty(groupTypeProperties)) {
1331                 BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "group type does not have properties", ErrorSeverity.INFO);
1332                 loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY,component.getComponentMetadataForSupportLog(), StatusCode.ERROR,"group {} does not have properties ",groupDefinition.getName());
1333                 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.MATCH_NOT_FOUND))));
1334             }
1335
1336             Map<String, PropertyDefinition> groupTypePropertiesMap = groupTypeProperties.stream().collect(Collectors.toMap(PropertyDefinition::getName, p -> p));
1337
1338             Either<GroupProperty, JanusGraphOperationStatus> addPropertyResult;
1339             int i = 1;
1340             for (GroupProperty prop : properties) {
1341                 addPropertyResult = handleProperty(prop, groupTypePropertiesMap.get(prop.getName()), i, allDAtaTypes, groupType);
1342                 if (addPropertyResult.isRight()) {
1343                     BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "failed to validate property", ErrorSeverity.INFO);
1344                     return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(addPropertyResult.right().value()))));
1345                 }
1346                 updatedGroupTypeProperties.add(addPropertyResult.left().value());
1347
1348                 i++;
1349             }
1350         }
1351
1352         if (groupDefinition.getUniqueId() == null) {
1353             String uid = UniqueIdBuilder.buildGroupingUid(component.getUniqueId(), groupDefinitionName);
1354             groupDefinition.setUniqueId(uid);
1355         }
1356         groupDefinition.convertFromGroupProperties(updatedGroupTypeProperties);
1357         groupDefinition.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
1358         groupDefinition.setGroupUUID(UniqueIdBuilder.generateUUID());
1359         groupDefinition.setVersion(INITIAL_VERSION);
1360         groupDefinition.setTypeUid(groupTypeDefinition.getUniqueId());
1361         loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY,component.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,"group {} has been created ",groupDefinition.getName());
1362         return Either.left(groupDefinition);
1363     }
1364
1365     private static boolean groupExistsInComponent(String groupDefinitionName, Component component) {
1366         boolean found = false;
1367         List<GroupDefinition> groups = component.getGroups();
1368         if (CollectionUtils.isNotEmpty(groups)) {
1369             found = groups.stream().filter(p -> (p.getName().equalsIgnoreCase(groupDefinitionName))
1370                     || p.getInvariantName().equalsIgnoreCase(groupDefinitionName))
1371                     .findFirst().orElse(null) != null;
1372         }
1373         return found;
1374     }
1375
1376     private Either<GroupProperty, JanusGraphOperationStatus> handleProperty(GroupProperty groupProperty, PropertyDefinition prop, Integer index, Map<String, DataTypeDefinition> allDataTypes, String groupType) {
1377
1378         if (prop == null) {
1379             return Either.right(JanusGraphOperationStatus.ILLEGAL_ARGUMENT);
1380         }
1381
1382         String propertyType = prop.getType();
1383         String value = groupProperty.getValue();
1384
1385         Either<String, JanusGraphOperationStatus> checkInnerType = propertyOperation.checkInnerType(prop);
1386         if (checkInnerType.isRight()) {
1387             JanusGraphOperationStatus status = checkInnerType.right().value();
1388             return Either.right(status);
1389         }
1390
1391         String innerType = checkInnerType.left().value();
1392
1393         log.debug("Before validateAndUpdatePropertyValue");
1394         Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes);
1395         log.debug("After validateAndUpdatePropertyValue. isValid = {}", isValid);
1396
1397         String newValue = value;
1398         if (isValid.isRight()) {
1399             Boolean res = isValid.right().value();
1400             if (!res) {
1401                 return Either.right(JanusGraphOperationStatus.ILLEGAL_ARGUMENT);
1402             }
1403         } else {
1404             Object object = isValid.left().value();
1405             if (object != null) {
1406                 newValue = object.toString();
1407             }
1408         }
1409
1410         String uniqueId = shouldReconstructUniqueId(groupType) ? UniqueIdBuilder.buildGroupPropertyValueUid(prop.getUniqueId(), index)
1411                 : prop.getUniqueId();
1412
1413         groupProperty.setUniqueId(uniqueId);
1414         groupProperty.setValue(newValue);
1415         groupProperty.setType(prop.getType());
1416         groupProperty.setDefaultValue(prop.getDefaultValue());
1417         groupProperty.setDescription(prop.getDescription());
1418         groupProperty.setSchema(prop.getSchema());
1419         groupProperty.setPassword(prop.isPassword());
1420         groupProperty.setParentUniqueId(prop.getUniqueId());
1421
1422         log.debug("Before adding property value to graph {}", groupProperty);
1423
1424         return Either.left(groupProperty);
1425     }
1426
1427     // For old groups we want to leave indexing of property
1428     // For new groups we just need the types
1429     private boolean shouldReconstructUniqueId(String groupType) {
1430         return Constants.GROUP_TOSCA_HEAT.equals(groupType) || Constants.DEFAULT_GROUP_VF_MODULE.equals(groupType);
1431     }
1432
1433 }