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