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