Inheritance in ComponentException
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / components / impl / ArtifactsBusinessLogic.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  * Modifications copyright (c) 2019 Nokia
20  * ================================================================================
21  */
22
23 package org.openecomp.sdc.be.components.impl;
24
25 import com.google.common.annotations.VisibleForTesting;
26 import com.google.gson.Gson;
27 import com.google.gson.GsonBuilder;
28 import fj.data.Either;
29 import org.apache.commons.codec.binary.Base64;
30 import org.apache.commons.collections.CollectionUtils;
31 import org.apache.commons.collections.MapUtils;
32 import org.apache.commons.lang.StringUtils;
33 import org.apache.commons.lang3.tuple.ImmutablePair;
34 import org.elasticsearch.common.Strings;
35 import org.openecomp.sdc.be.components.ArtifactsResolver;
36 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
37 import org.openecomp.sdc.be.components.impl.artifact.ArtifactTypeToPayloadTypeSelector;
38 import org.openecomp.sdc.be.components.impl.artifact.PayloadTypeEnum;
39 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
40 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
41 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
42 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
43 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
44 import org.openecomp.sdc.be.components.utils.InterfaceOperationUtils;
45 import org.openecomp.sdc.be.config.BeEcompErrorManager;
46 import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
47 import org.openecomp.sdc.be.config.ConfigurationManager;
48 import org.openecomp.sdc.be.dao.api.ActionStatus;
49 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
50 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
51 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
52 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
53 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
54 import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition;
55 import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition;
56 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
57 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
58 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
59 import org.openecomp.sdc.be.info.ArtifactTemplateInfo;
60 import org.openecomp.sdc.be.model.ArtifactDefinition;
61 import org.openecomp.sdc.be.model.ArtifactType;
62 import org.openecomp.sdc.be.model.Component;
63 import org.openecomp.sdc.be.model.ComponentInstance;
64 import org.openecomp.sdc.be.model.ComponentParametersView;
65 import org.openecomp.sdc.be.model.GroupDefinition;
66 import org.openecomp.sdc.be.model.GroupInstance;
67 import org.openecomp.sdc.be.model.HeatParameterDefinition;
68 import org.openecomp.sdc.be.model.InterfaceDefinition;
69 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
70 import org.openecomp.sdc.be.model.LifecycleStateEnum;
71 import org.openecomp.sdc.be.model.Operation;
72 import org.openecomp.sdc.be.model.Resource;
73 import org.openecomp.sdc.be.model.Service;
74 import org.openecomp.sdc.be.model.User;
75 import org.openecomp.sdc.be.model.heat.HeatParameterType;
76 import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation;
77 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
78 import org.openecomp.sdc.be.model.operations.api.IHeatParametersOperation;
79 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
80 import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation;
81 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
82 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
83 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
84 import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
85 import org.openecomp.sdc.be.resources.data.ESArtifactData;
86 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
87 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
88 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
89 import org.openecomp.sdc.be.servlets.RepresentationUtils;
90 import org.openecomp.sdc.be.tosca.CsarUtils;
91 import org.openecomp.sdc.be.tosca.ToscaError;
92 import org.openecomp.sdc.be.tosca.ToscaExportHandler;
93 import org.openecomp.sdc.be.tosca.ToscaRepresentation;
94 import org.openecomp.sdc.be.user.IUserBusinessLogic;
95 import org.openecomp.sdc.be.user.Role;
96 import org.openecomp.sdc.be.user.UserBusinessLogic;
97 import org.openecomp.sdc.be.utils.TypeUtils;
98 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
99 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
100 import org.openecomp.sdc.common.api.Constants;
101 import org.openecomp.sdc.common.datastructure.Wrapper;
102 import org.openecomp.sdc.common.log.wrappers.Logger;
103 import org.openecomp.sdc.common.util.GeneralUtility;
104 import org.openecomp.sdc.common.util.ValidationUtils;
105 import org.openecomp.sdc.common.util.YamlToObjectConverter;
106 import org.openecomp.sdc.exception.ResponseFormat;
107 import org.springframework.beans.factory.annotation.Autowired;
108 import org.xml.sax.InputSource;
109 import org.xml.sax.SAXException;
110 import org.xml.sax.SAXNotRecognizedException;
111 import org.xml.sax.SAXNotSupportedException;
112 import org.xml.sax.XMLReader;
113 import org.yaml.snakeyaml.Yaml;
114
115 import javax.servlet.http.HttpServletRequest;
116 import javax.xml.XMLConstants;
117 import javax.xml.parsers.ParserConfigurationException;
118 import javax.xml.parsers.SAXParserFactory;
119 import java.io.ByteArrayInputStream;
120 import java.io.IOException;
121 import java.math.BigDecimal;
122 import java.util.ArrayList;
123 import java.util.Collections;
124 import java.util.Comparator;
125 import java.util.HashMap;
126 import java.util.Iterator;
127 import java.util.List;
128 import java.util.Map;
129 import java.util.Map.Entry;
130 import java.util.Objects;
131 import java.util.Optional;
132 import java.util.Set;
133 import java.util.function.Predicate;
134 import java.util.function.Supplier;
135 import java.util.stream.Collectors;
136
137 @org.springframework.stereotype.Component("artifactBusinessLogic")
138 public class ArtifactsBusinessLogic extends BaseBusinessLogic {
139     private static final String RESOURCE_INSTANCE = "resource instance";
140     private static final String ARTIFACT_TYPE_OTHER = "OTHER";
141     private static final String ARTIFACT_DESCRIPTION = "artifact description";
142     private static final String ARTIFACT_LABEL = "artifact label";
143     private static final String ARTIFACT_URL = "artifact url";
144     private static final String ARTIFACT_NAME = "artifact name";
145     private static final String ARTIFACT_PAYLOAD = "artifact payload";
146
147     private static final String ARTIFACT_PLACEHOLDER_TYPE = "type";
148     private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName";
149     private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description";
150
151     public static final String HEAT_ENV_NAME = "heatEnv";
152     public static final String HEAT_VF_ENV_NAME = "VfHeatEnv";
153     public static final String HEAT_ENV_SUFFIX = "env";
154     private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension";
155
156     private static final Logger log = Logger.getLogger(ArtifactsBusinessLogic.class);
157     public static final String FAILED_UPDATE_GROUPS = "Failed to update groups of the component {}. ";
158     public static final String FAILED_UPDATE_ARTIFACT = "Failed to delete or update the artifact {}. Parent uniqueId is {}";
159     public static final String FAILED_SAVE_ARTIFACT = "Failed to save the artifact.";
160     public static final String UPDATE_ARTIFACT_LOCK = "Update Artifact - lock ";
161     public static final String FAILED_DOWNLOAD_ARTIFACT = "Download artifact {} failed";
162     public static final String FAILED_UPLOAD_ARTIFACT_TO_COMPONENT = "Failed to upload artifact to component with type {} and uuid {}. Status is {}. ";
163     public static final String FAILED_UPLOAD_ARTIFACT_TO_INSTANCE = "Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ";
164     public static final String FAILED_FETCH_COMPONENT = "Could not fetch component with type {} and uuid {}. Status is {}. ";
165     public static final String NULL_PARAMETER = "One of the function parameteres is null";
166     public static final String COMPONENT_INSTANCE_NOT_FOUND = "Component instance {} was not found for component {}";
167     public static final String ROLLBACK = "all changes rollback";
168     public static final String COMMIT = "all changes committed";
169     public static final String ARTIFACT_SAVED = "Artifact saved into ES - {}";
170     public static final String UPDATE_ARTIFACT = "Update Artifact";
171     public static final String FOUND_DEPLOYMENT_ARTIFACT = "Found deployment artifact {}";
172     private Gson gson = new GsonBuilder().setPrettyPrinting().create();
173
174     @javax.annotation.Resource
175     private IInterfaceLifecycleOperation interfaceLifecycleOperation;
176     @javax.annotation.Resource
177     private IUserAdminOperation userOperaton;
178
179     @javax.annotation.Resource
180     private IElementOperation elementOperation;
181
182     @javax.annotation.Resource
183     private ResourceBusinessLogic resourceBusinessLogic;
184
185     @javax.annotation.Resource
186     private ServiceBusinessLogic serviceBusinessLogic;
187
188     @javax.annotation.Resource
189     private UserBusinessLogic userAdminManager;
190
191     @javax.annotation.Resource
192     private IHeatParametersOperation heatParametersOperation;
193
194     @Autowired
195     private ArtifactCassandraDao artifactCassandraDao;
196
197     @Autowired
198     private ToscaExportHandler toscaExportUtils;
199
200     @Autowired
201     private CsarUtils csarUtils;
202
203     @Autowired
204     private LifecycleBusinessLogic lifecycleBusinessLogic;
205
206     @Autowired
207     private IUserBusinessLogic userBusinessLogic;
208
209     @Autowired
210     private NodeTemplateOperation nodeTemplateOperation;
211
212     @Autowired
213     private ArtifactsResolver artifactsResolver;
214
215     public enum ArtifactOperationEnum {
216         CREATE, UPDATE, DELETE, DOWNLOAD, LINK;
217
218         public static boolean isCreateOrLink(ArtifactOperationEnum operation) {
219             return operation == CREATE || operation == LINK;
220         }
221     }
222
223     public class ArtifactOperationInfo {
224
225         private ArtifactOperationEnum artifactOperationEnum;
226         private boolean isExternalApi;
227         private boolean ignoreLifecycleState;
228
229         public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, ArtifactOperationEnum artifactOperationEnum) {
230             this.artifactOperationEnum = artifactOperationEnum;
231             this.isExternalApi = isExternalApi;
232             this.ignoreLifecycleState = ignoreLifecycleState;
233         }
234
235         public boolean isExternalApi() {
236             return isExternalApi;
237         }
238
239         public boolean ignoreLifecycleState() {
240             return ignoreLifecycleState;
241         }
242
243         public ArtifactOperationEnum getArtifactOperationEnum() {
244             return artifactOperationEnum;
245         }
246
247     }
248
249     // new flow US556184
250     public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
251                                                                                                String origMd5, String originData, String interfaceUuid, String operationUuid, String parentId, String containerComponentType) {
252         return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceUuid, operationUuid, parentId, containerComponentType, true, false);
253     }
254
255     public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
256                                                                                                String origMd5, String originData, String interfaceUuid, String operationUuid, String parentId, String containerComponentType, boolean shouldLock, boolean inTransaction) {
257
258         // step 1 - detect auditing type
259         AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
260         // step 2 - check header
261         if (userId == null) {
262             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
263             log.debug("handleArtifactRequest - no HTTP_CSP_HEADER , component id {}", componentId);
264             handleAuditing(auditingAction, null, componentId, null, null, null, artifactId, responseFormat, componentType, null);
265             return Either.right(responseFormat);
266         }
267         // step 3 - check user existence
268         Either<User, ResponseFormat> userResult = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction);
269         if (userResult.isRight()) {
270             return Either.right(userResult.right().value());
271         }
272
273         // step 4 - check user's role
274         User user = userResult.left().value();
275         Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation);
276         if (validateUserRole.isRight()) {
277             return Either.right(validateUserRole.right().value());
278         }
279
280         // steps 5 - 6 - 7
281         // 5. check service/resource existence
282         // 6. check service/resource check out
283         // 7. user is owner of checkout state
284         org.openecomp.sdc.be.model.Component component = null;
285         String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
286         Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, auditingAction, user, artifactId, componentType, containerComponentType);
287         if (validateComponent.isRight()) {
288             return Either.right(validateComponent.right().value());
289         }
290         component = validateComponent.left().value();
291         Either<Boolean, ResponseFormat> validateWorkOnResource = validateWorkOnComponent(component, userId, auditingAction, user, artifactId, operation);
292         if (validateWorkOnResource.isRight()) {
293             return Either.right(validateWorkOnResource.right().value());
294         }
295         // step 8
296
297         return validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceUuid, operationUuid, user, component,
298                 shouldLock, inTransaction, true);
299     }
300
301     /**
302      * This Method validates only the Artifact and does not validate user / role / component ect...<br>
303      * For regular usage use <br>
304      * {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperationInfo, String, ArtifactDefinition, String, String, String, String, String, String)}
305      *
306      * @return
307      */
308     public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact(String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactUniqueId,
309                                                                                                    ArtifactDefinition artifactDefinition, String origMd5, String originData, String interfaceUuid, String operationName, User user, Component component, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
310         Component parent = component;
311         Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
312
313         AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
314         artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, auditingAction, user, component, parent, errorWrapper, shouldLock, inTransaction);
315
316         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
317         if (errorWrapper.isEmpty()) {
318             // step 10
319             result = doAction(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, origMd5, originData, interfaceUuid, operationName, auditingAction, user, parent, shouldLock, inTransaction, needUpdateGroup);
320         }
321         else {
322             result = Either.right(errorWrapper.getInnerElement());
323         }
324         return result;
325     }
326
327     private ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user,
328                                                 Component component, Component parent, Wrapper<ResponseFormat> errorWrapper, boolean shouldLock, boolean inTransaction) {
329         ArtifactDefinition validatedArtifactInfo = artifactInfo;
330         if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE || operation.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE || operation
331                 .getArtifactOperationEnum() == ArtifactOperationEnum.DOWNLOAD) {
332             Either<ArtifactDefinition, ResponseFormat> validateArtifact = validateArtifact(componentId, componentType, artifactId, component);
333             if (validateArtifact.isRight()) {
334                 ResponseFormat responseFormat = validateArtifact.right().value();
335                 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
336                 errorWrapper.setInnerElement(validateArtifact.right().value());
337             }
338             else if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.DOWNLOAD) {
339                 validatedArtifactInfo = validateArtifact.left().value();
340                     handleHeatEnvDownload(componentId, componentType, user, component, validateArtifact, errorWrapper, shouldLock, inTransaction);
341             }
342         }
343         return validatedArtifactInfo;
344     }
345
346     private void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, Either<ArtifactDefinition,
347             ResponseFormat> validateArtifact, Wrapper<ResponseFormat> errorWrapper, boolean shouldLock, boolean inTransaction) {
348         ArtifactDefinition validatedArtifact = validateArtifact.left().value();
349
350         if (validatedArtifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())
351                 && ComponentTypeEnum.SERVICE == component.getComponentType()) {
352             ComponentInstance componentInstance = component.getComponentInstances()
353                                                            .stream()
354                                                            .filter(p -> p.getUniqueId().equals(componentId))
355                                                            .findAny()
356                                                            .get();
357             Map<String, ArtifactDefinition> deploymentArtifacts = componentInstance.getDeploymentArtifacts();
358
359             ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values()
360                                                                           .stream()
361                                                                           .filter(p -> p.getUniqueId()
362                                                                                         .equals(validatedArtifact.getUniqueId()))
363                                                                           .findAny()
364                                                                           .get();
365             Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, componentType, component, componentInstance
366                     .getName(), user, componentId, shouldLock, inTransaction);
367             if (eitherGenerated.isRight()) {
368                 errorWrapper.setInnerElement(eitherGenerated.right().value());
369             }
370         }
371     }
372
373     private boolean artifactGenerationRequired(org.openecomp.sdc.be.model.Component component, ArtifactDefinition artifactInfo) {
374         boolean needGenerate;
375         needGenerate = artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component
376                 .getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
377         needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && (artifactInfo.getArtifactType()
378                                                                                                                    .equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV
379                                                                                                                            .getType()) || isAbstractVfcEmptyCsar((Resource) component, artifactInfo)));
380         return needGenerate;
381     }
382
383     private boolean isAbstractVfcEmptyCsar(Resource resource, ArtifactDefinition artifactInfo) {
384         return resource.isAbstract() && artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactInfo
385                 .getArtifactType()
386                 .equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) && StringUtils.isEmpty(artifactInfo.getArtifactChecksum());
387     }
388
389     public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateAndSaveToscaArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest,
390                                                                                                       boolean shouldLock, boolean inTransaction, boolean fetchTemplatesFromDB) {
391
392         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB);
393         if (generated.isRight()) {
394             return generated;
395         }
396         byte[] decodedPayload = artifactDefinition.getPayloadData();
397         artifactDefinition.setEsId(artifactDefinition.getUniqueId());
398         artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload));
399         return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition
400                         .getUniqueId(), user, component.getComponentType(), component, decodedPayload, null, null,
401                 shouldLock, inTransaction);
402
403     }
404
405     private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB) {
406         log.debug("tosca artifact generation");
407         if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) {
408             Either<byte[], ResponseFormat> generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest);
409
410             if (generated.isRight()) {
411                 log.debug("Failed to export tosca csar for component {} error {}", parent.getUniqueId(), generated.right()
412                                                                                                                   .value());
413
414                 return Either.right(generated.right().value());
415             }
416             byte[] value = generated.left().value();
417             artifactInfo.setPayload(value);
418
419         }
420         else {
421             Either<ToscaRepresentation, ToscaError> exportComponent = toscaExportUtils.exportComponent(parent);
422             if (exportComponent.isRight()) {
423                 log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), exportComponent.right()
424                                                                                                                      .value());
425                 ActionStatus status = componentsUtils.convertFromToscaError(exportComponent.right().value());
426                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status);
427                 return Either.right(responseFormat);
428             }
429             log.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
430             String payload = exportComponent.left().value().getMainYaml();
431             artifactInfo.setPayloadData(payload);
432         }
433         return Either.left(Either.left(artifactInfo));
434     }
435
436     private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5,
437                                                                                    String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
438         switch (operation.getArtifactOperationEnum()) {
439             case DOWNLOAD:
440                 if (artifactGenerationRequired(parent, artifactInfo)) {
441                     return generateNotSavedArtifact(parent, artifactInfo);
442                 }
443                 return handleDownload(componentId, artifactId, user, auditingAction, componentType, parent);
444             case DELETE:
445                 return handleDelete(componentId, artifactId, user, auditingAction, componentType, parent, shouldLock, inTransaction);
446             case UPDATE:
447                 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = null;
448                 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
449                 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)
450                         && (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) {
451                     result = handleUpdateHeatEnv(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction);
452                     if (needUpdateGroup && result.isLeft()) {
453                         Either<ArtifactDefinition, Operation> updateResult = result.left().value();
454                         ActionStatus error = updateGroupInstance(artifactInfo, updateResult.left()
455                                                                                            .value(), parent, componentType, componentId);
456                         if (error != ActionStatus.OK) {
457                             result = Either.right(componentsUtils.getResponseFormat(error));
458                         }
459                     }
460                 }
461                 else {
462                     if (componentType.equals(ComponentTypeEnum.RESOURCE) && artifactType == ArtifactTypeEnum.HEAT_ENV) {
463                         result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction, needUpdateGroup);
464                     }
465                 }
466                 if (result == null) {
467                     result = handleUpdate(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
468                     if (needUpdateGroup && result.isLeft()) {
469                         Either<ArtifactDefinition, Operation> updateResult = result.left().value();
470
471                         ActionStatus error = updateGroupForHeat(artifactInfo, updateResult.left()
472                                                                                           .value(), parent, componentType);
473                         if (error != ActionStatus.OK) {
474                             result = Either.right(componentsUtils.getResponseFormat(error));
475                         }
476                     }
477                 }
478                 return result;
479             case CREATE:
480                 return handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
481             case LINK:
482                 return handleLink(componentId, artifactInfo, auditingAction, user, componentType, parent, shouldLock, inTransaction);
483         }
484         return null;
485     }
486
487     private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType) {
488         List<GroupDefinition> groups = parent.getGroups();
489         if (groups != null && !groups.isEmpty()) {
490             List<GroupDataDefinition> groupToUpdate = groups.stream()
491                                                             .filter(g -> g.getArtifacts() != null && g.getArtifacts()
492                                                                                                       .contains(artifactInfo
493                                                                                                               .getUniqueId()))
494                                                             .collect(Collectors.toList());
495             if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
496                 groupToUpdate.forEach(g -> {
497                     g.getArtifacts().remove(artifactInfo.getUniqueId());
498                     g.getArtifactsUuid().remove(artifactInfo.getArtifactUUID());
499                     g.getArtifacts().add(artAfterUpdate.getUniqueId());
500                     g.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID());
501                 });
502                 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate);
503                 if (status.isRight()) {
504                     log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
505                     return componentsUtils.convertFromStorageResponse(status.right().value());
506                 }
507             }
508         }
509         return ActionStatus.OK;
510     }
511
512     private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE, ArtifactDefinition artHEAfterUpdate, Component parent, ComponentTypeEnum componentType) {
513         List<GroupDefinition> groups = parent.getGroups();
514         if (groups != null && !groups.isEmpty()) {
515             List<GroupDataDefinition> groupToUpdate = groups.stream()
516                                                             .filter(g -> g.getArtifacts() != null && g.getArtifacts()
517                                                                                                       .contains(artifactInfoHeat
518                                                                                                               .getUniqueId()))
519                                                             .collect(Collectors.toList());
520             if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
521                 groupToUpdate.forEach(g -> {
522                     g.getArtifacts().remove(artifactInfoHeat.getUniqueId());
523                     g.getArtifactsUuid().remove(artifactInfoHeat.getArtifactUUID());
524                     g.getArtifacts().remove(artifactInfoHeatE.getUniqueId());
525                     g.getArtifacts().add(artHeatAfterUpdate.getUniqueId());
526                     g.getArtifactsUuid().add(artHeatAfterUpdate.getArtifactUUID());
527                     g.getArtifacts().add(artHEAfterUpdate.getUniqueId());
528                 });
529                 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate);
530                 if (status.isRight()) {
531                     log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
532                     return componentsUtils.convertFromStorageResponse(status.right().value());
533                 }
534             }
535         }
536         return ActionStatus.OK;
537     }
538
539     private ActionStatus updateGroupInstance(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType, String parentId) {
540         List<GroupInstance> updatedGroupInstances = new ArrayList<>();
541         List<GroupInstance> groupInstances = null;
542         Optional<ComponentInstance> componentInstOp = parent.getComponentInstances()
543                                                             .stream()
544                                                             .filter(ci -> ci.getUniqueId().equals(parentId))
545                                                             .findFirst();
546         if (componentInstOp.isPresent()) {
547             groupInstances = componentInstOp.get().getGroupInstances();
548         }
549         if (CollectionUtils.isNotEmpty(groupInstances)) {
550             boolean isUpdated = false;
551             for (GroupInstance groupInstance : groupInstances) {
552                 isUpdated = false;
553                 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts()
554                                                                                                           .contains(artifactInfo
555                                                                                                                   .getUniqueId())) {
556                     groupInstance.getGroupInstanceArtifacts().remove(artifactInfo.getUniqueId());
557                     groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getUniqueId());
558                     isUpdated = true;
559                 }
560                 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid()
561                                                                                                               .contains(artifactInfo
562                                                                                                                       .getArtifactUUID())) {
563                     groupInstance.getGroupInstanceArtifactsUuid().remove(artifactInfo.getArtifactUUID());
564                     groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getArtifactUUID());
565                     isUpdated = true;
566                 }
567                 if (isUpdated) {
568                     updatedGroupInstances.add(groupInstance);
569                 }
570             }
571         }
572         Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, parentId, updatedGroupInstances);
573         if (status.isRight()) {
574             log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
575             return componentsUtils.convertFromStorageResponse(status.right().value());
576         }
577         return ActionStatus.OK;
578     }
579
580     Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateNotSavedArtifact(Component parent, ArtifactDefinition artifactInfo) {
581         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
582         if (artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) {
583             result = generateToscaArtifact(parent, artifactInfo, false, false);
584         }
585         else {
586             String heatArtifactId = artifactInfo.getGeneratedFromId();
587             Either<ArtifactDefinition, StorageOperationStatus> heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId);
588             if (heatRes.isRight()) {
589                 log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactInfo
590                         .getUniqueId());
591                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatRes
592                         .right()
593                         .value()), "");
594                 return Either.right(responseFormat);
595             }
596             String generatedPayload = generateHeatEnvPayload(heatRes.left().value());
597             artifactInfo.setPayloadData(generatedPayload);
598             result = Either.left(Either.left(artifactInfo));
599         }
600         return result;
601     }
602
603     private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
604                                                                                                             ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction, boolean needToUpdateGroup) {
605         convertParentType(componentType);
606         String parentId = parent.getUniqueId();
607         Either<ArtifactDefinition, StorageOperationStatus> artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo
608                 .getGeneratedFromId());
609         ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value();
610
611         if (origMd5 != null) {
612             Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
613             if (validateMd5.isRight()) {
614                 ResponseFormat responseFormat = validateMd5.right().value();
615                 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
616                 return Either.right(responseFormat);
617             }
618
619             if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
620
621                 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
622                 if (payloadEither.isRight()) {
623                     ResponseFormat responseFormat = payloadEither.right().value();
624                     handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
625                     return Either.right(responseFormat);
626                 }
627             }
628             else { // duplicate
629                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
630                 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
631                 return Either.right(responseFormat);
632             }
633         }
634
635         // lock resource
636         if (shouldLock) {
637             Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, UPDATE_ARTIFACT_LOCK);
638             if (lockComponent.isRight()) {
639                 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
640                                                                                                             .value(), componentType, null);
641                 return Either.right(lockComponent.right().value());
642             }
643         }
644         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
645         try {
646             resultOp = updateHeatParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currHeatArtifact, needToUpdateGroup);
647             return resultOp;
648
649         }
650         finally {
651             // unlock resource
652             if (resultOp == null || resultOp.isRight()) {
653                 log.debug(ROLLBACK);
654                 if (!inTransaction) {
655                     titanDao.rollback();
656                 }
657             }
658             else {
659                 log.debug(COMMIT);
660                 if (!inTransaction) {
661                     titanDao.commit();
662                 }
663             }
664             if (shouldLock) {
665                 graphLockOperation.unlockComponent(parent.getUniqueId(), parent.getComponentType().getNodeType());
666             }
667         }
668     }
669
670     public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) {
671         if (artifactGenerationRequired(component, csarArtifact)) {
672             Either<byte[], ResponseFormat> generated = csarUtils.createCsar(component, false, false);
673
674             if (generated.isRight()) {
675                 log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right()
676                                                                                                                      .value());
677
678                 return Either.right(generated.right().value());
679             }
680             return Either.left(new ImmutablePair<String, byte[]>(csarArtifact.getArtifactName(), generated.left()
681                                                                                                           .value()));
682         }
683         return downloadArtifact(csarArtifact);
684     }
685
686     public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) {
687         // perform all validation in common flow
688         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DOWNLOAD), artifactId, null, null, null, null,
689                 null, parentId, containerComponentType);
690         if (result.isRight()) {
691             return Either.right(result.right().value());
692         }
693         ArtifactDefinition artifactDefinition;
694         Either<ArtifactDefinition, Operation> insideValue = result.left().value();
695         if (insideValue.isLeft()) {
696             artifactDefinition = insideValue.left().value();
697         }
698         else {
699             artifactDefinition = insideValue.right().value().getImplementationArtifact();
700         }
701         // for tosca artifacts and heat env on VF level generated on download without saving
702         if (artifactDefinition.getPayloadData() != null) {
703             return Either.left(new ImmutablePair<String, byte[]>(artifactDefinition.getArtifactName(), artifactDefinition
704                     .getPayloadData()));
705         }
706         return downloadArtifact(artifactDefinition);
707     }
708
709     public Either<Map<String, ArtifactDefinition>, ResponseFormat> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) {
710         // step 1
711         // detect auditing type
712         Map<String, ArtifactDefinition> resMap = null;
713         Either<Map<String, ArtifactDefinition>, ResponseFormat> resultOp = null;
714
715         new Wrapper<>();
716         // step 2
717         // check header
718         if (userId == null) {
719             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
720             log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId);
721
722             resultOp = Either.right(responseFormat);
723             return resultOp;
724         }
725         // step 3
726         // check user existence
727         // step 4
728         // check user's role
729
730         validateUserExists(userId, "get artifacts", false);
731         // steps 5 - 6 - 7
732         // 5. check service/resource existence
733         // 6. check service/resource check out
734         // 7. user is owner of checkout state
735         org.openecomp.sdc.be.model.Component component = null;
736         String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
737         ComponentParametersView componentFilter = new ComponentParametersView();
738         componentFilter.disableAll();
739         componentFilter.setIgnoreArtifacts(false);
740         if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
741             componentFilter.setIgnoreComponentInstances(false);
742         }
743
744         Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum
745                 .findByParamName(containerComponentType), componentFilter);
746
747         if (validateComponent.isRight()) {
748             resultOp = Either.right(validateComponent.right().value());
749             return resultOp;
750         }
751         component = validateComponent.left().value();
752         Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, UPDATE_ARTIFACT_LOCK);
753         if (lockComponent.isRight()) {
754
755             resultOp = Either.right(lockComponent.right().value());
756             return resultOp;
757         }
758
759         try {
760             ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType);
761
762             if (groupType == null) {
763                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
764                 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
765
766                 resultOp = Either.right(responseFormat);
767                 return resultOp;
768
769             }
770             if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
771                 List<ArtifactDefinition> list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId);
772                 if (list != null && !list.isEmpty()) {
773                     resMap = list.stream().collect(Collectors.toMap(a -> a.getArtifactLabel(), a -> a));
774                 }
775                 else {
776                     resMap = new HashMap<>();
777                 }
778                 resultOp = Either.left(resMap);
779                 return resultOp;
780             }
781             else {
782
783                 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType
784                         .getNodeType(), groupType, componentId);
785                 if (artifactsMapStatus.isRight()) {
786                     if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) {
787                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
788                         log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
789                         resultOp = Either.right(responseFormat);
790                     }
791                     else {
792                         resMap = new HashMap<>();
793                         resultOp = Either.left(resMap);
794                     }
795                 }
796                 else {
797                     resMap = artifactsMapStatus.left().value();
798                     resultOp = Either.left(resMap);
799                 }
800                 return resultOp;
801             }
802         }
803         finally {
804             // unlock resource
805             if (resultOp == null || resultOp.isRight()) {
806                 log.debug(ROLLBACK);
807                 titanDao.rollback();
808             }
809             else {
810                 log.debug(COMMIT);
811                 titanDao.commit();
812             }
813
814             componentType = component.getComponentType();
815             NodeTypeEnum nodeType = componentType.getNodeType();
816             graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
817         }
818
819     }
820
821     private Either<ArtifactDefinition, ResponseFormat> validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, Component component) {
822         // step 9
823         // check artifact existence
824         Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, component
825                 .getUniqueId());
826         if (artifactResult.isRight()) {
827             if (artifactResult.right().value().equals(StorageOperationStatus.ARTIFACT_NOT_FOUND)) {
828                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
829                 log.debug("addArtifact - artifact {} not found", artifactId);
830                 return Either.right(responseFormat);
831
832             }
833             else {
834                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactResult
835                         .right()
836                         .value()));
837                 log.debug("addArtifact - failed to fetch artifact {}, error {}", artifactId, artifactResult.right()
838                                                                                                            .value());
839                 return Either.right(responseFormat);
840             }
841         }
842         // step 9.1
843         // check artifact belong to component
844         boolean found = false;
845         switch (componentType) {
846             case RESOURCE:
847             case SERVICE:
848                 found = checkArtifactInComponent(component, artifactId);
849                 break;
850             case RESOURCE_INSTANCE:
851                 found = checkArtifactInResourceInstance(component, componentId, artifactId);
852                 break;
853             default:
854
855         }
856         if (!found) {
857             String componentName = componentType.name().toLowerCase();
858             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, componentName);
859             log.debug("addArtifact - Component artifact not found component Id {}, artifact id {}", componentId, artifactId);
860             return Either.right(responseFormat);
861         }
862         return Either.left(artifactResult.left().value());
863     }
864
865     private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
866                                                                                        org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
867
868         String artifactId = null;
869
870         // step 11
871         Either<byte[], ResponseFormat> payloadEither = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName);
872         if (payloadEither.isRight()) {
873             return Either.right(payloadEither.right().value());
874         }
875         byte[] decodedPayload = payloadEither.left().value();
876         convertParentType(componentType);
877
878         if (shouldLock) {
879             Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
880             if (lockComponent.isRight()) {
881                 handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right()
882                                                                                                          .value(), componentType, null);
883                 return Either.right(lockComponent.right().value());
884             }
885         }
886         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
887
888         try {
889             resultOp = createArtifact(parent, componentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName);
890             return resultOp;
891         }
892         finally {
893             if (shouldLock) {
894                 unlockComponent(resultOp, parent, inTransaction);
895             }
896
897         }
898
899     }
900
901     private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleLink(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
902                                                                                      Component parent, boolean shouldLock, boolean inTransaction) {
903
904         if (shouldLock) {
905             Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
906             if (lockComponent.isRight()) {
907                 handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right()
908                                                                                                          .value(), componentType, null);
909                 return Either.right(lockComponent.right().value());
910             }
911         }
912         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
913
914         try {
915             resultOp = createAndLinkArtifact(parent, componentId, artifactInfo, user, componentType, auditingAction);
916             return resultOp;
917         }
918         finally {
919             if (shouldLock) {
920                 unlockComponent(resultOp, parent, inTransaction);
921             }
922
923         }
924
925     }
926
927     private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
928                                                                                                          ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, byte[] decodedPayload, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
929
930         convertParentType(componentType);
931
932         // lock resource
933         if (shouldLock) {
934             Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, UPDATE_ARTIFACT_LOCK);
935
936             if (lockComponent.isRight()) {
937                 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
938                                                                                                             .value(), componentType, null);
939                 return Either.right(lockComponent.right().value());
940             }
941         }
942
943         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
944         try {
945             resultOp = updateArtifactFlow(parent, parentId, artifactId, artifactInfo, user, decodedPayload, componentType, auditingAction, interfaceType, operationName);
946             return resultOp;
947
948         }
949         finally {
950             if (shouldLock) {
951                 unlockComponent(resultOp, parent, inTransaction);
952             }
953         }
954     }
955
956     private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user,
957                                                                                        ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
958
959         Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName);
960
961         if (payloadEither.isRight()) {
962             return Either.right(payloadEither.right().value());
963         }
964         byte[] decodedPayload = payloadEither.left().value();
965
966         return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction);
967     }
968
969     private Either<byte[], ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
970                                                          Component parent, String origMd5, String originData, String interfaceType, String operationName) {
971         // Md5 validations
972         Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
973         if (validateMd5.isRight()) {
974             ResponseFormat responseFormat = validateMd5.right().value();
975             handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
976             return Either.right(responseFormat);
977         }
978
979         // step 11
980         Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(componentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent);
981         if (validateResult.isRight()) {
982             ResponseFormat responseFormat = validateResult.right().value();
983             handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
984             return Either.right(validateResult.right().value());
985         }
986
987         Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
988         if (payloadEither.isRight()) {
989             ResponseFormat responseFormat = payloadEither.right().value();
990             handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
991             log.debug("Error during handle payload");
992             return Either.right(responseFormat);
993         }
994
995         // validate heat parameters. this part must be after the parameters are
996         // extracted in "handlePayload"
997         Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, artifactInfo
998                 .getArtifactType());
999         if (validateAndConvertHeatParamers.isRight()) {
1000             ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
1001             handleAuditing(auditingAction, parent, componentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null);
1002             log.debug("Error during handle payload");
1003             return Either.right(responseFormat);
1004         }
1005         return payloadEither;
1006     }
1007
1008     public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat,
1009                                ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
1010
1011         if (componentsUtils.isExternalApiEvent(auditingActionEnum)) {
1012             return;
1013         }
1014
1015         if (user == null) {
1016             user = new User();
1017             user.setUserId("UNKNOWN");
1018         }
1019         handleInternalAuditEvent(auditingActionEnum, component, componentId, user, artifactDefinition, prevArtifactUuid, currentArtifactUuid, responseFormat, componentTypeEnum, resourceInstanceName);
1020     }
1021
1022     private void handleInternalAuditEvent(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat, ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
1023         switch (componentTypeEnum) {
1024             case RESOURCE:
1025                 Resource resource = (Resource) component;
1026                 if (resource == null) {
1027                     // In that case, component ID should be instead of name
1028                     resource = new Resource();
1029                     resource.setName(componentId);
1030                 }
1031                 componentsUtils.auditResource(responseFormat, user, resource, resource.getName(), auditingActionEnum,
1032                         ResourceVersionInfo.newBuilder()
1033                                 .artifactUuid(prevArtifactUuid)
1034                                 .build(), currentArtifactUuid, artifactDefinition);
1035                 break;
1036
1037             case SERVICE:
1038                 Service service = (Service) component;
1039                 if (service == null) {
1040                     // In that case, component ID should be instead of name
1041                     service = new Service();
1042                     service.setName(componentId);
1043                 }
1044                 componentsUtils.auditComponent(responseFormat, user, service, auditingActionEnum, new ResourceCommonInfo(ComponentTypeEnum.SERVICE.getValue()),
1045                         ResourceVersionInfo.newBuilder()
1046                                 .artifactUuid(prevArtifactUuid)
1047                                 .build(),
1048                         ResourceVersionInfo.newBuilder()
1049                                 .artifactUuid(currentArtifactUuid)
1050                                 .build(),
1051                         null, artifactDefinition, null);
1052                 break;
1053
1054             case RESOURCE_INSTANCE:
1055                 if (resourceInstanceName == null) {
1056                     resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId);
1057                 }
1058                 componentsUtils.auditComponent(responseFormat, user, component, auditingActionEnum,
1059                         new ResourceCommonInfo(resourceInstanceName, ComponentTypeEnum.RESOURCE_INSTANCE.getValue()),
1060                         ResourceVersionInfo.newBuilder()
1061                                 .artifactUuid(prevArtifactUuid)
1062                                 .build(),
1063                         ResourceVersionInfo.newBuilder()
1064                                 .artifactUuid(currentArtifactUuid)
1065                                 .build(),
1066                         null, artifactDefinition, null);
1067                 break;
1068             default:
1069                 break;
1070         }
1071     }
1072
1073     private String getResourceInstanceNameFromComponent(Component component, String componentId) {
1074         ComponentInstance resourceInstance = component.getComponentInstances()
1075                                                       .stream()
1076                                                       .filter(p -> p.getUniqueId().equals(componentId))
1077                                                       .findFirst()
1078                                                       .orElse(null);
1079         String resourceInstanceName = null;
1080         if (resourceInstance != null) {
1081             resourceInstanceName = resourceInstance.getName();
1082         }
1083         return resourceInstanceName;
1084     }
1085
1086     private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) {
1087         StringBuilder sb = new StringBuilder();
1088         if (artifactDefinition != null) {
1089             sb.append(artifactDefinition.getArtifactGroupType().getType())
1090               .append(",")
1091               .append("'")
1092               .append(artifactDefinition.getArtifactLabel())
1093               .append("'")
1094               .append(",")
1095               .append(artifactDefinition.getArtifactType())
1096               .append(",")
1097               .append(artifactDefinition.getArtifactName())
1098               .append(",")
1099               .append(artifactDefinition.getTimeout())
1100               .append(",")
1101               .append(artifactDefinition.getEsId());
1102
1103             sb.append(",");
1104             if (artifactDefinition.getArtifactVersion() != null) {
1105
1106                 sb.append(artifactDefinition.getArtifactVersion());
1107             }
1108             else {
1109                 sb.append(" ");
1110             }
1111             sb.append(",");
1112             if (artifactDefinition.getArtifactUUID() != null) {
1113                 sb.append(artifactDefinition.getArtifactUUID());
1114             }
1115             else {
1116                 sb.append(" ");
1117             }
1118         }
1119         return sb.toString();
1120     }
1121
1122     private Either<Boolean, ResponseFormat> validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) {
1123
1124         if (origMd5 != null) {
1125             String encodeBase64Str = GeneralUtility.calculateMD5Base64EncodedByString(originData);
1126             if (!encodeBase64Str.equals(origMd5)) {
1127                 log.debug("The calculated md5 is different then the received one");
1128                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1129             }
1130         }
1131         else {
1132             if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && payload != null && payload.length != 0) {
1133                 log.debug("Missing md5 header during artifact create");
1134                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1135             }
1136             // Update metadata
1137             if (payload != null && payload.length != 0) {
1138                 log.debug("Cannot have payload while md5 header is missing");
1139                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1140             }
1141         }
1142         return Either.left(true);
1143     }
1144
1145     private Either<ArtifactDefinition, ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName,
1146                                                                      ComponentTypeEnum componentType, Component parentComponent) {
1147
1148         Either<ArtifactDefinition, ResponseFormat> artifactById = findArtifactOnParentComponent(parentComponent, componentType, componentId, operation, artifactId);
1149         if (artifactById.isRight()) {
1150             return Either.right(artifactById.right().value());
1151         }
1152         ArtifactDefinition currentArtifactInfo = artifactById.left().value();
1153
1154         ignoreUnupdateableFieldsInUpdate(operation, artifactInfo, currentArtifactInfo);
1155         Either<Boolean, ResponseFormat> validateInformationalArtifactRes = validateInformationalArtifact(artifactInfo, parentComponent);
1156         if (validateInformationalArtifactRes.isRight()) {
1157             return Either.right(validateInformationalArtifactRes.right().value());
1158         }
1159         Either<Boolean, ResponseFormat> validateAndSetArtifactname = validateAndSetArtifactname(artifactInfo);
1160         if (validateAndSetArtifactname.isRight()) {
1161             return Either.right(validateAndSetArtifactname.right().value());
1162         }
1163         if (operationName != null && interfaceName != null) {
1164             operationName = operationName.toLowerCase();
1165             interfaceName = interfaceName.toLowerCase();
1166         }
1167         Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(componentId, parentComponent, operation, artifactInfo, operationName, componentType);
1168         if (logicalNameStatus.isRight()) {
1169             return Either.right(logicalNameStatus.right().value());
1170         }
1171         // This is a patch to block possibility of updating service api fields
1172         // through other artifacts flow
1173
1174         ArtifactGroupTypeEnum artifactGroupType = operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL;
1175         if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1176             checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, artifactGroupType);
1177         }
1178         else {
1179             checkCreateFields(user, artifactInfo, artifactGroupType);
1180         }
1181
1182         composeArtifactId(componentId, artifactId, artifactInfo, interfaceName, operationName);
1183         if (currentArtifactInfo != null) {
1184             artifactInfo.setMandatory(currentArtifactInfo.getMandatory());
1185         }
1186
1187         // artifactGroupType is not allowed to be updated
1188         if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1189             Either<ArtifactDefinition, ResponseFormat> validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo);
1190             if (validateGroupType.isRight()) {
1191                 return Either.right(validateGroupType.right().value());
1192             }
1193         }
1194         NodeTypeEnum parentType = convertParentType(componentType);
1195
1196         boolean isCreate = ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum());
1197
1198         if (isDeploymentArtifact(artifactInfo)) {
1199             Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, componentId, isCreate, artifactInfo, currentArtifactInfo, parentType);
1200             if (deploymentValidationResult.isRight()) {
1201                 return Either.right(deploymentValidationResult.right().value());
1202             }
1203         }
1204         else {
1205             artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1206         }
1207
1208         Either<Boolean, ResponseFormat> descriptionResult = validateAndCleanDescription(artifactInfo);
1209         if (descriptionResult.isRight()) {
1210             return Either.right(descriptionResult.right().value());
1211         }
1212
1213         if (currentArtifactInfo != null && currentArtifactInfo.getArtifactGroupType()
1214                                                               .equals(ArtifactGroupTypeEnum.SERVICE_API)) {
1215             Either<ActionStatus, ResponseFormat> validateServiceApiType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1216             if (validateServiceApiType.isRight()) {
1217                 return Either.right(validateServiceApiType.right().value());
1218             }
1219             // Change of type is not allowed and should be ignored
1220
1221             artifactInfo.setArtifactType(ARTIFACT_TYPE_OTHER);
1222
1223             Either<Boolean, ResponseFormat> validateUrl = validateAndServiceApiUrl(artifactInfo);
1224             if (validateUrl.isRight()) {
1225                 return Either.right(validateUrl.right().value());
1226             }
1227
1228             Either<Boolean, ResponseFormat> validateUpdate = validateFirstUpdateHasPayload(artifactInfo, currentArtifactInfo);
1229             if (validateUpdate.isRight()) {
1230                 log.debug("serviceApi first update cnnot be without payload.");
1231                 return Either.right(validateUpdate.right().value());
1232             }
1233         }
1234         else {
1235             Either<ActionStatus, ResponseFormat> validateArtifactType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1236             if (validateArtifactType.isRight()) {
1237                 return Either.right(validateArtifactType.right().value());
1238             }
1239             if (artifactInfo.getApiUrl() != null) {
1240                 artifactInfo.setApiUrl(null);
1241                 log.error("Artifact URL cannot be set through this API - ignoring");
1242             }
1243
1244             if (artifactInfo.getServiceApi() != null && artifactInfo.getServiceApi()) {
1245                 artifactInfo.setServiceApi(false);
1246                 log.error("Artifact service API flag cannot be changed - ignoring");
1247             }
1248         }
1249
1250         return Either.left(artifactInfo);
1251     }
1252
1253     private void ignoreUnupdateableFieldsInUpdate(ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifactInfo) {
1254         if (operation.getArtifactOperationEnum().equals(ArtifactOperationEnum.UPDATE)) {
1255             artifactInfo.setArtifactType(currentArtifactInfo.getArtifactType());
1256             artifactInfo.setArtifactGroupType(currentArtifactInfo.getArtifactGroupType());
1257             artifactInfo.setArtifactLabel(currentArtifactInfo.getArtifactLabel());
1258         }
1259     }
1260
1261     private Either<ArtifactDefinition, ResponseFormat> findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) {
1262
1263         Either<ArtifactDefinition, ResponseFormat> result = null;
1264         ArtifactDefinition foundArtifact = null;
1265         if (StringUtils.isNotEmpty(artifactId)) {
1266             foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId);
1267         }
1268         if (foundArtifact != null && ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1269             log.debug("Artifact {} already exist", artifactId);
1270             result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel()));
1271         }
1272         if (foundArtifact == null && !ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1273             log.debug("The artifact {} was not found on parent {}. ", artifactId, parentId);
1274             result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
1275         }
1276         if (result == null) {
1277             result = Either.left(foundArtifact);
1278         }
1279         return result;
1280     }
1281
1282     private ArtifactDefinition findArtifact(Component parentComponent, ComponentTypeEnum componentType, String parentId, String artifactId) {
1283         ArtifactDefinition foundArtifact;
1284         if (parentComponent.getUniqueId().equals(parentId)) {
1285             foundArtifact = artifactsResolver.findArtifactOnComponent(parentComponent, componentType, artifactId);
1286         }
1287         else {
1288             ComponentInstance instance = findComponentInstance(parentId, parentComponent);
1289             foundArtifact = artifactsResolver.findArtifactOnComponentInstance(instance, artifactId);
1290         }
1291         return foundArtifact;
1292     }
1293
1294     private Either<Boolean, ResponseFormat> validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) {
1295         ComponentTypeEnum parentComponentType = parentComponent.getComponentType();
1296         ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType();
1297         Either<Boolean, ResponseFormat> validationResult = Either.left(true);
1298         ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1299         if (artifactType == null) {
1300             validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
1301                     .getArtifactType()));
1302         }
1303         else if (parentComponentType == ComponentTypeEnum.RESOURCE && groupType == ArtifactGroupTypeEnum.INFORMATIONAL) {
1304             String artifactTypeName = artifactType.getType();
1305             ResourceTypeEnum parentResourceType = ((Resource) parentComponent).getResourceType();
1306             Map<String, ArtifactTypeConfig> resourceInformationalArtifacts = ConfigurationManager.getConfigurationManager()
1307                                                                                                  .getConfiguration()
1308                                                                                                  .getResourceInformationalArtifacts();
1309             Set<String> validArtifactTypes = resourceInformationalArtifacts.keySet();
1310             if (!validArtifactTypes.contains(artifactTypeName)) {
1311                 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1312             }
1313             else {
1314                 List<String> validResourceType = resourceInformationalArtifacts.get(artifactTypeName)
1315                                                                                .getValidForResourceTypes();
1316                 if (!validResourceType.contains(parentResourceType.name())) {
1317                     validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1318                 }
1319             }
1320         }
1321         return validationResult;
1322     }
1323
1324     private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) {
1325         if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1326             return NodeTypeEnum.Resource;
1327         }
1328         else if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1329             return NodeTypeEnum.ResourceInstance;
1330         }
1331         else {
1332             return NodeTypeEnum.Service;
1333         }
1334     }
1335
1336     public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete(String parentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, Component parent,
1337                                                                                       boolean shouldLock, boolean inTransaction) {
1338
1339         NodeTypeEnum parentType = convertParentType(componentType);
1340         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1341         Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes = null;
1342         ArtifactDefinition foundArtifact = null;
1343         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1344         Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getContainerRes = null;
1345         org.openecomp.sdc.be.model.Component fetchedContainerComponent = null;
1346         boolean isDuplicated = false;
1347         String esId = null;
1348         Either<Boolean, StorageOperationStatus> needCloneRes = null;
1349         try {
1350             if (shouldLock) {
1351                 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Delete Artifact - lock resource: ");
1352                 if (lockComponent.isRight()) {
1353                     handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
1354                                                                                                                 .value(), componentType, null);
1355                     resultOp = Either.right(lockComponent.right().value());
1356                 }
1357             }
1358             if (resultOp == null) {
1359                 log.debug("Going to fetch the container component {}. ", parent.getUniqueId());
1360                 getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId());
1361                 if (getContainerRes.isRight()) {
1362                     log.debug("Failed to fetch the container component {}. ", parentId);
1363                     responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(getContainerRes
1364                             .right()
1365                             .value()), artifactId);
1366                     handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1367                     resultOp = Either.right(responseFormat);
1368                 }
1369             }
1370             if (resultOp == null) {
1371                 fetchedContainerComponent = getContainerRes.left().value();
1372                 log.debug("Going to find the artifact {} on the component {}", artifactId, fetchedContainerComponent.getUniqueId());
1373                 getArtifactRes = findArtifact(artifactId, fetchedContainerComponent, parentId, componentType);
1374                 if (getArtifactRes.isRight()) {
1375                     log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, fetchedContainerComponent
1376                             .getUniqueId());
1377                     responseFormat = componentsUtils.getResponseFormatByArtifactId(getArtifactRes.right()
1378                                                                                                  .value(), artifactId);
1379                     handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1380                     resultOp = Either.right(responseFormat);
1381                 }
1382                 else {
1383                     foundArtifact = getArtifactRes.left().value().getLeft();
1384                     esId = foundArtifact.getEsId();
1385                 }
1386             }
1387             if (resultOp == null && StringUtils.isNotEmpty(esId)) {
1388                 needCloneRes = artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, convertParentType(parent
1389                         .getComponentType()));
1390                 if (needCloneRes.isRight()) {
1391                     log.debug(FAILED_UPDATE_ARTIFACT, artifactId, parentId);
1392                     responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(needCloneRes
1393                             .right()
1394                             .value()), foundArtifact.getArtifactDisplayName());
1395                     handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1396                     resultOp = Either.right(responseFormat);
1397                 }
1398             }
1399             boolean isNeedToDeleteArtifactFromDB = true;
1400             if (resultOp == null) {
1401
1402                 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1403                     String instanceId = parentId;
1404                     Either<Boolean, ActionStatus> isOnlyResourceInstanceArtifact = isArtifactOnlyResourceInstanceArtifact(foundArtifact, fetchedContainerComponent, instanceId);
1405
1406                     if (isOnlyResourceInstanceArtifact.isRight()) {
1407                         log.debug(FAILED_UPDATE_ARTIFACT, artifactId, parentId);
1408                         responseFormat = componentsUtils.getResponseFormatByArtifactId(isOnlyResourceInstanceArtifact.right()
1409                                                                                                                      .value(), foundArtifact
1410                                 .getArtifactDisplayName());
1411                         handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1412                         return Either.right(responseFormat);
1413                     }
1414                     isNeedToDeleteArtifactFromDB = isOnlyResourceInstanceArtifact.left().value();
1415                 }
1416
1417                 Either<ArtifactDataDefinition, StorageOperationStatus> updatedArtifactRes = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needCloneRes
1418                         .left()
1419                         .value());
1420                 if (updatedArtifactRes.isRight()) {
1421                     log.debug(FAILED_UPDATE_ARTIFACT, artifactId, parentId);
1422                     responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updatedArtifactRes
1423                             .right()
1424                             .value()), foundArtifact.getArtifactDisplayName());
1425                     handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1426                     resultOp = Either.right(responseFormat);
1427                 }
1428                 else {
1429                     isDuplicated = updatedArtifactRes.left().value().getDuplicated();
1430                 }
1431             }
1432
1433             if (resultOp == null && (!needCloneRes.left().value() && !isDuplicated) && isNeedToDeleteArtifactFromDB) {
1434                 log.debug("Going to delete the artifact {} from the database. ", artifactId);
1435                 CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId);
1436                 if (cassandraStatus != CassandraOperationStatus.OK) {
1437                     log.debug("Failed to delete the artifact {} from the database. ", artifactId);
1438                     responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(componentsUtils.convertToStorageOperationStatus(cassandraStatus)), foundArtifact
1439                             .getArtifactDisplayName());
1440                     handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1441                     resultOp = Either.right(responseFormat);
1442                 }
1443             }
1444             if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1445
1446                 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, getArtifactRes
1447                         .left()
1448                         .value()
1449                         .getRight()
1450                         .getGroupInstances());
1451                 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
1452                     Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(fetchedContainerComponent, parentId, updatedGroupInstances);
1453                     if (status.isRight()) {
1454                         log.debug(FAILED_UPDATE_GROUPS, fetchedContainerComponent.getUniqueId());
1455                         responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status
1456                                 .right()
1457                                 .value()), foundArtifact.getArtifactDisplayName());
1458                         handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1459                         resultOp = Either.right(responseFormat);
1460                     }
1461                 }
1462             }
1463             if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1464                 StorageOperationStatus status = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
1465                 if (status != StorageOperationStatus.OK) {
1466                     log.debug("Failed to generate new customization UUID for the component instance {}. ", parentId);
1467                     responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status), foundArtifact
1468                             .getArtifactDisplayName());
1469                     handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1470                     resultOp = Either.right(responseFormat);
1471                 }
1472             }
1473             if (resultOp == null && componentType != ComponentTypeEnum.RESOURCE_INSTANCE) {
1474                 List<GroupDataDefinition> updatedGroups = getUpdatedGroups(artifactId, foundArtifact, fetchedContainerComponent
1475                         .getGroups());
1476                 if (CollectionUtils.isNotEmpty(updatedGroups)) {
1477                     Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(fetchedContainerComponent, updatedGroups);
1478                     if (status.isRight()) {
1479                         log.debug(FAILED_UPDATE_GROUPS, fetchedContainerComponent.getUniqueId());
1480                         responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status
1481                                 .right()
1482                                 .value()), foundArtifact.getArtifactDisplayName());
1483                         handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1484                         resultOp = Either.right(responseFormat);
1485                     }
1486                 }
1487             }
1488             if (resultOp == null) {
1489                 resultOp = Either.left(Either.left(foundArtifact));
1490                 handleAuditing(auditingAction, parent, parentId, user, foundArtifact, null, artifactId, responseFormat, componentType, null);
1491             }
1492             return resultOp;
1493         }
1494         finally {
1495             if (shouldLock) {
1496                 unlockComponent(resultOp, parent, inTransaction);
1497             }
1498         }
1499     }
1500
1501     private Either<Boolean, ActionStatus> isArtifactOnlyResourceInstanceArtifact(ArtifactDefinition foundArtifact, Component parent, String instanceId) {
1502         Either<Boolean, ActionStatus> result = Either.left(true);
1503         ComponentInstance foundInstance = null;
1504         Optional<ComponentInstance> componentInstanceOpt = parent.getComponentInstances()
1505                                                                  .stream()
1506                                                                  .filter(i -> i.getUniqueId().equals(instanceId))
1507                                                                  .findFirst();
1508         if (!componentInstanceOpt.isPresent()) {
1509             result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1510         }
1511         else {
1512             foundInstance = componentInstanceOpt.get();
1513             String componentUid = foundInstance.getComponentUid();
1514             Either<Component, StorageOperationStatus> getContainerRes = toscaOperationFacade.getToscaElement(componentUid);
1515             if (getContainerRes.isRight()) {
1516                 log.debug("Failed to fetch the container component {}. ", componentUid);
1517                 return Either.right(componentsUtils.convertFromStorageResponse(getContainerRes.right().value()));
1518             }
1519             Component origComponent = getContainerRes.left().value();
1520             Map<String, ArtifactDefinition> deploymentArtifacts = origComponent.getDeploymentArtifacts();
1521             if (deploymentArtifacts != null && !deploymentArtifacts.isEmpty()) {
1522                 Optional<String> op = deploymentArtifacts.keySet()
1523                                                          .stream()
1524                                                          .filter(a -> a.equals(foundArtifact.getArtifactLabel()))
1525                                                          .findAny();
1526                 if (op.isPresent()) {
1527                     return Either.left(false);
1528                 }
1529             }
1530             Map<String, ArtifactDefinition> artifacts = origComponent.getArtifacts();
1531             if (artifacts != null && !artifacts.isEmpty()) {
1532                 Optional<String> op = artifacts.keySet()
1533                                                .stream()
1534                                                .filter(a -> a.equals(foundArtifact.getArtifactLabel()))
1535                                                .findAny();
1536                 if (op.isPresent()) {
1537                     return Either.left(false);
1538                 }
1539             }
1540
1541         }
1542         return result;
1543     }
1544
1545     private List<GroupDataDefinition> getUpdatedGroups(String artifactId, ArtifactDefinition foundArtifact, List<GroupDefinition> groups) {
1546         List<GroupDataDefinition> updatedGroups = new ArrayList<>();
1547         boolean isUpdated = false;
1548         if (groups != null) {
1549             for (GroupDefinition group : groups) {
1550                 isUpdated = false;
1551                 if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactId)) {
1552                     group.getArtifacts().remove(artifactId);
1553                     isUpdated = true;
1554                 }
1555                 if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid()
1556                                                                                  .contains(foundArtifact.getArtifactUUID())) {
1557                     group.getArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1558                     isUpdated = true;
1559                 }
1560                 if (isUpdated) {
1561                     updatedGroups.add(group);
1562                 }
1563             }
1564         }
1565         return updatedGroups;
1566     }
1567
1568     private List<GroupInstance> getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List<GroupInstance> groupInstances) {
1569         List<GroupInstance> updatedGroupInstances = new ArrayList<>();
1570         if (CollectionUtils.isNotEmpty(groupInstances)) {
1571             boolean isUpdated = false;
1572             for (GroupInstance groupInstance : groupInstances) {
1573                 isUpdated = false;
1574                 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts()
1575                                                                                                           .contains(artifactId)) {
1576                     groupInstance.getGroupInstanceArtifacts().remove(artifactId);
1577                     isUpdated = true;
1578                 }
1579                 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid()
1580                                                                                                               .contains(foundArtifact
1581                                                                                                                       .getArtifactUUID())) {
1582                     groupInstance.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1583                     isUpdated = true;
1584                 }
1585                 if (isUpdated) {
1586                     updatedGroupInstances.add(groupInstance);
1587                 }
1588             }
1589         }
1590         return updatedGroupInstances;
1591     }
1592
1593     private Either<ArtifactDataDefinition, StorageOperationStatus> deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) {
1594
1595         Either<ArtifactDataDefinition, StorageOperationStatus> result;
1596         boolean isMandatory = foundArtifact.getMandatory() || foundArtifact.getServiceApi();
1597         String componentId = component.getUniqueId();
1598         String instanceId = componentId.equals(parentId) ? null : parentId;
1599         if (isMandatory) {
1600             log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId);
1601             resetMandatoryArtifactFields(foundArtifact);
1602             result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId, true, true);
1603         }
1604         else if (cloneIsNeeded) {
1605             log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId);
1606             result = artifactToscaOperation.deleteArtifactWithCloningOnGraph(componentId, foundArtifact, parentType, instanceId, false);
1607         }
1608         else {
1609             log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId);
1610             result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false);
1611         }
1612         return result;
1613     }
1614
1615     private Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) {
1616
1617         Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> result = null;
1618         Map<String, ArtifactDefinition> artifacts = new HashMap<>();
1619         ComponentInstance foundInstance = null;
1620         if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && StringUtils.isNotEmpty(parentId)) {
1621             Optional<ComponentInstance> componentInstanceOpt = fetchedContainerComponent.getComponentInstances()
1622                                                                                         .stream()
1623                                                                                         .filter(i -> i.getUniqueId()
1624                                                                                                       .equals(parentId))
1625                                                                                         .findFirst();
1626             if (!componentInstanceOpt.isPresent()) {
1627                 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1628             }
1629             else {
1630                 foundInstance = componentInstanceOpt.get();
1631                 fetchArtifactsFromInstance(artifactId, artifacts, foundInstance);
1632             }
1633         }
1634         else {
1635             fetchArtifactsFromComponent(artifactId, fetchedContainerComponent, artifacts);
1636         }
1637         if (result == null) {
1638             if (artifacts.containsKey(artifactId)) {
1639                 result = Either.left(new ImmutablePair<>(artifacts.get(artifactId), foundInstance));
1640             }
1641             else {
1642                 result = Either.right(ActionStatus.ARTIFACT_NOT_FOUND);
1643             }
1644         }
1645         return result;
1646     }
1647
1648     private void fetchArtifactsFromComponent(String artifactId, Component component, Map<String, ArtifactDefinition> artifacts) {
1649         Map<String, ArtifactDefinition> currArtifacts;
1650         if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getDeploymentArtifacts())) {
1651             currArtifacts = component.getDeploymentArtifacts()
1652                                      .values()
1653                                      .stream()
1654                                      .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1655             if (MapUtils.isNotEmpty(currArtifacts)) {
1656                 artifacts.putAll(currArtifacts);
1657             }
1658         }
1659         if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1660             currArtifacts = component.getArtifacts()
1661                                      .values()
1662                                      .stream()
1663                                      .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1664             if (MapUtils.isNotEmpty(currArtifacts)) {
1665                 artifacts.putAll(currArtifacts);
1666             }
1667         }
1668         if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1669             currArtifacts = component.getToscaArtifacts()
1670                                      .values()
1671                                      .stream()
1672                                      .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1673             if (MapUtils.isNotEmpty(currArtifacts)) {
1674                 artifacts.putAll(currArtifacts);
1675             }
1676         }
1677     }
1678
1679     private void fetchArtifactsFromInstance(String artifactId, Map<String, ArtifactDefinition> artifacts, ComponentInstance instance) {
1680         Map<String, ArtifactDefinition> currArtifacts;
1681         if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) {
1682             currArtifacts = instance.getDeploymentArtifacts()
1683                                     .values()
1684                                     .stream()
1685                                     .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1686             if (MapUtils.isNotEmpty(currArtifacts)) {
1687                 artifacts.putAll(currArtifacts);
1688             }
1689         }
1690         if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(instance.getArtifacts())) {
1691             currArtifacts = instance.getArtifacts()
1692                                     .values()
1693                                     .stream()
1694                                     .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1695             if (MapUtils.isNotEmpty(currArtifacts)) {
1696                 artifacts.putAll(currArtifacts);
1697             }
1698         }
1699     }
1700
1701     private void resetMandatoryArtifactFields(ArtifactDefinition fetchedArtifact) {
1702         if (fetchedArtifact != null) {
1703             log.debug("Going to reset mandatory artifact {} fields. ", fetchedArtifact.getUniqueId());
1704             fetchedArtifact.setEsId(null);
1705             fetchedArtifact.setArtifactName(null);
1706             fetchedArtifact.setDescription(null);
1707             fetchedArtifact.setApiUrl(null);
1708             fetchedArtifact.setArtifactChecksum(null);
1709             nodeTemplateOperation.setDefaultArtifactTimeout(fetchedArtifact.getArtifactGroupType(), fetchedArtifact);
1710             fetchedArtifact.setArtifactUUID(null);
1711             long time = System.currentTimeMillis();
1712             fetchedArtifact.setPayloadUpdateDate(time);
1713             fetchedArtifact.setHeatParameters(null);
1714             fetchedArtifact.setHeatParamsUpdateDate(null);
1715         }
1716     }
1717
1718     private StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId, ComponentTypeEnum componentType) {
1719         StorageOperationStatus error = StorageOperationStatus.OK;
1720         if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1721             log.debug("Need to re-generate  customization UUID for instance {}", instanceId);
1722             error = toscaOperationFacade.generateCustomizationUUIDOnInstance(componentId, instanceId);
1723         }
1724         return error;
1725     }
1726
1727     private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDownload(String componentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType,
1728                                                                                          Component parent) {
1729         Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, parent
1730                 .getUniqueId());
1731         if (artifactById.isRight()) {
1732             ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
1733             log.debug("Error when getting artifact info by id{}, error: {}", artifactId, actionStatus);
1734             ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, "");
1735             handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1736             return Either.right(responseFormat);
1737         }
1738         ArtifactDefinition artifactDefinition = artifactById.left().value();
1739         if (artifactDefinition == null) {
1740             log.debug("Empty artifact definition returned from DB by artifact id {}", artifactId);
1741             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
1742             handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1743             return Either.right(responseFormat);
1744         }
1745
1746         Either<ArtifactDefinition, Operation> insideEither = Either.left(artifactDefinition);
1747         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1748         handleAuditing(auditingAction, parent, componentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null);
1749         return Either.left(insideEither);
1750     }
1751
1752     private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, String operationName,
1753                                                                      ComponentTypeEnum componentType) {
1754
1755         String artifactLabel = artifactInfo.getArtifactLabel();
1756         if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel()
1757                                                                                              .isEmpty())) {
1758             BeEcompErrorManager.getInstance()
1759                                .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
1760             log.debug("missing artifact logical name for component {}", componentId);
1761             return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1762         }
1763         if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && !artifactInfo.getMandatory()) {
1764
1765             if (operationName != null) {
1766                 if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) {
1767                     log.debug("artifact label cannot be set {}", artifactLabel);
1768                     return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
1769                 }
1770                 else {
1771                     artifactLabel = operationName;
1772                 }
1773             }
1774             String displayName = artifactInfo.getArtifactDisplayName();
1775             if (displayName == null || displayName.isEmpty()) {
1776                 displayName = artifactLabel;
1777             }
1778             displayName = ValidationUtils.cleanArtifactDisplayName(displayName);
1779             artifactInfo.setArtifactDisplayName(displayName);
1780
1781             if (!ValidationUtils.validateArtifactLabel(artifactLabel)) {
1782                 log.debug("Invalid format form Artifact label : {}", artifactLabel);
1783                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1784             }
1785             artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel);
1786
1787             if (artifactLabel.isEmpty()) {
1788                 log.debug("missing normalized artifact logical name for component {}", componentId);
1789                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1790             }
1791
1792             if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) {
1793                 log.debug("Invalid lenght form Artifact label : {}", artifactLabel);
1794                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String
1795                         .valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
1796             }
1797             if (!validateLabelUniqueness(componentId, parentComponent, artifactLabel, componentType)) {
1798                 log.debug("Non unique Artifact label : {}", artifactLabel);
1799                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel));
1800             }
1801         }
1802         artifactInfo.setArtifactLabel(artifactLabel);
1803
1804         return Either.left(ActionStatus.OK);
1805     }
1806
1807     private boolean validateLabelUniqueness(String componentId, Component parentComponent, String artifactLabel, ComponentTypeEnum componentType) {
1808         boolean isUnique = true;
1809         Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts;
1810         if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1811             artifacts = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
1812         }
1813         else {
1814             artifacts = artifactToscaOperation.getArtifacts(componentId);
1815         }
1816
1817         if (artifacts.isLeft()) {
1818             for (String label : artifacts.left().value().keySet()) {
1819                 if (label.equals(artifactLabel)) {
1820                     isUnique = false;
1821                     break;
1822                 }
1823             }
1824         }
1825         if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1826             Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
1827                     .getAllInterfacesOfResource(componentId, true, true);
1828             if (allInterfacesOfResource.isLeft()) {
1829                 for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) {
1830                     for (Operation operation : interace.getOperationsMap().values()) {
1831                         if (operation.getImplementation() != null && operation.getImplementation()
1832                                                                               .getArtifactLabel()
1833                                                                               .equals(artifactLabel)) {
1834                             isUnique = false;
1835                             break;
1836                         }
1837                     }
1838                 }
1839             }
1840         }
1841         return isUnique;
1842     }
1843
1844     boolean validateArtifactNameUniqueness(String componentId, Component parentComponent, ArtifactDefinition artifactInfo,
1845                                            ComponentTypeEnum componentType) {
1846         Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = getArtifacts(componentType,
1847                 parentComponent, componentId, artifactInfo.getArtifactGroupType());
1848         String artifactName = artifactInfo.getArtifactName();
1849         if (artifacts.isLeft() && Objects.nonNull(artifacts.left().value())){
1850             if (artifacts.left().value().values().stream()
1851                     .anyMatch(ad -> artifactName.equals(ad.getArtifactName())
1852                             //check whether it is the same artifact we hold (by label)
1853                             && !artifactInfo.getArtifactLabel().equals(ad.getArtifactLabel()))){
1854                 return false;
1855             }
1856         }
1857         if (ComponentTypeEnum.RESOURCE.equals(componentType)) {
1858             return isUniqueArtifactNameInResourceInterfaces(componentId, artifactName, artifactInfo.getArtifactLabel());
1859         }
1860         return true;
1861     }
1862
1863     private boolean isUniqueArtifactNameInResourceInterfaces(String componentId, String artifactName, String artifactLabel) {
1864         Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
1865                 .getAllInterfacesOfResource(componentId, true, true);
1866
1867         if (allInterfacesOfResource.isLeft() && Objects.nonNull(allInterfacesOfResource)){
1868             return !allInterfacesOfResource.left().value()
1869                     .values()
1870                     .stream().map(InterfaceDefinition :: getOperationsMap)
1871                     .flatMap(map -> map.values().stream())
1872                     .map(OperationDataDefinition::getImplementation)
1873                     .filter(Objects::nonNull)
1874                     .anyMatch(add -> artifactName.equals(add.getArtifactName())
1875                             && !artifactLabel.equals(add.getArtifactLabel()));
1876         }
1877         return true;
1878     }
1879
1880     private boolean isUniqueLabelInResourceInterfaces(String componentId, String artifactLabel) {
1881         Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
1882                 .getAllInterfacesOfResource(componentId, true, true);
1883
1884         if (allInterfacesOfResource.isLeft()){
1885             return !allInterfacesOfResource.left().value()
1886                     .values()
1887                     .stream().map(InterfaceDefinition :: getOperationsMap)
1888                     .flatMap(map -> map.values().stream())
1889                     .map(OperationDataDefinition::getImplementation)
1890                     .filter(Objects::nonNull)
1891                     .anyMatch(add -> artifactLabel.equals(add.getArtifactLabel()));
1892         }
1893         return true;
1894     }
1895
1896     private Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(ComponentTypeEnum componentType, Component parentComponent,
1897                                                                                          String componentId, ArtifactGroupTypeEnum artifactGroupType) {
1898         Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsResponse;
1899         if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1900             artifactsResponse = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
1901         }
1902         else {
1903             artifactsResponse = artifactToscaOperation.getArtifacts(componentId);
1904         }
1905         if (artifactsResponse.isRight() && artifactsResponse.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
1906             log.debug("failed to retrieve artifacts for {} ", componentId);
1907             return Either.right(artifactsResponse.right().value());
1908         }
1909         return Either.left(artifactsResponse.left().value().entrySet()
1910                 .stream()
1911                 .filter(x -> artifactGroupType.equals(x.getValue().getArtifactGroupType()))
1912                 .collect(Collectors.toMap(Entry::getKey, Entry::getValue)));
1913     }
1914
1915     private List<String> getListOfArtifactName(Map<String, ArtifactDefinition> artifacts) {
1916         return artifacts.entrySet()
1917                 .stream()
1918                 .map(x -> x.getValue().getArtifactName())
1919                 .collect(Collectors.toList());
1920     }
1921
1922     // ***************************************************************
1923
1924     private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createAndLinkArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, User user,
1925                                                                                                 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum) {
1926         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1927         Either<ArtifactDefinition, Operation> insideEither = null;
1928         ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1929         String instanceId = null;
1930         String instanceName = null;
1931         if (foundInstance != null) {
1932             instanceId = foundInstance.getUniqueId();
1933             instanceName = foundInstance.getName();
1934         }
1935         boolean isLeft = false;
1936         String artifactUniqueId = null;
1937         StorageOperationStatus error = null;
1938         // information/deployment/api aritfacts
1939         log.trace("Try to create entry on graph");
1940         NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
1941         Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent
1942                 .getUniqueId(), nodeType, true, instanceId);
1943
1944         isLeft = result.isLeft();
1945         if (isLeft) {
1946             artifactUniqueId = result.left().value().getUniqueId();
1947             result.left().value();
1948
1949             insideEither = Either.left(result.left().value());
1950             resultOp = Either.left(insideEither);
1951
1952             error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
1953             if (error != StorageOperationStatus.OK) {
1954                 isLeft = false;
1955             }
1956
1957         }
1958         if (isLeft) {
1959             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1960             handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1961             return resultOp;
1962         }
1963         else {
1964             log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
1965             ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo
1966                     .getArtifactDisplayName());
1967             handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
1968             resultOp = Either.right(responseFormat);
1969             return resultOp;
1970
1971         }
1972     }
1973
1974     private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload, User user,
1975                                                                                          ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) {
1976
1977         ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
1978         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1979         Either<ArtifactDefinition, Operation> insideEither = null;
1980         ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1981         String instanceId = null;
1982         String instanceName = null;
1983         if (foundInstance != null) {
1984             if (foundInstance.isArtifactExists(artifactInfo.getArtifactGroupType(), artifactInfo.getArtifactLabel())) {
1985                 log.debug("Failed to create artifact, already exists");
1986                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactInfo
1987                         .getArtifactLabel());
1988                 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactInfo.getUniqueId(), responseFormat, componentTypeEnum, foundInstance
1989                         .getName());
1990                 resultOp = Either.right(responseFormat);
1991                 return resultOp;
1992             }
1993
1994             instanceId = foundInstance.getUniqueId();
1995             instanceName = foundInstance.getName();
1996         }
1997         if (artifactData == null) {
1998             BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1999             log.debug("Failed to create artifact object for ES.");
2000             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2001             handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, null);
2002             resultOp = Either.right(responseFormat);
2003             return resultOp;
2004
2005         }
2006         // set on graph object id of artifact in ES!
2007         artifactInfo.setEsId(artifactData.getId());
2008
2009         boolean isLeft = false;
2010         String artifactUniqueId = null;
2011         StorageOperationStatus error = null;
2012         if (interfaceType != null && operationName != null) {
2013             // lifecycle artifact
2014             Operation operation = convertToOperation(artifactInfo, operationName);
2015
2016             Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
2017
2018             isLeft = result.isLeft();
2019             if (isLeft) {
2020                 artifactUniqueId = result.left().value().getImplementation().getUniqueId();
2021                 result.left().value().getImplementation();
2022
2023                 insideEither = Either.right(result.left().value());
2024                 resultOp = Either.left(insideEither);
2025             }
2026             else {
2027                 error = result.right().value();
2028             }
2029         }
2030         else {
2031             // information/deployment/api aritfacts
2032             log.trace("Try to create entry on graph");
2033             NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
2034             Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent
2035                     .getUniqueId(), nodeType, true, instanceId);
2036
2037             isLeft = result.isLeft();
2038             if (isLeft) {
2039                 artifactUniqueId = result.left().value().getUniqueId();
2040                 artifactData.setId(result.left().value().getEsId());
2041                 insideEither = Either.left(result.left().value());
2042                 resultOp = Either.left(insideEither);
2043
2044                 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
2045                 if (error != StorageOperationStatus.OK) {
2046                     isLeft = false;
2047                 }
2048
2049             }
2050             else {
2051                 error = result.right().value();
2052             }
2053         }
2054         if (isLeft) {
2055             boolean res = saveArtifacts(artifactData, parentId);
2056
2057             if (res) {
2058                 log.debug(ARTIFACT_SAVED, artifactUniqueId);
2059
2060                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
2061                 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
2062                 return resultOp;
2063             }
2064             else {
2065                 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
2066                 log.debug(FAILED_SAVE_ARTIFACT);
2067                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2068                 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
2069
2070                 resultOp = Either.right(responseFormat);
2071                 return resultOp;
2072             }
2073         }
2074         else {
2075             log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
2076             ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo
2077                     .getArtifactDisplayName());
2078             handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
2079             resultOp = Either.right(responseFormat);
2080             return resultOp;
2081         }
2082
2083     }
2084
2085     private ComponentInstance findComponentInstance(String componentInstanceId, Component containerComponent) {
2086         ComponentInstance foundInstance = null;
2087         if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
2088             foundInstance = containerComponent.getComponentInstances()
2089                                               .stream()
2090                                               .filter(i -> i.getUniqueId().equals(componentInstanceId))
2091                                               .findFirst()
2092                                               .orElse(null);
2093         }
2094         return foundInstance;
2095     }
2096
2097     private Either<Boolean, ResponseFormat> validateDeploymentArtifact(Component parentComponent, String parentId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
2098
2099         Either<Boolean, ResponseFormat> result = Either.left(true);
2100         Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
2101
2102         validateArtifactTypeExists(responseWrapper, artifactInfo);
2103
2104         ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
2105
2106         Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType);
2107
2108         if (responseWrapper.isEmpty()) {
2109             validateDeploymentArtifactConf(artifactInfo, responseWrapper, artifactType, resourceDeploymentArtifacts);
2110         }
2111
2112         // Common code for all types
2113         // not allowed to change artifactType
2114         if (responseWrapper.isEmpty() && !isCreate) {
2115             Either<Boolean, ResponseFormat> validateServiceApiType = validateArtifactTypeNotChanged(artifactInfo, currentArtifact);
2116             if (validateServiceApiType.isRight()) {
2117                 responseWrapper.setInnerElement(validateServiceApiType.right().value());
2118             }
2119         }
2120         if (responseWrapper.isEmpty()) {
2121             if (parentType.equals(NodeTypeEnum.Resource)) {
2122                 Resource resource = (Resource) parentComponent;
2123                 ResourceTypeEnum resourceType = resource.getResourceType();
2124                 ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType());
2125                 if (config == null) {
2126                     responseWrapper.setInnerElement(ResponseFormatManager.getInstance()
2127                                                                          .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2128                                                                                  .getArtifactType()));
2129                 }
2130                 else {
2131                     List<String> myList = config.getValidForResourceTypes();
2132                     Either<Boolean, ResponseFormat> either = validateResourceType(resourceType, artifactInfo, myList);
2133                     if (either.isRight()) {
2134                         responseWrapper.setInnerElement(either.right().value());
2135                     }
2136                 }
2137             }
2138
2139             validateFileExtension(responseWrapper, () -> getDeploymentArtifactTypeConfig(parentType, artifactType), artifactInfo, parentType, artifactType);
2140         }
2141
2142         if (responseWrapper.isEmpty() && !NodeTypeEnum.ResourceInstance.equals(parentType)) {
2143             String artifactName = artifactInfo.getArtifactName();
2144             if (isCreate || !artifactName.equalsIgnoreCase(currentArtifact.getArtifactName())) {
2145                 validateSingleDeploymentArtifactName(responseWrapper, artifactName, parentComponent, parentType);
2146             }
2147         }
2148
2149         if (responseWrapper.isEmpty()) {
2150             switch (artifactType) {
2151                 case HEAT:
2152                 case HEAT_VOL:
2153                 case HEAT_NET:
2154                     result = validateHeatDeploymentArtifact(isCreate, artifactInfo, currentArtifact);
2155                     break;
2156                 case HEAT_ENV:
2157                     result = validateHeatEnvDeploymentArtifact(parentComponent, parentId, artifactInfo, parentType);
2158                     artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
2159                     break;
2160                 case DCAE_INVENTORY_TOSCA:
2161                 case DCAE_INVENTORY_JSON:
2162                 case DCAE_INVENTORY_POLICY:
2163                     // Validation is done in handle payload.
2164                 case DCAE_INVENTORY_DOC:
2165                 case DCAE_INVENTORY_BLUEPRINT:
2166                 case DCAE_INVENTORY_EVENT:
2167                     // No specific validation
2168                 default:
2169                     artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
2170                     break;
2171             }
2172
2173         }
2174
2175         if (!responseWrapper.isEmpty()) {
2176             result = Either.right(responseWrapper.getInnerElement());
2177         }
2178         return result;
2179     }
2180
2181     private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper<ResponseFormat> responseWrapper, ArtifactTypeEnum artifactType, Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) {
2182         if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) {
2183             ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2184                                                                  .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2185                                                                          .getArtifactType());
2186             responseWrapper.setInnerElement(responseFormat);
2187             log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
2188         }
2189     }
2190
2191     private Map<String, ArtifactTypeConfig> fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) {
2192         Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = null;
2193         if (parentType.equals(NodeTypeEnum.Resource)) {
2194             resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2195                                                               .getConfiguration()
2196                                                               .getResourceDeploymentArtifacts();
2197         }
2198         else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2199             resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2200                                                               .getConfiguration()
2201                                                               .getResourceInstanceDeploymentArtifacts();
2202         }
2203         else {
2204             resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2205                                                               .getConfiguration()
2206                                                               .getServiceDeploymentArtifacts();
2207         }
2208         return resourceDeploymentArtifacts;
2209     }
2210
2211     public void validateArtifactTypeExists(Wrapper<ResponseFormat> responseWrapper, ArtifactDefinition artifactInfo) {
2212         ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
2213         if (artifactType == null) {
2214             ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2215                                                                  .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2216                                                                          .getArtifactType());
2217             responseWrapper.setInnerElement(responseFormat);
2218             log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
2219         }
2220     }
2221
2222     private ArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
2223         ArtifactTypeConfig retConfig = null;
2224         String fileType = artifactType.getType();
2225         if (parentType.equals(NodeTypeEnum.Resource)) {
2226             retConfig = ConfigurationManager.getConfigurationManager()
2227                                             .getConfiguration()
2228                                             .getResourceDeploymentArtifacts()
2229                                             .get(fileType);
2230         }
2231         else if (parentType.equals(NodeTypeEnum.Service)) {
2232             retConfig = ConfigurationManager.getConfigurationManager()
2233                                             .getConfiguration()
2234                                             .getServiceDeploymentArtifacts()
2235                                             .get(fileType);
2236         }
2237         else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2238             retConfig = ConfigurationManager.getConfigurationManager()
2239                                             .getConfiguration()
2240                                             .getResourceInstanceDeploymentArtifacts()
2241                                             .get(fileType);
2242         }
2243         return retConfig;
2244     }
2245
2246     private Either<Boolean, ResponseFormat> extractHeatParameters(ArtifactDefinition artifactInfo) {
2247         // extract heat parameters
2248         if (artifactInfo.getPayloadData() != null) {
2249             String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData()));
2250             Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo
2251                     .getArtifactType());
2252             if (heatParameters.isRight() && (!heatParameters.right()
2253                                                             .value()
2254                                                             .equals(ResultStatusEnum.ELEMENT_NOT_FOUND))) {
2255                 log.info("failed to parse heat parameters ");
2256                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo
2257                         .getArtifactType());
2258                 return Either.right(responseFormat);
2259             }
2260             else if (heatParameters.isLeft() && heatParameters.left().value() != null) {
2261                 artifactInfo.setListHeatParameters(heatParameters.left().value());
2262             }
2263         }
2264         return Either.left(true);
2265
2266     }
2267
2268     // Valid extension
2269     public void validateFileExtension(Wrapper<ResponseFormat> responseWrapper, IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
2270         String fileType = artifactType.getType();
2271         List<String> acceptedTypes = null;
2272         ArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig();
2273         if (!parentType.equals(NodeTypeEnum.Resource) && !parentType.equals(NodeTypeEnum.Service) && !parentType.equals(NodeTypeEnum.ResourceInstance)) {
2274             log.debug("parent type of artifact can be either resource or service");
2275             responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2276             return;
2277         }
2278
2279         if (deploymentAcceptedTypes == null) {
2280             log.debug("parent type of artifact can be either resource or service");
2281             responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2282                     .getArtifactType()));
2283             return;
2284         }
2285         else {
2286             acceptedTypes = deploymentAcceptedTypes.getAcceptedTypes();
2287         }
2288         /*
2289          * No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted.
2290          */
2291
2292         String artifactName = artifactInfo.getArtifactName();
2293         String fileExtension = GeneralUtility.getFilenameExtension(artifactName);
2294         // Pavel - File extension validation is case-insensitive - Ella,
2295         // 21/02/2016
2296         if (acceptedTypes != null && !acceptedTypes.isEmpty() && !acceptedTypes.contains(fileExtension.toLowerCase())) {
2297             log.debug("File extension \"{}\" is not allowed for {} which is of type:{}", fileExtension, artifactName, fileType);
2298             responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION, fileType));
2299             return;
2300         }
2301     }
2302
2303     private Either<Boolean, ResponseFormat> validateHeatEnvDeploymentArtifact(Component parentComponent, String parentId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2304
2305         Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
2306         Wrapper<ArtifactDefinition> heatMDWrapper = new Wrapper<>();
2307         Wrapper<byte[]> payloadWrapper = new Wrapper<>();
2308
2309         if (errorWrapper.isEmpty()) {
2310             validateValidYaml(errorWrapper, artifactInfo);
2311         }
2312
2313         if (errorWrapper.isEmpty()) {
2314             // Validate Heat Exist
2315             validateHeatExist(parentComponent.getUniqueId(), parentId, errorWrapper, heatMDWrapper, artifactInfo, parentType, parentComponent
2316                     .getComponentType());
2317         }
2318
2319         if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
2320             fillArtifactPayloadValidation(errorWrapper, payloadWrapper, heatMDWrapper.getInnerElement());
2321         }
2322
2323         if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
2324             validateEnvVsHeat(errorWrapper, artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement());
2325         }
2326
2327         // init Response
2328         Either<Boolean, ResponseFormat> eitherResponse;
2329         if (errorWrapper.isEmpty()) {
2330             eitherResponse = Either.left(true);
2331         }
2332         else {
2333             eitherResponse = Either.right(errorWrapper.getInnerElement());
2334         }
2335         return eitherResponse;
2336     }
2337
2338     public void fillArtifactPayloadValidation(Wrapper<ResponseFormat> errorWrapper, Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactDefinition) {
2339         if (artifactDefinition.getPayloadData() == null || artifactDefinition.getPayloadData().length == 0) {
2340             Either<Boolean, ResponseFormat> fillArtifactPayload = fillArtifactPayload(payloadWrapper, artifactDefinition);
2341             if (fillArtifactPayload.isRight()) {
2342                 errorWrapper.setInnerElement(fillArtifactPayload.right().value());
2343                 log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName());
2344             }
2345         }
2346         else {
2347             payloadWrapper.setInnerElement(artifactDefinition.getPayloadData());
2348         }
2349     }
2350
2351     public Either<Boolean, ResponseFormat> fillArtifactPayload(Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactMD) {
2352         Either<Boolean, ResponseFormat> result = Either.left(true);
2353         Either<ESArtifactData, CassandraOperationStatus> eitherArtifactData = artifactCassandraDao.getArtifact(artifactMD
2354                 .getEsId());
2355         if (eitherArtifactData.isLeft()) {
2356             byte[] data = eitherArtifactData.left().value().getDataAsArray();
2357             data = Base64.encodeBase64(data);
2358             payloadWrapper.setInnerElement(data);
2359         }
2360         else {
2361             StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData
2362                     .right()
2363                     .value());
2364             ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus));
2365             result = Either.right(responseFormat);
2366         }
2367         return result;
2368
2369     }
2370
2371     @SuppressWarnings("unchecked")
2372     private void validateEnvVsHeat(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) {
2373         String envPayload = new String(Base64.decodeBase64(envArtifact.getPayloadData()));
2374         Map<String, Object> heatEnvToscaJson = (Map<String, Object>) new Yaml().load(envPayload);
2375         String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData));
2376         Map<String, Object> heatToscaJson = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
2377
2378         Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS);
2379         Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS);
2380         if (eitherHeatEnvProperties.isRight()) {
2381             ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2382                                                                  .getResponseFormat(ActionStatus.CORRUPTED_FORMAT, "Heat Env");
2383             errorWrapper.setInnerElement(responseFormat);
2384             log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName());
2385         }
2386         else if (eitherHeatProperties.isRight()) {
2387             ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2388                                                                  .getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact
2389                                                                          .getArtifactName(), heatArtifact.getArtifactName());
2390             errorWrapper.setInnerElement(responseFormat);
2391             log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact
2392                     .getArtifactName());
2393         }
2394         else {
2395             Set<String> heatPropertiesKeys = eitherHeatProperties.left().value().keySet();
2396             Set<String> heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet();
2397             heatEnvPropertiesKeys.removeAll(heatPropertiesKeys);
2398             if (!heatEnvPropertiesKeys.isEmpty()) {
2399                 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2400                                                                      .getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact
2401                                                                              .getArtifactName(), heatArtifact.getArtifactName());
2402                 errorWrapper.setInnerElement(responseFormat);
2403             }
2404         }
2405     }
2406
2407     private void validateValidYaml(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition artifactInfo) {
2408         YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
2409         boolean isYamlValid = yamlConvertor.isValidYamlEncoded64(artifactInfo.getPayloadData());
2410         if (!isYamlValid) {
2411             ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2412                                                                  .getResponseFormat(ActionStatus.INVALID_YAML, artifactInfo
2413                                                                          .getArtifactType());
2414             errorWrapper.setInnerElement(responseFormat);
2415             log.debug("Yaml is not valid for artifact : {}", artifactInfo.getArtifactName());
2416         }
2417     }
2418
2419     private boolean isValidXml(byte[] xmlToParse) {
2420         boolean isXmlValid = true;
2421         try {
2422             XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
2423             setFeatures(reader);
2424             reader.parse(new InputSource(new ByteArrayInputStream(xmlToParse)));
2425         }
2426         catch (ParserConfigurationException | IOException | SAXException e) {
2427             log.debug("Xml is invalid : {}", e.getMessage(), e);
2428             isXmlValid = false;
2429         }
2430         return isXmlValid;
2431     }
2432
2433     private void setFeatures(XMLReader reader) throws SAXNotSupportedException {
2434         try {
2435             reader.setFeature("http://apache.org/xml/features/validation/schema", false);
2436             reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
2437         }
2438         catch (SAXNotRecognizedException e) {
2439             log.debug("Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e);
2440         }
2441     }
2442
2443     private void validateSingleDeploymentArtifactName(Wrapper<ResponseFormat> errorWrapper, String artifactName, Component parentComponent, NodeTypeEnum parentType) {
2444         boolean artifactNameFound = false;
2445         Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, null)
2446                 .iterator();
2447
2448         while (!artifactNameFound && parentDeploymentArtifactsItr.hasNext()) {
2449             artifactNameFound = artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName());
2450         }
2451         if (artifactNameFound) {
2452             String parentName = parentComponent.getName();
2453             ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2454                                                                  .getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, parentType
2455                                                                          .name(), parentName, artifactName);
2456
2457             errorWrapper.setInnerElement(responseFormat);
2458             log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName);
2459
2460         }
2461     }
2462
2463     private void validateHeatExist(String componentId, String parentRiId, Wrapper<ResponseFormat> errorWrapper, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, NodeTypeEnum parentType,
2464                                    ComponentTypeEnum componentType) {
2465         Either<ArtifactDefinition, StorageOperationStatus> res = artifactToscaOperation.getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, parentType, componentId, componentType);
2466         if (res.isRight()) {
2467             ResponseFormat responseFormat;
2468             if (res.right().value() == StorageOperationStatus.NOT_FOUND) {
2469                 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2470             }
2471             else {
2472                 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2473             }
2474             errorWrapper.setInnerElement(responseFormat);
2475             return;
2476         }
2477         ArtifactDefinition heatArtifact = res.left().value();
2478         heatArtifactMDWrapper.setInnerElement(heatArtifact);
2479     }
2480
2481     private Either<Boolean, ResponseFormat> validateHeatDeploymentArtifact(boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2482         log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel());
2483         // timeout > 0 for HEAT artifacts
2484         Integer timeout = artifactInfo.getTimeout();
2485         if (timeout == null) {
2486             Integer defaultTimeout = isCreate ? NodeTemplateOperation.getDefaultHeatTimeout() : currentArtifact.getTimeout();
2487             artifactInfo.setTimeout(defaultTimeout);
2488             // HEAT artifact but timeout is invalid
2489         }
2490         else if (timeout < 1) {
2491             return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_TIMEOUT));
2492         }
2493
2494         // US649856 - Allow several HEAT files on Resource
2495         log.trace("Ended HEAT validation for artifact {}", artifactInfo.getArtifactLabel());
2496         return Either.left(true);
2497     }
2498
2499     private Either<Boolean, ResponseFormat> validateResourceType(ResourceTypeEnum resourceType, ArtifactDefinition artifactInfo, List<String> typeList) {
2500         String listToString = (typeList != null) ? typeList.toString() : "";
2501         ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2502                                                              .getResponseFormat(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo
2503                                                                      .getArtifactName(), listToString, resourceType.getValue());
2504         Either<Boolean, ResponseFormat> either = Either.right(responseFormat);
2505         String resourceTypeName = resourceType.name();
2506         if (typeList != null && typeList.contains(resourceTypeName)) {
2507             either = Either.left(true);
2508         }
2509         return either;
2510     }
2511
2512     private Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers(ArtifactDefinition artifactInfo, String artifactType) {
2513         if (artifactInfo.getHeatParameters() != null) {
2514             for (HeatParameterDefinition heatParam : artifactInfo.getListHeatParameters()) {
2515                 String parameterType = heatParam.getType();
2516                 HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType);
2517                 String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType();
2518                 if (heatParameterType == null) {
2519                     ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam
2520                             .getType());
2521                     return Either.right(responseFormat);
2522                 }
2523
2524                 StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam);
2525                 if (validateAndUpdateProperty != StorageOperationStatus.OK) {
2526                     log.debug("Heat parameter {} is invalid. Status is {}", heatParam.getName(), validateAndUpdateProperty);
2527                     ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
2528                     ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam
2529                             .getType(), heatParam.getName());
2530                     return Either.right(responseFormat);
2531                 }
2532             }
2533         }
2534         return Either.left(artifactInfo);
2535     }
2536
2537     public List<ArtifactDefinition> getDeploymentArtifacts(Component parentComponent, NodeTypeEnum parentType, String ciId) {
2538         List<ArtifactDefinition> deploymentArtifacts = new ArrayList<>();
2539         if (parentComponent.getDeploymentArtifacts() != null) {
2540             if (NodeTypeEnum.ResourceInstance == parentType && ciId != null) {
2541                 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parentComponent, ciId, null, null, null);
2542                 if (getRI.isRight()) {
2543                     return deploymentArtifacts;
2544                 }
2545                 ComponentInstance ri = getRI.left().value();
2546                 if (ri.getDeploymentArtifacts() != null) {
2547                     deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values());
2548                 }
2549             }
2550             else if (parentComponent.getDeploymentArtifacts() != null) {
2551                 deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values());
2552             }
2553         }
2554         return deploymentArtifacts;
2555     }
2556
2557     private void checkCreateFields(User user, ArtifactDefinition artifactInfo, ArtifactGroupTypeEnum type) {
2558         // on create if null add informational to current
2559         if (artifactInfo.getArtifactGroupType() == null) {
2560             artifactInfo.setArtifactGroupType(type);
2561         }
2562         if (artifactInfo.getUniqueId() != null) {
2563             log.error("artifact uniqid cannot be set ignoring");
2564         }
2565         artifactInfo.setUniqueId(null);
2566
2567         if (artifactInfo.getArtifactRef() != null) {
2568             log.error("artifact ref cannot be set ignoring");
2569         }
2570         artifactInfo.setArtifactRef(null);
2571
2572         if (artifactInfo.getArtifactRepository() != null) {
2573             log.error("artifact repository cannot be set ignoring");
2574         }
2575         artifactInfo.setArtifactRepository(null);
2576
2577         if (artifactInfo.getUserIdCreator() != null) {
2578             log.error("creator uuid cannot be set ignoring");
2579         }
2580         artifactInfo.setArtifactCreator(user.getUserId());
2581
2582         if (artifactInfo.getUserIdLastUpdater() != null) {
2583             log.error("userId of last updater cannot be set ignoring");
2584         }
2585         artifactInfo.setUserIdLastUpdater(user.getUserId());
2586
2587         if (artifactInfo.getCreatorFullName() != null) {
2588             log.error("creator Full name cannot be set ignoring");
2589         }
2590         String fullName = user.getFirstName() + " " + user.getLastName();
2591         artifactInfo.setUpdaterFullName(fullName);
2592
2593         if (artifactInfo.getUpdaterFullName() != null) {
2594             log.error("updater Full name cannot be set ignoring");
2595         }
2596         artifactInfo.setUpdaterFullName(fullName);
2597
2598         if (artifactInfo.getCreationDate() != null) {
2599             log.error("Creation Date cannot be set ignoring");
2600         }
2601         long time = System.currentTimeMillis();
2602         artifactInfo.setCreationDate(time);
2603
2604         if (artifactInfo.getLastUpdateDate() != null) {
2605             log.error("Last Update Date cannot be set ignoring");
2606         }
2607         artifactInfo.setLastUpdateDate(time);
2608
2609         if (artifactInfo.getEsId() != null) {
2610             log.error("es id cannot be set ignoring");
2611         }
2612         artifactInfo.setEsId(null);
2613
2614     }
2615
2616
2617     private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) {
2618         String id = artifactId;
2619         if (artifactId == null || artifactId.isEmpty()) {
2620             String uniqueId = null;
2621             if (interfaceName != null && operationName != null) {
2622                 uniqueId = UniqueIdBuilder.buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo
2623                         .getArtifactLabel());
2624             }
2625             else {
2626                 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel());
2627             }
2628             artifactInfo.setUniqueId(uniqueId);
2629             artifactInfo.setEsId(uniqueId);
2630             id = uniqueId;
2631         }
2632         else {
2633             artifactInfo.setUniqueId(artifactId);
2634             artifactInfo.setEsId(artifactId);
2635         }
2636         return id;
2637     }
2638
2639     private Either<ActionStatus, ResponseFormat> validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2640         if (Strings.isNullOrEmpty(artifactInfo.getArtifactType())) {
2641             BeEcompErrorManager.getInstance()
2642                                .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
2643             log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName());
2644             return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2645         }
2646
2647         boolean artifactTypeExist = false;
2648         Either<List<ArtifactType>, ActionStatus> allArtifactTypes = null;
2649         ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType();
2650
2651         if ((artifactGroupType != null) && artifactGroupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) {
2652             allArtifactTypes = getDeploymentArtifactTypes(parentType);
2653         }
2654         else {
2655
2656             allArtifactTypes = elementOperation.getAllArtifactTypes();
2657         }
2658         if (allArtifactTypes.isRight()) {
2659             BeEcompErrorManager.getInstance()
2660                                .logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes
2661                                        .right()
2662                                        .value()
2663                                        .name());
2664             log.debug("Failed to retrieve list of suported artifact types. error: {}", allArtifactTypes.right()
2665                                                                                                        .value());
2666             return Either.right(componentsUtils.getResponseFormatByUserId(allArtifactTypes.right().value(), userId));
2667         }
2668
2669         for (ArtifactType type : allArtifactTypes.left().value()) {
2670             if (type.getName().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2671                 artifactInfo.setArtifactType(artifactInfo.getArtifactType().toUpperCase());
2672                 artifactTypeExist = true;
2673                 break;
2674             }
2675         }
2676
2677         if (!artifactTypeExist) {
2678             BeEcompErrorManager.getInstance()
2679                                .logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo
2680                                        .getArtifactType(), "Artifact " + artifactInfo.getArtifactName());
2681             log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType());
2682             return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2683                     .getArtifactType()));
2684         }
2685
2686         return Either.left(ActionStatus.OK);
2687     }
2688
2689     private Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(NodeTypeEnum parentType) {
2690
2691         Map<String, ArtifactTypeConfig> deploymentArtifacts ;
2692         List<ArtifactType> artifactTypes = new ArrayList<>();
2693
2694         if (parentType.equals(NodeTypeEnum.Service)) {
2695             deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2696                                                       .getConfiguration()
2697                                                       .getServiceDeploymentArtifacts();
2698         }
2699         else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2700             deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2701                                                       .getConfiguration()
2702                                                       .getResourceInstanceDeploymentArtifacts();
2703         }
2704         else {
2705             deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2706                                                       .getConfiguration()
2707                                                       .getResourceDeploymentArtifacts();
2708         }
2709         if (deploymentArtifacts != null) {
2710             for (String artifactType : deploymentArtifacts.keySet()) {
2711                 ArtifactType artifactT = new ArtifactType();
2712                 artifactT.setName(artifactType);
2713                 artifactTypes.add(artifactT);
2714             }
2715             return Either.left(artifactTypes);
2716         }
2717         else {
2718             return Either.right(ActionStatus.GENERAL_ERROR);
2719         }
2720
2721     }
2722
2723     private Either<Boolean, ResponseFormat> validateFirstUpdateHasPayload(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2724         if (currentArtifact.getEsId() == null && (artifactInfo.getPayloadData() == null || artifactInfo.getPayloadData().length == 0)) {
2725             return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD));
2726         }
2727         return Either.left(true);
2728
2729     }
2730
2731     private Either<Boolean, ResponseFormat> validateAndSetArtifactname(ArtifactDefinition artifactInfo) {
2732         if (artifactInfo.getArtifactName() == null || artifactInfo.getArtifactName().isEmpty()) {
2733             return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2734         }
2735
2736         String normalizeFileName = ValidationUtils.normalizeFileName(artifactInfo.getArtifactName());
2737         if (normalizeFileName == null || normalizeFileName.isEmpty()) {
2738             return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2739         }
2740         artifactInfo.setArtifactName(normalizeFileName);
2741
2742         if (!ValidationUtils.validateArtifactNameLength(artifactInfo.getArtifactName())) {
2743             return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH)));
2744         }
2745
2746         return Either.left(true);
2747     }
2748
2749     private Either<Boolean, ResponseFormat> validateArtifactTypeNotChanged(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2750         if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
2751             log.info("artifact type is missing operation ignored");
2752             return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2753         }
2754
2755         if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2756             log.info("artifact type cannot be changed operation ignored");
2757             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2758         }
2759         return Either.left(true);
2760     }
2761
2762     private Either<ArtifactDefinition, ResponseFormat> validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2763         if (artifactInfo.getArtifactGroupType() == null) {
2764             artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2765         }
2766
2767         else if (!currentArtifact.getArtifactGroupType()
2768                                  .getType()
2769                                  .equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) {
2770             log.info("artifact group type cannot be changed. operation failed");
2771             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2772         }
2773         return Either.left(artifactInfo);
2774     }
2775
2776     private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, ArtifactGroupTypeEnum type) {
2777
2778         // on update if null add informational to current
2779         if (currentArtifact.getArtifactGroupType() == null && type != null) {
2780             currentArtifact.setArtifactGroupType(type);
2781         }
2782
2783         if (artifactInfo.getUniqueId() != null && !currentArtifact.getUniqueId().equals(artifactInfo.getUniqueId())) {
2784             log.error("artifact uniqid cannot be set ignoring");
2785         }
2786         artifactInfo.setUniqueId(currentArtifact.getUniqueId());
2787
2788         if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef()
2789                                                                      .equals(artifactInfo.getArtifactRef())) {
2790             log.error("artifact ref cannot be set ignoring");
2791         }
2792         artifactInfo.setArtifactRef(currentArtifact.getArtifactRef());
2793
2794         if (artifactInfo.getArtifactRepository() != null && !currentArtifact.getArtifactRepository()
2795                                                                             .equals(artifactInfo.getArtifactRepository())) {
2796             log.error("artifact repository cannot be set ignoring");
2797         }
2798         artifactInfo.setArtifactRepository(currentArtifact.getArtifactRepository());
2799
2800         if (artifactInfo.getUserIdCreator() != null && !currentArtifact.getUserIdCreator()
2801                                                                        .equals(artifactInfo.getUserIdCreator())) {
2802             log.error("creator uuid cannot be set ignoring");
2803         }
2804         artifactInfo.setUserIdCreator(currentArtifact.getUserIdCreator());
2805
2806         if (artifactInfo.getArtifactCreator() != null && !currentArtifact.getArtifactCreator()
2807                                                                          .equals(artifactInfo.getArtifactCreator())) {
2808             log.error("artifact creator cannot be set ignoring");
2809         }
2810         artifactInfo.setArtifactCreator(currentArtifact.getArtifactCreator());
2811
2812         if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.getUserIdLastUpdater()
2813                                                                            .equals(artifactInfo.getUserIdLastUpdater())) {
2814             log.error("userId of last updater cannot be set ignoring");
2815         }
2816         artifactInfo.setUserIdLastUpdater(user.getUserId());
2817
2818         if (artifactInfo.getCreatorFullName() != null && !currentArtifact.getCreatorFullName()
2819                                                                          .equals(artifactInfo.getCreatorFullName())) {
2820             log.error("creator Full name cannot be set ignoring");
2821         }
2822         artifactInfo.setCreatorFullName(currentArtifact.getCreatorFullName());
2823
2824         if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.getUpdaterFullName()
2825                                                                          .equals(artifactInfo.getUpdaterFullName())) {
2826             log.error("updater Full name cannot be set ignoring");
2827         }
2828         String fullName = user.getFirstName() + " " + user.getLastName();
2829         artifactInfo.setUpdaterFullName(fullName);
2830
2831         if (artifactInfo.getCreationDate() != null && !currentArtifact.getCreationDate()
2832                                                                       .equals(artifactInfo.getCreationDate())) {
2833             log.error("Creation Date cannot be set ignoring");
2834         }
2835         artifactInfo.setCreationDate(currentArtifact.getCreationDate());
2836
2837         if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate()
2838                                                                         .equals(artifactInfo.getLastUpdateDate())) {
2839             log.error("Last Update Date cannot be set ignoring");
2840         }
2841         long time = System.currentTimeMillis();
2842         artifactInfo.setLastUpdateDate(time);
2843
2844         if (artifactInfo.getEsId() != null && !currentArtifact.getEsId().equals(artifactInfo.getEsId())) {
2845             log.error("es id cannot be set ignoring");
2846         }
2847         artifactInfo.setEsId(currentArtifact.getUniqueId());
2848
2849         if (artifactInfo.getArtifactDisplayName() != null && !currentArtifact.getArtifactDisplayName()
2850                                                                              .equals(artifactInfo.getArtifactDisplayName())) {
2851             log.error(" Artifact Display Name cannot be set ignoring");
2852         }
2853         artifactInfo.setArtifactDisplayName(currentArtifact.getArtifactDisplayName());
2854
2855         if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi()
2856                                                                     .equals(artifactInfo.getServiceApi())) {
2857             log.debug("serviceApi cannot be set. ignoring.");
2858         }
2859         artifactInfo.setServiceApi(currentArtifact.getServiceApi());
2860
2861         if (artifactInfo.getArtifactGroupType() != null && !currentArtifact.getArtifactGroupType()
2862                                                                            .equals(artifactInfo.getArtifactGroupType())) {
2863             log.debug("artifact group cannot be set. ignoring.");
2864         }
2865         artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2866
2867         artifactInfo.setArtifactVersion(currentArtifact.getArtifactVersion());
2868
2869         if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID()
2870                                                                    .isEmpty() && !currentArtifact.getArtifactUUID()
2871                                                                                                  .equals(artifactInfo.getArtifactUUID())) {
2872             log.debug("artifact UUID cannot be set. ignoring.");
2873         }
2874         artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID());
2875
2876         if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo
2877                 .getHeatParameters()
2878                 .isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) {
2879             checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters());
2880         }
2881     }
2882
2883     private void checkAndSetUnupdatableHeatParams(List<HeatParameterDefinition> heatParameters, List<HeatParameterDefinition> currentParameters) {
2884
2885         Map<String, HeatParameterDefinition> currentParametersMap = getMapOfParameters(currentParameters);
2886         for (HeatParameterDefinition parameter : heatParameters) {
2887             HeatParameterDefinition currentParam = currentParametersMap.get(parameter.getUniqueId());
2888
2889             if (currentParam != null) {
2890
2891                 if (parameter.getName() != null && !parameter.getName().equalsIgnoreCase(currentParam.getName())) {
2892                     log.debug("heat parameter name cannot be updated  ({}). ignoring.", parameter.getName());
2893                     parameter.setName(currentParam.getName());
2894                 }
2895                 if (parameter.getDefaultValue() != null && !parameter.getDefaultValue()
2896                                                                      .equalsIgnoreCase(currentParam.getDefaultValue())) {
2897                     log.debug("heat parameter defaultValue cannot be updated  ({}). ignoring.", parameter.getDefaultValue());
2898                     parameter.setDefaultValue(currentParam.getDefaultValue());
2899                 }
2900                 if (parameter.getType() != null && !parameter.getType().equalsIgnoreCase(currentParam.getType())) {
2901                     log.debug("heat parameter type cannot be updated  ({}). ignoring.", parameter.getType());
2902                     parameter.setType(currentParam.getType());
2903                 }
2904                 if (parameter.getDescription() != null && !parameter.getDescription()
2905                                                                     .equalsIgnoreCase(currentParam.getDescription())) {
2906                     log.debug("heat parameter description cannot be updated  ({}). ignoring.", parameter.getDescription());
2907                     parameter.setDescription(currentParam.getDescription());
2908                 }
2909
2910                 // check and set current value
2911                 if ((parameter.getCurrentValue() == null) && (currentParam.getDefaultValue() != null)) {
2912                     log.debug("heat parameter current value is null. set it to default value {}). ignoring.", parameter.getDefaultValue());
2913                     parameter.setCurrentValue(currentParam.getDefaultValue());
2914                 }
2915             }
2916         }
2917     }
2918
2919     private Map<String, HeatParameterDefinition> getMapOfParameters(List<HeatParameterDefinition> currentParameters) {
2920
2921         Map<String, HeatParameterDefinition> currentParamsMap = new HashMap<String, HeatParameterDefinition>();
2922         for (HeatParameterDefinition param : currentParameters) {
2923             currentParamsMap.put(param.getUniqueId(), param);
2924         }
2925         return currentParamsMap;
2926     }
2927
2928     private Either<Boolean, ResponseFormat> validateAndServiceApiUrl(ArtifactDefinition artifactInfo) {
2929         if (!ValidationUtils.validateStringNotEmpty(artifactInfo.getApiUrl())) {
2930             log.debug("Artifact url cannot be empty.");
2931             return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_URL));
2932         }
2933         artifactInfo.setApiUrl(artifactInfo.getApiUrl().toLowerCase());
2934
2935         if (!ValidationUtils.validateUrl(artifactInfo.getApiUrl())) {
2936             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_API_URL));
2937         }
2938         if (!ValidationUtils.validateUrlLength(artifactInfo.getApiUrl())) {
2939             return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH)));
2940         }
2941
2942         return Either.left(true);
2943     }
2944
2945     private Either<Boolean, ResponseFormat> validateAndCleanDescription(ArtifactDefinition artifactInfo) {
2946         if (artifactInfo.getDescription() == null || artifactInfo.getDescription().isEmpty()) {
2947             log.debug("Artifact description cannot be empty.");
2948             return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_DESCRIPTION));
2949         }
2950         String description = artifactInfo.getDescription();
2951         description = ValidationUtils.removeNoneUtf8Chars(description);
2952         description = ValidationUtils.normaliseWhitespace(description);
2953         description = ValidationUtils.stripOctets(description);
2954         description = ValidationUtils.removeHtmlTagsOnly(description);
2955         if (!ValidationUtils.validateIsEnglish(description)) {
2956             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2957         }
2958         if (!ValidationUtils.validateLength(description, ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)) {
2959             return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION, String
2960                     .valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)));
2961         }
2962         artifactInfo.setDescription(description);
2963         return Either.left(true);
2964     }
2965
2966     private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactFlow(org.openecomp.sdc.be.model.Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user, byte[] decodedPayload,
2967                                                                                              ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationUuid) {
2968         ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
2969         String prevArtifactId = null;
2970         String currArtifactId = artifactId;
2971
2972         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
2973         Either<ArtifactDefinition, Operation> insideEither = null;
2974
2975         log.trace("Try to update entry on graph");
2976         String artifactUniqueId = null;
2977         ArtifactDefinition artifactDefinition = artifactInfo;
2978         StorageOperationStatus error;
2979
2980         boolean isLeft;
2981         if (interfaceType == null || operationUuid == null) {
2982             log.debug("Entity on graph is updated. Update artifact in ES");
2983             boolean res = true;
2984             // Changing previous and current artifactId for auditing
2985             prevArtifactId = currArtifactId;
2986             currArtifactId = artifactDefinition.getUniqueId();
2987
2988
2989             if (decodedPayload == null) {
2990                 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
2991                     Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition
2992                             .getEsId());
2993                     if (artifactFromCassandra.isRight()) {
2994                         log.debug("Failed to get artifact data from ES for artifact id  {}", artifactId);
2995                         error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right()
2996                                 .value());
2997                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
2998                         handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2999                         resultOp = Either.right(responseFormat);
3000                         return resultOp;
3001                     }
3002                     // clone data to new artifact
3003                     artifactData.setData(artifactFromCassandra.left().value().getData());
3004                     artifactData.setId(artifactFromCassandra.left().value().getId());
3005                 }
3006             } else {
3007                 if (artifactDefinition.getEsId() == null) {
3008                     artifactDefinition.setEsId(artifactDefinition.getUniqueId());
3009                     artifactData.setId(artifactDefinition.getUniqueId());
3010                 }
3011             }
3012
3013             NodeTypeEnum convertParentType = convertParentType(componentType);
3014             Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.updateArtifactOnResource(artifactInfo, parent
3015                     .getUniqueId(), artifactId, convertParentType, parentId);
3016             isLeft = result.isLeft();
3017             if (isLeft) {
3018                 artifactUniqueId = result.left().value().getUniqueId();
3019                 artifactDefinition = result.left().value();
3020                 String artifactType = artifactInfo.getArtifactType();
3021                 if (NodeTypeEnum.Resource == convertParentType
3022                         && (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType)
3023                         || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType)
3024                         || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType))
3025                         && !artifactUniqueId.equals(artifactId)) {
3026                     // need to update the generated id in heat env
3027                     Map<String, ArtifactDefinition> deploymentArtifacts = parent.getDeploymentArtifacts();
3028                     Optional<Entry<String, ArtifactDefinition>> findFirst = deploymentArtifacts.entrySet()
3029                             .stream()
3030                             .filter(a -> a.getValue()
3031                                     .getGeneratedFromId() != null && a
3032                                     .getValue()
3033                                     .getGeneratedFromId()
3034                                     .equals(artifactId))
3035                             .findFirst();
3036                     if (findFirst.isPresent()) {
3037                         ArtifactDefinition artifactEnvInfo = findFirst.get().getValue();
3038                         artifactEnvInfo.setArtifactChecksum(null);
3039                         artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, artifactId, artifactUniqueId, convertParentType, parentId);
3040                     }
3041                 }
3042                 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
3043
3044                 insideEither = Either.left(result.left().value());
3045                 resultOp = Either.left(insideEither);
3046                 if (error != StorageOperationStatus.OK) {
3047                     isLeft = false;
3048                 }
3049
3050             } else {
3051                 error = result.right().value();
3052             }
3053             if (isLeft) {
3054
3055                 // create new entry in ES
3056                 res = true;
3057                 if (artifactData.getData() != null) {
3058                     if (!artifactDefinition.getDuplicated() || artifactData.getId() == null) {
3059                         artifactData.setId(artifactDefinition.getEsId());
3060                     }
3061                     res = saveArtifacts(artifactData, parentId);
3062
3063                 }
3064             }
3065
3066             if (res) {
3067                 log.debug(ARTIFACT_SAVED, artifactUniqueId);
3068                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3069                 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3070             } else {
3071                 BeEcompErrorManager.getInstance().logBeDaoSystemError(UPDATE_ARTIFACT);
3072                 log.debug(FAILED_SAVE_ARTIFACT);
3073                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3074                 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3075                 resultOp = Either.right(responseFormat);
3076             }
3077         } else {
3078             return updateArtifactsFlowForInterfaceOperations(parent, parentId, artifactId, artifactInfo, user,
3079                     decodedPayload, componentType, auditingAction, interfaceType, operationUuid, artifactData, prevArtifactId,
3080                     currArtifactId, artifactDefinition);
3081         }
3082
3083         return resultOp;
3084     }
3085
3086     private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactsFlowForInterfaceOperations(
3087             Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user,
3088             byte[] decodedPayload, ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType,
3089             String operationUuid, ESArtifactData artifactData, String prevArtifactId, String currArtifactId,
3090             ArtifactDefinition artifactDefinition) {
3091         StorageOperationStatus error;
3092         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp;
3093         if (decodedPayload == null) {
3094             if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
3095                 Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition
3096                         .getEsId());
3097                 if (artifactFromCassandra.isRight()) {
3098                     log.debug("Failed to get artifact data from ES for artifact id  {}", artifactId);
3099                     error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right()
3100                             .value());
3101                     ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
3102                     handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3103                     resultOp = Either.right(responseFormat);
3104                     return resultOp;
3105                 }
3106                 // clone data to new artifact
3107                 artifactData.setData(artifactFromCassandra.left().value().getData());
3108                 artifactData.setId(artifactFromCassandra.left().value().getId());
3109             } else {
3110                 // todo if not exist(first time)
3111             }
3112
3113         } else {
3114             if (artifactDefinition.getEsId() == null) {
3115                 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
3116                 artifactData.setId(artifactDefinition.getUniqueId());
3117             }
3118         }
3119         NodeTypeEnum convertParentType = convertParentType(componentType);
3120         // Set additional fields for artifact
3121         artifactInfo.setArtifactLabel(artifactInfo.getArtifactName());
3122         artifactInfo.setArtifactDisplayName(artifactInfo.getArtifactName());
3123
3124         Either<ArtifactDefinition, StorageOperationStatus> updateArtifactOnResourceEither =
3125                 artifactToscaOperation.updateArtifactOnResource(artifactInfo, parent.getUniqueId(), artifactId, convertParentType, parentId);
3126         if(updateArtifactOnResourceEither.isRight()){
3127             log.debug("Failed to persist operation artifact {} in resource, error is {}",artifactInfo.getArtifactName(), updateArtifactOnResourceEither.right().value());
3128             ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(updateArtifactOnResourceEither.right().value());
3129             return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse));
3130         }
3131         if (artifactData.getData() != null) {
3132             CassandraOperationStatus cassandraOperationStatus = artifactCassandraDao.saveArtifact(artifactData);
3133             if(cassandraOperationStatus != CassandraOperationStatus.OK){
3134                 log.debug("Failed to persist operation artifact {}, error is {}",artifactInfo.getArtifactName(),cassandraOperationStatus);
3135                 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(cassandraOperationStatus);
3136                 ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus);
3137                 return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse));
3138             }
3139         }
3140
3141         Either<ArtifactDefinition, ResponseFormat> updateOprEither = updateOperationArtifact(parentId, interfaceType, operationUuid, updateArtifactOnResourceEither.left().value());
3142         if(updateOprEither.isRight()){
3143             return Either.right(updateOprEither.right().value());
3144         }
3145
3146         return Either.left(Either.left(updateOprEither.left().value()));
3147     }
3148
3149     private Either<byte[], ResponseFormat> handlePayload(ArtifactDefinition artifactInfo, boolean isArtifactMetadataUpdate) {
3150         log.trace("Starting payload handling");
3151         byte[] payload = artifactInfo.getPayloadData();
3152         byte[] decodedPayload = null;
3153
3154         if (payload != null && payload.length != 0) {
3155             // the generated artifacts were already decoded by the handler
3156             decodedPayload = artifactInfo.getGenerated() ? payload : Base64.decodeBase64(payload);
3157             if (decodedPayload.length == 0) {
3158                 log.debug("Failed to decode the payload.");
3159                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3160                 return Either.right(responseFormat);
3161             }
3162
3163             String checkSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload);
3164             artifactInfo.setArtifactChecksum(checkSum);
3165             log.trace("Calculated checksum, base64 payload: {},  checksum: {}", payload, checkSum);
3166
3167             // Specific payload validations of different types
3168             Either<Boolean, ResponseFormat> result = Either.left(true);
3169             if (isDeploymentArtifact(artifactInfo)) {
3170                 log.trace("Starting deployment artifacts payload validation");
3171                 String artifactType = artifactInfo.getArtifactType();
3172                 String fileExtension = GeneralUtility.getFilenameExtension(artifactInfo.getArtifactName());
3173                 PayloadTypeEnum payloadType = ArtifactTypeToPayloadTypeSelector.getPayloadType(artifactType, fileExtension);
3174                 Either<Boolean, ActionStatus> isPayloadValid = payloadType.isValid(decodedPayload);
3175                 if (isPayloadValid.isRight()) {
3176                     ResponseFormat responseFormat = componentsUtils.getResponseFormat(isPayloadValid.right().value(), artifactType);
3177                     return Either.right(responseFormat);
3178                 }
3179
3180                 if (payloadType.isHeatRelated()) {
3181                     log.trace("Payload is heat related so going to extract heat parameters for artifact type {}", artifactType);
3182                     result = extractHeatParameters(artifactInfo);
3183                 }
3184             }
3185             if (result.isRight()) {
3186                 return Either.right(result.right().value());
3187             }
3188
3189         } // null/empty payload is normal if called from metadata update ONLY.
3190         // The validation of whether this is metadata/payload update case is
3191         // currently done separately
3192         else {
3193             if (!isArtifactMetadataUpdate) {
3194                 log.debug("In artifact: {} Payload is missing.",artifactInfo.getArtifactName());
3195                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
3196                 return Either.right(responseFormat);
3197             }
3198         }
3199         log.trace("Ended payload handling");
3200         return Either.left(decodedPayload);
3201     }
3202
3203     public Either<Operation, ResponseFormat> deleteArtifactByInterface(String resourceId, String userUserId, String artifactId,
3204                                                                        boolean inTransaction) {
3205         User user = new User();
3206         user.setUserId(userUserId);
3207         Either<Resource, StorageOperationStatus> parent = toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata);
3208         if (parent.isRight()) {
3209             ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(parent
3210                     .right()
3211                     .value()));
3212             return Either.right(responseFormat);
3213         }
3214         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = handleDelete(resourceId, artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, parent
3215                         .left()
3216                         .value(),
3217                 false, inTransaction);
3218         if (handleDelete.isRight()) {
3219             return Either.right(handleDelete.right().value());
3220         }
3221         Either<ArtifactDefinition, Operation> result = handleDelete.left().value();
3222         return Either.left(result.right().value());
3223
3224     }
3225
3226     private Operation convertToOperation(ArtifactDefinition artifactInfo, String operationName) {
3227         Operation op = new Operation();
3228         long time = System.currentTimeMillis();
3229         op.setCreationDate(time);
3230
3231         String artifactName = artifactInfo.getArtifactName();
3232         artifactInfo.setArtifactName(createInterfaceArtifactNameFromOperation(operationName, artifactName));
3233
3234         op.setImplementation(artifactInfo);
3235         op.setLastUpdateDate(time);
3236         return op;
3237     }
3238
3239     private String createInterfaceArtifactNameFromOperation(String operationName, String artifactName) {
3240         String newArtifactName = operationName + "_" + artifactName;
3241         log.trace("converting artifact name {} to {}", artifactName, newArtifactName);
3242         return newArtifactName;
3243     }
3244
3245     // download by MSO
3246     public Either<byte[], ResponseFormat> downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) {
3247
3248         // General validation
3249         if (serviceName == null || serviceVersion == null || resourceName == null || resourceVersion == null || artifactName == null) {
3250             log.debug(NULL_PARAMETER);
3251             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3252         }
3253
3254         // Normalizing artifact name
3255         artifactName = ValidationUtils.normalizeFileName(artifactName);
3256
3257         // Resource validation
3258         Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion);
3259         if (validateResourceNameAndVersion.isRight()) {
3260             return Either.right(validateResourceNameAndVersion.right().value());
3261         }
3262
3263         Resource resource = validateResourceNameAndVersion.left().value();
3264         String resourceId = resource.getUniqueId();
3265
3266         // Service validation
3267         Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3268         if (validateServiceNameAndVersion.isRight()) {
3269             return Either.right(validateServiceNameAndVersion.right().value());
3270         }
3271
3272         Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
3273         if (artifacts == null || artifacts.isEmpty()) {
3274             log.debug("Deployment artifacts of resource {} are not found", resourceId);
3275             return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3276         }
3277
3278         ArtifactDefinition deploymentArtifact = null;
3279
3280         for (ArtifactDefinition artifactDefinition : artifacts.values()) {
3281             if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName()
3282                                                                                   .equals(artifactName)) {
3283                 log.debug(FOUND_DEPLOYMENT_ARTIFACT, artifactName);
3284                 deploymentArtifact = artifactDefinition;
3285                 break;
3286             }
3287         }
3288
3289         if (deploymentArtifact == null) {
3290             log.debug("No deployment artifact {} was found for resource {}", artifactName, resourceId);
3291             return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3292         }
3293
3294         // Downloading the artifact
3295         Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact);
3296         if (downloadArtifactEither.isRight()) {
3297             log.debug(FAILED_DOWNLOAD_ARTIFACT, artifactName);
3298             return Either.right(downloadArtifactEither.right().value());
3299         }
3300         log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId());
3301         return Either.left(downloadArtifactEither.left().value().getRight());
3302     }
3303
3304     // download by MSO
3305     public Either<byte[], ResponseFormat> downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) {
3306
3307         // General validation
3308         if (serviceName == null || serviceVersion == null || resourceInstanceName == null || artifactName == null) {
3309             log.debug(NULL_PARAMETER);
3310             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3311         }
3312
3313         // Normalizing artifact name
3314         artifactName = ValidationUtils.normalizeFileName(artifactName);
3315
3316         // Service validation
3317         Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3318         if (validateServiceNameAndVersion.isRight()) {
3319             return Either.right(validateServiceNameAndVersion.right().value());
3320         }
3321
3322         Service service = validateServiceNameAndVersion.left().value();
3323
3324         // ResourceInstance validation
3325         Either<ComponentInstance, ResponseFormat> validateResourceInstance = validateResourceInstance(service, resourceInstanceName);
3326         if (validateResourceInstance.isRight()) {
3327             return Either.right(validateResourceInstance.right().value());
3328         }
3329
3330         ComponentInstance resourceInstance = validateResourceInstance.left().value();
3331
3332         Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3333
3334         final String finalArtifactName = artifactName;
3335         Predicate<ArtifactDefinition> filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName);
3336
3337         boolean hasDeploymentArtifacts = artifacts != null && artifacts.values()
3338                                                                        .stream()
3339                                                                        .anyMatch(filterArtifactByName);
3340         ArtifactDefinition deployableArtifact;
3341
3342         if (!hasDeploymentArtifacts) {
3343             log.debug("Deployment artifact with name {} not found", artifactName);
3344             return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3345         }
3346
3347         log.debug(FOUND_DEPLOYMENT_ARTIFACT, artifactName);
3348         deployableArtifact = artifacts.values().stream().filter(filterArtifactByName).findFirst().get();
3349         // Downloading the artifact
3350         Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deployableArtifact);
3351
3352         if (downloadArtifactEither.isRight()) {
3353             log.debug(FAILED_DOWNLOAD_ARTIFACT, artifactName);
3354             return Either.right(downloadArtifactEither.right().value());
3355         }
3356         log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId());
3357         return Either.left(downloadArtifactEither.left().value().getRight());
3358     }
3359
3360     private Either<ComponentInstance, ResponseFormat> validateResourceInstance(Service service, String resourceInstanceName) {
3361
3362         List<ComponentInstance> riList = service.getComponentInstances();
3363         for (ComponentInstance ri : riList) {
3364             if (ri.getNormalizedName().equals(resourceInstanceName)) {
3365                 return Either.left(ri);
3366             }
3367         }
3368
3369         return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, resourceInstanceName));
3370     }
3371
3372     private Either<Service, ResponseFormat> validateServiceNameAndVersion(String serviceName, String serviceVersion) {
3373
3374         Either<List<Service>, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName);
3375         if (serviceListBySystemName.isRight()) {
3376             log.debug("Couldn't fetch any service with name {}", serviceName);
3377             return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceListBySystemName
3378                     .right()
3379                     .value(), ComponentTypeEnum.SERVICE), serviceName));
3380         }
3381         List<Service> serviceList = serviceListBySystemName.left().value();
3382         if (serviceList == null || serviceList.isEmpty()) {
3383             log.debug("Couldn't fetch any service with name {}", serviceName);
3384             return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceName));
3385         }
3386
3387         Service foundService = null;
3388         for (Service service : serviceList) {
3389             if (service.getVersion().equals(serviceVersion)) {
3390                 log.trace("Found service with version {}", serviceVersion);
3391                 foundService = service;
3392                 break;
3393             }
3394         }
3395
3396         if (foundService == null) {
3397             log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName);
3398             return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE
3399                     .getValue(), serviceVersion));
3400         }
3401         return Either.left(foundService);
3402     }
3403
3404     private Either<Resource, ResponseFormat> validateResourceNameAndVersion(String resourceName, String resourceVersion) {
3405
3406         Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata);
3407         if (resourceListBySystemName.isRight()) {
3408             log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion);
3409             return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceListBySystemName
3410                     .right()
3411                     .value()), resourceName));
3412         }
3413         return Either.left(resourceListBySystemName.left().value());
3414     }
3415
3416     public Either<byte[], ResponseFormat> downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) {
3417         // Validation
3418         log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, artifactName);
3419         if (serviceName == null || serviceVersion == null || artifactName == null) {
3420             log.debug(NULL_PARAMETER);
3421             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3422         }
3423
3424         // Normalizing artifact name
3425         final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName);
3426
3427         // Service validation
3428         Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3429         if (validateServiceNameAndVersion.isRight()) {
3430             return Either.right(validateServiceNameAndVersion.right().value());
3431         }
3432
3433         String serviceId = validateServiceNameAndVersion.left().value().getUniqueId();
3434
3435         // Looking for deployment or tosca artifacts
3436         Service service = validateServiceNameAndVersion.left().value();
3437
3438         if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) {
3439             log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId);
3440             return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3441         }
3442
3443         Optional<ArtifactDefinition> foundArtifactOptl = null;
3444
3445         if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) {
3446             foundArtifactOptl = service.getDeploymentArtifacts().values().stream()
3447                                        // filters artifact by name
3448                                        .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3449         }
3450         if ((foundArtifactOptl == null || !foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) {
3451             foundArtifactOptl = service.getToscaArtifacts().values().stream()
3452                                        // filters TOSCA artifact by name
3453                                        .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3454         }
3455         if (!foundArtifactOptl.isPresent()) {
3456             log.debug("The artifact {} was not found for service {}", normalizedArtifactName, serviceId);
3457             return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3458         }
3459         log.debug(FOUND_DEPLOYMENT_ARTIFACT, normalizedArtifactName);
3460         // Downloading the artifact
3461         Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl
3462                 .get());
3463         if (downloadArtifactEither.isRight()) {
3464             log.debug(FAILED_DOWNLOAD_ARTIFACT, normalizedArtifactName);
3465             return Either.right(downloadArtifactEither.right().value());
3466         }
3467         log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId());
3468         return Either.left(downloadArtifactEither.left().value().getRight());
3469     }
3470
3471     public Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(String parentId, String artifactUniqueId) {
3472         log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId);
3473         Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactUniqueId);
3474         if (artifactById.isRight()) {
3475             ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
3476             log.debug("Error when getting artifact info by id{}, error: {}", artifactUniqueId, actionStatus);
3477             return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, ""));
3478         }
3479         ArtifactDefinition artifactDefinition = artifactById.left().value();
3480         if (artifactDefinition == null) {
3481             log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId);
3482             return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
3483         }
3484
3485         return downloadArtifact(artifactDefinition);
3486     }
3487
3488     private boolean checkArtifactInComponent(org.openecomp.sdc.be.model.Component component, String artifactId) {
3489         boolean found = false;
3490         Map<String, ArtifactDefinition> artifactsS = component.getArtifacts();
3491         if (artifactsS != null) {
3492             for (Map.Entry<String, ArtifactDefinition> entry : artifactsS.entrySet()) {
3493                 if (entry.getValue().getUniqueId().equals(artifactId)) {
3494                     found = true;
3495                     break;
3496                 }
3497             }
3498         }
3499         Map<String, ArtifactDefinition> deploymentArtifactsS = component.getDeploymentArtifacts();
3500         if (!found && deploymentArtifactsS != null) {
3501             for (Map.Entry<String, ArtifactDefinition> entry : deploymentArtifactsS.entrySet()) {
3502                 if (entry.getValue().getUniqueId().equals(artifactId)) {
3503                     found = true;
3504                     break;
3505                 }
3506             }
3507         }
3508         Map<String, ArtifactDefinition> toscaArtifactsS = component.getToscaArtifacts();
3509         if (!found && toscaArtifactsS != null) {
3510             for (Map.Entry<String, ArtifactDefinition> entry : toscaArtifactsS.entrySet()) {
3511                 if (entry.getValue().getUniqueId().equals(artifactId)) {
3512                     found = true;
3513                     break;
3514                 }
3515             }
3516         }
3517
3518         Map<String, InterfaceDefinition> interfaces = component.getInterfaces();
3519         if (!found && interfaces != null) {
3520             for (Map.Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) {
3521                 Map<String, Operation> operations = entry.getValue().getOperationsMap();
3522                 for (Map.Entry<String, Operation> entryOp : operations.entrySet()) {
3523                     if (entryOp.getValue().getImplementation() != null && entryOp.getValue()
3524                             .getImplementation()
3525                             .getUniqueId()
3526                             .equals(artifactId)) {
3527                         found = true;
3528                         break;
3529                     }
3530                 }
3531             }
3532         }
3533
3534         switch (component.getComponentType()) {
3535             case RESOURCE:
3536                 break;
3537             case SERVICE:
3538                 Map<String, ArtifactDefinition> apiArtifacts = ((Service) component).getServiceApiArtifacts();
3539                 if (!found && apiArtifacts != null) {
3540                     for (Map.Entry<String, ArtifactDefinition> entry : apiArtifacts.entrySet()) {
3541                         if (entry.getValue().getUniqueId().equals(artifactId)) {
3542                             found = true;
3543                             break;
3544                         }
3545                     }
3546                 }
3547                 break;
3548             default:
3549
3550         }
3551
3552         return found;
3553     }
3554
3555     private boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) {
3556
3557         boolean found = false;
3558         List<ComponentInstance> resourceInstances = component.getComponentInstances();
3559         ComponentInstance resourceInstance = null;
3560         for (ComponentInstance ri : resourceInstances) {
3561             if (ri.getUniqueId().equals(resourceInstanceId)) {
3562                 resourceInstance = ri;
3563                 break;
3564             }
3565         }
3566         if (resourceInstance != null) {
3567             Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3568             if (artifacts != null) {
3569                 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3570                     if (entry.getValue().getUniqueId().equals(artifactId)) {
3571                         found = true;
3572                         break;
3573                     }
3574                 }
3575             }
3576             if (!found) {
3577                 artifacts = resourceInstance.getArtifacts();
3578                 if (artifacts != null) {
3579                     for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3580                         if (entry.getValue().getUniqueId().equals(artifactId)) {
3581                             found = true;
3582                             break;
3583                         }
3584                     }
3585                 }
3586             }
3587         }
3588         return found;
3589     }
3590
3591     private Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists(String componentId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType,
3592                                                                                                            String containerComponentType) {
3593
3594         ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType);
3595         componentForAudit.getNodeType();
3596
3597         Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = toscaOperationFacade
3598                 .getToscaFullElement(componentId);
3599
3600         if (componentResult.isRight()) {
3601             ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentType == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND;
3602             ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId);
3603             log.debug("Service not found, serviceId {}", componentId);
3604             handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null);
3605             return Either.right(responseFormat);
3606         }
3607         return Either.left(componentResult.left().value());
3608     }
3609
3610     private Either<Boolean, ResponseFormat> validateWorkOnComponent(Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation) {
3611         if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD && !operation.ignoreLifecycleState()) {
3612             Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
3613             if (canWork.isRight()) {
3614                 String uniqueId = component.getUniqueId();
3615                 log.debug("Service status isn't  CHECKOUT or user isn't owner, serviceId {}", uniqueId);
3616                 handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, canWork.right()
3617                                                                                                          .value(), component
3618                         .getComponentType(), null);
3619                 return Either.right(canWork.right().value());
3620             }
3621         }
3622         return Either.left(true);
3623     }
3624
3625     private Either<Boolean, ResponseFormat> validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) {
3626
3627         if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD) {
3628             String role = user.getRole();
3629             if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) {
3630                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3631                 log.debug("addArtifact - user isn't permitted to perform operation, userId {}, role {}", user.getUserId(), role);
3632                 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
3633                 return Either.right(responseFormat);
3634             }
3635         }
3636         return Either.left(true);
3637     }
3638
3639     private Either<User, ResponseFormat> validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) {
3640         User user;
3641         try{
3642             user = validateUserExists(userId, auditingAction.getName(), inTransaction);
3643         } catch(ByResponseFormatComponentException e){
3644             ResponseFormat responseFormat = e.getResponseFormat();
3645             handleComponentException(auditingAction, componentId, artifactId, responseFormat, componentType, userId);
3646             throw e;
3647         } catch(ByActionStatusComponentException e){
3648             ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
3649             handleComponentException(auditingAction, componentId, artifactId, responseFormat, componentType, userId);
3650             throw e;
3651         }
3652         return Either.left(user);
3653     }
3654
3655     private void handleComponentException(AuditingActionEnum auditingAction, String componentId, String artifactId,
3656         ResponseFormat responseFormat, ComponentTypeEnum componentType, String userId){
3657         User user = new User();
3658         user.setUserId(userId);
3659         handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
3660     }
3661
3662     protected AuditingActionEnum detectAuditingType(ArtifactOperationInfo operation, String origMd5) {
3663         AuditingActionEnum auditingAction = null;
3664         switch (operation.getArtifactOperationEnum()) {
3665             case CREATE:
3666                 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD;
3667                 break;
3668             case UPDATE:
3669                 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE;
3670                 break;
3671             case DELETE:
3672                 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_DELETE_BY_API : AuditingActionEnum.ARTIFACT_DELETE;
3673                 break;
3674             case DOWNLOAD:
3675                 auditingAction = operation.isExternalApi() ? AuditingActionEnum.DOWNLOAD_ARTIFACT : AuditingActionEnum.ARTIFACT_DOWNLOAD;
3676                 break;
3677             default:
3678                 break;
3679         }
3680         return auditingAction;
3681     }
3682
3683     private Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(ArtifactDefinition artifactDefinition) {
3684         String esArtifactId = artifactDefinition.getEsId();
3685         Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3686         if (artifactfromES.isRight()) {
3687             CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3688             StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3689             ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3690             log.debug("Error when getting artifact from ES, error: {}", actionStatus);
3691             ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition
3692                     .getArtifactDisplayName());
3693
3694             return Either.right(responseFormat);
3695         }
3696
3697         ESArtifactData esArtifactData = artifactfromES.left().value();
3698         byte[] data = esArtifactData.getDataAsArray();
3699         if (data == null) {
3700             log.debug("Artifact data from ES is null");
3701             return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactDefinition.getArtifactDisplayName()));
3702         }
3703         String artifactName = artifactDefinition.getArtifactName();
3704         log.trace("Download of artifact succeeded, uniqueId {}, artifact file name {}", artifactDefinition.getUniqueId(), artifactName);
3705         return Either.left(new ImmutablePair<String, byte[]>(artifactName, data));
3706     }
3707
3708     public ESArtifactData createEsArtifactData(ArtifactDataDefinition artifactInfo, byte[] artifactPayload) {
3709         return new ESArtifactData(artifactInfo.getEsId(), artifactPayload);
3710     }
3711
3712     private boolean saveArtifacts(ESArtifactData artifactData, String resourceId) {
3713         CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData);
3714
3715         if (resourceUploadStatus.equals(CassandraOperationStatus.OK)) {
3716             log.debug("Artifact {} was saved in component .", artifactData.getId(), resourceId);
3717         }
3718         else {
3719             log.info("Failed to save artifact {}.", artifactData.getId());
3720             return false;
3721         }
3722         return true;
3723     }
3724
3725     private boolean isArtifactMetadataUpdate(AuditingActionEnum auditingActionEnum) {
3726         return auditingActionEnum.equals(AuditingActionEnum.ARTIFACT_METADATA_UPDATE);
3727     }
3728
3729     private boolean isDeploymentArtifact(ArtifactDefinition artifactInfo) {
3730         return ArtifactGroupTypeEnum.DEPLOYMENT.equals(artifactInfo.getArtifactGroupType());
3731     }
3732
3733     public Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) {
3734         Either<User, ActionStatus> user = userAdminManager.getUser(userUserId, inTransaction);
3735         if (user.isRight()) {
3736             ResponseFormat responseFormat;
3737             if (user.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
3738                 log.debug("create artifact placeholder - not authorized user, userId {}", userUserId);
3739                 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3740             }
3741             else {
3742                 log.debug("create artifact placeholder - failed to authorize user, userId {}", userUserId);
3743                 responseFormat = componentsUtils.getResponseFormat(user.right().value());
3744             }
3745             return Either.right(responseFormat);
3746         }
3747
3748         ArtifactDefinition artifactDefinition = createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user
3749                 .left()
3750                 .value(), groupType);
3751         return Either.left(artifactDefinition);
3752     }
3753
3754     public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, User user, ArtifactGroupTypeEnum groupType) {
3755         ArtifactDefinition artifactInfo = new ArtifactDefinition();
3756
3757         String artifactName = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME);
3758         String artifactType = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_TYPE);
3759         String artifactDescription = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DESCRIPTION);
3760
3761         artifactInfo.setArtifactDisplayName(artifactName);
3762         artifactInfo.setArtifactLabel(logicalName.toLowerCase());
3763         artifactInfo.setArtifactType(artifactType);
3764         artifactInfo.setDescription(artifactDescription);
3765         artifactInfo.setArtifactGroupType(groupType);
3766         nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo);
3767
3768         setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo);
3769
3770         return artifactInfo;
3771     }
3772
3773     private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) {
3774         String uniqueId = null;
3775
3776         if (resourceId != null) {
3777             uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel()
3778                                                                                                    .toLowerCase());
3779             artifactInfo.setUniqueId(uniqueId);
3780         }
3781         artifactInfo.setUserIdCreator(user.getUserId());
3782         String fullName = user.getFullName();
3783         artifactInfo.setUpdaterFullName(fullName);
3784
3785         long time = System.currentTimeMillis();
3786
3787         artifactInfo.setCreatorFullName(fullName);
3788         artifactInfo.setCreationDate(time);
3789
3790         artifactInfo.setLastUpdateDate(time);
3791         artifactInfo.setUserIdLastUpdater(user.getUserId());
3792
3793         artifactInfo.setMandatory(true);
3794     }
3795
3796     public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, ArtifactGroupTypeEnum groupType, String instanceId) {
3797         return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId);
3798     }
3799
3800     public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String componentId, NodeTypeEnum parentType, String instanceId) {
3801         return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, componentId, parentType, true, instanceId);
3802     }
3803
3804     private Either<ESArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) {
3805
3806         byte[] payload = payloadStr.getBytes();
3807
3808         ESArtifactData artifactData = createEsArtifactData(artifactDefinition, payload);
3809         return Either.left(artifactData);
3810     }
3811
3812     /**
3813      * @param artifactDefinition
3814      * @return
3815      */
3816     public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3817                                                                               String instanceId, boolean shouldLock, boolean inTransaction) {
3818         String payload = generateHeatEnvPayload(artifactDefinition);
3819         String prevUUID = artifactDefinition.getArtifactUUID();
3820         ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3821         return generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction)
3822                 .left()
3823                 .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
3824     }
3825
3826     public Either<ArtifactDefinition, ResponseFormat> forceGenerateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3827                                                                                    boolean shouldLock, boolean inTransaction, String instanceId) {
3828         String payload = generateHeatEnvPayload(artifactDefinition);
3829         String prevUUID = artifactDefinition.getArtifactUUID();
3830         ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3831         return forceGenerateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction)
3832                 .left()
3833                 .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
3834     }
3835
3836     private Either<ArtifactDefinition, ResponseFormat> updateArtifactOnGroupInstance(ComponentTypeEnum componentType, Component component, String instanceId, String prevUUID, ArtifactDefinition clonedBeforeGenerate, ArtifactDefinition updatedArtDef) {
3837         if (prevUUID == null || !prevUUID.equals(updatedArtDef.getArtifactUUID())) {
3838             List<ComponentInstance> componentInstances = component.getComponentInstances();
3839             if (componentInstances != null) {
3840                 Optional<ComponentInstance> findFirst = componentInstances.stream()
3841                                                                           .filter(ci -> ci.getUniqueId()
3842                                                                                           .equals(instanceId))
3843                                                                           .findFirst();
3844                 if (findFirst.isPresent()) {
3845                     ComponentInstance relevantInst = findFirst.get();
3846                     List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst
3847                             .getGroupInstances());
3848
3849                     if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
3850                         updatedGroupInstances.forEach(gi -> {
3851                             gi.getGroupInstanceArtifacts().add(updatedArtDef.getUniqueId());
3852                             gi.getGroupInstanceArtifactsUuid().add(updatedArtDef.getArtifactUUID());
3853                         });
3854                         Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, instanceId, updatedGroupInstances);
3855                         if (status.isRight()) {
3856                             log.debug(FAILED_UPDATE_GROUPS, component.getUniqueId());
3857                             ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils
3858                                     .convertFromStorageResponse(status.right()
3859                                                                       .value()), clonedBeforeGenerate.getArtifactDisplayName());
3860                             return Either.right(responseFormat);
3861                         }
3862                     }
3863                 }
3864             }
3865         }
3866         return Either.left(updatedArtDef);
3867     }
3868
3869     private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) {
3870         List<HeatParameterDefinition> heatParameters = artifactDefinition.getListHeatParameters();
3871         StringBuilder sb = new StringBuilder();
3872         sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
3873         sb.append("parameters:\n");
3874         if (heatParameters != null) {
3875             heatParameters.sort(Comparator.comparing(e -> e.getName()));
3876
3877             List<HeatParameterDefinition> empltyHeatValues = new ArrayList<>();
3878
3879             for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
3880
3881                 String heatValue = heatParameterDefinition.getCurrentValue();
3882                 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3883                     heatValue = heatParameterDefinition.getDefaultValue();
3884                     if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3885                         empltyHeatValues.add(heatParameterDefinition);
3886                         continue;
3887                     }
3888                 }
3889                 HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType());
3890                 if (type != null) {
3891                     switch (type) {
3892                         case BOOLEAN:
3893                             sb.append("  ")
3894                               .append(heatParameterDefinition.getName())
3895                               .append(":")
3896                               .append(" ")
3897                               .append(Boolean.parseBoolean(heatValue))
3898                               .append("\n");
3899                             break;
3900                         case NUMBER:
3901                             sb.append("  ")
3902                               .append(heatParameterDefinition.getName())
3903                               .append(":")
3904                               .append(" ")
3905                               .append(new BigDecimal(heatValue).toPlainString())
3906                               .append("\n");
3907                             break;
3908                         case COMMA_DELIMITED_LIST:
3909                         case JSON:
3910                             sb.append("  ")
3911                               .append(heatParameterDefinition.getName())
3912                               .append(":")
3913                               .append(" ")
3914                               .append(heatValue)
3915                               .append("\n");
3916                             break;
3917                         default:
3918                             String value = heatValue;
3919                             boolean starts = value.startsWith("\"");
3920                             boolean ends = value.endsWith("\"");
3921                             if (!(starts && ends)) {
3922                                 starts = value.startsWith("'");
3923                                 ends = value.endsWith("'");
3924                                 if (!(starts && ends)) {
3925                                     value = "\"" + value + "\"";
3926                                 }
3927                             }
3928                             sb.append("  ")
3929                               .append(heatParameterDefinition.getName())
3930                               .append(":")
3931                               .append(" ")
3932                               .append(value);
3933                             sb.append("\n");
3934                             break;
3935
3936                     }
3937                 }
3938             }
3939             if (!empltyHeatValues.isEmpty()) {
3940                 empltyHeatValues.sort(Comparator.comparing(e -> e.getName()));
3941                 empltyHeatValues.forEach(hv -> {
3942                     sb.append("  ").append(hv.getName()).append(":");
3943                     HeatParameterType type = HeatParameterType.isValidType(hv.getType());
3944                     if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv
3945                             .getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) {
3946                         sb.append(" \"\"").append("\n");
3947                     }
3948                     else {
3949                         sb.append(" ").append("\n");
3950                     }
3951                 });
3952             }
3953         }
3954         sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
3955
3956         // DE265919 fix
3957         return sb.toString().replaceAll("\\\\n", "\n");
3958     }
3959
3960     /**
3961      * @param artifactDefinition
3962      * @param payload
3963      * @return
3964      */
3965     public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
3966                                                                                      User modifier, String instanceId, boolean shouldLock, boolean inTransaction) {
3967         return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, () -> artifactDefinition
3968                         .getHeatParamsUpdateDate(),
3969                 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
3970
3971     }
3972
3973     public Either<ArtifactDefinition, ResponseFormat> forceGenerateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
3974                                                                                           User modifier, String instanceId, boolean shouldLock, boolean inTransaction) {
3975         return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, System::currentTimeMillis,
3976                 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
3977
3978     }
3979
3980     protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3981                                                                                  boolean shouldLock, boolean inTransaction, Supplier<Long> payloadUpdateDateGen, Supplier<Either<ESArtifactData, ResponseFormat>> esDataCreator, String instanceId) {
3982
3983         log.trace("Start generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition
3984                 .getEsId());
3985         if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition
3986                 .getPayloadUpdateDate() <= payloadUpdateDateGen.get()) {
3987
3988             log.trace("Generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3989             Either<ESArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get();
3990             ESArtifactData artifactData = null;
3991
3992             if (artifactDataRes.isLeft()) {
3993                 artifactData = artifactDataRes.left().value();
3994             }
3995             else {
3996                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3997                 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
3998                                 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3999                         ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4000
4001                 return Either.right(artifactDataRes.right().value());
4002             }
4003             String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(artifactData.getDataAsArray());
4004             String oldCheckSum;
4005             String esArtifactId = artifactDefinition.getEsId();
4006             Either<ESArtifactData, CassandraOperationStatus> artifactfromES;
4007             ESArtifactData esArtifactData;
4008             if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) {
4009                 log.debug("Try to fetch artifact from cassandra with id : {}", esArtifactId);
4010                 artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
4011                 if (artifactfromES.isRight()) {
4012                     CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
4013                     StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
4014                     ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
4015                     log.debug("Error when getting artifact from ES, error: {} esid : {}", actionStatus, esArtifactId);
4016                     return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
4017                 }
4018                 esArtifactData = artifactfromES.left().value();
4019                 oldCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(esArtifactData.getDataAsArray());
4020             }
4021             else {
4022                 oldCheckSum = artifactDefinition.getArtifactChecksum();
4023
4024             }
4025             Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus = null;
4026
4027             if (shouldLock) {
4028                 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock resource: ");
4029                 if (lockComponent.isRight()) {
4030                     handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition
4031                             .getUniqueId(), lockComponent.right().value(), component.getComponentType(), null);
4032                     return Either.right(lockComponent.right().value());
4033                 }
4034             }
4035             try {
4036                 if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) {
4037
4038                     artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get());
4039                     updateArifactDefinitionStatus = artifactToscaOperation.updateArtifactOnResource(artifactDefinition, component
4040                             .getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
4041                     log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition
4042                             .getArtifactType(), artifactDefinition.getEsId());
4043                     if (updateArifactDefinitionStatus.isRight()) {
4044                         ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
4045                                 .right()
4046                                 .value()), artifactDefinition.getArtifactDisplayName());
4047                         log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId());
4048                         handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4049                                         .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4050                                 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4051
4052                         return Either.right(responseFormat);
4053                     }
4054                 }
4055                 else {
4056
4057                     oldCheckSum = artifactDefinition.getArtifactChecksum();
4058                     artifactDefinition.setArtifactChecksum(newCheckSum);
4059                     artifactDefinition.setEsId(artifactDefinition.getUniqueId());
4060                     log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition
4061                             .getArtifactType(), artifactDefinition.getEsId());
4062                     updateArifactDefinitionStatus = artifactToscaOperation.updateArtifactOnResource(artifactDefinition, component
4063                             .getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
4064
4065                     log.trace("Update Payload  ", artifactDefinition.getEsId());
4066                 }
4067                 if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) {
4068
4069                     artifactDefinition = updateArifactDefinitionStatus.left().value();
4070                     artifactData.setId(artifactDefinition.getUniqueId());
4071                     CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
4072
4073                     if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) {
4074                         if (!inTransaction) {
4075                             titanDao.commit();
4076                         }
4077                         log.debug("Artifact Saved In ES {}", artifactData.getId());
4078                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4079                         handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4080                                         .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4081                                 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4082
4083                     }
4084                     else {
4085                         if (!inTransaction) {
4086                             titanDao.rollback();
4087                         }
4088                         log.info("Failed to save artifact {}.", artifactData.getId());
4089                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4090                         handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4091                                         .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4092                                 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4093
4094                         return Either.right(responseFormat);
4095                     }
4096                 }
4097                 else {
4098                     ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
4099                             .right()
4100                             .value()), artifactDefinition.getArtifactDisplayName());
4101                     log.debug("Failed To update artifact {}", artifactData.getId());
4102                     handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4103                                     .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4104                             ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4105
4106                     return Either.right(responseFormat);
4107
4108                 }
4109             }
4110             finally {
4111                 if (shouldLock) {
4112                     graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType()
4113                                                                                          .getNodeType());
4114                 }
4115             }
4116         }
4117
4118         return Either.left(artifactDefinition);
4119     }
4120
4121
4122     public Map<String, Object> buildJsonForUpdateArtifact(ArtifactDefinition artifactDef, ArtifactGroupTypeEnum artifactGroupType, List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
4123         return this.buildJsonForUpdateArtifact(artifactDef.getUniqueId(), artifactDef.getArtifactName(), artifactDef.getArtifactType(), artifactGroupType, artifactDef
4124                         .getArtifactLabel(), artifactDef.getArtifactDisplayName(),
4125                 artifactDef.getDescription(), artifactDef.getPayloadData(), updatedRequiredArtifacts, artifactDef.getListHeatParameters());
4126
4127     }
4128
4129     public Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContent,
4130                                                           List<ArtifactTemplateInfo> updatedRequiredArtifacts, List<HeatParameterDefinition> heatParameters) {
4131
4132         Map<String, Object> json = new HashMap<>();
4133         if (artifactId != null && !artifactId.isEmpty()) {
4134             json.put(Constants.ARTIFACT_ID, artifactId);
4135         }
4136
4137         json.put(Constants.ARTIFACT_NAME, artifactName);
4138         json.put(Constants.ARTIFACT_TYPE, artifactType);
4139         json.put(Constants.ARTIFACT_DESCRIPTION, description);
4140
4141         if (artifactContent != null) {
4142             log.debug("payload is encoded. perform decode");
4143             String encodedPayload = Base64.encodeBase64String(artifactContent);
4144             json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
4145         }
4146         json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
4147         json.put(Constants.ARTIFACT_LABEL, label);
4148         json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType());
4149         json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>()
4150                 : updatedRequiredArtifacts.stream()
4151                                           .filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e
4152                                                   .getType()
4153                                                   .equals(ArtifactTypeEnum.HEAT_NESTED.getType()))
4154                                           .map(e -> e.getFileName())
4155                                           .collect(Collectors.toList()));
4156         json.put(Constants.ARTIFACT_HEAT_PARAMS, (heatParameters == null || heatParameters.isEmpty()) ? new ArrayList<>()
4157                 : heatParameters);
4158         return json;
4159     }
4160
4161     public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateResourceInstanceArtifactNoContent(String resourceId, Component containerComponent, User user, Map<String, Object> json, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo) {
4162
4163         String jsonStr = gson.toJson(json);
4164         ArtifactDefinition artifactDefinitionFromJson = artifactInfo == null ? RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class) : artifactInfo;
4165         String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId();
4166         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = validateAndHandleArtifact(resourceId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactUniqueId,
4167                 artifactDefinitionFromJson, null, jsonStr, null, null, user, containerComponent, false, false, true);
4168         if (uploadArtifactToService.isRight()) {
4169             return Either.right(uploadArtifactToService.right().value());
4170         }
4171
4172         return Either.left(uploadArtifactToService.left().value());
4173     }
4174
4175     private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
4176                                                                                               org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
4177         convertParentType(componentType);
4178         String parentId = parent.getUniqueId();
4179         ArtifactDefinition currArtifact = artifactInfo;
4180
4181         if (origMd5 != null) {
4182             Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
4183             if (validateMd5.isRight()) {
4184                 ResponseFormat responseFormat = validateMd5.right().value();
4185                 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4186                 return Either.right(responseFormat);
4187             }
4188
4189             if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
4190                 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parent, componentId, false, artifactInfo, currArtifact, NodeTypeEnum.ResourceInstance);
4191                 if (deploymentValidationResult.isRight()) {
4192                     ResponseFormat responseFormat = deploymentValidationResult.right().value();
4193                     handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4194                     return Either.right(responseFormat);
4195                 }
4196
4197                 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
4198                 if (payloadEither.isRight()) {
4199                     ResponseFormat responseFormat = payloadEither.right().value();
4200                     handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4201                     return Either.right(responseFormat);
4202                 }
4203             }
4204             else { // duplicate
4205                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
4206                 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4207                 return Either.right(responseFormat);
4208             }
4209         }
4210
4211         // lock resource
4212         if (shouldLock) {
4213             Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, UPDATE_ARTIFACT_LOCK);
4214             if (lockComponent.isRight()) {
4215                 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
4216                                                                                                             .value(), componentType, null);
4217                 return Either.right(lockComponent.right().value());
4218             }
4219         }
4220         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
4221         try {
4222             resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, origMd5);
4223             return resultOp;
4224
4225         }
4226         finally {
4227             // unlock resource
4228             if (resultOp == null || resultOp.isRight()) {
4229                 log.debug(ROLLBACK);
4230                 if (!inTransaction) {
4231                     titanDao.rollback();
4232                 }
4233             }
4234             else {
4235                 log.debug(COMMIT);
4236                 if (!inTransaction) {
4237                     titanDao.commit();
4238                 }
4239             }
4240             if (shouldLock) {
4241                 componentType = parent.getComponentType();
4242             }
4243             NodeTypeEnum nodeType = componentType.getNodeType();
4244             graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
4245         }
4246     }
4247
4248     private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatEnvParams(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent,
4249                                                                                               ComponentTypeEnum componentType, String origMd5) {
4250
4251         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
4252         Either<ArtifactDefinition, Operation> insideEither = null;
4253         Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user);
4254         if (getRI.isRight()) {
4255             return Either.right(getRI.right().value());
4256         }
4257         ComponentInstance ri = getRI.left().value();
4258         Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, ri, componentId, artifactId, auditingAction, user);
4259         if (getArtifactRes.isRight()) {
4260             return Either.right(getArtifactRes.right().value());
4261         }
4262         ArtifactDefinition currArtifact = getArtifactRes.left().value();
4263
4264         if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType()
4265                                                                                                   .equals(ArtifactTypeEnum.HEAT_VOL
4266                                                                                                           .getType()) || currArtifact
4267                 .getArtifactType()
4268                 .equals(ArtifactTypeEnum.HEAT_NET.getType())) {
4269             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
4270             handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4271                     .getName());
4272             return Either.right(responseFormat);
4273         }
4274         List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters();
4275         List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getListHeatParameters();
4276         new ArrayList<HeatParameterDefinition>();
4277
4278         // upload
4279         if (origMd5 != null) {
4280             Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, artifactId, componentType, ri
4281                             .getName(), currentHeatEnvParams,
4282                     updatedHeatEnvParams, currArtifact.getArtifactName());
4283             if (uploadParamsValidationResult.isRight()) {
4284                 ResponseFormat responseFormat = uploadParamsValidationResult.right().value();
4285                 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4286                         .getName());
4287                 return Either.right(responseFormat);
4288             }
4289             artifactInfo.setListHeatParameters(updatedHeatEnvParams);
4290         }
4291
4292         Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV
4293                 .getType());
4294         if (validateAndConvertHeatParamers.isRight()) {
4295             ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
4296             handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4297                     .getName());
4298             return Either.right(responseFormat);
4299         }
4300
4301         if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) {
4302             // fill reduced heat env parameters List for updating
4303             replaceCurrHeatValueWithUpdatedValue(currentHeatEnvParams, updatedHeatEnvParams);
4304             currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
4305             currArtifact.setListHeatParameters(currentHeatEnvParams);
4306
4307             Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactToscaOperation.updateArtifactOnResource(currArtifact, parent
4308                     .getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId);
4309             if (updateArifactRes.isRight()) {
4310                 log.debug("Failed to update artifact on graph  - {}", artifactId);
4311                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes
4312                         .right()
4313                         .value()));
4314                 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4315                         .getName());
4316                 return Either.right(responseFormat);
4317             }
4318             StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType);
4319             if (error != StorageOperationStatus.OK) {
4320                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
4321                 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4322                         .getName());
4323                 return Either.right(responseFormat);
4324             }
4325
4326             error = generateCustomizationUUIDOnGroupInstance(ri, updateArifactRes.left()
4327                                                                                  .value()
4328                                                                                  .getUniqueId(), parent.getUniqueId());
4329             if (error != StorageOperationStatus.OK) {
4330                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
4331                 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4332                         .getName());
4333                 return Either.right(responseFormat);
4334             }
4335
4336         }
4337         insideEither = Either.left(currArtifact);
4338         resultOp = Either.left(insideEither);
4339         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4340         handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri
4341                 .getName());
4342         return resultOp;
4343     }
4344
4345     private void replaceCurrHeatValueWithUpdatedValue(List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams) {
4346         for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
4347             String paramName = heatEnvParam.getName();
4348             for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4349                 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4350                     String updatedParamValue = heatEnvParam.getCurrentValue();
4351                     currHeatParam.setCurrentValue(updatedParamValue);
4352                 }
4353             }
4354         }
4355     }
4356
4357     private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent,
4358                                                                                            ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, boolean needToUpdateGroup) {
4359
4360         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp;
4361         Either<ArtifactDefinition, Operation> insideEither = null;
4362         String currentHeatId = currHeatArtifact.getUniqueId();
4363
4364         String esArtifactId = currHeatArtifact.getEsId();
4365         Either<ESArtifactData, CassandraOperationStatus> artifactFromES = artifactCassandraDao.getArtifact(esArtifactId);
4366         if (artifactFromES.isRight()) {
4367             CassandraOperationStatus resourceUploadStatus = artifactFromES.right().value();
4368             StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
4369             ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
4370             log.debug("Error when getting artifact from ES, error: {}", actionStatus);
4371             return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, currHeatArtifact.getArtifactDisplayName()));
4372         }
4373
4374         ESArtifactData esArtifactData = artifactFromES.left().value();
4375
4376         ArtifactDefinition updatedHeatArt = currHeatArtifact;
4377
4378         List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters();
4379         List<HeatParameterDefinition> currentHeatEnvParams = currHeatArtifact.getListHeatParameters();
4380         List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
4381
4382         if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams
4383                 .isEmpty()) {
4384
4385             String paramName;
4386             for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
4387
4388                 paramName = heatEnvParam.getName();
4389                 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4390                     if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4391
4392                         String updatedParamValue = heatEnvParam.getCurrentValue();
4393                         if (updatedParamValue == null) {
4394                             updatedParamValue = heatEnvParam.getDefaultValue();
4395                         }
4396                         HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
4397                         if (!paramType.getValidator().isValid(updatedParamValue, null)) {
4398                             ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
4399                             ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV
4400                                     .getType(), paramType.getType(), paramName);
4401                             handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactEnvInfo, null, artifactId, responseFormat, componentType, "");
4402                             return Either.right(responseFormat);
4403
4404                         }
4405                         currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
4406                         newHeatEnvParams.add(currHeatParam);
4407                         break;
4408                     }
4409                 }
4410             }
4411             if (!newHeatEnvParams.isEmpty()) {
4412                 currHeatArtifact.setListHeatParameters(currentHeatEnvParams);
4413                 Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArtifactOnResource(currHeatArtifact, parent
4414                         .getUniqueId(), currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId);
4415
4416                 if (operationStatus.isRight()) {
4417                     log.debug("Failed to update artifact on graph  - {}", currHeatArtifact.getUniqueId());
4418
4419                     ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus
4420                             .right()
4421                             .value()));
4422                     return Either.right(responseFormat);
4423
4424                 }
4425                 updatedHeatArt = operationStatus.left().value();
4426                 boolean res = true;
4427                 if (!updatedHeatArt.getDuplicated() || esArtifactData.getId() == null) {
4428                     esArtifactData.setId(updatedHeatArt.getEsId());
4429                 }
4430                 res = saveArtifacts(esArtifactData, parent.getUniqueId());
4431
4432                 if (res) {
4433                     log.debug(ARTIFACT_SAVED, updatedHeatArt.getUniqueId());
4434                     ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4435                     handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt
4436                             .getUniqueId(), responseFormat, componentType, null);
4437                 }
4438                 else {
4439                     BeEcompErrorManager.getInstance().logBeDaoSystemError(UPDATE_ARTIFACT);
4440                     log.debug(FAILED_SAVE_ARTIFACT);
4441                     ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4442                     handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt
4443                             .getUniqueId(), responseFormat, componentType, null);
4444                     resultOp = Either.right(responseFormat);
4445                 }
4446
4447                 insideEither = Either.left(updatedHeatArt);
4448             }
4449         }
4450         Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact;
4451         if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) {
4452             artifactEnvInfo.setArtifactChecksum(null);
4453             updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt
4454                     .getUniqueId(), componentType.getNodeType(), componentId);
4455         }
4456         else {
4457             updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType
4458                     .getNodeType());
4459
4460         }
4461         if (needToUpdateGroup && updateHeatEnvArtifact.isLeft()) {
4462             ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact
4463                     .left()
4464                     .value(), parent, componentType);
4465             if (result != ActionStatus.OK) {
4466                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(result);
4467                 return Either.right(responseFormat);
4468             }
4469         }
4470
4471         if (updatedHeatEnvParams.isEmpty()) {
4472             return getResponseAndAuditInvalidEmptyHeatEnvFile(auditingAction, parent, user, currHeatArtifact, artifactId, componentType);
4473         }
4474         resultOp = Either.left(insideEither);
4475         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4476         handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4477         return resultOp;
4478
4479     }
4480
4481     private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> getResponseAndAuditInvalidEmptyHeatEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition currHeatArtifact, String artifactId, ComponentTypeEnum componentType) {
4482         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, currHeatArtifact.getArtifactName());
4483         handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4484         return Either.right(responseFormat);
4485     }
4486
4487
4488     private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) {
4489         StorageOperationStatus error = StorageOperationStatus.OK;
4490         log.debug("Need to re-generate  customization UUID for group instance on component instance  {}", ri.getUniqueId());
4491         List<GroupInstance> groupsInstances = ri.getGroupInstances();
4492         List<String> groupInstancesId = null;
4493         if (groupsInstances != null && !groupsInstances.isEmpty()) {
4494             groupInstancesId = groupsInstances.stream()
4495                                               .filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts()
4496                                                                                                      .contains(artifactId))
4497                                               .map(GroupInstanceDataDefinition::getUniqueId)
4498                                               .collect(Collectors.toList());
4499         }
4500         if (groupInstancesId != null && !groupInstancesId.isEmpty()) {
4501             toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId);
4502         }
4503         return error;
4504
4505     }
4506
4507     public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType,
4508                                                                                                  String riName, List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams, String currArtifactName) {
4509
4510         if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) {
4511             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo
4512                     .getArtifactName(), currArtifactName);
4513             handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4514             return Either.right(responseFormat);
4515         }
4516
4517         for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) {
4518             String paramName = uploadedHeatParam.getName();
4519             boolean isExistsInHeat = false;
4520             for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4521                 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4522
4523                     isExistsInHeat = true;
4524                     uploadedHeatParam.setType(currHeatParam.getType());
4525                     uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue());
4526                     uploadedHeatParam.setDefaultValue(currHeatParam.getDefaultValue());
4527                     uploadedHeatParam.setUniqueId(currHeatParam.getUniqueId());
4528                     break;
4529                 }
4530             }
4531             if (!isExistsInHeat) {
4532                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName);
4533                 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4534                 return Either.right(responseFormat);
4535             }
4536         }
4537         return Either.left(updatedHeatEnvParams);
4538     }
4539
4540     private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4541         ResponseFormat responseFormat = null;
4542         List<ComponentInstance> ris = component.getComponentInstances();
4543         for (ComponentInstance ri : ris) {
4544             if (riID.equals(ri.getUniqueId())) {
4545                 return Either.left(ri);
4546             }
4547         }
4548         responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, riID);
4549         log.debug("Resource Instance not found, resourceInstanceId {}", riID);
4550         handleAuditing(auditingAction, null, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, null);
4551         return Either.right(responseFormat);
4552     }
4553
4554     private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4555         ResponseFormat responseFormat = null;
4556         Map<String, ArtifactDefinition> rtifactsMap = ri.getDeploymentArtifacts();
4557         for (ArtifactDefinition artifact : rtifactsMap.values()) {
4558             if (artifactId.equals(artifact.getUniqueId())) {
4559                 return Either.left(artifact);
4560             }
4561         }
4562         responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId());
4563         handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri
4564                 .getName());
4565         return Either.right(responseFormat);
4566     }
4567
4568     public ArtifactDefinition extractArtifactDefinition(Either<ArtifactDefinition, Operation> eitherArtifact) {
4569         ArtifactDefinition ret;
4570         if (eitherArtifact.isLeft()) {
4571             ret = eitherArtifact.left().value();
4572         }
4573         else {
4574             ret = eitherArtifact.right().value().getImplementationArtifact();
4575         }
4576         return ret;
4577     }
4578
4579     /**
4580      * downloads artifact of component by UUIDs
4581      *
4582      * @param componentType
4583      * @param componentUuid
4584      * @param artifactUUID
4585      * @param resourceCommonInfo
4586      * @return
4587      */
4588     public Either<byte[], ResponseFormat> downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo) {
4589         Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4590         Either<byte[], ResponseFormat> result;
4591         byte[] downloadedArtifact = null;
4592         Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
4593         if (errorWrapper.isEmpty() && component != null) {
4594             resourceCommonInfo.setResourceName(component.getName());
4595             downloadedArtifact = downloadArtifact(component.getAllArtifacts(), artifactUUID, errorWrapper, component.getName());
4596         }
4597         if (errorWrapper.isEmpty()) {
4598             result = Either.left(downloadedArtifact);
4599         }
4600         else {
4601             result = Either.right(errorWrapper.getInnerElement());
4602         }
4603         return result;
4604     }
4605
4606     /**
4607      * downloads an artifact of resource instance of component by UUIDs
4608      *
4609      * @param componentType
4610      * @param componentUuid
4611      * @param resourceInstanceName
4612      * @param artifactUUID
4613      * @return
4614      */
4615     public Either<byte[], ResponseFormat> downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID) {
4616         Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4617         Either<byte[], ResponseFormat> result;
4618         byte[] downloadedArtifact = null;
4619         ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4620         if (errorWrapper.isEmpty()) {
4621             downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance
4622                     .getName());
4623         }
4624         if (errorWrapper.isEmpty()) {
4625             result = Either.left(downloadedArtifact);
4626         }
4627         else {
4628             result = Either.right(errorWrapper.getInnerElement());
4629         }
4630         return result;
4631     }
4632
4633     /**
4634      * uploads an artifact to a component by UUID
4635      *
4636      * @param data
4637      * @param request
4638      * @param componentType
4639      * @param componentUuid
4640      * @param resourceCommonInfo
4641      * @param operation
4642      * @return
4643      */
4644     public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, ResourceCommonInfo resourceCommonInfo,ArtifactOperationInfo operation) {
4645         Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4646         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4647         Component component = null;
4648         String componentId = null;
4649         ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4650         String origMd5 = request.getHeader(Constants.MD5_HEADER);
4651         String userId = request.getHeader(Constants.USER_ID_HEADER);
4652
4653         Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4654         if (getComponentRes.isRight()) {
4655             StorageOperationStatus status = getComponentRes.right().value();
4656             log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status);
4657             errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4658         }
4659         if (errorWrapper.isEmpty()) {
4660             componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4661             String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4662
4663             if (!getComponentRes.left()
4664                     .value()
4665                     .getMetadataDataDefinition()
4666                     .getState()
4667                     .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4668                 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4669                 if (component != null) {
4670                     componentId = component.getUniqueId();
4671                     componentName = component.getName();
4672                 }
4673             }
4674             resourceCommonInfo.setResourceName(componentName);
4675         }
4676         if (errorWrapper.isEmpty()) {
4677             actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null);
4678             if (actionResult.isRight()) {
4679                 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
4680                         .right()
4681                         .value());
4682                 return Either.right(actionResult.right().value());
4683             }
4684             return Either.left(actionResult.left().value().left().value());
4685         }
4686         return Either.right(errorWrapper.getInnerElement());
4687     }
4688     /**
4689      * upload an artifact to a resource instance by UUID
4690      *
4691      * @param data
4692      * @param request
4693      * @param componentType
4694      * @param componentUuid
4695      * @param resourceInstanceName
4696      * @param operation
4697      * @return
4698      */
4699     public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
4700                                                                                 ArtifactOperationInfo operation) {
4701         Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4702         Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4703         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4704         ArtifactDefinition uploadArtifact = null;
4705         Component component = null;
4706         String componentInstanceId;
4707         String componentId;
4708         String origMd5 = request.getHeader(Constants.MD5_HEADER);
4709         String userId = request.getHeader(Constants.USER_ID_HEADER);
4710
4711         ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4712         Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4713         if (getComponentRes.isRight()) {
4714             StorageOperationStatus status = getComponentRes.right().value();
4715             log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4716             errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName));
4717         }
4718         if (errorWrapper.isEmpty() && !getComponentRes.left()
4719                                                       .value()
4720                                                       .getMetadataDataDefinition()
4721                                                       .getState()
4722                                                       .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4723             component = checkoutParentComponent(componentType, getComponentRes.left()
4724                                                                               .value()
4725                                                                               .getMetadataDataDefinition()
4726                                                                               .getUniqueId(), userId, errorWrapper);
4727         }
4728         if (errorWrapper.isEmpty()) {
4729             if (component == null) {
4730                 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4731             }
4732             else {
4733                 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4734             }
4735         }
4736         if (errorWrapper.isEmpty()) {
4737             componentInstanceId = componentRiPair.getRight().getUniqueId();
4738             componentId = componentRiPair.getLeft().getUniqueId();
4739             ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4740
4741             actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum
4742                     .findParamByType(componentType));
4743             if (actionResult.isRight()) {
4744                 log.debug(FAILED_UPLOAD_ARTIFACT_TO_INSTANCE, resourceInstanceName, componentType, componentUuid, actionResult
4745                         .right()
4746                         .value());
4747                 errorWrapper.setInnerElement(actionResult.right().value());
4748             }
4749         }
4750         if (errorWrapper.isEmpty()) {
4751             uploadArtifact = actionResult.left().value().left().value();
4752             uploadArtifactResult = Either.left(uploadArtifact);
4753         }
4754         else {
4755             uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4756         }
4757         return uploadArtifactResult;
4758     }
4759
4760     /**
4761      * updates an artifact on a component by UUID
4762      *
4763      * @param data
4764      * @param request
4765      * @param componentType
4766      * @param componentUuid
4767      * @param artifactUUID
4768      * @param operation
4769      * @return
4770      */
4771     public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID,
4772                                                                                       ResourceCommonInfo resourceCommonInfo, ArtifactOperationInfo operation) {
4773         Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4774         Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4775         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4776         ArtifactDefinition updateArtifact = null;
4777         Component component = null;
4778         String componentId = null;
4779         String artifactId = null;
4780         ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
4781         String origMd5 = request.getHeader(Constants.MD5_HEADER);
4782         String userId = request.getHeader(Constants.USER_ID_HEADER);
4783
4784         Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4785         if (getComponentRes.isRight()) {
4786             StorageOperationStatus status = getComponentRes.right().value();
4787             log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4788             errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4789         }
4790         if (errorWrapper.isEmpty()) {
4791             componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4792             String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4793
4794             if (!getComponentRes.left()
4795                                 .value()
4796                                 .getMetadataDataDefinition()
4797                                 .getState()
4798                                 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4799                 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4800                 if (component != null) {
4801                     componentId = component.getUniqueId();
4802                     componentName = component.getName();
4803                 }
4804             }
4805             resourceCommonInfo.setResourceName(componentName);
4806         }
4807         if (errorWrapper.isEmpty()) {
4808             artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4809         }
4810         if (errorWrapper.isEmpty()) {
4811             actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null);
4812             if (actionResult.isRight()) {
4813                 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
4814                         .right()
4815                         .value());
4816                 errorWrapper.setInnerElement(actionResult.right().value());
4817             }
4818         }
4819         if (errorWrapper.isEmpty()) {
4820             updateArtifact = actionResult.left().value().left().value();
4821             updateArtifactResult = Either.left(updateArtifact);
4822
4823         }
4824         else {
4825             updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4826         }
4827         return updateArtifactResult;
4828     }
4829
4830     /**
4831      * updates an artifact on a resource instance by UUID
4832      *
4833      * @param data
4834      * @param request
4835      * @param componentType
4836      * @param componentUuid
4837      * @param resourceInstanceName
4838      * @param artifactUUID
4839      * @param operation            TODO
4840      * @return
4841      */
4842     public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4843                                                                                 ArtifactOperationInfo operation) {
4844
4845         Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4846         Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4847         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4848         ArtifactDefinition updateArtifact = null;
4849         Component component = null;
4850         String componentInstanceId = null;
4851         String componentId = null;
4852         String artifactId = null;
4853         String origMd5 = request.getHeader(Constants.MD5_HEADER);
4854         String userId = request.getHeader(Constants.USER_ID_HEADER);
4855
4856         ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4857         Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4858         if (getComponentRes.isRight()) {
4859             StorageOperationStatus status = getComponentRes.right().value();
4860             log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4861             errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4862         }
4863         if (errorWrapper.isEmpty() && !getComponentRes.left()
4864                                                       .value()
4865                                                       .getMetadataDataDefinition()
4866                                                       .getState()
4867                                                       .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4868             component = checkoutParentComponent(componentType, getComponentRes.left()
4869                                                                               .value()
4870                                                                               .getMetadataDataDefinition()
4871                                                                               .getUniqueId(), userId, errorWrapper);
4872         }
4873         if (errorWrapper.isEmpty()) {
4874             if (component == null) {
4875                 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4876             }
4877             else {
4878                 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4879             }
4880         }
4881         if (errorWrapper.isEmpty()) {
4882             componentInstanceId = componentRiPair.getRight().getUniqueId();
4883             componentId = componentRiPair.getLeft().getUniqueId();
4884             artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
4885         }
4886         if (errorWrapper.isEmpty()) {
4887             ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4888
4889             actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum
4890                     .findParamByType(componentType));
4891             if (actionResult.isRight()) {
4892                 log.debug(FAILED_UPLOAD_ARTIFACT_TO_INSTANCE, resourceInstanceName, componentType, componentUuid, actionResult
4893                         .right()
4894                         .value());
4895                 errorWrapper.setInnerElement(actionResult.right().value());
4896             }
4897         }
4898         if (errorWrapper.isEmpty()) {
4899             updateArtifact = actionResult.left().value().left().value();
4900             updateArtifactResult = Either.left(updateArtifact);
4901         }
4902         else {
4903             updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4904         }
4905         return updateArtifactResult;
4906     }
4907
4908     private Either<ArtifactDefinition, ResponseFormat> updateOperationArtifact(String componentId, String interfaceType, String operationUuid, ArtifactDefinition artifactInfo){
4909         Either<Component, StorageOperationStatus> componentStorageOperationStatusEither = toscaOperationFacade.getToscaElement(componentId);
4910         if (componentStorageOperationStatusEither.isRight()) {
4911             StorageOperationStatus errorStatus = componentStorageOperationStatusEither.right().value();
4912             log.debug("Failed to fetch resource information by resource id, error {}", errorStatus);
4913             return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
4914         }
4915         Component storedComponent = componentStorageOperationStatusEither.left().value();
4916
4917         Optional<InterfaceDefinition> optionalInterface = InterfaceOperationUtils.getInterfaceDefinitionFromComponentByInterfaceType(storedComponent, interfaceType);
4918         if(!optionalInterface.isPresent()) {
4919             log.debug("Failed to get resource interface for resource Id {}", componentId);
4920             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceType));
4921         }
4922
4923         //fetch the operation from storage
4924         InterfaceDefinition gotInterface = optionalInterface.get();
4925         Map<String, Operation> operationsMap = gotInterface.getOperationsMap();
4926         Optional<Operation> optionalOperation = operationsMap.values()
4927                                                         .stream()
4928                                                         .filter(o -> o.getUniqueId().equals(operationUuid))
4929                                                         .findFirst();
4930         if (!optionalOperation.isPresent()) {
4931             log.debug("Failed to get resource interface operation for resource Id {} and operationId {}", componentId, operationUuid);
4932             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, componentId);
4933             return Either.right(responseFormat);
4934         }
4935
4936         Operation operation = optionalOperation.get();
4937         ArtifactDefinition implementationArtifact =  operation.getImplementationArtifact();
4938         implementationArtifact.setArtifactUUID(artifactInfo.getArtifactUUID());
4939         implementationArtifact.setUniqueId(artifactInfo.getUniqueId());
4940         implementationArtifact.setArtifactName(artifactInfo.getArtifactName());
4941         implementationArtifact.setDescription(artifactInfo.getDescription());
4942         implementationArtifact.setArtifactType(artifactInfo.getArtifactType());
4943         implementationArtifact.setArtifactLabel(artifactInfo.getArtifactLabel());
4944         implementationArtifact.setArtifactDisplayName(artifactInfo.getArtifactDisplayName());
4945         implementationArtifact.setEsId(artifactInfo.getEsId());
4946         operation.setImplementation(implementationArtifact);
4947         gotInterface.setOperationsMap(operationsMap);
4948         Either<List<InterfaceDefinition>, StorageOperationStatus> interfaceDefinitionStorageOperationStatusEither =
4949                 interfaceOperation.updateInterfaces(storedComponent.getUniqueId(), Collections.singletonList(gotInterface));
4950         if (interfaceDefinitionStorageOperationStatusEither.isRight()){
4951             StorageOperationStatus storageOperationStatus = interfaceDefinitionStorageOperationStatusEither.right().value();
4952             ActionStatus actionStatus =
4953                     componentsUtils.convertFromStorageResponseForDataType(storageOperationStatus);
4954             return Either.right(componentsUtils.getResponseFormat(actionStatus));
4955         }
4956
4957         return Either.left(artifactInfo);
4958     }
4959
4960     /**
4961      * updates an artifact on a component by UUID
4962      *
4963      * @param data
4964      * @param request
4965      * @param componentType
4966      * @param componentUuid
4967      * @param artifactUUID
4968      * @param operation
4969      * @return
4970      */
4971     public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnInterfaceOperationByResourceUUID(
4972             String data, HttpServletRequest request, ComponentTypeEnum componentType,
4973             String componentUuid, String interfaceUUID, String operationUUID, String artifactUUID,
4974         ResourceCommonInfo resourceCommonInfo,ArtifactOperationInfo operation) {
4975         Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4976         Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4977         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4978         ArtifactDefinition updateArtifact = null;
4979         String componentId = null;
4980         ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
4981         String origMd5 = request.getHeader(Constants.MD5_HEADER);
4982         String userId = request.getHeader(Constants.USER_ID_HEADER);
4983         ArtifactDefinition existingArtifactInfo = null;
4984         String interfaceName = null;
4985
4986         Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4987         if (getComponentRes.isRight()) {
4988             StorageOperationStatus status = getComponentRes.right().value();
4989             log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4990             errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4991         }
4992
4993         if (errorWrapper.isEmpty()) {
4994             componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4995             String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4996             if (!getComponentRes.left()
4997                     .value()
4998                     .getMetadataDataDefinition()
4999                     .getState()
5000                     .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
5001                 Component component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
5002                 if (component != null) {
5003                     componentId = component.getUniqueId();
5004                     componentName = component.getName();
5005                 }
5006
5007             }
5008             resourceCommonInfo.setResourceName(componentName);
5009         }
5010
5011         if(errorWrapper.isEmpty()){
5012             Either<String, ResponseFormat> interfaceNameEither = fetchInterfaceName(componentId, interfaceUUID);
5013             if (interfaceNameEither.isRight()) {
5014                 errorWrapper.setInnerElement(interfaceNameEither.right().value());
5015             }
5016             else {
5017                 interfaceName = interfaceNameEither.left().value();
5018             }
5019
5020             if(errorWrapper.isEmpty()){
5021                 Either<Component, StorageOperationStatus> toscaComponentEither = toscaOperationFacade.getToscaElement(componentId);
5022                 if (toscaComponentEither.isRight()) {
5023                     StorageOperationStatus status = toscaComponentEither.right().value();
5024                     log.debug("Could not fetch component with type {} and id {}. Status is {}. ", componentType, componentId, status);
5025                     errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5026                 }
5027
5028                 if (errorWrapper.isEmpty()) {
5029                     NodeTypeEnum parentType = convertParentType(componentType);
5030                     List<ArtifactDefinition> existingDeploymentArtifacts = getDeploymentArtifacts(toscaComponentEither.left().value(), parentType,null);
5031                     for (ArtifactDefinition artifactDefinition: existingDeploymentArtifacts){
5032                         if(artifactInfo.getArtifactName().equalsIgnoreCase(artifactDefinition.getArtifactName())){
5033                             existingArtifactInfo = artifactDefinition;
5034                             break;
5035                         }
5036                     }
5037                     if(existingArtifactInfo != null){
5038                         return updateOperationArtifact(componentId, interfaceName, operationUUID, existingArtifactInfo);
5039                     }
5040                 }
5041             }
5042         }
5043
5044         if (errorWrapper.isEmpty()) {
5045             actionResult = handleArtifactRequest(componentId, userId, componentType, operation,
5046                     artifactUUID, artifactInfo, origMd5, data, interfaceName,
5047                     operationUUID, null, null);
5048             if (actionResult.isRight()) {
5049                 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
5050                                                                                                      .right()
5051                                                                                                      .value());
5052                 errorWrapper.setInnerElement(actionResult.right().value());
5053             }
5054         }
5055
5056         if (errorWrapper.isEmpty()) {
5057             updateArtifact = actionResult.left().value().left().value();
5058             updateArtifactResult = Either.left(updateArtifact);
5059
5060         }
5061         else {
5062             updateArtifactResult = Either.right(errorWrapper.getInnerElement());
5063         }
5064         return updateArtifactResult;
5065     }
5066
5067     private Either<String, ResponseFormat> fetchInterfaceName(String componentId, String interfaceUUID) {
5068         Either<Component, StorageOperationStatus> componentStorageOperationStatusEither = toscaOperationFacade.getToscaElement(componentId);
5069         if (componentStorageOperationStatusEither.isRight()) {
5070             StorageOperationStatus errorStatus = componentStorageOperationStatusEither.right().value();
5071             log.debug("Failed to fetch component information by component id, error {}", errorStatus);
5072             return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
5073         }
5074         Component storedComponent = componentStorageOperationStatusEither.left().value();
5075
5076         Optional<InterfaceDefinition> optionalInterface = InterfaceOperationUtils
5077             .getInterfaceDefinitionFromComponentByInterfaceId(storedComponent, interfaceUUID);
5078         if(!optionalInterface.isPresent()) {
5079             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceUUID));
5080         }
5081         return Either.left(optionalInterface.get().getType());
5082     }
5083
5084
5085     /**
5086      * deletes an artifact on a component by UUID
5087      *
5088      * @param request
5089      * @param componentType
5090      * @param componentUuid
5091      * @param artifactUUID
5092      * @param resourceCommonInfo
5093      * @param operation        TODO
5094      * @return
5095      */
5096     public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo,
5097                                                                                       ArtifactOperationInfo operation) {
5098
5099         Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5100         Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
5101         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
5102         ArtifactDefinition deleteArtifact = null;
5103         Component component = null;
5104         String componentId = null;
5105         String artifactId = null;
5106         String origMd5 = request.getHeader(Constants.MD5_HEADER);
5107         String userId = request.getHeader(Constants.USER_ID_HEADER);
5108
5109         Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
5110         if (getComponentRes.isRight()) {
5111             StorageOperationStatus status = getComponentRes.right().value();
5112             log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5113             errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
5114         }
5115         if (errorWrapper.isEmpty()) {
5116             componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
5117             String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
5118             if (!getComponentRes.left()
5119                                 .value()
5120                                 .getMetadataDataDefinition()
5121                                 .getState()
5122                                 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
5123                 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
5124                 if (component != null) {
5125                     componentId = component.getUniqueId();
5126                     componentName = component.getName();
5127                 }
5128             }
5129             resourceCommonInfo.setResourceName(componentName);
5130         }
5131         if (errorWrapper.isEmpty()) {
5132             artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
5133         }
5134         if (errorWrapper.isEmpty()) {
5135             actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null);
5136             if (actionResult.isRight()) {
5137                 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
5138                         .right()
5139                         .value());
5140                 errorWrapper.setInnerElement(actionResult.right().value());
5141             }
5142         }
5143         if (errorWrapper.isEmpty()) {
5144             deleteArtifact = actionResult.left().value().left().value();
5145             deleteArtifactResult = Either.left(deleteArtifact);
5146         }
5147         else {
5148             deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
5149         }
5150         return deleteArtifactResult;
5151     }
5152
5153     /**
5154      * deletes an artifact from a resource instance by UUID
5155      *
5156      * @param request
5157      * @param componentType
5158      * @param componentUuid
5159      * @param resourceInstanceName
5160      * @param artifactUUID
5161      * @param operation            TODO
5162      * @return
5163      */
5164     public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
5165                                                                                ArtifactOperationInfo operation) {
5166
5167         Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5168         Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
5169         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
5170         ArtifactDefinition deleteArtifact = null;
5171         Component component = null;
5172         String componentInstanceId = null;
5173         String componentId = null;
5174         String artifactId = null;
5175         String origMd5 = request.getHeader(Constants.MD5_HEADER);
5176         String userId = request.getHeader(Constants.USER_ID_HEADER);
5177         ImmutablePair<Component, ComponentInstance> componentRiPair = null;
5178         Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
5179         if (getComponentRes.isRight()) {
5180             StorageOperationStatus status = getComponentRes.right().value();
5181             log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5182             errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5183         }
5184         if (errorWrapper.isEmpty() && !getComponentRes.left()
5185                                                       .value()
5186                                                       .getMetadataDataDefinition()
5187                                                       .getState()
5188                                                       .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
5189             component = checkoutParentComponent(componentType, getComponentRes.left()
5190                                                                               .value()
5191                                                                               .getMetadataDataDefinition()
5192                                                                               .getUniqueId(), userId, errorWrapper);
5193         }
5194         if (errorWrapper.isEmpty()) {
5195             if (component == null) {
5196                 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
5197             }
5198             else {
5199                 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
5200             }
5201         }
5202         if (errorWrapper.isEmpty()) {
5203             componentInstanceId = componentRiPair.getRight().getUniqueId();
5204             componentId = componentRiPair.getLeft().getUniqueId();
5205             artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
5206         }
5207         if (errorWrapper.isEmpty()) {
5208
5209             actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum
5210                     .findParamByType(componentType));
5211
5212             if (actionResult.isRight()) {
5213                 log.debug(FAILED_UPLOAD_ARTIFACT_TO_INSTANCE, resourceInstanceName, componentType, componentUuid, actionResult
5214                         .right()
5215                         .value());
5216                 errorWrapper.setInnerElement(actionResult.right().value());
5217             }
5218         }
5219         if (errorWrapper.isEmpty()) {
5220             deleteArtifact = actionResult.left().value().left().value();
5221             deleteArtifactResult = Either.left(deleteArtifact);
5222         }
5223         else {
5224             deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
5225         }
5226         return deleteArtifactResult;
5227     }
5228
5229     private String findArtifactId(ComponentInstance instance, String artifactUUID, Wrapper<ResponseFormat> errorWrapper) {
5230         String artifactId = null;
5231         ArtifactDefinition foundArtifact = null;
5232         if (instance.getDeploymentArtifacts() != null) {
5233             foundArtifact = instance.getDeploymentArtifacts()
5234                                     .values()
5235                                     .stream()
5236                                     .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID()
5237                                                                                  .equals(artifactUUID))
5238                                     .findFirst()
5239                                     .orElse(null);
5240         }
5241         if (foundArtifact == null && instance.getArtifacts() != null) {
5242             foundArtifact = instance.getArtifacts()
5243                                     .values()
5244                                     .stream()
5245                                     .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID()
5246                                                                                  .equals(artifactUUID))
5247                                     .findFirst()
5248                                     .orElse(null);
5249         }
5250         if (foundArtifact == null) {
5251             log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId());
5252             errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
5253         }
5254         else {
5255             artifactId = foundArtifact.getUniqueId();
5256         }
5257         return artifactId;
5258     }
5259
5260     @SuppressWarnings("unchecked")
5261     public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition heatArtifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
5262                                                                                Map<String, String> existingEnvVersions) {
5263         Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
5264                                                                               .getConfiguration()
5265                                                                               .getDeploymentResourceInstanceArtifacts();
5266         if (deploymentResourceArtifacts == null) {
5267             log.debug("no deployment artifacts are configured for generated artifacts");
5268             return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
5269         }
5270         Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(envType);
5271         if (placeHolderData == null) {
5272             log.debug("no env type {} are configured for generated artifacts", envType);
5273             return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
5274         }
5275
5276         String envLabel = (heatArtifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
5277         Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentId, envLabel, placeHolderData, user
5278                 .getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true);
5279         if (createArtifactPlaceHolder.isRight()) {
5280             return Either.right(createArtifactPlaceHolder.right().value());
5281         }
5282         ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value();
5283         artifactHeatEnv.setGeneratedFromId(heatArtifact.getUniqueId());
5284         artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
5285         artifactHeatEnv.setTimeout(0);
5286         buildHeatEnvFileName(heatArtifact, artifactHeatEnv, placeHolderData);
5287         // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow
5288         handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions);
5289         ArtifactDefinition heatEnvPlaceholder;
5290         // Evg : for resource instance artifact will be added later as block with other env artifacts from BL
5291         if (parentType != NodeTypeEnum.ResourceInstance) {
5292             Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, heatArtifact, component
5293                     .getUniqueId(), parentType, parentId);
5294             if (addHeatEnvArtifact.isRight()) {
5295                 log.debug("failed to create heat env artifact on resource instance");
5296                 return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact
5297                         .right()
5298                         .value(), false), "", null));
5299             }
5300             heatEnvPlaceholder = createArtifactPlaceHolder.left().value();
5301         }
5302         else {
5303             heatEnvPlaceholder = artifactHeatEnv;
5304             artifactToscaOperation.generateUUID(heatEnvPlaceholder, heatEnvPlaceholder.getArtifactVersion());
5305             setHeatCurrentValuesOnHeatEnvDefaultValues(heatArtifact, heatEnvPlaceholder);
5306         }
5307
5308         ComponentTypeEnum componentType = component.getComponentType();
5309         if (parentType == NodeTypeEnum.ResourceInstance) {
5310             componentType = ComponentTypeEnum.RESOURCE_INSTANCE;
5311         }
5312         componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, AuditingActionEnum.ARTIFACT_UPLOAD,
5313                 new ResourceCommonInfo(parentName, componentType.getValue()),
5314                 ResourceVersionInfo.newBuilder().build(),
5315                 ResourceVersionInfo.newBuilder().artifactUuid(heatEnvPlaceholder.getUniqueId()).build(),
5316                 null, heatEnvPlaceholder, null);
5317         return Either.left(heatEnvPlaceholder);
5318     }
5319
5320     private void setHeatCurrentValuesOnHeatEnvDefaultValues(ArtifactDefinition artifact, ArtifactDefinition artifactDefinition) {
5321         if (artifact.getListHeatParameters() == null) {
5322             return;
5323         }
5324         List<HeatParameterDefinition> heatEnvParameters = new ArrayList<>();
5325         for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) {
5326             HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter);
5327             heatEnvParameter.setDefaultValue(parameter.getCurrentValue());
5328             heatEnvParameter.setCurrentValue(null);
5329             heatEnvParameters.add(heatEnvParameter);
5330         }
5331         artifactDefinition.setListHeatParameters(heatEnvParameters);
5332     }
5333
5334     private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map<String, Object> placeHolderData) {
5335         String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName());
5336         String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION);
5337         String name = heatArtifact.getArtifactName();
5338         String fileName;
5339         if (name == null) {
5340             name = heatArtifact.getArtifactLabel();
5341             fileName = name + "." + envExtension;
5342         }
5343         else {
5344             fileName = name.replaceAll("." + heatExtension, "." + envExtension);
5345         }
5346         heatEnvArtifact.setArtifactName(fileName);
5347     }
5348
5349     private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map<String, String> existingEnvVersions) {
5350         if (null != existingEnvVersions) {
5351             String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName());
5352             if (null != prevVersion) {
5353                 heatEnvArtifact.setArtifactVersion(prevVersion);
5354             }
5355         }
5356     }
5357
5358     /**
5359      * Handles Artifacts Request For Inner Component
5360      *
5361      * @param artifactsToHandle
5362      * @param component
5363      * @param user
5364      * @param vfcsNewCreatedArtifacts
5365      * @param operation
5366      * @param shouldLock
5367      * @param inTransaction
5368      * @return
5369      */
5370     public Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
5371                                                                                                        ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
5372
5373         Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsResult = null;
5374         ComponentTypeEnum componentType = component.getComponentType();
5375         List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>();
5376         Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5377         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult;
5378         String originData;
5379         String origMd5;
5380         try {
5381             for (ArtifactDefinition artifact : artifactsToHandle) {
5382                 originData = buildJsonStringForCsarVfcArtifact(artifact);
5383                 origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(originData);
5384                 actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact
5385                         .getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction);
5386                 if (actionResult.isRight()) {
5387                     log.debug("Failed to upload artifact to component with type {} and name {}. Status is {}. ", componentType, component
5388                             .getName(), actionResult.right().value());
5389                     errorWrapper.setInnerElement(actionResult.right().value());
5390                     if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
5391                         vfcsNewCreatedArtifacts.addAll(uploadedArtifacts);
5392                     }
5393                     break;
5394                 }
5395                 uploadedArtifacts.add(actionResult.left().value().left().value());
5396             }
5397             if (errorWrapper.isEmpty()) {
5398                 handleArtifactsResult = Either.left(uploadedArtifacts);
5399             }
5400             else {
5401                 handleArtifactsResult = Either.right(errorWrapper.getInnerElement());
5402             }
5403         }
5404         catch (Exception e) {
5405             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5406             handleArtifactsResult = Either.right(responseFormat);
5407             log.debug("Exception occured when handleArtifactsRequestForInnerVfcComponent, error is:{}", e.getMessage(), e);
5408         }
5409         return handleArtifactsResult;
5410     }
5411
5412     private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5413         ComponentInstance componentInstance = null;
5414         String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
5415         Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
5416         if (errorWrapper.isEmpty()) {
5417             componentInstance = component.getComponentInstances()
5418                                          .stream()
5419                                          .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName())
5420                                                                       .equals(normalizedName))
5421                                          .findFirst()
5422                                          .orElse(null);
5423             if (componentInstance == null) {
5424                 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, RESOURCE_INSTANCE, component
5425                         .getComponentType()
5426                         .getValue(), component.getName()));
5427                 log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
5428             }
5429         }
5430         return componentInstance;
5431     }
5432
5433     private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5434
5435         ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
5436         String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
5437         ComponentInstance componentInstance = component.getComponentInstances()
5438                                                        .stream()
5439                                                        .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName())
5440                                                                                     .equals(normalizedName))
5441                                                        .findFirst()
5442                                                        .orElse(null);
5443         if (componentInstance == null) {
5444             errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, RESOURCE_INSTANCE, component
5445                     .getComponentType()
5446                     .getValue(), component.getName()));
5447             log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
5448         }
5449         else {
5450             relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
5451         }
5452         return relatedComponentComponentInstancePair;
5453     }
5454
5455     private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5456         ComponentInstance componentInstance;
5457         ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
5458         Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
5459         if (errorWrapper.isEmpty()) {
5460             componentInstance = component.getComponentInstances()
5461                                          .stream()
5462                                          .filter(ci -> ci.getNormalizedName().equals(resourceInstanceName))
5463                                          .findFirst()
5464                                          .orElse(null);
5465             if (componentInstance == null) {
5466                 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, RESOURCE_INSTANCE, component
5467                         .getComponentType()
5468                         .getValue(), component.getName()));
5469                 log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
5470             }
5471             else {
5472                 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
5473             }
5474         }
5475         return relatedComponentComponentInstancePair;
5476     }
5477
5478     private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String componentName) {
5479
5480         byte[] downloadedArtifact = null;
5481         Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = null;
5482         List<ArtifactDefinition> artifactsList = null;
5483         ArtifactDefinition deploymentArtifact = null;
5484         if (artifacts != null && !artifacts.isEmpty()) {
5485             artifactsList = artifacts.values()
5486                                      .stream()
5487                                      .filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID()
5488                                                                                         .equals(artifactUUID))
5489                                      .collect(Collectors.toList());
5490         }
5491         if (artifactsList == null || artifactsList.isEmpty()) {
5492             log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName);
5493             errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
5494         }
5495         if (errorWrapper.isEmpty()) {
5496             deploymentArtifact = artifactsList.get(0);
5497             downloadArtifactEither = downloadArtifact(deploymentArtifact);
5498             if (downloadArtifactEither.isRight()) {
5499                 log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName());
5500                 errorWrapper.setInnerElement(downloadArtifactEither.right().value());
5501             }
5502         }
5503         if (errorWrapper.isEmpty()) {
5504             log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId());
5505             downloadedArtifact = downloadArtifactEither.left().value().getRight();
5506         }
5507         return downloadedArtifact;
5508     }
5509
5510     private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
5511         Component component = null;
5512         Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid);
5513         if (getComponentRes.isRight()) {
5514             StorageOperationStatus status = getComponentRes.right().value();
5515             log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5516             errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5517         }
5518         else {
5519             component = getComponentRes.left().value();
5520         }
5521         return component;
5522     }
5523
5524     private Component getComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
5525         Component component = null;
5526         Either<List<Component>, StorageOperationStatus> getComponentRes = toscaOperationFacade.getComponentListByUuid(componentUuid, null);
5527         if (getComponentRes.isRight()) {
5528             StorageOperationStatus status = getComponentRes.right().value();
5529             log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5530             errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5531         }
5532         else {
5533             List<Component> value = getComponentRes.left().value();
5534             if (value.isEmpty()) {
5535                 log.debug("Could not fetch component with type {} and uuid {}.", componentType, componentUuid);
5536                 ActionStatus status = componentType == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND;
5537                 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(status));
5538             }
5539             else {
5540                 component = value.get(0);
5541             }
5542         }
5543         return component;
5544     }
5545
5546     private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String parentId, ComponentTypeEnum componentType) {
5547         String artifactId = null;
5548         ActionStatus actionStatus = ActionStatus.ARTIFACT_NOT_FOUND;
5549         StorageOperationStatus storageStatus;
5550         ArtifactDefinition latestArtifact = null;
5551         List<ArtifactDefinition> artifacts = null;
5552         Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId);
5553         if (getArtifactsRes.isRight()) {
5554             storageStatus = getArtifactsRes.right().value();
5555             log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType, parentId, storageStatus);
5556             if (!storageStatus.equals(StorageOperationStatus.NOT_FOUND)) {
5557                 actionStatus = componentsUtils.convertFromStorageResponse(storageStatus);
5558             }
5559             errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5560         }
5561         if (errorWrapper.isEmpty()) {
5562             artifacts = getArtifactsRes.left()
5563                                        .value()
5564                                        .values()
5565                                        .stream()
5566                                        .filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID()
5567                                                                                     .equals(artifactUUID))
5568                                        .collect(Collectors.toList());
5569             if (artifacts == null || artifacts.isEmpty()) {
5570                 log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus);
5571                 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5572             }
5573         }
5574         if (errorWrapper.isEmpty()) {
5575             latestArtifact = artifacts.stream().max((a1, a2) -> {
5576                 int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion()));
5577                 if (compareRes == 0) {
5578                     compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2
5579                             .getLastUpdateDate());
5580                 }
5581                 return compareRes;
5582             }).get();
5583             if (latestArtifact == null) {
5584                 log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus);
5585                 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5586             }
5587         }
5588         if (errorWrapper.isEmpty()) {
5589             artifactId = latestArtifact.getUniqueId();
5590         }
5591         return artifactId;
5592     }
5593
5594     private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId, Wrapper<ResponseFormat> errorWrapper) {
5595
5596         Component component = null;
5597         Either<User, ActionStatus> getUserRes = userBusinessLogic.getUser(userId, false);
5598         if (getUserRes.isRight()) {
5599             log.debug("Could not fetch User of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, getUserRes
5600                     .right()
5601                     .value());
5602             errorWrapper.setInnerElement(componentsUtils.getResponseFormat(getUserRes.right().value()));
5603         }
5604         if (errorWrapper.isEmpty()) {
5605             User modifier = getUserRes.left().value();
5606             LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API);
5607             Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true);
5608             if (checkoutRes.isRight()) {
5609                 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType
5610                         .getNodeType(), parentId, checkoutRes.right().value().getStatus());
5611                 errorWrapper.setInnerElement(checkoutRes.right().value());
5612             }
5613             else {
5614                 component = checkoutRes.left().value();
5615             }
5616         }
5617         return component;
5618     }
5619
5620     private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) {
5621         Map<String, Object> json = new HashMap<>();
5622         String artifactName = artifact.getArtifactName();
5623         json.put(Constants.ARTIFACT_NAME, artifactName);
5624         json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel());
5625         json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType());
5626         json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
5627         json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription());
5628         json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData());
5629         json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName());
5630         return gson.toJson(json);
5631     }
5632
5633     @VisibleForTesting
5634     void setNodeTemplateOperation(NodeTemplateOperation nodeTemplateOperation) {
5635         this.nodeTemplateOperation = nodeTemplateOperation;
5636     }
5637 }