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