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