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