[SDC-29] rebase continue work to align source
[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  */
20
21 package org.openecomp.sdc.be.components.impl;
22
23 import java.io.IOException;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.EnumMap;
28 import java.util.HashMap;
29 import java.util.HashSet;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Map.Entry;
33 import java.util.Optional;
34 import java.util.Set;
35 import java.util.function.Function;
36 import java.util.regex.Pattern;
37 import java.util.stream.Collectors;
38
39 import org.apache.commons.collections.CollectionUtils;
40 import org.apache.commons.collections.MapUtils;
41 import org.apache.commons.io.FilenameUtils;
42 import org.apache.commons.lang.StringUtils;
43 import org.apache.commons.lang3.math.NumberUtils;
44 import org.apache.commons.lang3.tuple.ImmutablePair;
45 import org.codehaus.jackson.JsonGenerationException;
46 import org.codehaus.jackson.map.JsonMappingException;
47 import org.openecomp.sdc.be.config.BeEcompErrorManager;
48 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
49 import org.openecomp.sdc.be.dao.api.ActionStatus;
50 import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils;
51 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
52 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
53 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
54 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
55 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
56 import org.openecomp.sdc.be.info.ArtifactDefinitionInfo;
57 import org.openecomp.sdc.be.info.ArtifactTemplateInfo;
58 import org.openecomp.sdc.be.info.GroupDefinitionInfo;
59 import org.openecomp.sdc.be.model.ArtifactDefinition;
60 import org.openecomp.sdc.be.model.Component;
61 import org.openecomp.sdc.be.model.ComponentInstance;
62 import org.openecomp.sdc.be.model.ComponentParametersView;
63 import org.openecomp.sdc.be.model.DataTypeDefinition;
64 import org.openecomp.sdc.be.model.GroupDefinition;
65 import org.openecomp.sdc.be.model.GroupInstance;
66 import org.openecomp.sdc.be.model.GroupInstanceProperty;
67 import org.openecomp.sdc.be.model.GroupProperty;
68 import org.openecomp.sdc.be.model.GroupTypeDefinition;
69 import org.openecomp.sdc.be.model.PropertyDefinition;
70 import org.openecomp.sdc.be.model.PropertyDefinition.GroupInstancePropertyValueUpdateBehavior;
71 import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames;
72 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
73 import org.openecomp.sdc.be.model.jsontitan.operations.ArtifactsOperations;
74 import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation;
75 import org.openecomp.sdc.be.model.Resource;
76 import org.openecomp.sdc.be.model.User;
77 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
78 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
79 import org.openecomp.sdc.be.model.operations.impl.GroupOperation;
80 import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation;
81 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
82 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
83 import org.openecomp.sdc.common.api.Constants;
84 import org.openecomp.sdc.exception.ResponseFormat;
85 import org.slf4j.Logger;
86 import org.slf4j.LoggerFactory;
87 import org.springframework.beans.factory.annotation.Autowired;
88
89 import com.google.gson.Gson;
90 import com.google.gson.GsonBuilder;
91 import com.google.gson.JsonSyntaxException;
92
93 import fj.data.Either;
94
95 @org.springframework.stereotype.Component("groupBusinessLogic")
96 public class GroupBusinessLogic extends BaseBusinessLogic {
97         private static String ADDING_GROUP = "AddingGroup";
98
99         public static final String INITIAL_VERSION = "1";
100
101         private static final String CREATE_GROUP = "CreateGroup";
102
103         private static final String UPDATE_GROUP = "UpdateGroup";
104
105         private static final String GET_GROUP = "GetGroup";
106
107         private static Logger log = LoggerFactory.getLogger(GroupBusinessLogic.class.getName());
108
109         public GroupBusinessLogic() {
110
111         }
112
113         @javax.annotation.Resource
114         private GroupTypeOperation groupTypeOperation;
115
116         @Autowired
117         ArtifactsOperations artifactsOperation;
118
119         @Autowired
120         private GroupsOperation groupsOperation;
121         @Autowired
122         private ApplicationDataTypeCache dataTypeCache;
123
124         /**
125          * 
126          * 1. validate user exist
127          * 
128          * 2. validate component can be edited
129          * 
130          * 3. verify group not already exist
131          * 
132          * 4. verify type of group exist
133          * 
134          * 5. verify Component instances exist under the component
135          * 
136          * 6. verify the component instances type are allowed according to the member types in the group type
137          * 
138          * 7. verify the artifacts belongs to the component
139          * 
140          * @param componentId
141          * @param userId
142          * @param componentType
143          * @param groupDefinition
144          * @param inTransaction
145          * @return
146          */
147         /*
148          * public Either<GroupDefinition, ResponseFormat> createGroup(String componentId, String userId, ComponentTypeEnum componentType, GroupDefinition groupDefinition, boolean inTransaction) {
149          * 
150          * Either<GroupDefinition, ResponseFormat> result = null;
151          * 
152          * try { Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, CREATE_GROUP, inTransaction);
153          * 
154          * if (validateUserExists.isRight()) { result = Either.right(validateUserExists.right().value()); return result; }
155          * 
156          * User user = validateUserExists.left().value(); // 5. check service/resource existence // 6. check service/resource check out // 7. user is owner of checkout state org.openecomp.sdc.be.model.Component component = null;
157          * 
158          * // String realComponentId = componentType == // ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId; String realComponentId = componentId;
159          * 
160          * ComponentParametersView componentParametersView = new ComponentParametersView(); componentParametersView.disableAll(); componentParametersView.setIgnoreGroups(false); componentParametersView.setIgnoreArtifacts(false);
161          * componentParametersView.setIgnoreUsers(false); componentParametersView.setIgnoreComponentInstances(false);
162          * 
163          * Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView);
164          * 
165          * if (validateComponent.isRight()) { result = Either.right(validateComponent.right().value()); return result; } component = validateComponent.left().value(); Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component,
166          * userId); if (canWork.isRight()) { result = Either.right(canWork.right().value()); return result; }
167          * 
168          * result = this.createGroup(component, user, componentType, groupDefinition, inTransaction); return result;
169          * 
170          * } finally {
171          * 
172          * if (false == inTransaction) {
173          * 
174          * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); }
175          * 
176          * }
177          * 
178          * } }
179          */
180
181         private String getComponentTypeForResponse(org.openecomp.sdc.be.model.Component component) {
182                 String componentTypeForResponse = "SERVICE";
183                 if (component instanceof Resource) {
184                         componentTypeForResponse = ((Resource) component).getResourceType().name();
185                 }
186                 return componentTypeForResponse;
187         }
188
189         /**
190          * Verify that the artifact members belongs to the component
191          * 
192          * @param component
193          * @param artifacts
194          * @return
195          */
196         private Either<Boolean, ResponseFormat> verifyArtifactsBelongsToComponent(Component component, List<String> artifacts, String context) {
197
198                 if (artifacts == null || true == artifacts.isEmpty()) {
199                         return Either.left(true);
200                 }
201
202                 Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts();
203                 if (deploymentArtifacts == null || true == deploymentArtifacts.isEmpty()) {
204                         BeEcompErrorManager.getInstance().logInvalidInputError(context, "No deployment artifact found under component " + component.getNormalizedName(), ErrorSeverity.INFO);
205                         return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
206                 }
207
208                 List<String> currentArtifacts = deploymentArtifacts.values().stream().map(p -> p.getUniqueId()).collect(Collectors.toList());
209                 log.debug("The deployment artifacts of component {} are {}", component.getNormalizedName(), deploymentArtifacts);
210                 if (false == currentArtifacts.containsAll(artifacts)) {
211                         BeEcompErrorManager.getInstance().logInvalidInputError(context, "Not all artifacts belongs to component " + component.getNormalizedName(), ErrorSeverity.INFO);
212                         return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
213                 }
214
215                 return Either.left(true);
216
217         }
218
219         /**
220          * verify that the members are component instances of the component
221          * 
222          * @param component
223          * @param componentType
224          * @param groupMembers
225          * @param memberToscaTypes
226          * @return
227          */
228         private Either<Boolean, ResponseFormat> verifyComponentInstancesAreValidMembers(Component component, ComponentTypeEnum componentType, String groupName, String groupType, Map<String, String> groupMembers, List<String> memberToscaTypes) {
229
230                 if (groupMembers == null || true == groupMembers.isEmpty()) {
231                         return Either.left(true);
232                 }
233
234                 if (memberToscaTypes == null || true == memberToscaTypes.isEmpty()) {
235                         return Either.left(true);
236                 }
237
238                 List<ComponentInstance> componentInstances = component.getComponentInstances();
239                 if (componentInstances != null && false == componentInstances.isEmpty()) {
240                         Map<String, ComponentInstance> compInstUidToCompInstMap = componentInstances.stream().collect(Collectors.toMap(p -> p.getUniqueId(), p -> p));
241
242                         Set<String> allCompInstances = compInstUidToCompInstMap.keySet();
243
244                         for (Entry<String, String> groupMember : groupMembers.entrySet()) {
245                                 String compName = groupMember.getKey();
246                                 String compUid = groupMember.getValue();
247
248                                 if (false == allCompInstances.contains(compUid)) {
249                                         /*
250                                          * %1 - member name %2 - group name %3 - VF name %4 - component type [VF ]
251                                          */
252                                         String componentTypeForResponse = getComponentTypeForResponse(component);
253
254                                         BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "Not all group members exists under the component", ErrorSeverity.INFO);
255                                         return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, compName, groupName, component.getNormalizedName(), componentTypeForResponse));
256                                 }
257                         }
258
259                         // ComponentOperation componentOperation = getComponentOperationByParentComponentType(componentType);
260                         // if (componentOperation instanceof ResourceOperation) {
261                         // ResourceOperation resourceOperation = (ResourceOperation) componentOperation;
262                         //
263                         // for (Entry<String, String> groupMember : groupMembers.entrySet()) {
264                         //
265                         // String componentInstName = groupMember.getKey();
266                         // String componentInstUid = groupMember.getValue();
267                         //
268                         // ComponentInstance componentInstance = compInstUidToCompInstMap.get(componentInstUid);
269                         // String componentUid = componentInstance.getComponentUid();
270                         // List<String> componentToscaNames = new ArrayList<>();
271                         // TitanOperationStatus status = resourceOperation.fillResourceDerivedListFromGraph(componentUid, componentToscaNames);
272                         // if (status != TitanOperationStatus.OK) {
273                         // BeEcompErrorManager.getInstance().logInternalFlowError(CREATE_GROUP, "Cannot find tosca list of component id " + componentUid, ErrorSeverity.ERROR);
274                         // return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
275                         // }
276                         //
277                         // log.debug("The tosca names of component id {} are {}", componentUid, memberToscaTypes);
278                         //
279                         // boolean found = false;
280                         // for (String memberToscaType : memberToscaTypes) {
281                         // if (componentToscaNames.contains(memberToscaType)) {
282                         // found = true;
283                         // break;
284                         // }
285                         // }
286                         // if (found == false) {
287                         // BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP,
288                         // "No tosca types from " + memberToscaTypes + " can be found in the tosca list " + componentToscaNames + " of component " + componentInstance.getNormalizedName(), ErrorSeverity.INFO);
289                         // /*
290                         // * # %1 - member name # %2 - group name # %3 - group type
291                         // */
292                         // return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_TOSCA_NAME_OF_COMPONENT_INSTANCE, componentInstName, groupName, groupType));
293                         // } else {
294                         // log.debug("Component instance {} fits to one of the required tosca types", componentInstance.getNormalizedName());
295                         // }
296                         // }
297                         // } else {
298                         // BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "Cannot find tosca list since it is not supported for product", ErrorSeverity.ERROR);
299                         // return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
300                         // }
301
302                 }
303
304                 return Either.left(true);
305         }
306
307         /**
308          * Update specific group version
309          * 
310          * @param groupDefinition
311          * @param inTransaction
312          * @return
313          */
314         /*
315          * public Either<GroupDefinition, StorageOperationStatus> updateGroupVersion(GroupDefinition groupDefinition, boolean inTransaction) { Either<GroupDefinition, StorageOperationStatus> result = null; List<String> groupIdsToUpdateVersion = new
316          * ArrayList<>(); groupIdsToUpdateVersion.add(groupDefinition.getUniqueId()); Either<List<GroupDefinition>, StorageOperationStatus> updateGroupVersion = updateGroupVersion(groupIdsToUpdateVersion, inTransaction); if (updateGroupVersion.isLeft())
317          * { result = Either.left(updateGroupVersion.left().value().get(0)); } else { log.debug("Failed to update group version. Status is {} ", updateGroupVersion.right().value()); result = Either.right(updateGroupVersion.right().value()); } return
318          * result; }
319          */
320
321         /**
322          * Update list of groups versions
323          * 
324          * @param groupsUniqueId
325          * @param inTransaction
326          * @return
327          */
328         /*
329          * public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupVersion(List<String> groupsUniqueId, boolean inTransaction) {
330          * 
331          * Either<List<GroupDefinition>, StorageOperationStatus> result = null;
332          * 
333          * try {
334          * 
335          * result = groupOperation.updateGroupVersion(groupsUniqueId, true);
336          * 
337          * return result;
338          * 
339          * } finally {
340          * 
341          * if (false == inTransaction) {
342          * 
343          * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); }
344          * 
345          * }
346          * 
347          * }
348          * 
349          * }
350          */
351
352         /**
353          * Update GroupDefinition metadata
354          * 
355          * @param componentId
356          * @param user
357          * @param componentType
358          * @param updatedGroup
359          * @param inTransaction
360          * @return
361          */
362         public Either<GroupDefinition, ResponseFormat> validateAndUpdateGroupMetadata(String componentId, User user, ComponentTypeEnum componentType, GroupDefinition updatedGroup, boolean inTransaction) {
363
364                 Either<GroupDefinition, ResponseFormat> result = null;
365                 try {
366                         // Validate user exist
367                         Either<User, ResponseFormat> validateUserExists = validateUserExists(user.getUserId(), UPDATE_GROUP, inTransaction);
368                         if (validateUserExists.isRight()) {
369                                 result = Either.right(validateUserExists.right().value());
370                                 return result;
371                         }
372                         // Validate component exist
373                         Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, null);
374                         if (validateComponent.isRight()) {
375                                 result = Either.right(validateComponent.right().value());
376                                 return result;
377                         }
378                         org.openecomp.sdc.be.model.Component component = validateComponent.left().value();
379                         // validate we can work on component
380                         Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, user.getUserId());
381                         if (canWork.isRight()) {
382                                 result = Either.right(canWork.right().value());
383                                 return result;
384                         }
385                         List<GroupDefinition> currentGroups = component.getGroups();
386                         if (CollectionUtils.isEmpty(currentGroups)) {
387                                 log.error("Failed to update the metadata of group {} on component {}. The status is {}. ", updatedGroup.getName(), component.getName(), ActionStatus.GROUP_IS_MISSING);
388                                 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, updatedGroup.getName(), component.getName(), component.getComponentType().getValue()));
389                                 return result;
390                         }
391                         // Validate groups exists in the component
392                         Optional<GroupDefinition> currentGroupOpt = currentGroups.stream().filter(g -> g.getUniqueId().equals(updatedGroup.getUniqueId())).findAny();
393                         if (!currentGroupOpt.isPresent()) {
394                                 log.error("Failed to update the metadata of group {} on component {}. The status is {}. ", updatedGroup.getName(), component.getName(), ActionStatus.GROUP_IS_MISSING);
395                                 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, updatedGroup.getName(), component.getName(), component.getComponentType().getValue()));
396                                 return result;
397                         }
398                         GroupDefinition currentGroup = currentGroupOpt.get();
399                         Either<Boolean, ResponseFormat> lockResult = lockComponent(componentId, component, "Update GroupDefinition Metadata");
400                         if (lockResult.isRight()) {
401                                 result = Either.right(lockResult.right().value());
402                                 return result;
403                         }
404                         // Validate group type is vfModule
405                         if (!currentGroup.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) {
406                                 log.error("Failed to update the metadata of group {}. Group type is {} and different then: {}", currentGroup.getName(), currentGroup.getType(), Constants.DEFAULT_GROUP_VF_MODULE);
407                                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_TYPE, updatedGroup.getType());
408                                 result = Either.right(responseFormat);
409                                 return result;
410                         }
411                         result = updateGroupMetadata(component, currentGroup, updatedGroup);
412                         return result;
413
414                 } finally {
415                         if (result.isLeft()) {
416                                 titanDao.commit();
417                         } else {
418                                 titanDao.rollback();
419                         }
420                         graphLockOperation.unlockComponent(componentId, componentType.getNodeType());
421                 }
422         }
423
424         private Either<GroupDefinition, ResponseFormat> updateGroupMetadata(Component component, GroupDefinition currentGroup, GroupDefinition updatedGroup) {
425                 String currentGroupName = currentGroup.getName();
426                 Either<GroupDefinition, ResponseFormat> result = validateAndUpdateGroupMetadata(currentGroup, updatedGroup);
427
428                 if (result.isRight()) {
429                         log.debug("Failed to validate a metadata of the group {} on component {}. ", updatedGroup.getName(), component.getName());
430                 }
431                 if (result.isLeft()) {
432                         result = updateGroup(component, currentGroup, currentGroupName);
433                 }
434                 return result;
435         }
436
437         private Either<GroupDefinition, ResponseFormat> updateGroup(Component component, GroupDefinition updatedGroup, String currentGroupName) {
438                 Either<GroupDefinition, StorageOperationStatus> handleGroupRes;
439                 Either<GroupDefinition, ResponseFormat> result = null;
440                 if (updatedGroup.getName().equals(currentGroupName)) {
441                         handleGroupRes = groupsOperation.updateGroup(component, updatedGroup);
442                         if (handleGroupRes.isRight()) {
443                                 log.debug("Failed to update a metadata of the group {} on component {}. ", updatedGroup.getName(), component.getName());
444                                 result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(handleGroupRes.right().value())));
445                         }
446                 } else {
447                         StorageOperationStatus deleteStatus = groupsOperation.deleteGroup(component, currentGroupName);
448                         if (deleteStatus != StorageOperationStatus.OK) {
449                                 log.debug("Failed to delete the group {} from component {}. ", updatedGroup.getName(), component.getName());
450                                 result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteStatus)));
451                         }
452                         handleGroupRes = groupsOperation.addGroup(component, updatedGroup);
453                         if (handleGroupRes.isRight()) {
454                                 log.debug("Failed to add the group {} to component {}. ", updatedGroup.getName(), component.getName());
455                                 result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(handleGroupRes.right().value())));
456                         }
457                 }
458                 if (result == null) {
459                         result = Either.left(updatedGroup);
460                 }
461                 return result;
462         }
463
464         /**
465          * Validate and Update Group Property
466          * 
467          * @param componentId
468          * @param groupUniqueId
469          * @param user
470          * @param componentType
471          * @param groupPropertiesToUpdate
472          * @param inTransaction
473          * @return
474          */
475         public Either<List<GroupProperty>, ResponseFormat> validateAndUpdateGroupProperties(String componentId, String groupUniqueId, User user, ComponentTypeEnum componentType, List<GroupProperty> groupPropertiesToUpdate, boolean inTransaction) {
476
477                 Either<List<GroupProperty>, ResponseFormat> result = Either.left(groupPropertiesToUpdate);
478                 try {
479                         Optional<GroupDefinition> optionalGroupConnectedToVf = null;
480                         GroupDefinition currentGroup = null;
481                         StorageOperationStatus lockResult = graphLockOperation.lockComponent(componentId, componentType.getNodeType());
482                         if (lockResult != StorageOperationStatus.OK) {
483                                 result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult, componentType), componentId));
484                         }
485                         if (result.isLeft()) {
486                                 // VF exist because lock succedded
487                                 Resource vf = (Resource) toscaOperationFacade.getToscaElement(componentId).left().value();
488                                 optionalGroupConnectedToVf =
489                                                 // All groups on resource
490                                                 vf.getGroups().stream().
491                                                 // Filter in group sent is part of VF groups
492                                                                 filter(e -> e.getUniqueId().equals(groupUniqueId)).
493                                                                 // Collect
494                                                                 findAny();
495                                 if (!optionalGroupConnectedToVf.isPresent()) {
496                                         result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, groupUniqueId, vf.getName(), ComponentTypeEnum.RESOURCE.getValue()));
497                                 }
498                         }
499
500                         if (result.isLeft()) {
501                                 currentGroup = optionalGroupConnectedToVf.get();
502                                 result = validateGroupPropertyAndResetEmptyValue(currentGroup, groupPropertiesToUpdate);
503                         }
504                         if (result.isLeft()) {
505                                 result = updateGroupPropertiesValue(componentId, currentGroup, groupPropertiesToUpdate, inTransaction);
506                                 if (result.isRight()) {
507                                         BeEcompErrorManager.getInstance().logBeSystemError("Update GroupProperties");
508                                         log.debug("failed to update Vf {}", componentId);
509                                 }
510                         }
511
512                 } catch (Exception e) {
513                         log.debug("Error in validateAndUpdateGroupProperty {}", e);
514                         result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
515                 } finally {
516                         graphLockOperation.unlockComponent(componentId, componentType.getNodeType());
517                 }
518                 return result;
519         }
520
521         private void resetEmptyValueWithDefaults(List<GroupProperty> groupPropertiesToUpdate, GroupDefinition originalGroup) {
522                 Map<String, GroupProperty> originalProperties =
523                                 // Stream of original properties from group
524                                 originalGroup.convertToGroupProperties().stream().
525                                 // Collecting to map with name as key
526                                                 collect(Collectors.toMap(e -> e.getName(), e -> e));
527                 for (GroupProperty gp : groupPropertiesToUpdate) {
528                         if (StringUtils.isEmpty(gp.getValue())) {
529                                 gp.setValue(originalProperties.get(gp.getName()).getDefaultValue());
530                         }
531                 }
532
533         }
534
535         private Either<List<GroupProperty>, ResponseFormat> validateGroupPropertyAndResetEmptyValue(GroupDefinition originalGroup, List<GroupProperty> groupPropertiesToUpdate) {
536
537                 Either<List<GroupProperty>, ResponseFormat> ret = validateOnlyValueChanged(groupPropertiesToUpdate, originalGroup);
538                 if (ret.isLeft()) {
539                         resetEmptyValueWithDefaults(groupPropertiesToUpdate, originalGroup);
540                 }
541                 if (ret.isLeft()) {
542                         // Validate Type Match Value
543                         Optional<StorageOperationStatus> optionalError =
544                                         // Stream of group properties
545                                         groupPropertiesToUpdate.stream().
546                                         // Validate each and map to returned Strorage status value
547                                                         map(e -> groupOperation.validateAndUpdatePropertyValue(e)).
548                                                         // Keep only failed result if there is such
549                                                         filter(e -> e != StorageOperationStatus.OK).
550                                                         // collect
551                                                         findFirst();
552                         if (optionalError.isPresent()) {
553                                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(optionalError.get());
554                                 ret = Either.right(componentsUtils.getResponseFormat(actionStatus));
555                         }
556
557                 }
558                 if (ret.isLeft()) {
559                         // Validate min max ect...
560                         ret = validatePropertyBusinessLogic(groupPropertiesToUpdate, originalGroup);
561                 }
562
563                 return ret;
564         }
565
566         private Either<List<GroupProperty>, ResponseFormat> validatePropertyBusinessLogic(List<GroupProperty> groupPropertiesToUpdate, GroupDefinition originalGroup) {
567
568                 Either<List<GroupProperty>, ResponseFormat> ret = Either.left(groupPropertiesToUpdate);
569
570                 Map<PropertyNames, String> nameValueMap = new HashMap<>();
571                 for (GroupProperty gp : groupPropertiesToUpdate) {
572                         // Filter out non special properties which does not have Enum
573                         final PropertyNames gpEnum = PropertyNames.findName(gp.getName());
574                         if (gpEnum != null) {
575                                 nameValueMap.put(gpEnum, gp.getValue());
576                         }
577                 }
578
579                 if (!MapUtils.isEmpty(nameValueMap)) {
580
581                         if (nameValueMap.containsKey(PropertyNames.INITIAL_COUNT) || nameValueMap.containsKey(PropertyNames.MAX_INSTANCES) || nameValueMap.containsKey(PropertyNames.MIN_INSTANCES)) {
582
583                                 Map<PropertyNames, String> oldValueMap = prepareMapWithOriginalProperties(originalGroup);
584
585                                 Either<Boolean, ResponseFormat> eitherValid = validateMinMaxAndInitialCountPropertyLogicVF(nameValueMap, oldValueMap);
586                                 if (eitherValid.isRight()) {
587                                         ret = Either.right(eitherValid.right().value());
588                                 }
589                         }
590                         if (ret.isLeft() && (nameValueMap.containsKey(PropertyNames.VF_MODULE_DESCRIPTION) || nameValueMap.containsKey(PropertyNames.VF_MODULE_LABEL))) {
591
592                                 Optional<ResponseFormat> optionalError =
593                                                 // Stream of group Properties
594                                                 groupPropertiesToUpdate.stream().
595                                                 // Filter in only properties that needs text validation
596                                                                 filter(e -> enumHasValueFilter(e.getName(), enumName -> PropertyNames.findName(enumName), PropertyNames.VF_MODULE_DESCRIPTION, PropertyNames.VF_MODULE_LABEL)).
597                                                                 // validate text properties
598                                                                 map(e -> validateFreeText(e)).
599                                                                 // filter in only errors if exist
600                                                                 filter(e -> e.isRight()).
601                                                                 // map the Either value to the Error
602                                                                 map(e -> e.right().value())
603                                                                 // collect
604                                                                 .findFirst();
605                                 if (optionalError.isPresent()) {
606                                         ret = Either.right(optionalError.get());
607                                 }
608
609                         }
610                 }
611
612                 return ret;
613         }
614
615         private Map<PropertyNames, String> prepareMapWithOriginalProperties(GroupDefinition originalGroup) {
616                 Map<PropertyNames, String> oldValueMap = new HashMap<>();
617                 PropertyNames[] propertiesToCheck = new PropertyNames[] { PropertyNames.INITIAL_COUNT, PropertyNames.MAX_INSTANCES, PropertyNames.MIN_INSTANCES };
618
619                 for (GroupProperty gp : originalGroup.convertToGroupProperties()) {
620                         if (enumHasValueFilter(gp.getName(), enumName -> PropertyNames.findName(enumName), propertiesToCheck)) {
621                                 oldValueMap.put(PropertyNames.findName(gp.getName()), gp.getValue());
622                         }
623                 }
624                 if (StringUtils.isEmpty(oldValueMap.get(PropertyNames.MAX_INSTANCES))) {
625                         oldValueMap.put(PropertyNames.MAX_INSTANCES, String.valueOf(Integer.MAX_VALUE));
626                 }
627                 return oldValueMap;
628         }
629
630         private Either<List<GroupProperty>, ResponseFormat> validateOnlyValueChanged(List<GroupProperty> groupPropertiesToUpdate, GroupDefinition originalGroup) {
631
632                 Either<List<GroupProperty>, ResponseFormat> ret = Either.left(groupPropertiesToUpdate);
633                 if (CollectionUtils.isEmpty(groupPropertiesToUpdate)) {
634                         ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, StringUtils.EMPTY));
635                 } else if (CollectionUtils.isEmpty(originalGroup.getProperties())) {
636                         ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, groupPropertiesToUpdate.get(NumberUtils.INTEGER_ZERO).getName()));
637                 } else {
638                         Map<String, GroupProperty> namePropertyMap =
639                                         // Original Group Properties Stream
640                                         originalGroup.convertToGroupProperties().stream().
641                                         // Collect to map with name as key
642                                                         collect(Collectors.toMap(e -> e.getName(), e -> e));
643
644                         Optional<GroupProperty> optionalMissingProperty =
645                                         // Group Properties to be updated Stream
646                                         groupPropertiesToUpdate.stream().
647                                         // Filter in property that is not contained in original if there is such
648                                                         filter(e -> !namePropertyMap.containsKey(e.getName())).
649                                                         // collect
650                                                         findFirst();
651
652                         if (optionalMissingProperty.isPresent()) {
653                                 ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, optionalMissingProperty.get().getName()));
654                         } else {
655                                 Optional<GroupProperty> optionalNonValueChange =
656                                                 // groups to be updated stream
657                                                 groupPropertiesToUpdate.stream().
658                                                 // filter in only properties with non-value (illegal) change
659                                                                 filter(e -> !isOnlyGroupPropertyValueChanged(e, namePropertyMap.get(e.getName()))).
660                                                                 // Collect
661                                                                 findFirst();
662                                 if (optionalNonValueChange.isPresent()) {
663                                         ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY, optionalNonValueChange.get().getName()));
664
665                                 }
666                         }
667
668                 }
669                 return ret;
670         }
671
672         /**
673          * if groupProperty are the same or if only value is different returns true, otherwise returns false.
674          * 
675          * @param groupProperty
676          * @param groupProperty2
677          * @return
678          */
679         private boolean isOnlyGroupPropertyValueChanged(GroupProperty groupProperty, GroupProperty groupProperty2) {
680                 // Create 2 duplicates for groupPropery and reset their values
681                 Gson gson = new GsonBuilder().setPrettyPrinting().create();
682                 try {
683                         GroupProperty groupPropertyDuplicate = new GroupProperty(groupProperty);
684                         groupPropertyDuplicate.setValue(null);
685                         groupPropertyDuplicate.setSchema(null);
686                         groupPropertyDuplicate.setParentUniqueId(null);
687                         // GroupProperty groupProperty2Duplicate = gson.fromJson(JsonParserUtils.jsonToString(groupProperty2), GroupProperty.class);
688                         GroupProperty groupProperty2Duplicate = new GroupProperty(groupProperty2);
689                         groupProperty2Duplicate.setValue(null);
690                         groupProperty2Duplicate.setSchema(null);
691                         groupProperty2Duplicate.setParentUniqueId(null);
692                         return groupPropertyDuplicate.equals(groupProperty2Duplicate) && StringUtils.equals(groupPropertyDuplicate.getValueUniqueUid(), groupProperty2Duplicate.getValueUniqueUid());
693                 } catch (Exception e) {
694                         log.debug("Failed validate group properties. ", e);
695                         return false;
696                 }
697         }
698
699         /**
700          * Validate and update GroupDefinition metadata
701          * 
702          * @param user
703          * @param currentGroup
704          * @param groupUpdate
705          * @return
706          **/
707         private Either<GroupDefinition, ResponseFormat> validateAndUpdateGroupMetadata(GroupDefinition currentGroup, GroupDefinition groupUpdate) {
708                 // Check if to update, and update GroupDefinition name.
709                 Either<Boolean, ResponseFormat> response = validateAndUpdateGroupName(currentGroup, groupUpdate);
710                 if (response.isRight()) {
711                         ResponseFormat errorResponse = response.right().value();
712                         return Either.right(errorResponse);
713                 }
714
715                 // Do not allow to update GroupDefinition version directly.
716                 String versionUpdated = groupUpdate.getVersion();
717                 String versionCurrent = currentGroup.getVersion();
718                 if (versionUpdated != null && !versionCurrent.equals(versionUpdated)) {
719                         log.info("update Group: recived request to update version to {} the field is not updatable ignoring.", versionUpdated);
720                 }
721
722                 return Either.left(currentGroup);
723         }
724
725         /**
726          * Validate and update GroupDefinition name
727          * 
728          * @param user
729          * @param currentGroup
730          * @param groupUpdate
731          * @return
732          */
733         private Either<Boolean, ResponseFormat> validateAndUpdateGroupName(GroupDefinition currentGroup, GroupDefinition groupUpdate) {
734                 String nameUpdated = groupUpdate.getName();
735                 String nameCurrent = currentGroup.getName();
736                 if (!nameCurrent.equals(nameUpdated)) {
737                         Either<Boolean, ResponseFormat> validatNameResponse = validateGroupName(currentGroup.getName(), groupUpdate.getName());
738                         if (validatNameResponse.isRight()) {
739                                 ResponseFormat errorRespons = validatNameResponse.right().value();
740                                 return Either.right(errorRespons);
741                         }
742                         currentGroup.setName(groupUpdate.getName());
743                 }
744                 return Either.left(true);
745         }
746
747         /**
748          * 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
749          * MyDesc was changed.
750          * 
751          * @param currentGroupName
752          * @param groupUpdateName
753          * @return
754          */
755         private Either<Boolean, ResponseFormat> validateGroupName(String currentGroupName, String groupUpdateName) {
756                 try {
757                         // Check if the group name is in old format.
758                         if (Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(groupUpdateName).matches()) {
759                                 log.error("Group name {} is in old format", groupUpdateName);
760                                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME, groupUpdateName));
761                         }
762
763                         // Check that name pats 1 and 3 did not changed (only the second
764                         // part can be changed)
765                         // But verify before that the current group format is the new one
766                         if (!Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(currentGroupName).matches()) {
767                                 String[] split1 = currentGroupName.split("\\.\\.");
768                                 String currentResourceName = split1[0];
769                                 String currentCounter = split1[2];
770
771                                 String[] split2 = groupUpdateName.split("\\.\\.");
772                                 String groupUpdateResourceName = split2[0];
773                                 String groupUpdateCounter = split2[2];
774
775                                 if (!currentResourceName.equals(groupUpdateResourceName)) {
776                                         return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME_MODIFICATION, currentResourceName));
777                                 }
778
779                                 if (!currentCounter.equals(groupUpdateCounter)) {
780                                         return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME_MODIFICATION, currentCounter));
781                                 }
782                         }
783
784                         return Either.left(true);
785                 } catch (Exception e) {
786                         log.error("Error valiadting group name", e);
787                         return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
788                 }
789         }
790
791         /**
792          * associate artifacts to a given group
793          * 
794          * @param componentId
795          * @param userId
796          * @param componentType
797          * @param groups
798          * @param shouldLockComp
799          * @param inTransaction
800          * @return
801          */
802         /*
803          * public Either<List<GroupDefinition>, ResponseFormat> associateArtifactsToGroup(String componentId, String userId, ComponentTypeEnum componentType, List<GroupDefinition> groups, boolean shouldLockComp, boolean inTransaction) {
804          * 
805          * Either<List<GroupDefinition>, ResponseFormat> result = null;
806          * 
807          * if (shouldLockComp == true && inTransaction == true) { BeEcompErrorManager.getInstance().logInternalFlowError("dissociateArtifactsFromGroup", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR); // Cannot lock
808          * component since we are in a middle of another // transaction. ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; result = Either.right(componentsUtils.getResponseFormat(actionStatus)); return result; }
809          * 
810          * Component component = null; try {
811          * 
812          * if (groups == null || groups.isEmpty()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.OK)); }
813          * 
814          * Either<Component, ResponseFormat> validateGroupsBeforeUpdate = validateGroupsBeforeUpdate(componentId, userId, componentType, groups, inTransaction); if (validateGroupsBeforeUpdate.isRight()) { result =
815          * Either.right(validateGroupsBeforeUpdate.right().value()); return result; }
816          * 
817          * component = validateGroupsBeforeUpdate.left().value();
818          * 
819          * if (shouldLockComp) { Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Group - Associate Artifacts"); if (lockComponent.isRight()) { return Either.right(lockComponent.right().value()); } }
820          * 
821          * List<GroupDefinition> updatedGroups = new ArrayList<>();
822          * 
823          * List<GroupDefinition> componentGroups = component.getGroups();
824          * 
825          * // per group, associate to it the artifacts for (GroupDefinition groupDefinition : groups) {
826          * 
827          * GroupDefinition componentGroup = componentGroups.stream().filter(p -> p.getUniqueId().equals(groupDefinition.getUniqueId())).findFirst().orElse(null); if (componentGroup != null) { List<String> componentArtifacts =
828          * componentGroup.getArtifacts(); int artifactsSizeInGroup = componentArtifacts == null ? 0 : componentArtifacts.size(); if (artifactsSizeInGroup > 0) { List<String> artifactsToAssociate = groupDefinition.getArtifacts();
829          * 
830          * // if no artifcats sent if (artifactsToAssociate == null || true == artifactsToAssociate.isEmpty()) { continue; }
831          * 
832          * boolean isChanged = componentArtifacts.removeAll(artifactsToAssociate); if (isChanged) {// I.e. At least one artifact is already // associated to the group log.debug("Some of the artifacts already associated to group {}" ,
833          * groupDefinition.getUniqueId()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ARTIFACT_ALREADY_ASSOCIATED, componentGroup.getName())); } } }
834          * 
835          * Either<GroupDefinition, StorageOperationStatus> associateArtifactsToGroup = groupOperation.associateArtifactsToGroup(groupDefinition.getUniqueId(), groupDefinition.getArtifacts(), true);
836          * 
837          * if (associateArtifactsToGroup.isRight()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(associateArtifactsToGroup.right().value()); result = Either.right(componentsUtils.getResponseFormat(actionStatus));
838          * log.debug("Failed to update group {} under component {}, error: {}", groupDefinition.getName(), component.getNormalizedName(), actionStatus.name()); return result; } updatedGroups.add(associateArtifactsToGroup.left().value());
839          * 
840          * }
841          * 
842          * result = Either.left(updatedGroups); return result;
843          * 
844          * } finally {
845          * 
846          * if (false == inTransaction) {
847          * 
848          * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); }
849          * 
850          * }
851          * 
852          * // unlock resource if (shouldLockComp && component != null) { graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); }
853          * 
854          * } }
855          */
856
857         /*
858          * public Either<List<GroupDefinition>, ResponseFormat> associateMembersToGroup(String componentId, String userId, ComponentTypeEnum componentType, List<GroupDefinition> groups, boolean shouldLockComp, boolean inTransaction) {
859          * 
860          * Either<List<GroupDefinition>, ResponseFormat> result = null;
861          * 
862          * if (shouldLockComp == true && inTransaction == true) { BeEcompErrorManager.getInstance().logInternalFlowError("dissociateArtifactsFromGroup", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR); // Cannot lock
863          * component since we are in a middle of another // transaction. ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; result = Either.right(componentsUtils.getResponseFormat(actionStatus)); return result; }
864          * 
865          * Component component = null; try {
866          * 
867          * if (groups == null || groups.isEmpty()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.OK)); }
868          * 
869          * Either<Component, ResponseFormat> validateGroupsBeforeUpdate = validateGroupsBeforeUpdate(componentId, userId, componentType, groups, inTransaction); if (validateGroupsBeforeUpdate.isRight()) { result =
870          * Either.right(validateGroupsBeforeUpdate.right().value()); return result; }
871          * 
872          * component = validateGroupsBeforeUpdate.left().value();
873          * 
874          * if (shouldLockComp) { Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Group - Associate Members"); if (lockComponent.isRight()) { return Either.right(lockComponent.right().value()); } }
875          * 
876          * List<GroupDefinition> updatedGroups = new ArrayList<>();
877          * 
878          * // per group, associate to it the members for (GroupDefinition groupDefinition : groups) {
879          * 
880          * Either<GroupDefinition, StorageOperationStatus> associateMembersToGroup = groupOperation.associateMembersToGroup(groupDefinition.getUniqueId(), groupDefinition.getMembers(), true);
881          * 
882          * if (associateMembersToGroup.isRight()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(associateMembersToGroup.right().value()); result = Either.right(componentsUtils.getResponseFormat(actionStatus));
883          * log.debug("Failed to update group {} under component {}, error: {}", groupDefinition.getName(), component.getNormalizedName(), actionStatus.name()); return result; } else { updatedGroups.add(associateMembersToGroup.left().value()); }
884          * 
885          * }
886          * 
887          * result = Either.left(updatedGroups); return result;
888          * 
889          * } finally {
890          * 
891          * if (false == inTransaction) {
892          * 
893          * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); }
894          * 
895          * }
896          * 
897          * // unlock resource if (shouldLockComp && component != null) { graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); }
898          * 
899          * } }
900          */
901
902         /**
903          * associate artifacts to a given group
904          * 
905          * @param componentId
906          * @param userId
907          * @param componentType
908          * @param groups
909          * @param shouldLockComp
910          * @param inTransaction
911          * @return
912          */
913         public Either<GroupDefinitionInfo, ResponseFormat> getGroupWithArtifactsById(ComponentTypeEnum componentType, String componentId, String groupId, String userId, boolean inTransaction) {
914
915                 Either<GroupDefinitionInfo, ResponseFormat> result = null;
916
917                 // Validate user exist
918                 Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, UPDATE_GROUP, true);
919
920                 if (validateUserExists.isRight()) {
921                         result = Either.right(validateUserExists.right().value());
922                         return result;
923                 }
924
925                 // Validate component exist
926                 org.openecomp.sdc.be.model.Component component = null;
927                 String realComponentId = componentId;
928
929                 try {
930                         ComponentParametersView componentParametersView = new ComponentParametersView();
931                         componentParametersView.disableAll();
932                         componentParametersView.setIgnoreGroups(false);
933                         componentParametersView.setIgnoreArtifacts(false);
934                         componentParametersView.setIgnoreUsers(false);
935
936                         Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView);
937                         if (validateComponent.isRight()) {
938                                 result = Either.right(validateComponent.right().value());
939                                 return result;
940                         }
941                         component = validateComponent.left().value();
942
943                         Either<GroupDefinition, StorageOperationStatus> groupEither = findGroupOnComponent(component, groupId);
944
945                         if (groupEither.isRight()) {
946                                 log.debug("Faild to find group {} under component {}", groupId, component.getUniqueId());
947                                 BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "group  " + groupId + " not found under component " + component.getUniqueId(), ErrorSeverity.INFO);
948                                 String componentTypeForResponse = getComponentTypeForResponse(component);
949                                 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, groupId, component.getSystemName(), componentTypeForResponse));
950                                 return result;
951                         }
952                         GroupDefinition group = groupEither.left().value();
953
954                         Boolean isBase = null;// Constants.IS_BASE;
955                         List<GroupProperty> props = group.convertToGroupProperties();
956                         if (props != null && !props.isEmpty()) {
957                                 Optional<GroupProperty> isBasePropOp = props.stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny();
958                                 if (isBasePropOp.isPresent()) {
959                                         GroupProperty propIsBase = isBasePropOp.get();
960                                         isBase = Boolean.parseBoolean(propIsBase.getValue());
961
962                                 } else {
963                                         BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO);
964                                         // return
965                                         // Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
966
967                                 }
968                         }
969
970                         List<ArtifactDefinitionInfo> artifacts = new ArrayList<>();
971                         List<ArtifactDefinition> artifactsFromComponent = new ArrayList<>();
972                         List<String> artifactsIds = group.getArtifacts();
973
974                         Map<String, ArtifactDefinition> deploymentArtifacts = null;
975                         if (MapUtils.isNotEmpty(component.getDeploymentArtifacts())) {
976                                 deploymentArtifacts = component.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(a -> a.getUniqueId(), a -> a));
977                         }
978
979                         if (artifactsIds != null && !artifactsIds.isEmpty()) {
980                                 for (String id : artifactsIds) {
981                                         if (MapUtils.isEmpty(deploymentArtifacts) || !deploymentArtifacts.containsKey(id)) {
982                                                 log.debug("Failed to get artifact {} . Status is {} ", id, StorageOperationStatus.NOT_FOUND);
983                                                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND));
984                                                 result = Either.right(responseFormat);
985                                                 return result;
986                                         }
987                                         artifactsFromComponent.add(deploymentArtifacts.get(id));
988                                 }
989                                 if (!artifactsFromComponent.isEmpty()) {
990                                         for (ArtifactDefinition artifactDefinition : artifactsFromComponent) {
991                                                 ArtifactDefinitionInfo artifactDefinitionInfo = new ArtifactDefinitionInfo(artifactDefinition);
992                                                 artifacts.add(artifactDefinitionInfo);
993                                         }
994                                 }
995
996                         }
997                         GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group);
998                         resultInfo.setIsBase(isBase);
999                         if (!artifacts.isEmpty())
1000                                 resultInfo.setArtifacts(artifacts);
1001
1002                         result = Either.left(resultInfo);
1003
1004                         return result;
1005
1006                 } finally {
1007
1008                         if (false == inTransaction) {
1009
1010                                 if (result == null || result.isRight()) {
1011                                         log.debug("Going to execute rollback on create group.");
1012                                         titanDao.rollback();
1013                                 } else {
1014                                         log.debug("Going to execute commit on create group.");
1015                                         titanDao.commit();
1016                                 }
1017
1018                         }
1019
1020                 }
1021
1022         }
1023
1024         private Either<GroupDefinition, StorageOperationStatus> findGroupOnComponent(Component component, String groupId) {
1025
1026                 Either<GroupDefinition, StorageOperationStatus> result = null;
1027                 if (CollectionUtils.isNotEmpty(component.getGroups())) {
1028                         Optional<GroupDefinition> foundGroup = component.getGroups().stream().filter(g -> g.getUniqueId().equals(groupId)).findFirst();
1029                         if (foundGroup.isPresent()) {
1030                                 result = Either.left(foundGroup.get());
1031                         }
1032                 }
1033                 if (result == null) {
1034                         result = Either.right(StorageOperationStatus.NOT_FOUND);
1035                 }
1036                 return result;
1037         }
1038
1039         /**
1040          * @param componentId
1041          * @param userId
1042          * @param componentType
1043          * @param groups
1044          * @param inTransaction
1045          * @return
1046          */
1047         private Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateGroupsBeforeUpdate(String componentId, String userId, ComponentTypeEnum componentType, List<GroupDefinition> groups, boolean inTransaction) {
1048
1049                 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> result;
1050
1051                 // Validate user exist
1052                 Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, UPDATE_GROUP, inTransaction);
1053                 if (validateUserExists.isRight()) {
1054                         result = Either.right(validateUserExists.right().value());
1055                         return result;
1056                 }
1057
1058                 // Validate component exist
1059                 String realComponentId = componentId;
1060
1061                 ComponentParametersView componentParametersView = new ComponentParametersView();
1062                 componentParametersView.disableAll();
1063                 componentParametersView.setIgnoreGroups(false);
1064                 componentParametersView.setIgnoreArtifacts(false);
1065                 componentParametersView.setIgnoreUsers(false);
1066                 componentParametersView.setIgnoreComponentInstances(false);
1067
1068                 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView);
1069
1070                 if (validateComponent.isRight()) {
1071                         result = Either.right(validateComponent.right().value());
1072                         return result;
1073                 }
1074                 org.openecomp.sdc.be.model.Component component = validateComponent.left().value();
1075
1076                 // validate we can work on component
1077                 Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
1078                 if (canWork.isRight()) {
1079                         result = Either.right(canWork.right().value());
1080                         return result;
1081                 }
1082
1083                 // Validate groups exists in the component
1084                 ResponseFormat validateGroupsInComponent = validateGroupsInComponentByFunc(groups, component, p -> p.getUniqueId());
1085                 if (validateGroupsInComponent != null) {
1086                         result = Either.right(validateGroupsInComponent);
1087                         return result;
1088                 }
1089
1090                 Set<String> artifacts = new HashSet<>();
1091                 groups.forEach(p -> {
1092                         if (p.getArtifacts() != null) {
1093                                 artifacts.addAll(p.getArtifacts());
1094                         }
1095                 });
1096                 // validate all artifacts belongs to the component
1097                 Either<Boolean, ResponseFormat> verifyArtifactsBelongsToComponent = verifyArtifactsBelongsToComponent(component, new ArrayList<>(artifacts), UPDATE_GROUP);
1098                 if (verifyArtifactsBelongsToComponent.isRight()) {
1099                         result = Either.right(verifyArtifactsBelongsToComponent.right().value());
1100                         return result;
1101                 }
1102
1103                 return Either.left(component);
1104         }
1105
1106         /**
1107          * @param groups
1108          * @param component
1109          * @param getByParam
1110          *            - the method to fetch the key of the GroupDefinition(from groups) in order to compare to groups in the component
1111          * @return
1112          */
1113         private ResponseFormat validateGroupsInComponentByFunc(List<GroupDefinition> groups, org.openecomp.sdc.be.model.Component component, Function<GroupDefinition, String> getByParam) {
1114                 ResponseFormat result = null;
1115
1116                 List<GroupDefinition> currentGroups = component.getGroups();
1117
1118                 boolean found = false;
1119                 List<String> updatedGroupsName = groups.stream().map(getByParam).collect(Collectors.toList());
1120
1121                 List<String> missingGroupNames = updatedGroupsName;
1122
1123                 if (currentGroups != null && false == currentGroups.isEmpty()) {
1124                         List<String> currentGroupsName = currentGroups.stream().map(getByParam).collect(Collectors.toList());
1125
1126                         if (currentGroupsName.containsAll(updatedGroupsName)) {
1127                                 found = true;
1128                         } else {
1129                                 currentGroupsName.removeAll(currentGroupsName);
1130                                 missingGroupNames = currentGroupsName;
1131                         }
1132                 }
1133                 if (false == found) {
1134                         String componentTypeForResponse = getComponentTypeForResponse(component);
1135                         String listOfGroups = getAsString(missingGroupNames);
1136                         result = componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, listOfGroups, component.getSystemName(), componentTypeForResponse);
1137                         return result;
1138                 }
1139
1140                 return null;
1141         }
1142
1143         public String getAsString(List<String> list) {
1144
1145                 if (list == null || list.isEmpty()) {
1146                         return "";
1147                 }
1148                 StringBuilder builder = new StringBuilder();
1149                 list.forEach(p -> builder.append(p + ","));
1150
1151                 String result = builder.toString();
1152                 return result.substring(0, result.length());
1153
1154         }
1155
1156         /**
1157          * dissociate artifacts from a given group
1158          * 
1159          * @param componentId
1160          * @param userId
1161          * @param componentType
1162          * @param groups
1163          * @param shouldLockComp
1164          * @param inTransaction
1165          * @return
1166          */
1167         /*
1168          * public Either<List<GroupDefinition>, ResponseFormat> dissociateArtifactsFromGroup(String componentId, String userId, ComponentTypeEnum componentType, List<GroupDefinition> groups, boolean shouldLockComp, boolean inTransaction) {
1169          * 
1170          * Either<List<GroupDefinition>, ResponseFormat> result = null;
1171          * 
1172          * if (shouldLockComp == true && inTransaction == true) { BeEcompErrorManager.getInstance().logInternalFlowError("dissociateArtifactsFromGroup", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR); // Cannot lock
1173          * component since we are in a middle of another // transaction. ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; result = Either.right(componentsUtils.getResponseFormat(actionStatus)); return result; }
1174          * 
1175          * Component component = null;
1176          * 
1177          * try {
1178          * 
1179          * if (groups == null || groups.isEmpty()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.OK)); }
1180          * 
1181          * Either<Component, ResponseFormat> validateGroupsBeforeUpdate = validateGroupsBeforeUpdate(componentId, userId, componentType, groups, inTransaction); if (validateGroupsBeforeUpdate.isRight()) { result =
1182          * Either.right(validateGroupsBeforeUpdate.right().value()); return result; }
1183          * 
1184          * component = validateGroupsBeforeUpdate.left().value();
1185          * 
1186          * if (shouldLockComp) { Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Group - Dissociate Artifacts"); if (lockComponent.isRight()) { return Either.right(lockComponent.right().value()); } }
1187          * 
1188          * List<GroupDefinition> updatedGroups = new ArrayList<>();
1189          * 
1190          * List<GroupDefinition> componentGroups = component.getGroups(); // per group, associate to it the artifacts for (GroupDefinition groupDefinition : groups) {
1191          * 
1192          * GroupDefinition componentGroup = componentGroups.stream().filter(p -> p.getUniqueId().equals(groupDefinition.getUniqueId())).findFirst().orElse(null); if (componentGroup != null) { List<String> componentArtifacts =
1193          * componentGroup.getArtifacts(); int artifactsSizeInGroup = componentArtifacts == null ? 0 : componentArtifacts.size(); List<String> artifactsToDissociate = groupDefinition.getArtifacts();
1194          * 
1195          * // if no artifcats sent if (artifactsToDissociate == null || true == artifactsToDissociate.isEmpty()) { continue; }
1196          * 
1197          * if (artifactsSizeInGroup > 0) {
1198          * 
1199          * boolean containsAll = componentArtifacts.containsAll(artifactsToDissociate); if (false == containsAll) { // At least one artifact is // not associated to the // group log.debug("Some of the artifacts already dissociated to group {}" ,
1200          * groupDefinition.getUniqueId()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ARTIFACT_ALREADY_DISSOCIATED, componentGroup.getName())); } } else { if (artifactsSizeInGroup == 0) { if (artifactsToDissociate != null &&
1201          * false == artifactsToDissociate.isEmpty()) { log.debug("No artifact is found under the group {}" , groupDefinition.getUniqueId()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ARTIFACT_ALREADY_DISSOCIATED,
1202          * componentGroup.getName())); } } } }
1203          * 
1204          * Either<GroupDefinition, StorageOperationStatus> associateArtifactsToGroup = groupOperation.dissociateArtifactsFromGroup(groupDefinition.getUniqueId(), groupDefinition.getArtifacts(), true);
1205          * 
1206          * if (associateArtifactsToGroup.isRight()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(associateArtifactsToGroup.right().value()); result = Either.right(componentsUtils.getResponseFormat(actionStatus));
1207          * log.debug("Failed to update group {} under component {}, error: {}", groupDefinition.getName(), component.getNormalizedName(), actionStatus.name()); return result; } updatedGroups.add(associateArtifactsToGroup.left().value());
1208          * 
1209          * }
1210          * 
1211          * result = Either.left(updatedGroups); return result;
1212          * 
1213          * } finally {
1214          * 
1215          * if (false == inTransaction) {
1216          * 
1217          * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); }
1218          * 
1219          * } // unlock resource if (shouldLockComp && component != null) { graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); }
1220          * 
1221          * }
1222          * 
1223          * }
1224          */
1225
1226         /*
1227          * public Either<List<GroupDefinition>, ResponseFormat> createGroups(String componentId, String userId, ComponentTypeEnum componentType, List<GroupDefinition> groupDefinitions, boolean shouldLockComp, boolean inTransaction) {
1228          * 
1229          * Either<List<GroupDefinition>, ResponseFormat> result = null;
1230          * 
1231          * List<GroupDefinition> groups = new ArrayList<>(); org.openecomp.sdc.be.model.Component component = null; try {
1232          * 
1233          * if (groupDefinitions != null && !groupDefinitions.isEmpty()) {
1234          * 
1235          * if (shouldLockComp && inTransaction) { BeEcompErrorManager.getInstance().logInternalFlowError("createGroups", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR); // Cannot lock component since we are in a middle of
1236          * another // transaction. ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; result = Either.right(componentsUtils.getResponseFormat(actionStatus)); return result; }
1237          * 
1238          * Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, CREATE_GROUP, true); if (validateUserExists.isRight()) { result = Either.right(validateUserExists.right().value()); return result; }
1239          * 
1240          * User user = validateUserExists.left().value();
1241          * 
1242          * ComponentParametersView componentParametersView = new ComponentParametersView(); componentParametersView.disableAll(); componentParametersView.setIgnoreGroups(false); componentParametersView.setIgnoreArtifacts(false);
1243          * componentParametersView.setIgnoreUsers(false); componentParametersView.setIgnoreComponentInstances(false);
1244          * 
1245          * Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, componentParametersView);
1246          * 
1247          * if (validateComponent.isRight()) { result = Either.right(validateComponent.right().value()); return result; } component = validateComponent.left().value();
1248          * 
1249          * if (shouldLockComp) { Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "CreateGroups"); if (lockComponent.isRight()) { return Either.right(lockComponent.right().value()); } }
1250          * 
1251          * Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId); if (canWork.isRight()) { result = Either.right(canWork.right().value()); return result; }
1252          * 
1253          * for (GroupDefinition groupDefinition : groupDefinitions) { Either<GroupDefinition, ResponseFormat> createGroup = this.createGroup(component, user, componentType, groupDefinition, true); if (createGroup.isRight()) {
1254          * log.debug("Failed to create group {}." , groupDefinition ); result = Either.right(createGroup.right().value()); return result; } GroupDefinition createdGroup = createGroup.left().value(); groups.add(createdGroup); } }
1255          * 
1256          * result = Either.left(groups); return result;
1257          * 
1258          * } finally {
1259          * 
1260          * if (false == inTransaction) {
1261          * 
1262          * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); }
1263          * 
1264          * } // unlock resource if (shouldLockComp && component != null) { graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); }
1265          * 
1266          * }
1267          * 
1268          * }
1269          * 
1270          * public Either<GroupDefinition, ResponseFormat> createGroup(Component component, User user, ComponentTypeEnum componentType, GroupDefinition groupDefinition, boolean inTransaction) {
1271          * 
1272          * Either<GroupDefinition, ResponseFormat> result = null;
1273          * 
1274          * log.trace("Going to create group {}" , groupDefinition);
1275          * 
1276          * try {
1277          * 
1278          * // 3. verify group not already exist List<GroupDefinition> groups = component.getGroups(); boolean found = false; if (groups != null && false == groups.isEmpty()) {
1279          * 
1280          * GroupDefinition existGroupDef = groups.stream().filter(p -> p.getName().equalsIgnoreCase(groupDefinition.getName())).findFirst().orElse(null);
1281          * 
1282          * found = existGroupDef != null; }
1283          * 
1284          * if (true == found) { String componentTypeForResponse = getComponentTypeForResponse(component); result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ALREADY_EXIST, groupDefinition.getName(), component.getNormalizedName(),
1285          * componentTypeForResponse)); return result; }
1286          * 
1287          * // 4. verify type of group exist String groupType = groupDefinition.getType(); if (groupType == null || groupType.isEmpty()) { result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_MISSING_GROUP_TYPE,
1288          * groupDefinition.getName())); return result; } Either<GroupTypeDefinition, StorageOperationStatus> getGroupType = groupTypeOperation.getLatestGroupTypeByType(groupType, true); if (getGroupType.isRight()) { StorageOperationStatus status =
1289          * getGroupType.right().value(); if (status == StorageOperationStatus.NOT_FOUND) { BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "group type " + groupType + " cannot be found", ErrorSeverity.INFO); result =
1290          * Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, groupType)); return result; } else { result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); return result; } }
1291          * 
1292          * // 6. verify the component instances type are allowed according to // the member types in the group type GroupTypeDefinition groupTypeDefinition = getGroupType.left().value();
1293          * 
1294          * Either<Boolean, ResponseFormat> areValidMembers = verifyComponentInstancesAreValidMembers(component, componentType, groupDefinition.getName(), groupType, groupDefinition.getMembers(), groupTypeDefinition.getMembers());
1295          * 
1296          * if (areValidMembers.isRight()) { ResponseFormat responseFormat = areValidMembers.right().value(); result = Either.right(responseFormat); return result; }
1297          * 
1298          * // 7. verify the artifacts belongs to the component Either<Boolean, ResponseFormat> areValidArtifacts = verifyArtifactsBelongsToComponent(component, groupDefinition.getArtifacts(), CREATE_GROUP); if (areValidArtifacts.isRight()) {
1299          * ResponseFormat responseFormat = areValidArtifacts.right().value(); result = Either.right(responseFormat); return result; }
1300          * 
1301          * NodeTypeEnum nodeTypeEnum = componentType.getNodeType();
1302          * 
1303          * // add invariantUUID String invariantUUID = UniqueIdBuilder.buildInvariantUUID(); groupDefinition.setInvariantUUID(invariantUUID);
1304          * 
1305          * // add groupUUID String groupUUID = UniqueIdBuilder.generateUUID(); groupDefinition.setGroupUUID(groupUUID);
1306          * 
1307          * // add version groupDefinition.setVersion(INITIAL_VERSION);
1308          * 
1309          * // set groupType uid groupDefinition.setTypeUid(groupTypeDefinition.getUniqueId());
1310          * 
1311          * Either<GroupDefinition, StorageOperationStatus> addGroupToGraph = groupOperation.addGroup(nodeTypeEnum, component.getUniqueId(), groupDefinition, true);
1312          * 
1313          * if (addGroupToGraph.isRight()) { StorageOperationStatus storageOperationStatus = addGroupToGraph.right().value(); ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus); result =
1314          * Either.right(componentsUtils.getResponseFormat(actionStatus)); log.debug("Failed to create group {} under component {}, error: {}", groupDefinition.getName(), component.getNormalizedName(), actionStatus.name()); } else { GroupDefinition
1315          * groupDefinitionCreated = addGroupToGraph.left().value(); result = Either.left(groupDefinitionCreated); }
1316          * 
1317          * return result;
1318          * 
1319          * } finally {
1320          * 
1321          * if (false == inTransaction) {
1322          * 
1323          * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); }
1324          * 
1325          * }
1326          * 
1327          * }
1328          * 
1329          * }
1330          * 
1331          * public Either<List<GroupDefinition>, ResponseFormat> updateVfModuleGroupNames(String resourceSystemName, List<GroupDefinition> groups, boolean inTransaction) { List<GroupDefinition> updatedGroups = new ArrayList<>();
1332          * Either<List<GroupDefinition>, ResponseFormat> updateGroupNamesRes = Either.left(updatedGroups); Either<GroupDefinition, StorageOperationStatus> updateGroupNameRes; Either<String, ResponseFormat> validateGenerateGroupNameRes; int counter; for
1333          * (GroupDefinition group : groups) { if (!group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE) && !Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(group.getName()).matches()) { continue; } counter =
1334          * Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1]); validateGenerateGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, group.getDescription(), counter); if (validateGenerateGroupNameRes.isRight()) {
1335          * updateGroupNamesRes = Either.right(validateGenerateGroupNameRes.right().value()); break; } updateGroupNameRes = groupOperation.updateGroupName(group.getUniqueId(), validateGenerateGroupNameRes.left().value(), inTransaction); if
1336          * (updateGroupNameRes.isRight()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(updateGroupNameRes.right().value()); updateGroupNamesRes = Either.right(componentsUtils.getResponseFormat(actionStatus)); break; }
1337          * updatedGroups.add(updateGroupNameRes.left().value()); } return updateGroupNamesRes; }
1338          */
1339
1340         private Either<List<GroupProperty>, ResponseFormat> updateGroupPropertiesValue(String componentId, GroupDefinition currentGroup, List<GroupProperty> groupPropertyToUpdate, boolean inTransaction) {
1341                 Either<List<GroupProperty>, ResponseFormat> result;
1342
1343                 Either<List<GroupProperty>, StorageOperationStatus> eitherUpdate = groupsOperation.updateGroupPropertiesOnComponent(componentId, currentGroup, groupPropertyToUpdate);
1344                 if (eitherUpdate.isRight()) {
1345                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(eitherUpdate.right().value());
1346                         result = Either.right(componentsUtils.getResponseFormat(actionStatus));
1347                 } else {
1348                         result = Either.left(eitherUpdate.left().value());
1349                 }
1350                 return result;
1351         }
1352
1353         public Either<Boolean, ResponseFormat> validateGenerateVfModuleGroupNames(List<ArtifactTemplateInfo> allGroups, String resourceSystemName, int startGroupCounter) {
1354                 Either<Boolean, ResponseFormat> validateGenerateGroupNamesRes = Either.left(true);
1355                 Collections.sort(allGroups, (art1, art2) -> ArtifactTemplateInfo.compareByGroupName(art1, art2));
1356                 for (ArtifactTemplateInfo group : allGroups) {
1357                         Either<String, ResponseFormat> validateGenerateGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, group.getDescription(), startGroupCounter++);
1358                         if (validateGenerateGroupNameRes.isRight()) {
1359                                 validateGenerateGroupNamesRes = Either.right(validateGenerateGroupNameRes.right().value());
1360                                 break;
1361                         }
1362                         group.setGroupName(validateGenerateGroupNameRes.left().value());
1363                 }
1364                 return validateGenerateGroupNamesRes;
1365         }
1366
1367         /**
1368          * Generate module name from resourceName, description and counter
1369          * 
1370          * @param resourceSystemName
1371          * @param description
1372          * @param groupCounter
1373          * @return
1374          */
1375         private Either<String, ResponseFormat> validateGenerateVfModuleGroupName(String resourceSystemName, String description, int groupCounter) {
1376                 Either<String, ResponseFormat> validateGenerateGroupNameRes;
1377                 if (resourceSystemName != null && description != null && Pattern.compile(Constants.MODULE_DESC_PATTERN).matcher(description).matches()) {
1378                         final String fileName = description.replaceAll("\\.\\.", "\\.");
1379                         validateGenerateGroupNameRes = Either.left(String.format(Constants.MODULE_NAME_FORMAT, resourceSystemName, FilenameUtils.removeExtension(fileName), groupCounter));
1380                 } else {
1381                         validateGenerateGroupNameRes = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME));
1382                 }
1383                 return validateGenerateGroupNameRes;
1384         }
1385
1386         public Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNames(Map<String, GroupDefinition> groups, String resourceSystemName) {
1387
1388                 Map<String, GroupDefinition> updatedNamesGroups = new HashMap<>();
1389                 Either<Map<String, GroupDefinition>, ResponseFormat> result = Either.left(updatedNamesGroups);
1390                 for (Entry<String, GroupDefinition> groupEntry : groups.entrySet()) {
1391                         GroupDefinition curGroup = groupEntry.getValue();
1392                         String groupType = curGroup.getType();
1393                         String groupName = groupEntry.getKey();
1394                         int counter;
1395                         String description;
1396                         Either<String, ResponseFormat> newGroupNameRes;
1397                         if (groupType.equals(Constants.DEFAULT_GROUP_VF_MODULE) && !Pattern.compile(Constants.MODULE_NEW_NAME_PATTERN).matcher(groupName).matches()) {
1398
1399                                 if (Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(groupEntry.getKey()).matches()) {
1400                                         counter = Integer.parseInt(groupEntry.getKey().split(Constants.MODULE_NAME_DELIMITER)[1]);
1401                                         description = curGroup.getDescription();
1402                                 } else {
1403                                         counter = getNextVfModuleNameCounter(updatedNamesGroups);
1404                                         description = groupName;
1405                                 }
1406                                 newGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, description, counter);
1407                                 if (newGroupNameRes.isRight()) {
1408                                         log.debug("Failed to generate new vf module group name. Status is {} ", newGroupNameRes.right().value());
1409                                         result = Either.right(newGroupNameRes.right().value());
1410                                         break;
1411                                 }
1412                                 groupName = newGroupNameRes.left().value();
1413                                 curGroup.setName(groupName);
1414                         }
1415                         updatedNamesGroups.put(groupName, curGroup);
1416                 }
1417                 return result;
1418         }
1419
1420         public int getNextVfModuleNameCounter(Map<String, GroupDefinition> groups) {
1421                 int counter = 0;
1422                 if (groups != null && !groups.isEmpty()) {
1423                         counter = getNextVfModuleNameCounter(groups.values());
1424                 }
1425                 return counter;
1426         }
1427
1428         public int getNextVfModuleNameCounter(Collection<GroupDefinition> groups) {
1429                 int counter = 0;
1430                 if (groups != null && !groups.isEmpty()) {
1431                         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())
1432                                         .map(group -> Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1])).collect(Collectors.toList());
1433                         counter = (counters == null || counters.isEmpty()) ? 0 : counters.stream().max((a, b) -> Integer.compare(a, b)).get() + 1;
1434                 }
1435                 return counter;
1436         }
1437
1438         public Either<List<GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesOnGraph(List<GroupDefinition> groups, Component component, boolean inTransaction) {
1439                 List<GroupDefinition> updatedGroups = new ArrayList<>();
1440                 Either<List<GroupDefinition>, ResponseFormat> result = Either.left(updatedGroups);
1441
1442                 for (GroupDefinition group : groups) {
1443                         String groupType = group.getType();
1444                         String oldGroupName = group.getName();
1445                         String newGroupName;
1446                         Either<String, ResponseFormat> newGroupNameRes;
1447                         Either<GroupDefinition, StorageOperationStatus> updateGroupNameRes;
1448                         int counter;
1449                         if (groupType.equals(Constants.DEFAULT_GROUP_VF_MODULE) && Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(oldGroupName).matches()) {
1450                                 counter = Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1]);
1451                                 newGroupNameRes = validateGenerateVfModuleGroupName(component.getSystemName(), group.getDescription(), counter);
1452                                 if (newGroupNameRes.isRight()) {
1453                                         log.debug("Failed to generate new vf module group name. Status is {} ", newGroupNameRes.right().value());
1454                                         result = Either.right(newGroupNameRes.right().value());
1455                                         break;
1456                                 }
1457                                 newGroupName = newGroupNameRes.left().value();
1458                                 group.setName(newGroupName);
1459
1460                         }
1461                         updatedGroups.add(group);
1462
1463                 }
1464
1465                 result = Either.left(updatedGroups);
1466                 return result;
1467         }
1468
1469         /*
1470          * public Either<List<GroupDefinition>, ResponseFormat> createGroups(Component component, User user, ComponentTypeEnum componentType, List<GroupDefinition> groupDefinitions, boolean inTransaction) {
1471          * 
1472          * List<GroupDefinition> generatedGroups = new ArrayList<>(); Either<List<GroupDefinition>, ResponseFormat> result = Either.left(generatedGroups);
1473          * 
1474          * try {
1475          * 
1476          * if (groupDefinitions != null && false == groupDefinitions.isEmpty()) { for (GroupDefinition groupDefinition : groupDefinitions) { Either<GroupDefinition, ResponseFormat> createGroup = this.createGroup(component, user, componentType,
1477          * groupDefinition, true); if (createGroup.isRight()) { result = Either.right(createGroup.right().value()); return result; } GroupDefinition generatedGroup = createGroup.left().value(); generatedGroups.add(generatedGroup); } }
1478          * 
1479          * return result; } finally {
1480          * 
1481          * if (false == inTransaction) {
1482          * 
1483          * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); }
1484          * 
1485          * }
1486          * 
1487          * }
1488          * 
1489          * }
1490          */
1491
1492         public Either<GroupDefinitionInfo, ResponseFormat> getGroupInstWithArtifactsById(ComponentTypeEnum componentType, String componentId, String componentInstanceId, String groupInstId, String userId, boolean inTransaction) {
1493                 Either<GroupDefinitionInfo, ResponseFormat> result = null;
1494
1495                 // Validate user exist
1496                 Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, UPDATE_GROUP, true);
1497
1498                 if (validateUserExists.isRight()) {
1499                         result = Either.right(validateUserExists.right().value());
1500                         return result;
1501                 }
1502
1503                 // Validate component exist
1504                 org.openecomp.sdc.be.model.Component component = null;
1505                 String realComponentId = componentId;
1506
1507                 try {
1508                         ComponentParametersView componentParametersView = new ComponentParametersView();
1509                         componentParametersView.disableAll();
1510                         componentParametersView.setIgnoreUsers(false);
1511                         componentParametersView.setIgnoreComponentInstances(false);
1512                         componentParametersView.setIgnoreArtifacts(false);
1513
1514                         Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView);
1515                         if (validateComponent.isRight()) {
1516                                 result = Either.right(validateComponent.right().value());
1517                                 return result;
1518                         }
1519                         component = validateComponent.left().value();
1520                         Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> findComponentInstanceAndGroupInstanceRes = findComponentInstanceAndGroupInstanceOnComponent(component, componentInstanceId, groupInstId);
1521
1522                         if (findComponentInstanceAndGroupInstanceRes.isRight()) {
1523                                 log.debug("Failed to get group {} . Status is {} ", groupInstId, findComponentInstanceAndGroupInstanceRes.right().value());
1524                                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findComponentInstanceAndGroupInstanceRes.right().value()));
1525                                 result = Either.right(responseFormat);
1526                                 return result;
1527                         }
1528
1529                         GroupInstance group = findComponentInstanceAndGroupInstanceRes.left().value().getRight();
1530                         ComponentInstance componentInstance = findComponentInstanceAndGroupInstanceRes.left().value().getLeft();
1531
1532                         Boolean isBase = null;// Constants.IS_BASE;
1533                         List<? extends GroupProperty> props = group.convertToGroupInstancesProperties();
1534                         if (props != null && !props.isEmpty()) {
1535                                 Optional<? extends GroupProperty> isBasePropOp = props.stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny();
1536                                 if (isBasePropOp.isPresent()) {
1537                                         GroupProperty propIsBase = isBasePropOp.get();
1538                                         isBase = Boolean.parseBoolean(propIsBase.getValue());
1539
1540                                 } else {
1541                                         BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO);
1542                                         // return
1543                                         // Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1544
1545                                 }
1546                         }
1547
1548                         List<ArtifactDefinitionInfo> artifacts = new ArrayList<>();
1549                         List<String> artifactsIds = group.getArtifacts();
1550                         if (artifactsIds != null && !artifactsIds.isEmpty()) {
1551
1552                                 List<ComponentInstance> instances = component.getComponentInstances();
1553                                 if (instances != null) {
1554                                         Optional<ComponentInstance> findFirst = instances.stream().filter(i -> i.getUniqueId().equals(componentInstanceId)).findFirst();
1555                                         if (findFirst.isPresent()) {
1556                                                 ComponentInstance ci = findFirst.get();
1557                                                 Map<String, ArtifactDefinition> deploymentArtifacts = ci.getDeploymentArtifacts();
1558                                                 for (String id : artifactsIds) {
1559                                                         Optional<ArtifactDefinition> artOp = deploymentArtifacts.values().stream().filter(a -> a.getUniqueId().equals(id)).findFirst();
1560                                                         if (artOp.isPresent()) {
1561                                                                 artifacts.add(new ArtifactDefinitionInfo(artOp.get()));
1562                                                         }
1563                                                 }
1564                                                 List<String> instArtifactsIds = group.getGroupInstanceArtifacts();
1565                                                 for (String id : instArtifactsIds) {
1566                                                         Optional<ArtifactDefinition> artOp = deploymentArtifacts.values().stream().filter(a -> a.getUniqueId().equals(id)).findFirst();
1567                                                         if (artOp.isPresent()) {
1568                                                                 artifacts.add(new ArtifactDefinitionInfo(artOp.get()));
1569                                                         }
1570                                                 }
1571                                         }
1572
1573                                 }
1574                         }
1575                         GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group);
1576                         resultInfo.setIsBase(isBase);
1577                         if (!artifacts.isEmpty())
1578                                 resultInfo.setArtifacts(artifacts);
1579
1580                         result = Either.left(resultInfo);
1581
1582                         return result;
1583
1584                 } finally {
1585
1586                         if (false == inTransaction) {
1587
1588                                 if (result == null || result.isRight()) {
1589                                         log.debug("Going to execute rollback on create group.");
1590                                         titanDao.rollback();
1591                                 } else {
1592                                         log.debug("Going to execute commit on create group.");
1593                                         titanDao.commit();
1594                                 }
1595
1596                         }
1597
1598                 }
1599         }
1600
1601         private Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> findComponentInstanceAndGroupInstanceOnComponent(Component component, String componentInstanceId, String groupInstId) {
1602
1603                 Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> result = null;
1604                 if (CollectionUtils.isNotEmpty(component.getComponentInstances())) {
1605                         Optional<GroupInstance> foundGroup;
1606                         Optional<ComponentInstance> foundComponent = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstanceId)).findFirst();
1607                         if (foundComponent.isPresent() && CollectionUtils.isNotEmpty(foundComponent.get().getGroupInstances())) {
1608                                 foundGroup = foundComponent.get().getGroupInstances().stream().filter(gi -> gi.getUniqueId().equals(groupInstId)).findFirst();
1609                                 if (foundGroup.isPresent()) {
1610                                         result = Either.left(new ImmutablePair<>(foundComponent.get(), foundGroup.get()));
1611                                 }
1612                         }
1613                 }
1614                 if (result == null) {
1615                         result = Either.right(StorageOperationStatus.NOT_FOUND);
1616                 }
1617                 return result;
1618         }
1619
1620         private int getLatestIntProperty(Map<PropertyNames, String> newValues, Map<PropertyNames, String> parentValues, PropertyNames propertyKey) {
1621                 String value;
1622                 if (newValues.containsKey(propertyKey)) {
1623                         value = newValues.get(propertyKey);
1624                 } else {
1625                         value = parentValues.get(propertyKey);
1626                 }
1627                 return Integer.valueOf(value);
1628         }
1629
1630         private boolean isPropertyChanged(Map<PropertyNames, String> newValues, Map<PropertyNames, String> parentValues, final PropertyNames minInstances) {
1631                 return newValues.containsKey(minInstances) && newValues.containsKey(minInstances) && !newValues.get(minInstances).equals(parentValues.get(minInstances));
1632         }
1633
1634         private Either<Boolean, ResponseFormat> validateMinMaxAndInitialCountPropertyLogicVF(Map<PropertyNames, String> newValues, Map<PropertyNames, String> parentValues) {
1635
1636                 int latestMaxInstances = getLatestIntProperty(newValues, parentValues, PropertyNames.MAX_INSTANCES);
1637                 int latestInitialCount = getLatestIntProperty(newValues, parentValues, PropertyNames.INITIAL_COUNT);
1638                 int latestMinInstances = getLatestIntProperty(newValues, parentValues, PropertyNames.MIN_INSTANCES);
1639                 Either<Boolean, ResponseFormat> result = Either.left(true);
1640
1641                 if (isPropertyChanged(newValues, parentValues, PropertyNames.INITIAL_COUNT) && result.isLeft()) {
1642                         if (latestInitialCount > latestMaxInstances || latestInitialCount < latestMinInstances) {
1643                                 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_INITIAL_COUNT_PROPERTY_VALUE, PropertyNames.INITIAL_COUNT.getPropertyName(), String.valueOf(latestMinInstances), String.valueOf(latestMaxInstances)));
1644                         }
1645                 }
1646                 if (isPropertyChanged(newValues, parentValues, PropertyNames.MAX_INSTANCES) && result.isLeft()) {
1647                         if (latestMaxInstances < latestInitialCount) {
1648                                 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER, PropertyNames.MAX_INSTANCES.getPropertyName(), "higher", String.valueOf(latestInitialCount)));
1649                         }
1650
1651                 }
1652                 if (isPropertyChanged(newValues, parentValues, PropertyNames.MIN_INSTANCES) && result.isLeft()) {
1653                         if (latestMinInstances > latestInitialCount) {
1654                                 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER, PropertyNames.MIN_INSTANCES.getPropertyName(), "lower", String.valueOf(latestInitialCount)));
1655                         }
1656
1657                 }
1658                 return result;
1659         }
1660
1661         private Either<Boolean, ResponseFormat> validateMinMaxAndInitialCountPropertyLogic(Map<PropertyNames, String> newValues, Map<PropertyNames, String> currValues, Map<PropertyNames, String> parentValues) {
1662
1663                 Either<Boolean, ResponseFormat> result;
1664                 for (Entry<PropertyNames, String> entry : newValues.entrySet()) {
1665                         PropertyNames currPropertyName = entry.getKey();
1666                         if (currPropertyName == PropertyNames.MIN_INSTANCES) {
1667                                 String minValue = parentValues.get(PropertyNames.MIN_INSTANCES);
1668                                 String maxValue = newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MAX_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT);
1669                                 result = validateValueInRange(new ImmutablePair<PropertyNames, String>(currPropertyName, entry.getValue()), new ImmutablePair<PropertyNames, String>(PropertyNames.MIN_INSTANCES, minValue),
1670                                                 new ImmutablePair<PropertyNames, String>(PropertyNames.MAX_INSTANCES, maxValue));
1671                                 if (result.isRight()) {
1672                                         return result;
1673                                 }
1674                         } else if (currPropertyName == PropertyNames.INITIAL_COUNT) {
1675                                 String minValue = newValues.containsKey(PropertyNames.MIN_INSTANCES) ? newValues.get(PropertyNames.MIN_INSTANCES) : currValues.get(PropertyNames.MIN_INSTANCES);
1676                                 String maxValue = newValues.containsKey(PropertyNames.MAX_INSTANCES) ? newValues.get(PropertyNames.MAX_INSTANCES) : currValues.get(PropertyNames.MAX_INSTANCES);
1677                                 result = validateValueInRange(new ImmutablePair<PropertyNames, String>(currPropertyName, entry.getValue()), new ImmutablePair<PropertyNames, String>(PropertyNames.MIN_INSTANCES, minValue),
1678                                                 new ImmutablePair<PropertyNames, String>(PropertyNames.MAX_INSTANCES, maxValue));
1679                                 if (result.isRight()) {
1680                                         return result;
1681                                 }
1682                         } else if (currPropertyName == PropertyNames.MAX_INSTANCES) {
1683                                 String minValue = newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MIN_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT);
1684                                 String maxValue = parentValues.get(PropertyNames.MAX_INSTANCES);
1685                                 result = validateValueInRange(new ImmutablePair<PropertyNames, String>(currPropertyName, entry.getValue()), new ImmutablePair<PropertyNames, String>(PropertyNames.MIN_INSTANCES, minValue),
1686                                                 new ImmutablePair<PropertyNames, String>(PropertyNames.MAX_INSTANCES, maxValue));
1687                                 if (result.isRight()) {
1688                                         return result;
1689                                 }
1690                         }
1691                 }
1692                 return Either.left(true);
1693         }
1694
1695         private Either<Boolean, ResponseFormat> validateValueInRange(ImmutablePair<PropertyNames, String> newValue, ImmutablePair<PropertyNames, String> min, ImmutablePair<PropertyNames, String> max) {
1696                 Either<Boolean, ResponseFormat> result;
1697                 final String warnMessage = "Failed to validate {} as property value of {}. It must be not higher than {}, and not lower than {}.";
1698                 int newValueInt = parseIntValue(newValue.getValue(), newValue.getKey());
1699                 int minInt = parseIntValue(min.getValue(), min.getKey());
1700                 int maxInt = parseIntValue(max.getValue(), max.getKey());
1701                 if (newValueInt < 0 || minInt < 0 || maxInt < 0) {
1702                         result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY));
1703                 } else if (newValueInt < minInt || newValueInt > maxInt) {
1704                         log.debug(warnMessage, newValue.getValue(), newValue.getKey().getPropertyName(), min.getValue(), max.getValue());
1705                         result = Either
1706                                         .right(componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_MIN_MAX_INSTANCES_PROPERTY_VALUE, newValue.getKey().getPropertyName(), maxInt == Integer.MAX_VALUE ? Constants.UNBOUNDED : max.getValue(), min.getValue()));
1707                 } else {
1708                         result = Either.left(true);
1709                 }
1710                 return result;
1711         }
1712
1713         private int parseIntValue(String value, PropertyNames propertyName) {
1714                 int result;
1715                 if (propertyName == PropertyNames.MAX_INSTANCES) {
1716                         result = convertIfUnboundMax(value);
1717                 } else if (NumberUtils.isNumber(value)) {
1718                         result = Integer.parseInt(value);
1719                 } else {
1720                         result = -1;
1721                 }
1722                 return result;
1723         }
1724
1725         /**
1726          * validates received new property values and updates group instance in case of success
1727          * 
1728          * @param oldGroupInstance
1729          * @param groupInstanceId
1730          * @param newProperties
1731          * @param inTransaction
1732          * @return
1733          */
1734         public Either<GroupInstance, ResponseFormat> validateAndUpdateGroupInstancePropertyValues(String componentId, String instanceId, GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties, boolean inTransaction) {
1735
1736                 Either<GroupInstance, ResponseFormat> actionResult = null;
1737                 Either<GroupInstance, StorageOperationStatus> updateGroupInstanceResult = null;
1738                 Either<List<GroupInstanceProperty>, ResponseFormat> validateRes = validateReduceGroupInstancePropertiesBeforeUpdate(oldGroupInstance, newProperties);
1739                 if (validateRes.isRight()) {
1740                         log.debug("Failed to validate group instance {} properties before update. ", oldGroupInstance.getName());
1741                         actionResult = Either.right(validateRes.right().value());
1742                 }
1743                 if (actionResult == null) {
1744                         List<GroupInstanceProperty> validatedReducedNewProperties = validateRes.left().value();
1745                         updateGroupInstanceResult = groupsOperation.updateGroupInstancePropertyValuesOnGraph(componentId, instanceId, oldGroupInstance, validatedReducedNewProperties);
1746                         if (updateGroupInstanceResult.isRight()) {
1747                                 log.debug("Failed to update group instance {} property values. ", oldGroupInstance.getName());
1748                                 actionResult = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateGroupInstanceResult.right().value())));
1749                         }
1750                 }
1751                 if (actionResult == null) {
1752                         actionResult = Either.left(updateGroupInstanceResult.left().value());
1753                 }
1754                 return actionResult;
1755         }
1756
1757         private Either<List<GroupInstanceProperty>, ResponseFormat> validateReduceGroupInstancePropertiesBeforeUpdate(GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties) {
1758
1759                 Either<Boolean, ResponseFormat> validationRes = null;
1760                 Either<List<GroupInstanceProperty>, ResponseFormat> actionResult;
1761                 Map<String, GroupInstanceProperty> existingProperties = oldGroupInstance.convertToGroupInstancesProperties().stream().collect(Collectors.toMap(p -> p.getName(), p -> p));
1762                 Map<PropertyNames, String> newPropertyValues = new EnumMap<>(PropertyNames.class);
1763                 List<GroupInstanceProperty> reducedProperties = new ArrayList<>();
1764                 String currPropertyName;
1765                 try {
1766                         for (GroupInstanceProperty currNewProperty : newProperties) {
1767                                 currPropertyName = currNewProperty.getName();
1768                                 validationRes = handleAndAddProperty(reducedProperties, newPropertyValues, currNewProperty, existingProperties.get(currPropertyName));
1769                                 if (validationRes.isRight()) {
1770                                         log.debug("Failed to handle property {} of group instance {}. ", currPropertyName, oldGroupInstance.getName());
1771                                         break;
1772                                 }
1773                         }
1774                         if (validationRes == null || validationRes.isLeft()) {
1775                                 Map<PropertyNames, String> existingPropertyValues = new EnumMap<>(PropertyNames.class);
1776                                 Map<PropertyNames, String> parentPropertyValues = new EnumMap<>(PropertyNames.class);
1777                                 fillValuesAndParentValuesFromExistingProperties(existingProperties, existingPropertyValues, parentPropertyValues);
1778                                 validationRes = validateMinMaxAndInitialCountPropertyLogic(newPropertyValues, existingPropertyValues, parentPropertyValues);
1779                         }
1780                         if (validationRes.isLeft()) {
1781                                 actionResult = Either.left(reducedProperties);
1782                         } else {
1783                                 actionResult = Either.right(validationRes.right().value());
1784                         }
1785                 } catch (Exception e) {
1786                         log.error("Exception occured during validation and reducing group instance properties. The message is {}", e.getMessage(), e);
1787                         actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1788                 }
1789                 return actionResult;
1790         }
1791
1792         private void fillValuesAndParentValuesFromExistingProperties(Map<String, GroupInstanceProperty> existingProperties, Map<PropertyNames, String> propertyValues, Map<PropertyNames, String> parentPropertyValues) {
1793                 PropertyNames[] allPropertyNames = PropertyNames.values();
1794                 for (PropertyNames name : allPropertyNames) {
1795                         if (isUpdatable(name)) {
1796                                 propertyValues.put(name, String.valueOf(existingProperties.get(name.getPropertyName()).getValue()));
1797                                 parentPropertyValues.put(name, String.valueOf(existingProperties.get(name.getPropertyName()).getParentValue()));
1798                         }
1799                 }
1800         }
1801
1802         private Either<Boolean, ResponseFormat> handleAndAddProperty(List<GroupInstanceProperty> reducedProperties, Map<PropertyNames, String> newPropertyValues, GroupInstanceProperty currNewProperty, GroupInstanceProperty currExistingProperty) {
1803
1804                 Either<Boolean, ResponseFormat> validationRes = null;
1805                 String currPropertyName = currNewProperty.getName();
1806                 PropertyNames propertyName = PropertyNames.findName(currPropertyName);
1807                 try {
1808                         if (currExistingProperty == null) {
1809                                 log.warn("The value of property with the name {} cannot be updated. The property not found on group instance. ", currPropertyName);
1810                         } else if (isUpdatable(propertyName)) {
1811                                 validationRes = validateAndUpdatePropertyValue(currNewProperty, currExistingProperty);
1812                                 if (validationRes.isRight()) {
1813                                         log.debug("Failed to validate property value {} of property {}. ", currNewProperty.getValue(), currPropertyName);
1814                                 } else {
1815                                         addPropertyUpdatedValues(reducedProperties, propertyName, newPropertyValues, currNewProperty, currExistingProperty);
1816                                 }
1817                         } else {
1818                                 validateImmutableProperty(currExistingProperty, currNewProperty);
1819                         }
1820                         if (validationRes == null) {
1821                                 validationRes = Either.left(true);
1822                         }
1823                 } catch (Exception e) {
1824                         log.error("Exception occured during handle and adding property. The message is {}", e.getMessage(), e);
1825                         validationRes = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1826                 }
1827                 return validationRes;
1828         }
1829
1830         private boolean isUpdatable(PropertyNames updatablePropertyName) {
1831                 return updatablePropertyName != null && updatablePropertyName.getUpdateBehavior().getLevelNumber() >= GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL.getLevelNumber();
1832         }
1833
1834         private void addPropertyUpdatedValues(List<GroupInstanceProperty> reducedProperties, PropertyNames propertyName, Map<PropertyNames, String> newPropertyValues, GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) {
1835
1836                 String newValue = newProperty.getValue();
1837                 if (!newValue.equals(String.valueOf(existingProperty.getValue()))) {
1838                         newProperty.setValueUniqueUid(existingProperty.getValueUniqueUid());
1839                         reducedProperties.add(newProperty);
1840                 }
1841                 if (!isEmptyMinInitialCountValue(propertyName, newValue)) {
1842                         newPropertyValues.put(propertyName, newValue);
1843                 }
1844         }
1845
1846         private boolean isEmptyMinInitialCountValue(PropertyNames propertyName, String newValue) {
1847                 boolean result = false;
1848                 if ((propertyName == PropertyNames.MIN_INSTANCES || propertyName == PropertyNames.INITIAL_COUNT) && !NumberUtils.isNumber(newValue)) {
1849                         result = true;
1850                 }
1851                 return result;
1852         }
1853
1854         private int convertIfUnboundMax(String value) {
1855
1856                 int result;
1857                 if (!NumberUtils.isNumber(value)) {
1858                         result = Integer.MAX_VALUE;
1859                 } else {
1860                         result = Integer.parseInt(value);
1861                 }
1862                 return result;
1863         }
1864
1865         private Either<Boolean, ResponseFormat> validateAndUpdatePropertyValue(GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) {
1866
1867                 Either<Boolean, ResponseFormat> validationRes = null;
1868                 String parentValue = existingProperty.getParentValue();
1869
1870                 newProperty.setParentValue(parentValue);
1871                 if (StringUtils.isEmpty(newProperty.getValue())) {
1872                         newProperty.setValue(parentValue);
1873                 }
1874                 if (StringUtils.isEmpty(existingProperty.getValue())) {
1875                         existingProperty.setValue(parentValue);
1876                 }
1877                 StorageOperationStatus status = groupOperation.validateAndUpdatePropertyValue(newProperty);
1878                 if (status != StorageOperationStatus.OK) {
1879                         log.debug("Failed to validate property value {} of property with name {}. Status is {}. ", newProperty.getValue(), newProperty.getName(), status);
1880                         validationRes = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
1881                 }
1882                 if (validationRes == null) {
1883                         validationRes = Either.left(true);
1884                 }
1885                 return validationRes;
1886         }
1887
1888         private void validateImmutableProperty(GroupProperty oldProperty, GroupProperty newProperty) {
1889                 if (oldProperty.getValue() == null && newProperty.getValue() != null || oldProperty.getValue() != null && !oldProperty.getValue().equals(newProperty.getValue())) {
1890                         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());
1891                 }
1892         }
1893
1894         public Either<List<GroupDefinition>, ResponseFormat> createGroups(Component component, User user, ComponentTypeEnum componentType, List<GroupDefinition> groupDefinitions) {
1895
1896                 Map<String, GroupDataDefinition> groups = new HashMap<>();
1897                 // Map<String, MapPropertiesDataDefinition> groupsPropertiesMap = new HashMap<>();
1898                 Either<List<GroupDefinition>, ResponseFormat> result = null;
1899                 Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult = null;
1900                 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
1901                 if (allDataTypes.isRight()) {
1902                         TitanOperationStatus status = allDataTypes.right().value();
1903                         BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR);
1904                         return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
1905
1906                 }
1907
1908                 // handle groups and convert to tosca data
1909                 if (groupDefinitions != null && !groupDefinitions.isEmpty()) {
1910                         for (GroupDefinition groupDefinition : groupDefinitions) {
1911                                 Either<GroupDefinition, ResponseFormat> handleGroupRes = handleGroup(component, user, componentType, groupDefinition, allDataTypes.left().value());
1912                                 if (handleGroupRes.isRight()) {
1913                                         result = Either.right(handleGroupRes.right().value());
1914                                         break;
1915                                 }
1916                                 GroupDefinition handledGroup = handleGroupRes.left().value();
1917                                 groups.put(handledGroup.getName(), new GroupDataDefinition(handledGroup));
1918
1919                         }
1920                 }
1921                 if (result == null) {
1922                         createGroupsResult = groupsOperation.createGroups(component, user, componentType, groups);
1923                         if (createGroupsResult.isRight()) {
1924                                 result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value())));
1925                         }
1926                 }
1927                 if (result == null) {
1928                         result = Either.left(createGroupsResult.left().value());
1929                 }
1930                 return result;
1931         }
1932
1933         public Either<List<GroupDefinition>, ResponseFormat> addGroups(Component component, User user, ComponentTypeEnum componentType, List<GroupDefinition> groupDefinitions) {
1934
1935                 Either<List<GroupDefinition>, ResponseFormat> result = null;
1936                 Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult = null;
1937                 List<GroupDataDefinition> groups = new ArrayList<>();
1938
1939                 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
1940                 if (allDataTypes.isRight()) {
1941                         TitanOperationStatus status = allDataTypes.right().value();
1942                         BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR);
1943                         return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
1944
1945                 }
1946
1947                 // handle groups and convert to tosca data
1948                 if (groupDefinitions != null && !groupDefinitions.isEmpty()) {
1949                         for (GroupDefinition groupDefinition : groupDefinitions) {
1950                                 Either<GroupDefinition, ResponseFormat> handleGroupRes = handleGroup(component, user, componentType, groupDefinition, allDataTypes.left().value());
1951                                 if (handleGroupRes.isRight()) {
1952                                         result = Either.right(handleGroupRes.right().value());
1953                                         break;
1954                                 }
1955                                 GroupDefinition handledGroup = handleGroupRes.left().value();
1956                                 groups.add(new GroupDataDefinition(handledGroup));
1957                         }
1958                 }
1959                 if (result == null) {
1960                         createGroupsResult = groupsOperation.addGroups(component, user, componentType, groups);
1961                         if (createGroupsResult.isRight()) {
1962                                 result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value())));
1963                         }
1964                 }
1965                 if (result == null) {
1966                         result = Either.left(createGroupsResult.left().value());
1967                 }
1968                 return result;
1969         }
1970
1971         public Either<List<GroupDefinition>, ResponseFormat> deleteGroups(Component component, User user, ComponentTypeEnum componentType, List<GroupDefinition> groupDefinitions) {
1972
1973                 Either<List<GroupDefinition>, ResponseFormat> result = null;
1974                 Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult = null;
1975
1976                 createGroupsResult = groupsOperation.deleteGroups(component, user, componentType, groupDefinitions.stream().map(x -> new GroupDataDefinition(x)).collect(Collectors.toList()));
1977                 if (createGroupsResult.isRight()) {
1978                         result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value())));
1979                 }
1980
1981                 if (result == null) {
1982                         result = Either.left(createGroupsResult.left().value());
1983                 }
1984                 return result;
1985         }
1986
1987         /**
1988          * Update specific group version
1989          * 
1990          * @param groupDefinition
1991          * @param inTransaction
1992          * @return
1993          */
1994         public Either<List<GroupDefinition>, ResponseFormat> updateGroups(Component component, ComponentTypeEnum componentType, List<GroupDefinition> groupDefinitions) {
1995
1996                 Either<List<GroupDefinition>, ResponseFormat> result = null;
1997                 Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult = null;
1998
1999                 createGroupsResult = groupsOperation.updateGroups(component, componentType, groupDefinitions.stream().map(x -> new GroupDataDefinition(x)).collect(Collectors.toList()));
2000                 if (createGroupsResult.isRight()) {
2001                         result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value())));
2002                 }
2003
2004                 if (result == null) {
2005                         result = Either.left(createGroupsResult.left().value());
2006                 }
2007                 return result;
2008         }
2009
2010         public Either<GroupDefinition, ResponseFormat> handleGroup(Component component, User user, ComponentTypeEnum componentType, GroupDefinition groupDefinition, Map<String, DataTypeDefinition> allDAtaTypes) {
2011
2012                 Either<GroupDefinition, ResponseFormat> result = null;
2013
2014                 log.trace("Going to create group {}", groupDefinition);
2015                 // 3. verify group not already exist
2016                 List<GroupDefinition> groups = component.getGroups();
2017                 boolean found = false;
2018                 if (groups != null && false == groups.isEmpty()) {
2019
2020                         GroupDefinition existGroupDef = groups.stream().filter(p -> p.getName().equalsIgnoreCase(groupDefinition.getName())).findFirst().orElse(null);
2021
2022                         found = existGroupDef != null;
2023                 }
2024                 if (true == found) {
2025                         String componentTypeForResponse = getComponentTypeForResponse(component);
2026                         result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ALREADY_EXIST, groupDefinition.getName(), component.getNormalizedName(), componentTypeForResponse));
2027                         return result;
2028                 }
2029                 // 4. verify type of group exist
2030                 String groupType = groupDefinition.getType();
2031                 if (groupType == null || groupType.isEmpty()) {
2032                         result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_MISSING_GROUP_TYPE, groupDefinition.getName()));
2033                         return result;
2034                 }
2035                 Either<GroupTypeDefinition, StorageOperationStatus> getGroupType = groupTypeOperation.getLatestGroupTypeByType(groupType, true);
2036                 if (getGroupType.isRight()) {
2037                         StorageOperationStatus status = getGroupType.right().value();
2038                         if (status == StorageOperationStatus.NOT_FOUND) {
2039                                 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "group type " + groupType + " cannot be found", ErrorSeverity.INFO);
2040                                 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, groupType));
2041                                 return result;
2042                         } else {
2043                                 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2044                                 return result;
2045                         }
2046                 }
2047                 // 6. verify the component instances type are allowed according to
2048                 // the member types in the group type
2049                 GroupTypeDefinition groupTypeDefinition = getGroupType.left().value();
2050
2051                 Either<Boolean, ResponseFormat> areValidMembers = verifyComponentInstancesAreValidMembers(component, componentType, groupDefinition.getName(), groupType, groupDefinition.getMembers(), groupTypeDefinition.getMembers());
2052
2053                 if (areValidMembers.isRight()) {
2054                         ResponseFormat responseFormat = areValidMembers.right().value();
2055                         result = Either.right(responseFormat);
2056                         return result;
2057                 }
2058                 // 7. verify the artifacts belongs to the component
2059                 Either<Boolean, ResponseFormat> areValidArtifacts = verifyArtifactsBelongsToComponent(component, groupDefinition.getArtifacts(), CREATE_GROUP);
2060                 if (areValidArtifacts.isRight()) {
2061                         ResponseFormat responseFormat = areValidArtifacts.right().value();
2062                         result = Either.right(responseFormat);
2063                         return result;
2064                 }
2065                 List<PropertyDefinition> groupTypeProperties = groupTypeDefinition.getProperties();
2066
2067                 List<GroupProperty> properties = groupDefinition.convertToGroupProperties();
2068                 List<GroupProperty> updatedGroupTypeProperties = new ArrayList<>();
2069                 if (properties != null && false == properties.isEmpty()) {
2070
2071                         if (groupTypeProperties == null || true == groupTypeProperties.isEmpty()) {
2072                                 BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "group type does not have properties", ErrorSeverity.INFO);
2073                                 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.MATCH_NOT_FOUND))));
2074                         }
2075
2076                         Map<String, PropertyDefinition> groupTypePropertiesMap = groupTypeProperties.stream().collect(Collectors.toMap(p -> p.getName(), p -> p));
2077
2078                         Either<GroupProperty, TitanOperationStatus> addPropertyResult = null;
2079                         int i = 1;
2080                         for (GroupProperty prop : properties) {
2081                                 addPropertyResult = handleProperty(prop, groupTypePropertiesMap.get(prop.getName()), i, allDAtaTypes);
2082                                 if (addPropertyResult.isRight()) {
2083                                         BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "failed to validate property", ErrorSeverity.INFO);
2084                                         return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertyResult.right().value()))));
2085                                 }
2086                                 updatedGroupTypeProperties.add(addPropertyResult.left().value());
2087
2088                                 i++;
2089                         }
2090                 }
2091                 if (groupDefinition.getUniqueId() == null) {
2092                         String uid = UniqueIdBuilder.buildGroupingUid(component.getUniqueId(), groupDefinition.getName());
2093                         groupDefinition.setUniqueId(uid);
2094                 }
2095                 groupDefinition.convertFromGroupProperties(updatedGroupTypeProperties);
2096                 groupDefinition.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
2097                 groupDefinition.setGroupUUID(UniqueIdBuilder.generateUUID());
2098                 groupDefinition.setVersion(INITIAL_VERSION);
2099                 groupDefinition.setTypeUid(groupTypeDefinition.getUniqueId());
2100
2101                 return Either.left(groupDefinition);
2102         }
2103
2104         public Either<GroupProperty, TitanOperationStatus> handleProperty(GroupProperty groupProperty, PropertyDefinition prop, Integer index, Map<String, DataTypeDefinition> allDataTypes) {
2105
2106                 if (prop == null) {
2107                         return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
2108                 }
2109
2110                 PropertyDataDefinition propDataDef = prop;
2111                 String propertyType = propDataDef.getType();
2112                 String value = groupProperty.getValue();
2113
2114                 Either<String, TitanOperationStatus> checkInnerType = propertyOperation.checkInnerType(propDataDef);
2115                 if (checkInnerType.isRight()) {
2116                         TitanOperationStatus status = checkInnerType.right().value();
2117                         return Either.right(status);
2118                 }
2119
2120                 String innerType = checkInnerType.left().value();
2121
2122                 log.debug("Before validateAndUpdatePropertyValue");
2123                 Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes);
2124                 log.debug("After validateAndUpdatePropertyValue. isValid = {}", isValid);
2125
2126                 String newValue = value;
2127                 if (isValid.isRight()) {
2128                         Boolean res = isValid.right().value();
2129                         if (res == false) {
2130                                 return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
2131                         }
2132                 } else {
2133                         Object object = isValid.left().value();
2134                         if (object != null) {
2135                                 newValue = object.toString();
2136                         }
2137                 }
2138
2139                 String uniqueId = UniqueIdBuilder.buildGroupPropertyValueUid((String) prop.getUniqueId(), index);
2140
2141                 groupProperty.setUniqueId(uniqueId);
2142                 groupProperty.setValue(newValue);
2143                 groupProperty.setType(prop.getType());
2144                 groupProperty.setDefaultValue(prop.getDefaultValue());
2145                 groupProperty.setDescription(prop.getDescription());
2146                 groupProperty.setSchema(prop.getSchema());
2147                 groupProperty.setPassword(prop.isPassword());
2148                 groupProperty.setParentUniqueId(prop.getUniqueId());
2149
2150                 log.debug("Before adding property value to graph {}", groupProperty);
2151
2152                 return Either.left(groupProperty);
2153         }
2154
2155 }