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