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.nio.charset.StandardCharsets;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.Collection;
27 import java.util.Collections;
28 import java.util.EnumMap;
29 import java.util.HashMap;
30 import java.util.List;
32 import java.util.Optional;
34 import java.util.concurrent.Callable;
35 import java.util.function.Function;
36 import java.util.stream.Collectors;
38 import javax.servlet.ServletContext;
39 import javax.servlet.http.HttpServletRequest;
41 import org.apache.commons.collections.CollectionUtils;
42 import org.apache.commons.collections.MapUtils;
43 import org.apache.commons.lang3.tuple.ImmutablePair;
44 import org.openecomp.sdc.be.components.distribution.engine.IDistributionEngine;
45 import org.openecomp.sdc.be.components.distribution.engine.INotificationData;
46 import org.openecomp.sdc.be.components.distribution.engine.VfModuleArtifactPayload;
47 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
48 import org.openecomp.sdc.be.config.BeEcompErrorManager;
49 import org.openecomp.sdc.be.config.ConfigurationManager;
50 import org.openecomp.sdc.be.dao.api.ActionStatus;
51 import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao;
52 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
53 import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
54 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
55 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
56 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
57 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
58 import org.openecomp.sdc.be.model.ArtifactDefinition;
59 import org.openecomp.sdc.be.model.Component;
60 import org.openecomp.sdc.be.model.ComponentInstance;
61 import org.openecomp.sdc.be.model.ComponentParametersView;
62 import org.openecomp.sdc.be.model.DistributionStatusEnum;
63 import org.openecomp.sdc.be.model.DistributionTransitionEnum;
64 import org.openecomp.sdc.be.model.GroupInstance;
65 import org.openecomp.sdc.be.model.GroupInstanceProperty;
66 import org.openecomp.sdc.be.model.LifecycleStateEnum;
67 import org.openecomp.sdc.be.model.Resource;
68 import org.openecomp.sdc.be.model.Service;
69 import org.openecomp.sdc.be.model.User;
70 import org.openecomp.sdc.be.model.category.CategoryDefinition;
71 import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation;
72 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
73 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
74 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
75 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
76 import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
77 import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
78 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
79 import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
80 import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent;
81 import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent;
82 import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent;
83 import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
84 import org.openecomp.sdc.be.user.Role;
85 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
86 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
87 import org.openecomp.sdc.common.api.Constants;
88 import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
89 import org.openecomp.sdc.common.datastructure.Wrapper;
90 import org.openecomp.sdc.common.kpi.api.ASDCKpiApi;
91 import org.openecomp.sdc.common.util.GeneralUtility;
92 import org.openecomp.sdc.common.util.ThreadLocalsHolder;
93 import org.openecomp.sdc.common.util.ValidationUtils;
94 import org.openecomp.sdc.exception.ResponseFormat;
95 import org.slf4j.Logger;
96 import org.slf4j.LoggerFactory;
97 import org.springframework.beans.factory.annotation.Autowired;
98 import org.springframework.web.context.WebApplicationContext;
100 import com.google.gson.Gson;
101 import com.google.gson.GsonBuilder;
103 import fj.data.Either;
105 @org.springframework.stereotype.Component("serviceBusinessLogic")
106 public class ServiceBusinessLogic extends ComponentBusinessLogic {
108 private static final String STATUS_SUCCESS_200 = "200";
110 private static final String STATUS_DEPLOYED = "DEPLOYED";
113 private IElementOperation elementDao;
116 private IDistributionEngine distributionEngine;
119 // private AuditingDao auditingDao;
122 private AuditCassandraDao auditCassandraDao;
125 private ServiceComponentInstanceBusinessLogic serviceComponentInstanceBusinessLogic;
128 private GroupBusinessLogic groupBusinessLogic;
131 private ICacheMangerOperation cacheManagerOperation;
133 private static Logger log = LoggerFactory.getLogger(ServiceBusinessLogic.class.getName());
134 private static final String INITIAL_VERSION = "0.1";
136 public ServiceBusinessLogic() {
137 log.debug("ServiceBusinessLogic started");
140 public Either<Service, ResponseFormat> changeServiceDistributionState(String serviceId, String state, LifecycleChangeInfoWithAction commentObj, User user) {
142 Either<User, ResponseFormat> resp = validateUserExists(user.getUserId(), "change Service Distribution State", false);
143 if (resp.isRight()) {
144 return Either.right(resp.right().value());
147 log.debug("check request state");
148 Either<DistributionTransitionEnum, ResponseFormat> validateEnum = validateTransitionEnum(state, user);
149 if (validateEnum.isRight()) {
150 return Either.right(validateEnum.right().value());
152 DistributionTransitionEnum distributionTransition = validateEnum.left().value();
153 AuditingActionEnum auditAction = (distributionTransition == DistributionTransitionEnum.APPROVE ? AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_APPROV : AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REJECT);
154 Either<String, ResponseFormat> commentResponse = validateComment(commentObj, user, auditAction);
155 if (commentResponse.isRight()) {
156 return Either.right(commentResponse.right().value());
158 String comment = commentResponse.left().value();
160 Either<Service, ResponseFormat> validateService = validateServiceDistributionChange(user, serviceId, auditAction, comment);
161 if (validateService.isRight()) {
162 return Either.right(validateService.right().value());
164 Service service = validateService.left().value();
165 DistributionStatusEnum initState = service.getDistributionStatus();
167 Either<User, ResponseFormat> validateUser = validateUserDistributionChange(user, service, auditAction, comment);
168 if (validateUser.isRight()) {
169 return Either.right(validateUser.right().value());
171 user = validateUser.left().value();
175 * StorageOperationStatus lockResult = graphLockOperation.lockComponent(serviceId, NodeTypeEnum.Service); if (!lockResult.equals(StorageOperationStatus.OK)) { BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.
176 * BeFailedLockObjectError, "ChangeServiceDistributionState"); log.debug("Failed to lock service {} error - {}", serviceId, lockResult); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR,
177 * service.getVersion(), service.getServiceName());
179 * createAudit(user, auditAction, comment, service, responseFormat); return Either.right(componentsUtils.getResponseFormat(ActionStatus. GENERAL_ERROR)); }
181 Either<Boolean, ResponseFormat> lockResult = lockComponent(serviceId, service, "ChangeServiceDistributionState");
182 if (lockResult.isRight()) {
183 ResponseFormat responseFormat = lockResult.right().value();
184 createAudit(user, auditAction, comment, service, responseFormat);
185 return Either.right(responseFormat);
190 DistributionStatusEnum newState;
191 if (distributionTransition == DistributionTransitionEnum.APPROVE) {
192 newState = DistributionStatusEnum.DISTRIBUTION_APPROVED;
194 newState = DistributionStatusEnum.DISTRIBUTION_REJECTED;
196 Either<Service, StorageOperationStatus> result = toscaOperationFacade.updateDistributionStatus(service, user, newState);
197 if (result.isRight()) {
199 BeEcompErrorManager.getInstance().logBeSystemError("ChangeServiceDistributionState");
200 log.debug("service {} is change destribuation status failed", service.getUniqueId());
201 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR, service.getVersion(), service.getName());
202 createAudit(user, auditAction, comment, service, responseFormat);
203 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
206 Service updatedService = result.left().value();
207 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
208 EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
209 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS, updatedService.getDistributionStatus().name());
210 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS, initState.name());
211 createAudit(user, auditAction, comment, updatedService, responseFormat, auditingFields);
212 return Either.left(result.left().value());
215 graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service);
220 public Either<List<Map<String, Object>>, ResponseFormat> getComponentAuditRecords(String componentVersion, String componentUUID, String userId) {
221 Either<User, ResponseFormat> resp = validateUserExists(userId, "get Component Audit Records", false);
222 if (resp.isRight()) {
223 return Either.right(resp.right().value());
225 Either<List<Map<String, Object>>, ActionStatus> result;
229 if (componentVersion.endsWith(".0")) {
230 Either<List<ResourceAdminEvent>, ActionStatus> eitherAuditingForCertified = auditCassandraDao.getByServiceInstanceId(componentUUID);
231 if (eitherAuditingForCertified.isLeft()) {
232 result = Either.left(getAuditingFieldsList(eitherAuditingForCertified.left().value()));
234 result = Either.right(eitherAuditingForCertified.right().value());
237 // Uncertified Version
239 result = getAuditRecordsForUncertifiedComponent(componentUUID, componentVersion);
241 } catch (Exception e) {
242 log.debug("get Audit Records failed with exception {}", e);
243 result = Either.right(ActionStatus.GENERAL_ERROR);
246 if (result.isRight()) {
247 return Either.right(componentsUtils.getResponseFormat(result.right().value()));
249 return Either.left(result.left().value());
254 private Either<List<Map<String, Object>>, ActionStatus> getAuditRecordsForUncertifiedComponent(String componentUUID, String componentVersion) {
256 Either<List<ResourceAdminEvent>, ActionStatus> eitherprevVerAudit = auditCassandraDao.getAuditByServiceIdAndPrevVersion(componentUUID, componentVersion);
258 if (eitherprevVerAudit.isRight()) {
259 return Either.right(eitherprevVerAudit.right().value());
263 Either<List<ResourceAdminEvent>, ActionStatus> eitherCurrVerAudit = auditCassandraDao.getAuditByServiceIdAndCurrVersion(componentUUID, componentVersion);
264 if (eitherCurrVerAudit.isRight()) {
265 return Either.right(eitherCurrVerAudit.right().value());
268 List<Map<String, Object>> prevVerAuditList = getAuditingFieldsList(eitherprevVerAudit.left().value());
269 List<Map<String, Object>> currVerAuditList = getAuditingFieldsList(eitherCurrVerAudit.left().value());
271 List<Map<String, Object>> duplicateElements = new ArrayList<Map<String, Object>>();
272 duplicateElements.addAll(prevVerAuditList);
273 duplicateElements.retainAll(currVerAuditList);
275 List<Map<String, Object>> joinedNonDuplicatedList = new ArrayList<Map<String, Object>>();
276 joinedNonDuplicatedList.addAll(prevVerAuditList);
277 joinedNonDuplicatedList.removeAll(duplicateElements);
278 joinedNonDuplicatedList.addAll(currVerAuditList);
280 return Either.left(joinedNonDuplicatedList);
283 private List<Map<String, Object>> getAuditingFieldsList(List<? extends AuditingGenericEvent> prevVerAuditList) {
285 List<Map<String, Object>> prevVerAudit = new ArrayList<Map<String, Object>>();
286 for (AuditingGenericEvent auditEvent : prevVerAuditList) {
287 auditEvent.fillFields();
288 prevVerAudit.add(auditEvent.getFields());
299 * - modifier data (userId)
300 * @return Either<Service, responseFormat>
302 public Either<Service, ResponseFormat> createService(Service service, User user) {
305 Either<User, ResponseFormat> eitherCreator = validateUser(user, "Create Service", service, AuditingActionEnum.CREATE_RESOURCE, false);
306 if (eitherCreator.isRight()) {
307 return Either.right(eitherCreator.right().value());
309 user = eitherCreator.left().value();
311 // validate user role
312 Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, service, new ArrayList<Role>(), AuditingActionEnum.CREATE_RESOURCE, null);
313 if (validateRes.isRight()) {
314 return Either.right(validateRes.right().value());
316 service.setCreatorUserId(user.getUserId());
318 // warn on overridden fields
319 checkFieldsForOverideAttampt(service);
321 log.debug("enrich service with version and state");
322 service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
323 service.setVersion(INITIAL_VERSION);
324 service.setConformanceLevel(ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel());
325 service.setDistributionStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED);
327 Either<Service, ResponseFormat> createServiceResponse = validateServiceBeforeCreate(service, user, AuditingActionEnum.CREATE_RESOURCE);
328 if (createServiceResponse.isRight()) {
329 return createServiceResponse;
331 return createServiceByDao(service, AuditingActionEnum.CREATE_RESOURCE, user);
334 private void checkFieldsForOverideAttampt(Service service) {
335 checkComponentFieldsForOverrideAttempt(service);
336 if ((service.getDistributionStatus() != null)) {
337 log.info("Distribution Status cannot be defined by user. This field will be overridden by the application");
341 private Either<Service, ResponseFormat> createServiceByDao(Service service, AuditingActionEnum actionEnum, User user) {
342 log.debug("send service {} to dao for create", service.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
344 Either<Boolean, ResponseFormat> lockResult = lockComponentByName(service.getSystemName(), service, "Create Service");
345 if (lockResult.isRight()) {
346 ResponseFormat responseFormat = lockResult.right().value();
347 componentsUtils.auditComponentAdmin(responseFormat, user, service, "", "", actionEnum, ComponentTypeEnum.SERVICE);
348 return Either.right(responseFormat);
351 log.debug("System name locked is {}, status = {}", service.getSystemName(), lockResult);
355 createMandatoryArtifactsData(service, user);
356 createServiceApiArtifactsData(service, user);
357 setToscaArtifactsPlaceHolders(service, user);
358 Either<Resource, ResponseFormat> genericServiceEither = fetchAndSetDerivedFromGenericType(service);
359 if (genericServiceEither.isRight())
360 return Either.right(genericServiceEither.right().value());
362 generateInputsFromGenericTypeProperties(service, genericServiceEither.left().value());
364 Either<Service, StorageOperationStatus> dataModelResponse = toscaOperationFacade.createToscaComponent(service);
366 // service created successfully!!!
367 if (dataModelResponse.isLeft()) {
368 log.debug("Service created successfully!!!");
369 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
370 componentsUtils.auditComponentAdmin(responseFormat, user, service, "", "", actionEnum, ComponentTypeEnum.SERVICE);
371 ASDCKpiApi.countCreatedServicesKPI();
372 return Either.left(dataModelResponse.left().value());
375 ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), service, ComponentTypeEnum.SERVICE);
376 log.debug("audit before sending response");
377 componentsUtils.auditComponentAdmin(responseFormat, user, service, "", "", actionEnum, ComponentTypeEnum.SERVICE);
378 return Either.right(responseFormat);
381 graphLockOperation.unlockComponentByName(service.getSystemName(), service.getUniqueId(), NodeTypeEnum.Service);
385 @SuppressWarnings("unchecked")
386 private void createServiceApiArtifactsData(Service service, User user) {
387 // create mandatory artifacts
389 // TODO it must be removed after that artifact uniqueId creation will be
390 // moved to ArtifactOperation
391 // String serviceUniqueId =
392 // UniqueIdBuilder.buildServiceUniqueId(service.getComponentMetadataDefinition().getMetadataDataDefinition().getName(),
393 // service.getComponentMetadataDefinition().getMetadataDataDefinition().getVersion());
394 String serviceUniqueId = service.getUniqueId();
395 Map<String, ArtifactDefinition> artifactMap = service.getServiceApiArtifacts();
396 if (artifactMap == null)
397 artifactMap = new HashMap<String, ArtifactDefinition>();
399 Map<String, Object> serviceApiArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceApiArtifacts();
400 List<String> exludeServiceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeServiceCategory();
402 List<CategoryDefinition> categories = service.getCategories();
403 boolean isCreateArtifact = true;
404 if (categories != null && exludeServiceCategory != null && !exludeServiceCategory.isEmpty()) {
405 for (String exlude : exludeServiceCategory) {
406 if (exlude.equalsIgnoreCase(categories.get(0).getName())) {
407 isCreateArtifact = false;
414 if (serviceApiArtifacts != null && isCreateArtifact) {
415 Set<String> keys = serviceApiArtifacts.keySet();
416 for (String serviceApiArtifactName : keys) {
417 Map<String, Object> artifactInfoMap = (Map<String, Object>) serviceApiArtifacts.get(serviceApiArtifactName);
418 ArtifactDefinition artifactDefinition = createArtifactDefinition(serviceUniqueId, serviceApiArtifactName, artifactInfoMap, user, true);
419 artifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.SERVICE_API);
420 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
423 service.setServiceApiArtifacts(artifactMap);
427 private Either<Service, ResponseFormat> validateServiceBeforeCreate(Service service, User user, AuditingActionEnum actionEnum) {
429 Either<Boolean, ResponseFormat> validationResponse = validateServiceFieldsBeforeCreate(user, service, actionEnum);
430 if (validationResponse.isRight()) {
431 return Either.right(validationResponse.right().value());
433 service.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
434 service.setContactId(service.getContactId().toLowerCase());
436 // Generate invariant UUID - must be here and not in operation since it
437 // should stay constant during clone
438 String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
439 service.setInvariantUUID(invariantUUID);
441 return Either.left(service);
444 private Either<Boolean, ResponseFormat> validateServiceFieldsBeforeCreate(User user, Service service, AuditingActionEnum actionEnum) {
445 Either<Boolean, ResponseFormat> componentsFieldsValidation = validateComponentFieldsBeforeCreate(user, service, actionEnum);
446 if (componentsFieldsValidation.isRight()) {
447 return componentsFieldsValidation;
450 // validate service name uniqueness
451 log.debug("validate service name uniqueness");
452 Either<Boolean, ResponseFormat> serviceNameUniquenessValidation = validateComponentNameUnique(user, service, actionEnum);
453 if (serviceNameUniquenessValidation.isRight()) {
454 return serviceNameUniquenessValidation;
458 log.debug("validate category");
459 Either<Boolean, ResponseFormat> categoryValidation = validateServiceCategory(user, service, actionEnum);
460 if (categoryValidation.isRight()) {
461 return categoryValidation;
464 // validate project name (ProjectCode) - mandatory in service
466 log.debug("validate projectName");
467 Either<Boolean, ResponseFormat> projectCodeValidation = validateProjectCode(user, service, actionEnum);
468 if (projectCodeValidation.isRight()) {
469 return projectCodeValidation;
472 return Either.left(true);
476 private Either<Boolean, ResponseFormat> validateServiceCategory(User user, Service service, AuditingActionEnum actionEnum) {
477 log.debug("validate Service category");
479 if (service.getCategories() == null || service.getCategories().size() == 0) {
480 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
481 componentsUtils.auditComponentAdmin(errorResponse, user, service, "", "", actionEnum, ComponentTypeEnum.SERVICE);
482 return Either.right(errorResponse);
485 Either<Boolean, ResponseFormat> validatCategory = validateServiceCategory(service.getCategories());
486 if (validatCategory.isRight()) {
487 ResponseFormat responseFormat = validatCategory.right().value();
488 componentsUtils.auditComponentAdmin(responseFormat, user, service, "", "", actionEnum, ComponentTypeEnum.SERVICE);
489 return Either.right(responseFormat);
492 return Either.left(true);
495 public Either<Map<String, Boolean>, ResponseFormat> validateServiceNameExists(String serviceName, String userId) {
497 Either<User, ResponseFormat> resp = validateUserExists(userId, "validate Service Name Exists", false);
498 if (resp.isRight()) {
499 return Either.right(resp.right().value());
502 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(serviceName, null, ComponentTypeEnum.SERVICE);
507 if (dataModelResponse.isLeft()) {
508 Map<String, Boolean> result = new HashMap<>();
509 result.put("isValid", dataModelResponse.left().value());
510 log.debug("validation was successfully performed.");
511 return Either.left(result);
514 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
516 return Either.right(responseFormat);
519 public void setElementDao(IElementOperation elementDao) {
520 this.elementDao = elementDao;
523 public void setCassandraAuditingDao(AuditCassandraDao auditingDao) {
524 this.auditCassandraDao = auditingDao;
528 * public void setUserAdmin(UserAdminBuisinessLogic userAdmin) { this.userAdmin = userAdmin; }
530 * public void setComponentsUtils(ComponentsUtils componentsUtils) { this.componentsUtils = componentsUtils; }
532 * public void setGraphLockOperation(IGraphLockOperation graphLockOperation) { this.graphLockOperation = graphLockOperation; }
535 public ArtifactsBusinessLogic getArtifactBl() {
536 return artifactsBusinessLogic;
539 public void setArtifactBl(ArtifactsBusinessLogic artifactBl) {
540 this.artifactsBusinessLogic = artifactBl;
543 public Either<Service, ResponseFormat> updateServiceMetadata(String serviceId, Service serviceUpdate, User user) {
544 Either<User, ResponseFormat> eitherCreator = validateUser(user, "updateServiceMetadata", serviceUpdate, null, false);
545 if (eitherCreator.isRight()) {
546 return Either.right(eitherCreator.right().value());
548 user = eitherCreator.left().value();
550 // validate user role
551 Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, serviceUpdate, new ArrayList<Role>(), null, null);
552 if (validateRes.isRight()) {
553 return Either.right(validateRes.right().value());
556 Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
557 if (storageStatus.isRight()) {
558 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), ""));
561 Service currentService = storageStatus.left().value();
563 if (!ComponentValidationUtils.canWorkOnComponent(currentService, user.getUserId())) {
564 log.info("Restricted operation for user: {}, on service: {}", user.getUserId(), currentService.getCreatorUserId());
565 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
568 Either<Service, ResponseFormat> validationRsponse = validateAndUpdateServiceMetadata(user, currentService, serviceUpdate);
569 if (validationRsponse.isRight()) {
570 log.info("service update metadata: validations field.");
571 return validationRsponse;
573 Service serviceToUpdate = validationRsponse.left().value();
576 Either<Boolean, ResponseFormat> lockResult = lockComponent(serviceId, currentService, "Update Service Metadata");
577 if (lockResult.isRight()) {
578 return Either.right(lockResult.right().value());
581 Either<Service, StorageOperationStatus> updateResponse = toscaOperationFacade.updateToscaElement(serviceToUpdate);
582 if (updateResponse.isRight()) {
584 BeEcompErrorManager.getInstance().logBeSystemError("Update Service Metadata");
585 log.debug("failed to update sevice {}", serviceToUpdate.getUniqueId());
586 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
589 return Either.left(updateResponse.left().value());
591 graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service);
595 private Either<Service, ResponseFormat> validateAndUpdateServiceMetadata(User user, Service currentService, Service serviceUpdate) {
597 boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentService.getVersion());
598 Either<Boolean, ResponseFormat> response = validateAndUpdateCategory(user, currentService, serviceUpdate, hasBeenCertified, null);
599 if (response.isRight()) {
600 ResponseFormat errorResponse = response.right().value();
601 return Either.right(errorResponse);
604 String creatorUserIdUpdated = serviceUpdate.getCreatorUserId();
605 String creatorUserIdCurrent = currentService.getCreatorUserId();
606 if (creatorUserIdUpdated != null && !creatorUserIdCurrent.equals(creatorUserIdUpdated)) {
607 log.info("update srvice: recived request to update creatorUserId to {} the field is not updatable ignoring.", creatorUserIdUpdated);
610 String creatorFullNameUpdated = serviceUpdate.getCreatorFullName();
611 String creatorFullNameCurrent = currentService.getCreatorFullName();
612 if (creatorFullNameUpdated != null && !creatorFullNameCurrent.equals(creatorFullNameUpdated)) {
613 log.info("update srvice: recived request to update creatorFullName to {} the field is not updatable ignoring.", creatorFullNameUpdated);
616 String lastUpdaterUserIdUpdated = serviceUpdate.getLastUpdaterUserId();
617 String lastUpdaterUserIdCurrent = currentService.getLastUpdaterUserId();
618 if (lastUpdaterUserIdUpdated != null && !lastUpdaterUserIdCurrent.equals(lastUpdaterUserIdUpdated)) {
619 log.info("update srvice: recived request to update lastUpdaterUserId to {} the field is not updatable ignoring.", lastUpdaterUserIdUpdated);
622 String lastUpdaterFullNameUpdated = serviceUpdate.getLastUpdaterFullName();
623 String lastUpdaterFullNameCurrent = currentService.getLastUpdaterFullName();
624 if (lastUpdaterFullNameUpdated != null && !lastUpdaterFullNameCurrent.equals(lastUpdaterFullNameUpdated)) {
625 log.info("update srvice: recived request to update lastUpdaterFullName to {} the field is not updatable ignoring.", lastUpdaterFullNameUpdated);
628 response = validateAndUpdateServiceName(user, currentService, serviceUpdate, hasBeenCertified, null);
629 if (response.isRight()) {
630 ResponseFormat errorResponse = response.right().value();
631 return Either.right(errorResponse);
634 DistributionStatusEnum distributionStatusUpdated = serviceUpdate.getDistributionStatus();
635 DistributionStatusEnum distributionStatusCurrent = currentService.getDistributionStatus();
636 if (distributionStatusUpdated != null && !distributionStatusUpdated.name().equals((distributionStatusCurrent != null ? distributionStatusCurrent.name() : null))) {
637 log.info("update srvice: recived request to update distributionStatus to {} the field is not updatable ignoring.", distributionStatusUpdated);
640 if (serviceUpdate.getProjectCode() != null) {
641 response = validateAndUpdateProjectCode(user, currentService, serviceUpdate, null);
642 if (response.isRight()) {
643 ResponseFormat errorResponse = response.right().value();
644 return Either.right(errorResponse);
648 response = validateAndUpdateIcon(user, currentService, serviceUpdate, hasBeenCertified, null);
649 if (response.isRight()) {
650 ResponseFormat errorResponse = response.right().value();
651 return Either.right(errorResponse);
654 Long creationDateUpdated = serviceUpdate.getCreationDate();
655 Long creationDateCurrent = currentService.getCreationDate();
656 if (creationDateUpdated != null && !creationDateCurrent.equals(creationDateUpdated)) {
657 log.info("update srvice: recived request to update creationDate to {} the field is not updatable ignoring.", creationDateUpdated);
660 String versionUpdated = serviceUpdate.getVersion();
661 String versionCurrent = currentService.getVersion();
662 if (versionUpdated != null && !versionCurrent.equals(versionUpdated)) {
663 log.info("update srvice: recived request to update version to {} the field is not updatable ignoring.", versionUpdated);
666 response = validateAndUpdateDescription(user, currentService, serviceUpdate, hasBeenCertified, null);
667 if (response.isRight()) {
668 ResponseFormat errorResponse = response.right().value();
669 return Either.right(errorResponse);
672 response = validateAndUpdateTags(user, currentService, serviceUpdate, hasBeenCertified, null);
673 if (response.isRight()) {
674 ResponseFormat errorResponse = response.right().value();
675 return Either.right(errorResponse);
678 response = validateAndUpdateContactId(user, currentService, serviceUpdate, null);
679 if (response.isRight()) {
680 ResponseFormat errorResponse = response.right().value();
681 return Either.right(errorResponse);
684 Long lastUpdateDateUpdated = serviceUpdate.getLastUpdateDate();
685 Long lastUpdateDateCurrent = currentService.getLastUpdateDate();
686 if (lastUpdateDateUpdated != null && !lastUpdateDateCurrent.equals(lastUpdateDateUpdated)) {
687 log.info("update srvice: recived request to update lastUpdateDate to {} the field is not updatable ignoring.", lastUpdateDateUpdated);
690 LifecycleStateEnum lifecycleStateUpdated = serviceUpdate.getLifecycleState();
691 LifecycleStateEnum lifecycleStateCurrent = currentService.getLifecycleState();
692 if (lifecycleStateUpdated != null && !lifecycleStateCurrent.name().equals(lifecycleStateUpdated.name())) {
693 log.info("update srvice: recived request to update lifecycleState to {} the field is not updatable ignoring.", lifecycleStateUpdated);
696 Boolean isHighestVersionUpdated = serviceUpdate.isHighestVersion();
697 Boolean isHighestVersionCurrent = currentService.isHighestVersion();
698 if (isHighestVersionUpdated != null && !isHighestVersionCurrent.equals(isHighestVersionUpdated)) {
699 log.info("update srvice: recived request to update isHighestVersion to {} the field is not updatable ignoring.", isHighestVersionUpdated);
702 String uuidUpdated = serviceUpdate.getUUID();
703 String uuidCurrent = currentService.getUUID();
704 if (!uuidCurrent.equals(uuidUpdated)) {
705 log.info("update srvice: recived request to update uuid to {} the field is not updatable ignoring.", uuidUpdated);
708 String currentInvariantUuid = currentService.getInvariantUUID();
709 String updatedInvariantUuid = serviceUpdate.getInvariantUUID();
711 if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
712 log.warn("Product invariant UUID is automatically set and cannot be updated");
713 serviceUpdate.setInvariantUUID(currentInvariantUuid);
715 validateAndUpdateEcompNaming(currentService, serviceUpdate);
717 return Either.left(currentService);
721 private void validateAndUpdateEcompNaming(Service currentService, Service serviceUpdate) {
722 Boolean isEcompoGeneratedCurr = currentService.isEcompGeneratedNaming();
723 Boolean isEcompoGeneratedUpdate = serviceUpdate.isEcompGeneratedNaming();
724 if (isEcompoGeneratedUpdate != null && isEcompoGeneratedCurr != isEcompoGeneratedUpdate) {
725 currentService.setEcompGeneratedNaming(isEcompoGeneratedUpdate);
727 String namingPolicyUpd = serviceUpdate.getNamingPolicy();
728 if (!currentService.isEcompGeneratedNaming()) {
729 if (ValidationUtils.validateStringNotEmpty(namingPolicyUpd)) {
730 log.warn("NamingPolicy must be empty for EcompGeneratedNaming=false");
731 currentService.setNamingPolicy("");
733 currentService.setNamingPolicy(namingPolicyUpd);
736 currentService.setNamingPolicy(namingPolicyUpd);
740 private Either<Boolean, ResponseFormat> validateAndUpdateContactId(User user, Service currentService, Service serviceUpdate, AuditingActionEnum audatingAction) {
741 String contactIdUpdated = serviceUpdate.getContactId();
742 String contactIdCurrent = currentService.getContactId();
743 if (!contactIdCurrent.equals(contactIdUpdated)) {
744 Either<Boolean, ResponseFormat> validatContactId = validateContactId(user, serviceUpdate, audatingAction);
745 if (validatContactId.isRight()) {
746 ResponseFormat errorRespons = validatContactId.right().value();
747 return Either.right(errorRespons);
749 currentService.setContactId(contactIdUpdated.toLowerCase());
751 return Either.left(true);
754 private Either<Boolean, ResponseFormat> validateAndUpdateTags(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) {
755 List<String> tagsUpdated = serviceUpdate.getTags();
756 List<String> tagsCurrent = currentService.getTags();
757 if (tagsUpdated == null || tagsUpdated.isEmpty()) {
758 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_TAGS);
759 componentsUtils.auditComponentAdmin(responseFormat, user, serviceUpdate, "", "", audatingAction, ComponentTypeEnum.SERVICE);
760 return Either.right(responseFormat);
763 if (!(tagsCurrent.containsAll(tagsUpdated) && tagsUpdated.containsAll(tagsCurrent))) {
764 Either<Boolean, ResponseFormat> validatResponse = validateTagsListAndRemoveDuplicates(user, serviceUpdate, audatingAction);
765 if (validatResponse.isRight()) {
766 ResponseFormat errorRespons = validatResponse.right().value();
767 return Either.right(errorRespons);
769 currentService.setTags(tagsUpdated);
771 return Either.left(true);
774 private Either<Boolean, ResponseFormat> validateAndUpdateDescription(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) {
775 String descriptionUpdated = serviceUpdate.getDescription();
776 String descriptionCurrent = currentService.getDescription();
777 if (!descriptionCurrent.equals(descriptionUpdated)) {
778 Either<Boolean, ResponseFormat> validateDescriptionResponse = validateDescriptionAndCleanup(user, serviceUpdate, audatingAction);
779 if (validateDescriptionResponse.isRight()) {
780 ResponseFormat errorRespons = validateDescriptionResponse.right().value();
781 return Either.right(errorRespons);
783 currentService.setDescription(serviceUpdate.getDescription());
785 return Either.left(true);
788 private Either<Boolean, ResponseFormat> validateAndUpdateProjectCode(User user, Service currentService, Service serviceUpdate, AuditingActionEnum audatingAction) {
789 String projectCodeUpdated = serviceUpdate.getProjectCode();
790 String projectCodeCurrent = currentService.getProjectCode();
791 if (!projectCodeCurrent.equals(projectCodeUpdated)) {
793 Either<Boolean, ResponseFormat> validatProjectCodeResponse = validateProjectCode(user, serviceUpdate, audatingAction);
794 if (validatProjectCodeResponse.isRight()) {
795 ResponseFormat errorRespons = validatProjectCodeResponse.right().value();
796 return Either.right(errorRespons);
798 currentService.setProjectCode(projectCodeUpdated);
801 return Either.left(true);
804 private Either<Boolean, ResponseFormat> validateAndUpdateIcon(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) {
805 String iconUpdated = serviceUpdate.getIcon();
806 String iconCurrent = currentService.getIcon();
807 if (!iconCurrent.equals(iconUpdated)) {
808 if (!hasBeenCertified) {
809 Either<Boolean, ResponseFormat> validatIconResponse = validateIcon(user, serviceUpdate, audatingAction);
810 if (validatIconResponse.isRight()) {
811 ResponseFormat errorRespons = validatIconResponse.right().value();
812 return Either.right(errorRespons);
814 currentService.setIcon(iconUpdated);
816 log.info("icon {} cannot be updated once the service has been certified once.", iconUpdated);
817 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_ICON_CANNOT_BE_CHANGED);
818 return Either.right(errorResponse);
821 return Either.left(true);
824 private Either<Boolean, ResponseFormat> validateAndUpdateServiceName(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) {
825 String serviceNameUpdated = serviceUpdate.getName();
826 String serviceNameCurrent = currentService.getName();
827 if (!serviceNameCurrent.equals(serviceNameUpdated)) {
828 if (!hasBeenCertified) {
829 Either<Boolean, ResponseFormat> validatServiceNameResponse = validateComponentName(user, serviceUpdate, audatingAction);
830 if (validatServiceNameResponse.isRight()) {
831 ResponseFormat errorRespons = validatServiceNameResponse.right().value();
832 return Either.right(errorRespons);
835 Either<Boolean, ResponseFormat> serviceNameUniquenessValidation = validateComponentNameUnique(user, serviceUpdate, audatingAction);
836 if (serviceNameUniquenessValidation.isRight()) {
837 return serviceNameUniquenessValidation;
839 currentService.setName(serviceNameUpdated);
840 currentService.getComponentMetadataDefinition().getMetadataDataDefinition().setNormalizedName(ValidationUtils.normaliseComponentName(serviceNameUpdated));
841 currentService.getComponentMetadataDefinition().getMetadataDataDefinition().setSystemName(ValidationUtils.convertToSystemName(serviceNameUpdated));
844 log.info("service name {} cannot be updated once the service has been certified once.", serviceNameUpdated);
845 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NAME_CANNOT_BE_CHANGED);
846 return Either.right(errorResponse);
849 return Either.left(true);
852 private Either<Boolean, ResponseFormat> validateAndUpdateCategory(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) {
853 List<CategoryDefinition> categoryUpdated = serviceUpdate.getCategories();
854 List<CategoryDefinition> categoryCurrent = currentService.getCategories();
855 Either<Boolean, ResponseFormat> validatCategoryResponse = validateServiceCategory(user, serviceUpdate, audatingAction);
856 if (validatCategoryResponse.isRight()) {
857 ResponseFormat errorRespons = validatCategoryResponse.right().value();
858 return Either.right(errorRespons);
860 if (!categoryCurrent.get(0).getName().equals(categoryUpdated.get(0).getName())) {
861 if (!hasBeenCertified) {
862 currentService.setCategories(categoryUpdated);
864 log.info("category {} cannot be updated once the service has been certified once.", categoryUpdated);
865 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_CATEGORY_CANNOT_BE_CHANGED);
866 return Either.right(errorResponse);
869 return Either.left(true);
873 public Either<Boolean, ResponseFormat> validateServiceCategory(List<CategoryDefinition> list) {
875 if (list.size() > 1) {
876 log.debug("Must be only one category for service");
877 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.SERVICE.getValue());
878 return Either.right(responseFormat);
880 CategoryDefinition category = list.get(0);
881 if (category.getSubcategories() != null) {
882 log.debug("Subcategories cannot be defined for service");
883 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_CANNOT_CONTAIN_SUBCATEGORY);
884 return Either.right(responseFormat);
886 if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
887 log.debug("Resource category is empty");
888 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
889 return Either.right(responseFormat);
892 log.debug("validating service category {} against valid categories list", list);
893 Either<List<CategoryDefinition>, ActionStatus> categorys = elementDao.getAllServiceCategories();
894 if (categorys.isRight()) {
895 log.debug("failed to retrive service categories from Titan");
896 ResponseFormat responseFormat = componentsUtils.getResponseFormat(categorys.right().value());
897 return Either.right(responseFormat);
899 List<CategoryDefinition> categoryList = categorys.left().value();
900 for (CategoryDefinition value : categoryList) {
901 if (value.getName().equals(category.getName())) {
902 return Either.left(true);
905 log.debug("Category {} is not part of service category group. Service category valid values are {}", list, categoryList);
906 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue()));
908 return Either.left(false);
911 public ResponseFormat deleteService(String serviceId, User user) {
912 ResponseFormat responseFormat;
913 String ecompErrorContext = "delete service";
915 Either<User, ResponseFormat> eitherCreator = validateUserExists(user, ecompErrorContext, false);
916 if (eitherCreator.isRight()) {
917 return eitherCreator.right().value();
919 user = eitherCreator.left().value();
921 Either<Service, StorageOperationStatus> serviceStatus = toscaOperationFacade.getToscaElement(serviceId);
922 if (serviceStatus.isRight()) {
923 log.debug("failed to get service {}", serviceId);
924 return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceStatus.right().value()), "");
927 Service service = serviceStatus.left().value();
929 StorageOperationStatus result = StorageOperationStatus.OK;
930 Either<Boolean, ResponseFormat> lockResult = lockComponent(service, "Mark service to delete");
931 if (lockResult.isRight()) {
932 result = StorageOperationStatus.GENERAL_ERROR;
933 return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
938 result = markComponentToDelete(service);
939 if (result.equals(StorageOperationStatus.OK)) {
940 responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
942 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
943 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, service.getName());
945 return responseFormat;
948 if (result == null || !result.equals(StorageOperationStatus.OK)) {
949 log.warn("operation failed. do rollback");
950 BeEcompErrorManager.getInstance().logBeSystemError("Delete Service");
953 log.debug("operation success. do commit");
956 graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service);
960 public ResponseFormat deleteServiceByNameAndVersion(String serviceName, String version, User user) {
961 ResponseFormat responseFormat;
962 String ecompErrorContext = "delete service";
963 Either<User, ResponseFormat> validateEmptyResult = validateUserNotEmpty(user, ecompErrorContext);
964 if (validateEmptyResult.isRight()) {
965 return validateEmptyResult.right().value();
968 Either<User, ResponseFormat> eitherCreator = validateUserExists(user, ecompErrorContext, false);
969 if (eitherCreator.isRight()) {
970 return eitherCreator.right().value();
972 user = eitherCreator.left().value();
974 Either<Service, ResponseFormat> getResult = getServiceByNameAndVersion(serviceName, version, user.getUserId());
975 if (getResult.isRight()) {
976 return getResult.right().value();
978 Service service = getResult.left().value();
980 StorageOperationStatus result = StorageOperationStatus.OK;
981 Either<Boolean, ResponseFormat> lockResult = lockComponent(service, "Mark service to delete");
982 if (lockResult.isRight()) {
983 result = StorageOperationStatus.GENERAL_ERROR;
984 return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
988 result = markComponentToDelete(service);
989 if (result.equals(StorageOperationStatus.OK)) {
990 responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
992 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
993 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, service.getName());
995 return responseFormat;
998 if (result == null || !result.equals(StorageOperationStatus.OK)) {
999 log.warn("operation failed. do rollback");
1000 BeEcompErrorManager.getInstance().logBeSystemError("Delete Service");
1001 titanDao.rollback();
1003 log.debug("operation success. do commit");
1006 graphLockOperation.unlockComponent(service.getUniqueId(), NodeTypeEnum.Service);
1010 public Either<Service, ResponseFormat> getService(String serviceId, User user) {
1011 String ecompErrorContext = "Get service";
1012 Either<User, ResponseFormat> validateEmptyResult = validateUserNotEmpty(user, ecompErrorContext);
1013 if (validateEmptyResult.isRight()) {
1014 return Either.right(validateEmptyResult.right().value());
1017 Either<User, ResponseFormat> eitherCreator = validateUserExists(user, ecompErrorContext, false);
1018 if (eitherCreator.isRight()) {
1019 return Either.right(eitherCreator.right().value());
1021 user = eitherCreator.left().value();
1023 Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
1024 if (storageStatus.isRight()) {
1025 log.debug("failed to get service by id {}", serviceId);
1026 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), serviceId));
1028 // Service service =
1029 // createServiceApiArtifactLIst(storageStatus.left().value());
1030 Service service = storageStatus.left().value();
1031 return Either.left(service);
1034 public Either<Service, ResponseFormat> getServiceByNameAndVersion(String serviceName, String serviceVersion, String userId) {
1035 Either<User, ResponseFormat> resp = validateUserExists(userId, "get Service By Name And Version", false);
1036 if (resp.isRight()) {
1037 return Either.right(resp.right().value());
1039 Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.SERVICE, serviceName, serviceVersion);
1040 if (storageStatus.isRight()) {
1041 log.debug("failed to get service by name {} and version {}", serviceName, serviceVersion);
1042 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), serviceName));
1044 Service service = storageStatus.left().value();
1045 return Either.left(service);
1048 @SuppressWarnings("unchecked")
1049 private void createMandatoryArtifactsData(Service service, User user) {
1050 // create mandatory artifacts
1052 // TODO it must be removed after that artifact uniqueId creation will be
1053 // moved to ArtifactOperation
1054 // String serviceUniqueId =
1055 // UniqueIdBuilder.buildServiceUniqueId(service.getComponentMetadataDefinition().getMetadataDataDefinition().getName(),
1056 // service.getComponentMetadataDefinition().getMetadataDataDefinition().getVersion());
1057 String serviceUniqueId = service.getUniqueId();
1058 Map<String, ArtifactDefinition> artifactMap = service.getArtifacts();
1059 if (artifactMap == null)
1060 artifactMap = new HashMap<String, ArtifactDefinition>();
1062 Map<String, Object> informationalServiceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getInformationalServiceArtifacts();
1063 List<String> exludeServiceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeServiceCategory();
1065 String category = service.getCategories().get(0).getName();
1066 boolean isCreateArtifact = true;
1067 if (category != null && exludeServiceCategory != null && !exludeServiceCategory.isEmpty()) {
1068 for (String exlude : exludeServiceCategory) {
1069 if (exlude.equalsIgnoreCase(category)) {
1070 isCreateArtifact = false;
1077 if (informationalServiceArtifacts != null && isCreateArtifact) {
1078 Set<String> keys = informationalServiceArtifacts.keySet();
1079 for (String informationalServiceArtifactName : keys) {
1080 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalServiceArtifacts.get(informationalServiceArtifactName);
1081 ArtifactDefinition artifactDefinition = createArtifactDefinition(serviceUniqueId, informationalServiceArtifactName, artifactInfoMap, user, false);
1082 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
1086 service.setArtifacts(artifactMap);
1090 private ArtifactDefinition createArtifactDefinition(String serviceId, String logicalName, Map<String, Object> artifactInfoMap, User user, Boolean isServiceApi) {
1092 ArtifactDefinition artifactInfo = artifactsBusinessLogic.createArtifactPlaceHolderInfo(serviceId, logicalName, artifactInfoMap, user, ArtifactGroupTypeEnum.INFORMATIONAL);
1095 artifactInfo.setMandatory(false);
1096 artifactInfo.setServiceApi(true);
1098 return artifactInfo;
1101 private Either<DistributionTransitionEnum, ResponseFormat> validateTransitionEnum(String distributionTransition, User user) {
1102 DistributionTransitionEnum transitionEnum = null;
1104 transitionEnum = DistributionTransitionEnum.getFromDisplayName(distributionTransition);
1105 if (transitionEnum == null) {
1106 BeEcompErrorManager.getInstance().logBeSystemError("Change Service Distribution");
1107 log.info("state operation is not valid. operations allowed are: {}", DistributionTransitionEnum.valuesAsString());
1108 ResponseFormat error = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1109 return Either.right(error);
1112 return Either.left(transitionEnum);
1115 private Either<String, ResponseFormat> validateComment(LifecycleChangeInfoWithAction comment, User user, AuditingActionEnum auditAction) {
1116 String data = comment.getUserRemarks();
1118 if (data == null || data.trim().isEmpty()) {
1119 BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Change Service Distribution");
1120 log.debug("user comment cannot be empty or null.");
1121 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1123 data = ValidationUtils.removeNoneUtf8Chars(data);
1124 data = ValidationUtils.removeHtmlTags(data);
1125 data = ValidationUtils.normaliseWhitespace(data);
1126 data = ValidationUtils.stripOctets(data);
1128 if (!ValidationUtils.validateLength(data, ValidationUtils.COMMENT_MAX_LENGTH)) {
1129 BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Change Service Distribution");
1130 log.debug("user comment exceeds limit.");
1131 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, "comment", String.valueOf(ValidationUtils.COMMENT_MAX_LENGTH)));
1133 if (!ValidationUtils.validateIsEnglish(data)) {
1134 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1136 return Either.left(data);
1139 private Either<Service, ResponseFormat> validateServiceDistributionChange(User user, String serviceId, AuditingActionEnum auditAction, String comment) {
1140 Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
1141 if (storageStatus.isRight()) {
1142 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceId);
1143 createAudit(user, auditAction, comment, responseFormat);
1144 return Either.right(responseFormat);
1146 Service service = storageStatus.left().value();
1148 if (service.getLifecycleState() != LifecycleStateEnum.CERTIFIED) {
1149 log.info("service {} is not available for distribution. Should be in certified state", service.getUniqueId());
1150 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, service.getVersion(), service.getName());
1151 createAudit(user, auditAction, comment, service, responseFormat);
1152 return Either.right(responseFormat);
1154 return Either.left(service);
1157 private Either<User, ResponseFormat> validateUserDistributionChange(User user, Service service, AuditingActionEnum auditAction, String comment) {
1158 log.debug("get user from DB");
1161 Either<User, ResponseFormat> eitherCreator = validateUser(user, "Activate Distribution", service, auditAction, false);
1162 if (eitherCreator.isRight()) {
1163 return Either.right(eitherCreator.right().value());
1165 user = eitherCreator.left().value();
1167 // validate user role
1168 List<Role> roles = new ArrayList<>();
1169 roles.add(Role.ADMIN);
1170 roles.add(Role.GOVERNOR);
1171 roles.add(Role.OPS);
1172 Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, service, roles, auditAction, comment);
1173 if (validateRes.isRight()) {
1174 return Either.right(validateRes.right().value());
1176 return Either.left(user);
1179 private void createAudit(User user, AuditingActionEnum auditAction, String comment, ResponseFormat responseFormat) {
1180 EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
1182 createAudit(user, auditAction, comment, null, responseFormat, auditingFields);
1185 private void createAudit(User user, AuditingActionEnum auditAction, String comment, Service component, ResponseFormat responseFormat) {
1186 EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
1187 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS, component.getDistributionStatus().name());
1188 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS, component.getDistributionStatus().name());
1189 createAudit(user, auditAction, comment, component, component.getLifecycleState().name(), component.getVersion(), responseFormat, auditingFields);
1192 private void createAudit(User user, AuditingActionEnum auditAction, String comment, Service component, ResponseFormat responseFormat, EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
1193 log.debug("audit before sending response");
1194 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, comment);
1195 componentsUtils.auditComponent(responseFormat, user, component, null, null, auditAction, ComponentTypeEnum.SERVICE, auditingFields);
1198 private void createAudit(User user, AuditingActionEnum auditAction, String comment, Service component, String prevState, String prevVersion, ResponseFormat responseFormat, EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
1199 log.debug("audit before sending response");
1200 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, comment);
1201 componentsUtils.auditComponent(responseFormat, user, component, prevState, prevVersion, auditAction, ComponentTypeEnum.SERVICE, auditingFields);
1204 public Either<Service, ResponseFormat> activateDistribution(String serviceId, String envName, User modifier, HttpServletRequest request) {
1206 Either<User, ResponseFormat> eitherCreator = validateUserExists(modifier.getUserId(), "activate Distribution", false);
1207 if (eitherCreator.isRight()) {
1208 return Either.right(eitherCreator.right().value());
1211 User user = eitherCreator.left().value();
1213 Either<Service, ResponseFormat> result = null;
1214 ResponseFormat response = null;
1215 Service updatedService = null;
1216 String did = ThreadLocalsHolder.getUuid();
1217 EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
1218 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, did);
1220 String configuredEnvName = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getEnvironments().get(0);
1221 if (configuredEnvName != null && false == envName.equals(configuredEnvName)) {
1222 log.trace("Update environment name to be {} instead of {}", configuredEnvName, envName);
1223 envName = configuredEnvName;
1227 ServletContext servletContext = request.getSession().getServletContext();
1228 boolean isDistributionEngineUp = getHealthCheckBL(servletContext).isDistributionEngineUp(request.getSession().getServletContext()); // DE
1229 if (!isDistributionEngineUp) {
1230 BeEcompErrorManager.getInstance().logBeSystemError("Distribution Engine is DOWN");
1231 log.debug("Distribution Engine is DOWN");
1232 response = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1233 return Either.right(response);
1236 Either<Service, StorageOperationStatus> serviceRes = toscaOperationFacade.getToscaElement(serviceId);
1237 if (serviceRes.isRight()) {
1238 log.debug("failed retrieving service");
1239 response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceRes.right().value(), ComponentTypeEnum.SERVICE), serviceId);
1240 componentsUtils.auditComponent(response, user, null, null, null, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST, ComponentTypeEnum.SERVICE, auditingFields);
1241 return Either.right(response);
1243 Service service = serviceRes.left().value();
1244 String dcurrStatus = service.getDistributionStatus().name();
1245 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS, dcurrStatus);
1247 Either<INotificationData, StorageOperationStatus> readyForDistribution = distributionEngine.isReadyForDistribution(service, did, envName);
1248 if (readyForDistribution.isLeft()) {
1249 INotificationData notificationData = readyForDistribution.left().value();
1250 StorageOperationStatus notifyServiceResponse = distributionEngine.notifyService(did, service, notificationData, envName, user.getUserId(), user.getFullName());
1251 if (notifyServiceResponse == StorageOperationStatus.OK) {
1252 Either<Service, ResponseFormat> updateStateRes = updateDistributionStatusForActivation(service, user, DistributionStatusEnum.DISTRIBUTED);
1253 if (updateStateRes.isLeft() && updateStateRes.left().value() != null) {
1254 updatedService = updateStateRes.left().value();
1255 dcurrStatus = updatedService.getDistributionStatus().name();
1257 // The response is not relevant
1258 updatedService = service;
1260 ASDCKpiApi.countActivatedDistribution();
1261 response = componentsUtils.getResponseFormat(ActionStatus.OK);
1262 result = Either.left(updatedService);
1264 BeEcompErrorManager.getInstance().logBeSystemError("Activate Distribution - send notification");
1265 log.debug("distributionEngine.notifyService response is: {}", notifyServiceResponse);
1266 response = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1267 result = Either.right(response);
1270 StorageOperationStatus distEngineValidationResponse = readyForDistribution.right().value();
1271 response = componentsUtils.getResponseFormatByDE(componentsUtils.convertFromStorageResponse(distEngineValidationResponse), service.getName(), envName);
1272 result = Either.right(response);
1274 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS, dcurrStatus);
1275 componentsUtils.auditComponent(response, user, service, null, null, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST, ComponentTypeEnum.SERVICE, auditingFields);
1279 // convert to private after deletion of temp url
1280 public Either<Service, ResponseFormat> updateDistributionStatusForActivation(Service service, User user, DistributionStatusEnum state) {
1282 Either<User, ResponseFormat> resp = validateUserExists(user.getUserId(), "update Distribution Status For Activation", false);
1283 if (resp.isRight()) {
1284 return Either.right(resp.right().value());
1287 String serviceId = service.getUniqueId();
1288 Either<Boolean, ResponseFormat> lockResult = lockComponent(serviceId, service, "updateDistributionStatusForActivation");
1289 if (lockResult.isRight()) {
1290 return Either.right(lockResult.right().value());
1293 Either<Service, StorageOperationStatus> result = toscaOperationFacade.updateDistributionStatus(service, user, state);
1294 if (result.isRight()) {
1295 titanDao.rollback();
1296 BeEcompErrorManager.getInstance().logBeSystemError("updateDistributionStatusForActivation");
1297 log.debug("service {} change distribution status failed", serviceId);
1298 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1301 return Either.left(result.left().value());
1303 graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service);
1307 public Either<Service, ResponseFormat> markDistributionAsDeployed(String serviceId, String did, User user) {
1309 Either<User, ResponseFormat> resp = validateUserExists(user.getUserId(), "mark Distribution As Deployed", false);
1310 if (resp.isRight()) {
1311 return Either.right(resp.right().value());
1314 log.debug("mark distribution deployed");
1316 AuditingActionEnum auditAction = AuditingActionEnum.DISTRIBUTION_DEPLOY;
1317 Either<Service, StorageOperationStatus> getServiceResponse = toscaOperationFacade.getToscaElement(serviceId);
1318 if (getServiceResponse.isRight()) {
1319 BeEcompErrorManager.getInstance().logBeComponentMissingError("markDistributionAsDeployed", ComponentTypeEnum.SERVICE.getValue(), serviceId);
1320 log.debug("service {} not found", serviceId);
1321 ResponseFormat responseFormat = auditDeployError(did, user, auditAction, null, componentsUtils.convertFromStorageResponse(getServiceResponse.right().value(), ComponentTypeEnum.SERVICE), "");
1323 return Either.right(responseFormat);
1326 Service service = getServiceResponse.left().value();
1328 Either<User, ResponseFormat> validateRoleForDeploy = validateRoleForDeploy(did, user, auditAction, service);
1329 if (validateRoleForDeploy.isRight()) {
1330 return Either.right(validateRoleForDeploy.right().value());
1332 user = validateRoleForDeploy.left().value();
1334 return checkDistributionAndDeploy(did, user, auditAction, service);
1338 public Either<Service, ResponseFormat> generateVfModuleArtifacts(Service service, User modifier, boolean shouldLock) {
1339 Function<ComponentInstance, List<ArtifactGenerator<ArtifactDefinition>>> artifactTaskGeneratorCreator = ri ->
1340 // Only one VF Module Artifact per instance - add it to a list of one
1341 buildArtifactGenList(service, modifier, shouldLock, ri);
1343 return generateDeploymentArtifacts(service, modifier, artifactTaskGeneratorCreator);
1347 private List<ArtifactGenerator<ArtifactDefinition>> buildArtifactGenList(Service service, User modifier, boolean shouldLock, ComponentInstance ri) {
1348 List<ArtifactGenerator<ArtifactDefinition>> asList = new ArrayList<ArtifactGenerator<ArtifactDefinition>>();
1350 if (ri.getOriginType() == OriginTypeEnum.VF) {
1351 asList = Arrays.asList(new VfModuleArtifacGenerator(modifier, ri, service, shouldLock));
1356 private List<GroupInstance> collectGroupsInstanceForCompInstance(ComponentInstance currVF, Wrapper<ResponseFormat> responseWrapper) {
1358 return currVF.getGroupInstances();
1361 private ArtifactDefinition getVfModuleInstArtifactForCompInstance(ComponentInstance currVF, Service service, User modifier, List<GroupInstance> groupsForCurrVF, Wrapper<String> payloadWrapper, Wrapper<ResponseFormat> responseWrapper) {
1362 ArtifactDefinition vfModuleAertifact = null;
1363 if (MapUtils.isNotEmpty(currVF.getDeploymentArtifacts())) {
1364 Optional<ArtifactDefinition> optionalVfModuleArtifact = currVF.getDeploymentArtifacts().values().stream().filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.VF_MODULES_METADATA.name())).findAny();
1365 if (optionalVfModuleArtifact.isPresent()) {
1366 vfModuleAertifact = optionalVfModuleArtifact.get();
1369 if (vfModuleAertifact == null) {
1370 Either<ArtifactDefinition, ResponseFormat> createVfModuleArtifact = createVfModuleArtifact(modifier, currVF, service, payloadWrapper.getInnerElement());
1371 if (createVfModuleArtifact.isLeft()) {
1372 vfModuleAertifact = createVfModuleArtifact.left().value();
1374 responseWrapper.setInnerElement(createVfModuleArtifact.right().value());
1377 return vfModuleAertifact;
1380 private void fillVfModuleInstHeatEnvPayload(List<GroupInstance> groupsForCurrVF, ComponentInstance currVFInstance, Wrapper<String> payloadWrapper) {
1381 // Converts GroupDefinition to VfModuleArtifactPayload which is the
1382 // format used in the payload
1384 // List<VfModuleArtifactPayload> vfModulePayloadForCurrVF = groupsForCurrVF.stream().map(group -> new VfModuleArtifactPayload(group)).collect(Collectors.toList());
1385 List<VfModuleArtifactPayload> vfModulePayloadForCurrVF = new ArrayList<VfModuleArtifactPayload>();
1386 if (groupsForCurrVF != null) {
1387 for (GroupInstance groupInstance : groupsForCurrVF) {
1388 VfModuleArtifactPayload modulePayload = new VfModuleArtifactPayload(groupInstance);
1389 vfModulePayloadForCurrVF.add(modulePayload);
1391 Collections.sort(vfModulePayloadForCurrVF, (art1, art2) -> VfModuleArtifactPayload.compareByGroupName(art1, art2));
1392 // Update Payload With Heat Env
1393 // vfModulePayloadForCurrVF.stream().forEach(e -> addHeatEnvArtifactsToVFModulePayload(e, currVFInstance));
1395 final Gson gson = new GsonBuilder().setPrettyPrinting().create();
1397 String vfModulePayloadString = gson.toJson(vfModulePayloadForCurrVF);
1398 payloadWrapper.setInnerElement(vfModulePayloadString);
1403 private void addHeatEnvArtifactsToVFModulePayload(VfModuleArtifactPayload vfModulePayload, ComponentInstance currVFInstance) {
1404 List<String> originalModuleArtifacts = vfModulePayload.getArtifacts();
1405 if (!MapUtils.isEmpty(currVFInstance.getDeploymentArtifacts()) && !CollectionUtils.isEmpty(originalModuleArtifacts)) {
1407 // EVG : fix now for patch. remove null from list. Need to be fixed later : remove VF HEAT ENV uuid from the list??
1408 List<String> filteredUUIDFromModule = originalModuleArtifacts.stream().filter(uuid -> uuid != null).collect(Collectors.toList());
1410 final Collection<ArtifactDefinition> depInsArtifacts = currVFInstance.getDeploymentArtifacts().values();
1412 List<ArtifactDefinition> heatEnvArtifacts = depInsArtifacts.stream().filter(art -> art.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.getType())).collect(Collectors.toList());
1413 // Unique Id Of Artifacts In the vf module
1414 List<String> moduleArtUniqueId = depInsArtifacts.stream().filter(art -> originalModuleArtifacts.contains(art.getArtifactUUID())).map(art -> art.getUniqueId()).collect(Collectors.toList());
1415 // Collect Only Heat Artifatcs that are Generated from artifacts in
1417 List<String> relevantHeatEnvUUID = heatEnvArtifacts.stream().filter(heatEnv -> moduleArtUniqueId.contains(heatEnv.getGeneratedFromId())).map(heatEnv -> heatEnv.getArtifactUUID()).collect(Collectors.toList());
1419 List<String> fullArtifactList = new ArrayList<>();
1420 fullArtifactList.addAll(filteredUUIDFromModule);
1421 fullArtifactList.addAll(relevantHeatEnvUUID);
1423 vfModulePayload.setArtifacts(fullArtifactList);
1427 private Either<ArtifactDefinition, ResponseFormat> generateVfModuleInstanceArtifact(User modifier, ComponentInstance currVFInstance, Service service, boolean shouldLock) {
1428 ArtifactDefinition vfModuleAertifact = null;
1429 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
1430 Wrapper<String> payloadWrapper = new Wrapper<>();
1431 List<GroupInstance> groupsForCurrVF = collectGroupsInstanceForCompInstance(currVFInstance, responseWrapper);
1432 if (responseWrapper.isEmpty()) {
1433 fillVfModuleInstHeatEnvPayload(groupsForCurrVF, currVFInstance, payloadWrapper);
1435 if (responseWrapper.isEmpty() && payloadWrapper.getInnerElement() != null) {
1436 vfModuleAertifact = getVfModuleInstArtifactForCompInstance(currVFInstance, service, modifier, groupsForCurrVF, payloadWrapper, responseWrapper);
1438 if (responseWrapper.isEmpty() && vfModuleAertifact != null) {
1439 vfModuleAertifact = fillVfModulePayload(modifier, currVFInstance, vfModuleAertifact, shouldLock, payloadWrapper, responseWrapper, service);
1442 Either<ArtifactDefinition, ResponseFormat> result;
1443 if (responseWrapper.isEmpty()) {
1444 result = Either.left(vfModuleAertifact);
1446 result = Either.right(responseWrapper.getInnerElement());
1452 private ArtifactDefinition fillVfModulePayload(User modifier, ComponentInstance currVF, ArtifactDefinition vfModuleArtifact, boolean shouldLock, Wrapper<String> payloadWrapper, Wrapper<ResponseFormat> responseWrapper, Service service) {
1453 ArtifactDefinition result = null;
1454 // final Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(currVF.getComponentUid());
1455 // if (eitherResource.isRight()) {
1456 // responseWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherResource.right().value())));
1457 // } else if (!payloadWrapper.isEmpty()) {
1458 // Resource resource = eitherResource.left().value();
1459 Either<ArtifactDefinition, ResponseFormat> eitherPayload = artifactsBusinessLogic.generateArtifactPayload(vfModuleArtifact, ComponentTypeEnum.RESOURCE_INSTANCE, service, currVF.getName(), modifier, shouldLock, () -> System.currentTimeMillis(),
1460 () -> Either.left(artifactsBusinessLogic.createEsArtifactData(vfModuleArtifact, payloadWrapper.getInnerElement().getBytes(StandardCharsets.UTF_8))), currVF.getUniqueId());
1461 if (eitherPayload.isLeft()) {
1462 result = eitherPayload.left().value();
1464 responseWrapper.setInnerElement(eitherPayload.right().value());
1467 if (result == null) {
1468 result = vfModuleArtifact;
1474 private Either<ArtifactDefinition, ResponseFormat> createVfModuleArtifact(User modifier, ComponentInstance currVF, Service service, String vfModulePayloadString) {
1476 ArtifactDefinition vfModuleArtifactDefinition = new ArtifactDefinition();
1477 String newCheckSum = null;
1479 vfModuleArtifactDefinition.setDescription("Auto-generated VF Modules information artifact");
1480 vfModuleArtifactDefinition.setArtifactDisplayName("Vf Modules Metadata");
1481 vfModuleArtifactDefinition.setArtifactType(ArtifactTypeEnum.VF_MODULES_METADATA.getType());
1482 vfModuleArtifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT);
1483 vfModuleArtifactDefinition.setArtifactLabel("vfModulesMetadata");
1484 vfModuleArtifactDefinition.setTimeout(0);
1485 vfModuleArtifactDefinition.setArtifactName(currVF.getNormalizedName() + "_modules.json");
1486 vfModuleArtifactDefinition.setPayloadData(vfModulePayloadString);
1487 if (vfModulePayloadString != null) {
1488 newCheckSum = GeneralUtility.calculateMD5ByByteArray(vfModulePayloadString.getBytes());
1490 vfModuleArtifactDefinition.setArtifactChecksum(newCheckSum);
1492 Either<ArtifactDefinition, StorageOperationStatus> addArifactToComponent = artifactToscaOperation.addArifactToComponent(vfModuleArtifactDefinition, service.getUniqueId(), NodeTypeEnum.ResourceInstance, true, currVF.getUniqueId());
1494 Either<ArtifactDefinition, ResponseFormat> result;
1495 if (addArifactToComponent.isLeft()) {
1496 result = Either.left(addArifactToComponent.left().value());
1498 result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArifactToComponent.right().value())));
1504 public Either<Service, ResponseFormat> generateHeatEnvArtifacts(Service service, User modifier, boolean shouldLock) {
1506 Function<ComponentInstance, List<ArtifactGenerator<ArtifactDefinition>>> artifactTaskGeneratorCreator = resourceInstance ->
1507 // Get All Deployment Artifacts
1508 service.getComponentInstances().stream().filter(ri -> ri != null && ri == resourceInstance).filter(ri -> ri.getDeploymentArtifacts() != null).flatMap(ri -> ri.getDeploymentArtifacts().values().stream()).
1509 // Filter in Only Heat Env
1510 filter(depArtifact -> ArtifactTypeEnum.HEAT_ENV.getType().equals(depArtifact.getArtifactType())).
1511 // Create ArtifactGenerator from those Artifacts
1512 map(depArtifact -> new HeatEnvArtifactGenerator(depArtifact, service, resourceInstance.getName(), modifier, shouldLock, resourceInstance.getUniqueId())).collect(Collectors.toList());
1514 return generateDeploymentArtifacts(service, modifier, artifactTaskGeneratorCreator);
1518 private <CallVal> Either<Service, ResponseFormat> generateDeploymentArtifacts(Service service, User modifier, Function<ComponentInstance, List<ArtifactGenerator<CallVal>>> artifactTaskGeneratorCreator) {
1520 // Get Flat List of (Callable) ArtifactGenerator for all the RI in the
1522 if (service.getComponentInstances() != null) {
1523 List<ArtifactGenerator<CallVal>> artifactGenList = service.getComponentInstances().stream().flatMap(ri -> artifactTaskGeneratorCreator.apply(ri).stream()).collect(Collectors.toList());
1524 if (artifactGenList != null && !artifactGenList.isEmpty()) {
1525 for (ArtifactGenerator<CallVal> entry : artifactGenList) {
1526 Either<CallVal, ResponseFormat> callRes;
1528 callRes = entry.call();
1529 if (callRes.isRight()) {
1530 log.debug("Failed to generate artifact error : {}", callRes.right().value());
1531 return Either.right(callRes.right().value());
1533 } catch (Exception e) {
1534 log.debug("Failed to generate artifact exception : {}", e);
1535 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1540 return Either.left(service);
1543 abstract class ArtifactGenerator<CallVal> implements Callable<Either<CallVal, ResponseFormat>> {
1547 class HeatEnvArtifactGenerator extends ArtifactGenerator<ArtifactDefinition> {
1548 ArtifactDefinition artifactDefinition;
1550 String resourceInstanceName;
1555 HeatEnvArtifactGenerator(ArtifactDefinition artifactDefinition, Service service, String resourceInstanceName, User modifier, boolean shouldLock, String instanceId) {
1556 this.artifactDefinition = artifactDefinition;
1557 this.service = service;
1558 this.resourceInstanceName = resourceInstanceName;
1559 this.modifier = modifier;
1560 this.shouldLock = shouldLock;
1561 this.instanceId = instanceId;
1565 public Either<ArtifactDefinition, ResponseFormat> call() throws Exception {
1566 return artifactsBusinessLogic.generateHeatEnvArtifact(artifactDefinition, ComponentTypeEnum.RESOURCE_INSTANCE, service, resourceInstanceName, modifier, shouldLock, instanceId);
1569 public ArtifactDefinition getArtifactDefinition() {
1570 return artifactDefinition;
1575 class VfModuleArtifacGenerator extends ArtifactGenerator<ArtifactDefinition> {
1577 private ComponentInstance componentInstance;
1578 private Service service;
1582 public Either<ArtifactDefinition, ResponseFormat> call() throws Exception {
1583 return generateVfModuleInstanceArtifact(user, componentInstance, service, shouldLock);// generateVfModuleArtifact(user, componentInstance, service, shouldLock);
1586 private VfModuleArtifacGenerator(User user, ComponentInstance componentInstance, Service service, boolean shouldLock) {
1589 this.componentInstance = componentInstance;
1590 this.service = service;
1591 this.shouldLock = shouldLock;
1596 private synchronized Either<Service, ResponseFormat> checkDistributionAndDeploy(String did, User user, AuditingActionEnum auditAction, Service service) {
1597 boolean isDeployed = isDistributionDeployed(did, service);
1599 return Either.left(service);
1601 Either<Boolean, ResponseFormat> distributionSuccess = checkDistributionSuccess(did, user, auditAction, service);
1602 if (distributionSuccess.isRight()) {
1603 return Either.right(distributionSuccess.right().value());
1606 log.debug("mark distribution {} as deployed - success", did);
1607 componentsUtils.auditServiceDistributionDeployed(auditAction, service.getName(), service.getVersion(), service.getUUID(), did, STATUS_DEPLOYED, "OK", user);
1608 return Either.left(service);
1611 private boolean isDistributionDeployed(String did, Service service) {
1612 Either<List<DistributionDeployEvent>, ActionStatus> alreadyDeployed = auditCassandraDao.getDistributionDeployByStatus(did, AuditingActionEnum.DISTRIBUTION_DEPLOY.getName(), STATUS_DEPLOYED);
1614 boolean isDeployed = false;
1615 if (alreadyDeployed.isLeft() && !alreadyDeployed.left().value().isEmpty()) {
1617 log.debug("distribution {} is already deployed", did);
1623 protected Either<Boolean, ResponseFormat> checkDistributionSuccess(String did, User user, AuditingActionEnum auditAction, Service service) {
1625 log.trace("checkDistributionSuccess");
1626 // get all "DRequest" records for this distribution
1627 // Either<List<ESTimeBasedEvent>, ActionStatus> distRequestsResponse =
1628 // auditingDao.getListOfDistributionByAction(did,
1629 // AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName(), "",
1630 // ResourceAdminEvent.class);
1631 Either<List<ResourceAdminEvent>, ActionStatus> distRequestsResponse = auditCassandraDao.getDistributionRequest(did, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName());
1632 if (distRequestsResponse.isRight()) {
1633 ResponseFormat error = auditDeployError(did, user, auditAction, service, distRequestsResponse.right().value());
1634 return Either.right(error);
1637 List<ResourceAdminEvent> distributionRequests = distRequestsResponse.left().value();
1638 if (distributionRequests.isEmpty()) {
1639 BeEcompErrorManager.getInstance().logBeDistributionMissingError("markDistributionAsDeployed", did);
1640 log.info("distribution {} is not found", did);
1641 ResponseFormat error = auditDeployError(did, user, auditAction, service, ActionStatus.DISTRIBUTION_REQUESTED_NOT_FOUND);
1642 return Either.right(error);
1644 boolean isRequestSucceeded = false;
1645 for (ResourceAdminEvent event : distributionRequests) {
1646 String eventStatus = event.getStatus();
1647 if (eventStatus != null && eventStatus.equals(STATUS_SUCCESS_200)) {
1648 isRequestSucceeded = true;
1653 // get all "DNotify" records for this distribution
1654 // Either<List<ESTimeBasedEvent>, ActionStatus>
1655 // distNotificationsResponse =
1656 // auditingDao.getListOfDistributionByAction(did,
1657 // AuditingActionEnum.DISTRIBUTION_NOTIFY.getName(), "",
1658 // DistributionNotificationEvent.class);
1659 Either<List<DistributionNotificationEvent>, ActionStatus> distNotificationsResponse = auditCassandraDao.getDistributionNotify(did, AuditingActionEnum.DISTRIBUTION_NOTIFY.getName());
1660 if (distNotificationsResponse.isRight()) {
1661 ResponseFormat error = auditDeployError(did, user, auditAction, service, distNotificationsResponse.right().value());
1662 return Either.right(error);
1665 List<DistributionNotificationEvent> distributionNotifications = distNotificationsResponse.left().value();
1666 boolean isNotificationsSucceeded = false;
1667 for (DistributionNotificationEvent event : distributionNotifications) {
1668 String eventStatus = event.getStatus();
1669 if (eventStatus != null && eventStatus.equals(STATUS_SUCCESS_200)) {
1670 isNotificationsSucceeded = true;
1675 // if request failed OR there are notifications that failed
1676 if (!(isRequestSucceeded && isNotificationsSucceeded)) {
1678 log.info("distribution {} has failed", did);
1679 ResponseFormat error = componentsUtils.getResponseFormat(ActionStatus.DISTRIBUTION_REQUESTED_FAILED, did);
1680 auditDeployError(did, user, auditAction, service, ActionStatus.DISTRIBUTION_REQUESTED_FAILED, did);
1681 return Either.right(error);
1683 return Either.left(true);
1686 private ResponseFormat auditDeployError(String did, User user, AuditingActionEnum auditAction, Service service, ActionStatus status, String... params) {
1688 ResponseFormat error = componentsUtils.getResponseFormat(status, params);
1689 String message = "";
1690 if (error.getMessageId() != null) {
1691 message = error.getMessageId() + ": ";
1693 message += error.getFormattedMessage();
1695 if (service != null) {
1696 componentsUtils.auditServiceDistributionDeployed(auditAction, service.getName(), service.getVersion(), service.getUUID(), did, error.getStatus().toString(), message, user);
1698 componentsUtils.auditServiceDistributionDeployed(auditAction, "", "", "", did, error.getStatus().toString(), message, user);
1703 private Either<User, ResponseFormat> validateRoleForDeploy(String did, User user, AuditingActionEnum auditAction, Service service) {
1704 Either<User, ActionStatus> eitherCreator = userAdmin.getUser(user.getUserId(), false);
1705 if (eitherCreator.isRight() || eitherCreator.left().value() == null) {
1706 BeEcompErrorManager.getInstance().logBeUserMissingError("Deploy Service", user.getUserId());
1707 log.debug("validateRoleForDeploy method - user is not listed. userId= {}", user.getUserId());
1708 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND, user.getUserId());
1709 auditDeployError(did, user, auditAction, service, ActionStatus.USER_NOT_FOUND);
1710 return Either.right(responseFormat);
1712 user = eitherCreator.left().value();
1713 log.debug("validate user role");
1714 List<Role> roles = new ArrayList<>();
1715 roles.add(Role.ADMIN);
1716 roles.add(Role.OPS);
1717 Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, service, roles, auditAction, null);
1718 if (validateRes.isRight()) {
1719 log.info("role {} is not allowed to perform this action", user.getRole());
1720 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
1721 auditDeployError(did, user, auditAction, service, ActionStatus.RESTRICTED_OPERATION);
1722 return Either.right(responseFormat);
1724 return Either.left(user);
1729 public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
1734 public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
1735 return deleteMarkedComponents(ComponentTypeEnum.SERVICE);
1738 private HealthCheckBusinessLogic getHealthCheckBL(ServletContext context) {
1739 WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
1740 WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
1741 HealthCheckBusinessLogic healthCheckBl = webApplicationContext.getBean(HealthCheckBusinessLogic.class);
1742 return healthCheckBl;
1746 public ComponentInstanceBusinessLogic getComponentInstanceBL() {
1747 return serviceComponentInstanceBusinessLogic;
1751 public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) {
1753 Either<User, ResponseFormat> resp = validateUserExists(userId, "Get Component Instances", false);
1754 if (resp.isRight()) {
1755 return Either.right(resp.right().value());
1757 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1758 if (getComponentRes.isRight()) {
1759 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentRes.right().value()));
1760 return Either.right(responseFormat);
1763 List<ComponentInstance> componentInstances = getComponentRes.left().value().getComponentInstances();
1764 // componentInstances = componentInstances.stream().filter(instance -> instance.getOriginType().equals(OriginTypeEnum.VF)).collect(Collectors.toList());
1766 return Either.left(componentInstances);
1769 public ICacheMangerOperation getCacheManagerOperation() {
1770 return cacheManagerOperation;
1773 public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) {
1774 this.cacheManagerOperation = cacheManagerOperation;
1778 * updates group instance with new property values in case of successful update of group instance related component instance will be updated with new modification time and related service will be updated with new last update date
1782 * @param componentInstanceId
1783 * @param groupInstanceId
1784 * @param newProperties
1787 public Either<List<GroupInstanceProperty>, ResponseFormat> updateGroupInstancePropertyValues(User modifier, String serviceId, String componentInstanceId, String groupInstanceId, List<GroupInstanceProperty> newProperties) {
1789 Either<List<GroupInstanceProperty>, ResponseFormat> actionResult = null;
1790 Either<ImmutablePair<Component, User>, ResponseFormat> validateUserAndComponentRes;
1791 Component component = null;
1792 Either<Boolean, ResponseFormat> lockResult = null;
1793 log.debug("Going to update group instance {} of service {} with new property values. ", groupInstanceId, serviceId);
1795 validateUserAndComponentRes = validateUserAndComponent(serviceId, modifier);
1796 if (validateUserAndComponentRes.isRight()) {
1797 log.debug("Cannot update group instance {} of service {} with new property values. Validation failed. ", groupInstanceId, serviceId);
1798 actionResult = Either.right(validateUserAndComponentRes.right().value());
1800 if (actionResult == null) {
1801 component = validateUserAndComponentRes.left().value().getKey();
1802 lockResult = lockComponentByName(component.getSystemName(), component, "Update Group Instance on Service");
1803 if (lockResult.isRight()) {
1804 log.debug("Failed to lock service {}. Response is {}. ", component.getName(), lockResult.right().value().getFormattedMessage());
1805 actionResult = Either.right(lockResult.right().value());
1807 log.debug("The service with system name {} locked. ", component.getSystemName());
1810 if (actionResult == null) {
1811 actionResult = validateAndUpdateGroupInstancePropertyValuesAndContainingParents(component, componentInstanceId, groupInstanceId, newProperties);
1812 if (actionResult.isRight()) {
1813 log.debug("Failed to validate and update group instance {} property values and containing parents. The message is {}. ", groupInstanceId, actionResult.right().value().getFormattedMessage());
1816 } catch (Exception e) {
1817 log.error("Exception occured during update Group Instance property values: {}", e.getMessage(), e);
1818 actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1820 if (lockResult != null && lockResult.isLeft() && lockResult.left().value()) {
1821 graphLockOperation.unlockComponentByName(component.getSystemName(), component.getUniqueId(), NodeTypeEnum.Service);
1824 return actionResult;
1827 private Either<List<GroupInstanceProperty>, ResponseFormat> validateAndUpdateGroupInstancePropertyValuesAndContainingParents(Component component, String componentInstanceId, String groupInstanceId, List<GroupInstanceProperty> newProperties) {
1829 Either<List<GroupInstanceProperty>, ResponseFormat> actionResult = null;
1830 Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceRes;
1831 Either<ImmutablePair<ComponentMetadataData, ComponentInstanceData>, ResponseFormat> updateParentsModificationTimeRes;
1832 ComponentInstance relatedComponentInstance = null;
1833 GroupInstance oldGroupInstance = null;
1834 Either<GroupInstance, ResponseFormat> updateGroupInstanceResult = null;
1835 GroupInstance updatedGroupInstance = null;
1836 boolean inTransaction = true;
1837 boolean shouldCloseTransaction = true;
1838 findGroupInstanceRes = findGroupInstanceOnRelatedComponentInstance(component, componentInstanceId, groupInstanceId);
1839 if (findGroupInstanceRes.isRight()) {
1840 log.debug("Group instance {} not found. ", groupInstanceId);
1841 actionResult = Either.right(findGroupInstanceRes.right().value());
1843 if (actionResult == null) {
1844 oldGroupInstance = findGroupInstanceRes.left().value().getValue();
1845 relatedComponentInstance = findGroupInstanceRes.left().value().getKey();
1846 updateGroupInstanceResult = groupBusinessLogic.validateAndUpdateGroupInstancePropertyValues(component.getUniqueId(), componentInstanceId, oldGroupInstance, newProperties, inTransaction);
1847 if (updateGroupInstanceResult.isRight()) {
1848 log.debug("Failed to update group instance {} property values. ", oldGroupInstance.getName());
1849 actionResult = Either.right(updateGroupInstanceResult.right().value());
1852 if (actionResult == null) {
1853 updatedGroupInstance = updateGroupInstanceResult.left().value();
1854 if (!oldGroupInstance.getModificationTime().equals(updatedGroupInstance.getModificationTime())) {
1855 updateParentsModificationTimeRes = updateParentsModificationTimeAndCustomizationUuid(component, relatedComponentInstance, updatedGroupInstance, inTransaction, shouldCloseTransaction);
1856 if (updateParentsModificationTimeRes.isRight()) {
1857 log.debug("Failed to update modification time. ", oldGroupInstance.getName());
1858 actionResult = Either.right(updateParentsModificationTimeRes.right().value());
1862 if (actionResult == null) {
1863 actionResult = Either.left(updatedGroupInstance.convertToGroupInstancesProperties());
1865 return actionResult;
1868 private Either<ImmutablePair<ComponentMetadataData, ComponentInstanceData>, ResponseFormat> updateParentsModificationTimeAndCustomizationUuid(Component component, ComponentInstance relatedComponentInstance, GroupInstance updatedGroupInstance,
1869 boolean inTranscation, boolean shouldCloseTransaction) {
1871 Either<ImmutablePair<ComponentMetadataData, ComponentInstanceData>, ResponseFormat> actionResult;
1872 Either<ComponentMetadataData, StorageOperationStatus> serviceMetadataUpdateResult;
1873 Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceRes = serviceComponentInstanceBusinessLogic.updateComponentInstanceModificationTimeAndCustomizationUuid(relatedComponentInstance, NodeTypeEnum.ResourceInstance,
1874 updatedGroupInstance.getModificationTime(), inTranscation);
1875 if (updateComponentInstanceRes.isRight()) {
1876 log.debug("Failed to update component instance {} after update of group instance {}. ", relatedComponentInstance.getName(), updatedGroupInstance.getName());
1877 actionResult = Either.right(updateComponentInstanceRes.right().value());
1879 serviceMetadataUpdateResult = toscaOperationFacade.updateComponentLastUpdateDateOnGraph(component, updatedGroupInstance.getModificationTime());
1880 if (serviceMetadataUpdateResult.isRight()) {
1881 log.debug("Failed to update service {} after update of component instance {} with new property values of group instance {}. ", component.getName(), relatedComponentInstance.getName(), updatedGroupInstance.getName());
1882 actionResult = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceMetadataUpdateResult.right().value())));
1884 actionResult = Either.left(new ImmutablePair<>(serviceMetadataUpdateResult.left().value(), updateComponentInstanceRes.left().value()));
1887 return actionResult;
1890 private Either<ImmutablePair<Component, User>, ResponseFormat> validateUserAndComponent(String serviceId, User modifier) {
1892 Either<ImmutablePair<Component, User>, ResponseFormat> result = null;
1893 Either<Component, ResponseFormat> validateComponentExistsRes = null;
1894 User currUser = null;
1895 Component component = null;
1896 Either<User, ResponseFormat> validationUserResult = validateUserIgnoreAudit(modifier, "updateGroupInstancePropertyValues");
1897 if (validationUserResult.isRight()) {
1898 log.debug("Failed to validate user with userId for update service {}. ", modifier.getUserId(), serviceId);
1899 result = Either.right(validationUserResult.right().value());
1901 if (result == null) {
1902 currUser = validationUserResult.left().value();
1903 validateComponentExistsRes = validateComponentExists(serviceId, ComponentTypeEnum.SERVICE, null);
1904 if (validateComponentExistsRes.isRight()) {
1905 log.debug("Failed to validate service existing {}. ", serviceId);
1906 result = Either.right(validateComponentExistsRes.right().value());
1909 if (result == null) {
1910 component = validateComponentExistsRes.left().value();
1911 if (!ComponentValidationUtils.canWorkOnComponent(component, currUser.getUserId())) {
1912 log.info("Restricted operation for user: {}, on service: {}", currUser.getUserId(), component.getCreatorUserId());
1913 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1916 if (result == null) {
1917 result = Either.left(new ImmutablePair<>(component, currUser));
1922 private Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceOnRelatedComponentInstance(Component component, String componentInstanceId, String groupInstanceId) {
1924 Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> actionResult = null;
1925 GroupInstance groupInstance = null;
1926 ComponentInstance foundComponentInstance = findRelatedComponentInstance(component, componentInstanceId);
1927 if (foundComponentInstance == null) {
1928 log.debug("Component instance {} not found on service {}. ", componentInstanceId, component.getName());
1929 actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstanceId, "resource instance", "service", component.getName()));
1930 } else if (!CollectionUtils.isEmpty(foundComponentInstance.getGroupInstances())) {
1931 groupInstance = foundComponentInstance.getGroupInstances().stream().filter(gi -> gi.getUniqueId().equals(groupInstanceId)).findFirst().orElse(null);
1932 if (groupInstance == null) {
1933 log.debug("Group instance {} not found on component instance {}. ", groupInstanceId, foundComponentInstance.getName());
1934 actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INSTANCE_NOT_FOUND_ON_COMPONENT_INSTANCE, groupInstanceId, foundComponentInstance.getName()));
1937 if (actionResult == null) {
1938 actionResult = Either.left(new ImmutablePair<>(foundComponentInstance, groupInstance));
1940 return actionResult;
1943 private ComponentInstance findRelatedComponentInstance(Component component, String componentInstanceId) {
1944 ComponentInstance componentInstance = null;
1945 if (!CollectionUtils.isEmpty(component.getComponentInstances())) {
1946 componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstanceId)).findFirst().orElse(null);
1948 return componentInstance;
1951 private Either<User, ResponseFormat> validateUserIgnoreAudit(User modifier, String ecompErrorContext) {
1952 Either<User, ResponseFormat> result = validateUser(modifier, ecompErrorContext, null, null, false);
1953 if (result.isLeft()) {
1954 List<Role> roles = new ArrayList<>();
1955 roles.add(Role.ADMIN);
1956 roles.add(Role.DESIGNER);
1957 Either<Boolean, ResponseFormat> validationRoleRes = validateUserRole(result.left().value(), roles);
1958 if (validationRoleRes.isRight()) {
1959 result = Either.right(validationRoleRes.right().value());
1965 public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String serviceId, List<String> dataParamsToReturn) {
1967 ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
1968 Either<Service, StorageOperationStatus> serviceResultEither = toscaOperationFacade.getToscaElement(serviceId, paramsToRetuen);
1970 if (serviceResultEither.isRight()) {
1971 if(serviceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
1972 log.debug("Failed to found service with id {} ", serviceId);
1973 Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceId));
1976 log.debug("failed to get service by id {} with filters {}", serviceId, dataParamsToReturn.toString());
1977 return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(serviceResultEither.right().value()), ""));
1980 Service service = serviceResultEither.left().value();
1981 UiComponentDataTransfer dataTransfer = UiComponentDataConverter.getUiDataTransferFromServiceByParams(service, dataParamsToReturn);
1982 return Either.left(dataTransfer);