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