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