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