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