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