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