[sdc] update code of sdc
[sdc.git] / catalog-model / src / main / java / org / openecomp / sdc / be / model / jsontitan / operations / ArtifactsOperations.java
1 package org.openecomp.sdc.be.model.jsontitan.operations;
2
3 import java.util.ArrayList;
4 import java.util.HashMap;
5 import java.util.List;
6 import java.util.Map;
7 import java.util.Optional;
8 import java.util.UUID;
9 import java.util.stream.Collectors;
10
11 import org.apache.commons.collections.MapUtils;
12 import org.apache.commons.lang3.tuple.ImmutableTriple;
13 import org.apache.commons.lang3.tuple.Triple;
14 import org.apache.tinkerpop.gremlin.structure.Direction;
15 import org.openecomp.sdc.be.config.BeEcompErrorManager;
16 import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
17 import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
18 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
19 import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
20 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
21 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
22 import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition;
23 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
24 import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
25 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
26 import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
27 import org.openecomp.sdc.be.model.ArtifactDefinition;
28 import org.openecomp.sdc.be.model.HeatParameterDefinition;
29 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
30 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
31 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
32 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
33 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
34 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
35 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38 import org.slf4j.MDC;
39
40 import fj.data.Either;
41
42 @org.springframework.stereotype.Component("artifacts-operations")
43
44 public class ArtifactsOperations extends BaseOperation {
45         private static Logger log = LoggerFactory.getLogger(ArtifactsOperations.class.getName());
46
47         public Either<ArtifactDefinition, StorageOperationStatus> addArifactToComponent(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type, boolean failIfExist, String instanceId) {
48
49                 Either<ArtifactDataDefinition, StorageOperationStatus> status = updateArtifactOnGraph(parentId, artifactInfo, type, artifactInfo.getUniqueId(), instanceId, false);
50                 if (status.isRight()) {
51
52                         log.debug("Failed to update artifact {} of {} {}. status is {}", artifactInfo.getArtifactName(), type.getName(), parentId, status.right().value());
53                         BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("Update Artifact", artifactInfo.getArtifactName(), String.valueOf(status.right().value()));
54                         return Either.right(status.right().value());
55                 } else {
56
57                         ArtifactDataDefinition artifactData = status.left().value();
58
59                         ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactInfo, artifactData);
60                         log.debug("The returned ArtifactDefintion is {}", artifactDefResult);
61                         return Either.left(artifactDefResult);
62                 }
63
64         }
65
66         public Either<ArtifactDefinition, StorageOperationStatus> updateArifactOnResource(ArtifactDefinition artifactInfo, String id, String artifactId, NodeTypeEnum type, String instanceId) {
67
68                 Either<ArtifactDataDefinition, StorageOperationStatus> status = updateArtifactOnGraph(id, artifactInfo, type, artifactId, instanceId, true);
69                 if (status.isRight()) {
70
71                         log.debug("Failed to update artifact {} of {} {}. status is {}", artifactInfo.getArtifactName(), type.getName(), id, status.right().value());
72                         BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("Update Artifact", artifactInfo.getArtifactName(), String.valueOf(status.right().value()));
73                         return Either.right(status.right().value());
74                 } else {
75
76                         ArtifactDataDefinition artifactData = status.left().value();
77
78                         ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactInfo, artifactData);
79                         log.debug("The returned ArtifactDefintion is {}", artifactDefResult);
80                         return Either.left(artifactDefResult);
81                 }
82         }
83
84         public Either<Boolean, StorageOperationStatus> isCloneNeeded(String parentId, ArtifactDefinition artifactInfo, NodeTypeEnum type) {
85                 ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType();
86
87                 Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> triple = getEdgeLabelEnumFromArtifactGroupType(groupType, type);
88                 EdgeLabelEnum edgeLabelEnum = triple.getLeft();
89                 return super.isCloneNeeded(parentId, edgeLabelEnum);
90         }
91
92         public Either<ArtifactDefinition, StorageOperationStatus> getArtifactById(String parentId, String id) {
93                 return getArtifactById(parentId, id, null, null);
94         }
95
96         public Either<ArtifactDefinition, StorageOperationStatus> getArtifactById(String parentId, String id, ComponentTypeEnum componentType, String containerId) {
97                 Either<ArtifactDefinition, StorageOperationStatus> result = null;
98                 ArtifactDataDefinition foundArtifact = null;
99                 if (componentType != null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
100                         foundArtifact = getInstanceArtifactByLabelAndId(parentId, id, containerId, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
101                         if ( foundArtifact == null ){
102                                 foundArtifact = getInstanceArtifactByLabelAndId(parentId, id, containerId, EdgeLabelEnum.INSTANCE_ARTIFACTS);
103                         }
104                 }
105                 if (foundArtifact == null) {
106                         foundArtifact = getArtifactByLabelAndId(parentId, id, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS);
107                 }
108                 if (foundArtifact == null) {
109                         foundArtifact = getArtifactByLabelAndId(parentId, id, EdgeLabelEnum.TOSCA_ARTIFACTS);
110                 }
111
112                 if (foundArtifact == null) {
113                         foundArtifact = getArtifactByLabelAndId(parentId, id, EdgeLabelEnum.ARTIFACTS);
114                 }
115
116                 if (foundArtifact == null) {
117                         foundArtifact = getArtifactByLabelAndId(parentId, id, EdgeLabelEnum.SERVICE_API_ARTIFACTS);
118                 }
119
120                 if (foundArtifact == null) {
121                         result = Either.right(StorageOperationStatus.NOT_FOUND);
122                         return result;
123                 }
124
125                 ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(null, foundArtifact);
126                 return Either.left(artifactDefResult);
127
128         }
129
130         public Either<ArtifactDefinition, StorageOperationStatus> removeArifactFromResource(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact) {
131                 Either<ArtifactDefinition, StorageOperationStatus> status = removeArtifactOnGraph(id, artifactId, type, deleteMandatoryArtifact);
132
133                 if (status.isRight()) {
134
135                         log.debug("Failed to delete artifact {} of resource {}", artifactId, id);
136
137                         BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError("Delete Artifact", artifactId, String.valueOf(status.right().value()));
138                         return Either.right(status.right().value());
139                 } else {
140
141                         return Either.left(status.left().value());
142                 }
143         }
144
145         public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, ArtifactGroupTypeEnum groupType, String instanceId) {
146
147                 Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> triple = getEdgeLabelEnumFromArtifactGroupType(groupType, parentType);
148                 EdgeLabelEnum edgeLabelEnum = triple.getLeft();
149
150                 Either<Map<String, ArtifactDefinition>, TitanOperationStatus> foundArtifact = null;
151                 Map<String, ArtifactDefinition> resMap = new HashMap<>();
152                 foundArtifact = getArtifactByLabel(parentId, instanceId, edgeLabelEnum);
153                 if (foundArtifact.isRight()) {
154                         log.debug("Failed to find artifact in component {} with label {} ", parentId, edgeLabelEnum);
155                         return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(foundArtifact.right().value()));
156                 }
157
158                 resMap.putAll(foundArtifact.left().value());
159
160                 return Either.left(resMap);
161         }
162
163         public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId) {
164
165                 Either<Map<String, ArtifactDefinition>, TitanOperationStatus> foundArtifact = null;
166                 Map<String, ArtifactDefinition> resMap = new HashMap<>();
167                 foundArtifact = getArtifactByLabel(parentId, null, EdgeLabelEnum.ARTIFACTS);
168                 if (foundArtifact.isLeft()) {
169                         resMap.putAll(foundArtifact.left().value());
170
171                 }
172                 foundArtifact = getArtifactByLabel(parentId, null, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS);
173                 if (foundArtifact.isLeft()) {
174                         resMap.putAll(foundArtifact.left().value());
175
176                 }
177                 foundArtifact = getArtifactByLabel(parentId, null, EdgeLabelEnum.TOSCA_ARTIFACTS);
178                 if (foundArtifact.isLeft()) {
179                         resMap.putAll(foundArtifact.left().value());
180
181                 }
182
183                 return Either.left(resMap);
184
185         }
186
187         public Either<ArtifactDefinition, StorageOperationStatus> removeArtifactOnGraph(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact) {
188
189                 Either<ArtifactDefinition, StorageOperationStatus> artifactData = this.getArtifactById(id, artifactId);
190                 if (artifactData.isRight()) {
191                         log.debug("Failed to find artifact in component {} with id {} ", id, artifactId);
192                         return Either.right(artifactData.right().value());
193                 }
194                 ArtifactDataDefinition artifactDefinition = artifactData.left().value();
195                 boolean isMandatory = false;
196                 if ((artifactDefinition.getMandatory() || artifactDefinition.getServiceApi()) && !deleteMandatoryArtifact) {
197                         // return Either.left(artifactData.left().value());
198                         isMandatory = true;
199                 }
200
201                 Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> triple = getEdgeLabelEnumFromArtifactGroupType(artifactDefinition.getArtifactGroupType(), type);
202                 EdgeLabelEnum edgeLabelEnum = triple.getLeft();
203                 VertexTypeEnum vertexTypeEnum = triple.getRight();
204
205                 if (!isMandatory) {
206                         StorageOperationStatus status = deleteToscaDataElement(id, edgeLabelEnum, vertexTypeEnum, artifactDefinition.getArtifactLabel(), JsonPresentationFields.ARTIFACT_LABEL);
207                         if (status != StorageOperationStatus.OK)
208                                 return Either.right(status);
209                 }
210
211                 return Either.left(artifactData.left().value());
212
213         }
214
215         public void updateUUID(ArtifactDataDefinition artifactData, String oldChecksum, String oldVesrion, boolean isUpdate, EdgeLabelEnum edgeLabel) {
216                 if (oldVesrion == null || oldVesrion.isEmpty())
217                         oldVesrion = "0";
218
219                 String currentChecksum = artifactData.getArtifactChecksum();
220                 
221                 if ( isUpdate ){
222                         ArtifactTypeEnum type = ArtifactTypeEnum.findType(artifactData.getArtifactType());
223                         switch ( type ){
224                         case HEAT_ENV: 
225                                 if ( edgeLabel == EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS ){
226                                         generateUUID(artifactData, oldVesrion);
227                                 }else{
228                                         updateVersionAndDate(artifactData, oldVesrion);
229                                 }
230                                 break;
231                         case HEAT:
232                         case HEAT_NET:
233                         case HEAT_VOL:
234                                 generateUUID(artifactData, oldVesrion);
235                                 break;
236                         default:
237                                 if (oldChecksum == null || oldChecksum.isEmpty()) {
238                                         if (currentChecksum != null) {
239                                                 generateUUID(artifactData, oldVesrion);
240                                         }
241                                 } else if ((currentChecksum != null && !currentChecksum.isEmpty()) && !oldChecksum.equals(currentChecksum)) {
242                                         generateUUID(artifactData, oldVesrion);
243                                 }
244                                 break;
245                         }
246                 }else{
247                         if (oldChecksum == null || oldChecksum.isEmpty()) {
248                                 if (currentChecksum != null) {
249                                         generateUUID(artifactData, oldVesrion);
250                                 }
251                         } else if ((currentChecksum != null && !currentChecksum.isEmpty()) && !oldChecksum.equals(currentChecksum)) {
252                                 generateUUID(artifactData, oldVesrion);
253                         }
254                 }
255         }
256
257         // @TODO add implementation
258
259         public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType) {
260                 return null;
261         }
262
263         public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifactHeat, String componentId, NodeTypeEnum parentType, boolean failIfExist, String instanceId) {
264                 artifactHeatEnv.setGeneratedFromId(artifactHeat.getUniqueId());
265                 return addArifactToComponent(artifactHeatEnv, componentId, parentType, failIfExist, instanceId);
266         }
267
268         public Either<ArtifactDefinition, StorageOperationStatus> getHeatArtifactByHeatEnvId(String parentId, ArtifactDefinition heatEnv, NodeTypeEnum parentType, String containerId, ComponentTypeEnum componentType) {
269                 String id = heatEnv.getGeneratedFromId();
270                 ComponentTypeEnum compType;
271                 switch (parentType) {
272                 case ResourceInstance:
273                         compType = ComponentTypeEnum.RESOURCE_INSTANCE;
274                         break;
275                 default:
276                         compType = componentType;
277                 }
278                 return getArtifactById(parentId, id, compType, containerId);
279         }
280
281         public Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact(String id, ArtifactDefinition artifactEnvInfo, String artifactId, String newArtifactId, NodeTypeEnum type, String instanceId) {
282
283                 Either<Map<String, ArtifactDefinition>, TitanOperationStatus> artifactsEither = getArtifactByLabel(id, instanceId, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS);
284                 if (artifactsEither.isRight()) {
285                         log.debug("Failed to find artifacts in component {} with id {} ", id, artifactsEither.right().value());
286                         return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(artifactsEither.right().value()));
287                 }
288
289                 Map<String, ArtifactDefinition> artifacts = artifactsEither.left().value();
290                 List<ArtifactDefinition> envList = artifacts.values().stream().filter(a -> a.getGeneratedFromId()!= null && a.getGeneratedFromId().equals(artifactId)).collect(Collectors.toList());
291                 if (envList != null && !envList.isEmpty()) {
292                         envList.forEach(a -> {
293                                 a.setGeneratedFromId(newArtifactId);
294                                 updateArifactOnResource(a, id, a.getUniqueId(), type, instanceId);
295
296                         });
297
298                 }
299                 return Either.left(artifactEnvInfo);
300         }
301
302         public Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvPlaceholder(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type) {
303                 return updateArifactOnResource(artifactInfo, parentId, artifactInfo.getUniqueId(), type, null);
304         }
305
306         // public Either<List<HeatParameterDefinition>, StorageOperationStatus> getHeatParamsForEnv(ArtifactDefinition heatEnvArtifact, String parentId) {
307         // return null;
308         // }
309
310         ///////////////////////////////////////////// private methods ////////////////////////////////////////////////////
311
312         protected ArtifactDefinition convertArtifactDataToArtifactDefinition(ArtifactDefinition artifactInfo, ArtifactDataDefinition artifactDefResult) {
313                 log.debug("The object returned after create property is {}", artifactDefResult);
314
315                 ArtifactDefinition propertyDefResult = new ArtifactDefinition(artifactDefResult);
316                 if (artifactInfo != null)
317                         propertyDefResult.setPayload(artifactInfo.getPayloadData());
318
319                 List<HeatParameterDefinition> parameters = new ArrayList<HeatParameterDefinition>();
320                 /*
321                  * StorageOperationStatus heatParametersOfNode = heatParametersOperation.getHeatParametersOfNode(NodeTypeEnum.ArtifactRef, artifactDefResult.getUniqueId().toString(), parameters); if ((heatParametersOfNode.equals(StorageOperationStatus.OK))
322                  * && !parameters.isEmpty()) { propertyDefResult.setHeatParameters(parameters); }
323                  */
324                 return propertyDefResult;
325         }
326
327         private ArtifactDataDefinition getInstanceArtifactByLabelAndId(String parentId, String id, String containerId, EdgeLabelEnum edgeLabelEnum) {
328                 ArtifactDataDefinition foundArtifact = null;
329                 Either<Map<String, MapArtifactDataDefinition>, TitanOperationStatus> artifactsEither = getDataFromGraph(containerId, edgeLabelEnum);
330                 if (artifactsEither.isRight()) {
331                         log.debug("failed to fetch {} for tosca element with id {}, error {}", edgeLabelEnum, containerId, artifactsEither.right().value());
332                         return null;
333                 }
334
335                 Map<String, MapArtifactDataDefinition> artifacts = artifactsEither.left().value();
336
337                 MapArtifactDataDefinition artifactsPerInstance = artifacts.get(parentId);
338                 if (artifactsPerInstance == null) {
339                         log.debug("failed to fetch artifacts for instance {} in tosca element with id {}, error {}", parentId, containerId, artifactsEither.right().value());
340                         return null;
341                 }
342                 Optional<ArtifactDataDefinition> op = artifactsPerInstance.getMapToscaDataDefinition().values().stream().filter(p -> p.getUniqueId().equals(id)).findAny();
343                 if (op.isPresent()) {
344                         foundArtifact = op.get();
345                 }
346                 return foundArtifact;
347         }
348
349         private ArtifactDataDefinition getArtifactByLabelAndId(String parentId, String id, EdgeLabelEnum edgeLabelEnum) {
350                 ArtifactDataDefinition foundArtifact = null;
351                 Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> artifactsEither = getDataFromGraph(parentId, edgeLabelEnum);
352                 if (artifactsEither.isRight()) {
353                         log.debug("failed to fetch {} for tosca element with id {}, error {}", edgeLabelEnum, parentId, artifactsEither.right().value());
354                         return null;
355                 }
356
357                 Map<String, ArtifactDataDefinition> artifacts = artifactsEither.left().value();
358                 Optional<ArtifactDataDefinition> op = artifacts.values().stream().filter(p -> p.getUniqueId().equals(id)).findAny();
359                 if (op.isPresent()) {
360                         foundArtifact = op.get();
361                 }
362                 return foundArtifact;
363         }
364
365         private Either<Map<String, ArtifactDefinition>, TitanOperationStatus> getArtifactByLabel(String parentId, String instanceId, EdgeLabelEnum edgeLabelEnum) {
366
367                 Map<String, ArtifactDefinition> artMap = null;
368                 Map<String, ArtifactDataDefinition> artifactDataMap = null;
369                 
370                 if (edgeLabelEnum != EdgeLabelEnum.INSTANCE_ARTIFACTS) {
371                         Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> resultEither = getDataFromGraph(parentId, edgeLabelEnum);
372                         if (resultEither.isRight()) {
373                                 log.debug("failed to fetch {} for tosca element with id {}, error {}", edgeLabelEnum, parentId, resultEither.right().value());
374                                 return Either.right(resultEither.right().value());
375                         }
376                         artifactDataMap = resultEither.left().value();
377                 }else{
378                         Either<Map<String, MapArtifactDataDefinition>, TitanOperationStatus> resultEither = getDataFromGraph(parentId, edgeLabelEnum);
379                         if (resultEither.isRight()) {
380                                 log.debug("failed to fetch {} for tosca element with id {}, error {}", edgeLabelEnum, parentId, resultEither.right().value());
381                                 return Either.right(resultEither.right().value());
382                         }
383                         Map<String, MapArtifactDataDefinition> mapArtifacts = resultEither.left().value();
384                         MapArtifactDataDefinition artifactPerInstance = mapArtifacts.get(instanceId);
385                         if ( artifactPerInstance != null ){
386                                 artifactDataMap = artifactPerInstance.getMapToscaDataDefinition();
387                         }
388                 }
389                 if (artifactDataMap != null && !artifactDataMap.isEmpty()) {
390                         artMap = artifactDataMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> convertArtifactDataToArtifactDefinition(null, e.getValue())));
391                 }else{
392                         artMap = new HashMap<>();
393                 }
394                 return Either.left(artMap);
395
396         }
397
398         private Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> getEdgeLabelEnumFromArtifactGroupType(ArtifactGroupTypeEnum groupType, NodeTypeEnum nodeType) {
399                 EdgeLabelEnum edgeLabelEnum;
400                 VertexTypeEnum vertexTypeEnum;
401                 Boolean isDeepElement = false;
402                 /*
403                  * if (nodeType == NodeTypeEnum.ResourceInstance) { edgeLabelEnum = EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS; vertexTypeEnum = VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS; isDeepElement = true; } else {
404                  */
405                 switch (groupType) {
406                 case TOSCA:
407                         edgeLabelEnum = EdgeLabelEnum.TOSCA_ARTIFACTS;
408                         vertexTypeEnum = VertexTypeEnum.TOSCA_ARTIFACTS;
409                         break;
410                 case DEPLOYMENT:
411                         if (nodeType == NodeTypeEnum.ResourceInstance) {
412                                 edgeLabelEnum = EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS;
413                                 vertexTypeEnum = VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS;
414                                 isDeepElement = true;
415                         } else {
416                                 edgeLabelEnum = EdgeLabelEnum.DEPLOYMENT_ARTIFACTS;
417                                 vertexTypeEnum = VertexTypeEnum.DEPLOYMENT_ARTIFACTS;
418                         }
419                         break;
420                 case SERVICE_API:
421                         edgeLabelEnum = EdgeLabelEnum.SERVICE_API_ARTIFACTS;
422                         vertexTypeEnum = VertexTypeEnum.SERVICE_API_ARTIFACTS;
423                         break;
424                 default:
425                         if (nodeType == NodeTypeEnum.ResourceInstance) {
426                                 edgeLabelEnum = EdgeLabelEnum.INSTANCE_ARTIFACTS;
427                                 vertexTypeEnum = VertexTypeEnum.INSTANCE_ARTIFACTS;
428                                 isDeepElement = true;
429                         } else {
430                                 edgeLabelEnum = EdgeLabelEnum.ARTIFACTS;
431                                 vertexTypeEnum = VertexTypeEnum.ARTIFACTS;
432                         }
433                         break;
434                 }
435                 // }
436                 return new ImmutableTriple<EdgeLabelEnum, Boolean, VertexTypeEnum>(edgeLabelEnum, isDeepElement, vertexTypeEnum);
437
438         }
439
440         public Either<ArtifactDataDefinition, StorageOperationStatus> updateArtifactOnGraph(String componentId, ArtifactDefinition artifactInfo, NodeTypeEnum type, String artifactId, String instanceId, boolean isUpdate) {
441                 Either<ArtifactDataDefinition, StorageOperationStatus> res = null;
442                 ArtifactDataDefinition artifactToUpdate = new ArtifactDataDefinition(artifactInfo);
443                 ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType();
444
445                 Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> triple = getEdgeLabelEnumFromArtifactGroupType(groupType, type);
446                 EdgeLabelEnum edgeLabelEnum = triple.getLeft();
447                 VertexTypeEnum vertexTypeEnum = triple.getRight();
448
449                 Either<Boolean, StorageOperationStatus> isNeedToCloneEither = isCloneNeeded(componentId, edgeLabelEnum);
450                 if (isNeedToCloneEither.isRight()) {
451                         log.debug("Failed check is clone needed {}", componentId);
452                         return Either.right(isNeedToCloneEither.right().value());
453
454                 }
455                 boolean isNeedToClone = isNeedToCloneEither.left().value();
456
457                 if (artifactId == null || isNeedToClone) {
458                         String uniqueId;
459                         if (edgeLabelEnum != EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS && edgeLabelEnum != EdgeLabelEnum.INSTANCE_ARTIFACTS) {
460                                 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(componentId, artifactToUpdate.getArtifactLabel());
461                         } else {
462                                 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(instanceId, artifactToUpdate.getArtifactLabel());
463                         }
464                         artifactToUpdate.setUniqueId(uniqueId);
465
466                 } else
467                         artifactToUpdate.setUniqueId(artifactId);
468
469                 Map<String, ArtifactDataDefinition> artifacts = null;
470                 if (edgeLabelEnum != EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS && edgeLabelEnum != EdgeLabelEnum.INSTANCE_ARTIFACTS) {
471
472                         Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> artifactsEither = this.getDataFromGraph(componentId, edgeLabelEnum);
473
474                         if (artifactsEither.isLeft() && artifactsEither.left().value() != null && !artifactsEither.left().value().isEmpty()) {
475                                 artifacts = artifactsEither.left().value();
476                                 if (isNeedToClone) {
477                                         artifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE));
478                                 }
479                         }
480                 } else {
481                         Either<Map<String, MapArtifactDataDefinition>, TitanOperationStatus> artifactsEither = this.getDataFromGraph(componentId, edgeLabelEnum);
482                         if (artifactsEither.isLeft()) {
483                                 Map<String, MapArtifactDataDefinition> artifactInst = artifactsEither.left().value();
484                                 if (isNeedToClone) {
485                                         artifactInst.values().forEach(ma -> ma.getMapToscaDataDefinition().values().forEach(a -> a.setDuplicated(Boolean.TRUE)));
486                                 }
487                                 MapArtifactDataDefinition artifatcsOnInstance = artifactInst.get(instanceId);
488                                 if (artifatcsOnInstance != null) {
489                                         artifacts = artifatcsOnInstance.getMapToscaDataDefinition();
490                                 }
491                         }
492                 }
493                 String oldChecksum = null;
494                 String oldVersion = null;
495                 if (artifacts != null && artifacts.containsKey(artifactInfo.getArtifactLabel())) {
496                         ArtifactDataDefinition oldArtifactData = artifacts.get(artifactInfo.getArtifactLabel());
497                         oldChecksum = oldArtifactData.getArtifactChecksum();
498                         oldVersion = oldArtifactData.getArtifactVersion();
499                         if (isNeedToClone)
500                                 artifactToUpdate.setDuplicated(Boolean.FALSE);
501                         else {
502                                 if (artifactToUpdate.getDuplicated()) {
503                                         String id = type != NodeTypeEnum.ResourceInstance ? componentId : instanceId;
504                                         String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(id, artifactToUpdate.getArtifactLabel());
505                                         artifactToUpdate.setUniqueId(uniqueId);
506                                         artifactToUpdate.setDuplicated(Boolean.TRUE);
507                                 }
508                         }
509                 }
510                 updateUUID(artifactToUpdate, oldChecksum, oldVersion, isUpdate, edgeLabelEnum );
511
512                 if (artifactInfo.getPayloadData() == null) {
513                         if (!artifactToUpdate.getMandatory() || artifactToUpdate.getEsId() != null) {
514                                 artifactToUpdate.setEsId(artifactToUpdate.getUniqueId());
515                         }
516                 } else {
517                         if (artifactToUpdate.getEsId() == null) {
518                                 artifactToUpdate.setEsId(artifactToUpdate.getUniqueId());
519
520                         }
521                 }
522
523                 StorageOperationStatus status;
524                 if (edgeLabelEnum != EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS && edgeLabelEnum != EdgeLabelEnum.INSTANCE_ARTIFACTS) {
525                         status = updateToscaDataOfToscaElement(componentId, edgeLabelEnum, vertexTypeEnum, artifactToUpdate, JsonPresentationFields.ARTIFACT_LABEL);
526                 } else {
527                         List<String> pathKeys = new ArrayList<>();
528                         pathKeys.add(instanceId);
529                         List<ArtifactDataDefinition> toscaDataList = new ArrayList<>();
530                         toscaDataList.add(artifactToUpdate);
531                         status = updateToscaDataDeepElementsOfToscaElement(componentId, edgeLabelEnum, vertexTypeEnum, toscaDataList, pathKeys, JsonPresentationFields.ARTIFACT_LABEL);
532                 }
533                 if (status == StorageOperationStatus.OK)
534                         res = Either.left(artifactToUpdate);
535                 else
536                         res = Either.right(status);
537                 return res;
538         }
539
540         public void generateUUID(ArtifactDataDefinition artifactData, String oldVesrion) {
541
542                 UUID uuid = UUID.randomUUID();
543                 artifactData.setArtifactUUID(uuid.toString());
544                 MDC.put("serviceInstanceID", uuid.toString());
545                 updateVersionAndDate(artifactData, oldVesrion);
546         }
547
548         private void updateVersionAndDate(ArtifactDataDefinition artifactData, String oldVesrion) {
549                 if (artifactData.getArtifactChecksum() != null) {
550                         long time = System.currentTimeMillis();
551                         artifactData.setPayloadUpdateDate(time);
552                 }
553                 int newVersion = new Integer(oldVesrion).intValue();
554                 newVersion++;
555                 artifactData.setArtifactVersion(String.valueOf(newVersion));
556         }
557
558         private boolean validateParentType(NodeTypeEnum type) {
559                 boolean isValid = false;
560                 switch (type) {
561                 case Resource:
562                 case InterfaceOperation:
563                 case Service:
564                 case ResourceInstance:
565                         isValid = true;
566                         break;
567                 default:
568                         log.debug("Not supported node type for artifact relation : {} ", type);
569                 }
570                 return isValid;
571         }
572
573         public Either<ArtifactDataDefinition, StorageOperationStatus> removeArtifactOnGraph(ArtifactDefinition artifactFromGraph, String componentId, String instanceId, NodeTypeEnum type, boolean deleteMandatoryArtifact) {
574
575                 Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> triple = getEdgeLabelEnumFromArtifactGroupType(artifactFromGraph.getArtifactGroupType(), type);
576                 EdgeLabelEnum edgeLabelEnum = triple.getLeft();
577                 VertexTypeEnum vertexTypeEnum = triple.getRight();
578
579                 if (deleteMandatoryArtifact || !(artifactFromGraph.getMandatory() || artifactFromGraph.getServiceApi())) {
580                         StorageOperationStatus status;
581                         if (triple.getMiddle()) {
582                                 List<String> pathKeys = new ArrayList<>();
583                                 pathKeys.add(instanceId);
584                                 status = deleteToscaDataDeepElement(componentId, edgeLabelEnum, vertexTypeEnum, artifactFromGraph.getArtifactLabel(), pathKeys, JsonPresentationFields.ARTIFACT_LABEL);
585                         } else {
586                                 status = deleteToscaDataElement(componentId, edgeLabelEnum, vertexTypeEnum, artifactFromGraph.getArtifactLabel(), JsonPresentationFields.ARTIFACT_LABEL);
587                         }
588                         if (status != StorageOperationStatus.OK)
589                                 return Either.right(status);
590                 }
591                 return Either.left(artifactFromGraph);
592
593         }
594
595         public Either<ArtifactDataDefinition, StorageOperationStatus> deleteArtifactWithClonnigOnGraph(String componentId, ArtifactDefinition artifactToDelete, NodeTypeEnum type, String instanceId, boolean deleteMandatoryArtifact) {
596
597                 Either<ArtifactDataDefinition, StorageOperationStatus> result = null;
598                 Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> triple = getEdgeLabelEnumFromArtifactGroupType(artifactToDelete.getArtifactGroupType(), type);
599                 EdgeLabelEnum edgeLabel = triple.getLeft();
600                 VertexTypeEnum vertexLabel = triple.getRight();
601
602                 Boolean deleteElement = deleteMandatoryArtifact || !(artifactToDelete.getMandatory() || artifactToDelete.getServiceApi());
603                 Map<String, ToscaDataDefinition> artifacts = null;
604                 GraphVertex parentVertex = null;
605                 Either<Map<String, ToscaDataDefinition>, TitanOperationStatus> getArtifactsRes = null;
606
607                 Either<GraphVertex, TitanOperationStatus> getToscaElementRes = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
608                 if (getToscaElementRes.isRight()) {
609                         CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon getting tosca data from graph. Status is {}. ", componentId, getToscaElementRes.right().value());
610                         result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getToscaElementRes.right().value()));
611                 }
612                 if (result == null) {
613                         parentVertex = getToscaElementRes.left().value();
614                         getArtifactsRes = this.getDataFromGraph(parentVertex, edgeLabel);
615                         if (getArtifactsRes.isRight()) {
616                                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getArtifactsRes.right().value()));
617                         }
618                 }
619                 if (result == null) {
620                         artifacts = getArtifactsRes.left().value();
621                         if (triple.getMiddle()) {
622                                 artifacts.values().forEach(ma -> ((MapArtifactDataDefinition) ma).getMapToscaDataDefinition().values().forEach(a -> a.setDuplicated(Boolean.TRUE)));
623                                 MapArtifactDataDefinition artifatcsOnInstance = (MapArtifactDataDefinition) artifacts.get(instanceId);
624                                 if (artifatcsOnInstance != null && deleteElement) {
625                                         artifatcsOnInstance.getMapToscaDataDefinition().remove(artifactToDelete.getArtifactLabel());
626                                 }
627                         } else {
628                                 if (deleteElement) {
629                                         artifacts.remove(artifactToDelete.getArtifactLabel());
630                                 }
631                                 artifacts.values().stream().forEach(a -> ((ArtifactDataDefinition) a).setDuplicated(Boolean.TRUE));
632                         }
633                         artifactToDelete.setDuplicated(Boolean.TRUE);
634                 }
635                 if (artifacts != null) {
636                         TitanOperationStatus status = titanDao.deleteEdgeByDirection(parentVertex, Direction.OUT, edgeLabel);
637                         if (status != TitanOperationStatus.OK) {
638                                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
639                         } else if (MapUtils.isNotEmpty(artifacts)) {
640                                 Either<GraphVertex, StorageOperationStatus> assosiateRes = assosiateElementToData(parentVertex, vertexLabel, edgeLabel, artifacts);
641                                 if (assosiateRes.isRight()) {
642                                         result = Either.right(result.right().value());
643                                 }
644                         }
645                 }
646                 if (result == null) {
647                         result = Either.left(artifactToDelete);
648                 }
649                 return result;
650         }
651 }