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