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