2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.sdc.be.components.impl;
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;
32 import java.util.Map.Entry;
33 import java.util.Optional;
35 import java.util.function.Function;
36 import java.util.regex.Pattern;
37 import java.util.stream.Collectors;
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;
89 import com.google.gson.Gson;
90 import com.google.gson.GsonBuilder;
91 import com.google.gson.JsonSyntaxException;
93 import fj.data.Either;
95 @org.springframework.stereotype.Component("groupBusinessLogic")
96 public class GroupBusinessLogic extends BaseBusinessLogic {
97 private static String ADDING_GROUP = "AddingGroup";
99 public static final String INITIAL_VERSION = "1";
101 private static final String CREATE_GROUP = "CreateGroup";
103 private static final String UPDATE_GROUP = "UpdateGroup";
105 private static final String GET_GROUP = "GetGroup";
107 private static Logger log = LoggerFactory.getLogger(GroupBusinessLogic.class.getName());
109 public GroupBusinessLogic() {
113 @javax.annotation.Resource
114 private GroupTypeOperation groupTypeOperation;
117 ArtifactsOperations artifactsOperation;
120 private GroupsOperation groupsOperation;
122 private ApplicationDataTypeCache dataTypeCache;
126 * 1. validate user exist
128 * 2. validate component can be edited
130 * 3. verify group not already exist
132 * 4. verify type of group exist
134 * 5. verify Component instances exist under the component
136 * 6. verify the component instances type are allowed according to the member types in the group type
138 * 7. verify the artifacts belongs to the component
142 * @param componentType
143 * @param groupDefinition
144 * @param inTransaction
148 * public Either<GroupDefinition, ResponseFormat> createGroup(String componentId, String userId, ComponentTypeEnum componentType, GroupDefinition groupDefinition, boolean inTransaction) {
150 * Either<GroupDefinition, ResponseFormat> result = null;
152 * try { Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, CREATE_GROUP, inTransaction);
154 * if (validateUserExists.isRight()) { result = Either.right(validateUserExists.right().value()); return result; }
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;
158 * // String realComponentId = componentType == // ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId; String realComponentId = componentId;
160 * ComponentParametersView componentParametersView = new ComponentParametersView(); componentParametersView.disableAll(); componentParametersView.setIgnoreGroups(false); componentParametersView.setIgnoreArtifacts(false);
161 * componentParametersView.setIgnoreUsers(false); componentParametersView.setIgnoreComponentInstances(false);
163 * Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView);
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; }
168 * result = this.createGroup(component, user, componentType, groupDefinition, inTransaction); return result;
172 * if (false == inTransaction) {
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(); }
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();
186 return componentTypeForResponse;
190 * Verify that the artifact members belongs to the component
196 private Either<Boolean, ResponseFormat> verifyArtifactsBelongsToComponent(Component component, List<String> artifacts, String context) {
198 if (artifacts == null || true == artifacts.isEmpty()) {
199 return Either.left(true);
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));
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));
215 return Either.left(true);
220 * verify that the members are component instances of the component
223 * @param componentType
224 * @param groupMembers
225 * @param memberToscaTypes
228 private Either<Boolean, ResponseFormat> verifyComponentInstancesAreValidMembers(Component component, ComponentTypeEnum componentType, String groupName, String groupType, Map<String, String> groupMembers, List<String> memberToscaTypes) {
230 if (groupMembers == null || true == groupMembers.isEmpty()) {
231 return Either.left(true);
234 if (memberToscaTypes == null || true == memberToscaTypes.isEmpty()) {
235 return Either.left(true);
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));
242 Set<String> allCompInstances = compInstUidToCompInstMap.keySet();
244 for (Entry<String, String> groupMember : groupMembers.entrySet()) {
245 String compName = groupMember.getKey();
246 String compUid = groupMember.getValue();
248 if (false == allCompInstances.contains(compUid)) {
250 * %1 - member name %2 - group name %3 - VF name %4 - component type [VF ]
252 String componentTypeForResponse = getComponentTypeForResponse(component);
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));
259 // ComponentOperation componentOperation = getComponentOperationByParentComponentType(componentType);
260 // if (componentOperation instanceof ResourceOperation) {
261 // ResourceOperation resourceOperation = (ResourceOperation) componentOperation;
263 // for (Entry<String, String> groupMember : groupMembers.entrySet()) {
265 // String componentInstName = groupMember.getKey();
266 // String componentInstUid = groupMember.getValue();
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));
277 // log.debug("The tosca names of component id {} are {}", componentUid, memberToscaTypes);
279 // boolean found = false;
280 // for (String memberToscaType : memberToscaTypes) {
281 // if (componentToscaNames.contains(memberToscaType)) {
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);
290 // * # %1 - member name # %2 - group name # %3 - group type
292 // return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_TOSCA_NAME_OF_COMPONENT_INSTANCE, componentInstName, groupName, groupType));
294 // log.debug("Component instance {} fits to one of the required tosca types", componentInstance.getNormalizedName());
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));
304 return Either.left(true);
308 * Update specific group version
310 * @param groupDefinition
311 * @param inTransaction
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
322 * Update list of groups versions
324 * @param groupsUniqueId
325 * @param inTransaction
329 * public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupVersion(List<String> groupsUniqueId, boolean inTransaction) {
331 * Either<List<GroupDefinition>, StorageOperationStatus> result = null;
335 * result = groupOperation.updateGroupVersion(groupsUniqueId, true);
341 * if (false == inTransaction) {
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(); }
353 * Update GroupDefinition metadata
357 * @param componentType
358 * @param updatedGroup
359 * @param inTransaction
362 public Either<GroupDefinition, ResponseFormat> validateAndUpdateGroupMetadata(String componentId, User user, ComponentTypeEnum componentType, GroupDefinition updatedGroup, boolean inTransaction) {
364 Either<GroupDefinition, ResponseFormat> result = null;
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());
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());
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());
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()));
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()));
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());
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);
411 result = updateGroupMetadata(component, currentGroup, updatedGroup);
415 if (result.isLeft()) {
420 graphLockOperation.unlockComponent(componentId, componentType.getNodeType());
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);
428 if (result.isRight()) {
429 log.debug("Failed to validate a metadata of the group {} on component {}. ", updatedGroup.getName(), component.getName());
431 if (result.isLeft()) {
432 result = updateGroup(component, currentGroup, currentGroupName);
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())));
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)));
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())));
458 if (result == null) {
459 result = Either.left(updatedGroup);
465 * Validate and Update Group Property
468 * @param groupUniqueId
470 * @param componentType
471 * @param groupPropertiesToUpdate
472 * @param inTransaction
475 public Either<List<GroupProperty>, ResponseFormat> validateAndUpdateGroupProperties(String componentId, String groupUniqueId, User user, ComponentTypeEnum componentType, List<GroupProperty> groupPropertiesToUpdate, boolean inTransaction) {
477 Either<List<GroupProperty>, ResponseFormat> result = Either.left(groupPropertiesToUpdate);
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));
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)).
495 if (!optionalGroupConnectedToVf.isPresent()) {
496 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, groupUniqueId, vf.getName(), ComponentTypeEnum.RESOURCE.getValue()));
500 if (result.isLeft()) {
501 currentGroup = optionalGroupConnectedToVf.get();
502 result = validateGroupPropertyAndResetEmptyValue(currentGroup, groupPropertiesToUpdate);
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);
512 } catch (Exception e) {
513 log.debug("Error in validateAndUpdateGroupProperty {}", e);
514 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
516 graphLockOperation.unlockComponent(componentId, componentType.getNodeType());
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());
535 private Either<List<GroupProperty>, ResponseFormat> validateGroupPropertyAndResetEmptyValue(GroupDefinition originalGroup, List<GroupProperty> groupPropertiesToUpdate) {
537 Either<List<GroupProperty>, ResponseFormat> ret = validateOnlyValueChanged(groupPropertiesToUpdate, originalGroup);
539 resetEmptyValueWithDefaults(groupPropertiesToUpdate, originalGroup);
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).
552 if (optionalError.isPresent()) {
553 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(optionalError.get());
554 ret = Either.right(componentsUtils.getResponseFormat(actionStatus));
559 // Validate min max ect...
560 ret = validatePropertyBusinessLogic(groupPropertiesToUpdate, originalGroup);
566 private Either<List<GroupProperty>, ResponseFormat> validatePropertyBusinessLogic(List<GroupProperty> groupPropertiesToUpdate, GroupDefinition originalGroup) {
568 Either<List<GroupProperty>, ResponseFormat> ret = Either.left(groupPropertiesToUpdate);
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());
579 if (!MapUtils.isEmpty(nameValueMap)) {
581 if (nameValueMap.containsKey(PropertyNames.INITIAL_COUNT) || nameValueMap.containsKey(PropertyNames.MAX_INSTANCES) || nameValueMap.containsKey(PropertyNames.MIN_INSTANCES)) {
583 Map<PropertyNames, String> oldValueMap = prepareMapWithOriginalProperties(originalGroup);
585 Either<Boolean, ResponseFormat> eitherValid = validateMinMaxAndInitialCountPropertyLogicVF(nameValueMap, oldValueMap);
586 if (eitherValid.isRight()) {
587 ret = Either.right(eitherValid.right().value());
590 if (ret.isLeft() && (nameValueMap.containsKey(PropertyNames.VF_MODULE_DESCRIPTION) || nameValueMap.containsKey(PropertyNames.VF_MODULE_LABEL))) {
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())
605 if (optionalError.isPresent()) {
606 ret = Either.right(optionalError.get());
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 };
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());
624 if (StringUtils.isEmpty(oldValueMap.get(PropertyNames.MAX_INSTANCES))) {
625 oldValueMap.put(PropertyNames.MAX_INSTANCES, String.valueOf(Integer.MAX_VALUE));
630 private Either<List<GroupProperty>, ResponseFormat> validateOnlyValueChanged(List<GroupProperty> groupPropertiesToUpdate, GroupDefinition originalGroup) {
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()));
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));
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())).
652 if (optionalMissingProperty.isPresent()) {
653 ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, optionalMissingProperty.get().getName()));
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()))).
662 if (optionalNonValueChange.isPresent()) {
663 ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY, optionalNonValueChange.get().getName()));
673 * if groupProperty are the same or if only value is different returns true, otherwise returns false.
675 * @param groupProperty
676 * @param groupProperty2
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();
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);
700 * Validate and update GroupDefinition metadata
703 * @param currentGroup
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);
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);
722 return Either.left(currentGroup);
726 * Validate and update GroupDefinition name
729 * @param currentGroup
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);
742 currentGroup.setName(groupUpdate.getName());
744 return Either.left(true);
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.
751 * @param currentGroupName
752 * @param groupUpdateName
755 private Either<Boolean, ResponseFormat> validateGroupName(String currentGroupName, String groupUpdateName) {
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));
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];
771 String[] split2 = groupUpdateName.split("\\.\\.");
772 String groupUpdateResourceName = split2[0];
773 String groupUpdateCounter = split2[2];
775 if (!currentResourceName.equals(groupUpdateResourceName)) {
776 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME_MODIFICATION, currentResourceName));
779 if (!currentCounter.equals(groupUpdateCounter)) {
780 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME_MODIFICATION, currentCounter));
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));
792 * associate artifacts to a given group
796 * @param componentType
798 * @param shouldLockComp
799 * @param inTransaction
803 * public Either<List<GroupDefinition>, ResponseFormat> associateArtifactsToGroup(String componentId, String userId, ComponentTypeEnum componentType, List<GroupDefinition> groups, boolean shouldLockComp, boolean inTransaction) {
805 * Either<List<GroupDefinition>, ResponseFormat> result = null;
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; }
810 * Component component = null; try {
812 * if (groups == null || groups.isEmpty()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.OK)); }
814 * Either<Component, ResponseFormat> validateGroupsBeforeUpdate = validateGroupsBeforeUpdate(componentId, userId, componentType, groups, inTransaction); if (validateGroupsBeforeUpdate.isRight()) { result =
815 * Either.right(validateGroupsBeforeUpdate.right().value()); return result; }
817 * component = validateGroupsBeforeUpdate.left().value();
819 * if (shouldLockComp) { Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Group - Associate Artifacts"); if (lockComponent.isRight()) { return Either.right(lockComponent.right().value()); } }
821 * List<GroupDefinition> updatedGroups = new ArrayList<>();
823 * List<GroupDefinition> componentGroups = component.getGroups();
825 * // per group, associate to it the artifacts for (GroupDefinition groupDefinition : groups) {
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();
830 * // if no artifcats sent if (artifactsToAssociate == null || true == artifactsToAssociate.isEmpty()) { continue; }
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())); } } }
835 * Either<GroupDefinition, StorageOperationStatus> associateArtifactsToGroup = groupOperation.associateArtifactsToGroup(groupDefinition.getUniqueId(), groupDefinition.getArtifacts(), true);
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());
842 * result = Either.left(updatedGroups); return result;
846 * if (false == inTransaction) {
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(); }
852 * // unlock resource if (shouldLockComp && component != null) { graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); }
858 * public Either<List<GroupDefinition>, ResponseFormat> associateMembersToGroup(String componentId, String userId, ComponentTypeEnum componentType, List<GroupDefinition> groups, boolean shouldLockComp, boolean inTransaction) {
860 * Either<List<GroupDefinition>, ResponseFormat> result = null;
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; }
865 * Component component = null; try {
867 * if (groups == null || groups.isEmpty()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.OK)); }
869 * Either<Component, ResponseFormat> validateGroupsBeforeUpdate = validateGroupsBeforeUpdate(componentId, userId, componentType, groups, inTransaction); if (validateGroupsBeforeUpdate.isRight()) { result =
870 * Either.right(validateGroupsBeforeUpdate.right().value()); return result; }
872 * component = validateGroupsBeforeUpdate.left().value();
874 * if (shouldLockComp) { Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Group - Associate Members"); if (lockComponent.isRight()) { return Either.right(lockComponent.right().value()); } }
876 * List<GroupDefinition> updatedGroups = new ArrayList<>();
878 * // per group, associate to it the members for (GroupDefinition groupDefinition : groups) {
880 * Either<GroupDefinition, StorageOperationStatus> associateMembersToGroup = groupOperation.associateMembersToGroup(groupDefinition.getUniqueId(), groupDefinition.getMembers(), true);
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()); }
887 * result = Either.left(updatedGroups); return result;
891 * if (false == inTransaction) {
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(); }
897 * // unlock resource if (shouldLockComp && component != null) { graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); }
903 * associate artifacts to a given group
907 * @param componentType
909 * @param shouldLockComp
910 * @param inTransaction
913 public Either<GroupDefinitionInfo, ResponseFormat> getGroupWithArtifactsById(ComponentTypeEnum componentType, String componentId, String groupId, String userId, boolean inTransaction) {
915 Either<GroupDefinitionInfo, ResponseFormat> result = null;
917 // Validate user exist
918 Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, UPDATE_GROUP, true);
920 if (validateUserExists.isRight()) {
921 result = Either.right(validateUserExists.right().value());
925 // Validate component exist
926 org.openecomp.sdc.be.model.Component component = null;
927 String realComponentId = componentId;
930 ComponentParametersView componentParametersView = new ComponentParametersView();
931 componentParametersView.disableAll();
932 componentParametersView.setIgnoreGroups(false);
933 componentParametersView.setIgnoreArtifacts(false);
934 componentParametersView.setIgnoreUsers(false);
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());
941 component = validateComponent.left().value();
943 Either<GroupDefinition, StorageOperationStatus> groupEither = findGroupOnComponent(component, groupId);
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));
952 GroupDefinition group = groupEither.left().value();
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());
963 BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO);
965 // Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
970 List<ArtifactDefinitionInfo> artifacts = new ArrayList<>();
971 List<ArtifactDefinition> artifactsFromComponent = new ArrayList<>();
972 List<String> artifactsIds = group.getArtifacts();
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));
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);
987 artifactsFromComponent.add(deploymentArtifacts.get(id));
989 if (!artifactsFromComponent.isEmpty()) {
990 for (ArtifactDefinition artifactDefinition : artifactsFromComponent) {
991 ArtifactDefinitionInfo artifactDefinitionInfo = new ArtifactDefinitionInfo(artifactDefinition);
992 artifacts.add(artifactDefinitionInfo);
997 GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group);
998 resultInfo.setIsBase(isBase);
999 if (!artifacts.isEmpty())
1000 resultInfo.setArtifacts(artifacts);
1002 result = Either.left(resultInfo);
1008 if (false == inTransaction) {
1010 if (result == null || result.isRight()) {
1011 log.debug("Going to execute rollback on create group.");
1012 titanDao.rollback();
1014 log.debug("Going to execute commit on create group.");
1024 private Either<GroupDefinition, StorageOperationStatus> findGroupOnComponent(Component component, String groupId) {
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());
1033 if (result == null) {
1034 result = Either.right(StorageOperationStatus.NOT_FOUND);
1040 * @param componentId
1042 * @param componentType
1044 * @param inTransaction
1047 private Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateGroupsBeforeUpdate(String componentId, String userId, ComponentTypeEnum componentType, List<GroupDefinition> groups, boolean inTransaction) {
1049 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> result;
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());
1058 // Validate component exist
1059 String realComponentId = componentId;
1061 ComponentParametersView componentParametersView = new ComponentParametersView();
1062 componentParametersView.disableAll();
1063 componentParametersView.setIgnoreGroups(false);
1064 componentParametersView.setIgnoreArtifacts(false);
1065 componentParametersView.setIgnoreUsers(false);
1066 componentParametersView.setIgnoreComponentInstances(false);
1068 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView);
1070 if (validateComponent.isRight()) {
1071 result = Either.right(validateComponent.right().value());
1074 org.openecomp.sdc.be.model.Component component = validateComponent.left().value();
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());
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);
1090 Set<String> artifacts = new HashSet<>();
1091 groups.forEach(p -> {
1092 if (p.getArtifacts() != null) {
1093 artifacts.addAll(p.getArtifacts());
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());
1103 return Either.left(component);
1110 * - the method to fetch the key of the GroupDefinition(from groups) in order to compare to groups in the component
1113 private ResponseFormat validateGroupsInComponentByFunc(List<GroupDefinition> groups, org.openecomp.sdc.be.model.Component component, Function<GroupDefinition, String> getByParam) {
1114 ResponseFormat result = null;
1116 List<GroupDefinition> currentGroups = component.getGroups();
1118 boolean found = false;
1119 List<String> updatedGroupsName = groups.stream().map(getByParam).collect(Collectors.toList());
1121 List<String> missingGroupNames = updatedGroupsName;
1123 if (currentGroups != null && false == currentGroups.isEmpty()) {
1124 List<String> currentGroupsName = currentGroups.stream().map(getByParam).collect(Collectors.toList());
1126 if (currentGroupsName.containsAll(updatedGroupsName)) {
1129 currentGroupsName.removeAll(currentGroupsName);
1130 missingGroupNames = currentGroupsName;
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);
1143 public String getAsString(List<String> list) {
1145 if (list == null || list.isEmpty()) {
1148 StringBuilder builder = new StringBuilder();
1149 list.forEach(p -> builder.append(p + ","));
1151 String result = builder.toString();
1152 return result.substring(0, result.length());
1157 * dissociate artifacts from a given group
1159 * @param componentId
1161 * @param componentType
1163 * @param shouldLockComp
1164 * @param inTransaction
1168 * public Either<List<GroupDefinition>, ResponseFormat> dissociateArtifactsFromGroup(String componentId, String userId, ComponentTypeEnum componentType, List<GroupDefinition> groups, boolean shouldLockComp, boolean inTransaction) {
1170 * Either<List<GroupDefinition>, ResponseFormat> result = null;
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; }
1175 * Component component = null;
1179 * if (groups == null || groups.isEmpty()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.OK)); }
1181 * Either<Component, ResponseFormat> validateGroupsBeforeUpdate = validateGroupsBeforeUpdate(componentId, userId, componentType, groups, inTransaction); if (validateGroupsBeforeUpdate.isRight()) { result =
1182 * Either.right(validateGroupsBeforeUpdate.right().value()); return result; }
1184 * component = validateGroupsBeforeUpdate.left().value();
1186 * if (shouldLockComp) { Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Group - Dissociate Artifacts"); if (lockComponent.isRight()) { return Either.right(lockComponent.right().value()); } }
1188 * List<GroupDefinition> updatedGroups = new ArrayList<>();
1190 * List<GroupDefinition> componentGroups = component.getGroups(); // per group, associate to it the artifacts for (GroupDefinition groupDefinition : groups) {
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();
1195 * // if no artifcats sent if (artifactsToDissociate == null || true == artifactsToDissociate.isEmpty()) { continue; }
1197 * if (artifactsSizeInGroup > 0) {
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())); } } } }
1204 * Either<GroupDefinition, StorageOperationStatus> associateArtifactsToGroup = groupOperation.dissociateArtifactsFromGroup(groupDefinition.getUniqueId(), groupDefinition.getArtifacts(), true);
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());
1211 * result = Either.left(updatedGroups); return result;
1215 * if (false == inTransaction) {
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(); }
1219 * } // unlock resource if (shouldLockComp && component != null) { graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); }
1227 * public Either<List<GroupDefinition>, ResponseFormat> createGroups(String componentId, String userId, ComponentTypeEnum componentType, List<GroupDefinition> groupDefinitions, boolean shouldLockComp, boolean inTransaction) {
1229 * Either<List<GroupDefinition>, ResponseFormat> result = null;
1231 * List<GroupDefinition> groups = new ArrayList<>(); org.openecomp.sdc.be.model.Component component = null; try {
1233 * if (groupDefinitions != null && !groupDefinitions.isEmpty()) {
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; }
1238 * Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, CREATE_GROUP, true); if (validateUserExists.isRight()) { result = Either.right(validateUserExists.right().value()); return result; }
1240 * User user = validateUserExists.left().value();
1242 * ComponentParametersView componentParametersView = new ComponentParametersView(); componentParametersView.disableAll(); componentParametersView.setIgnoreGroups(false); componentParametersView.setIgnoreArtifacts(false);
1243 * componentParametersView.setIgnoreUsers(false); componentParametersView.setIgnoreComponentInstances(false);
1245 * Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, componentParametersView);
1247 * if (validateComponent.isRight()) { result = Either.right(validateComponent.right().value()); return result; } component = validateComponent.left().value();
1249 * if (shouldLockComp) { Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "CreateGroups"); if (lockComponent.isRight()) { return Either.right(lockComponent.right().value()); } }
1251 * Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId); if (canWork.isRight()) { result = Either.right(canWork.right().value()); return result; }
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); } }
1256 * result = Either.left(groups); return result;
1260 * if (false == inTransaction) {
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(); }
1264 * } // unlock resource if (shouldLockComp && component != null) { graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); }
1270 * public Either<GroupDefinition, ResponseFormat> createGroup(Component component, User user, ComponentTypeEnum componentType, GroupDefinition groupDefinition, boolean inTransaction) {
1272 * Either<GroupDefinition, ResponseFormat> result = null;
1274 * log.trace("Going to create group {}" , groupDefinition);
1278 * // 3. verify group not already exist List<GroupDefinition> groups = component.getGroups(); boolean found = false; if (groups != null && false == groups.isEmpty()) {
1280 * GroupDefinition existGroupDef = groups.stream().filter(p -> p.getName().equalsIgnoreCase(groupDefinition.getName())).findFirst().orElse(null);
1282 * found = existGroupDef != null; }
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; }
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; } }
1292 * // 6. verify the component instances type are allowed according to // the member types in the group type GroupTypeDefinition groupTypeDefinition = getGroupType.left().value();
1294 * Either<Boolean, ResponseFormat> areValidMembers = verifyComponentInstancesAreValidMembers(component, componentType, groupDefinition.getName(), groupType, groupDefinition.getMembers(), groupTypeDefinition.getMembers());
1296 * if (areValidMembers.isRight()) { ResponseFormat responseFormat = areValidMembers.right().value(); result = Either.right(responseFormat); return result; }
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; }
1301 * NodeTypeEnum nodeTypeEnum = componentType.getNodeType();
1303 * // add invariantUUID String invariantUUID = UniqueIdBuilder.buildInvariantUUID(); groupDefinition.setInvariantUUID(invariantUUID);
1305 * // add groupUUID String groupUUID = UniqueIdBuilder.generateUUID(); groupDefinition.setGroupUUID(groupUUID);
1307 * // add version groupDefinition.setVersion(INITIAL_VERSION);
1309 * // set groupType uid groupDefinition.setTypeUid(groupTypeDefinition.getUniqueId());
1311 * Either<GroupDefinition, StorageOperationStatus> addGroupToGraph = groupOperation.addGroup(nodeTypeEnum, component.getUniqueId(), groupDefinition, true);
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); }
1321 * if (false == inTransaction) {
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(); }
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; }
1340 private Either<List<GroupProperty>, ResponseFormat> updateGroupPropertiesValue(String componentId, GroupDefinition currentGroup, List<GroupProperty> groupPropertyToUpdate, boolean inTransaction) {
1341 Either<List<GroupProperty>, ResponseFormat> result;
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));
1348 result = Either.left(eitherUpdate.left().value());
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());
1362 group.setGroupName(validateGenerateGroupNameRes.left().value());
1364 return validateGenerateGroupNamesRes;
1368 * Generate module name from resourceName, description and counter
1370 * @param resourceSystemName
1371 * @param description
1372 * @param groupCounter
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));
1381 validateGenerateGroupNameRes = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME));
1383 return validateGenerateGroupNameRes;
1386 public Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNames(Map<String, GroupDefinition> groups, String resourceSystemName) {
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();
1396 Either<String, ResponseFormat> newGroupNameRes;
1397 if (groupType.equals(Constants.DEFAULT_GROUP_VF_MODULE) && !Pattern.compile(Constants.MODULE_NEW_NAME_PATTERN).matcher(groupName).matches()) {
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();
1403 counter = getNextVfModuleNameCounter(updatedNamesGroups);
1404 description = groupName;
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());
1412 groupName = newGroupNameRes.left().value();
1413 curGroup.setName(groupName);
1415 updatedNamesGroups.put(groupName, curGroup);
1420 public int getNextVfModuleNameCounter(Map<String, GroupDefinition> groups) {
1422 if (groups != null && !groups.isEmpty()) {
1423 counter = getNextVfModuleNameCounter(groups.values());
1428 public int getNextVfModuleNameCounter(Collection<GroupDefinition> groups) {
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;
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);
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;
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());
1457 newGroupName = newGroupNameRes.left().value();
1458 group.setName(newGroupName);
1461 updatedGroups.add(group);
1465 result = Either.left(updatedGroups);
1470 * public Either<List<GroupDefinition>, ResponseFormat> createGroups(Component component, User user, ComponentTypeEnum componentType, List<GroupDefinition> groupDefinitions, boolean inTransaction) {
1472 * List<GroupDefinition> generatedGroups = new ArrayList<>(); Either<List<GroupDefinition>, ResponseFormat> result = Either.left(generatedGroups);
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); } }
1479 * return result; } finally {
1481 * if (false == inTransaction) {
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(); }
1492 public Either<GroupDefinitionInfo, ResponseFormat> getGroupInstWithArtifactsById(ComponentTypeEnum componentType, String componentId, String componentInstanceId, String groupInstId, String userId, boolean inTransaction) {
1493 Either<GroupDefinitionInfo, ResponseFormat> result = null;
1495 // Validate user exist
1496 Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, UPDATE_GROUP, true);
1498 if (validateUserExists.isRight()) {
1499 result = Either.right(validateUserExists.right().value());
1503 // Validate component exist
1504 org.openecomp.sdc.be.model.Component component = null;
1505 String realComponentId = componentId;
1508 ComponentParametersView componentParametersView = new ComponentParametersView();
1509 componentParametersView.disableAll();
1510 componentParametersView.setIgnoreUsers(false);
1511 componentParametersView.setIgnoreComponentInstances(false);
1512 componentParametersView.setIgnoreArtifacts(false);
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());
1519 component = validateComponent.left().value();
1520 Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> findComponentInstanceAndGroupInstanceRes = findComponentInstanceAndGroupInstanceOnComponent(component, componentInstanceId, groupInstId);
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);
1529 GroupInstance group = findComponentInstanceAndGroupInstanceRes.left().value().getRight();
1530 ComponentInstance componentInstance = findComponentInstanceAndGroupInstanceRes.left().value().getLeft();
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());
1541 BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO);
1543 // Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1548 List<ArtifactDefinitionInfo> artifacts = new ArrayList<>();
1549 List<String> artifactsIds = group.getArtifacts();
1550 if (artifactsIds != null && !artifactsIds.isEmpty()) {
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()));
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()));
1575 GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group);
1576 resultInfo.setIsBase(isBase);
1577 if (!artifacts.isEmpty())
1578 resultInfo.setArtifacts(artifacts);
1580 result = Either.left(resultInfo);
1586 if (false == inTransaction) {
1588 if (result == null || result.isRight()) {
1589 log.debug("Going to execute rollback on create group.");
1590 titanDao.rollback();
1592 log.debug("Going to execute commit on create group.");
1601 private Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> findComponentInstanceAndGroupInstanceOnComponent(Component component, String componentInstanceId, String groupInstId) {
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()));
1614 if (result == null) {
1615 result = Either.right(StorageOperationStatus.NOT_FOUND);
1620 private int getLatestIntProperty(Map<PropertyNames, String> newValues, Map<PropertyNames, String> parentValues, PropertyNames propertyKey) {
1622 if (newValues.containsKey(propertyKey)) {
1623 value = newValues.get(propertyKey);
1625 value = parentValues.get(propertyKey);
1627 return Integer.valueOf(value);
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));
1634 private Either<Boolean, ResponseFormat> validateMinMaxAndInitialCountPropertyLogicVF(Map<PropertyNames, String> newValues, Map<PropertyNames, String> parentValues) {
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);
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)));
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)));
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)));
1661 private Either<Boolean, ResponseFormat> validateMinMaxAndInitialCountPropertyLogic(Map<PropertyNames, String> newValues, Map<PropertyNames, String> currValues, Map<PropertyNames, String> parentValues) {
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()) {
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()) {
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()) {
1692 return Either.left(true);
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());
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()));
1708 result = Either.left(true);
1713 private int parseIntValue(String value, PropertyNames propertyName) {
1715 if (propertyName == PropertyNames.MAX_INSTANCES) {
1716 result = convertIfUnboundMax(value);
1717 } else if (NumberUtils.isNumber(value)) {
1718 result = Integer.parseInt(value);
1726 * validates received new property values and updates group instance in case of success
1728 * @param oldGroupInstance
1729 * @param groupInstanceId
1730 * @param newProperties
1731 * @param inTransaction
1734 public Either<GroupInstance, ResponseFormat> validateAndUpdateGroupInstancePropertyValues(String componentId, String instanceId, GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties, boolean inTransaction) {
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());
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())));
1751 if (actionResult == null) {
1752 actionResult = Either.left(updateGroupInstanceResult.left().value());
1754 return actionResult;
1757 private Either<List<GroupInstanceProperty>, ResponseFormat> validateReduceGroupInstancePropertiesBeforeUpdate(GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties) {
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;
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());
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);
1780 if (validationRes.isLeft()) {
1781 actionResult = Either.left(reducedProperties);
1783 actionResult = Either.right(validationRes.right().value());
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));
1789 return actionResult;
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()));
1802 private Either<Boolean, ResponseFormat> handleAndAddProperty(List<GroupInstanceProperty> reducedProperties, Map<PropertyNames, String> newPropertyValues, GroupInstanceProperty currNewProperty, GroupInstanceProperty currExistingProperty) {
1804 Either<Boolean, ResponseFormat> validationRes = null;
1805 String currPropertyName = currNewProperty.getName();
1806 PropertyNames propertyName = PropertyNames.findName(currPropertyName);
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);
1815 addPropertyUpdatedValues(reducedProperties, propertyName, newPropertyValues, currNewProperty, currExistingProperty);
1818 validateImmutableProperty(currExistingProperty, currNewProperty);
1820 if (validationRes == null) {
1821 validationRes = Either.left(true);
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));
1827 return validationRes;
1830 private boolean isUpdatable(PropertyNames updatablePropertyName) {
1831 return updatablePropertyName != null && updatablePropertyName.getUpdateBehavior().getLevelNumber() >= GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL.getLevelNumber();
1834 private void addPropertyUpdatedValues(List<GroupInstanceProperty> reducedProperties, PropertyNames propertyName, Map<PropertyNames, String> newPropertyValues, GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) {
1836 String newValue = newProperty.getValue();
1837 if (!newValue.equals(String.valueOf(existingProperty.getValue()))) {
1838 newProperty.setValueUniqueUid(existingProperty.getValueUniqueUid());
1839 reducedProperties.add(newProperty);
1841 if (!isEmptyMinInitialCountValue(propertyName, newValue)) {
1842 newPropertyValues.put(propertyName, newValue);
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)) {
1854 private int convertIfUnboundMax(String value) {
1857 if (!NumberUtils.isNumber(value)) {
1858 result = Integer.MAX_VALUE;
1860 result = Integer.parseInt(value);
1865 private Either<Boolean, ResponseFormat> validateAndUpdatePropertyValue(GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) {
1867 Either<Boolean, ResponseFormat> validationRes = null;
1868 String parentValue = existingProperty.getParentValue();
1870 newProperty.setParentValue(parentValue);
1871 if (StringUtils.isEmpty(newProperty.getValue())) {
1872 newProperty.setValue(parentValue);
1874 if (StringUtils.isEmpty(existingProperty.getValue())) {
1875 existingProperty.setValue(parentValue);
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)));
1882 if (validationRes == null) {
1883 validationRes = Either.left(true);
1885 return validationRes;
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());
1894 public Either<List<GroupDefinition>, ResponseFormat> createGroups(Component component, User user, ComponentTypeEnum componentType, List<GroupDefinition> groupDefinitions) {
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))));
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());
1916 GroupDefinition handledGroup = handleGroupRes.left().value();
1917 groups.put(handledGroup.getName(), new GroupDataDefinition(handledGroup));
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())));
1927 if (result == null) {
1928 result = Either.left(createGroupsResult.left().value());
1933 public Either<List<GroupDefinition>, ResponseFormat> addGroups(Component component, User user, ComponentTypeEnum componentType, List<GroupDefinition> groupDefinitions) {
1935 Either<List<GroupDefinition>, ResponseFormat> result = null;
1936 Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult = null;
1937 List<GroupDataDefinition> groups = new ArrayList<>();
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))));
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());
1955 GroupDefinition handledGroup = handleGroupRes.left().value();
1956 groups.add(new GroupDataDefinition(handledGroup));
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())));
1965 if (result == null) {
1966 result = Either.left(createGroupsResult.left().value());
1971 public Either<List<GroupDefinition>, ResponseFormat> deleteGroups(Component component, User user, ComponentTypeEnum componentType, List<GroupDefinition> groupDefinitions) {
1973 Either<List<GroupDefinition>, ResponseFormat> result = null;
1974 Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult = null;
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())));
1981 if (result == null) {
1982 result = Either.left(createGroupsResult.left().value());
1988 * Update specific group version
1990 * @param groupDefinition
1991 * @param inTransaction
1994 public Either<List<GroupDefinition>, ResponseFormat> updateGroups(Component component, ComponentTypeEnum componentType, List<GroupDefinition> groupDefinitions) {
1996 Either<List<GroupDefinition>, ResponseFormat> result = null;
1997 Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult = null;
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())));
2004 if (result == null) {
2005 result = Either.left(createGroupsResult.left().value());
2010 public Either<GroupDefinition, ResponseFormat> handleGroup(Component component, User user, ComponentTypeEnum componentType, GroupDefinition groupDefinition, Map<String, DataTypeDefinition> allDAtaTypes) {
2012 Either<GroupDefinition, ResponseFormat> result = null;
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()) {
2020 GroupDefinition existGroupDef = groups.stream().filter(p -> p.getName().equalsIgnoreCase(groupDefinition.getName())).findFirst().orElse(null);
2022 found = existGroupDef != null;
2024 if (true == found) {
2025 String componentTypeForResponse = getComponentTypeForResponse(component);
2026 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ALREADY_EXIST, groupDefinition.getName(), component.getNormalizedName(), componentTypeForResponse));
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()));
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));
2043 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
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();
2051 Either<Boolean, ResponseFormat> areValidMembers = verifyComponentInstancesAreValidMembers(component, componentType, groupDefinition.getName(), groupType, groupDefinition.getMembers(), groupTypeDefinition.getMembers());
2053 if (areValidMembers.isRight()) {
2054 ResponseFormat responseFormat = areValidMembers.right().value();
2055 result = Either.right(responseFormat);
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);
2065 List<PropertyDefinition> groupTypeProperties = groupTypeDefinition.getProperties();
2067 List<GroupProperty> properties = groupDefinition.convertToGroupProperties();
2068 List<GroupProperty> updatedGroupTypeProperties = new ArrayList<>();
2069 if (properties != null && false == properties.isEmpty()) {
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))));
2076 Map<String, PropertyDefinition> groupTypePropertiesMap = groupTypeProperties.stream().collect(Collectors.toMap(p -> p.getName(), p -> p));
2078 Either<GroupProperty, TitanOperationStatus> addPropertyResult = null;
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()))));
2086 updatedGroupTypeProperties.add(addPropertyResult.left().value());
2091 if (groupDefinition.getUniqueId() == null) {
2092 String uid = UniqueIdBuilder.buildGroupingUid(component.getUniqueId(), groupDefinition.getName());
2093 groupDefinition.setUniqueId(uid);
2095 groupDefinition.convertFromGroupProperties(updatedGroupTypeProperties);
2096 groupDefinition.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
2097 groupDefinition.setGroupUUID(UniqueIdBuilder.generateUUID());
2098 groupDefinition.setVersion(INITIAL_VERSION);
2099 groupDefinition.setTypeUid(groupTypeDefinition.getUniqueId());
2101 return Either.left(groupDefinition);
2104 public Either<GroupProperty, TitanOperationStatus> handleProperty(GroupProperty groupProperty, PropertyDefinition prop, Integer index, Map<String, DataTypeDefinition> allDataTypes) {
2107 return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
2110 PropertyDataDefinition propDataDef = prop;
2111 String propertyType = propDataDef.getType();
2112 String value = groupProperty.getValue();
2114 Either<String, TitanOperationStatus> checkInnerType = propertyOperation.checkInnerType(propDataDef);
2115 if (checkInnerType.isRight()) {
2116 TitanOperationStatus status = checkInnerType.right().value();
2117 return Either.right(status);
2120 String innerType = checkInnerType.left().value();
2122 log.debug("Before validateAndUpdatePropertyValue");
2123 Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes);
2124 log.debug("After validateAndUpdatePropertyValue. isValid = {}", isValid);
2126 String newValue = value;
2127 if (isValid.isRight()) {
2128 Boolean res = isValid.right().value();
2130 return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
2133 Object object = isValid.left().value();
2134 if (object != null) {
2135 newValue = object.toString();
2139 String uniqueId = UniqueIdBuilder.buildGroupPropertyValueUid((String) prop.getUniqueId(), index);
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());
2150 log.debug("Before adding property value to graph {}", groupProperty);
2152 return Either.left(groupProperty);