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