Import VSP top. template handling non SDC model
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / components / impl / ComponentBusinessLogic.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  * Modifications copyright (c) 2019 Nokia
20  * ================================================================================
21  */
22 package org.openecomp.sdc.be.components.impl;
23
24 import fj.data.Either;
25 import java.util.ArrayList;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Map.Entry;
30 import java.util.Optional;
31 import java.util.function.BiFunction;
32 import java.util.function.BooleanSupplier;
33 import java.util.stream.Collectors;
34 import org.apache.commons.collections.CollectionUtils;
35 import org.apache.commons.lang3.StringUtils;
36 import org.apache.commons.lang3.tuple.ImmutablePair;
37 import org.openecomp.sdc.be.catalog.enums.ChangeTypeEnum;
38 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
39 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
40 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
41 import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic;
42 import org.openecomp.sdc.be.components.validation.component.ComponentContactIdValidator;
43 import org.openecomp.sdc.be.components.validation.component.ComponentDescriptionValidator;
44 import org.openecomp.sdc.be.components.validation.component.ComponentIconValidator;
45 import org.openecomp.sdc.be.components.validation.component.ComponentNameValidator;
46 import org.openecomp.sdc.be.components.validation.component.ComponentProjectCodeValidator;
47 import org.openecomp.sdc.be.components.validation.component.ComponentTagsValidator;
48 import org.openecomp.sdc.be.components.validation.component.ComponentValidator;
49 import org.openecomp.sdc.be.config.BeEcompErrorManager;
50 import org.openecomp.sdc.be.config.ConfigurationManager;
51 import org.openecomp.sdc.be.dao.api.ActionStatus;
52 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
53 import org.openecomp.sdc.be.dao.utils.MapUtil;
54 import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
55 import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition;
56 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
57 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
58 import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
59 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
60 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
61 import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
62 import org.openecomp.sdc.be.facade.operations.CatalogOperation;
63 import org.openecomp.sdc.be.impl.ComponentsUtils;
64 import org.openecomp.sdc.be.model.ArtifactDefinition;
65 import org.openecomp.sdc.be.model.AttributeDefinition;
66 import org.openecomp.sdc.be.model.CapReqDef;
67 import org.openecomp.sdc.be.model.Component;
68 import org.openecomp.sdc.be.model.ComponentInstance;
69 import org.openecomp.sdc.be.model.ComponentInstanceInput;
70 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
71 import org.openecomp.sdc.be.model.ComponentParametersView;
72 import org.openecomp.sdc.be.model.DataTypeDefinition;
73 import org.openecomp.sdc.be.model.GroupDefinition;
74 import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement;
75 import org.openecomp.sdc.be.model.InputDefinition;
76 import org.openecomp.sdc.be.model.LifecycleStateEnum;
77 import org.openecomp.sdc.be.model.Operation;
78 import org.openecomp.sdc.be.model.PropertyDefinition;
79 import org.openecomp.sdc.be.model.Resource;
80 import org.openecomp.sdc.be.model.User;
81 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
82 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
83 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
84 import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
85 import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
86 import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
87 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
88 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
89 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
90 import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
91 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
92 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
93 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
94 import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
95 import org.openecomp.sdc.be.user.Role;
96 import org.openecomp.sdc.be.utils.CommonBeUtils;
97 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
98 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
99 import org.openecomp.sdc.common.log.wrappers.Logger;
100 import org.openecomp.sdc.common.util.ValidationUtils;
101 import org.openecomp.sdc.exception.ResponseFormat;
102 import org.springframework.beans.factory.annotation.Autowired;
103
104 public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
105
106     private static final Logger log = Logger.getLogger(ComponentBusinessLogic.class.getName());
107     protected final GroupBusinessLogic groupBusinessLogic;
108     protected ArtifactsBusinessLogic artifactsBusinessLogic;
109     protected GenericTypeBusinessLogic genericTypeBusinessLogic;
110     protected ComponentDescriptionValidator componentDescriptionValidator;
111     protected ComponentProjectCodeValidator componentProjectCodeValidator;
112     protected CatalogOperation catalogOperations;
113     protected ComponentIconValidator componentIconValidator;
114     protected ComponentTagsValidator componentTagsValidator;
115     protected ComponentNameValidator componentNameValidator;
116     protected ComponentContactIdValidator componentContactIdValidator;
117
118     public ComponentBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
119                                   IGroupTypeOperation groupTypeOperation, GroupBusinessLogic groupBusinessLogic,
120                                   InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
121                                   ArtifactsBusinessLogic artifactsBusinessLogic, ArtifactsOperations artifactToscaOperation,
122                                   ComponentContactIdValidator componentContactIdValidator, ComponentNameValidator componentNameValidator,
123                                   ComponentTagsValidator componentTagsValidator, ComponentValidator componentValidator,
124                                   ComponentIconValidator componentIconValidator, ComponentProjectCodeValidator componentProjectCodeValidator,
125                                   ComponentDescriptionValidator componentDescriptionValidator) {
126         super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
127             artifactToscaOperation);
128         this.artifactsBusinessLogic = artifactsBusinessLogic;
129         this.groupBusinessLogic = groupBusinessLogic;
130         this.componentContactIdValidator = componentContactIdValidator;
131         this.componentNameValidator = componentNameValidator;
132         this.componentTagsValidator = componentTagsValidator;
133         this.componentIconValidator = componentIconValidator;
134         this.componentProjectCodeValidator = componentProjectCodeValidator;
135         this.componentDescriptionValidator = componentDescriptionValidator;
136     }
137
138     private static Either<ArtifactDefinition, Operation> saveToscaArtifactAndPopulateToscaArtifactsWithResult(Component component,
139                                                                                                               final ComponentsUtils componentsUtils,
140                                                                                                               final ArtifactTypeEnum artifactEnum,
141                                                                                                               final BiFunction<Component, ArtifactDefinition, Either<ArtifactDefinition, Operation>> saveToscaArtifactPayloadFunction) {
142         ArtifactDefinition artifactDefinition = getToscaArtifactByTypeOrThrowException(component, artifactEnum, componentsUtils);
143         Either<ArtifactDefinition, Operation> result = saveToscaArtifactPayloadFunction.apply(component, artifactDefinition);
144         if (result.isLeft()) {
145             ArtifactDefinition def = result.left().value();
146             component.getToscaArtifacts().put(def.getArtifactLabel(), def);
147         }
148         return result;
149     }
150
151     private static Optional<ArtifactDefinition> getToscaArtifactByType(final Map<String, ArtifactDefinition> toscaArtifacts,
152                                                                        final ArtifactTypeEnum typeEnum) {
153         return toscaArtifacts.values().stream().filter(p -> p.getArtifactType().equals(typeEnum.getType())).findAny();
154     }
155
156     private static ArtifactDefinition getToscaArtifactByTypeOrThrowException(final Component component, final ArtifactTypeEnum typeEnum,
157                                                                              final ComponentsUtils componentsUtils) {
158         return Optional.ofNullable(component.getToscaArtifacts()).flatMap(toscaArtifacts -> getToscaArtifactByType(toscaArtifacts, typeEnum))
159             .orElseThrow(() -> {
160                 log.debug("Impossible to find a ToscaArtifact with type '{}' for {}", typeEnum.getType(), component);
161                 return new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, typeEnum.name()));
162             });
163     }
164
165     public void setComponentDescriptionValidator(ComponentDescriptionValidator componentDescriptionValidator) {
166         this.componentDescriptionValidator = componentDescriptionValidator;
167     }
168
169     public void setComponentProjectCodeValidator(ComponentProjectCodeValidator componentProjectCodeValidator) {
170         this.componentProjectCodeValidator = componentProjectCodeValidator;
171     }
172
173     public void setComponentIconValidator(ComponentIconValidator componentIconValidator) {
174         this.componentIconValidator = componentIconValidator;
175     }
176
177     public void setComponentContactIdValidator(ComponentContactIdValidator componentContactIdValidator) {
178         this.componentContactIdValidator = componentContactIdValidator;
179     }
180
181     public void setComponentTagsValidator(ComponentTagsValidator componentTagsValidator) {
182         this.componentTagsValidator = componentTagsValidator;
183     }
184
185     public void setComponentNameValidator(ComponentNameValidator componentNameValidator) {
186         this.componentNameValidator = componentNameValidator;
187     }
188
189     @Autowired
190     public void setGenericTypeBusinessLogic(GenericTypeBusinessLogic genericTypeBusinessLogic) {
191         this.genericTypeBusinessLogic = genericTypeBusinessLogic;
192     }
193
194     public abstract Either<List<String>, ResponseFormat> deleteMarkedComponents();
195
196     public abstract ComponentInstanceBusinessLogic getComponentInstanceBL();
197
198     public abstract Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId,
199                                                                                                                        String userId);
200
201     /**
202      * @param componentId
203      * @param dataParamsToReturn
204      * @return
205      */
206     public abstract Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String componentId,
207                                                                                                             List<String> dataParamsToReturn);
208
209     User validateUser(User user, String ecompErrorContext, Component component, AuditingActionEnum auditAction, boolean inTransaction) {
210         User validatedUser;
211         ResponseFormat responseFormat;
212         try {
213             validateUserNotEmpty(user, ecompErrorContext);
214             validatedUser = validateUserExists(user);
215         } catch (ByActionStatusComponentException e) {
216             if (e.getActionStatus() == ActionStatus.MISSING_INFORMATION) {
217                 user.setUserId("UNKNOWN");
218             }
219             responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
220             componentsUtils.auditComponentAdmin(responseFormat, user, component, auditAction, component.getComponentType());
221             throw e;
222         } catch (ByResponseFormatComponentException e) {
223             responseFormat = e.getResponseFormat();
224             componentsUtils.auditComponentAdmin(responseFormat, user, component, auditAction, component.getComponentType());
225             throw e;
226         }
227         return validatedUser;
228     }
229
230     protected void validateUserRole(User user, Component component, List<Role> roles, AuditingActionEnum auditAction, String comment) {
231         if (roles != null && roles.isEmpty()) {
232             roles.add(Role.ADMIN);
233             roles.add(Role.DESIGNER);
234         }
235         try {
236             validateUserRole(user, roles);
237         } catch (ByActionStatusComponentException e) {
238             ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
239             handleComponentException(component, comment, responseFormat, user, auditAction);
240             throw e;
241         } catch (ByResponseFormatComponentException e) {
242             ResponseFormat responseFormat = e.getResponseFormat();
243             handleComponentException(component, comment, responseFormat, user, auditAction);
244             throw e;
245         }
246     }
247
248     private void handleComponentException(Component component, String comment, ResponseFormat responseFormat, User user,
249                                           AuditingActionEnum auditAction) {
250         String commentStr = null;
251         String distrStatus = null;
252         ComponentTypeEnum componentType = component.getComponentType();
253         if (componentType == ComponentTypeEnum.SERVICE) {
254             distrStatus = ((ServiceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition())
255                 .getDistributionStatus();
256             commentStr = comment;
257         }
258         componentsUtils.auditComponent(responseFormat, user, component, auditAction, new ResourceCommonInfo(componentType.getValue()),
259             ResourceVersionInfo.newBuilder().distributionStatus(distrStatus).build(),
260             ResourceVersionInfo.newBuilder().distributionStatus(distrStatus).build(), commentStr, null, null);
261     }
262
263     public Either<Boolean, ResponseFormat> validateConformanceLevel(String componentUuid, ComponentTypeEnum componentTypeEnum, String userId) {
264         log.trace("validate conformance level");
265         if (componentTypeEnum != ComponentTypeEnum.SERVICE) {
266             log.error("conformance level validation for non service component, id {}", componentUuid);
267             ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
268             return Either.right(errorResponse);
269         }
270         validateUserExists(userId);
271         Either<ComponentMetadataData, StorageOperationStatus> eitherComponent = toscaOperationFacade
272             .getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, null);
273         if (eitherComponent.isRight()) {
274             log.error("can't validate conformance level, component not found, uuid {}", componentUuid);
275             BeEcompErrorManager.getInstance().logBeComponentMissingError("validateConformanceLevel", componentTypeEnum.getValue(), componentUuid);
276             StorageOperationStatus status = eitherComponent.right().value();
277             ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(status, componentTypeEnum);
278             ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus);
279             return Either.right(responseFormat);
280         }
281         String componentConformanceLevel = eitherComponent.left().value().getMetadataDataDefinition().getConformanceLevel();
282         if (StringUtils.isBlank(componentConformanceLevel)) {
283             log.error("component conformance level property is null or empty, uuid {}", componentUuid);
284             ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
285             return Either.right(errorResponse);
286         }
287         String configConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getMinToscaConformanceLevel();
288         Boolean result = true;
289         if (CommonBeUtils.conformanceLevelCompare(componentConformanceLevel, configConformanceLevel) < 0) {
290             log.error("invalid asset conformance level, uuid {}, asset conformanceLevel {}, config conformanceLevel {}", componentUuid,
291                 componentConformanceLevel, configConformanceLevel);
292             result = false;
293         }
294         log.trace("conformance level validation finished");
295         return Either.left(result);
296     }
297
298     protected void validateIcon(User user, Component component, AuditingActionEnum actionEnum) {
299         log.debug("validate Icon");
300         ComponentTypeEnum type = component.getComponentType();
301         String icon = component.getIcon();
302         if (!ValidationUtils.validateStringNotEmpty(icon)) {
303             log.info("icon is missing.");
304             ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_ICON, type.getValue());
305             componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type);
306             throw new ComponentException(ActionStatus.COMPONENT_MISSING_ICON, type.getValue());
307         }
308         try {
309             validateIcon(icon, type);
310         } catch (ComponentException e) {
311             ResponseFormat responseFormat =
312                 e.getResponseFormat() != null ? e.getResponseFormat() : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
313             componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, type);
314             throw e;
315         }
316     }
317
318     private void validateIcon(String icon, ComponentTypeEnum type) {
319         if (icon != null) {
320             if (!ValidationUtils.validateIconLength(icon)) {
321                 log.debug("icon exceeds max length");
322                 throw new ComponentException(ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH);
323             }
324             if (!ValidationUtils.validateIcon(icon)) {
325                 log.info("icon is invalid.");
326                 throw new ComponentException(ActionStatus.COMPONENT_INVALID_ICON, type.getValue());
327             }
328         }
329     }
330
331     protected void checkComponentFieldsForOverrideAttempt(Component component) {
332         if (component.getLifecycleState() != null) {
333             log.info("LifecycleState cannot be defined by user. This field will be overridden by the application");
334         }
335         if (component.getVersion() != null) {
336             log.info("Version cannot be defined by user. This field will be overridden by the application");
337         }
338         if (component.getCreatorUserId() != null || component.getCreatorFullName() != null) {
339             log.info("Creator cannot be defined by user. This field will be overridden by the application");
340         }
341         if (component.getLastUpdaterUserId() != null || component.getLastUpdaterFullName() != null) {
342             log.info("Last Updater cannot be defined by user. This field will be overridden by the application");
343         }
344         if (component.getCreationDate() != null) {
345             log.info("Creation Date cannot be defined by user. This field will be overridden by the application");
346         }
347         if (component.isHighestVersion() != null) {
348             log.info("Is Highest Version cannot be defined by user. This field will be overridden by the application");
349         }
350         if (component.getUUID() != null) {
351             log.info("UUID cannot be defined by user. This field will be overridden by the application");
352         }
353         if (component.getLastUpdateDate() != null) {
354             log.info("Last Update Date cannot be defined by user. This field will be overridden by the application");
355         }
356         if (component.getUniqueId() != null) {
357             log.info("uid cannot be defined by user. This field will be overridden by the application.");
358             component.setUniqueId(null);
359         }
360         if (component.getInvariantUUID() != null) {
361             log.info("Invariant UUID cannot be defined by user. This field will be overridden by the application.");
362         }
363     }
364
365     protected void validateComponentFieldsBeforeCreate(User user, Component component, AuditingActionEnum actionEnum) {
366         // validate component name uniqueness
367         log.debug("validate component name ");
368         componentNameValidator.validateAndCorrectField(user, component, actionEnum);
369         // validate description
370         log.debug("validate description");
371         componentDescriptionValidator.validateAndCorrectField(user, component, actionEnum);
372         // validate tags
373         log.debug("validate tags");
374         componentTagsValidator.validateAndCorrectField(user, component, actionEnum);
375         // validate contact info
376         log.debug("validate contact info");
377         componentContactIdValidator.validateAndCorrectField(user, component, actionEnum);
378         // validate icon
379         log.debug("validate icon");
380         validateIcon(user, component, actionEnum);
381     }
382
383     public CapReqDef getRequirementsAndCapabilities(String componentId, ComponentTypeEnum componentTypeEnum, String userId) {
384         validateUserExists(userId);
385         ComponentParametersView filter = new ComponentParametersView(true);
386         filter.setIgnoreCapabilities(false);
387         filter.setIgnoreRequirements(false);
388         filter.setIgnoreComponentInstances(false);
389         try {
390             Component component = validateComponentExists(componentId, componentTypeEnum, filter);
391             return new CapReqDef(component.getRequirements(), component.getCapabilities());
392         } catch (ComponentException e) {
393             BeEcompErrorManager.getInstance().logBeComponentMissingError("getRequirementsAndCapabilities", componentTypeEnum.getValue(), componentId);
394             throwComponentException(e.getResponseFormat());
395         }
396         return null;
397     }
398
399     public Either<List<Component>, ResponseFormat> getLatestVersionNotAbstractComponents(boolean isAbstractAbstract,
400                                                                                          ComponentTypeEnum componentTypeEnum,
401                                                                                          String internalComponentType, List<String> componentUids,
402                                                                                          String userId) {
403         try {
404             validateUserExists(userId);
405             List<Component> result = new ArrayList<>();
406             List<String> componentsUidToFetch = new ArrayList<>();
407             componentsUidToFetch.addAll(componentUids);
408             if (!componentsUidToFetch.isEmpty()) {
409                 log.debug("Number of Components to fetch from graph is {}", componentsUidToFetch.size());
410                 Either<List<Component>, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade
411                     .getLatestVersionNotAbstractComponents(isAbstractAbstract, componentTypeEnum, internalComponentType, componentsUidToFetch);
412                 if (nonCheckoutCompResponse.isLeft()) {
413                     log.debug("Retrived Resource successfully.");
414                     result.addAll(nonCheckoutCompResponse.left().value());
415                 } else {
416                     return Either.right(
417                         componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value())));
418                 }
419             }
420             return Either.left(result);
421         } finally {
422             janusGraphDao.commit();
423         }
424     }
425
426     public Either<List<Component>, ResponseFormat> getLatestVersionNotAbstractComponentsMetadata(boolean isAbstractAbstract,
427                                                                                                  HighestFilterEnum highestFilter,
428                                                                                                  ComponentTypeEnum componentTypeEnum,
429                                                                                                  String internalComponentType, String userId,
430                                                                                                  String modelName) {
431         Either<List<Component>, StorageOperationStatus> nonCheckoutCompResponse = null;
432         try {
433             validateUserExists(userId);
434            nonCheckoutCompResponse = toscaOperationFacade
435                 .getLatestVersionNotAbstractMetadataOnly(isAbstractAbstract, componentTypeEnum, internalComponentType, modelName);
436             if (nonCheckoutCompResponse.isLeft()) {
437                 log.debug("Retrieved Resource successfully.");
438                 return Either.left(nonCheckoutCompResponse.left().value());
439             }
440             return Either
441                 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value())));
442         } finally {
443             if(nonCheckoutCompResponse != null && nonCheckoutCompResponse.isLeft() ) {
444                 janusGraphDao.commit();
445             }
446         }
447     }
448
449     public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
450     }
451
452     @SuppressWarnings("unchecked")
453     public void setToscaArtifactsPlaceHolders(Component component, User user) {
454         Map<String, ArtifactDefinition> artifactMap = component.getToscaArtifacts();
455         if (artifactMap == null) {
456             artifactMap = new HashMap<>();
457         }
458         String componentUniqueId = component.getUniqueId();
459         String componentSystemName = component.getSystemName();
460         String componentType = component.getComponentType().getValue().toLowerCase();
461         Map<String, Object> toscaArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts();
462         if (toscaArtifacts != null) {
463             for (Entry<String, Object> artifactInfoMap : toscaArtifacts.entrySet()) {
464                 Map<String, Object> artifactInfo = (Map<String, Object>) artifactInfoMap.getValue();
465                 ArtifactDefinition artifactDefinition = artifactsBusinessLogic
466                     .createArtifactPlaceHolderInfo(componentUniqueId, artifactInfoMap.getKey(), artifactInfo, user, ArtifactGroupTypeEnum.TOSCA);
467                 artifactDefinition
468                     .setArtifactName(ValidationUtils.normalizeFileName(componentType + "-" + componentSystemName + artifactInfo.get("artifactName")));
469                 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
470             }
471         }
472         component.setToscaArtifacts(artifactMap);
473     }
474
475     public Either<ArtifactDefinition, Operation> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest,
476                                                                         boolean inTransaction, boolean shouldLock) {
477         return populateToscaArtifacts(component, user, isInCertificationRequest, inTransaction, shouldLock, true, true);
478     }
479
480     public Either<ArtifactDefinition, Operation> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest,
481                                                                         boolean inTransaction, boolean shouldLock, boolean retrieveResource) {
482         return populateToscaArtifacts(component, user, isInCertificationRequest, inTransaction, shouldLock, true, retrieveResource);
483     }
484
485     private Either<ArtifactDefinition, Operation> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest,
486                                                                          boolean inTransaction, boolean shouldLock, boolean fetchTemplatesFromDB,
487                                                                          boolean retrieveResource) {
488         if (retrieveResource) {
489             Either<Component, StorageOperationStatus> toscaElement = toscaOperationFacade.getToscaFullElement(component.getUniqueId());
490             if (toscaElement.isRight()) {
491                 throw new ByActionStatusComponentException(
492                     componentsUtils.convertFromStorageResponse(toscaElement.right().value(), component.getComponentType()));
493             }
494             component = toscaElement.left().value();
495         }
496         Either<ArtifactDefinition, Operation> generateToscaRes = saveToscaArtifactAndPopulateToscaArtifactsWithResult(component, componentsUtils,
497             ArtifactTypeEnum.TOSCA_TEMPLATE,
498             (comp, toscaArtifact) -> saveToscaArtifactPayload(toscaArtifact, comp, user, isInCertificationRequest, shouldLock, inTransaction,
499                 fetchTemplatesFromDB));
500         if (!isAbstractResource(component)) {
501             generateToscaRes = saveToscaArtifactAndPopulateToscaArtifactsWithResult(component, componentsUtils, ArtifactTypeEnum.TOSCA_CSAR,
502                 (comp, toscaArtifactArg) -> saveToscaArtifactPayload(toscaArtifactArg, comp, user, isInCertificationRequest, shouldLock,
503                     inTransaction, true));
504         }
505         return generateToscaRes;
506     }
507
508     private boolean isAbstractResource(Component component) {
509         return component.getComponentType() == ComponentTypeEnum.RESOURCE && ((Resource) component).isAbstract();
510     }
511
512     private Either<ArtifactDefinition, Operation> saveToscaArtifactPayload(ArtifactDefinition artifactDefinition,
513                                                                            org.openecomp.sdc.be.model.Component component, User user,
514                                                                            boolean isInCertificationRequest, boolean shouldLock,
515                                                                            boolean inTransaction, boolean fetchTemplatesFromDB) {
516         return artifactsBusinessLogic
517             .generateAndSaveToscaArtifact(artifactDefinition, component, user, isInCertificationRequest, shouldLock, inTransaction,
518                 fetchTemplatesFromDB);
519     }
520
521     public ImmutablePair<String, byte[]> getToscaModelByComponentUuid(ComponentTypeEnum componentType, String uuid,
522                                                                       ResourceCommonInfo resourceCommonInfo) {
523         Either<List<Component>, StorageOperationStatus> latestVersionEither = toscaOperationFacade.getComponentListByUuid(uuid, null);
524         if (latestVersionEither.isRight()) {
525             throw new ByActionStatusComponentException(
526                 componentsUtils.convertFromStorageResponse(latestVersionEither.right().value(), componentType));
527         }
528         List<Component> components = latestVersionEither.left().value();
529         Component component = components.stream().filter(Component::isHighestVersion).findFirst().orElse(null);
530         if (component == null) {
531             component = components.stream().filter(c -> c.getLifecycleState() == LifecycleStateEnum.CERTIFIED).findFirst().orElse(null);
532         }
533         if (component == null) {
534             throw new ByResponseFormatComponentException(
535                 componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, componentType)));
536         }
537         resourceCommonInfo.setResourceName(component.getName());
538         // TODO remove after migration - handle artifact not found(no
539
540         // placeholder)
541         if (null == component.getToscaArtifacts() || component.getToscaArtifacts().isEmpty()) {
542             throw new ByResponseFormatComponentException(
543                 componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ArtifactTypeEnum.TOSCA_CSAR.name()));
544         }
545         ArtifactDefinition csarArtifact = component.getToscaArtifacts().values().stream()
546             .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())).findAny().get();
547         return artifactsBusinessLogic.handleDownloadToscaModelRequest(component, csarArtifact);
548     }
549
550     protected StorageOperationStatus markComponentToDelete(Component component) {
551         ComponentTypeEnum componentType = component.getComponentType();
552         String uniqueId = component.getUniqueId();
553         if (Boolean.TRUE.equals(component.getIsDeleted())) {
554             log.info("component {} already marked as deleted. id= {}, type={}", component.getName(), uniqueId, componentType);
555             return StorageOperationStatus.NOT_FOUND;
556         }
557         StorageOperationStatus markResourceToDelete = toscaOperationFacade.markComponentToDelete(component);
558         if (StorageOperationStatus.OK != markResourceToDelete) {
559             log.debug("failed to mark component {} of type {} for delete. error = {}", uniqueId, componentType, markResourceToDelete);
560             return markResourceToDelete;
561         } else {
562             log.debug("Component {}  of type {} was marked as deleted", uniqueId, componentType);
563             updateCatalog(component, ChangeTypeEnum.DELETE);
564             return StorageOperationStatus.OK;
565         }
566     }
567
568     public Either<Boolean, ResponseFormat> validateAndUpdateDescription(User user, Component currentComponent, Component updatedComponent,
569                                                                         AuditingActionEnum auditingAction) {
570         String descriptionUpdated = updatedComponent.getDescription();
571         String descriptionCurrent = currentComponent.getDescription();
572         if (descriptionUpdated != null && !descriptionCurrent.equals(descriptionUpdated)) {
573             componentDescriptionValidator.validateAndCorrectField(user, updatedComponent, auditingAction);
574             currentComponent.setDescription(updatedComponent.getDescription());
575         }
576         return Either.left(true);
577     }
578
579     public Either<Boolean, ResponseFormat> validateAndUpdateProjectCode(User user, Component currentComponent, Component updatedComponent) {
580         String projectCodeUpdated = updatedComponent.getProjectCode();
581         String projectCodeCurrent = currentComponent.getProjectCode();
582         if (projectCodeUpdated != null && !projectCodeCurrent.equals(projectCodeUpdated)) {
583             try {
584                 componentProjectCodeValidator.validateAndCorrectField(user, updatedComponent, null);
585             } catch (ComponentException exp) {
586                 ResponseFormat errorRespons = exp.getResponseFormat();
587                 return Either.right(errorRespons);
588             }
589             currentComponent.setProjectCode(updatedComponent.getProjectCode());
590         }
591         return Either.left(true);
592     }
593
594     public Either<Boolean, ResponseFormat> validateAndUpdateIcon(User user, Component currentComponent, Component updatedComponent,
595                                                                  boolean hasBeenCertified) {
596         String iconUpdated = updatedComponent.getIcon();
597         String iconCurrent = currentComponent.getIcon();
598         if (iconUpdated != null && !iconCurrent.equals(iconUpdated)) {
599             if (!hasBeenCertified) {
600                 componentIconValidator.validateAndCorrectField(user, updatedComponent, null);
601                 currentComponent.setIcon(updatedComponent.getIcon());
602             } else {
603                 log.info("icon {} cannot be updated once the component has been certified once.", iconUpdated);
604                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_PARAMETER_CANNOT_BE_CHANGED, "Icon",
605                     currentComponent.getComponentType().name().toLowerCase());
606                 return Either.right(errorResponse);
607             }
608         }
609         return Either.left(true);
610     }
611
612     protected Either<List<String>, ResponseFormat> deleteMarkedComponents(ComponentTypeEnum componentType) {
613         log.trace("start deleteMarkedComponents");
614         Either<List<String>, StorageOperationStatus> deleteMarkedElements = toscaOperationFacade.deleteMarkedElements(componentType);
615         if (deleteMarkedElements.isRight()) {
616             janusGraphDao.rollback();
617             ResponseFormat responseFormat = componentsUtils
618                 .getResponseFormat(componentsUtils.convertFromStorageResponse(deleteMarkedElements.right().value(), componentType));
619             return Either.right(responseFormat);
620         }
621         log.trace("end deleteMarkedComponents");
622         janusGraphDao.commit();
623         return Either.left(deleteMarkedElements.left().value());
624     }
625
626     public Either<List<ArtifactDefinition>, StorageOperationStatus> getComponentArtifactsForDelete(String parentId, NodeTypeEnum parentType) {
627         List<ArtifactDefinition> artifacts = new ArrayList<>();
628         Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsResponse = artifactToscaOperation.getArtifacts(parentId);
629         if (artifactsResponse.isRight()) {
630             if (artifactsResponse.right().value() != StorageOperationStatus.NOT_FOUND) {
631                 log.debug("failed to retrieve artifacts for {} {}", parentType, parentId);
632                 return Either.right(artifactsResponse.right().value());
633             }
634         } else {
635             artifacts.addAll(artifactsResponse.left().value().values());
636         }
637         return Either.left(artifacts);
638     }
639
640     /**
641      * @param componentId
642      * @param user
643      * @param dataParamsToReturn - ui list of params to return
644      * @return
645      */
646     public Either<UiComponentDataTransfer, ResponseFormat> getComponentDataFilteredByParams(String componentId, User user,
647                                                                                             List<String> dataParamsToReturn) {
648         if (user != null) {
649             validateUserExists(user);
650         }
651         UiComponentDataTransfer result = new UiComponentDataTransfer();
652         if (dataParamsToReturn == null || dataParamsToReturn.isEmpty()) {
653             Either.left(result);
654         } else {
655             Either<UiComponentDataTransfer, ResponseFormat> uiDataTransferEither = getUiComponentDataTransferByComponentId(componentId,
656                 dataParamsToReturn);
657             if (uiDataTransferEither.isRight()) {
658                 return Either.right(uiDataTransferEither.right().value());
659             }
660             result = uiDataTransferEither.left().value();
661         }
662         return Either.left(result);
663     }
664
665     protected <T extends Component> void generateAndAddInputsFromGenericTypeProperties(T component, Resource genericType) {
666         List<InputDefinition> genericAndComponentInputs = new ArrayList<>();
667         List<InputDefinition> genericInputs = genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericType);
668         genericAndComponentInputs.addAll(genericInputs);
669         if (null != component.getInputs()) {
670             List<InputDefinition> nonGenericInputsFromComponent = getAllNonGenericInputsFromComponent(genericInputs, component.getInputs());
671             genericAndComponentInputs.addAll(nonGenericInputsFromComponent);
672         }
673         component.setInputs(genericAndComponentInputs);
674     }
675
676     private List<InputDefinition> getAllNonGenericInputsFromComponent(List<InputDefinition> genericInputs, List<InputDefinition> componentInputs) {
677         if (genericInputs == null) {
678             return componentInputs;
679         }
680         Map<String, InputDefinition> inputByNameMap = MapUtil.toMap(genericInputs, InputDefinition::getName);
681         List<InputDefinition> componentNonGenericInputs = new ArrayList<>();
682         componentInputs.stream().forEach(input -> {
683             if (!inputByNameMap.containsKey(input.getName())) {
684                 componentNonGenericInputs.add(input);
685             }
686         });
687         return componentNonGenericInputs;
688     }
689     
690     protected void generatePropertiesFromGenericType(final Component component, final Resource genericType) {
691         if (CollectionUtils.isEmpty(genericType.getProperties())) {
692             return;
693         }
694         final List<PropertyDefinition> genericTypePropertyList = genericType.getProperties().stream().map(PropertyDefinition::new)
695             .peek(propertyDefinition -> propertyDefinition.setUniqueId(null)).collect(Collectors.toList());
696         if (component.getProperties() == null) {
697             component.setProperties(new ArrayList<>(genericTypePropertyList));
698         } else {
699             List<PropertyDefinition> servicePropertyList = component.getProperties();
700             genericTypePropertyList.stream()
701                 .filter(property -> servicePropertyList.stream().noneMatch(property1 -> property1.getName().equals(property.getName())))
702                 .forEach(servicePropertyList::add);
703         }
704         component.getProperties().forEach(propertyDefinition -> propertyDefinition.setUniqueId(null));
705     }
706     protected <T extends Component> Resource fetchAndSetDerivedFromGenericType(final T component) {
707         return fetchAndSetDerivedFromGenericType(component, null);
708     }
709
710     protected <T extends Component> Resource fetchAndSetDerivedFromGenericType(final T component, final String toscaType) {
711         final Either<Resource, ResponseFormat> genericTypeEither = this.genericTypeBusinessLogic.fetchDerivedFromGenericType(component, toscaType);
712         if (genericTypeEither.isRight()) {
713             log.debug("Failed to fetch latest generic type for component {} of type", component.getName(), component.assetType());
714             throw new ByActionStatusComponentException(ActionStatus.GENERIC_TYPE_NOT_FOUND, component.assetType());
715         }
716         final Resource genericTypeResource = genericTypeEither.left().value();
717         component.setDerivedFromGenericInfo(genericTypeResource);
718         return genericTypeResource;
719     }
720
721     public Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> getFilteredComponentInstanceProperties(String componentId,
722                                                                                                                                 Map<FilterKeyEnum, List<String>> filters,
723                                                                                                                                 String userId) {
724         Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> response = null;
725         Either<Component, StorageOperationStatus> getResourceRes = null;
726         try {
727             if (!filters.containsKey(FilterKeyEnum.NAME_FRAGMENT) && StringUtils.isEmpty(filters.get(FilterKeyEnum.NAME_FRAGMENT).get(0))) {
728                 response = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
729             }
730             if (userId != null && response == null) {
731                 validateUserExists(userId);
732             }
733             if (response == null) {
734                 getResourceRes = toscaOperationFacade.getToscaElement(componentId);
735                 if (getResourceRes.isRight()) {
736                     response = Either
737                         .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getResourceRes.right().value())));
738                 }
739             }
740             if (response == null) {
741                 response = getFilteredComponentInstancesProperties(getResourceRes.left().value(), filters);
742             }
743         } catch (Exception e) {
744             log.debug("The exception {} occured during filtered instance properties fetching. the  containing component is {}. ", e, componentId);
745             response = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
746         } finally {
747             if (response != null && response.isLeft()) {
748                 toscaOperationFacade.commit();
749             } else {
750                 toscaOperationFacade.rollback();
751             }
752         }
753         return response;
754     }
755
756     private Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> getFilteredComponentInstancesProperties(Component component,
757                                                                                                                                   Map<FilterKeyEnum, List<String>> filters) {
758         Map<String, List<IComponentInstanceConnectedElement>> filteredProperties = new HashMap<>();
759         Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> result = Either.left(filteredProperties);
760         List<ComponentInstance> filteredInstances = getFilteredInstances(component, filters.get(FilterKeyEnum.RESOURCE_TYPE));
761         String propertyNameFragment = filters.get(FilterKeyEnum.NAME_FRAGMENT).get(0);
762         boolean searchByFragment = propertyNameFragment.length() > 3;
763         if (CollectionUtils.isNotEmpty(filteredInstances)) {
764             for (ComponentInstance instance : filteredInstances) {
765                 if (component.getComponentInstancesProperties() != null && component.getComponentInstancesProperties()
766                     .containsKey(instance.getUniqueId())) {
767                     List<IComponentInstanceConnectedElement> currProperties = getFilteredComponentInstanceProperties(
768                         component.getComponentInstancesProperties().get(instance.getUniqueId()), propertyNameFragment, searchByFragment);
769                     setFilteredProperties(filteredProperties, instance, currProperties);
770                 }
771                 if (component.getComponentInstancesInputs() != null && component.getComponentInstancesInputs().containsKey(instance.getUniqueId())) {
772                     List<IComponentInstanceConnectedElement> currInputs = getFilteredComponentInstanceInputs(
773                         component.getComponentInstancesInputs().get(instance.getUniqueId()), propertyNameFragment, searchByFragment);
774                     if (CollectionUtils.isNotEmpty(currInputs)) {
775                         checkFilteredProperties(filteredProperties, instance, currInputs);
776                     }
777                 }
778             }
779         }
780         return result;
781     }
782
783     private void setFilteredProperties(Map<String, List<IComponentInstanceConnectedElement>> filteredProperties, ComponentInstance instance,
784                                        List<IComponentInstanceConnectedElement> currProperties) {
785         if (CollectionUtils.isNotEmpty(currProperties)) {
786             filteredProperties.put(instance.getUniqueId(), currProperties);
787         }
788     }
789
790     private void checkFilteredProperties(Map<String, List<IComponentInstanceConnectedElement>> filteredProperties, ComponentInstance instance,
791                                          List<IComponentInstanceConnectedElement> currInputs) {
792         if (filteredProperties.get(instance.getUniqueId()) != null) {
793             filteredProperties.get(instance.getUniqueId()).addAll(currInputs);
794         } else {
795             filteredProperties.put(instance.getUniqueId(), currInputs);
796         }
797     }
798
799     private List<IComponentInstanceConnectedElement> getFilteredComponentInstanceInputs(List<ComponentInstanceInput> inputs,
800                                                                                         String propertyNameFragment, boolean searchByFragment) {
801         return inputs.stream().filter(i -> isMatchingInput(i, propertyNameFragment, searchByFragment)).collect(Collectors.toList());
802     }
803
804     private List<IComponentInstanceConnectedElement> getFilteredComponentInstanceProperties(List<ComponentInstanceProperty> instanceProperties,
805                                                                                             String propertyNameFragment, boolean searchByFragment) {
806         return instanceProperties.stream().filter(p -> isMatchingProperty(p, propertyNameFragment, searchByFragment)).collect(Collectors.toList());
807     }
808
809     private boolean isMatchingInput(ComponentInstanceInput input, String propertyNameFragment, boolean searchByFragment) {
810         boolean isMatching = false;
811         if (searchByFragment && input.getName().toLowerCase().contains(propertyNameFragment)) {
812             isMatching = true;
813         }
814         if (!searchByFragment && input.getName().equalsIgnoreCase(propertyNameFragment)) {
815             isMatching = true;
816         }
817         return isMatching;
818     }
819
820     private boolean isMatchingProperty(ComponentInstanceProperty property, String propertyNameFragment, boolean searchByFragment) {
821         boolean isMatching = false;
822         if (searchByFragment && property.getName().toLowerCase().contains(propertyNameFragment)) {
823             isMatching = true;
824         }
825         if (!searchByFragment && property.getName().equalsIgnoreCase(propertyNameFragment)) {
826             isMatching = true;
827         }
828         if (!isMatching && !ToscaPropertyType.isPrimitiveType(property.getType())) {
829             isMatching = isMatchingComplexPropertyByRecursively(property, propertyNameFragment, searchByFragment);
830         }
831         return isMatching;
832     }
833
834     private boolean isMatchingComplexPropertyByRecursively(PropertyDataDefinition property, String propertyNameFragment, boolean searchByFragment) {
835         String propertyType;
836         List<PropertyDefinition> dataTypeProperties;
837         DataTypeDefinition currentProperty;
838         if (searchByFragment && property.getName().toLowerCase().contains(propertyNameFragment.toLowerCase())) {
839             return true;
840         }
841         if (!searchByFragment && property.getName().equalsIgnoreCase(propertyNameFragment)) {
842             return true;
843         }
844         propertyType = isEmptyInnerType(property) ? property.getType() : property.getSchema().getProperty().getType();
845         if (ToscaPropertyType.isScalarType(propertyType)) {
846             return false;
847         }
848         Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByNameRes = propertyOperation.getDataTypeByName(propertyType, null);
849         if (getDataTypeByNameRes.isRight()) {
850             return false;
851         }
852         currentProperty = getDataTypeByNameRes.left().value();
853         dataTypeProperties = currentProperty.getProperties();
854         boolean dataPropertiesNotNull = CollectionUtils.isNotEmpty(dataTypeProperties);
855         BooleanSupplier dataMatchesComplexProperty = () -> isMatchingComplexProperty(propertyNameFragment, searchByFragment, dataTypeProperties);
856         BooleanSupplier parentPropertiesNotNull = () -> CollectionUtils.isNotEmpty(currentProperty.getDerivedFrom().getProperties());
857         BooleanSupplier parentDataMatchesComplexProperty = () -> isMatchingComplexProperty(propertyNameFragment, searchByFragment,
858             currentProperty.getDerivedFrom().getProperties());
859         return ((dataPropertiesNotNull && dataMatchesComplexProperty.getAsBoolean()) || (parentPropertiesNotNull.getAsBoolean()
860             && parentDataMatchesComplexProperty.getAsBoolean()));
861     }
862
863     private boolean isMatchingComplexProperty(String propertyNameFragment, boolean searchByFragment, List<PropertyDefinition> dataTypeProperties) {
864         for (PropertyDefinition prop : dataTypeProperties) {
865             if (isMatchingComplexPropertyByRecursively(prop, propertyNameFragment, searchByFragment)) {
866                 return true;
867             }
868         }
869         return false;
870     }
871
872     private boolean isEmptyInnerType(PropertyDataDefinition property) {
873         return property == null || property.getSchema() == null || property.getSchema().getProperty() == null
874             || property.getSchema().getProperty().getType() == null;
875     }
876
877     public Either<Boolean, ResponseFormat> shouldUpgradeToLatestGeneric(Component clonedComponent) {
878         if (!clonedComponent.deriveFromGeneric() || StringUtils.isNotEmpty(clonedComponent.getModel())) {
879             return Either.left(false);
880         }
881         Boolean shouldUpgrade = false;
882         String currentGenericType = clonedComponent.getDerivedFromGenericType();
883         String currentGenericVersion = clonedComponent.getDerivedFromGenericVersion();
884         Resource genericTypeResource = fetchAndSetDerivedFromGenericType(clonedComponent);
885         if (null == currentGenericType || !currentGenericType.equals(genericTypeResource.getToscaResourceName()) || !currentGenericVersion
886             .equals(genericTypeResource.getVersion())) {
887             shouldUpgrade = upgradeToLatestGeneric(clonedComponent, genericTypeResource);
888             if (!shouldUpgrade) {
889                 reverntUpdateOfGenericVersion(clonedComponent, currentGenericType, currentGenericVersion);
890             }
891         }
892         return Either.left(shouldUpgrade);
893     }
894
895     private void reverntUpdateOfGenericVersion(Component clonedComponent, String currentGenericType, String currentGenericVersion) {
896         clonedComponent.setDerivedFromGenericType(currentGenericType);
897         clonedComponent.setDerivedFromGenericVersion(currentGenericVersion);
898     }
899
900     private <T extends ToscaDataDefinition> Either<Map<String, T>, String> validateNoConflictingProperties(List<T> currentList,
901                                                                                                            List<T> upgradedList) {
902         Map<String, T> currentMap = ToscaDataDefinition.listToMapByName(currentList);
903         Map<String, T> upgradedMap = ToscaDataDefinition.listToMapByName(upgradedList);
904         return ToscaDataDefinition.mergeDataMaps(upgradedMap, currentMap, true);
905     }
906
907     private boolean shouldUpgradeNodeType(Component componentToCheckOut, Resource latestGeneric) {
908         List<PropertyDefinition> genericTypeProps = latestGeneric.getProperties();
909         Either<Map<String, PropertyDefinition>, String> validPropertiesMerge = validateNoConflictingProperties(genericTypeProps,
910             ((Resource) componentToCheckOut).getProperties());
911         if (validPropertiesMerge.isRight()) {
912             if (log.isDebugEnabled()) {
913                 log.debug("property {} cannot be overriden, check out performed without upgrading to latest generic",
914                         validPropertiesMerge.right().value());
915             }
916             return false;
917         }
918         List<AttributeDefinition> genericTypeAttributes = latestGeneric.getAttributes();
919         final Either<Map<String, AttributeDefinition>, String> validAttributesMerge = validateNoConflictingProperties(genericTypeAttributes,
920             ((Resource) componentToCheckOut).getAttributes());
921         if (validAttributesMerge.isRight()) {
922             if (log.isDebugEnabled()) {
923                 log.debug("attribute {} cannot be overriden, check out performed without upgrading to latest generic",
924                         validAttributesMerge.right().value());
925             }
926             return false;
927         }
928         return true;
929     }
930
931     private boolean upgradeToLatestGeneric(Component componentToCheckOut, Resource latestGeneric) {
932         if (!componentToCheckOut.shouldGenerateInputs()) {
933             //node type - validate properties and attributes
934             return shouldUpgradeNodeType(componentToCheckOut, latestGeneric);
935         }
936         List<PropertyDefinition> genericTypeProps = latestGeneric.getProperties();
937         List<InputDefinition> genericTypeInputs = null == genericTypeProps ? null
938             : genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericTypeProps, latestGeneric.getUniqueId());
939         List<InputDefinition> currentList = new ArrayList<>();
940         // nullify existing ownerId from existing list and merge into updated list
941         if (null != componentToCheckOut.getInputs()) {
942             for (InputDefinition input : componentToCheckOut.getInputs()) {
943                 InputDefinition copy = new InputDefinition(input);
944                 copy.setOwnerId(null);
945                 currentList.add(copy);
946             }
947         }
948         if (null == genericTypeInputs) {
949             componentToCheckOut.setInputs(currentList);
950             return true;
951         }
952         Either<Map<String, InputDefinition>, String> eitherMerged = validateNoConflictingProperties(genericTypeInputs, currentList);
953         if (eitherMerged.isRight()) {
954             if (log.isDebugEnabled()) {
955                 log.debug("input {} cannot be overriden, check out performed without upgrading to latest generic", eitherMerged.right().value());
956             }
957             return false;
958         }
959         componentToCheckOut.setInputs(new ArrayList<>(eitherMerged.left().value().values()));
960         return true;
961     }
962
963     private List<ComponentInstance> getFilteredInstances(Component component, List<String> resourceTypes) {
964         List<ComponentInstance> filteredInstances = null;
965         if (CollectionUtils.isEmpty(resourceTypes)) {
966             filteredInstances = component.getComponentInstances();
967         } else if (CollectionUtils.isNotEmpty(component.getComponentInstances())) {
968             filteredInstances = component.getComponentInstances().stream().filter(i -> isMatchingType(i.getOriginType(), resourceTypes))
969                 .collect(Collectors.toList());
970         }
971         if (filteredInstances == null) {
972             filteredInstances = new ArrayList<>();
973         }
974         return filteredInstances;
975     }
976
977     private boolean isMatchingType(OriginTypeEnum originType, List<String> resourceTypes) {
978         boolean isMatchingType = false;
979         for (String resourceType : resourceTypes) {
980             if (originType == OriginTypeEnum.findByValue(resourceType.toUpperCase())) {
981                 isMatchingType = true;
982                 break;
983             }
984         }
985         return isMatchingType;
986     }
987
988     public Either<Component, ActionStatus> shouldUpgradeToLatestDerived(Component clonedComponent) {
989         //general implementation. Must be error for service, VF . In ResourceBuisnessLogic exist override
990         return Either.right(ActionStatus.GENERAL_ERROR);
991     }
992
993     protected Either<Component, ResponseFormat> updateCatalog(Component component, ChangeTypeEnum changeStatus) {
994         if (log.isDebugEnabled()) {
995             log.debug("update Catalog start with Component Type {} And Componet Name {} with change status {}",
996                     component.getComponentType().name(),component.getName(), changeStatus.name());
997         }
998         ActionStatus status = catalogOperations.updateCatalog(changeStatus, component);
999         if (status != ActionStatus.OK) {
1000             return Either.right(componentsUtils.getResponseFormat(status));
1001         }
1002         return Either.left(component);
1003     }
1004
1005     public CatalogOperation getCatalogOperations() {
1006         return catalogOperations;
1007     }
1008
1009     @Autowired
1010     public void setCatalogOperations(CatalogOperation catalogOperations) {
1011         this.catalogOperations = catalogOperations;
1012     }
1013
1014     public List<GroupDefinition> throwComponentException(ResponseFormat responseFormat) {
1015         throw new ByResponseFormatComponentException(responseFormat);
1016     }
1017 }