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