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