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