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