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