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